summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/core
diff options
context:
space:
mode:
authorAllan Sandfeld Jensen <allan.jensen@qt.io>2019-08-30 10:22:43 +0200
committerAllan Sandfeld Jensen <allan.jensen@qt.io>2019-08-30 12:36:28 +0000
commit271a6c3487a14599023a9106329505597638d793 (patch)
treee040d58ffc86c1480b79ca8528020ca9ec919bf8 /chromium/third_party/blink/renderer/core
parent7b2ffa587235a47d4094787d72f38102089f402a (diff)
downloadqtwebengine-chromium-271a6c3487a14599023a9106329505597638d793.tar.gz
BASELINE: Update Chromium to 77.0.3865.59
Change-Id: I1e89a5f3b009a9519a6705102ad65c92fe736f21 Reviewed-by: Michael Brüning <michael.bruning@qt.io>
Diffstat (limited to 'chromium/third_party/blink/renderer/core')
-rw-r--r--chromium/third_party/blink/renderer/core/BUILD.gn678
-rw-r--r--chromium/third_party/blink/renderer/core/DEPS9
-rw-r--r--chromium/third_party/blink/renderer/core/accessibility/apply_dark_mode.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/accessibility/apply_dark_mode_test.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/animation/BUILD.gn10
-rw-r--r--chromium/third_party/blink/renderer/core/animation/animatable.cc (renamed from chromium/third_party/blink/renderer/core/animation/element_animation.cc)40
-rw-r--r--chromium/third_party/blink/renderer/core/animation/animatable.h (renamed from chromium/third_party/blink/renderer/core/animation/element_animation.h)35
-rw-r--r--chromium/third_party/blink/renderer/core/animation/animatable.idl (renamed from chromium/third_party/blink/renderer/core/animation/element_animation.idl)18
-rw-r--r--chromium/third_party/blink/renderer/core/animation/animation.cc188
-rw-r--r--chromium/third_party/blink/renderer/core/animation/animation.h29
-rw-r--r--chromium/third_party/blink/renderer/core/animation/animation.idl8
-rw-r--r--chromium/third_party/blink/renderer/core/animation/animation_clock.cc45
-rw-r--r--chromium/third_party/blink/renderer/core/animation/animation_clock.h31
-rw-r--r--chromium/third_party/blink/renderer/core/animation/animation_clock_test.cc139
-rw-r--r--chromium/third_party/blink/renderer/core/animation/animation_effect.cc100
-rw-r--r--chromium/third_party/blink/renderer/core/animation/animation_effect.h43
-rw-r--r--chromium/third_party/blink/renderer/core/animation/animation_effect_test.cc64
-rw-r--r--chromium/third_party/blink/renderer/core/animation/animation_input_helpers.cc2
-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.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/animation/animation_test.cc265
-rw-r--r--chromium/third_party/blink/renderer/core/animation/animation_test_helper.cc54
-rw-r--r--chromium/third_party/blink/renderer/core/animation/animation_time_delta.h4
-rw-r--r--chromium/third_party/blink/renderer/core/animation/animation_timeline.h19
-rw-r--r--chromium/third_party/blink/renderer/core/animation/animation_timeline.idl3
-rw-r--r--chromium/third_party/blink/renderer/core/animation/color_property_functions.cc50
-rw-r--r--chromium/third_party/blink/renderer/core/animation/compositor_animations.cc107
-rw-r--r--chromium/third_party/blink/renderer/core/animation/compositor_animations.h5
-rw-r--r--chromium/third_party/blink/renderer/core/animation/compositor_animations_test.cc197
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css/compositor_keyframe_color.h36
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css/compositor_keyframe_value.h4
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css/compositor_keyframe_value_factory.cc19
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css/compositor_keyframe_value_factory.h2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css/css_animation_update.h4
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css/css_animations.cc72
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css/css_animations.h10
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css/css_animations_test.cc30
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css/css_timing_data.h2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_angle_interpolation_type.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_custom_length_interpolation_type.cc51
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_custom_length_interpolation_type.h59
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_default_interpolation_type.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_image_interpolation_type.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_interpolation_environment.h32
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_interpolation_type.cc106
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_interpolation_type.h4
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_interpolation_types_map.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_length_interpolation_type.cc1
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_number_interpolation_type.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_paint_interpolation_type.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_percentage_interpolation_type.cc37
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_percentage_interpolation_type.h59
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_resolution_interpolation_type.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_scale_interpolation_type.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_time_interpolation_type.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_transform_origin_interpolation_type.h3
-rw-r--r--chromium/third_party/blink/renderer/core/animation/css_var_cycle_interpolation_type.cc28
-rw-r--r--chromium/third_party/blink/renderer/core/animation/document_animation.h2
-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.cc66
-rw-r--r--chromium/third_party/blink/renderer/core/animation/document_timeline.h23
-rw-r--r--chromium/third_party/blink/renderer/core/animation/document_timeline.idl3
-rw-r--r--chromium/third_party/blink/renderer/core/animation/document_timeline_test.cc65
-rw-r--r--chromium/third_party/blink/renderer/core/animation/effect_input.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/animation/effect_input.h2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/effect_stack_test.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/animation/element_animations.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/animation/element_animations.h2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/filter_interpolation_functions.cc43
-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.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/interpolation_effect.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/animation/interpolation_effect.h1
-rw-r--r--chromium/third_party/blink/renderer/core/animation/interpolation_effect_test.cc50
-rw-r--r--chromium/third_party/blink/renderer/core/animation/interpolation_environment.h2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/interpolation_type.h2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/invalidatable_interpolation.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/animation/keyframe.h2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/keyframe_effect.cc91
-rw-r--r--chromium/third_party/blink/renderer/core/animation/keyframe_effect.h4
-rw-r--r--chromium/third_party/blink/renderer/core/animation/keyframe_effect_model.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/animation/keyframe_effect_model.h7
-rw-r--r--chromium/third_party/blink/renderer/core/animation/keyframe_effect_model_test.cc202
-rw-r--r--chromium/third_party/blink/renderer/core/animation/keyframe_effect_test.cc71
-rw-r--r--chromium/third_party/blink/renderer/core/animation/length_interpolation_functions.cc32
-rw-r--r--chromium/third_party/blink/renderer/core/animation/length_interpolation_functions.h1
-rw-r--r--chromium/third_party/blink/renderer/core/animation/length_property_functions.h2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/list_interpolation_functions.h2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/list_interpolation_functions_test.cc5
-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.h2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/pending_animations.cc29
-rw-r--r--chromium/third_party/blink/renderer/core/animation/property_handle.h2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/sampled_effect.h2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/scroll_timeline.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/animation/scroll_timeline.h9
-rw-r--r--chromium/third_party/blink/renderer/core/animation/scroll_timeline.idl3
-rw-r--r--chromium/third_party/blink/renderer/core/animation/scroll_timeline_test.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/animation/scroll_timeline_util_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/string_keyframe.cc127
-rw-r--r--chromium/third_party/blink/renderer/core/animation/string_keyframe.h23
-rw-r--r--chromium/third_party/blink/renderer/core/animation/timing.cc76
-rw-r--r--chromium/third_party/blink/renderer/core/animation/timing.h49
-rw-r--r--chromium/third_party/blink/renderer/core/animation/timing_calculations.h192
-rw-r--r--chromium/third_party/blink/renderer/core/animation/timing_calculations_test.cc175
-rw-r--r--chromium/third_party/blink/renderer/core/animation/timing_input.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/animation/timing_input.h2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/typed_interpolation_value.h2
-rw-r--r--chromium/third_party/blink/renderer/core/animation/underlying_value_owner.h2
-rw-r--r--chromium/third_party/blink/renderer/core/clipboard/clipboard_utilities.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/clipboard/clipboard_utilities_test.cc46
-rw-r--r--chromium/third_party/blink/renderer/core/clipboard/data_object_item.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/clipboard/data_transfer.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/clipboard/data_transfer.idl3
-rw-r--r--chromium/third_party/blink/renderer/core/clipboard/data_transfer_item.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/clipboard/data_transfer_item.h7
-rw-r--r--chromium/third_party/blink/renderer/core/clipboard/data_transfer_item.idl4
-rw-r--r--chromium/third_party/blink/renderer/core/clipboard/data_transfer_item_list.idl4
-rw-r--r--chromium/third_party/blink/renderer/core/clipboard/system_clipboard.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/clipboard/system_clipboard.h2
-rw-r--r--chromium/third_party/blink/renderer/core/content_capture/BUILD.gn2
-rw-r--r--chromium/third_party/blink/renderer/core/content_capture/DEPS3
-rw-r--r--chromium/third_party/blink/renderer/core/content_capture/README.md19
-rw-r--r--chromium/third_party/blink/renderer/core/content_capture/content_capture_manager.cc32
-rw-r--r--chromium/third_party/blink/renderer/core/content_capture/content_capture_manager.h15
-rw-r--r--chromium/third_party/blink/renderer/core/content_capture/content_capture_task.cc35
-rw-r--r--chromium/third_party/blink/renderer/core/content_capture/content_capture_task.h10
-rw-r--r--chromium/third_party/blink/renderer/core/content_capture/content_capture_task_histogram_reporter.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/content_capture/content_capture_task_histogram_reporter.h16
-rw-r--r--chromium/third_party/blink/renderer/core/content_capture/content_capture_test.cc212
-rw-r--r--chromium/third_party/blink/renderer/core/content_capture/content_holder.cc37
-rw-r--r--chromium/third_party/blink/renderer/core/content_capture/content_holder.h47
-rw-r--r--chromium/third_party/blink/renderer/core/content_capture/task_session.cc152
-rw-r--r--chromium/third_party/blink/renderer/core/content_capture/task_session.h47
-rw-r--r--chromium/third_party/blink/renderer/core/core_idl_files.gni22
-rw-r--r--chromium/third_party/blink/renderer/core/core_initializer.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/BUILD.gn30
-rw-r--r--chromium/third_party/blink/renderer/core/css/abstract_property_set_css_style_declaration.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/css/abstract_property_set_css_style_declaration.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/basic_shape_functions.cc27
-rw-r--r--chromium/third_party/blink/renderer/core/css/css.dict1
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_axis_value.cc19
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_basic_shape_values.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_calculation_value.cc865
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_calculation_value.h162
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_computed_style_declaration.cc40
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_computed_style_declaration.h3
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_computed_style_declaration_test.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_condition_rule.idl4
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_default_style_sheets.cc27
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_default_style_sheets.h6
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_font_face.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_font_face_source.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_font_face_source_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_font_face_src_value.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_font_face_src_value.h28
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_font_feature_values_rule.idl2
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_font_selector.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_gradient_value.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_grouping_rule.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_image_generator_value.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_image_generator_value.h3
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_image_set_value.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_image_set_value.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_image_value.cc23
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_image_value.h36
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_keyframe_rule.idl4
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_keyframe_shorthand_value.cc32
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_keyframe_shorthand_value.h62
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_keyframes_rule.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_keyframes_rule.idl4
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_math_expression_node.cc860
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_math_expression_node.h242
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_math_expression_node_test.cc (renamed from chromium/third_party/blink/renderer/core/css/css_calculation_value_test.cc)70
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_math_function_value.cc127
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_math_function_value.h93
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_math_operator.cc45
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_math_operator.h21
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_numeric_literal_value.cc257
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_numeric_literal_value.h80
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_origin_clean.h11
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_paint_image_generator.h3
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_paint_value.cc96
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_paint_value.h13
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_paint_value_test.cc62
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_pending_interpolation_value.cc19
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_pending_interpolation_value.h61
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_pending_interpolation_value_test.cc55
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_primitive_value.cc429
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_primitive_value.h118
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_primitive_value_mappings.h1
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_primitive_value_test.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_properties.json5466
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_property_equality.cc40
-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_rule.cc49
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_property_rule.h48
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_property_rule.idl9
-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.cc19
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_property_value_set.h4
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_rule.h7
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_rule.idl4
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_selector.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_selector_list.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_selector_watch.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_style_declaration.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_supports_rule.idl4
-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.h6
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_syntax_descriptor.cc24
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_syntax_descriptor.h22
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_syntax_string_parser.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_test_helpers.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_test_helpers.h8
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_timing_function_value.cc25
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_to_length_conversion_data.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_unset_value.h8
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_value.cc52
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_value.h36
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_value_keywords.json517
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_value_pool.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_value_pool.h41
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_variable_reference_value.h3
-rw-r--r--chromium/third_party/blink/renderer/core/css/css_viewport_rule.idl3
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/computed_style_property_map.cc43
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/cross_thread_keyword_value.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/cross_thread_style_value_test.cc28
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/cross_thread_unsupported_value.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_math_invert.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_math_max.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_math_min.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_math_negate.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_math_product.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_math_product.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_math_sum.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_math_sum.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_math_value.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_matrix_component.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_numeric_value.cc83
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_numeric_value.h4
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_numeric_value_type.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_numeric_value_type.h4
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_perspective.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_style_value.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_style_value.h5
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_unit_value.cc36
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_unit_value.h12
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_url_image_value.cc23
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/css_url_image_value.h7
-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.h12
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/paint_worklet_input.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/paint_worklet_input.h19
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/paint_worklet_style_property_map.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/paint_worklet_style_property_map.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/paint_worklet_style_property_map_test.cc146
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/prepopulated_computed_style_property_map.cc2
-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/style_property_map.cc189
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/style_property_map_read_only_main_thread.cc47
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/style_property_map_read_only_main_thread.h3
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/style_value_factory.cc23
-rw-r--r--chromium/third_party/blink/renderer/core/css/cssom/style_value_factory.h5
-rw-r--r--chromium/third_party/blink/renderer/core/css/document_style_environment_variables.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/dom_window_css.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/element_rule_collector.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/css/font_face.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/font_face_cache_test.cc61
-rw-r--r--chromium/third_party/blink/renderer/core/css/font_face_set_document.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/css/font_face_set_document.h7
-rw-r--r--chromium/third_party/blink/renderer/core/css/font_face_set_worker.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/font_face_source.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/font_size_functions.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/hash_tools.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/inline_css_style_declaration.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/css/inline_css_style_declaration.h1
-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/invalidation_set.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/invalidation/style_invalidator.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/css/layout_tree_rebuild_root.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/local_font_face_source.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/css/local_font_face_source.h5
-rw-r--r--chromium/third_party/blink/renderer/core/css/media_feature_names.json51
-rw-r--r--chromium/third_party/blink/renderer/core/css/media_query.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/media_query.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/media_query_evaluator.cc21
-rw-r--r--chromium/third_party/blink/renderer/core/css/media_query_evaluator_test.cc33
-rw-r--r--chromium/third_party/blink/renderer/core/css/media_query_exp.cc140
-rw-r--r--chromium/third_party/blink/renderer/core/css/media_query_exp.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/media_query_set_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/media_values.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/css/media_values.h3
-rw-r--r--chromium/third_party/blink/renderer/core/css/media_values_cached.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/media_values_cached.h19
-rw-r--r--chromium/third_party/blink/renderer/core/css/media_values_dynamic.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/css/media_values_dynamic.h1
-rw-r--r--chromium/third_party/blink/renderer/core/css/offscreen_font_selector.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/at_rule_descriptor_parser.cc51
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/at_rule_descriptor_parser.h3
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/at_rule_names.json59
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_at_rule_id.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_at_rule_id.h1
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_lazy_parsing_state.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_parser.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_parser.h1
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_parser_context.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_parser_context.h8
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_parser_fast_paths.cc32
-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_impl.cc48
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_parser_impl.h5
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_parser_local_context.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_parser_mode.h4
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_parser_token.cc5
-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_parser_token_range.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_parser_token_stream.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_property_parser.cc32
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_property_parser.h4
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_property_parser_helpers.cc112
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_property_parser_test.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_proto_converter.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_proto_converter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_selector_parser.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_selector_parser_test.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_tokenizer.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/css_tokenizer_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/font_variant_numeric_parser.h68
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/media_condition_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/media_query_block_watcher.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/sizes_calc_parser.cc29
-rw-r--r--chromium/third_party/blink/renderer/core/css/parser/sizes_calc_parser.h11
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/computed_style_utils.cc233
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/computed_style_utils.h26
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/css_direction_aware_resolver.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/css_direction_aware_resolver.h5
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/css_exposure.h32
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/css_exposure_test.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/css_parsing_utils.cc59
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/css_parsing_utils.h8
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/css_parsing_utils_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/css_property.cc31
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/css_property.h45
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/css_property_methods.json52
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/css_property_test.cc90
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/css_unresolved_property.h5
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/custom_property.cc53
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/custom_property.h12
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/longhands_custom.cc1757
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/longhands/variable.h4
-rw-r--r--chromium/third_party/blink/renderer/core/css/properties/shorthands/shorthands_custom.cc405
-rw-r--r--chromium/third_party/blink/renderer/core/css/property_registration.cc90
-rw-r--r--chromium/third_party/blink/renderer/core/css/property_registration.h7
-rw-r--r--chromium/third_party/blink/renderer/core/css/property_registry.cc32
-rw-r--r--chromium/third_party/blink/renderer/core/css/property_registry.h9
-rw-r--r--chromium/third_party/blink/renderer/core/css/property_set_css_style_declaration.h3
-rw-r--r--chromium/third_party/blink/renderer/core/css/remote_font_face_source.cc40
-rw-r--r--chromium/third_party/blink/renderer/core/css/remote_font_face_source.h17
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/css_property_priority.h4
-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.cc85
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/css_variable_resolver.h22
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/css_variable_resolver_test.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/element_resolve_context.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/element_resolve_context.h5
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/element_style_resources.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/filter_operation_resolver.cc54
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/filter_operation_resolver.h3
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/match_result.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/match_result.h26
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/scoped_style_resolver.h3
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/style_adjuster.cc25
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/style_adjuster.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/style_animator.cc78
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/style_animator.h53
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/style_builder.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/style_builder_converter.cc80
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/style_builder_converter.h3
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/style_cascade.cc648
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/style_cascade.h508
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/style_cascade_test.cc1976
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/style_resolver.cc522
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/style_resolver.h35
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/style_resolver_state.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/style_resolver_state.h25
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/style_resolver_test.cc36
-rw-r--r--chromium/third_party/blink/renderer/core/css/resolver/transform_builder.cc21
-rw-r--r--chromium/third_party/blink/renderer/core/css/rule_feature_set_test.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/css/rule_set.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/css/rule_set.h5
-rw-r--r--chromium/third_party/blink/renderer/core/css/rule_set_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/selector_checker.cc25
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_attribute_mutation_scope.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_auto_color.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_color.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_engine.cc81
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_engine.h37
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_engine_context.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_engine_test.cc102
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_environment_variables_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_property_serializer.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_property_shorthand_custom.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_recalc_root.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_rule.cc34
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_rule.h35
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_rule_css_style_declaration.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_rule_css_style_declaration.h1
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_rule_import.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_rule_import.h8
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_sheet_collection.h2
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_sheet_contents.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/css/style_sheet_list.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/css/svg.css5
-rw-r--r--chromium/third_party/blink/renderer/core/css/threaded/css_to_length_conversion_data_threaded_test.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/css/threaded/multi_threaded_test_util.h30
-rw-r--r--chromium/third_party/blink/renderer/core/css/zoom_adjusted_pixel_value.h3
-rw-r--r--chromium/third_party/blink/renderer/core/display_lock/BUILD.gn13
-rw-r--r--chromium/third_party/blink/renderer/core/display_lock/DEPS3
-rw-r--r--chromium/third_party/blink/renderer/core/display_lock/display_lock.dict11
-rw-r--r--chromium/third_party/blink/renderer/core/display_lock/display_lock_budget.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/display_lock/display_lock_budget.h21
-rw-r--r--chromium/third_party/blink/renderer/core/display_lock/display_lock_budget_test.cc356
-rw-r--r--chromium/third_party/blink/renderer/core/display_lock/display_lock_context.cc321
-rw-r--r--chromium/third_party/blink/renderer/core/display_lock/display_lock_context.h53
-rw-r--r--chromium/third_party/blink/renderer/core/display_lock/display_lock_context_test.cc303
-rw-r--r--chromium/third_party/blink/renderer/core/display_lock/display_lock_fuzzer.cc50
-rw-r--r--chromium/third_party/blink/renderer/core/display_lock/display_lock_utilities.cc68
-rw-r--r--chromium/third_party/blink/renderer/core/display_lock/display_lock_utilities.h11
-rw-r--r--chromium/third_party/blink/renderer/core/display_lock/display_lock_utilities_test.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/display_lock/strict_yielding_display_lock_budget.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/display_lock/strict_yielding_display_lock_budget.h4
-rw-r--r--chromium/third_party/blink/renderer/core/display_lock/unyielding_display_lock_budget.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/display_lock/unyielding_display_lock_budget.h4
-rw-r--r--chromium/third_party/blink/renderer/core/display_lock/yielding_display_lock_budget.cc53
-rw-r--r--chromium/third_party/blink/renderer/core/display_lock/yielding_display_lock_budget.h11
-rw-r--r--chromium/third_party/blink/renderer/core/dom/BUILD.gn6
-rw-r--r--chromium/third_party/blink/renderer/core/dom/OWNERS2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/README.md2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/attr.idl5
-rw-r--r--chromium/third_party/blink/renderer/core/dom/attribute.h2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/attribute_collection.h2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/cdata_section.idl4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/character_data.idl5
-rw-r--r--chromium/third_party/blink/renderer/core/dom/child_node.h8
-rw-r--r--chromium/third_party/blink/renderer/core/dom/child_node.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/dom/comment.h2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/comment.idl3
-rw-r--r--chromium/third_party/blink/renderer/core/dom/container_node.cc109
-rw-r--r--chromium/third_party/blink/renderer/core/dom/container_node.h7
-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/create_element_flags.h2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/document.cc1372
-rw-r--r--chromium/third_party/blink/renderer/core/dom/document.h116
-rw-r--r--chromium/third_party/blink/renderer/core/dom/document.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/dom/document_and_element_event_handlers.h2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/document_encoding_data.h2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/document_fragment.idl3
-rw-r--r--chromium/third_party/blink/renderer/core/dom/document_init.cc44
-rw-r--r--chromium/third_party/blink/renderer/core/dom/document_init.h26
-rw-r--r--chromium/third_party/blink/renderer/core/dom/document_lifecycle.h2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/document_or_shadow_root.h4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/document_parser_timing.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/dom/document_parser_timing.h30
-rw-r--r--chromium/third_party/blink/renderer/core/dom/document_statistics_collector.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/dom/document_statistics_collector.h2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/document_test.cc94
-rw-r--r--chromium/third_party/blink/renderer/core/dom/document_timing.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/dom/document_timing.h24
-rw-r--r--chromium/third_party/blink/renderer/core/dom/document_type.h2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/document_type.idl4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/dom_exception.idl3
-rw-r--r--chromium/third_party/blink/renderer/core/dom/dom_high_res_time_stamp.h8
-rw-r--r--chromium/third_party/blink/renderer/core/dom/dom_implementation.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/dom/dom_implementation.idl4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/dom_node_ids.h2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/dom_string_list.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/dom_string_map.idl3
-rw-r--r--chromium/third_party/blink/renderer/core/dom/element.cc425
-rw-r--r--chromium/third_party/blink/renderer/core/dom/element.h80
-rw-r--r--chromium/third_party/blink/renderer/core/dom/element.idl9
-rw-r--r--chromium/third_party/blink/renderer/core/dom/element_traversal.h6
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/event.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/event.h19
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/event_dispatch_forbidden_scope.h2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/event_dispatcher.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/event_target.cc24
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/event_target.h4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/events/event_target_test.cc37
-rw-r--r--chromium/third_party/blink/renderer/core/dom/first_letter_pseudo_element.cc45
-rw-r--r--chromium/third_party/blink/renderer/core/dom/first_letter_pseudo_element.h2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/flat_tree_traversal.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/dom/flat_tree_traversal.h5
-rw-r--r--chromium/third_party/blink/renderer/core/dom/flat_tree_traversal_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/frame_request_callback_collection.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/global_event_handlers.h2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/icon_url.h2
-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.h4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/idle_deadline.idl4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/idle_deadline_test.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/dom/ignore_opens_during_unload_count_incrementer.h2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/increment_load_event_delay_count.h2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/layout_tree_builder.cc101
-rw-r--r--chromium/third_party/blink/renderer/core/dom/layout_tree_builder.h50
-rw-r--r--chromium/third_party/blink/renderer/core/dom/layout_tree_builder_traversal.cc38
-rw-r--r--chromium/third_party/blink/renderer/core/dom/layout_tree_builder_traversal.h5
-rw-r--r--chromium/third_party/blink/renderer/core/dom/live_node_list_registry.h2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/mutation_observer.cc134
-rw-r--r--chromium/third_party/blink/renderer/core/dom/mutation_observer.h16
-rw-r--r--chromium/third_party/blink/renderer/core/dom/mutation_observer_notifier.cc115
-rw-r--r--chromium/third_party/blink/renderer/core/dom/mutation_observer_notifier.h54
-rw-r--r--chromium/third_party/blink/renderer/core/dom/mutation_record.idl4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/named_node_map.idl3
-rw-r--r--chromium/third_party/blink/renderer/core/dom/names_map.h2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/node.cc383
-rw-r--r--chromium/third_party/blink/renderer/core/dom/node.h49
-rw-r--r--chromium/third_party/blink/renderer/core/dom/node.idl4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/node_computed_style.h8
-rw-r--r--chromium/third_party/blink/renderer/core/dom/node_filter.idl3
-rw-r--r--chromium/third_party/blink/renderer/core/dom/node_iterator.idl4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/node_iterator_base.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/node_list.idl4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/node_rare_data.h12
-rw-r--r--chromium/third_party/blink/renderer/core/dom/node_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/node_traversal.h2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/non_document_type_child_node.h2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/parent_node.h6
-rw-r--r--chromium/third_party/blink/renderer/core/dom/parent_node.idl4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/presentation_attribute_style.cc1
-rw-r--r--chromium/third_party/blink/renderer/core/dom/processing_instruction.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/processing_instruction.h2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/processing_instruction.idl4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/pseudo_element.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/dom/pseudo_element.h2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/qualified_name.h2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/range.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/dom/range.idl3
-rw-r--r--chromium/third_party/blink/renderer/core/dom/scriptable_document_parser.h4
-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.cc24
-rw-r--r--chromium/third_party/blink/renderer/core/dom/scripted_idle_task_controller.h14
-rw-r--r--chromium/third_party/blink/renderer/core/dom/scripted_idle_task_controller_test.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/dom/scripted_task_queue.cc113
-rw-r--r--chromium/third_party/blink/renderer/core/dom/scripted_task_queue.h57
-rw-r--r--chromium/third_party/blink/renderer/core/dom/scripted_task_queue.idl9
-rw-r--r--chromium/third_party/blink/renderer/core/dom/scripted_task_queue_controller.cc60
-rw-r--r--chromium/third_party/blink/renderer/core/dom/scripted_task_queue_controller.h47
-rw-r--r--chromium/third_party/blink/renderer/core/dom/scripted_task_queue_controller.idl9
-rw-r--r--chromium/third_party/blink/renderer/core/dom/shadow_root.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/shadow_root.h7
-rw-r--r--chromium/third_party/blink/renderer/core/dom/shadow_root.idl3
-rw-r--r--chromium/third_party/blink/renderer/core/dom/sink_document.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/slot_assignment.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/dom/slot_assignment_engine.cc3
-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_range.idl4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/task_type_traits.h2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/text.cc70
-rw-r--r--chromium/third_party/blink/renderer/core/dom/text.h5
-rw-r--r--chromium/third_party/blink/renderer/core/dom/text.idl3
-rw-r--r--chromium/third_party/blink/renderer/core/dom/text_link_colors.h2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/text_test.cc116
-rw-r--r--chromium/third_party/blink/renderer/core/dom/throw_on_dynamic_markup_insertion_count_incrementer.h2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/transform_source.h2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/tree_ordered_map.h2
-rw-r--r--chromium/third_party/blink/renderer/core/dom/tree_scope.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/dom/tree_scope_adopter.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/dom/tree_walker.idl4
-rw-r--r--chromium/third_party/blink/renderer/core/dom/user_action_element_set.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/dom/user_gesture_indicator.cc32
-rw-r--r--chromium/third_party/blink/renderer/core/dom/user_gesture_indicator.h8
-rw-r--r--chromium/third_party/blink/renderer/core/dom/user_gesture_indicator_test.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/dom/v0_insertion_point.cc28
-rw-r--r--chromium/third_party/blink/renderer/core/dom/v0_insertion_point.h6
-rw-r--r--chromium/third_party/blink/renderer/core/dom/visited_link_state.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/dom/weak_identifier_map.h2
-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.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/dom/xml_document.idl4
-rw-r--r--chromium/third_party/blink/renderer/core/editing/BUILD.gn1
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/apply_style_command.cc64
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/clipboard_commands.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/composite_edit_command.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/delete_selection_options.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/document_exec_command.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/editing_command_test.cc65
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/editing_commands_utilities.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/editing_state.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/editor_command.cc138
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/format_block_command.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/indent_outdent_command.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/insert_commands.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/insert_list_command.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/move_commands.cc201
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/move_commands.h27
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/move_commands_test.cc327
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/replace_selection_command.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/split_text_node_containing_element_command.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/style_commands.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/editing/commands/style_commands.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/compute_layer_selection_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/editing/dom_selection.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/editing_behavior.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/editing_strategy.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/editing_style.cc74
-rw-r--r--chromium/third_party/blink/renderer/core/editing/editing_style.h6
-rw-r--r--chromium/third_party/blink/renderer/core/editing/editing_style_utilities.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/editing/editing_style_utilities.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/editing_utilities.cc53
-rw-r--r--chromium/third_party/blink/renderer/core/editing/editing_utilities.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/editor.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/editing/element_inner_text.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/editing/ephemeral_range.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/editing/finder/find_buffer.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/editing/finder/find_task_controller.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/editing/finder/text_finder.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/editing/finder/text_finder_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/editing/frame_caret.cc27
-rw-r--r--chromium/third_party/blink/renderer/core/editing/frame_caret_test.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/editing/frame_selection.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/editing/frame_selection.h5
-rw-r--r--chromium/third_party/blink/renderer/core/editing/frame_selection_test.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/editing/granularity_strategy.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/granularity_strategy_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/ime/ime_text_span.h4
-rw-r--r--chromium/third_party/blink/renderer/core/editing/ime/input_method_controller.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/editing/ime/input_method_controller.h3
-rw-r--r--chromium/third_party/blink/renderer/core/editing/ime/input_method_controller_test.cc156
-rw-r--r--chromium/third_party/blink/renderer/core/editing/inline_box_position.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/inline_box_traversal.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/iterators/bit_stack.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/iterators/fully_clipped_state_stack.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/iterators/simplified_backwards_text_iterator_test.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/editing/iterators/text_iterator.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/editing/iterators/text_iterator_behavior.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/iterators/text_iterator_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/iterators/text_searcher_icu.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/editing/iterators/text_searcher_icu.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/keyboard_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/editing/layout_selection.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/editing/layout_selection_test.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/editing/link_selection_test.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/editing/markers/document_marker.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/markers/document_marker_controller.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/markers/document_marker_controller_test.cc36
-rw-r--r--chromium/third_party/blink/renderer/core/editing/markers/styleable_marker.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker_replacement_scope.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/markers/text_match_marker.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/editing/markers/text_match_marker.h10
-rw-r--r--chromium/third_party/blink/renderer/core/editing/markers/text_match_marker_list_impl.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/editing/plain_text_range.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/position.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/editing/selection.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/editing/selection_adjuster.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/selection_controller.cc59
-rw-r--r--chromium/third_party/blink/renderer/core/editing/selection_controller.h15
-rw-r--r--chromium/third_party/blink/renderer/core/editing/selection_controller_test.cc87
-rw-r--r--chromium/third_party/blink/renderer/core/editing/selection_editor.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/selection_modifier.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/selection_modifier_line.cc47
-rw-r--r--chromium/third_party/blink/renderer/core/editing/selection_template.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/editing/selection_template.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/serializers/markup_accumulator.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/editing/serializers/markup_accumulator.h5
-rw-r--r--chromium/third_party/blink/renderer/core/editing/serializers/markup_formatter.cc32
-rw-r--r--chromium/third_party/blink/renderer/core/editing/serializers/markup_formatter.h7
-rw-r--r--chromium/third_party/blink/renderer/core/editing/serializers/serialization.cc5
-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.cc48
-rw-r--r--chromium/third_party/blink/renderer/core/editing/serializers/styled_markup_serializer_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/editing/set_selection_options.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/spellcheck/cold_mode_spell_check_requester.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/editing/spellcheck/idle_spell_check_controller.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/editing/spellcheck/spell_check_requester.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/editing/spellcheck/spell_check_requester.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/spellcheck/text_checking.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/state_machines/backspace_state_machine.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/state_machines/backward_code_point_state_machine.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/state_machines/backward_grapheme_boundary_state_machine.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/state_machines/forward_code_point_state_machine.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/state_machines/forward_grapheme_boundary_state_machine.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/testing/selection_sample.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/editing/testing/selection_sample.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/text_offset_mapping.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/text_offset_mapping_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/editing/text_segments.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/visible_position.cc1
-rw-r--r--chromium/third_party/blink/renderer/core/editing/visible_selection.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/editing/visible_selection.h2
-rw-r--r--chromium/third_party/blink/renderer/core/editing/visible_units.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/editing/visible_units_line_test.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/events/animation_event.idl3
-rw-r--r--chromium/third_party/blink/renderer/core/events/animation_playback_event.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/events/animation_playback_event.idl3
-rw-r--r--chromium/third_party/blink/renderer/core/events/application_cache_error_event.h1
-rw-r--r--chromium/third_party/blink/renderer/core/events/composition_event.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/events/current_input_event.h2
-rw-r--r--chromium/third_party/blink/renderer/core/events/drag_event.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/events/drag_event.h6
-rw-r--r--chromium/third_party/blink/renderer/core/events/event_factory.h2
-rw-r--r--chromium/third_party/blink/renderer/core/events/event_type_names.json53
-rw-r--r--chromium/third_party/blink/renderer/core/events/focus_event.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/events/message_event.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/events/message_event.h15
-rw-r--r--chromium/third_party/blink/renderer/core/events/mouse_event.cc36
-rw-r--r--chromium/third_party/blink/renderer/core/events/mouse_event.h6
-rw-r--r--chromium/third_party/blink/renderer/core/events/navigator_events.h2
-rw-r--r--chromium/third_party/blink/renderer/core/events/pointer_event.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/events/pointer_event.h8
-rw-r--r--chromium/third_party/blink/renderer/core/events/pointer_event.idl5
-rw-r--r--chromium/third_party/blink/renderer/core/events/pointer_event_factory.cc74
-rw-r--r--chromium/third_party/blink/renderer/core/events/pointer_event_factory.h19
-rw-r--r--chromium/third_party/blink/renderer/core/events/pointer_event_factory_test.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/events/portal_activate_event.cc34
-rw-r--r--chromium/third_party/blink/renderer/core/events/portal_activate_event.h32
-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/text_event.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/events/touch_event.cc177
-rw-r--r--chromium/third_party/blink/renderer/core/events/touch_event.h4
-rw-r--r--chromium/third_party/blink/renderer/core/events/touch_event_test.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/events/transition_event.idl3
-rw-r--r--chromium/third_party/blink/renderer/core/events/ui_event.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/events/ui_event.h6
-rw-r--r--chromium/third_party/blink/renderer/core/events/ui_event_with_key_state.cc4
-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_scroll_event.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/events/web_input_event_conversion.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/events/web_input_event_conversion.h5
-rw-r--r--chromium/third_party/blink/renderer/core/events/web_input_event_conversion_test.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/events/wheel_event.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/execution_context/context_lifecycle_state_observer.cc2
-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.h38
-rw-r--r--chromium/third_party/blink/renderer/core/execution_context/remote_security_context.cc34
-rw-r--r--chromium/third_party/blink/renderer/core/execution_context/remote_security_context.h22
-rw-r--r--chromium/third_party/blink/renderer/core/execution_context/security_context.cc64
-rw-r--r--chromium/third_party/blink/renderer/core/execution_context/security_context.h45
-rw-r--r--chromium/third_party/blink/renderer/core/execution_context/window_agent.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/execution_context/window_agent.h13
-rw-r--r--chromium/third_party/blink/renderer/core/exported/BUILD.gn10
-rw-r--r--chromium/third_party/blink/renderer/core/exported/application_cache_host_for_shared_worker.cc54
-rw-r--r--chromium/third_party/blink/renderer/core/exported/application_cache_host_for_shared_worker.h46
-rw-r--r--chromium/third_party/blink/renderer/core/exported/local_frame_client_impl.cc59
-rw-r--r--chromium/third_party/blink/renderer/core/exported/local_frame_client_impl.h24
-rw-r--r--chromium/third_party/blink/renderer/core/exported/local_frame_client_impl_test.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/exported/renderer_webapplicationcachehost_impl.cc66
-rw-r--r--chromium/third_party/blink/renderer/core/exported/renderer_webapplicationcachehost_impl.h37
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_application_cache_host_impl.cc353
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_application_cache_host_impl.h84
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_content_holder.cc27
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_document_loader_impl.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_document_loader_impl.h2
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_document_subresource_filter_test.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_dom_message_event.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_element.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_element_test.cc10
-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.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_form_element_observer_impl.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_frame.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_frame_serializer.cc19
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_frame_serializer_import_test.cc68
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_frame_serializer_sanitization_test.cc175
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_frame_serializer_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_frame_serializer_test_helper.cc99
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_frame_serializer_test_helper.h32
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_frame_test.cc41
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_hit_test_result.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_input_method_controller_impl.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_input_method_controller_impl.h2
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_layer_test.cc191
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_memory_statistics.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_message_port_converter.cc24
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_node.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_page_importance_signals.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_page_popup_impl.cc45
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_plugin_container_impl.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_plugin_container_test.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_remote_frame_impl.cc68
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_remote_frame_impl.h12
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_scoped_page_pauser.cc38
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_searchable_form_data.cc35
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_settings_impl.cc20
-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.cc58
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_shared_worker_impl.h15
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_surrounding_text_test.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_user_gesture_indicator.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_user_gesture_token.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_user_gesture_token_test.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_view_impl.cc206
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_view_impl.h30
-rw-r--r--chromium/third_party/blink/renderer/core/exported/web_view_test.cc365
-rw-r--r--chromium/third_party/blink/renderer/core/exported/worker_shadow_page.cc24
-rw-r--r--chromium/third_party/blink/renderer/core/exported/worker_shadow_page.h19
-rw-r--r--chromium/third_party/blink/renderer/core/feature_policy/BUILD.gn1
-rw-r--r--chromium/third_party/blink/renderer/core/feature_policy/feature_policy_features.json55
-rw-r--r--chromium/third_party/blink/renderer/core/feature_policy/feature_policy_helper.h4
-rw-r--r--chromium/third_party/blink/renderer/core/feature_policy/feature_policy_parser.cc46
-rw-r--r--chromium/third_party/blink/renderer/core/feature_policy/feature_policy_parser.h12
-rw-r--r--chromium/third_party/blink/renderer/core/feature_policy/feature_policy_parser_delegate.h23
-rw-r--r--chromium/third_party/blink/renderer/core/feature_policy/feature_policy_value_fuzzer.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/feature_policy/layout_animations_policy.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/feature_policy/layout_animations_policy.h2
-rw-r--r--chromium/third_party/blink/renderer/core/feature_policy/policy_test.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/DEPS1
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/body_stream_buffer.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/body_stream_buffer_test.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/fetch_data_loader.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/fetch_header_list.h3
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/fetch_manager.cc79
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/fetch_request_data.cc55
-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.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/fetch_response_data.h8
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/form_data_bytes_consumer_test.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/global_fetch.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/multipart_parser.h2
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/readable_stream_bytes_consumer.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/readable_stream_bytes_consumer.h2
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/request.cc64
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/request.h4
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/request_test.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/response.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/testing/internals_fetch.h2
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/testing/worker_internals_fetch.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/fetch/testing/worker_internals_fetch.h2
-rw-r--r--chromium/third_party/blink/renderer/core/fileapi/blob.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/fileapi/file.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/fileapi/file_reader.cc25
-rw-r--r--chromium/third_party/blink/renderer/core/fileapi/file_reader.h6
-rw-r--r--chromium/third_party/blink/renderer/core/fileapi/file_reader_loader.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/fileapi/file_reader_loader.h2
-rw-r--r--chromium/third_party/blink/renderer/core/fileapi/file_reader_sync.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/fileapi/url_file_api.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/fileapi/url_file_api.h2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/BUILD.gn4
-rw-r--r--chromium/third_party/blink/renderer/core/frame/ad_tracker_test.cc34
-rw-r--r--chromium/third_party/blink/renderer/core/frame/bar_prop.idl4
-rw-r--r--chromium/third_party/blink/renderer/core/frame/browser_controls_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/csp/content_security_policy.cc35
-rw-r--r--chromium/third_party/blink/renderer/core/frame/csp/content_security_policy.h6
-rw-r--r--chromium/third_party/blink/renderer/core/frame/csp/content_security_policy_fuzzer.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/frame/csp/content_security_policy_test.cc36
-rw-r--r--chromium/third_party/blink/renderer/core/frame/csp/csp_directive_list.cc48
-rw-r--r--chromium/third_party/blink/renderer/core/frame/csp/csp_directive_list.h12
-rw-r--r--chromium/third_party/blink/renderer/core/frame/csp/csp_directive_list_test.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/frame/csp/csp_source.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/csp/csp_source.h2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/csp/execution_context_csp_delegate.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/frame/csp/media_list_directive_test.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/frame/csp/source_list_directive_test.cc28
-rw-r--r--chromium/third_party/blink/renderer/core/frame/dactyloscoper.h2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/deprecated_schedule_style_recalc_during_layout.h2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/deprecation.cc181
-rw-r--r--chromium/third_party/blink/renderer/core/frame/deprecation.h2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/dom_timer.cc40
-rw-r--r--chromium/third_party/blink/renderer/core/frame/dom_timer.h11
-rw-r--r--chromium/third_party/blink/renderer/core/frame/dom_timer_coordinator.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/dom_timer_coordinator.h2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/dom_timer_test.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/frame/dom_window.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/frame/embedded_content_view.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/frame/find_in_page.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/frame/find_in_page.h16
-rw-r--r--chromium/third_party/blink/renderer/core/frame/frame.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/frame/frame.h28
-rw-r--r--chromium/third_party/blink/renderer/core/frame/frame_console.h2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/frame_overlay_test.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/frame/frame_serializer.cc238
-rw-r--r--chromium/third_party/blink/renderer/core/frame/frame_serializer.h21
-rw-r--r--chromium/third_party/blink/renderer/core/frame/frame_serializer_test.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/frame/frame_test.cc38
-rw-r--r--chromium/third_party/blink/renderer/core/frame/frame_test_helpers.cc52
-rw-r--r--chromium/third_party/blink/renderer/core/frame/frame_test_helpers.h54
-rw-r--r--chromium/third_party/blink/renderer/core/frame/frame_view.cc42
-rw-r--r--chromium/third_party/blink/renderer/core/frame/frame_view.h7
-rw-r--r--chromium/third_party/blink/renderer/core/frame/frame_view_auto_size_info.h2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/fullscreen_controller.h2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/history.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/history.idl4
-rw-r--r--chromium/third_party/blink/renderer/core/frame/intervention.h2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/layout_subtree_root_list.h2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/local_dom_window.cc85
-rw-r--r--chromium/third_party/blink/renderer/core/frame/local_dom_window.h4
-rw-r--r--chromium/third_party/blink/renderer/core/frame/local_frame.cc213
-rw-r--r--chromium/third_party/blink/renderer/core/frame/local_frame.h31
-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.cc74
-rw-r--r--chromium/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator.cc19
-rw-r--r--chromium/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator.h29
-rw-r--r--chromium/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator_test.cc34
-rw-r--r--chromium/third_party/blink/renderer/core/frame/local_frame_view.cc324
-rw-r--r--chromium/third_party/blink/renderer/core/frame/local_frame_view.h66
-rw-r--r--chromium/third_party/blink/renderer/core/frame/local_frame_view_test.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/frame/location.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/frame/location.h2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/mhtml_archive_test.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/frame/mhtml_loading_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/frame/navigator.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/frame/navigator.idl4
-rw-r--r--chromium/third_party/blink/renderer/core/frame/navigator_device_memory.idl2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/opened_frame_tracker.h2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/page_scale_constraints.h2
-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.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/frame/performance_monitor.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/frame/performance_monitor.h4
-rw-r--r--chromium/third_party/blink/renderer/core/frame/picture_in_picture_controller.h1
-rw-r--r--chromium/third_party/blink/renderer/core/frame/remote_frame.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/frame/remote_frame.h9
-rw-r--r--chromium/third_party/blink/renderer/core/frame/reporting_context.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/frame/root_frame_viewport.cc70
-rw-r--r--chromium/third_party/blink/renderer/core/frame/root_frame_viewport.h16
-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/rotation_viewport_anchor.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/frame/rotation_viewport_anchor.h5
-rw-r--r--chromium/third_party/blink/renderer/core/frame/sandbox_flags.h2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/settings.h1
-rw-r--r--chromium/third_party/blink/renderer/core/frame/settings.json544
-rw-r--r--chromium/third_party/blink/renderer/core/frame/settings_delegate.h2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/smart_clip.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/frame/use_counter_helper.cc (renamed from chromium/third_party/blink/renderer/core/frame/use_counter.cc)40
-rw-r--r--chromium/third_party/blink/renderer/core/frame/use_counter_helper.h (renamed from chromium/third_party/blink/renderer/core/frame/use_counter.h)9
-rw-r--r--chromium/third_party/blink/renderer/core/frame/use_counter_helper_test.cc (renamed from chromium/third_party/blink/renderer/core/frame/use_counter_test.cc)44
-rw-r--r--chromium/third_party/blink/renderer/core/frame/user_activation.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/frame/visual_viewport.cc96
-rw-r--r--chromium/third_party/blink/renderer/core/frame/visual_viewport.h8
-rw-r--r--chromium/third_party/blink/renderer/core/frame/visual_viewport_test.cc75
-rw-r--r--chromium/third_party/blink/renderer/core/frame/web_frame_serializer_impl.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/frame/web_frame_widget_base.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/frame/web_frame_widget_base.h15
-rw-r--r--chromium/third_party/blink/renderer/core/frame/web_frame_widget_impl.cc80
-rw-r--r--chromium/third_party/blink/renderer/core/frame/web_frame_widget_impl.h7
-rw-r--r--chromium/third_party/blink/renderer/core/frame/web_local_frame_impl.cc172
-rw-r--r--chromium/third_party/blink/renderer/core/frame/web_local_frame_impl.h24
-rw-r--r--chromium/third_party/blink/renderer/core/frame/web_view_frame_widget.cc21
-rw-r--r--chromium/third_party/blink/renderer/core/frame/web_view_frame_widget.h5
-rw-r--r--chromium/third_party/blink/renderer/core/frame/window.idl2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/window_event_handlers.h2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/window_or_worker_global_scope.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/frame/window_or_worker_global_scope.h2
-rw-r--r--chromium/third_party/blink/renderer/core/frame/window_post_message_options.idl2
-rw-r--r--chromium/third_party/blink/renderer/core/fullscreen/document_fullscreen.h2
-rw-r--r--chromium/third_party/blink/renderer/core/fullscreen/element_fullscreen.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/fullscreen/element_fullscreen.h2
-rw-r--r--chromium/third_party/blink/renderer/core/fullscreen/fullscreen.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/fullscreen/scoped_allow_fullscreen.h2
-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.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/anchor_element_metrics_sender.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/html/anchor_element_metrics_sender.h4
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator.cc86
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator.h19
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/canvas_async_blob_creator_test.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/canvas_font_cache.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/canvas_font_cache.h5
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/canvas_rendering_context.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/canvas_rendering_context_factory.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/canvas_rendering_context_host.cc64
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/canvas_rendering_context_host.h11
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/html_canvas_element.cc109
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/html_canvas_element.h13
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/html_canvas_element.idl8
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/image_element_base.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/canvas/text_metrics.idl10
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/ce_reactions_scope.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/custom_element.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/custom_element_definition_builder.h2
-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_reaction_factory.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/custom_element_reaction_queue_test.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/custom_element_reaction_stack_test.cc35
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/custom_element_reaction_test_helpers.h5
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/custom_element_registry.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/custom_element_registry.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/custom_element_test_helpers.h3
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/custom_element_upgrade_sorter.cc9
-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.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_descriptor_hash.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_exception.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_microtask_import_step.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_registry.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/base_checkable_input_type.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/base_temporal_input_type.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/base_temporal_input_type.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/clear_button_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/clear_button_element.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/color_chooser_popup_ui_controller.cc63
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/color_chooser_popup_ui_controller.h3
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/color_input_type.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/date_input_type.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/date_time_chooser.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/date_time_chooser_impl.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/date_time_edit_element.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/date_time_edit_element.h4
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/date_time_field_elements.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/date_time_field_elements.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/date_time_fields_state.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/date_time_local_input_type.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/date_time_numeric_field_element.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/email_input_type.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/external_date_time_chooser.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/external_popup_menu.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/external_popup_menu_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/file_chooser.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/file_input_type.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/form_controller.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/form_controller.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/form_controller_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/form_data.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/form_data.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/hidden_input_type.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_button_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_data_list_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_data_list_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_field_set_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_field_set_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_form_control_element.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_form_control_element.h18
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_form_control_element_test.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_form_controls_collection.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_form_controls_collection.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_form_element.cc87
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_form_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_input_element.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_input_element.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_input_element.idl3
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_label_element.cc16
-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_label_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_legend_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_opt_group_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_option_element.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_option_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_options_collection.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_output_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_select_element.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_select_element.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_select_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_select_element_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_text_area_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/html_text_area_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/input_type.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/input_type_view.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/listed_element.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/month_input_type.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/multiple_fields_temporal_input_type_view.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/password_input_type_test.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/picker_indicator_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/picker_indicator_element.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/range_input_type.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/resources/calendarPicker.js15
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/resources/colorSuggestionPicker.css2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/resources/colorSuggestionPicker.js87
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/resources/color_picker.css99
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/resources/color_picker.js437
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/resources/color_picker_common.js73
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/resources/validation_bubble.css1
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/search_input_type.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/slider_thumb_element.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/slider_thumb_element.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/spin_button_element.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/spin_button_element.h13
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/step_range.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/submit_input_type.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/telephone_input_type.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/text_control_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/text_control_element.h3
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/text_control_inner_elements.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/time_input_type.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/type_ahead.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/type_ahead.h4
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/validity_state.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/html/forms/week_input_type.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_all_collection.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_anchor_element.cc80
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_anchor_element.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_anchor_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_area_element.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_area_element.h6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_area_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_base_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_body_element.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_body_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_br_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_content_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_content_element.h5
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_data_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_data_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_details_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_details_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_dialog_element.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_dialog_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_dimension.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_directory_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_div_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_dlist_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_document.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_document.idl2
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_element.cc21
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_embed_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_font_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_frame_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_frame_element_test.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_frame_owner_element.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_frame_set_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_frame_set_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_head_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_heading_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_hr_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_html_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_iframe_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_iframe_element.idl8
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_iframe_element_test.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_image_element.cc46
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_image_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_image_fallback_helper.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_li_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_link_element.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_link_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_map_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_map_element.h3
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_map_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_marquee_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_marquee_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_menu_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_meta_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_meta_element_test.cc37
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_meter_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_meter_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_mod_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_object_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_olist_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_olist_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_paragraph_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_param_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_picture_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_picture_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_plugin_element.cc133
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_plugin_element.h8
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_pre_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_progress_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_progress_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_quote_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_script_element.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_script_element.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_script_element.idl6
-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.cc88
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_slot_element.h15
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_slot_element_test.cc23
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_source_element.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_source_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_span_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_style_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_summary_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_table_caption_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_table_cell_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_table_cell_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_table_col_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_table_element.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_table_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_table_part_element.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_table_row_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_table_section_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_template_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_template_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_time_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_time_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_title_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_ulist_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_view_source_document.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/html/html_view_source_document.h3
-rw-r--r--chromium/third_party/blink/renderer/core/html/image_document.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/image_document_test.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/html/imports/html_import.h2
-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_state.h2
-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_imports_controller.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/imports/html_imports_controller.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/imports/link_import.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/html/imports/link_import.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/lazy_load_frame_observer.cc41
-rw-r--r--chromium/third_party/blink/renderer/core/html/lazy_load_frame_observer.h4
-rw-r--r--chromium/third_party/blink/renderer/core/html/lazy_load_frame_observer_test.cc152
-rw-r--r--chromium/third_party/blink/renderer/core/html/lazy_load_image_observer.cc68
-rw-r--r--chromium/third_party/blink/renderer/core/html/lazy_load_image_observer.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/lazy_load_image_observer_test.cc96
-rw-r--r--chromium/third_party/blink/renderer/core/html/link_manifest.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/link_rel_attribute.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/link_rel_attribute_test.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/html/link_style.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/autoplay_uma_helper.cc74
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/autoplay_uma_helper.h12
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/html_audio_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/html_media_element.cc96
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/html_media_element.h13
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/html_media_element.idl2
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/html_media_element_event_listeners_test.cc48
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/html_media_element_test.cc42
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/html_media_source.h11
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/html_video_element.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/html_video_element.h4
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/html_video_element.idl3
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/html_video_element_test.cc27
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/media_custom_controls_fullscreen_detector.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/media_document.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/media_error.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/media_fragment_uri_parser.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/media_fragment_uri_parser.h5
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/media_remoting_interstitial.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/picture_in_picture_interstitial.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/video_auto_fullscreen_test.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/html/media/video_wake_lock_test.cc38
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/atomic_html_token.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/atomic_html_token.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/background_html_input_stream.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/background_html_parser.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/background_html_parser.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/compact_html_token.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_construction_site.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_document_parser.cc65
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_document_parser.h9
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_element_stack.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_entity_parser.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_entity_search.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_entity_table.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_input_stream.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_parser_options.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_parser_scheduler.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_parser_scheduler.h7
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_preload_scanner.cc98
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_preload_scanner.h8
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_preload_scanner_fuzzer.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_preload_scanner_test.cc46
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_resource_preloader.cc66
-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_source_tracker.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_srcset_parser.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_srcset_parser.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_srcset_parser_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_stack_item.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/html_tree_builder.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/input_stream_preprocessor.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/preload_request.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/preload_request.h6
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/pump_session.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/text_resource_decoder_fuzzer.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/xss_auditor.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/xss_auditor.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/parser/xss_auditor_delegate.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/html/plugin_document.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/portal/html_portal_element.cc100
-rw-r--r--chromium/third_party/blink/renderer/core/html/portal/html_portal_element.h27
-rw-r--r--chromium/third_party/blink/renderer/core/html/portal/html_portal_element.idl2
-rw-r--r--chromium/third_party/blink/renderer/core/html/portal/portal_post_message_helper.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/resources/controls_refresh.css81
-rw-r--r--chromium/third_party/blink/renderer/core/html/resources/forced_colors.css145
-rw-r--r--chromium/third_party/blink/renderer/core/html/resources/html.css5
-rw-r--r--chromium/third_party/blink/renderer/core/html/shadow/progress_shadow_element_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/text_document.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/time_ranges.cc132
-rw-r--r--chromium/third_party/blink/renderer/core/html/time_ranges.h52
-rw-r--r--chromium/third_party/blink/renderer/core/html/time_ranges.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/automatic_track_selection.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/html_track_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/html_track_element.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/text_track.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/text_track_cue.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/text_track_cue_list.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/text_track_list.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/track_event.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/vtt/buffered_line_reader.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/vtt/buffered_line_reader_test.cc1
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/vtt/vtt_cue.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/vtt/vtt_cue.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/vtt/vtt_cue.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/vtt/vtt_parser.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/vtt/vtt_region.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/vtt/vtt_region.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/vtt/vtt_scanner.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/vtt/vtt_token.h2
-rw-r--r--chromium/third_party/blink/renderer/core/html/track/vtt/vtt_tokenizer.h2
-rw-r--r--chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap_factories.cc6
-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.cc1
-rw-r--r--chromium/third_party/blink/renderer/core/input/context_menu_allowed_scope.h2
-rw-r--r--chromium/third_party/blink/renderer/core/input/event_handler.cc305
-rw-r--r--chromium/third_party/blink/renderer/core/input/event_handler.h40
-rw-r--r--chromium/third_party/blink/renderer/core/input/event_handler_test.cc1067
-rw-r--r--chromium/third_party/blink/renderer/core/input/event_handling_util.cc36
-rw-r--r--chromium/third_party/blink/renderer/core/input/event_handling_util.h13
-rw-r--r--chromium/third_party/blink/renderer/core/input/fallback_cursor_event_manager.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/input/fallback_cursor_event_manager.h2
-rw-r--r--chromium/third_party/blink/renderer/core/input/fallback_cursor_event_manager_test.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/input/gesture_manager.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/input/ime_on_focus_test.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/input/keyboard_event_manager.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/input/keyboard_event_manager.h2
-rw-r--r--chromium/third_party/blink/renderer/core/input/mouse_event_manager.cc124
-rw-r--r--chromium/third_party/blink/renderer/core/input/mouse_event_manager.h6
-rw-r--r--chromium/third_party/blink/renderer/core/input/mouse_wheel_event_manager.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/input/overscroll_behavior_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/input/pointer_event_manager.cc121
-rw-r--r--chromium/third_party/blink/renderer/core/input/pointer_event_manager.h11
-rw-r--r--chromium/third_party/blink/renderer/core/input/pointer_event_manager_test.cc178
-rw-r--r--chromium/third_party/blink/renderer/core/input/scroll_manager.cc116
-rw-r--r--chromium/third_party/blink/renderer/core/input/scroll_manager.h16
-rw-r--r--chromium/third_party/blink/renderer/core/input/scroll_snap_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/input/touch_action_test.cc59
-rw-r--r--chromium/third_party/blink/renderer/core/input/touch_event_manager.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/input/touch_event_manager.h2
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/browser_protocol.pdl367
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/console_message.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/console_message.h2
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/dev_tools_emulator.cc76
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/dev_tools_emulator.h35
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/devtools_agent.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/devtools_agent.h3
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/devtools_session.cc81
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/devtools_session.h6
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/dom_patch_support.cc21
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/identifiers_factory.h2
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspect_tools.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspect_tools.h11
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_animation_agent.cc59
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_application_cache_agent.cc46
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_application_cache_agent.h9
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_css_agent.cc152
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_dom_agent.cc154
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_dom_debugger_agent.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_dom_snapshot_agent.cc348
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_dom_snapshot_agent.h2
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_emulation_agent.cc39
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_emulation_agent.h4
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_highlight.cc138
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_layer_tree_agent.cc90
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_log_agent.cc24
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_memory_agent.cc100
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_memory_agent.h4
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_network_agent.cc178
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_network_agent.h9
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_overlay_agent.cc82
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_overlay_agent.h9
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_page_agent.cc158
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_page_agent.h6
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_performance_agent.cc59
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_performance_agent.h26
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_protocol_config.json9
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_resource_content_loader.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_session_state.cc32
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_session_state.h25
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_session_state_test.cc4
-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_task_runner.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_task_runner.h2
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_trace_events.cc55
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/inspector_trace_events.h28
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/main_thread_debugger.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/protocol_parser_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/protocol_unittest.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/thread_debugger.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/thread_debugger.h10
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/v8_inspector_string.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/v8_inspector_string.h12
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/worker_inspector_controller.cc1
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/worker_inspector_controller.h2
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/worker_thread_debugger.cc1
-rw-r--r--chromium/third_party/blink/renderer/core/inspector/worker_thread_debugger.h1
-rw-r--r--chromium/third_party/blink/renderer/core/intersection_observer/intersection_geometry.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/intersection_observer/intersection_observer.idl5
-rw-r--r--chromium/third_party/blink/renderer/core/intersection_observer/intersection_observer_controller.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/intersection_observer/intersection_observer_controller.h4
-rw-r--r--chromium/third_party/blink/renderer/core/intersection_observer/intersection_observer_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/invisible_dom/invisible_dom.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/invisible_dom/invisible_dom.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/BUILD.gn14
-rw-r--r--chromium/third_party/blink/renderer/core/layout/README.md13
-rw-r--r--chromium/third_party/blink/renderer/core/layout/api/line_layout_api_shim.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/api/line_layout_block_flow.h5
-rw-r--r--chromium/third_party/blink/renderer/core/layout/api/line_layout_box.h11
-rw-r--r--chromium/third_party/blink/renderer/core/layout/api/line_layout_inline.h6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/api/line_layout_item.h12
-rw-r--r--chromium/third_party/blink/renderer/core/layout/collapsed_border_value.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/column_balancer.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/counter_node.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/custom/layout_worklet_global_scope.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/layout/custom/layout_worklet_global_scope_proxy.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/custom/layout_worklet_global_scope_proxy.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/depth_ordered_layout_object_list.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/flexible_box_algorithm.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/floating_objects.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/layout/floating_objects.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/fragmentainer_iterator.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/geometry/logical_offset.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/geometry/logical_rect.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/layout/geometry/physical_offset.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/geometry/physical_offset.h13
-rw-r--r--chromium/third_party/blink/renderer/core/layout/geometry/physical_rect.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/geometry/physical_rect.h8
-rw-r--r--chromium/third_party/blink/renderer/core/layout/geometry/physical_size.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/geometry/transform_state.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/grid.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/grid_baseline_alignment.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/grid_layout_utils.h2
-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.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/hit_test_location.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/layout/hit_test_location.h27
-rw-r--r--chromium/third_party/blink/renderer/core/layout/hit_test_request.h14
-rw-r--r--chromium/third_party/blink/renderer/core/layout/hit_test_result.cc65
-rw-r--r--chromium/third_party/blink/renderer/core/layout/hit_test_result.h26
-rw-r--r--chromium/third_party/blink/renderer/core/layout/hit_testing_transform_state.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/layout/hit_testing_transform_state.h6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/intrinsic_sizing_info.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/jank_tracker.h110
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_analyzer.cc1
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_analyzer.h3
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_block.cc154
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_block.h17
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_block_flow.cc127
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_block_flow.h15
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_block_flow_line.cc44
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_block_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_box.cc283
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_box.h51
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_box_model_object.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_box_model_object.h6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_box_model_object_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_box_test.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_br.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_br.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_button.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_counter.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_deprecated_flexible_box.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_details_marker.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_embedded_content.cc45
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_embedded_content.h10
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_embedded_object.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_file_upload_control.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_file_upload_control.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_flexible_box.cc63
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_flexible_box.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_flexible_box_test.cc50
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_flow_thread.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_flow_thread.h6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_frame_set.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_frame_set.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_geometry_map.cc2
-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_step.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_grid.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_image.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_image.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_image_resource.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_image_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_inline.cc65
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_inline.h14
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_inline_test.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_list_box.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_list_box.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_menu_list.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_multi_column_set.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_multi_column_set.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_multi_column_spanner_placeholder.cc8
-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.cc375
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_object.h201
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_object_child_list.cc19
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_object_factory.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_object_factory.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_object_inlines.h8
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_object_test.cc28
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_progress.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_progress.h6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_quote.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_replaced.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_replaced.h16
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_ruby.cc2
-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_scrollbar_theme.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_shift_region.cc (renamed from chromium/third_party/blink/renderer/core/layout/jank_region.cc)20
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_shift_region.h (renamed from chromium/third_party/blink/renderer/core/layout/jank_region.h)24
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_shift_region_test.cc (renamed from chromium/third_party/blink/renderer/core/layout/jank_region_test.cc)16
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_shift_tracker.cc (renamed from chromium/third_party/blink/renderer/core/layout/jank_tracker.cc)300
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_shift_tracker.h139
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_shift_tracker_test.cc (renamed from chromium/third_party/blink/renderer/core/layout/jank_tracker_test.cc)313
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_slider.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_state.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_table.cc33
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_table.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_table_cell.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_table_cell_test.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_table_row.cc31
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_table_row.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_table_section.cc128
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_table_section.h6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_table_section_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_table_test.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_text.cc94
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_text.h31
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_text_combine.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_text_control.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_text_control.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_text_control_multi_line.cc19
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_text_control_multi_line.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_text_control_single_line.cc32
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_text_control_single_line.h6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_text_control_single_line_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_text_fragment.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_text_fragment.h3
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_text_fragment_test.cc79
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_text_test.cc61
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_theme.cc40
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_theme.h13
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_theme_default.cc36
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_theme_default.h6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_theme_font_provider.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_theme_mac.h8
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_theme_mac.mm6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_theme_test.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_tree_as_text.cc126
-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_view.cc32
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_view.h11
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_view_test.cc361
-rw-r--r--chromium/third_party/blink/renderer/core/layout/layout_vtt_cue.cc27
-rw-r--r--chromium/third_party/blink/renderer/core/layout/line/breaking_context_inline_headers.h12
-rw-r--r--chromium/third_party/blink/renderer/core/layout/line/ellipsis_box.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/layout/line/ellipsis_box.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/line/glyph_overflow.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/line/inline_box.cc31
-rw-r--r--chromium/third_party/blink/renderer/core/layout/line/inline_box.h10
-rw-r--r--chromium/third_party/blink/renderer/core/layout/line/inline_flow_box.cc44
-rw-r--r--chromium/third_party/blink/renderer/core/layout/line/inline_flow_box.h10
-rw-r--r--chromium/third_party/blink/renderer/core/layout/line/inline_iterator.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/line/inline_text_box.cc19
-rw-r--r--chromium/third_party/blink/renderer/core/layout/line/inline_text_box.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/line/layout_text_info.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/line/line_box_list.cc31
-rw-r--r--chromium/third_party/blink/renderer/core/layout/line/line_box_list.h14
-rw-r--r--chromium/third_party/blink/renderer/core/layout/line/line_breaker.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/line/line_info.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/line/line_layout_state.h2
-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.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/layout/line/root_inline_box.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/line/trailing_objects.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/line/word_measurement.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/map_coordinates_test.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/layout/multi_column_fragmentainer_group.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/exclusions/ng_exclusion_space.cc46
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/exclusions/ng_exclusion_space.h28
-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/geometry/ng_static_position.cc75
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_static_position.h165
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_static_position_test.cc194
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/empty_offset_mapping_builder.h5
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/layout_ng_text.h9
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/layout_ng_text_fragment.h9
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_abstract_inline_text_box.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_baseline.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_bidi_paragraph.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_caret_position.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_box_state.cc19
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_box_state.h5
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_child_layout_context.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_fragment_traversal.cc101
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_fragment_traversal.h19
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_fragment_traversal_test.cc59
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_item.cc27
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_item.h24
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_item_result.h7
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_item_segment.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_items.h50
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_items_builder.cc86
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_items_builder.h12
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_items_builder_test.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm.cc89
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm_test.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.cc21
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node_data.h8
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node_test.cc91
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_box_fragment_builder.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_box_fragment_builder.h7
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_breaker.cc153
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_breaker.h5
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_breaker_test.cc27
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_truncator.cc178
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_truncator.h25
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping.h29
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping_builder.cc37
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping_builder.h8
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping_test.cc161
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_physical_line_box_fragment.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_physical_text_fragment.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_physical_text_fragment.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_physical_text_fragment_test.cc24
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_text_fragment_builder.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/inline/ng_text_fragment_builder.h13
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/layout_box_utils.cc139
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/layout_box_utils.h10
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/layout_ng_block_flow.cc135
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/layout_ng_block_flow.h6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/layout_ng_block_flow_mixin.cc331
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/layout_ng_block_flow_mixin.h100
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/layout_ng_flexible_box.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/layout_ng_flexible_box.h8
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/layout_ng_mixin.cc405
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/layout_ng_mixin.h66
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/layout_ng_table_caption.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/layout_ng_table_caption.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/layout_ng_table_cell.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/layout_ng_table_cell.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/legacy_layout_tree_walking.h5
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/list/layout_ng_inside_list_marker.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/list/layout_ng_inside_list_marker.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/list/layout_ng_list_item.cc28
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/list/layout_ng_list_item.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/list/layout_ng_list_marker.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/list/layout_ng_list_marker.h6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/list/ng_unpositioned_list_marker.cc61
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/list/ng_unpositioned_list_marker.h51
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_absolute_utils.cc822
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_absolute_utils.h62
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_absolute_utils_test.cc153
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_base_layout_algorithm_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_base_layout_algorithm_test.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_block_break_token.h22
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.cc523
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.h18
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm_test.cc23
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm_utils.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_block_node.cc157
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_block_node.h17
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_block_node_test.cc19
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_box_fragment.h7
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.cc87
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h13
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_break_token.cc2
-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_test.cc43
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_constraint_space.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_constraint_space.h77
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.cc21
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.h47
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_container_fragment_builder.cc149
-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_test.cc27
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_floats_utils.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_floats_utils.h12
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_fragment_builder.h16
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.h10
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_layout_algorithm.h5
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_layout_input_node.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_layout_input_node.h12
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_layout_result.cc204
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_layout_result.h255
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_layout_utils.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.cc493
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.h44
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_positioned_descendant.h46
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_positioned_node.h72
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_outline_utils.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment_test.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_physical_container_fragment.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_physical_container_fragment.h53
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_physical_fragment.cc82
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_physical_fragment.h13
-rw-r--r--chromium/third_party/blink/renderer/core/layout/ng/ng_simplified_layout_algorithm.cc85
-rw-r--r--chromium/third_party/blink/renderer/core/layout/order_iterator.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/paint_containment_test.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/layout/pointer_events_hit_rules.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/scroll_anchor.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/scrollbars_test.cc93
-rw-r--r--chromium/third_party/blink/renderer/core/layout/shapes/shape.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/layout/shapes/shape_outside_info.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/style_retain_scope.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/subtree_layout_scope.h2
-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_block.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_container.cc21
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_container.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_foreign_object.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_foreign_object.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_foreign_object_test.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_hidden_container.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_hidden_container.h4
-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_text.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_inline_text.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_path.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_clipper.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_filter_primitive.cc3
-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_paint_server.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_paint_server.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_root.cc34
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_root.h8
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_root_test.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_shape.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_shape.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_text.cc23
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_text.h6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_text_path.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_text_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_viewport_container.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/layout_svg_viewport_container.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/line/svg_inline_text_box.cc22
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/line/svg_inline_text_box.h6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/line/svg_root_inline_box.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/line/svg_root_inline_box.h6
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/svg_character_data.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/svg_layout_support.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/svg_layout_support.h4
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/svg_layout_tree_as_text.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/svg_marker_data.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/svg_resources.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/svg_resources.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/svg_resources_cache.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/svg_resources_cycle_solver.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/svg_text_chunk_builder.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/svg_text_fragment.h2
-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_attributes_builder.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/svg_text_layout_engine.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/svg_text_layout_engine_baseline.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/svg_text_layout_engine_spacing.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/svg_text_metrics.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/svg/svg_text_query.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/table_grid_cell.h2
-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_fixed.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/layout/text_autosizer.cc155
-rw-r--r--chromium/third_party/blink/renderer/core/layout/text_autosizer.h23
-rw-r--r--chromium/third_party/blink/renderer/core/layout/traced_layout_object.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/layout/vertical_position_cache.h2
-rw-r--r--chromium/third_party/blink/renderer/core/layout/visual_rect_mapping_test.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/loader/BUILD.gn8
-rw-r--r--chromium/third_party/blink/renderer/core/loader/DEPS5
-rw-r--r--chromium/third_party/blink/renderer/core/loader/alternate_signed_exchange_resource_info.cc70
-rw-r--r--chromium/third_party/blink/renderer/core/loader/alternate_signed_exchange_resource_info.h25
-rw-r--r--chromium/third_party/blink/renderer/core/loader/alternate_signed_exchange_resource_info_test.cc62
-rw-r--r--chromium/third_party/blink/renderer/core/loader/appcache/application_cache.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/loader/appcache/application_cache.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/loader/appcache/application_cache_host.cc389
-rw-r--r--chromium/third_party/blink/renderer/core/loader/appcache/application_cache_host.h174
-rw-r--r--chromium/third_party/blink/renderer/core/loader/appcache/application_cache_host_for_frame.cc254
-rw-r--r--chromium/third_party/blink/renderer/core/loader/appcache/application_cache_host_for_frame.h55
-rw-r--r--chromium/third_party/blink/renderer/core/loader/appcache/application_cache_host_for_shared_worker.cc55
-rw-r--r--chromium/third_party/blink/renderer/core/loader/appcache/application_cache_host_for_shared_worker.h32
-rw-r--r--chromium/third_party/blink/renderer/core/loader/base_fetch_context.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/loader/base_fetch_context.h4
-rw-r--r--chromium/third_party/blink/renderer/core/loader/cookie_jar.cc97
-rw-r--r--chromium/third_party/blink/renderer/core/loader/cookie_jar.h53
-rw-r--r--chromium/third_party/blink/renderer/core/loader/document_load_timing.cc34
-rw-r--r--chromium/third_party/blink/renderer/core/loader/document_load_timing.h68
-rw-r--r--chromium/third_party/blink/renderer/core/loader/document_load_timing_test.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/loader/document_loader.cc334
-rw-r--r--chromium/third_party/blink/renderer/core/loader/document_loader.h71
-rw-r--r--chromium/third_party/blink/renderer/core/loader/document_loader_test.cc51
-rw-r--r--chromium/third_party/blink/renderer/core/loader/empty_clients.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/loader/empty_clients.h19
-rw-r--r--chromium/third_party/blink/renderer/core/loader/form_submission.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/loader/form_submission.h2
-rw-r--r--chromium/third_party/blink/renderer/core/loader/frame_fetch_context.cc75
-rw-r--r--chromium/third_party/blink/renderer/core/loader/frame_fetch_context.h6
-rw-r--r--chromium/third_party/blink/renderer/core/loader/frame_fetch_context_test.cc190
-rw-r--r--chromium/third_party/blink/renderer/core/loader/frame_load_request.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/loader/frame_load_request.h2
-rw-r--r--chromium/third_party/blink/renderer/core/loader/frame_loader.cc157
-rw-r--r--chromium/third_party/blink/renderer/core/loader/frame_loader.h26
-rw-r--r--chromium/third_party/blink/renderer/core/loader/frame_loader_state_machine.h2
-rw-r--r--chromium/third_party/blink/renderer/core/loader/frame_resource_fetcher_properties.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/loader/history_item.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/loader/http_equiv.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/loader/http_equiv.h2
-rw-r--r--chromium/third_party/blink/renderer/core/loader/http_refresh_scheduler.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/loader/idleness_detector.cc42
-rw-r--r--chromium/third_party/blink/renderer/core/loader/idleness_detector.h28
-rw-r--r--chromium/third_party/blink/renderer/core/loader/idleness_detector_test.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/loader/image_loader.cc80
-rw-r--r--chromium/third_party/blink/renderer/core/loader/image_loader.h13
-rw-r--r--chromium/third_party/blink/renderer/core/loader/image_loader_test.cc52
-rw-r--r--chromium/third_party/blink/renderer/core/loader/importance_attribute.h2
-rw-r--r--chromium/third_party/blink/renderer/core/loader/interactive_detector.cc109
-rw-r--r--chromium/third_party/blink/renderer/core/loader/interactive_detector.h96
-rw-r--r--chromium/third_party/blink/renderer/core/loader/interactive_detector_test.cc460
-rw-r--r--chromium/third_party/blink/renderer/core/loader/link_load_parameters.h2
-rw-r--r--chromium/third_party/blink/renderer/core/loader/link_loader.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/loader/link_loader_test.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/loader/loader_factory_for_frame.cc1
-rw-r--r--chromium/third_party/blink/renderer/core/loader/long_task_detector.h3
-rw-r--r--chromium/third_party/blink/renderer/core/loader/long_task_detector_test.cc29
-rw-r--r--chromium/third_party/blink/renderer/core/loader/mixed_content_checker.cc24
-rw-r--r--chromium/third_party/blink/renderer/core/loader/mixed_content_checker_test.cc37
-rw-r--r--chromium/third_party/blink/renderer/core/loader/modulescript/document_module_script_fetcher.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/loader/modulescript/installed_service_worker_module_script_fetcher.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/loader/modulescript/module_script_creation_params.h40
-rw-r--r--chromium/third_party/blink/renderer/core/loader/modulescript/module_script_fetcher.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/loader/modulescript/module_script_loader.cc103
-rw-r--r--chromium/third_party/blink/renderer/core/loader/modulescript/module_script_loader_test.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/loader/modulescript/module_tree_linker.cc321
-rw-r--r--chromium/third_party/blink/renderer/core/loader/modulescript/module_tree_linker.h32
-rw-r--r--chromium/third_party/blink/renderer/core/loader/modulescript/worker_module_script_fetcher.cc24
-rw-r--r--chromium/third_party/blink/renderer/core/loader/modulescript/worklet_module_script_fetcher.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/loader/ping_loader.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/loader/prefetched_signed_exchange_manager.cc24
-rw-r--r--chromium/third_party/blink/renderer/core/loader/prefetched_signed_exchange_manager.h2
-rw-r--r--chromium/third_party/blink/renderer/core/loader/preload_helper.cc68
-rw-r--r--chromium/third_party/blink/renderer/core/loader/previews_resource_loading_hints.cc34
-rw-r--r--chromium/third_party/blink/renderer/core/loader/previews_resource_loading_hints.h21
-rw-r--r--chromium/third_party/blink/renderer/core/loader/previews_resource_loading_hints_receiver_impl.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/loader/previews_resource_loading_hints_test.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/loader/private/frame_client_hints_preferences_context.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/loader/private/frame_client_hints_preferences_context.h2
-rw-r--r--chromium/third_party/blink/renderer/core/loader/private/prerender_handle.cc9
-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.cc19
-rw-r--r--chromium/third_party/blink/renderer/core/loader/progress_tracker.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/loader/progress_tracker.h2
-rw-r--r--chromium/third_party/blink/renderer/core/loader/resource/css_style_sheet_resource.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/loader/resource/document_resource.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/loader/resource/font_resource.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/loader/resource/font_resource_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/loader/resource/image_resource.cc80
-rw-r--r--chromium/third_party/blink/renderer/core/loader/resource/image_resource.h5
-rw-r--r--chromium/third_party/blink/renderer/core/loader/resource/image_resource_content.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/loader/resource/image_resource_content.h2
-rw-r--r--chromium/third_party/blink/renderer/core/loader/resource/image_resource_info.h2
-rw-r--r--chromium/third_party/blink/renderer/core/loader/resource/image_resource_test.cc337
-rw-r--r--chromium/third_party/blink/renderer/core/loader/resource/script_resource.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/loader/resource/script_resource.h3
-rw-r--r--chromium/third_party/blink/renderer/core/loader/resource_load_observer_for_frame.cc58
-rw-r--r--chromium/third_party/blink/renderer/core/loader/resource_load_observer_for_frame.h6
-rw-r--r--chromium/third_party/blink/renderer/core/loader/resource_load_observer_for_worker.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/loader/resource_load_observer_for_worker.h6
-rw-r--r--chromium/third_party/blink/renderer/core/loader/subresource_integrity_helper.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/loader/subresource_integrity_helper.h2
-rw-r--r--chromium/third_party/blink/renderer/core/loader/text_track_loader.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/loader/threadable_loader.cc121
-rw-r--r--chromium/third_party/blink/renderer/core/loader/threadable_loader.h17
-rw-r--r--chromium/third_party/blink/renderer/core/loader/threadable_loader_test.cc33
-rw-r--r--chromium/third_party/blink/renderer/core/loader/threaded_icon_loader.cc183
-rw-r--r--chromium/third_party/blink/renderer/core/loader/threaded_icon_loader.h82
-rw-r--r--chromium/third_party/blink/renderer/core/loader/threaded_icon_loader_test.cc141
-rw-r--r--chromium/third_party/blink/renderer/core/loader/web_associated_url_loader_impl.cc (renamed from chromium/third_party/blink/renderer/core/exported/web_associated_url_loader_impl.cc)43
-rw-r--r--chromium/third_party/blink/renderer/core/loader/web_associated_url_loader_impl.h (renamed from chromium/third_party/blink/renderer/core/exported/web_associated_url_loader_impl.h)6
-rw-r--r--chromium/third_party/blink/renderer/core/loader/web_associated_url_loader_impl_test.cc (renamed from chromium/third_party/blink/renderer/core/exported/web_associated_url_loader_impl_test.cc)75
-rw-r--r--chromium/third_party/blink/renderer/core/loader/worker_fetch_context.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/loader/worker_fetch_context.h4
-rw-r--r--chromium/third_party/blink/renderer/core/loader/worker_resource_fetcher_properties.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/loader/worker_resource_timing_notifier_impl.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/messaging/blink_transferable_message.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/messaging/blink_transferable_message.h13
-rw-r--r--chromium/third_party/blink/renderer/core/messaging/blink_transferable_message_struct_traits.cc1
-rw-r--r--chromium/third_party/blink/renderer/core/messaging/blink_transferable_message_struct_traits.h4
-rw-r--r--chromium/third_party/blink/renderer/core/messaging/blink_transferable_message_struct_traits_test.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/messaging/message_port.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/mojo/DEPS4
-rw-r--r--chromium/third_party/blink/renderer/core/mojo/mojo.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/mojo/mojo_handle.cc29
-rw-r--r--chromium/third_party/blink/renderer/core/mojo/mojo_watcher.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/mojo/test/mojo_interface_interceptor.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/offscreencanvas/OWNERS1
-rw-r--r--chromium/third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.cc37
-rw-r--r--chromium/third_party/blink/renderer/core/origin_trials/origin_trial_context.cc106
-rw-r--r--chromium/third_party/blink/renderer/core/origin_trials/origin_trial_context.h32
-rw-r--r--chromium/third_party/blink/renderer/core/origin_trials/origin_trial_context_test.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/page/autoscroll_controller.cc76
-rw-r--r--chromium/third_party/blink/renderer/core/page/autoscroll_controller.h14
-rw-r--r--chromium/third_party/blink/renderer/core/page/autoscroll_controller_test.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/page/chrome_client.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/page/chrome_client.h50
-rw-r--r--chromium/third_party/blink/renderer/core/page/chrome_client_impl.cc168
-rw-r--r--chromium/third_party/blink/renderer/core/page/chrome_client_impl.h16
-rw-r--r--chromium/third_party/blink/renderer/core/page/chrome_client_test.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/page/context_menu_controller.cc44
-rw-r--r--chromium/third_party/blink/renderer/core/page/context_menu_controller.h2
-rw-r--r--chromium/third_party/blink/renderer/core/page/context_menu_controller_test.cc126
-rw-r--r--chromium/third_party/blink/renderer/core/page/create_window.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/page/drag_controller.cc47
-rw-r--r--chromium/third_party/blink/renderer/core/page/drag_image.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/page/drag_image.h2
-rw-r--r--chromium/third_party/blink/renderer/core/page/event_with_hit_test_results.h2
-rw-r--r--chromium/third_party/blink/renderer/core/page/focus_controller.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/page/focus_controller_test.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/page/frame_tree.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/page/page.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/page/page.h10
-rw-r--r--chromium/third_party/blink/renderer/core/page/page_popup_client.h6
-rw-r--r--chromium/third_party/blink/renderer/core/page/page_widget_delegate.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/page/page_widget_delegate.h10
-rw-r--r--chromium/third_party/blink/renderer/core/page/plugin_data.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/page/plugin_script_forbidden_scope.h2
-rw-r--r--chromium/third_party/blink/renderer/core/page/pointer_lock_controller.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/page/print_context.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/page/print_context_test.cc65
-rw-r--r--chromium/third_party/blink/renderer/core/page/scoped_page_pauser.h2
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/element_fragment_anchor.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/fragment_anchor.cc55
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/main_thread_scrolling_reasons_test.cc25
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/root_scroller_controller.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/root_scroller_test.cc144
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/scroll_into_view_test.cc28
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/scroll_metrics_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/scroll_state.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/scroll_state.h6
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/scroll_state_callback.h5
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator_context.h2
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator_test.cc23
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/snap_coordinator.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/snap_coordinator_test.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor.cc129
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor.h15
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor_metrics.cc34
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor_metrics.h5
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor_metrics_test.cc161
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor_test.cc294
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_finder.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/page/scrolling/viewport_scroll_callback.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/page/slot_scoped_traversal.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/page/slot_scoped_traversal.h2
-rw-r--r--chromium/third_party/blink/renderer/core/page/slot_scoped_traversal_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/page/spatial_navigation.cc178
-rw-r--r--chromium/third_party/blink/renderer/core/page/spatial_navigation.h24
-rw-r--r--chromium/third_party/blink/renderer/core/page/spatial_navigation_controller.cc27
-rw-r--r--chromium/third_party/blink/renderer/core/page/spatial_navigation_controller.h6
-rw-r--r--chromium/third_party/blink/renderer/core/page/spatial_navigation_test.cc139
-rw-r--r--chromium/third_party/blink/renderer/core/page/touch_adjustment.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/page/validation_message_client_impl.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/page/validation_message_client_impl.h2
-rw-r--r--chromium/third_party/blink/renderer/core/page/validation_message_overlay_delegate.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/page/viewport_description.cc2
-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.cc80
-rw-r--r--chromium/third_party/blink/renderer/core/page/zoom_test.cc30
-rw-r--r--chromium/third_party/blink/renderer/core/paint/BUILD.gn10
-rw-r--r--chromium/third_party/blink/renderer/core/paint/DEPS3
-rw-r--r--chromium/third_party/blink/renderer/core/paint/applied_decoration_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/background_image_geometry.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/paint/background_image_geometry.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/block_flow_paint_invalidator.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/block_paint_invalidator.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/block_painter.cc87
-rw-r--r--chromium/third_party/blink/renderer/core/paint/block_painter.h7
-rw-r--r--chromium/third_party/blink/renderer/core/paint/block_painter_test.cc164
-rw-r--r--chromium/third_party/blink/renderer/core/paint/box_model_object_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/box_paint_invalidator.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/box_painter.cc55
-rw-r--r--chromium/third_party/blink/renderer/core/paint/box_painter.h8
-rw-r--r--chromium/third_party/blink/renderer/core/paint/box_painter_base.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/paint/box_painter_base.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/box_painter_test.cc186
-rw-r--r--chromium/third_party/blink/renderer/core/paint/clip_rect.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/paint/clip_rect.h4
-rw-r--r--chromium/third_party/blink/renderer/core/paint/collapsed_border_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.cc126
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.h7
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/composited_layer_mapping_test.cc42
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/compositing_inputs_root.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/compositing_inputs_updater.cc41
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/compositing_inputs_updater.h5
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/compositing_inputs_updater_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/compositing_layer_assigner.cc30
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/compositing_layer_assigner.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/compositing_layer_assigner_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/compositing_layer_property_updater.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/compositing_layer_property_updater_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/compositing_reason_finder.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/compositing_reason_finder.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/compositing_reason_finder_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/compositing_requirements_updater.cc25
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/compositing_requirements_updater.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/compositing_requirements_updater_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/graphics_layer_tree_as_text.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/graphics_layer_tree_builder.cc21
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/graphics_layer_tree_builder.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/graphics_layer_updater.cc30
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/graphics_layer_updater.h3
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/paint_layer_compositor.cc197
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/paint_layer_compositor.h42
-rw-r--r--chromium/third_party/blink/renderer/core/paint/compositing/paint_layer_compositor_test.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/paint/css_mask_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/decoration_info.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/details_marker_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/document_marker_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/element_timing_utils.cc39
-rw-r--r--chromium/third_party/blink/renderer/core/paint/element_timing_utils.h29
-rw-r--r--chromium/third_party/blink/renderer/core/paint/ellipsis_box_painter.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/paint/ellipsis_box_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/embedded_content_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/embedded_object_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/fieldset_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/file_upload_control_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/filter_effect_builder.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/find_paint_offset_and_visual_rect_needing_update.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/find_properties_needing_update.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/first_meaningful_paint_detector.cc113
-rw-r--r--chromium/third_party/blink/renderer/core/paint/first_meaningful_paint_detector.h27
-rw-r--r--chromium/third_party/blink/renderer/core/paint/first_meaningful_paint_detector_test.cc174
-rw-r--r--chromium/third_party/blink/renderer/core/paint/fragment_data.cc23
-rw-r--r--chromium/third_party/blink/renderer/core/paint/fragment_data.h14
-rw-r--r--chromium/third_party/blink/renderer/core/paint/frame_painter.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/paint/frame_set_painter.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/paint/frame_set_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/html_canvas_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/image_element_timing.cc187
-rw-r--r--chromium/third_party/blink/renderer/core/paint/image_element_timing.h72
-rw-r--r--chromium/third_party/blink/renderer/core/paint/image_element_timing_test.cc204
-rw-r--r--chromium/third_party/blink/renderer/core/paint/image_paint_timing_detector.cc402
-rw-r--r--chromium/third_party/blink/renderer/core/paint/image_paint_timing_detector.h203
-rw-r--r--chromium/third_party/blink/renderer/core/paint/image_paint_timing_detector_test.cc483
-rw-r--r--chromium/third_party/blink/renderer/core/paint/image_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/inline_box_painter_base.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/inline_flow_box_painter.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/inline_flow_box_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/inline_painter.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/paint/inline_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/inline_text_box_painter.cc23
-rw-r--r--chromium/third_party/blink/renderer/core/paint/inline_text_box_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/largest_contentful_paint_calculator.cc162
-rw-r--r--chromium/third_party/blink/renderer/core/paint/largest_contentful_paint_calculator.h63
-rw-r--r--chromium/third_party/blink/renderer/core/paint/largest_contentful_paint_calculator_test.cc276
-rw-r--r--chromium/third_party/blink/renderer/core/paint/layout_object_counter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/line_box_list_painter.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/paint/line_box_list_painter.h8
-rw-r--r--chromium/third_party/blink/renderer/core/paint/link_highlight_impl.cc66
-rw-r--r--chromium/third_party/blink/renderer/core/paint/link_highlight_impl.h16
-rw-r--r--chromium/third_party/blink/renderer/core/paint/link_highlight_impl_test.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/paint/list_item_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/list_marker_painter.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/paint/list_marker_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/multi_column_set_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.cc256
-rw-r--r--chromium/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.h40
-rw-r--r--chromium/third_party/blink/renderer/core/paint/ng/ng_fieldset_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/ng/ng_fragment_painter.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/ng/ng_inline_box_fragment_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/ng/ng_paint_fragment.cc135
-rw-r--r--chromium/third_party/blink/renderer/core/paint/ng/ng_paint_fragment.h62
-rw-r--r--chromium/third_party/blink/renderer/core/paint/ng/ng_paint_fragment_test.cc38
-rw-r--r--chromium/third_party/blink/renderer/core/paint/ng/ng_text_fragment_painter.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/paint/ng/ng_text_fragment_painter.h6
-rw-r--r--chromium/third_party/blink/renderer/core/paint/ng/ng_text_painter.cc19
-rw-r--r--chromium/third_party/blink/renderer/core/paint/ng/ng_text_painter.h8
-rw-r--r--chromium/third_party/blink/renderer/core/paint/object_paint_invalidator.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/paint/object_paint_invalidator.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/object_paint_invalidator_test.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/paint/object_paint_properties.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/object_painter.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/object_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/object_painter_base.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_and_raster_invalidation_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_controller_paint_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_controller_paint_test.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_info.h8
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_invalidator.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_invalidator.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_layer.cc363
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_layer.h155
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_layer_clipper.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_layer_clipper.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_layer_clipper_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_layer_fragment.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_layer_paint_order_iterator.cc (renamed from chromium/third_party/blink/renderer/core/paint/paint_layer_stacking_node_iterator.cc)107
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_layer_paint_order_iterator.h (renamed from chromium/third_party/blink/renderer/core/paint/paint_layer_stacking_node_iterator.h)81
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_layer_painter.cc104
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_layer_painter.h14
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_layer_painter_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_layer_painting_info.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_layer_scrollable_area.cc201
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h28
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_layer_scrollable_area_test.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_layer_stacking_node.cc302
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_layer_stacking_node.h171
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_layer_test.cc455
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_phase.h23
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_property_tree_builder.cc168
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_property_tree_builder.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_property_tree_builder_test.cc162
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_property_tree_printer.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_property_tree_printer_test.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_property_tree_update_tests.cc151
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_timing.cc49
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_timing.h55
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_timing_detector.cc234
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_timing_detector.h135
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_timing_test_helper.h36
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_timing_visualizer.cc111
-rw-r--r--chromium/third_party/blink/renderer/core/paint/paint_timing_visualizer.h44
-rw-r--r--chromium/third_party/blink/renderer/core/paint/pre_paint_tree_walk.cc95
-rw-r--r--chromium/third_party/blink/renderer/core/paint/pre_paint_tree_walk.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/pre_paint_tree_walk_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/replaced_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/root_inline_box_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/rounded_inner_rect_clipper.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/scrollable_area_painter.cc92
-rw-r--r--chromium/third_party/blink/renderer/core/paint/scrollable_area_painter.h6
-rw-r--r--chromium/third_party/blink/renderer/core/paint/selection_painting_utils.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/paint/selection_painting_utils.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/svg_container_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/svg_filter_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/svg_foreign_object_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/svg_image_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/svg_inline_flow_box_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/svg_inline_text_box_painter.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/svg_inline_text_box_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/svg_mask_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/svg_model_object_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/svg_object_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/svg_root_inline_box_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/svg_root_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/svg_shape_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/svg_text_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/table_cell_paint_invalidator.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/table_cell_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/table_paint_invalidator.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/table_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/table_row_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/table_section_painter.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/table_section_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/text_control_single_line_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/text_element_timing.cc56
-rw-r--r--chromium/third_party/blink/renderer/core/paint/text_element_timing.h22
-rw-r--r--chromium/third_party/blink/renderer/core/paint/text_paint_style.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/text_paint_timing_detector.cc355
-rw-r--r--chromium/third_party/blink/renderer/core/paint/text_paint_timing_detector.h200
-rw-r--r--chromium/third_party/blink/renderer/core/paint/text_paint_timing_detector_test.cc390
-rw-r--r--chromium/third_party/blink/renderer/core/paint/text_painter.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/paint/text_painter.h8
-rw-r--r--chromium/third_party/blink/renderer/core/paint/text_painter_base.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/theme_painter.cc133
-rw-r--r--chromium/third_party/blink/renderer/core/paint/theme_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/theme_painter_default.cc29
-rw-r--r--chromium/third_party/blink/renderer/core/paint/video_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/video_painter_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/view_painter.cc23
-rw-r--r--chromium/third_party/blink/renderer/core/paint/view_painter.h2
-rw-r--r--chromium/third_party/blink/renderer/core/paint/view_painter_test.cc79
-rw-r--r--chromium/third_party/blink/renderer/core/probe/core_probes.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/probe/core_probes.h10
-rw-r--r--chromium/third_party/blink/renderer/core/probe/core_probes.pidl4
-rw-r--r--chromium/third_party/blink/renderer/core/resize_observer/resize_observation.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/resize_observer/resize_observer.idl5
-rw-r--r--chromium/third_party/blink/renderer/core/resize_observer/resize_observer_entry.idl3
-rw-r--r--chromium/third_party/blink/renderer/core/scheduler/frame_throttling_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/scheduler/scheduler_affecting_features_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/scheduler/throttling_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/scheduler/virtual_time_test.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/script/BUILD.gn23
-rw-r--r--chromium/third_party/blink/renderer/core/script/classic_pending_script.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/script/classic_pending_script.h4
-rw-r--r--chromium/third_party/blink/renderer/core/script/classic_script.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/script/classic_script.h2
-rw-r--r--chromium/third_party/blink/renderer/core/script/document_write_intervention.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/script/dynamic_module_resolver.cc78
-rw-r--r--chromium/third_party/blink/renderer/core/script/dynamic_module_resolver.h2
-rw-r--r--chromium/third_party/blink/renderer/core/script/dynamic_module_resolver_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/script/fetch_client_settings_object_impl.h4
-rwxr-xr-xchromium/third_party/blink/renderer/core/script/generate_lapi_grdp.py65
-rw-r--r--chromium/third_party/blink/renderer/core/script/html_parser_script_runner.cc140
-rw-r--r--chromium/third_party/blink/renderer/core/script/html_parser_script_runner.h22
-rw-r--r--chromium/third_party/blink/renderer/core/script/html_parser_script_runner_host.h2
-rw-r--r--chromium/third_party/blink/renderer/core/script/ignore_destructive_write_count_incrementer.h2
-rw-r--r--chromium/third_party/blink/renderer/core/script/import_map.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/script/js_module_script.cc19
-rw-r--r--chromium/third_party/blink/renderer/core/script/js_module_script.h3
-rw-r--r--chromium/third_party/blink/renderer/core/script/layered_api_module.h5
-rw-r--r--chromium/third_party/blink/renderer/core/script/layered_api_resources.h51
-rw-r--r--chromium/third_party/blink/renderer/core/script/layered_api_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/script/mock_script_element_base.h4
-rw-r--r--chromium/third_party/blink/renderer/core/script/modulator.h12
-rw-r--r--chromium/third_party/blink/renderer/core/script/modulator_impl_base.cc73
-rw-r--r--chromium/third_party/blink/renderer/core/script/modulator_impl_base.h6
-rw-r--r--chromium/third_party/blink/renderer/core/script/module_map.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/script/module_map.h2
-rw-r--r--chromium/third_party/blink/renderer/core/script/module_map_test.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/script/module_pending_script.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/script/module_pending_script.h4
-rw-r--r--chromium/third_party/blink/renderer/core/script/module_record_resolver.h6
-rw-r--r--chromium/third_party/blink/renderer/core/script/module_record_resolver_impl.cc45
-rw-r--r--chromium/third_party/blink/renderer/core/script/module_record_resolver_impl.h5
-rw-r--r--chromium/third_party/blink/renderer/core/script/module_record_resolver_impl_test.cc4
-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.h3
-rw-r--r--chromium/third_party/blink/renderer/core/script/module_script_test.cc23
-rw-r--r--chromium/third_party/blink/renderer/core/script/pending_script.cc58
-rw-r--r--chromium/third_party/blink/renderer/core/script/pending_script.h10
-rw-r--r--chromium/third_party/blink/renderer/core/script/resources/layered_api/PRESUBMIT.py39
-rw-r--r--chromium/third_party/blink/renderer/core/script/resources/layered_api/README.md24
-rw-r--r--chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/internal/reflection.mjs63
-rw-r--r--chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/switch/README.md3
-rw-r--r--chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/switch/face_utils.mjs75
-rw-r--r--chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/switch/index.mjs128
-rw-r--r--chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/switch/style.mjs224
-rw-r--r--chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/switch/track.mjs74
-rw-r--r--chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/toast/.eslintrc.js338
-rw-r--r--chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/toast/OWNERS1
-rw-r--r--chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/toast/index.mjs280
-rw-r--r--chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/.eslintrc.js337
-rw-r--r--chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/OWNERS1
-rw-r--r--chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/docs/README.md297
-rw-r--r--chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/docs/roaming-slot.pngbin0 -> 36729 bytes
-rw-r--r--chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/find-element.mjs104
-rw-r--r--chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/index.mjs57
-rw-r--r--chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/sets.mjs24
-rw-r--r--chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/visibility-manager.mjs407
-rw-r--r--chromium/third_party/blink/renderer/core/script/resources/layered_api/kv-storage/async_iterator.mjs8
-rw-r--r--chromium/third_party/blink/renderer/core/script/resources/layered_api/kv-storage/index.mjs33
-rw-r--r--chromium/third_party/blink/renderer/core/script/resources/layered_api/resources.grdp17
-rw-r--r--chromium/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/README.chromium12
-rw-r--r--chromium/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/index.mjs213
-rw-r--r--chromium/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/item-source.mjs47
-rw-r--r--chromium/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/layouts/layout-1d-base.mjs320
-rw-r--r--chromium/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/layouts/layout-1d-grid.mjs64
-rw-r--r--chromium/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/layouts/layout-1d.mjs349
-rw-r--r--chromium/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/virtual-repeater.mjs531
-rw-r--r--chromium/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/virtual-scroller.mjs444
-rw-r--r--chromium/third_party/blink/renderer/core/script/script.h2
-rw-r--r--chromium/third_party/blink/renderer/core/script/script_loader.cc112
-rw-r--r--chromium/third_party/blink/renderer/core/script/script_loader.h34
-rw-r--r--chromium/third_party/blink/renderer/core/script/script_runner.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/script/script_runner.h2
-rw-r--r--chromium/third_party/blink/renderer/core/script/script_scheduling_type.h9
-rw-r--r--chromium/third_party/blink/renderer/core/script/value_wrapper_synthetic_module_script.cc153
-rw-r--r--chromium/third_party/blink/renderer/core/script/value_wrapper_synthetic_module_script.h78
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/programmatic_scroll_animator.h2
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scroll_alignment.cc41
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scroll_alignment.h8
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scroll_animator.cc82
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scroll_animator.h27
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scroll_animator_base.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scroll_animator_base.h5
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scroll_animator_compositor_coordinator.h6
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scroll_animator_mac.h3
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scroll_animator_mac.mm31
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scroll_animator_test.cc307
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scrollable_area.cc94
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scrollable_area.h36
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scrollable_area_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scrollbar.cc23
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scrollbar.h7
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scrollbar_theme.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scrollbar_theme.h8
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scrollbar_theme_mac.h4
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scrollbar_theme_mac.mm8
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scrollbar_theme_overlay.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scrollbar_theme_overlay.h4
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scrollbar_theme_overlay_mock.h14
-rw-r--r--chromium/third_party/blink/renderer/core/scroll/scrolling_test.cc323
-rw-r--r--chromium/third_party/blink/renderer/core/streams/BUILD.gn8
-rw-r--r--chromium/third_party/blink/renderer/core/streams/README.md2
-rw-r--r--chromium/third_party/blink/renderer/core/streams/ReadableStream.js59
-rw-r--r--chromium/third_party/blink/renderer/core/streams/TransformStream.js2
-rw-r--r--chromium/third_party/blink/renderer/core/streams/byte_length_queuing_strategy.cc101
-rw-r--r--chromium/third_party/blink/renderer/core/streams/byte_length_queuing_strategy.h41
-rw-r--r--chromium/third_party/blink/renderer/core/streams/byte_length_queuing_strategy.idl17
-rw-r--r--chromium/third_party/blink/renderer/core/streams/count_queuing_strategy.cc72
-rw-r--r--chromium/third_party/blink/renderer/core/streams/count_queuing_strategy.h40
-rw-r--r--chromium/third_party/blink/renderer/core/streams/count_queuing_strategy.idl17
-rw-r--r--chromium/third_party/blink/renderer/core/streams/miscellaneous_operations.h2
-rw-r--r--chromium/third_party/blink/renderer/core/streams/miscellaneous_operations_test.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/streams/queuing_strategy_common.cc23
-rw-r--r--chromium/third_party/blink/renderer/core/streams/queuing_strategy_common.h20
-rw-r--r--chromium/third_party/blink/renderer/core/streams/queuing_strategy_init.idl10
-rw-r--r--chromium/third_party/blink/renderer/core/streams/readable_stream.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/streams/readable_stream_default_controller.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/streams/readable_stream_default_controller.h4
-rw-r--r--chromium/third_party/blink/renderer/core/streams/readable_stream_default_controller_interface.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/streams/readable_stream_default_controller_interface.h1
-rw-r--r--chromium/third_party/blink/renderer/core/streams/readable_stream_native.cc67
-rw-r--r--chromium/third_party/blink/renderer/core/streams/readable_stream_native.h29
-rw-r--r--chromium/third_party/blink/renderer/core/streams/readable_stream_operations_test.cc64
-rw-r--r--chromium/third_party/blink/renderer/core/streams/readable_stream_reader.cc49
-rw-r--r--chromium/third_party/blink/renderer/core/streams/readable_stream_reader.h9
-rw-r--r--chromium/third_party/blink/renderer/core/streams/readable_stream_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/streams/transferable_streams.cc878
-rw-r--r--chromium/third_party/blink/renderer/core/streams/transferable_streams.h37
-rw-r--r--chromium/third_party/blink/renderer/core/streams/transferable_streams_test.cc129
-rw-r--r--chromium/third_party/blink/renderer/core/streams/transform_stream_default_controller_interface.h2
-rw-r--r--chromium/third_party/blink/renderer/core/streams/transform_stream_native.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/streams/transform_stream_wrapper.h2
-rw-r--r--chromium/third_party/blink/renderer/core/streams/underlying_sink_base.h2
-rw-r--r--chromium/third_party/blink/renderer/core/streams/underlying_source_base.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/streams/underlying_source_base.h9
-rw-r--r--chromium/third_party/blink/renderer/core/streams/underlying_source_base.idl4
-rw-r--r--chromium/third_party/blink/renderer/core/streams/writable_stream.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/streams/writable_stream.h5
-rw-r--r--chromium/third_party/blink/renderer/core/streams/writable_stream_default_writer.h3
-rw-r--r--chromium/third_party/blink/renderer/core/streams/writable_stream_native.cc65
-rw-r--r--chromium/third_party/blink/renderer/core/streams/writable_stream_native.h14
-rw-r--r--chromium/third_party/blink/renderer/core/streams/writable_stream_test.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/streams/writable_stream_wrapper.cc23
-rw-r--r--chromium/third_party/blink/renderer/core/streams/writable_stream_wrapper.h6
-rw-r--r--chromium/third_party/blink/renderer/core/style/applied_text_decoration.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/basic_shapes.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/border_edge.h2
-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_image_length_box.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/border_style.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/border_value.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/cached_ua_style.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/clip_path_operation.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/computed_style.cc98
-rw-r--r--chromium/third_party/blink/renderer/core/style/computed_style.h243
-rw-r--r--chromium/third_party/blink/renderer/core/style/computed_style_diff_functions.json548
-rw-r--r--chromium/third_party/blink/renderer/core/style/computed_style_extra_fields.json5145
-rw-r--r--chromium/third_party/blink/renderer/core/style/computed_style_test.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/style/content_data.cc25
-rw-r--r--chromium/third_party/blink/renderer/core/style/content_data.h12
-rw-r--r--chromium/third_party/blink/renderer/core/style/counter_directives.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/data_ref.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/fill_layer.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/gap_length.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/grid_area.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/grid_length.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/grid_position.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/grid_positions_resolver.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/grid_track_size.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/nine_piece_image.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/quotes_data.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/shadow_list.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/style_content_alignment_data.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/style_difference.h16
-rw-r--r--chromium/third_party/blink/renderer/core/style/style_fetched_image.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/style/style_fetched_image.h1
-rw-r--r--chromium/third_party/blink/renderer/core/style/style_non_inherited_variables.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/style_path.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/style/style_path.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/style_reflection.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/style_self_alignment_data.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/style_svg_resource.h2
-rw-r--r--chromium/third_party/blink/renderer/core/style/svg_computed_style.h14
-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/svg_computed_style_test.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/style/text_size_adjust.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_animation_sandwich.cc153
-rw-r--r--chromium/third_party/blink/renderer/core/svg/animation/smil_animation_sandwich.h83
-rw-r--r--chromium/third_party/blink/renderer/core/svg/animation/smil_time.h2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/animation/smil_time_container.cc200
-rw-r--r--chromium/third_party/blink/renderer/core/svg/animation/smil_time_container.h17
-rw-r--r--chromium/third_party/blink/renderer/core/svg/animation/svg_smil_element.cc279
-rw-r--r--chromium/third_party/blink/renderer/core/svg/animation/svg_smil_element.h40
-rw-r--r--chromium/third_party/blink/renderer/core/svg/color_distance.h2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/gradient_attributes.h2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/graphics/dark_mode_svg_image_classifier.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/graphics/dark_mode_svg_image_classifier.h2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/graphics/filters/svg_filter_builder.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/svg/graphics/svg_image.cc21
-rw-r--r--chromium/third_party/blink/renderer/core/svg/graphics/svg_image.h7
-rw-r--r--chromium/third_party/blink/renderer/core/svg/graphics/svg_image_chrome_client.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/svg/graphics/svg_image_test.cc30
-rw-r--r--chromium/third_party/blink/renderer/core/svg/properties/svg_animated_property.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/properties/svg_list_property_helper.h2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_a_element.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_a_element.h4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_a_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_angle.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animate_element.cc34
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animate_element.h8
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animate_motion_element.cc24
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_angle.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_boolean.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_enumeration.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_href.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_integer.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_length.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_length.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_length_list.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_number.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_number_list.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_preserve_aspect_ratio.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_rect.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_string.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animated_transform_list.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animation_element.cc24
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_animation_element.h2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_circle_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_clip_path_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_defs_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_desc_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_discard_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_discard_element.h2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_element.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_element.h6
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_ellipse_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_image_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_fe_image_element.h10
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_filter_element.h4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_filter_primitive_standard_attributes.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_filter_primitive_standard_attributes.h9
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_foreign_object_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_foreign_object_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_g_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_geometry_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_gradient_element.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_gradient_element.h12
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_gradient_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_graphics_element.h8
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_graphics_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_image_element.cc2
-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_length.cc131
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_length.h17
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_length.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_length_list.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_length_list.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_length_tear_off.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_line_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_linear_gradient_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_marker_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_mask_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_metadata_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_mpath_element.h4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_number.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_number_list.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_parsing_error.h2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_path_blender.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_path_data.h2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_path_element.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_path_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_path_query.h2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_pattern_element.h4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_pattern_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_point_list.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_polygon_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_polyline_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_preserve_aspect_ratio.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_radial_gradient_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_rect.h2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_rect_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_resource.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_script_element.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_script_element.h2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_script_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_stop_element.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_stop_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_string_list.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_style_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_svg_element.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_svg_element.idl1
-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_switch_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_symbol_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_text_content_element.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_text_content_element.h8
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_text_content_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_text_content_element_test.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_text_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_text_path_element.h4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_text_path_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_text_positioning_element.h8
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_text_positioning_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_title_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_transform.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_transform_distance.h2
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_transform_list.cc29
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_transform_list.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_tspan_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_unit_types.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_uri_reference.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_uri_reference.h4
-rw-r--r--chromium/third_party/blink/renderer/core/svg/svg_use_element.cc16
-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_use_element.idl1
-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_element.idl1
-rw-r--r--chromium/third_party/blink/renderer/core/svg/unsafe_svg_attribute_sanitization_test.cc32
-rw-r--r--chromium/third_party/blink/renderer/core/testing/core_unit_test_helper.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/testing/core_unit_test_helper.h20
-rw-r--r--chromium/third_party/blink/renderer/core/testing/data/frameserialization/image_in_plugin.html10
-rw-r--r--chromium/third_party/blink/renderer/core/testing/data/frameserialization/img_srcset.html2
-rw-r--r--chromium/third_party/blink/renderer/core/testing/data/frameserialization/picture.html13
-rw-r--r--chromium/third_party/blink/renderer/core/testing/data/frameserialization/style_element_with_dynamic_css.html20
-rw-r--r--chromium/third_party/blink/renderer/core/testing/data/notifications/file.txt1
-rw-r--r--chromium/third_party/blink/renderer/core/testing/document_interface_broker_test_helpers.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/testing/document_interface_broker_test_helpers.h12
-rw-r--r--chromium/third_party/blink/renderer/core/testing/dummy_modulator.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/testing/dummy_page_holder.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/testing/dummy_page_holder.h18
-rw-r--r--chromium/third_party/blink/renderer/core/testing/gc_object_liveness_observer.h2
-rw-r--r--chromium/third_party/blink/renderer/core/testing/internal_settings.h2
-rw-r--r--chromium/third_party/blink/renderer/core/testing/internals.cc196
-rw-r--r--chromium/third_party/blink/renderer/core/testing/internals.h6
-rw-r--r--chromium/third_party/blink/renderer/core/testing/internals.idl9
-rw-r--r--chromium/third_party/blink/renderer/core/testing/null_execution_context.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/testing/null_execution_context.h5
-rw-r--r--chromium/third_party/blink/renderer/core/testing/origin_trials_test_partial.h2
-rw-r--r--chromium/third_party/blink/renderer/core/testing/page_test_base.cc61
-rw-r--r--chromium/third_party/blink/renderer/core/testing/page_test_base.h22
-rw-r--r--chromium/third_party/blink/renderer/core/testing/sim/sim_canvas.h2
-rw-r--r--chromium/third_party/blink/renderer/core/testing/sim/sim_compositor.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/testing/sim/sim_network.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/testing/sim/sim_network.h2
-rw-r--r--chromium/third_party/blink/renderer/core/testing/sim/sim_page.h6
-rw-r--r--chromium/third_party/blink/renderer/core/testing/sim/sim_request.cc23
-rw-r--r--chromium/third_party/blink/renderer/core/testing/sim/sim_request.h3
-rw-r--r--chromium/third_party/blink/renderer/core/testing/sim/sim_test.cc62
-rw-r--r--chromium/third_party/blink/renderer/core/testing/sim/sim_test.h18
-rw-r--r--chromium/third_party/blink/renderer/core/testing/worker_internals.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/timing/BUILD.gn2
-rw-r--r--chromium/third_party/blink/renderer/core/timing/event_timing.cc19
-rw-r--r--chromium/third_party/blink/renderer/core/timing/event_timing.h10
-rw-r--r--chromium/third_party/blink/renderer/core/timing/largest_contentful_paint.cc65
-rw-r--r--chromium/third_party/blink/renderer/core/timing/largest_contentful_paint.h54
-rw-r--r--chromium/third_party/blink/renderer/core/timing/largest_contentful_paint.idl16
-rw-r--r--chromium/third_party/blink/renderer/core/timing/layout_shift.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/timing/layout_shift.h10
-rw-r--r--chromium/third_party/blink/renderer/core/timing/layout_shift.idl4
-rw-r--r--chromium/third_party/blink/renderer/core/timing/memory_info.cc24
-rw-r--r--chromium/third_party/blink/renderer/core/timing/memory_info.h11
-rw-r--r--chromium/third_party/blink/renderer/core/timing/memory_info.idl2
-rw-r--r--chromium/third_party/blink/renderer/core/timing/memory_info_test.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance.cc295
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance.h38
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance.idl22
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_element_timing.cc35
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_element_timing.h25
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_element_timing.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_entry.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_entry.h11
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_entry_names.json55
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_event_timing.idl2
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_mark.cc87
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_mark.h22
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_mark_options.idl4
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_measure.cc58
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_measure.h28
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_measure_options.idl3
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_navigation_timing.cc44
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_navigation_timing.h2
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_observer.cc68
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_observer.idl2
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_observer_test.cc23
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_resource_timing.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_resource_timing.h13
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_test.cc126
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_timing.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_timing.h2
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_user_timing.cc44
-rw-r--r--chromium/third_party/blink/renderer/core/timing/performance_user_timing.h3
-rw-r--r--chromium/third_party/blink/renderer/core/timing/profiler.idl5
-rw-r--r--chromium/third_party/blink/renderer/core/timing/profiler_frame.idl12
-rw-r--r--chromium/third_party/blink/renderer/core/timing/profiler_group.cc103
-rw-r--r--chromium/third_party/blink/renderer/core/timing/profiler_group.h6
-rw-r--r--chromium/third_party/blink/renderer/core/timing/profiler_group_test.cc82
-rw-r--r--chromium/third_party/blink/renderer/core/timing/profiler_init_options.idl3
-rw-r--r--chromium/third_party/blink/renderer/core/timing/profiler_sample.idl10
-rw-r--r--chromium/third_party/blink/renderer/core/timing/profiler_stack.idl10
-rw-r--r--chromium/third_party/blink/renderer/core/timing/profiler_trace.idl12
-rw-r--r--chromium/third_party/blink/renderer/core/timing/sub_task_attribution.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/timing/sub_task_attribution.h14
-rw-r--r--chromium/third_party/blink/renderer/core/timing/time_clamper.h2
-rw-r--r--chromium/third_party/blink/renderer/core/timing/window_performance.cc78
-rw-r--r--chromium/third_party/blink/renderer/core/timing/window_performance.h26
-rw-r--r--chromium/third_party/blink/renderer/core/timing/window_performance_test.cc143
-rw-r--r--chromium/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.idl2
-rw-r--r--chromium/third_party/blink/renderer/core/trustedtypes/trusted_types_util.cc193
-rw-r--r--chromium/third_party/blink/renderer/core/trustedtypes/trusted_types_util.h27
-rw-r--r--chromium/third_party/blink/renderer/core/typed_arrays/dom_array_buffer.cc21
-rw-r--r--chromium/third_party/blink/renderer/core/typed_arrays/dom_array_buffer.h3
-rw-r--r--chromium/third_party/blink/renderer/core/url/dom_url_utils.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/url/url_search_params.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/workers/BUILD.gn13
-rw-r--r--chromium/third_party/blink/renderer/core/workers/dedicated_worker.cc66
-rw-r--r--chromium/third_party/blink/renderer/core/workers/dedicated_worker.h9
-rw-r--r--chromium/third_party/blink/renderer/core/workers/dedicated_worker_global_scope.cc8
-rw-r--r--chromium/third_party/blink/renderer/core/workers/dedicated_worker_global_scope.h2
-rw-r--r--chromium/third_party/blink/renderer/core/workers/dedicated_worker_messaging_proxy.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/workers/dedicated_worker_messaging_proxy.h2
-rw-r--r--chromium/third_party/blink/renderer/core/workers/dedicated_worker_object_proxy.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/workers/dedicated_worker_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/workers/dedicated_worker_thread.cc1
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/OWNERS4
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/README.md17
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/task.cc507
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/task.h230
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/task.idl11
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/task_worklet.cc143
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/task_worklet.h54
-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.cc110
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.h40
-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.cc167
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/thread_pool.h41
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/thread_pool_thread.cc104
-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.cc92
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/worker_task_queue.h55
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/worker_task_queue.idl17
-rw-r--r--chromium/third_party/blink/renderer/core/workers/global_scope_creation_params.h2
-rw-r--r--chromium/third_party/blink/renderer/core/workers/installed_scripts_manager.h2
-rw-r--r--chromium/third_party/blink/renderer/core/workers/main_thread_worklet_reporting_proxy.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/workers/main_thread_worklet_test.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/workers/parent_execution_context_task_runners.h2
-rw-r--r--chromium/third_party/blink/renderer/core/workers/shared_worker.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/workers/shared_worker_client.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/workers/shared_worker_client_holder.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/workers/shared_worker_global_scope.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/workers/shared_worker_global_scope.h2
-rw-r--r--chromium/third_party/blink/renderer/core/workers/shared_worker_reporting_proxy.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/workers/threaded_messaging_proxy_base.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/workers/threaded_messaging_proxy_base.h2
-rw-r--r--chromium/third_party/blink/renderer/core/workers/threaded_object_proxy_base.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/workers/threaded_worklet_messaging_proxy.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/workers/threaded_worklet_messaging_proxy.h2
-rw-r--r--chromium/third_party/blink/renderer/core/workers/threaded_worklet_object_proxy.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/workers/threaded_worklet_object_proxy.h2
-rw-r--r--chromium/third_party/blink/renderer/core/workers/threaded_worklet_test.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_animation_frame_provider.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_animation_frame_provider.h2
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_backing_thread.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_backing_thread.h7
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_backing_thread_startup_data.h12
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_classic_script_loader.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_classic_script_loader.h6
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_global_scope.cc31
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_global_scope.h16
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_global_scope.idl2
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_or_worklet_global_scope.cc24
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_or_worklet_global_scope.h10
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_reporting_proxy.h7
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_settings.h2
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_thread.cc24
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_thread.h12
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_thread_test.cc42
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_thread_test_helper.h9
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worklet.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worklet.h6
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worklet_global_scope.cc20
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worklet_global_scope.h8
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worklet_global_scope_proxy.h2
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worklet_module_responses_map.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worklet_module_responses_map.h2
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worklet_module_tree_client.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worklet_thread_holder.h1
-rw-r--r--chromium/third_party/blink/renderer/core/xml/document_xslt.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/xml/dom_parser.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/xml/parser/shared_buffer_reader.h2
-rw-r--r--chromium/third_party/blink/renderer/core/xml/parser/xml_document_parser.cc24
-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_document_parser_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/xml/parser/xml_parser_input.h2
-rw-r--r--chromium/third_party/blink/renderer/core/xml/xml_serializer.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/xml/xpath_functions.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/xml/xpath_functions_test.cc2
-rw-r--r--chromium/third_party/blink/renderer/core/xml/xpath_node_set.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/xml/xpath_parser.h2
-rw-r--r--chromium/third_party/blink/renderer/core/xml/xpath_step.cc29
-rw-r--r--chromium/third_party/blink/renderer/core/xml/xsl_style_sheet_libxslt.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/xml/xslt_processor.cc18
-rw-r--r--chromium/third_party/blink/renderer/core/xml/xslt_processor_libxslt.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.cc35
-rw-r--r--chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.h2
-rw-r--r--chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request_progress_event_throttle.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/xmlhttprequest/xml_http_request_progress_event_throttle.h7
2681 files changed, 54369 insertions, 35189 deletions
diff --git a/chromium/third_party/blink/renderer/core/BUILD.gn b/chromium/third_party/blink/renderer/core/BUILD.gn
index 9bf980cb526..79a7f1d5010 100644
--- a/chromium/third_party/blink/renderer/core/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/BUILD.gn
@@ -514,618 +514,20 @@ css_properties("make_core_generated_css_property_instances") {
]
}
-# FIXME: Need a better way to specify generated output files
-css_properties("make_core_generated_css_longhand_property_classes") {
+css_properties("make_core_generated_css_subclasses") {
script =
"../build/scripts/core/css/properties/make_css_property_subclasses.py"
in_files = [ "css/properties/css_property_methods.json5" ]
other_inputs = [
"css/css_properties.json5",
- "../build/scripts/core/css/properties/templates/css_property_subclass.h.tmpl",
- "../build/scripts/core/css/properties/templates/css_property_subclass.cc.tmpl",
+ "../build/scripts/core/css/properties/templates/css_properties.h.tmpl",
+ "../build/scripts/core/css/properties/templates/css_properties.cc.tmpl",
]
outputs = [
- "$blink_core_output_dir/css/properties/longhands/align_content.h",
- "$blink_core_output_dir/css/properties/longhands/align_items.h",
- "$blink_core_output_dir/css/properties/longhands/alignment_baseline.h",
- "$blink_core_output_dir/css/properties/longhands/align_self.h",
- "$blink_core_output_dir/css/properties/longhands/all.h",
- "$blink_core_output_dir/css/properties/longhands/animation_delay.h",
- "$blink_core_output_dir/css/properties/longhands/animation_direction.h",
- "$blink_core_output_dir/css/properties/longhands/animation_duration.h",
- "$blink_core_output_dir/css/properties/longhands/animation_fill_mode.h",
- "$blink_core_output_dir/css/properties/longhands/animation_iteration_count.h",
- "$blink_core_output_dir/css/properties/longhands/animation_name.h",
- "$blink_core_output_dir/css/properties/longhands/animation_play_state.h",
- "$blink_core_output_dir/css/properties/longhands/animation_timing_function.h",
- "$blink_core_output_dir/css/properties/longhands/backdrop_filter.h",
- "$blink_core_output_dir/css/properties/longhands/backface_visibility.h",
- "$blink_core_output_dir/css/properties/longhands/background_attachment.h",
- "$blink_core_output_dir/css/properties/longhands/background_attachment.cc",
- "$blink_core_output_dir/css/properties/longhands/background_blend_mode.h",
- "$blink_core_output_dir/css/properties/longhands/background_blend_mode.cc",
- "$blink_core_output_dir/css/properties/longhands/background_clip.h",
- "$blink_core_output_dir/css/properties/longhands/background_clip.cc",
- "$blink_core_output_dir/css/properties/longhands/background_color.h",
- "$blink_core_output_dir/css/properties/longhands/background_color.cc",
- "$blink_core_output_dir/css/properties/longhands/background_image.h",
- "$blink_core_output_dir/css/properties/longhands/background_image.cc",
- "$blink_core_output_dir/css/properties/longhands/background_origin.h",
- "$blink_core_output_dir/css/properties/longhands/background_origin.cc",
- "$blink_core_output_dir/css/properties/longhands/background_position_x.h",
- "$blink_core_output_dir/css/properties/longhands/background_position_x.cc",
- "$blink_core_output_dir/css/properties/longhands/background_position_y.h",
- "$blink_core_output_dir/css/properties/longhands/background_position_y.cc",
- "$blink_core_output_dir/css/properties/longhands/background_repeat_x.h",
- "$blink_core_output_dir/css/properties/longhands/background_repeat_x.cc",
- "$blink_core_output_dir/css/properties/longhands/background_repeat_y.h",
- "$blink_core_output_dir/css/properties/longhands/background_repeat_y.cc",
- "$blink_core_output_dir/css/properties/longhands/background_size.h",
- "$blink_core_output_dir/css/properties/longhands/background_size.cc",
- "$blink_core_output_dir/css/properties/longhands/baseline_shift.h",
- "$blink_core_output_dir/css/properties/longhands/block_size.h",
- "$blink_core_output_dir/css/properties/longhands/border_block_end_color.h",
- "$blink_core_output_dir/css/properties/longhands/border_block_end_style.h",
- "$blink_core_output_dir/css/properties/longhands/border_block_end_width.h",
- "$blink_core_output_dir/css/properties/longhands/border_block_start_color.h",
- "$blink_core_output_dir/css/properties/longhands/border_block_start_style.h",
- "$blink_core_output_dir/css/properties/longhands/border_block_start_width.h",
- "$blink_core_output_dir/css/properties/longhands/border_bottom_color.h",
- "$blink_core_output_dir/css/properties/longhands/border_bottom_color.cc",
- "$blink_core_output_dir/css/properties/longhands/border_bottom_left_radius.h",
- "$blink_core_output_dir/css/properties/longhands/border_bottom_right_radius.h",
- "$blink_core_output_dir/css/properties/longhands/border_bottom_style.h",
- "$blink_core_output_dir/css/properties/longhands/border_bottom_width.h",
- "$blink_core_output_dir/css/properties/longhands/border_collapse.h",
- "$blink_core_output_dir/css/properties/longhands/border_image_outset.h",
- "$blink_core_output_dir/css/properties/longhands/border_image_repeat.h",
- "$blink_core_output_dir/css/properties/longhands/border_image_slice.h",
- "$blink_core_output_dir/css/properties/longhands/border_image_source.h",
- "$blink_core_output_dir/css/properties/longhands/border_image_width.h",
- "$blink_core_output_dir/css/properties/longhands/border_inline_end_color.h",
- "$blink_core_output_dir/css/properties/longhands/border_inline_end_style.h",
- "$blink_core_output_dir/css/properties/longhands/border_inline_end_width.h",
- "$blink_core_output_dir/css/properties/longhands/border_inline_start_color.h",
- "$blink_core_output_dir/css/properties/longhands/border_inline_start_style.h",
- "$blink_core_output_dir/css/properties/longhands/border_inline_start_width.h",
- "$blink_core_output_dir/css/properties/longhands/border_left_color.h",
- "$blink_core_output_dir/css/properties/longhands/border_left_color.cc",
- "$blink_core_output_dir/css/properties/longhands/border_left_style.h",
- "$blink_core_output_dir/css/properties/longhands/border_left_width.h",
- "$blink_core_output_dir/css/properties/longhands/border_right_color.h",
- "$blink_core_output_dir/css/properties/longhands/border_right_color.cc",
- "$blink_core_output_dir/css/properties/longhands/border_right_style.h",
- "$blink_core_output_dir/css/properties/longhands/border_right_width.h",
- "$blink_core_output_dir/css/properties/longhands/border_top_color.h",
- "$blink_core_output_dir/css/properties/longhands/border_top_color.cc",
- "$blink_core_output_dir/css/properties/longhands/border_top_left_radius.h",
- "$blink_core_output_dir/css/properties/longhands/border_top_right_radius.h",
- "$blink_core_output_dir/css/properties/longhands/border_top_style.h",
- "$blink_core_output_dir/css/properties/longhands/border_top_width.h",
- "$blink_core_output_dir/css/properties/longhands/bottom.h",
- "$blink_core_output_dir/css/properties/longhands/box_shadow.h",
- "$blink_core_output_dir/css/properties/longhands/box_sizing.h",
- "$blink_core_output_dir/css/properties/longhands/break_after.h",
- "$blink_core_output_dir/css/properties/longhands/break_before.h",
- "$blink_core_output_dir/css/properties/longhands/break_inside.h",
- "$blink_core_output_dir/css/properties/longhands/buffered_rendering.h",
- "$blink_core_output_dir/css/properties/longhands/caption_side.h",
- "$blink_core_output_dir/css/properties/longhands/caret_color.h",
- "$blink_core_output_dir/css/properties/longhands/clear.h",
- "$blink_core_output_dir/css/properties/longhands/clip.h",
- "$blink_core_output_dir/css/properties/longhands/clip_path.h",
- "$blink_core_output_dir/css/properties/longhands/clip_rule.h",
- "$blink_core_output_dir/css/properties/longhands/color.h",
- "$blink_core_output_dir/css/properties/longhands/color_interpolation.h",
- "$blink_core_output_dir/css/properties/longhands/color_interpolation_filters.h",
- "$blink_core_output_dir/css/properties/longhands/color_rendering.h",
- "$blink_core_output_dir/css/properties/longhands/column_count.h",
- "$blink_core_output_dir/css/properties/longhands/column_fill.h",
- "$blink_core_output_dir/css/properties/longhands/column_gap.h",
- "$blink_core_output_dir/css/properties/longhands/column_rule_color.h",
- "$blink_core_output_dir/css/properties/longhands/column_rule_color.cc",
- "$blink_core_output_dir/css/properties/longhands/column_rule_style.h",
- "$blink_core_output_dir/css/properties/longhands/column_rule_width.h",
- "$blink_core_output_dir/css/properties/longhands/column_span.h",
- "$blink_core_output_dir/css/properties/longhands/column_width.h",
- "$blink_core_output_dir/css/properties/longhands/contain.h",
- "$blink_core_output_dir/css/properties/longhands/content.h",
- "$blink_core_output_dir/css/properties/longhands/counter_increment.h",
- "$blink_core_output_dir/css/properties/longhands/counter_increment.cc",
- "$blink_core_output_dir/css/properties/longhands/counter_reset.h",
- "$blink_core_output_dir/css/properties/longhands/counter_reset.cc",
- "$blink_core_output_dir/css/properties/longhands/cursor.h",
- "$blink_core_output_dir/css/properties/longhands/cx.h",
- "$blink_core_output_dir/css/properties/longhands/cy.h",
- "$blink_core_output_dir/css/properties/longhands/d.h",
- "$blink_core_output_dir/css/properties/longhands/direction.h",
- "$blink_core_output_dir/css/properties/longhands/display.h",
- "$blink_core_output_dir/css/properties/longhands/dominant_baseline.h",
- "$blink_core_output_dir/css/properties/longhands/empty_cells.h",
- "$blink_core_output_dir/css/properties/longhands/epub_caption_side.h",
- "$blink_core_output_dir/css/properties/longhands/epub_text_combine.h",
- "$blink_core_output_dir/css/properties/longhands/epub_text_emphasis_color.h",
- "$blink_core_output_dir/css/properties/longhands/epub_text_emphasis_style.h",
- "$blink_core_output_dir/css/properties/longhands/epub_text_orientation.h",
- "$blink_core_output_dir/css/properties/longhands/epub_text_transform.h",
- "$blink_core_output_dir/css/properties/longhands/epub_word_break.h",
- "$blink_core_output_dir/css/properties/longhands/epub_writing_mode.h",
- "$blink_core_output_dir/css/properties/longhands/fill.h",
- "$blink_core_output_dir/css/properties/longhands/fill_opacity.h",
- "$blink_core_output_dir/css/properties/longhands/fill_rule.h",
- "$blink_core_output_dir/css/properties/longhands/filter.h",
- "$blink_core_output_dir/css/properties/longhands/flex_basis.h",
- "$blink_core_output_dir/css/properties/longhands/flex_direction.h",
- "$blink_core_output_dir/css/properties/longhands/flex_grow.h",
- "$blink_core_output_dir/css/properties/longhands/flex_shrink.h",
- "$blink_core_output_dir/css/properties/longhands/flex_wrap.h",
- "$blink_core_output_dir/css/properties/longhands/float.h",
- "$blink_core_output_dir/css/properties/longhands/flood_color.h",
- "$blink_core_output_dir/css/properties/longhands/flood_opacity.h",
- "$blink_core_output_dir/css/properties/longhands/font_display.h",
- "$blink_core_output_dir/css/properties/longhands/font_family.h",
- "$blink_core_output_dir/css/properties/longhands/font_feature_settings.h",
- "$blink_core_output_dir/css/properties/longhands/font_kerning.h",
- "$blink_core_output_dir/css/properties/longhands/font_size.h",
- "$blink_core_output_dir/css/properties/longhands/font_size_adjust.h",
- "$blink_core_output_dir/css/properties/longhands/font_stretch.h",
- "$blink_core_output_dir/css/properties/longhands/font_style.h",
- "$blink_core_output_dir/css/properties/longhands/font_variant_caps.h",
- "$blink_core_output_dir/css/properties/longhands/font_variant_east_asian.h",
- "$blink_core_output_dir/css/properties/longhands/font_variant_ligatures.h",
- "$blink_core_output_dir/css/properties/longhands/font_variant_numeric.h",
- "$blink_core_output_dir/css/properties/longhands/font_variation_settings.h",
- "$blink_core_output_dir/css/properties/longhands/font_weight.h",
- "$blink_core_output_dir/css/properties/longhands/grid_auto_columns.h",
- "$blink_core_output_dir/css/properties/longhands/grid_auto_flow.h",
- "$blink_core_output_dir/css/properties/longhands/grid_auto_rows.h",
- "$blink_core_output_dir/css/properties/longhands/grid_column_end.h",
- "$blink_core_output_dir/css/properties/longhands/grid_column_start.h",
- "$blink_core_output_dir/css/properties/longhands/grid_row_end.h",
- "$blink_core_output_dir/css/properties/longhands/grid_row_start.h",
- "$blink_core_output_dir/css/properties/longhands/grid_template_areas.h",
- "$blink_core_output_dir/css/properties/longhands/grid_template_columns.h",
- "$blink_core_output_dir/css/properties/longhands/grid_template_columns.cc",
- "$blink_core_output_dir/css/properties/longhands/grid_template_rows.h",
- "$blink_core_output_dir/css/properties/longhands/grid_template_rows.cc",
- "$blink_core_output_dir/css/properties/longhands/height.h",
- "$blink_core_output_dir/css/properties/longhands/hyphens.h",
- "$blink_core_output_dir/css/properties/longhands/image_orientation.h",
- "$blink_core_output_dir/css/properties/longhands/image_rendering.h",
- "$blink_core_output_dir/css/properties/longhands/inline_size.h",
- "$blink_core_output_dir/css/properties/longhands/inset_block_end.h",
- "$blink_core_output_dir/css/properties/longhands/inset_block_start.h",
- "$blink_core_output_dir/css/properties/longhands/inset_inline_end.h",
- "$blink_core_output_dir/css/properties/longhands/inset_inline_start.h",
- "$blink_core_output_dir/css/properties/longhands/isolation.h",
- "$blink_core_output_dir/css/properties/longhands/justify_content.h",
- "$blink_core_output_dir/css/properties/longhands/justify_items.h",
- "$blink_core_output_dir/css/properties/longhands/justify_self.h",
- "$blink_core_output_dir/css/properties/longhands/left.h",
- "$blink_core_output_dir/css/properties/longhands/letter_spacing.h",
- "$blink_core_output_dir/css/properties/longhands/lighting_color.h",
- "$blink_core_output_dir/css/properties/longhands/line_break.h",
- "$blink_core_output_dir/css/properties/longhands/line_height.h",
- "$blink_core_output_dir/css/properties/longhands/line_height_step.h",
- "$blink_core_output_dir/css/properties/longhands/list_style_image.h",
- "$blink_core_output_dir/css/properties/longhands/list_style_position.h",
- "$blink_core_output_dir/css/properties/longhands/list_style_type.h",
- "$blink_core_output_dir/css/properties/longhands/margin_block_start.h",
- "$blink_core_output_dir/css/properties/longhands/margin_block_end.h",
- "$blink_core_output_dir/css/properties/longhands/margin_bottom.h",
- "$blink_core_output_dir/css/properties/longhands/margin_inline_start.h",
- "$blink_core_output_dir/css/properties/longhands/margin_inline_end.h",
- "$blink_core_output_dir/css/properties/longhands/margin_left.h",
- "$blink_core_output_dir/css/properties/longhands/margin_right.h",
- "$blink_core_output_dir/css/properties/longhands/margin_top.h",
- "$blink_core_output_dir/css/properties/longhands/marker_end.h",
- "$blink_core_output_dir/css/properties/longhands/marker_mid.h",
- "$blink_core_output_dir/css/properties/longhands/marker_start.h",
- "$blink_core_output_dir/css/properties/longhands/mask.h",
- "$blink_core_output_dir/css/properties/longhands/mask_source_type.h",
- "$blink_core_output_dir/css/properties/longhands/mask_source_type.cc",
- "$blink_core_output_dir/css/properties/longhands/mask_type.h",
- "$blink_core_output_dir/css/properties/longhands/max_block_size.h",
- "$blink_core_output_dir/css/properties/longhands/max_height.h",
- "$blink_core_output_dir/css/properties/longhands/max_inline_size.h",
- "$blink_core_output_dir/css/properties/longhands/max_width.h",
- "$blink_core_output_dir/css/properties/longhands/max_zoom.h",
- "$blink_core_output_dir/css/properties/longhands/min_block_size.h",
- "$blink_core_output_dir/css/properties/longhands/min_height.h",
- "$blink_core_output_dir/css/properties/longhands/min_inline_size.h",
- "$blink_core_output_dir/css/properties/longhands/min_width.h",
- "$blink_core_output_dir/css/properties/longhands/min_zoom.h",
- "$blink_core_output_dir/css/properties/longhands/mix_blend_mode.h",
- "$blink_core_output_dir/css/properties/longhands/object_fit.h",
- "$blink_core_output_dir/css/properties/longhands/object_position.h",
- "$blink_core_output_dir/css/properties/longhands/offset_anchor.h",
- "$blink_core_output_dir/css/properties/longhands/offset_distance.h",
- "$blink_core_output_dir/css/properties/longhands/offset_path.h",
- "$blink_core_output_dir/css/properties/longhands/offset_position.h",
- "$blink_core_output_dir/css/properties/longhands/offset_rotate.h",
- "$blink_core_output_dir/css/properties/longhands/opacity.h",
- "$blink_core_output_dir/css/properties/longhands/order.h",
- "$blink_core_output_dir/css/properties/longhands/orientation.h",
- "$blink_core_output_dir/css/properties/longhands/orphans.h",
- "$blink_core_output_dir/css/properties/longhands/outline_color.h",
- "$blink_core_output_dir/css/properties/longhands/outline_color.cc",
- "$blink_core_output_dir/css/properties/longhands/outline_offset.h",
- "$blink_core_output_dir/css/properties/longhands/outline_style.h",
- "$blink_core_output_dir/css/properties/longhands/outline_width.h",
- "$blink_core_output_dir/css/properties/longhands/overflow_anchor.h",
- "$blink_core_output_dir/css/properties/longhands/overflow_wrap.h",
- "$blink_core_output_dir/css/properties/longhands/overflow_x.h",
- "$blink_core_output_dir/css/properties/longhands/overflow_y.h",
- "$blink_core_output_dir/css/properties/longhands/overscroll_behavior_x.h",
- "$blink_core_output_dir/css/properties/longhands/overscroll_behavior_y.h",
- "$blink_core_output_dir/css/properties/longhands/padding_block_start.h",
- "$blink_core_output_dir/css/properties/longhands/padding_block_end.h",
- "$blink_core_output_dir/css/properties/longhands/padding_bottom.h",
- "$blink_core_output_dir/css/properties/longhands/padding_inline_start.h",
- "$blink_core_output_dir/css/properties/longhands/padding_inline_end.h",
- "$blink_core_output_dir/css/properties/longhands/padding_left.h",
- "$blink_core_output_dir/css/properties/longhands/padding_right.h",
- "$blink_core_output_dir/css/properties/longhands/padding_top.h",
- "$blink_core_output_dir/css/properties/longhands/page.h",
- "$blink_core_output_dir/css/properties/longhands/paint_order.h",
- "$blink_core_output_dir/css/properties/longhands/perspective.h",
- "$blink_core_output_dir/css/properties/longhands/perspective_origin.h",
- "$blink_core_output_dir/css/properties/longhands/pointer_events.h",
- "$blink_core_output_dir/css/properties/longhands/position.h",
- "$blink_core_output_dir/css/properties/longhands/quotes.h",
- "$blink_core_output_dir/css/properties/longhands/r.h",
- "$blink_core_output_dir/css/properties/longhands/resize.h",
- "$blink_core_output_dir/css/properties/longhands/right.h",
- "$blink_core_output_dir/css/properties/longhands/rotate.h",
- "$blink_core_output_dir/css/properties/longhands/row_gap.h",
- "$blink_core_output_dir/css/properties/longhands/rx.h",
- "$blink_core_output_dir/css/properties/longhands/ry.h",
- "$blink_core_output_dir/css/properties/longhands/scale.h",
- "$blink_core_output_dir/css/properties/longhands/scroll_behavior.h",
- "$blink_core_output_dir/css/properties/longhands/scroll_customization.h",
- "$blink_core_output_dir/css/properties/longhands/scroll_margin_block_end.h",
- "$blink_core_output_dir/css/properties/longhands/scroll_margin_block_start.h",
- "$blink_core_output_dir/css/properties/longhands/scroll_margin_bottom.h",
- "$blink_core_output_dir/css/properties/longhands/scroll_margin_inline_end.h",
- "$blink_core_output_dir/css/properties/longhands/scroll_margin_inline_start.h",
- "$blink_core_output_dir/css/properties/longhands/scroll_margin_left.h",
- "$blink_core_output_dir/css/properties/longhands/scroll_margin_right.h",
- "$blink_core_output_dir/css/properties/longhands/scroll_margin_top.h",
- "$blink_core_output_dir/css/properties/longhands/scroll_padding_block_end.h",
- "$blink_core_output_dir/css/properties/longhands/scroll_padding_block_start.h",
- "$blink_core_output_dir/css/properties/longhands/scroll_padding_bottom.h",
- "$blink_core_output_dir/css/properties/longhands/scroll_padding_inline_end.h",
- "$blink_core_output_dir/css/properties/longhands/scroll_padding_inline_start.h",
- "$blink_core_output_dir/css/properties/longhands/scroll_padding_left.h",
- "$blink_core_output_dir/css/properties/longhands/scroll_padding_right.h",
- "$blink_core_output_dir/css/properties/longhands/scroll_padding_top.h",
- "$blink_core_output_dir/css/properties/longhands/scroll_snap_align.h",
- "$blink_core_output_dir/css/properties/longhands/scroll_snap_stop.h",
- "$blink_core_output_dir/css/properties/longhands/scroll_snap_type.h",
- "$blink_core_output_dir/css/properties/longhands/shape_image_threshold.h",
- "$blink_core_output_dir/css/properties/longhands/shape_margin.h",
- "$blink_core_output_dir/css/properties/longhands/shape_outside.h",
- "$blink_core_output_dir/css/properties/longhands/shape_rendering.h",
- "$blink_core_output_dir/css/properties/longhands/size.h",
- "$blink_core_output_dir/css/properties/longhands/speak.h",
- "$blink_core_output_dir/css/properties/longhands/src.h",
- "$blink_core_output_dir/css/properties/longhands/stop_color.h",
- "$blink_core_output_dir/css/properties/longhands/stop_opacity.h",
- "$blink_core_output_dir/css/properties/longhands/stroke.h",
- "$blink_core_output_dir/css/properties/longhands/stroke_dasharray.h",
- "$blink_core_output_dir/css/properties/longhands/stroke_dashoffset.h",
- "$blink_core_output_dir/css/properties/longhands/stroke_linecap.h",
- "$blink_core_output_dir/css/properties/longhands/stroke_linejoin.h",
- "$blink_core_output_dir/css/properties/longhands/stroke_miterlimit.h",
- "$blink_core_output_dir/css/properties/longhands/stroke_opacity.h",
- "$blink_core_output_dir/css/properties/longhands/stroke_width.h",
- "$blink_core_output_dir/css/properties/longhands/table_layout.h",
- "$blink_core_output_dir/css/properties/longhands/tab_size.h",
- "$blink_core_output_dir/css/properties/longhands/text_align.h",
- "$blink_core_output_dir/css/properties/longhands/text_align_last.h",
- "$blink_core_output_dir/css/properties/longhands/text_anchor.h",
- "$blink_core_output_dir/css/properties/longhands/text_combine_upright.h",
- "$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",
- "$blink_core_output_dir/css/properties/longhands/text_orientation.h",
- "$blink_core_output_dir/css/properties/longhands/text_overflow.h",
- "$blink_core_output_dir/css/properties/longhands/text_rendering.h",
- "$blink_core_output_dir/css/properties/longhands/text_shadow.h",
- "$blink_core_output_dir/css/properties/longhands/text_size_adjust.h",
- "$blink_core_output_dir/css/properties/longhands/text_transform.h",
- "$blink_core_output_dir/css/properties/longhands/text_underline_position.h",
- "$blink_core_output_dir/css/properties/longhands/top.h",
- "$blink_core_output_dir/css/properties/longhands/touch_action.h",
- "$blink_core_output_dir/css/properties/longhands/transform.h",
- "$blink_core_output_dir/css/properties/longhands/transform_box.h",
- "$blink_core_output_dir/css/properties/longhands/transform_origin.h",
- "$blink_core_output_dir/css/properties/longhands/transform_style.h",
- "$blink_core_output_dir/css/properties/longhands/transition_delay.h",
- "$blink_core_output_dir/css/properties/longhands/transition_duration.h",
- "$blink_core_output_dir/css/properties/longhands/transition_property.h",
- "$blink_core_output_dir/css/properties/longhands/transition_timing_function.h",
- "$blink_core_output_dir/css/properties/longhands/translate.h",
- "$blink_core_output_dir/css/properties/longhands/unicode_bidi.h",
- "$blink_core_output_dir/css/properties/longhands/unicode_range.h",
- "$blink_core_output_dir/css/properties/longhands/user_select.h",
- "$blink_core_output_dir/css/properties/longhands/user_zoom.h",
- "$blink_core_output_dir/css/properties/longhands/vector_effect.h",
- "$blink_core_output_dir/css/properties/longhands/vertical_align.h",
- "$blink_core_output_dir/css/properties/longhands/visibility.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_align_content.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_align_items.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_align_self.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_animation_delay.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_animation_direction.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_animation_duration.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_animation_fill_mode.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_animation_iteration_count.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_animation_name.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_animation_play_state.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_animation_timing_function.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_appearance.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_app_region.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_backface_visibility.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_background_clip.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_background_origin.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_background_size.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_border_after_color.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_border_after_style.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_border_after_width.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_border_before_color.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_border_before_style.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_border_before_width.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_border_bottom_left_radius.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_border_bottom_right_radius.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_border_end_color.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_border_end_style.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_border_end_width.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_border_horizontal_spacing.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_border_image.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_border_start_color.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_border_start_style.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_border_start_width.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_border_top_left_radius.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_border_top_right_radius.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_border_vertical_spacing.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_box_align.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_box_decoration_break.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_box_direction.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_box_flex.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_box_ordinal_group.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_box_orient.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_box_pack.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_box_reflect.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_box_shadow.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_box_sizing.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_clip_path.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_column_count.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_column_gap.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_column_rule_color.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_column_rule_style.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_column_rule_width.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_column_span.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_column_width.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_filter.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_flex_basis.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_flex_direction.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_flex_grow.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_flex_shrink.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_flex_wrap.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_font_feature_settings.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_font_size_delta.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_font_smoothing.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_highlight.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_hyphenate_character.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_justify_content.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_line_break.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_line_clamp.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_locale.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_logical_height.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_logical_width.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_margin_after.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_margin_after_collapse.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_margin_before.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_margin_before_collapse.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_margin_bottom_collapse.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_margin_end.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_margin_start.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_margin_top_collapse.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_mask_box_image_outset.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_mask_box_image_repeat.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_mask_box_image_slice.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_mask_box_image_source.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_mask_box_image_width.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_mask_clip.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_mask_clip.cc",
- "$blink_core_output_dir/css/properties/longhands/webkit_mask_composite.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_mask_composite.cc",
- "$blink_core_output_dir/css/properties/longhands/webkit_mask_image.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_mask_image.cc",
- "$blink_core_output_dir/css/properties/longhands/webkit_mask_origin.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_mask_origin.cc",
- "$blink_core_output_dir/css/properties/longhands/webkit_mask_position_x.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_mask_position_x.cc",
- "$blink_core_output_dir/css/properties/longhands/webkit_mask_position_y.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_mask_position_y.cc",
- "$blink_core_output_dir/css/properties/longhands/webkit_mask_repeat_x.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_mask_repeat_x.cc",
- "$blink_core_output_dir/css/properties/longhands/webkit_mask_repeat_y.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_mask_repeat_y.cc",
- "$blink_core_output_dir/css/properties/longhands/webkit_mask_size.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_mask_size.cc",
- "$blink_core_output_dir/css/properties/longhands/webkit_max_logical_height.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_max_logical_width.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_min_logical_height.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_min_logical_width.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_opacity.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_order.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_padding_after.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_padding_before.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_padding_end.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_padding_start.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_perspective.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_perspective_origin.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_perspective_origin_x.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_perspective_origin_y.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_print_color_adjust.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_rtl_ordering.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_ruby_position.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_shape_image_threshold.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_shape_margin.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_shape_outside.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_tap_highlight_color.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_text_combine.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_text_decorations_in_effect.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_text_emphasis_color.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_text_emphasis_color.cc",
- "$blink_core_output_dir/css/properties/longhands/webkit_text_emphasis_position.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_text_emphasis_style.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_text_fill_color.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_text_fill_color.cc",
- "$blink_core_output_dir/css/properties/longhands/webkit_text_orientation.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_text_security.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_text_size_adjust.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_text_stroke_color.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_text_stroke_color.cc",
- "$blink_core_output_dir/css/properties/longhands/webkit_text_stroke_width.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_transform.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_transform_origin.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_transform_origin_x.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_transform_origin_y.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_transform_origin_z.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_transform_style.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_transition_delay.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_transition_duration.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_transition_property.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_transition_timing_function.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_user_drag.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_user_modify.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_user_select.h",
- "$blink_core_output_dir/css/properties/longhands/webkit_writing_mode.h",
- "$blink_core_output_dir/css/properties/longhands/white_space.h",
- "$blink_core_output_dir/css/properties/longhands/widows.h",
- "$blink_core_output_dir/css/properties/longhands/width.h",
- "$blink_core_output_dir/css/properties/longhands/will_change.h",
- "$blink_core_output_dir/css/properties/longhands/word_break.h",
- "$blink_core_output_dir/css/properties/longhands/word_spacing.h",
- "$blink_core_output_dir/css/properties/longhands/word_wrap.h",
- "$blink_core_output_dir/css/properties/longhands/writing_mode.h",
- "$blink_core_output_dir/css/properties/longhands/x.h",
- "$blink_core_output_dir/css/properties/longhands/y.h",
- "$blink_core_output_dir/css/properties/longhands/z_index.h",
- "$blink_core_output_dir/css/properties/longhands/zoom.h",
- ]
-}
-
-# FIXME: Need a better way to specify generated output files
-css_properties("make_core_generated_css_shorthand_property_classes") {
- script =
- "../build/scripts/core/css/properties/make_css_property_subclasses.py"
- in_files = [ "css/properties/css_property_methods.json5" ]
- other_inputs = [
- "css/css_properties.json5",
- "../build/scripts/core/css/properties/templates/css_property_subclass.h.tmpl",
- ]
- outputs = [
- "$blink_core_output_dir/css/properties/shorthands/animation.h",
- "$blink_core_output_dir/css/properties/shorthands/background.h",
- "$blink_core_output_dir/css/properties/shorthands/background_position.h",
- "$blink_core_output_dir/css/properties/shorthands/background_repeat.h",
- "$blink_core_output_dir/css/properties/shorthands/border.h",
- "$blink_core_output_dir/css/properties/shorthands/border_block.h",
- "$blink_core_output_dir/css/properties/shorthands/border_block_color.h",
- "$blink_core_output_dir/css/properties/shorthands/border_block_end.h",
- "$blink_core_output_dir/css/properties/shorthands/border_block_start.h",
- "$blink_core_output_dir/css/properties/shorthands/border_block_style.h",
- "$blink_core_output_dir/css/properties/shorthands/border_block_width.h",
- "$blink_core_output_dir/css/properties/shorthands/border_bottom.h",
- "$blink_core_output_dir/css/properties/shorthands/border_color.h",
- "$blink_core_output_dir/css/properties/shorthands/border_image.h",
- "$blink_core_output_dir/css/properties/shorthands/border_inline.h",
- "$blink_core_output_dir/css/properties/shorthands/border_inline_color.h",
- "$blink_core_output_dir/css/properties/shorthands/border_inline_end.h",
- "$blink_core_output_dir/css/properties/shorthands/border_inline_start.h",
- "$blink_core_output_dir/css/properties/shorthands/border_inline_style.h",
- "$blink_core_output_dir/css/properties/shorthands/border_inline_width.h",
- "$blink_core_output_dir/css/properties/shorthands/border_left.h",
- "$blink_core_output_dir/css/properties/shorthands/border_radius.h",
- "$blink_core_output_dir/css/properties/shorthands/border_right.h",
- "$blink_core_output_dir/css/properties/shorthands/border_spacing.h",
- "$blink_core_output_dir/css/properties/shorthands/border_style.h",
- "$blink_core_output_dir/css/properties/shorthands/border_top.h",
- "$blink_core_output_dir/css/properties/shorthands/border_width.h",
- "$blink_core_output_dir/css/properties/shorthands/column_rule.h",
- "$blink_core_output_dir/css/properties/shorthands/columns.h",
- "$blink_core_output_dir/css/properties/shorthands/epub_text_emphasis.h",
- "$blink_core_output_dir/css/properties/shorthands/flex.h",
- "$blink_core_output_dir/css/properties/shorthands/flex_flow.h",
- "$blink_core_output_dir/css/properties/shorthands/font.h",
- "$blink_core_output_dir/css/properties/shorthands/font_variant.h",
- "$blink_core_output_dir/css/properties/shorthands/gap.h",
- "$blink_core_output_dir/css/properties/shorthands/grid.h",
- "$blink_core_output_dir/css/properties/shorthands/grid_area.h",
- "$blink_core_output_dir/css/properties/shorthands/grid_column.h",
- "$blink_core_output_dir/css/properties/shorthands/grid_column_gap.h",
- "$blink_core_output_dir/css/properties/shorthands/grid_row_gap.h",
- "$blink_core_output_dir/css/properties/shorthands/grid_gap.h",
- "$blink_core_output_dir/css/properties/shorthands/grid_row.h",
- "$blink_core_output_dir/css/properties/shorthands/grid_template.h",
- "$blink_core_output_dir/css/properties/shorthands/inset.h",
- "$blink_core_output_dir/css/properties/shorthands/inset_block.h",
- "$blink_core_output_dir/css/properties/shorthands/inset_inline.h",
- "$blink_core_output_dir/css/properties/shorthands/list_style.h",
- "$blink_core_output_dir/css/properties/shorthands/margin.h",
- "$blink_core_output_dir/css/properties/shorthands/margin_block.h",
- "$blink_core_output_dir/css/properties/shorthands/margin_inline.h",
- "$blink_core_output_dir/css/properties/shorthands/marker.h",
- "$blink_core_output_dir/css/properties/shorthands/offset.h",
- "$blink_core_output_dir/css/properties/shorthands/outline.h",
- "$blink_core_output_dir/css/properties/shorthands/overflow.h",
- "$blink_core_output_dir/css/properties/shorthands/overscroll_behavior.h",
- "$blink_core_output_dir/css/properties/shorthands/padding.h",
- "$blink_core_output_dir/css/properties/shorthands/padding_block.h",
- "$blink_core_output_dir/css/properties/shorthands/padding_inline.h",
- "$blink_core_output_dir/css/properties/shorthands/page_break_after.h",
- "$blink_core_output_dir/css/properties/shorthands/page_break_before.h",
- "$blink_core_output_dir/css/properties/shorthands/page_break_inside.h",
- "$blink_core_output_dir/css/properties/shorthands/place_content.h",
- "$blink_core_output_dir/css/properties/shorthands/place_items.h",
- "$blink_core_output_dir/css/properties/shorthands/place_self.h",
- "$blink_core_output_dir/css/properties/shorthands/scroll_margin.h",
- "$blink_core_output_dir/css/properties/shorthands/scroll_margin_block.h",
- "$blink_core_output_dir/css/properties/shorthands/scroll_margin_inline.h",
- "$blink_core_output_dir/css/properties/shorthands/scroll_padding.h",
- "$blink_core_output_dir/css/properties/shorthands/scroll_padding_block.h",
- "$blink_core_output_dir/css/properties/shorthands/scroll_padding_inline.h",
- "$blink_core_output_dir/css/properties/shorthands/text_decoration.h",
- "$blink_core_output_dir/css/properties/shorthands/transition.h",
- "$blink_core_output_dir/css/properties/shorthands/webkit_animation.h",
- "$blink_core_output_dir/css/properties/shorthands/webkit_border_after.h",
- "$blink_core_output_dir/css/properties/shorthands/webkit_border_before.h",
- "$blink_core_output_dir/css/properties/shorthands/webkit_border_end.h",
- "$blink_core_output_dir/css/properties/shorthands/webkit_border_radius.h",
- "$blink_core_output_dir/css/properties/shorthands/webkit_border_start.h",
- "$blink_core_output_dir/css/properties/shorthands/webkit_column_break_after.h",
- "$blink_core_output_dir/css/properties/shorthands/webkit_column_break_before.h",
- "$blink_core_output_dir/css/properties/shorthands/webkit_column_break_inside.h",
- "$blink_core_output_dir/css/properties/shorthands/webkit_column_rule.h",
- "$blink_core_output_dir/css/properties/shorthands/webkit_columns.h",
- "$blink_core_output_dir/css/properties/shorthands/webkit_flex.h",
- "$blink_core_output_dir/css/properties/shorthands/webkit_flex_flow.h",
- "$blink_core_output_dir/css/properties/shorthands/webkit_margin_collapse.h",
- "$blink_core_output_dir/css/properties/shorthands/webkit_mask.h",
- "$blink_core_output_dir/css/properties/shorthands/webkit_mask_box_image.h",
- "$blink_core_output_dir/css/properties/shorthands/webkit_mask_position.h",
- "$blink_core_output_dir/css/properties/shorthands/webkit_mask_repeat.h",
- "$blink_core_output_dir/css/properties/shorthands/webkit_text_emphasis.h",
- "$blink_core_output_dir/css/properties/shorthands/webkit_text_stroke.h",
- "$blink_core_output_dir/css/properties/shorthands/webkit_transition.h",
+ "$blink_core_output_dir/css/properties/longhands.cc",
+ "$blink_core_output_dir/css/properties/longhands.h",
+ "$blink_core_output_dir/css/properties/shorthands.cc",
+ "$blink_core_output_dir/css/properties/shorthands.h",
]
}
@@ -1433,12 +835,6 @@ blink_python_runner("make_core_generated_css_tokenizer_codepoints") {
"--output_dir",
"$rel_blink_core_gen_dir/css",
]
- if (is_mac && !use_system_xcode) {
- args += [
- "--developer_dir",
- hermetic_xcode_path,
- ]
- }
deps = make_core_generated_deps
}
@@ -1462,12 +858,6 @@ blink_python_runner("make_core_generated_css_primitive_value_unit_trie") {
"--output_dir",
"$rel_blink_core_gen_dir/css",
]
- if (is_mac && !use_system_xcode) {
- args += [
- "--developer_dir",
- hermetic_xcode_path,
- ]
- }
deps = make_core_generated_deps
}
@@ -1491,12 +881,6 @@ blink_python_runner("make_core_generated_feature_policy_helper") {
"--output_dir",
"$rel_blink_core_gen_dir/feature_policy",
]
- if (is_mac && !use_system_xcode) {
- args += [
- "--developer_dir",
- hermetic_xcode_path,
- ]
- }
}
blink_python_runner("make_core_generated_html_element_lookup_trie") {
@@ -1520,12 +904,6 @@ blink_python_runner("make_core_generated_html_element_lookup_trie") {
"--output_dir",
rel_blink_core_gen_dir,
]
- if (is_mac && !use_system_xcode) {
- args += [
- "--developer_dir",
- hermetic_xcode_path,
- ]
- }
deps = make_core_generated_deps
}
@@ -1547,12 +925,6 @@ blink_python_runner("make_core_generated_origin_trials") {
"--output_dir",
"$rel_blink_core_gen_dir/origin_trials",
]
- if (is_mac && !use_system_xcode) {
- args += [
- "--developer_dir",
- hermetic_xcode_path,
- ]
- }
}
blink_python_runner("make_core_generated_web_origin_trials") {
script = "../build/scripts/make_web_origin_trials.py"
@@ -1571,12 +943,6 @@ blink_python_runner("make_core_generated_web_origin_trials") {
"--output_dir",
"$rel_blink_core_gen_dir/exported",
]
- if (is_mac && !use_system_xcode) {
- args += [
- "--developer_dir",
- hermetic_xcode_path,
- ]
- }
}
action_foreach("make_core_generated_bison") {
@@ -1593,9 +959,6 @@ action_foreach("make_core_generated_bison") {
rel_blink_core_gen_dir,
bison_exe,
]
- if (is_mac && !use_system_xcode) {
- args += [ hermetic_xcode_path ]
- }
deps = make_core_generated_deps
}
@@ -1609,10 +972,9 @@ 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_longhand_property_classes",
+ ":make_core_generated_css_subclasses",
":make_core_generated_css_property_names",
":make_core_generated_css_property_instances",
- ":make_core_generated_css_shorthand_property_classes",
":make_core_generated_css_value_id_mappings",
":make_core_generated_cssom_types",
":make_core_generated_enter_key_hint_names",
@@ -1735,6 +1097,7 @@ fuzzer_test("text_resource_decoder_fuzzer") {
jumbo_source_set("unit_tests") {
testonly = true
sources = [
+ "clipboard/clipboard_utilities_test.cc",
"content_capture/content_capture_test.cc",
"css/css_test_helpers.cc",
"css/css_test_helpers.h",
@@ -1784,13 +1147,15 @@ jumbo_source_set("unit_tests") {
"execution_context/context_lifecycle_state_observer_test.cc",
"exported/local_frame_client_impl_test.cc",
"exported/prerendering_test.cc",
- "exported/web_associated_url_loader_impl_test.cc",
"exported/web_document_subresource_filter_test.cc",
"exported/web_document_test.cc",
"exported/web_drag_data_test.cc",
"exported/web_element_test.cc",
+ "exported/web_frame_serializer_import_test.cc",
"exported/web_frame_serializer_sanitization_test.cc",
"exported/web_frame_serializer_test.cc",
+ "exported/web_frame_serializer_test_helper.cc",
+ "exported/web_frame_serializer_test_helper.h",
"exported/web_frame_test.cc",
"exported/web_layer_test.cc",
"exported/web_meaningful_layouts_test.cc",
@@ -1845,7 +1210,7 @@ jumbo_source_set("unit_tests") {
"frame/performance_monitor_test.cc",
"frame/root_frame_viewport_test.cc",
"frame/rotation_viewport_anchor_test.cc",
- "frame/use_counter_test.cc",
+ "frame/use_counter_helper_test.cc",
"frame/visual_viewport_test.cc",
"fullscreen/scoped_allow_fullscreen_test.cc",
"geometry/dom_matrix_test.cc",
@@ -1956,8 +1321,6 @@ jumbo_source_set("unit_tests") {
"layout/geometry/physical_rect_test.cc",
"layout/geometry/physical_size_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",
"layout/layout_box_test.cc",
@@ -1972,6 +1335,8 @@ jumbo_source_set("unit_tests") {
"layout/layout_object_test.cc",
"layout/layout_progress_test.cc",
"layout/layout_replaced_test.cc",
+ "layout/layout_shift_region_test.cc",
+ "layout/layout_shift_tracker_test.cc",
"layout/layout_table_cell_test.cc",
"layout/layout_table_col_test.cc",
"layout/layout_table_row_test.cc",
@@ -1991,6 +1356,7 @@ jumbo_source_set("unit_tests") {
"layout/multi_column_fragmentainer_group_test.cc",
"layout/ng/exclusions/ng_exclusion_space_test.cc",
"layout/ng/geometry/ng_box_strut_test.cc",
+ "layout/ng/geometry/ng_static_position_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",
@@ -2036,6 +1402,7 @@ jumbo_source_set("unit_tests") {
"loader/frame_fetch_context_test.cc",
"loader/frame_resource_fetcher_properties_test.cc",
"loader/idleness_detector_test.cc",
+ "loader/image_loader_test.cc",
"loader/interactive_detector_test.cc",
"loader/link_loader_test.cc",
"loader/long_task_detector_test.cc",
@@ -2058,6 +1425,8 @@ jumbo_source_set("unit_tests") {
"loader/resource_load_observer_for_frame_test.cc",
"loader/text_resource_decoder_builder_test.cc",
"loader/threadable_loader_test.cc",
+ "loader/threaded_icon_loader_test.cc",
+ "loader/web_associated_url_loader_impl_test.cc",
"messaging/blink_transferable_message_struct_traits_test.cc",
"origin_trials/origin_trial_context_test.cc",
"page/autoscroll_controller_test.cc",
@@ -2085,6 +1454,7 @@ jumbo_source_set("unit_tests") {
"page/touch_adjustment_test.cc",
"page/viewport_test.cc",
"page/window_features_test.cc",
+ "page/zoom_test.cc",
"paint/block_painter_test.cc",
"paint/box_paint_invalidator_test.cc",
"paint/box_painter_test.cc",
@@ -2104,6 +1474,7 @@ jumbo_source_set("unit_tests") {
"paint/image_element_timing_test.cc",
"paint/image_paint_timing_detector_test.cc",
"paint/inline_text_box_painter_test.cc",
+ "paint/largest_contentful_paint_calculator_test.cc",
"paint/link_highlight_impl_test.cc",
"paint/ng/ng_paint_fragment_test.cc",
"paint/ng/ng_paint_fragment_traversal_test.cc",
@@ -2122,6 +1493,7 @@ jumbo_source_set("unit_tests") {
"paint/paint_property_tree_builder_test.h",
"paint/paint_property_tree_printer_test.cc",
"paint/paint_property_tree_update_tests.cc",
+ "paint/paint_timing_test_helper.h",
"paint/pre_paint_tree_walk_test.cc",
"paint/table_painter_test.cc",
"paint/text_paint_timing_detector_test.cc",
@@ -2151,6 +1523,7 @@ jumbo_source_set("unit_tests") {
"streams/readable_stream_test.cc",
"streams/stream_promise_resolver_test.cc",
"streams/test_underlying_source.h",
+ "streams/transferable_streams_test.cc",
"streams/transform_stream_test.cc",
"streams/writable_stream_test.cc",
"style/border_value_test.cc",
@@ -2228,7 +1601,10 @@ jumbo_source_set("unit_tests") {
}
if (!is_mac) {
- sources += [ "scroll/scroll_animator_test.cc" ]
+ sources += [
+ "scroll/scroll_animator_test.cc",
+ "scroll/scrolling_test.cc",
+ ]
}
if (use_aura) {
diff --git a/chromium/third_party/blink/renderer/core/DEPS b/chromium/third_party/blink/renderer/core/DEPS
index 67311993341..30244fb66f2 100644
--- a/chromium/third_party/blink/renderer/core/DEPS
+++ b/chromium/third_party/blink/renderer/core/DEPS
@@ -2,6 +2,7 @@ include_rules = [
"+base/atomic_sequence_num.h",
"+base/barrier_closure.h",
"+base/bits.h",
+ "+base/callback_helpers.h",
"+base/files/file.h",
"+base/mac/foundation_util.h",
"+base/mac/mac_util.h",
@@ -13,6 +14,8 @@ include_rules = [
"+base/strings/stringprintf.h",
"+base/synchronization/waitable_event.h",
"+base/task/sequence_manager/task_time_observer.h",
+ "+base/test/bind_test_util.h",
+ "+base/test/simple_test_tick_clock.h",
"+base/time",
"+base/unguessable_token.h",
"+build/mac",
@@ -45,7 +48,6 @@ include_rules = [
"+cc/paint/paint_canvas.h",
"+cc/paint/paint_flags.h",
"+cc/paint/paint_worklet_input.h",
- "+cc/paint/text_holder.h",
"+cc/trees/paint_holding_commit_trigger.h",
"+gpu/config/gpu_feature_info.h",
"-inspector/v8",
@@ -73,7 +75,7 @@ include_rules = [
"+third_party/blink/renderer/core",
"-third_party/blink/renderer/modules",
"+third_party/skia/include",
- "+ui/base/ime/mojo/ime_types.mojom-shared.h",
+ "+ui/base/ime/mojo/ime_types.mojom-blink.h",
"+ui/gfx/geometry",
"+ui/gfx/skia_util.h",
"-web",
@@ -112,4 +114,7 @@ specific_include_rules = {
"find_task_controller.cc" : [
"+third_party/blink/renderer/core/frame/web_local_frame_impl.h",
],
+ "html_media_element_test.cc": [
+ "+base/test/gtest_util.h",
+ ],
}
diff --git a/chromium/third_party/blink/renderer/core/accessibility/apply_dark_mode.cc b/chromium/third_party/blink/renderer/core/accessibility/apply_dark_mode.cc
index 10e1a610e82..aa583d60764 100644
--- a/chromium/third_party/blink/renderer/core/accessibility/apply_dark_mode.cc
+++ b/chromium/third_party/blink/renderer/core/accessibility/apply_dark_mode.cc
@@ -21,7 +21,7 @@ bool HasLightBackground(const LayoutView& root) {
const ComputedStyle& style = root.StyleRef();
if (style.HasBackground()) {
Color color = style.VisitedDependentColor(GetCSSPropertyBackgroundColor());
- return IsLight(color, style.Opacity());
+ return IsLight(color);
}
// If we can't easily determine the background color, default to inverting the
@@ -53,7 +53,10 @@ DarkModeSettings BuildDarkModeSettings(const Settings& frame_settings,
dark_mode_settings.grayscale = frame_settings.GetDarkModeGrayscale();
dark_mode_settings.contrast = frame_settings.GetDarkModeContrast();
dark_mode_settings.image_policy = frame_settings.GetDarkModeImagePolicy();
- dark_mode_settings.text_policy = frame_settings.GetDarkModeTextPolicy();
+ dark_mode_settings.text_brightness_threshold =
+ frame_settings.GetDarkModeTextBrightnessThreshold();
+ dark_mode_settings.background_brightness_threshold =
+ frame_settings.GetDarkModeBackgroundBrightnessThreshold();
dark_mode_settings.image_grayscale_percent =
frame_settings.GetDarkModeImageGrayscale();
return dark_mode_settings;
diff --git a/chromium/third_party/blink/renderer/core/accessibility/apply_dark_mode_test.cc b/chromium/third_party/blink/renderer/core/accessibility/apply_dark_mode_test.cc
index 6c5f518902a..4749ee01acd 100644
--- a/chromium/third_party/blink/renderer/core/accessibility/apply_dark_mode_test.cc
+++ b/chromium/third_party/blink/renderer/core/accessibility/apply_dark_mode_test.cc
@@ -9,6 +9,7 @@
#include "third_party/blink/renderer/core/html/html_head_element.h"
#include "third_party/blink/renderer/core/style/computed_style.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"
namespace blink {
namespace {
@@ -29,9 +30,6 @@ TEST_F(ApplyDarkModeCheckTest, LightSolidBackgroundAlwaysFiltered) {
TEST_F(ApplyDarkModeCheckTest, DarkSolidBackgroundFilteredIfPolicyIsFilterAll) {
GetDocument().body()->SetInlineStyleProperty(CSSPropertyID::kBackgroundColor,
CSSValueID::kBlack);
- // TODO(https://crbug.com/925949): Set opacity the same way as the other CSS
- // properties.
- GetLayoutView().MutableStyle()->SetOpacity(0.9);
UpdateAllLifecyclePhasesForTest();
EXPECT_FALSE(ShouldApplyDarkModeFilterToPage(
@@ -40,20 +38,6 @@ TEST_F(ApplyDarkModeCheckTest, DarkSolidBackgroundFilteredIfPolicyIsFilterAll) {
GetLayoutView()));
}
-TEST_F(ApplyDarkModeCheckTest, DarkLowOpacityBackgroundAlwaysFiltered) {
- GetDocument().body()->SetInlineStyleProperty(CSSPropertyID::kBackgroundColor,
- CSSValueID::kBlack);
- // TODO(https://crbug.com/925949): Set opacity the same way as the other CSS
- // properties.
- GetLayoutView().MutableStyle()->SetOpacity(0.1);
- UpdateAllLifecyclePhasesForTest();
-
- EXPECT_TRUE(ShouldApplyDarkModeFilterToPage(
- DarkModePagePolicy::kFilterByBackground, GetLayoutView()));
- EXPECT_TRUE(ShouldApplyDarkModeFilterToPage(DarkModePagePolicy::kFilterAll,
- GetLayoutView()));
-}
-
TEST_F(ApplyDarkModeCheckTest, DarkTransparentBackgroundAlwaysFiltered) {
GetDocument().body()->SetInlineStyleProperty(CSSPropertyID::kBackgroundColor,
CSSValueID::kTransparent);
@@ -77,8 +61,8 @@ TEST_F(ApplyDarkModeCheckTest, BackgroundColorNotDefinedAlwaysFiltered) {
}
TEST_F(ApplyDarkModeCheckTest, MetaColorSchemeDark) {
- RuntimeEnabledFeatures::SetCSSColorSchemeEnabled(true);
- RuntimeEnabledFeatures::SetMetaColorSchemeEnabled(true);
+ ScopedCSSColorSchemeForTest css_feature_scope(true);
+ ScopedMetaColorSchemeForTest meta_feature_scope(true);
GetDocument().GetSettings()->SetForceDarkModeEnabled(true);
GetDocument().GetSettings()->SetPreferredColorScheme(
PreferredColorScheme::kDark);
diff --git a/chromium/third_party/blink/renderer/core/animation/BUILD.gn b/chromium/third_party/blink/renderer/core/animation/BUILD.gn
index 1cd0b923098..72b16e6a67a 100644
--- a/chromium/third_party/blink/renderer/core/animation/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/animation/BUILD.gn
@@ -8,6 +8,8 @@ blink_core_sources("animation") {
split_count = 5
sources = [
+ "animatable.cc",
+ "animatable.h",
"animation.cc",
"animation.h",
"animation_clock.cc",
@@ -26,6 +28,7 @@ blink_core_sources("animation") {
"color_property_functions.h",
"compositor_animations.cc",
"compositor_animations.h",
+ "css/compositor_keyframe_color.h",
"css/compositor_keyframe_double.h",
"css/compositor_keyframe_filter_operations.h",
"css/compositor_keyframe_transform.h",
@@ -52,6 +55,8 @@ blink_core_sources("animation") {
"css_clip_interpolation_type.h",
"css_color_interpolation_type.cc",
"css_color_interpolation_type.h",
+ "css_custom_length_interpolation_type.cc",
+ "css_custom_length_interpolation_type.h",
"css_custom_list_interpolation_type.cc",
"css_custom_list_interpolation_type.h",
"css_default_interpolation_type.cc",
@@ -87,6 +92,8 @@ blink_core_sources("animation") {
"css_paint_interpolation_type.h",
"css_path_interpolation_type.cc",
"css_path_interpolation_type.h",
+ "css_percentage_interpolation_type.cc",
+ "css_percentage_interpolation_type.h",
"css_position_axis_list_interpolation_type.cc",
"css_position_axis_list_interpolation_type.h",
"css_position_interpolation_type.h",
@@ -126,8 +133,6 @@ blink_core_sources("animation") {
"effect_model.h",
"effect_stack.cc",
"effect_stack.h",
- "element_animation.cc",
- "element_animation.h",
"element_animations.cc",
"element_animations.h",
"filter_interpolation_functions.cc",
@@ -242,7 +247,6 @@ blink_core_sources("animation") {
blink_core_tests("unit_tests") {
sources = [
- "animation_clock_test.cc",
"animation_effect_test.cc",
"animation_input_helpers_test.cc",
"animation_sim_test.cc",
diff --git a/chromium/third_party/blink/renderer/core/animation/element_animation.cc b/chromium/third_party/blink/renderer/core/animation/animatable.cc
index bbc894acf9f..d33e6a15cff 100644
--- a/chromium/third_party/blink/renderer/core/animation/element_animation.cc
+++ b/chromium/third_party/blink/renderer/core/animation/animatable.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/core/animation/element_animation.h"
+#include "third_party/blink/renderer/core/animation/animatable.h"
#include "third_party/blink/renderer/core/animation/animation.h"
#include "third_party/blink/renderer/core/animation/document_timeline.h"
@@ -41,9 +41,8 @@ void ReportFeaturePolicyViolationsIfNecessary(
} // namespace
-Animation* ElementAnimation::animate(
+Animation* Animatable::animate(
ScriptState* script_state,
- Element& element,
const ScriptValue& keyframes,
UnrestrictedDoubleOrKeyframeAnimationOptions options,
ExceptionState& exception_state) {
@@ -54,44 +53,45 @@ Animation* ElementAnimation::animate(
.value();
}
+ Element* element = GetAnimationTarget();
KeyframeEffectModelBase* effect = EffectInput::Convert(
- &element, keyframes, composite, script_state, exception_state);
+ element, keyframes, composite, script_state, exception_state);
if (exception_state.HadException())
return nullptr;
Timing timing =
- TimingInput::Convert(options, &element.GetDocument(), exception_state);
+ TimingInput::Convert(options, &element->GetDocument(), exception_state);
if (exception_state.HadException())
return nullptr;
- Animation* animation = animateInternal(element, effect, timing);
+ Animation* animation = animateInternal(*element, effect, timing);
if (options.IsKeyframeAnimationOptions())
animation->setId(options.GetAsKeyframeAnimationOptions()->id());
return animation;
}
-Animation* ElementAnimation::animate(ScriptState* script_state,
- Element& element,
- const ScriptValue& keyframes,
- ExceptionState& exception_state) {
+Animation* Animatable::animate(ScriptState* script_state,
+ const ScriptValue& keyframes,
+ ExceptionState& exception_state) {
+ Element* element = GetAnimationTarget();
KeyframeEffectModelBase* effect =
- EffectInput::Convert(&element, keyframes, EffectModel::kCompositeReplace,
+ EffectInput::Convert(element, keyframes, EffectModel::kCompositeReplace,
script_state, exception_state);
if (exception_state.HadException())
return nullptr;
- return animateInternal(element, effect, Timing());
+ return animateInternal(*element, effect, Timing());
}
-HeapVector<Member<Animation>> ElementAnimation::getAnimations(
- Element& element) {
- element.GetDocument().UpdateStyleAndLayoutTreeForNode(&element);
+HeapVector<Member<Animation>> Animatable::getAnimations() {
+ Element* element = GetAnimationTarget();
+ element->GetDocument().UpdateStyleAndLayoutTreeForNode(element);
HeapVector<Member<Animation>> animations;
- if (!element.HasAnimations())
+ if (!element->HasAnimations())
return animations;
for (const auto& animation :
- element.GetDocument().Timeline().getAnimations()) {
+ element->GetDocument().Timeline().getAnimations()) {
DCHECK(animation->effect());
if (ToKeyframeEffect(animation->effect())->target() == element &&
(animation->effect()->IsCurrent() || animation->effect()->IsInEffect()))
@@ -100,9 +100,9 @@ HeapVector<Member<Animation>> ElementAnimation::getAnimations(
return animations;
}
-Animation* ElementAnimation::animateInternal(Element& element,
- KeyframeEffectModelBase* effect,
- const Timing& timing) {
+Animation* Animatable::animateInternal(Element& element,
+ KeyframeEffectModelBase* effect,
+ const Timing& timing) {
ReportFeaturePolicyViolationsIfNecessary(element.GetDocument(), *effect);
auto* keyframe_effect =
MakeGarbageCollected<KeyframeEffect>(&element, effect, timing);
diff --git a/chromium/third_party/blink/renderer/core/animation/element_animation.h b/chromium/third_party/blink/renderer/core/animation/animatable.h
index 005da442a75..2bc0c196397 100644
--- a/chromium/third_party/blink/renderer/core/animation/element_animation.h
+++ b/chromium/third_party/blink/renderer/core/animation/animatable.h
@@ -28,14 +28,14 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_ELEMENT_ANIMATION_H_
-#define THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_ELEMENT_ANIMATION_H_
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_ANIMATABLE_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_ANIMATABLE_H_
#include "third_party/blink/renderer/bindings/core/v8/unrestricted_double_or_keyframe_animation_options.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/heap/heap_allocator.h"
#include "third_party/blink/renderer/platform/heap/member.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -46,24 +46,21 @@ class KeyframeEffectModelBase;
class ScriptState;
struct Timing;
-// Implements the interface in ElementAnimation.idl.
-
-class CORE_EXPORT ElementAnimation {
- STATIC_ONLY(ElementAnimation);
-
+// https://drafts.csswg.org/web-animations-1/#the-animatable-interface-mixin
+class CORE_EXPORT Animatable {
public:
- static Animation* animate(ScriptState*,
- Element&,
- const ScriptValue&,
- UnrestrictedDoubleOrKeyframeAnimationOptions,
- ExceptionState&);
+ // Returns the target element of the animation that these methods are being
+ // called on.
+ virtual Element* GetAnimationTarget() = 0;
+
+ Animation* animate(ScriptState*,
+ const ScriptValue&,
+ UnrestrictedDoubleOrKeyframeAnimationOptions,
+ ExceptionState&);
- static Animation* animate(ScriptState*,
- Element&,
- const ScriptValue&,
- ExceptionState&);
+ Animation* animate(ScriptState*, const ScriptValue&, ExceptionState&);
- static HeapVector<Member<Animation>> getAnimations(Element&);
+ HeapVector<Member<Animation>> getAnimations();
private:
FRIEND_TEST_ALL_PREFIXES(AnimationSimTest, CustomPropertyBaseComputedStyle);
@@ -75,4 +72,4 @@ class CORE_EXPORT ElementAnimation {
} // namespace blink
-#endif // THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_ELEMENT_ANIMATION_H_
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_ANIMATABLE_H_
diff --git a/chromium/third_party/blink/renderer/core/animation/element_animation.idl b/chromium/third_party/blink/renderer/core/animation/animatable.idl
index 1c596d36cd8..4862ea48a8d 100644
--- a/chromium/third_party/blink/renderer/core/animation/element_animation.idl
+++ b/chromium/third_party/blink/renderer/core/animation/animatable.idl
@@ -28,15 +28,15 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-// https://drafts.csswg.org/web-animations/#the-animatable-interface
-// https://drafts.csswg.org/web-animations/#extensions-to-the-element-interface
-
-// TODO(dstockwell): This should be an Animatable interface, where Element
-// includes Animatable.
-
-[
- ImplementedAs=ElementAnimation
-] partial interface Element {
+// https://drafts.csswg.org/web-animations/#the-animatable-interface-mixin
+interface mixin Animatable {
[CallWith=ScriptState, Measure, RaisesException] Animation animate(object? keyframes, optional (unrestricted double or KeyframeAnimationOptions) options);
[RuntimeEnabled=WebAnimationsAPI] sequence<Animation> getAnimations();
};
+
+// https://drafts.csswg.org/web-animations-1/#extensions-to-the-element-interface
+Element includes Animatable;
+
+// https://drafts.csswg.org/web-animations-1/#extensions-to-the-pseudoelement-interface
+// TODO(smcgruer): Uncomment once CSSPseudoElement is implemented in Chromium.
+// CSSPseudoElement includes Animatable;
diff --git a/chromium/third_party/blink/renderer/core/animation/animation.cc b/chromium/third_party/blink/renderer/core/animation/animation.cc
index b9a33875fe0..48f5bc4152b 100644
--- a/chromium/third_party/blink/renderer/core/animation/animation.cc
+++ b/chromium/third_party/blink/renderer/core/animation/animation.cc
@@ -41,12 +41,12 @@
#include "third_party/blink/renderer/core/animation/document_timeline.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/animation/scroll_timeline.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/dom/dom_node_ids.h"
#include "third_party/blink/renderer/core/events/animation_playback_event.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/inspector/inspector_trace_events.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
@@ -55,6 +55,7 @@
#include "third_party/blink/renderer/platform/heap/heap.h"
#include "third_party/blink/renderer/platform/heap/persistent.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
namespace blink {
@@ -115,24 +116,16 @@ Animation* Animation::Create(AnimationEffect* effect,
AnimationTimeline* timeline,
ExceptionState& exception_state) {
DCHECK(timeline);
- if (!timeline->IsDocumentTimeline()) {
+ if (!timeline->IsDocumentTimeline() && !timeline->IsScrollTimeline()) {
exception_state.ThrowDOMException(DOMExceptionCode::kNotSupportedError,
"Invalid timeline. Animation requires a "
- "DocumentTimeline");
+ "DocumentTimeline or ScrollTimeline");
return nullptr;
}
+ DCHECK(timeline->IsDocumentTimeline() || timeline->IsScrollTimeline());
- DocumentTimeline* subtimeline = ToDocumentTimeline(timeline);
-
- Animation* animation = MakeGarbageCollected<Animation>(
- subtimeline->GetDocument()->ContextDocument(), subtimeline, effect);
-
- if (subtimeline) {
- subtimeline->AnimationAttached(*animation);
- animation->AttachCompositorTimeline();
- }
-
- return animation;
+ return MakeGarbageCollected<Animation>(
+ timeline->GetDocument()->ContextDocument(), timeline, effect);
}
Animation* Animation::Create(ExecutionContext* execution_context,
@@ -156,7 +149,7 @@ Animation* Animation::Create(ExecutionContext* execution_context,
}
Animation::Animation(ExecutionContext* execution_context,
- DocumentTimeline* timeline,
+ AnimationTimeline* timeline,
AnimationEffect* content)
: ContextLifecycleObserver(execution_context),
internal_play_state_(kIdle),
@@ -190,6 +183,11 @@ Animation::Animation(ExecutionContext* execution_context,
document_ =
timeline_ ? timeline_->GetDocument() : To<Document>(execution_context);
DCHECK(document_);
+
+ TickingTimeline().AnimationAttached(this);
+ if (timeline_ && timeline_->IsScrollTimeline())
+ timeline_->AnimationAttached(this);
+ AttachCompositorTimeline();
probe::DidCreateAnimation(document_, sequence_number_);
}
@@ -199,6 +197,8 @@ Animation::~Animation() {
}
void Animation::Dispose() {
+ if (timeline_ && timeline_->IsScrollTimeline())
+ timeline_->AnimationDetached(this);
DestroyCompositorAnimation();
// If the DocumentTimeline and its Animation objects are
// finalized by the same GC, we have to eagerly clear out
@@ -207,7 +207,7 @@ void Animation::Dispose() {
}
double Animation::EffectEnd() const {
- return content_ ? content_->EndTimeInternal() : 0;
+ return content_ ? content_->SpecifiedTiming().EndTimeInternal() : 0;
}
bool Animation::Limited(double current_time) const {
@@ -215,9 +215,36 @@ bool Animation::Limited(double current_time) const {
(playback_rate_ > 0 && current_time >= EffectEnd());
}
+Document* Animation::GetDocument() {
+ return document_;
+}
+
+double Animation::TimelineTime() const {
+ if (timeline_)
+ return timeline_->CurrentTime().value_or(NullValue());
+ return NullValue();
+}
+
+DocumentTimeline& Animation::TickingTimeline() {
+ // Active animations are tracked and ticked through the timeline attached to
+ // the animation's document.
+ // TODO(crbug.com/916117): Reconsider how animations are tracked and ticked.
+ return document_->Timeline();
+}
+
void Animation::setCurrentTime(double new_current_time,
bool is_null,
ExceptionState& exception_state) {
+ // TODO(crbug.com/916117): Implement setting current time for scroll-linked
+ // animations.
+ if (timeline_ && timeline_->IsScrollTimeline()) {
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kNotSupportedError,
+ "Scroll-linked WebAnimation currently does not support setting"
+ " current time.");
+ return;
+ }
+
PlayStateUpdateScope update_scope(*this, kTimingUpdateOnDemand);
// Step 1. of the procedure to silently set the current time of an
@@ -274,7 +301,7 @@ void Animation::SetCurrentTimeInternal(double new_current_time,
// Update timing to reflect updated animation clock due to tick
void Animation::UpdateCurrentTimingState(TimingUpdateReason reason) {
- if (internal_play_state_ == kIdle || !timeline_)
+ if (internal_play_state_ == kIdle || !timeline_ || !timeline_->IsActive())
return;
if (hold_time_) {
double new_current_time = hold_time_.value();
@@ -328,13 +355,21 @@ double Animation::currentTime() {
// * the associated timeline is inactive, or
// * the animation’s start time is unresolved.
// The current time is an unresolved time value.
- if (!timeline_ || PlayStateInternal() == kIdle || !start_time_)
+ if (!timeline_ || !timeline_->IsActive() || PlayStateInternal() == kIdle ||
+ !start_time_) {
return NullValue();
+ }
// 3. Otherwise,
// current time = (timeline time - start time) × playback rate
+ base::Optional<double> timeline_time = timeline_->CurrentTimeSeconds();
+ // TODO(crbug.com/916117): Handle NaN values for scroll linked animations.
+ if (!timeline_time) {
+ DCHECK(timeline_->IsScrollTimeline());
+ return 0;
+ }
double current_time =
- (timeline_->EffectiveTime() - start_time_.value()) * playback_rate_;
+ (timeline_time.value() - start_time_.value()) * playback_rate_;
return ToMilliseconds(current_time);
}
@@ -521,20 +556,41 @@ base::Optional<double> Animation::CalculateStartTime(
double current_time) const {
base::Optional<double> start_time;
if (timeline_) {
- start_time = timeline_->EffectiveTime() - current_time / playback_rate_;
- DCHECK(!IsNull(start_time.value()));
+ base::Optional<double> timeline_time = timeline_->CurrentTimeSeconds();
+ if (timeline_time)
+ start_time = timeline_time.value() - current_time / playback_rate_;
+ // TODO(crbug.com/916117): Handle NaN time for scroll-linked animations.
+ DCHECK(start_time || timeline_->IsScrollTimeline());
}
return start_time;
}
double Animation::CalculateCurrentTime() const {
- if (!start_time_ || !timeline_)
+ if (!start_time_ || !timeline_ || !timeline_->IsActive())
+ return NullValue();
+ base::Optional<double> timeline_time = timeline_->CurrentTimeSeconds();
+ // TODO(crbug.com/916117): Handle NaN time for scroll-linked animations.
+ if (!timeline_time) {
+ DCHECK(timeline_->IsScrollTimeline());
return NullValue();
- return (timeline_->EffectiveTime() - start_time_.value()) * playback_rate_;
+ }
+ return (timeline_time.value() - start_time_.value()) * playback_rate_;
}
// https://drafts.csswg.org/web-animations/#setting-the-start-time-of-an-animation
-void Animation::setStartTime(double start_time, bool is_null) {
+void Animation::setStartTime(double start_time,
+ bool is_null,
+ ExceptionState& exception_state) {
+ // TODO(crbug.com/916117): Implement setting start time for scroll-linked
+ // animations.
+ if (timeline_ && timeline_->IsScrollTimeline()) {
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kNotSupportedError,
+ "Scroll-linked WebAnimation currently does not support setting start"
+ " time.");
+ return;
+ }
+
PlayStateUpdateScope update_scope(*this, kTimingUpdateOnDemand);
base::Optional<double> new_start_time;
@@ -556,7 +612,14 @@ void Animation::setStartTime(double start_time, bool is_null) {
void Animation::SetStartTimeInternal(base::Optional<double> new_start_time) {
bool had_start_time = start_time_.has_value();
double previous_current_time = CurrentTimeInternal();
- start_time_ = new_start_time;
+
+ // Scroll-linked animations are initialized with the start time of
+ // zero (i.e., scroll origin).
+ // Changing scroll-linked animation start_time initialization is under
+ // consideration here: https://github.com/w3c/csswg-drafts/issues/2075.
+ start_time_ =
+ (!timeline_ || timeline_->IsDocumentTimeline()) ? new_start_time : 0;
+
// When we don't have an active timeline it is only possible to set either the
// start time or the current time. Resetting the hold time clears current
// time.
@@ -706,6 +769,13 @@ void Animation::ResetPendingTasks() {
}
void Animation::pause(ExceptionState& exception_state) {
+ // TODO(crbug.com/916117): Implement pause for scroll-linked animations.
+ if (timeline_ && timeline_->IsScrollTimeline()) {
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kNotSupportedError,
+ "Scroll-linked WebAnimation currently does not support pause.");
+ return;
+ }
if (paused_)
return;
@@ -797,6 +867,13 @@ void Animation::play(ExceptionState& exception_state) {
// https://drafts.csswg.org/web-animations/#reversing-an-animation-section
void Animation::reverse(ExceptionState& exception_state) {
+ // TODO(crbug.com/916117): Implement reverse for scroll-linked animations.
+ if (timeline_ && timeline_->IsScrollTimeline()) {
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kNotSupportedError,
+ "Scroll-linked WebAnimation currently does not support reverse.");
+ return;
+ }
if (!playback_rate_) {
return;
}
@@ -852,7 +929,17 @@ void Animation::finish(ExceptionState& exception_state) {
}
// https://drafts.csswg.org/web-animations/#setting-the-playback-rate-of-an-animation
-void Animation::updatePlaybackRate(double playback_rate) {
+void Animation::updatePlaybackRate(double playback_rate,
+ ExceptionState& exception_state) {
+ // TODO(crbug.com/916117): Implement updatePlaybackRate for scroll-linked
+ // animations.
+ if (timeline_ && timeline_->IsScrollTimeline()) {
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kNotSupportedError,
+ "Scroll-linked WebAnimation currently does not support"
+ " updatePlaybackRate.");
+ return;
+ }
// The implementation differs from the spec; however, the end result is
// consistent. Whereas Animation.playbackRate updates the playback rate
// immediately, updatePlaybackRate is to take effect on the next async cycle.
@@ -929,7 +1016,17 @@ double Animation::playbackRate() const {
return active_playback_rate_.value_or(playback_rate_);
}
-void Animation::setPlaybackRate(double playback_rate) {
+void Animation::setPlaybackRate(double playback_rate,
+ ExceptionState& exception_state) {
+ // TODO(crbug.com/916117): Implement setting playback rate for scroll-linked
+ // animations.
+ if (timeline_ && timeline_->IsScrollTimeline()) {
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kNotSupportedError,
+ "Scroll-linked WebAnimation currently does not support setting"
+ " playback rate.");
+ return;
+ }
active_playback_rate_.reset();
if (playback_rate == playback_rate_)
return;
@@ -971,7 +1068,7 @@ void Animation::ClearOutdated() {
return;
outdated_ = false;
if (timeline_)
- timeline_->ClearOutdatedAnimation(this);
+ TickingTimeline().ClearOutdatedAnimation(this);
}
void Animation::SetOutdated() {
@@ -979,12 +1076,12 @@ void Animation::SetOutdated() {
return;
outdated_ = true;
if (timeline_)
- timeline_->SetOutdatedAnimation(this);
+ TickingTimeline().SetOutdatedAnimation(this);
}
void Animation::ForceServiceOnNextFrame() {
if (timeline_)
- timeline_->Wake();
+ TickingTimeline().Wake();
}
CompositorAnimations::FailureReasons
@@ -1025,7 +1122,8 @@ Animation::CheckCanStartAnimationOnCompositorInternal() const {
// reason to composite it. Additionally, mutating the timeline playback rate
// is a debug feature available via devtools; we don't support this on the
// compositor currently and there is no reason to do so.
- if (!timeline_ || timeline_->PlaybackRate() != 1)
+ if (!timeline_ || (timeline_->IsDocumentTimeline() &&
+ ToDocumentTimeline(timeline_)->PlaybackRate() != 1))
reasons |= CompositorAnimations::kInvalidAnimationOrEffect;
// An Animation without an effect cannot produce a visual, so there is no
@@ -1038,6 +1136,10 @@ Animation::CheckCanStartAnimationOnCompositorInternal() const {
if (!Playing())
reasons |= CompositorAnimations::kInvalidAnimationOrEffect;
+ // TODO(crbug.com/916117): Support accelerated scroll linked animations.
+ if (timeline_->IsScrollTimeline())
+ reasons |= CompositorAnimations::kInvalidAnimationOrEffect;
+
return reasons;
}
@@ -1045,14 +1147,16 @@ void Animation::StartAnimationOnCompositor(
const PaintArtifactCompositor* paint_artifact_compositor) {
DCHECK_EQ(CheckCanStartAnimationOnCompositor(paint_artifact_compositor),
CompositorAnimations::kNoFailure);
+ DCHECK(timeline_->IsDocumentTimeline());
bool reversed = playback_rate_ < 0;
base::Optional<double> start_time = base::nullopt;
double time_offset = 0;
if (start_time_) {
- start_time = TimelineInternal()->ZeroTime().since_origin().InSecondsF() +
- start_time_.value();
+ start_time =
+ ToDocumentTimeline(timeline_)->ZeroTime().since_origin().InSecondsF() +
+ start_time_.value();
if (reversed)
start_time = start_time.value() - (EffectEnd() / fabs(playback_rate_));
} else {
@@ -1153,15 +1257,14 @@ bool Animation::Update(TimingUpdateReason reason) {
bool idle = PlayStateInternal() == kIdle;
if (content_) {
- double inherited_time = idle || IsNull(timeline_->CurrentTimeInternal())
- ? NullValue()
- : CurrentTimeInternal();
+ double inherited_time =
+ idle || !timeline_->CurrentTime() ? NullValue() : CurrentTimeInternal();
// Special case for end-exclusivity when playing backwards.
if (inherited_time == 0 && playback_rate_ < 0)
inherited_time = -1;
- content_->UpdateInheritedTime(inherited_time, reason);
+ content_->UpdateInheritedTime(inherited_time, reason);
// After updating the animation time if the animation is no longer current
// blink will no longer composite the element (see
// CompositingReasonFinder::RequiresCompositingFor*Animation). We cancel any
@@ -1177,6 +1280,8 @@ bool Animation::Update(TimingUpdateReason reason) {
const AtomicString& event_type = event_type_names::kCancel;
if (GetExecutionContext() && HasEventListeners(event_type)) {
double event_current_time = NullValue();
+ // TODO(crbug.com/916117): Handle NaN values for scroll-linked
+ // animations.
pending_cancelled_event_ =
MakeGarbageCollected<AnimationPlaybackEvent>(
event_type, event_current_time, TimelineTime());
@@ -1198,6 +1303,7 @@ void Animation::QueueFinishedEvent() {
const AtomicString& event_type = event_type_names::kFinish;
if (GetExecutionContext() && HasEventListeners(event_type)) {
double event_current_time = CurrentTimeInternal() * 1000;
+ // TODO(crbug.com/916117): Handle NaN values for scroll-linked animations.
pending_finished_event_ = MakeGarbageCollected<AnimationPlaybackEvent>(
event_type, event_current_time, TimelineTime());
pending_finished_event_->SetTarget(this);
@@ -1239,7 +1345,7 @@ double Animation::TimeToEffectChange() {
: content_->TimeToReverseEffectChange() / -playback_rate_;
return !HasActiveAnimationsOnCompositor() &&
- content_->GetPhase() == AnimationEffect::kPhaseActive
+ content_->GetPhase() == Timing::kPhaseActive
? 0
: result;
}
@@ -1294,7 +1400,8 @@ void Animation::DestroyCompositorAnimation() {
void Animation::AttachCompositorTimeline() {
if (compositor_animation_) {
CompositorAnimationTimeline* timeline =
- timeline_ ? timeline_->CompositorTimeline() : nullptr;
+ timeline_ ? ToDocumentTimeline(timeline_)->CompositorTimeline()
+ : nullptr;
if (timeline)
timeline->AnimationAttached(*this);
}
@@ -1303,7 +1410,8 @@ void Animation::AttachCompositorTimeline() {
void Animation::DetachCompositorTimeline() {
if (compositor_animation_) {
CompositorAnimationTimeline* timeline =
- timeline_ ? timeline_->CompositorTimeline() : nullptr;
+ timeline_ ? ToDocumentTimeline(timeline_)->CompositorTimeline()
+ : nullptr;
if (timeline)
timeline->AnimationDestroyed(*this);
}
diff --git a/chromium/third_party/blink/renderer/core/animation/animation.h b/chromium/third_party/blink/renderer/core/animation/animation.h
index e79245a526f..326756d7a32 100644
--- a/chromium/third_party/blink/renderer/core/animation/animation.h
+++ b/chromium/third_party/blink/renderer/core/animation/animation.h
@@ -41,6 +41,7 @@
#include "third_party/blink/renderer/bindings/core/v8/script_promise_property.h"
#include "third_party/blink/renderer/core/animation/animation_effect.h"
#include "third_party/blink/renderer/core/animation/animation_effect_owner.h"
+#include "third_party/blink/renderer/core/animation/animation_timeline.h"
#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"
@@ -94,8 +95,7 @@ class CORE_EXPORT Animation final : public EventTargetWithInlineData,
AnimationTimeline*,
ExceptionState&);
- Animation(ExecutionContext*, DocumentTimeline*, AnimationEffect*);
-
+ Animation(ExecutionContext*, AnimationTimeline*, AnimationEffect*);
~Animation() override;
void Dispose();
@@ -137,7 +137,8 @@ class CORE_EXPORT Animation final : public EventTargetWithInlineData,
void play(ExceptionState& = ASSERT_NO_EXCEPTION);
void reverse(ExceptionState& = ASSERT_NO_EXCEPTION);
void finish(ExceptionState& = ASSERT_NO_EXCEPTION);
- void updatePlaybackRate(double playback_rate);
+ void updatePlaybackRate(double playback_rate,
+ ExceptionState& = ASSERT_NO_EXCEPTION);
ScriptPromise finished(ScriptState*);
ScriptPromise ready(ScriptState*);
@@ -158,20 +159,16 @@ class CORE_EXPORT Animation final : public EventTargetWithInlineData,
void ContextDestroyed(ExecutionContext*) override;
double playbackRate() const;
- void setPlaybackRate(double);
- AnimationTimeline* timeline() {
- return static_cast<AnimationTimeline*>(timeline_);
- }
- const DocumentTimeline* TimelineInternal() const { return timeline_; }
- DocumentTimeline* TimelineInternal() { return timeline_; }
- double TimelineTime() const {
- return timeline_ ? timeline_->currentTime() : NullValue();
- }
+ void setPlaybackRate(double, ExceptionState& = ASSERT_NO_EXCEPTION);
+ AnimationTimeline* timeline() { return timeline_; }
+ Document* GetDocument();
double startTime(bool& is_null) const;
base::Optional<double> startTime() const;
base::Optional<double> StartTimeInternal() const { return start_time_; }
- void setStartTime(double, bool is_null);
+ void setStartTime(double,
+ bool is_null,
+ ExceptionState& = ASSERT_NO_EXCEPTION);
const AnimationEffect* effect() const { return content_.Get(); }
AnimationEffect* effect() { return content_.Get(); }
@@ -299,6 +296,8 @@ class CORE_EXPORT Animation final : public EventTargetWithInlineData,
void QueueFinishedEvent();
void ResetPendingTasks();
+ double TimelineTime() const;
+ DocumentTimeline& TickingTimeline();
String id_;
@@ -328,7 +327,7 @@ class CORE_EXPORT Animation final : public EventTargetWithInlineData,
// Document refers to the timeline's document if there is a timeline.
// Otherwise it refers to the document for the execution context.
Member<Document> document_;
- Member<DocumentTimeline> timeline_;
+ Member<AnimationTimeline> timeline_;
// Reflects all pausing, including via pauseForTesting().
bool paused_;
@@ -435,7 +434,7 @@ class CORE_EXPORT Animation final : public EventTargetWithInlineData,
bool effect_suppressed_;
- FRIEND_TEST_ALL_PREFIXES(AnimationAnimationTest,
+ FRIEND_TEST_ALL_PREFIXES(AnimationAnimationTestCompositeAfterPaint,
NoCompositeWithoutCompositedElementId);
};
diff --git a/chromium/third_party/blink/renderer/core/animation/animation.idl b/chromium/third_party/blink/renderer/core/animation/animation.idl
index 351eda96e41..79acca95bda 100644
--- a/chromium/third_party/blink/renderer/core/animation/animation.idl
+++ b/chromium/third_party/blink/renderer/core/animation/animation.idl
@@ -42,20 +42,20 @@ enum AnimationPlayState { "idle", "pending", "running", "paused", "finished" };
[Measure] attribute AnimationEffect? effect;
// TODO(suzyh): Make timeline mutable.
[RuntimeEnabled=WebAnimationsAPI] readonly attribute AnimationTimeline? timeline;
- [Measure] attribute double? startTime;
+ [Measure, RaisesException=Setter] attribute double? startTime;
[Measure, RaisesException=Setter] attribute double? currentTime;
- [Measure] attribute double playbackRate;
+ [Measure, RaisesException=Setter] attribute double playbackRate;
[Measure] readonly attribute AnimationPlayState playState;
[Measure] readonly attribute boolean pending;
[Measure, RaisesException] void finish();
[Measure, RaisesException] void play();
[Measure, RaisesException] void pause();
[Measure, RaisesException] void reverse();
- [Measure] void updatePlaybackRate(double playback_rate);
+ [Measure, RaisesException] void updatePlaybackRate(double playback_rate);
[Measure] attribute DOMString id;
[Measure] void cancel();
[Measure] attribute EventHandler onfinish;
[Measure] attribute EventHandler oncancel;
[RuntimeEnabled=WebAnimationsAPI, CallWith=ScriptState] readonly attribute Promise<Animation> finished;
[RuntimeEnabled=WebAnimationsAPI, CallWith=ScriptState] readonly attribute Promise<Animation> ready;
-};
+}; \ No newline at end of file
diff --git a/chromium/third_party/blink/renderer/core/animation/animation_clock.cc b/chromium/third_party/blink/renderer/core/animation/animation_clock.cc
index fb1e29dc90c..1c8ae77d3e0 100644
--- a/chromium/third_party/blink/renderer/core/animation/animation_clock.cc
+++ b/chromium/third_party/blink/renderer/core/animation/animation_clock.cc
@@ -33,49 +33,22 @@
#include <math.h>
#include "third_party/blink/renderer/platform/wtf/time.h"
-namespace {
-
-// FIXME: This is an approximation of time between frames, used when
-// ticking the animation clock outside of animation frame callbacks.
-// Ideally this would be generated by the compositor.
-constexpr base::TimeDelta kApproximateFrameTime =
- base::TimeDelta::FromSecondsD(1 / 60.0);
-}
-
namespace blink {
-unsigned AnimationClock::currently_running_task_ = 0;
-
void AnimationClock::UpdateTime(base::TimeTicks time) {
- if (time > time_)
- time_ = time;
- task_for_which_time_was_calculated_ = currently_running_task_;
+ // TODO(crbug.com/985770): Change this to a DCHECK_GE(time, time_) when
+ // VR no longer sends historical timestamps.
+ if (time < time_)
+ return;
+ time_ = time;
}
-double AnimationClock::CurrentTime() {
- if (monotonically_increasing_time_ &&
- task_for_which_time_was_calculated_ != currently_running_task_) {
- const base::TimeTicks current_time = monotonically_increasing_time_();
- if (time_ < current_time) {
- // Advance to the first estimated frame after the current time.
- const base::TimeDelta frame_shift =
- (current_time - time_) % kApproximateFrameTime;
- const base::TimeTicks new_time =
- current_time + kApproximateFrameTime - frame_shift;
- DCHECK_GE(new_time, current_time);
- DCHECK_LE(new_time, current_time + kApproximateFrameTime);
- UpdateTime(new_time);
- } else {
- task_for_which_time_was_calculated_ = currently_running_task_;
- }
- }
- return time_.since_origin().InSecondsF();
+base::TimeTicks AnimationClock::CurrentTime() const {
+ return time_;
}
-void AnimationClock::ResetTimeForTesting(base::TimeTicks time) {
- time_ = time;
- task_for_which_time_was_calculated_ = 0;
- currently_running_task_ = 0;
+void AnimationClock::ResetTimeForTesting() {
+ time_ = base::TimeTicks();
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/animation/animation_clock.h b/chromium/third_party/blink/renderer/core/animation/animation_clock.h
index 56eb03f838b..b780210abdb 100644
--- a/chromium/third_party/blink/renderer/core/animation/animation_clock.h
+++ b/chromium/third_party/blink/renderer/core/animation/animation_clock.h
@@ -35,42 +35,25 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
-#include "third_party/blink/renderer/platform/wtf/time.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
-// Maintains a stationary clock time during script execution. Tries to track
-// the glass time (the moment photons leave the screen) of the current animation
-// frame.
+// Maintains a stationary clock time during script execution. Tracks the glass
+// time of the beginning of the current animation frame (i.e. the moment photons
+// left the screen for the previous frame).
class CORE_EXPORT AnimationClock {
DISALLOW_NEW();
public:
- using TimeTicksFunction = base::TimeTicks (*)();
- explicit AnimationClock(
- TimeTicksFunction monotonically_increasing_time = WTF::CurrentTimeTicks)
- : monotonically_increasing_time_(monotonically_increasing_time),
- time_(),
- task_for_which_time_was_calculated_(
- std::numeric_limits<unsigned>::max()) {}
+ AnimationClock() : time_() {}
void UpdateTime(base::TimeTicks time);
- double CurrentTime();
- void ResetTimeForTesting(base::TimeTicks time = base::TimeTicks());
- void DisableSyntheticTimeForTesting() {
- monotonically_increasing_time_ = nullptr;
- }
-
- // notifyTaskStart should be called right before the main message loop starts
- // to run the next task from the message queue.
- static void NotifyTaskStart() { ++currently_running_task_; }
+ base::TimeTicks CurrentTime() const;
+ void ResetTimeForTesting();
private:
- TimeTicksFunction monotonically_increasing_time_;
base::TimeTicks time_;
- unsigned task_for_which_time_was_calculated_;
- static unsigned currently_running_task_;
DISALLOW_COPY_AND_ASSIGN(AnimationClock);
};
diff --git a/chromium/third_party/blink/renderer/core/animation/animation_clock_test.cc b/chromium/third_party/blink/renderer/core/animation/animation_clock_test.cc
deleted file mode 100644
index 0d186f8754d..00000000000
--- a/chromium/third_party/blink/renderer/core/animation/animation_clock_test.cc
+++ /dev/null
@@ -1,139 +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.
- */
-
-#include "third_party/blink/renderer/core/animation/animation_clock.h"
-
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace blink {
-
-class AnimationAnimationClockTest : public testing::Test {
- public:
- AnimationAnimationClockTest() : animation_clock(MockTimeFunction) {}
-
- protected:
- void SetUp() override {
- mock_time_ = 0;
- animation_clock.ResetTimeForTesting();
- }
-
- static base::TimeTicks MockTimeFunction() {
- return base::TimeTicks() + base::TimeDelta::FromSecondsD(mock_time_);
- }
-
- static double mock_time_;
- AnimationClock animation_clock;
-};
-
-double AnimationAnimationClockTest::mock_time_;
-
-TEST_F(AnimationAnimationClockTest, TimeIsGreaterThanZeroForUnitTests) {
- AnimationClock clock;
- // unit tests outside core/animation shouldn't need to do anything to get
- // a non-zero currentTime().
- EXPECT_GT(clock.CurrentTime(), 0);
-}
-
-TEST_F(AnimationAnimationClockTest, TimeDoesNotChange) {
- animation_clock.UpdateTime(base::TimeTicks() +
- base::TimeDelta::FromSeconds(100));
- EXPECT_EQ(100, animation_clock.CurrentTime());
- EXPECT_EQ(100, animation_clock.CurrentTime());
-}
-
-TEST_F(AnimationAnimationClockTest, TimeAdvancesWhenUpdated) {
- animation_clock.UpdateTime(base::TimeTicks() +
- base::TimeDelta::FromSeconds(100));
- EXPECT_EQ(100, animation_clock.CurrentTime());
-
- animation_clock.UpdateTime(base::TimeTicks() +
- base::TimeDelta::FromSeconds(200));
- EXPECT_EQ(200, animation_clock.CurrentTime());
-}
-
-TEST_F(AnimationAnimationClockTest, TimeAdvancesToTaskTime) {
- animation_clock.UpdateTime(base::TimeTicks() +
- base::TimeDelta::FromSeconds(100));
- EXPECT_EQ(100, animation_clock.CurrentTime());
-
- mock_time_ = 150;
- AnimationClock::NotifyTaskStart();
- EXPECT_GE(animation_clock.CurrentTime(), mock_time_);
-}
-
-TEST_F(AnimationAnimationClockTest, TimeAdvancesToTaskTimeOnlyWhenRequired) {
- animation_clock.UpdateTime(base::TimeTicks() +
- base::TimeDelta::FromSeconds(100));
- EXPECT_EQ(100, animation_clock.CurrentTime());
-
- AnimationClock::NotifyTaskStart();
- animation_clock.UpdateTime(base::TimeTicks() +
- base::TimeDelta::FromSeconds(125));
- EXPECT_EQ(125, animation_clock.CurrentTime());
-}
-
-TEST_F(AnimationAnimationClockTest, UpdateTimeIsMonotonic) {
- animation_clock.UpdateTime(base::TimeTicks() +
- base::TimeDelta::FromSeconds(100));
- EXPECT_EQ(100, animation_clock.CurrentTime());
-
- // Update can't go backwards.
- animation_clock.UpdateTime(base::TimeTicks() +
- base::TimeDelta::FromSeconds(50));
- EXPECT_EQ(100, animation_clock.CurrentTime());
-
- mock_time_ = 50;
- AnimationClock::NotifyTaskStart();
- EXPECT_EQ(100, animation_clock.CurrentTime());
-
- mock_time_ = 150;
- AnimationClock::NotifyTaskStart();
- EXPECT_GE(animation_clock.CurrentTime(), mock_time_);
-
- // Update can't go backwards after advance to estimate.
- animation_clock.UpdateTime(base::TimeTicks() +
- base::TimeDelta::FromSeconds(100));
- EXPECT_GE(animation_clock.CurrentTime(), mock_time_);
-}
-
-TEST_F(AnimationAnimationClockTest, CurrentTimeUpdatesTask) {
- animation_clock.UpdateTime(base::TimeTicks() +
- base::TimeDelta::FromSeconds(100));
- EXPECT_EQ(100, animation_clock.CurrentTime());
-
- mock_time_ = 100;
- AnimationClock::NotifyTaskStart();
- EXPECT_EQ(100, animation_clock.CurrentTime());
-
- mock_time_ = 150;
- EXPECT_EQ(100, animation_clock.CurrentTime());
-}
-
-} // namespace blink
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 bc9cbfec1ef..a27cf06ea5a 100644
--- a/chromium/third_party/blink/renderer/core/animation/animation_effect.cc
+++ b/chromium/third_party/blink/renderer/core/animation/animation_effect.cc
@@ -39,19 +39,6 @@
namespace blink {
-namespace {
-
-Timing::FillMode ResolvedFillMode(Timing::FillMode fill_mode,
- bool is_animation) {
- if (fill_mode != Timing::FillMode::AUTO)
- return fill_mode;
- if (is_animation)
- return Timing::FillMode::NONE;
- return Timing::FillMode::BOTH;
-}
-
-} // namespace
-
AnimationEffect::AnimationEffect(const Timing& timing,
EventDelegate* event_delegate)
: owner_(nullptr),
@@ -63,27 +50,6 @@ AnimationEffect::AnimationEffect(const Timing& timing,
timing_.AssertValid();
}
-AnimationTimeDelta AnimationEffect::IterationDuration() const {
- AnimationTimeDelta result =
- timing_.iteration_duration.value_or(IntrinsicIterationDuration());
- DCHECK_GE(result, AnimationTimeDelta());
- return result;
-}
-
-double AnimationEffect::RepeatedDuration() const {
- const double result =
- MultiplyZeroAlwaysGivesZero(IterationDuration(), timing_.iteration_count);
- DCHECK_GE(result, 0);
- return result;
-}
-
-double AnimationEffect::EndTimeInternal() const {
- // Per the spec, the end time has a lower bound of 0.0:
- // https://drafts.csswg.org/web-animations-1/#end-time
- return std::max(timing_.start_delay + RepeatedDuration() + timing_.end_delay,
- 0.0);
-}
-
void AnimationEffect::UpdateSpecifiedTiming(const Timing& timing) {
// FIXME: Test whether the timing is actually different?
timing_ = timing;
@@ -95,46 +61,8 @@ EffectTiming* AnimationEffect::getTiming() const {
}
ComputedEffectTiming* AnimationEffect::getComputedTiming() const {
- ComputedEffectTiming* computed_timing = ComputedEffectTiming::Create();
-
- // ComputedEffectTiming members.
- computed_timing->setEndTime(EndTimeInternal() * 1000);
- computed_timing->setActiveDuration(RepeatedDuration() * 1000);
-
- if (IsNull(EnsureCalculated().local_time)) {
- computed_timing->setLocalTimeToNull();
- } else {
- computed_timing->setLocalTime(EnsureCalculated().local_time * 1000);
- }
-
- if (EnsureCalculated().is_in_effect) {
- computed_timing->setProgress(EnsureCalculated().progress.value());
- computed_timing->setCurrentIteration(EnsureCalculated().current_iteration);
- } else {
- 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(
- ResolvedFillMode(SpecifiedTiming().fill_mode, IsKeyframeEffect())));
- computed_timing->setIterationStart(SpecifiedTiming().iteration_start);
- computed_timing->setIterations(SpecifiedTiming().iteration_count);
-
- UnrestrictedDoubleOrString duration;
- duration.SetUnrestrictedDouble(IterationDuration().InMillisecondsF());
- computed_timing->setDuration(duration);
-
- computed_timing->setDirection(
- Timing::PlaybackDirectionString(SpecifiedTiming().direction));
- computed_timing->setEasing(SpecifiedTiming().timing_function->ToString());
-
- return computed_timing;
+ return SpecifiedTiming().getComputedTiming(EnsureCalculated(),
+ IsKeyframeEffect());
}
void AnimationEffect::updateTiming(OptionalEffectTiming* optional_timing,
@@ -159,23 +87,20 @@ void AnimationEffect::UpdateInheritedTime(double inherited_time,
const double local_time = inherited_time;
double time_to_next_iteration = std::numeric_limits<double>::infinity();
if (needs_update) {
- const double active_duration = RepeatedDuration();
- // TODO(yigu): Direction of WorkletAnimation is always forwards based on
- // the calculation. Need to unify the logic to handle it correctly.
- // https://crbug.com/896249.
+ const double active_duration = SpecifiedTiming().ActiveDuration();
const AnimationDirection direction =
(GetAnimation() && GetAnimation()->playbackRate() < 0) ? kBackwards
: kForwards;
- const Phase current_phase =
+ const Timing::Phase current_phase =
CalculatePhase(active_duration, local_time, direction, timing_);
const double active_time = CalculateActiveTime(
- active_duration,
- ResolvedFillMode(timing_.fill_mode, IsKeyframeEffect()), local_time,
- current_phase, timing_);
+ active_duration, timing_.ResolvedFillMode(IsKeyframeEffect()),
+ local_time, current_phase, timing_);
base::Optional<double> progress;
- const double iteration_duration = IterationDuration().InSecondsF();
+ const double iteration_duration =
+ SpecifiedTiming().IterationDuration().InSecondsF();
const double overall_progress = CalculateOverallProgress(
current_phase, active_time, iteration_duration, timing_.iteration_count,
@@ -217,7 +142,7 @@ void AnimationEffect::UpdateInheritedTime(double inherited_time,
}
const bool was_canceled = current_phase != calculated_.phase &&
- current_phase == AnimationEffect::kPhaseNone;
+ current_phase == Timing::kPhaseNone;
calculated_.phase = current_phase;
// If the animation was canceled, we need to fire the event condition before
// updating the timing so that the cancelation time can be determined.
@@ -228,8 +153,8 @@ void AnimationEffect::UpdateInheritedTime(double inherited_time,
calculated_.progress = progress;
calculated_.is_in_effect = !IsNull(active_time);
- calculated_.is_in_play = GetPhase() == kPhaseActive;
- calculated_.is_current = GetPhase() == kPhaseBefore || IsInPlay();
+ calculated_.is_in_play = GetPhase() == Timing::kPhaseActive;
+ calculated_.is_current = GetPhase() == Timing::kPhaseBefore || IsInPlay();
calculated_.local_time = last_update_time_;
}
@@ -259,8 +184,7 @@ void AnimationEffect::InvalidateAndNotifyOwner() const {
owner_->EffectInvalidated();
}
-const AnimationEffect::CalculatedTiming& AnimationEffect::EnsureCalculated()
- const {
+const Timing::CalculatedTiming& AnimationEffect::EnsureCalculated() const {
if (!owner_)
return calculated_;
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 5e64dc179cc..f1fb4a6ee11 100644
--- a/chromium/third_party/blink/renderer/core/animation/animation_effect.h
+++ b/chromium/third_party/blink/renderer/core/animation/animation_effect.h
@@ -53,14 +53,6 @@ enum TimingUpdateReason {
kTimingUpdateForAnimationFrame
};
-static inline bool IsNull(double value) {
- return std::isnan(value);
-}
-
-static inline double NullValue() {
- return std::numeric_limits<double>::quiet_NaN();
-}
-
// Represents the content of an Animation and its fractional timing state.
// https://drafts.csswg.org/web-animations/#the-animationeffect-interface
class CORE_EXPORT AnimationEffect : public ScriptWrappable {
@@ -75,13 +67,6 @@ class CORE_EXPORT AnimationEffect : public ScriptWrappable {
friend class EffectStack;
public:
- // Note that logic in CSSAnimations depends on the order of these values.
- enum Phase {
- kPhaseBefore,
- kPhaseActive,
- kPhaseAfter,
- kPhaseNone,
- };
// Represents the animation direction from the Web Animations spec, see
// https://drafts.csswg.org/web-animations-1/#animation-direction.
enum AnimationDirection {
@@ -102,7 +87,7 @@ class CORE_EXPORT AnimationEffect : public ScriptWrappable {
virtual bool IsKeyframeEffect() const { return false; }
virtual bool IsInertEffect() const { return false; }
- Phase GetPhase() const { return EnsureCalculated().phase; }
+ Timing::Phase GetPhase() const { return EnsureCalculated().phase; }
bool IsCurrent() const { return EnsureCalculated().is_current; }
bool IsInEffect() const { return EnsureCalculated().is_in_effect; }
bool IsInPlay() const { return EnsureCalculated().is_in_play; }
@@ -120,10 +105,6 @@ class CORE_EXPORT AnimationEffect : public ScriptWrappable {
}
double LocalTime() const { return EnsureCalculated().local_time; }
- AnimationTimeDelta IterationDuration() const;
- double RepeatedDuration() const;
- double EndTimeInternal() const;
-
const Timing& SpecifiedTiming() const { return timing_; }
void UpdateSpecifiedTiming(const Timing&);
EventDelegate* GetEventDelegate() { return event_delegate_; }
@@ -159,9 +140,15 @@ class CORE_EXPORT AnimationEffect : public ScriptWrappable {
void ClearEventDelegate() { event_delegate_ = nullptr; }
virtual void UpdateChildrenAndEffects() const = 0;
+
+ // This is the value of the iteration duration when it is specified as 'auto'.
+ // In web-animations-1, auto is treated as "the value zero for the purpose of
+ // timing model calculations and for the result of the duration member
+ // returned from getComputedTiming()".
virtual AnimationTimeDelta IntrinsicIterationDuration() const {
return AnimationTimeDelta();
}
+
virtual double CalculateTimeToEffectChange(
bool forwards,
double local_time,
@@ -174,22 +161,10 @@ class CORE_EXPORT AnimationEffect : public ScriptWrappable {
Timing timing_;
Member<EventDelegate> event_delegate_;
- mutable struct CalculatedTiming {
- DISALLOW_NEW();
- Phase phase;
- double current_iteration;
- base::Optional<double> progress;
- bool is_current;
- bool is_in_effect;
- bool is_in_play;
- double local_time = NullValue();
- double time_to_forwards_effect_change;
- double time_to_reverse_effect_change;
- } calculated_;
+ mutable Timing::CalculatedTiming calculated_;
mutable bool needs_update_;
mutable double last_update_time_;
-
- const CalculatedTiming& EnsureCalculated() const;
+ const Timing::CalculatedTiming& EnsureCalculated() const;
};
} // namespace blink
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 37203016513..d29b93837d7 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
@@ -130,42 +130,42 @@ TEST(AnimationAnimationEffectTest, Sanity) {
animation_node->UpdateInheritedTime(0);
- EXPECT_EQ(AnimationEffect::kPhaseActive, animation_node->GetPhase());
+ EXPECT_EQ(Timing::kPhaseActive, animation_node->GetPhase());
EXPECT_TRUE(animation_node->IsInPlay());
EXPECT_TRUE(animation_node->IsCurrent());
EXPECT_TRUE(animation_node->IsInEffect());
EXPECT_EQ(0, animation_node->CurrentIteration());
- EXPECT_EQ(2, animation_node->RepeatedDuration());
+ EXPECT_EQ(2, animation_node->SpecifiedTiming().ActiveDuration());
EXPECT_EQ(0, animation_node->Progress());
animation_node->UpdateInheritedTime(1);
- EXPECT_EQ(AnimationEffect::kPhaseActive, animation_node->GetPhase());
+ EXPECT_EQ(Timing::kPhaseActive, animation_node->GetPhase());
EXPECT_TRUE(animation_node->IsInPlay());
EXPECT_TRUE(animation_node->IsCurrent());
EXPECT_TRUE(animation_node->IsInEffect());
EXPECT_EQ(0, animation_node->CurrentIteration());
- EXPECT_EQ(2, animation_node->RepeatedDuration());
+ EXPECT_EQ(2, animation_node->SpecifiedTiming().ActiveDuration());
EXPECT_EQ(0.5, animation_node->Progress());
animation_node->UpdateInheritedTime(2);
- EXPECT_EQ(AnimationEffect::kPhaseAfter, animation_node->GetPhase());
+ EXPECT_EQ(Timing::kPhaseAfter, animation_node->GetPhase());
EXPECT_FALSE(animation_node->IsInPlay());
EXPECT_FALSE(animation_node->IsCurrent());
EXPECT_TRUE(animation_node->IsInEffect());
EXPECT_EQ(0, animation_node->CurrentIteration());
- EXPECT_EQ(2, animation_node->RepeatedDuration());
+ EXPECT_EQ(2, animation_node->SpecifiedTiming().ActiveDuration());
EXPECT_EQ(1, animation_node->Progress());
animation_node->UpdateInheritedTime(3);
- EXPECT_EQ(AnimationEffect::kPhaseAfter, animation_node->GetPhase());
+ EXPECT_EQ(Timing::kPhaseAfter, animation_node->GetPhase());
EXPECT_FALSE(animation_node->IsInPlay());
EXPECT_FALSE(animation_node->IsCurrent());
EXPECT_TRUE(animation_node->IsInEffect());
EXPECT_EQ(0, animation_node->CurrentIteration());
- EXPECT_EQ(2, animation_node->RepeatedDuration());
+ EXPECT_EQ(2, animation_node->SpecifiedTiming().ActiveDuration());
EXPECT_EQ(1, animation_node->Progress());
}
@@ -245,12 +245,12 @@ TEST(AnimationAnimationEffectTest, ZeroIteration) {
auto* animation_node = MakeGarbageCollected<TestAnimationEffect>(timing);
animation_node->UpdateInheritedTime(-1);
- EXPECT_EQ(0, animation_node->RepeatedDuration());
+ EXPECT_EQ(0, animation_node->SpecifiedTiming().ActiveDuration());
EXPECT_TRUE(IsNull(animation_node->CurrentIteration()));
EXPECT_FALSE(animation_node->Progress());
animation_node->UpdateInheritedTime(0);
- EXPECT_EQ(0, animation_node->RepeatedDuration());
+ EXPECT_EQ(0, animation_node->SpecifiedTiming().ActiveDuration());
EXPECT_EQ(0, animation_node->CurrentIteration());
EXPECT_EQ(0, animation_node->Progress());
}
@@ -267,7 +267,7 @@ TEST(AnimationAnimationEffectTest, InfiniteIteration) {
EXPECT_FALSE(animation_node->Progress());
EXPECT_EQ(std::numeric_limits<double>::infinity(),
- animation_node->RepeatedDuration());
+ animation_node->SpecifiedTiming().ActiveDuration());
animation_node->UpdateInheritedTime(0);
EXPECT_EQ(0, animation_node->CurrentIteration());
@@ -368,22 +368,22 @@ TEST(AnimationAnimationEffectTest, ZeroDurationSanity) {
animation_node->UpdateInheritedTime(0);
- EXPECT_EQ(AnimationEffect::kPhaseAfter, animation_node->GetPhase());
+ EXPECT_EQ(Timing::kPhaseAfter, animation_node->GetPhase());
EXPECT_FALSE(animation_node->IsInPlay());
EXPECT_FALSE(animation_node->IsCurrent());
EXPECT_TRUE(animation_node->IsInEffect());
EXPECT_EQ(0, animation_node->CurrentIteration());
- EXPECT_EQ(0, animation_node->RepeatedDuration());
+ EXPECT_EQ(0, animation_node->SpecifiedTiming().ActiveDuration());
EXPECT_EQ(1, animation_node->Progress());
animation_node->UpdateInheritedTime(1);
- EXPECT_EQ(AnimationEffect::kPhaseAfter, animation_node->GetPhase());
+ EXPECT_EQ(Timing::kPhaseAfter, animation_node->GetPhase());
EXPECT_FALSE(animation_node->IsInPlay());
EXPECT_FALSE(animation_node->IsCurrent());
EXPECT_TRUE(animation_node->IsInEffect());
EXPECT_EQ(0, animation_node->CurrentIteration());
- EXPECT_EQ(0, animation_node->RepeatedDuration());
+ EXPECT_EQ(0, animation_node->SpecifiedTiming().ActiveDuration());
EXPECT_EQ(1, animation_node->Progress());
}
@@ -474,12 +474,12 @@ TEST(AnimationAnimationEffectTest, ZeroDurationInfiniteIteration) {
auto* animation_node = MakeGarbageCollected<TestAnimationEffect>(timing);
animation_node->UpdateInheritedTime(-1);
- EXPECT_EQ(0, animation_node->RepeatedDuration());
+ EXPECT_EQ(0, animation_node->SpecifiedTiming().ActiveDuration());
EXPECT_TRUE(IsNull(animation_node->CurrentIteration()));
EXPECT_FALSE(animation_node->Progress());
animation_node->UpdateInheritedTime(0);
- EXPECT_EQ(0, animation_node->RepeatedDuration());
+ EXPECT_EQ(0, animation_node->SpecifiedTiming().ActiveDuration());
EXPECT_EQ(std::numeric_limits<double>::infinity(),
animation_node->CurrentIteration());
EXPECT_EQ(1, animation_node->Progress());
@@ -573,8 +573,8 @@ TEST(AnimationAnimationEffectTest, InfiniteDurationSanity) {
animation_node->UpdateInheritedTime(0);
EXPECT_EQ(std::numeric_limits<double>::infinity(),
- animation_node->RepeatedDuration());
- EXPECT_EQ(AnimationEffect::kPhaseActive, animation_node->GetPhase());
+ animation_node->SpecifiedTiming().ActiveDuration());
+ EXPECT_EQ(Timing::kPhaseActive, animation_node->GetPhase());
EXPECT_TRUE(animation_node->IsInPlay());
EXPECT_TRUE(animation_node->IsCurrent());
EXPECT_TRUE(animation_node->IsInEffect());
@@ -584,8 +584,8 @@ TEST(AnimationAnimationEffectTest, InfiniteDurationSanity) {
animation_node->UpdateInheritedTime(1);
EXPECT_EQ(std::numeric_limits<double>::infinity(),
- animation_node->RepeatedDuration());
- EXPECT_EQ(AnimationEffect::kPhaseActive, animation_node->GetPhase());
+ animation_node->SpecifiedTiming().ActiveDuration());
+ EXPECT_EQ(Timing::kPhaseActive, animation_node->GetPhase());
EXPECT_TRUE(animation_node->IsInPlay());
EXPECT_TRUE(animation_node->IsCurrent());
EXPECT_TRUE(animation_node->IsInEffect());
@@ -602,8 +602,8 @@ TEST(AnimationAnimationEffectTest, InfiniteDurationZeroIterations) {
animation_node->UpdateInheritedTime(0);
- EXPECT_EQ(0, animation_node->RepeatedDuration());
- EXPECT_EQ(AnimationEffect::kPhaseAfter, animation_node->GetPhase());
+ EXPECT_EQ(0, animation_node->SpecifiedTiming().ActiveDuration());
+ EXPECT_EQ(Timing::kPhaseAfter, animation_node->GetPhase());
EXPECT_FALSE(animation_node->IsInPlay());
EXPECT_FALSE(animation_node->IsCurrent());
EXPECT_TRUE(animation_node->IsInEffect());
@@ -612,8 +612,8 @@ TEST(AnimationAnimationEffectTest, InfiniteDurationZeroIterations) {
animation_node->UpdateInheritedTime(1);
- EXPECT_EQ(AnimationEffect::kPhaseAfter, animation_node->GetPhase());
- EXPECT_EQ(AnimationEffect::kPhaseAfter, animation_node->GetPhase());
+ EXPECT_EQ(Timing::kPhaseAfter, animation_node->GetPhase());
+ EXPECT_EQ(Timing::kPhaseAfter, animation_node->GetPhase());
EXPECT_FALSE(animation_node->IsInPlay());
EXPECT_FALSE(animation_node->IsCurrent());
EXPECT_TRUE(animation_node->IsInEffect());
@@ -630,8 +630,8 @@ TEST(AnimationAnimationEffectTest, InfiniteDurationInfiniteIterations) {
animation_node->UpdateInheritedTime(0);
EXPECT_EQ(std::numeric_limits<double>::infinity(),
- animation_node->RepeatedDuration());
- EXPECT_EQ(AnimationEffect::kPhaseActive, animation_node->GetPhase());
+ animation_node->SpecifiedTiming().ActiveDuration());
+ EXPECT_EQ(Timing::kPhaseActive, animation_node->GetPhase());
EXPECT_TRUE(animation_node->IsInPlay());
EXPECT_TRUE(animation_node->IsCurrent());
EXPECT_TRUE(animation_node->IsInEffect());
@@ -641,8 +641,8 @@ TEST(AnimationAnimationEffectTest, InfiniteDurationInfiniteIterations) {
animation_node->UpdateInheritedTime(1);
EXPECT_EQ(std::numeric_limits<double>::infinity(),
- animation_node->RepeatedDuration());
- EXPECT_EQ(AnimationEffect::kPhaseActive, animation_node->GetPhase());
+ animation_node->SpecifiedTiming().ActiveDuration());
+ EXPECT_EQ(Timing::kPhaseActive, animation_node->GetPhase());
EXPECT_TRUE(animation_node->IsInPlay());
EXPECT_TRUE(animation_node->IsCurrent());
EXPECT_TRUE(animation_node->IsInEffect());
@@ -657,7 +657,7 @@ TEST(AnimationAnimationEffectTest, EndTime) {
timing.iteration_duration = AnimationTimeDelta::FromSecondsD(4);
timing.iteration_count = 2;
auto* animation_node = MakeGarbageCollected<TestAnimationEffect>(timing);
- EXPECT_EQ(11, animation_node->EndTimeInternal());
+ EXPECT_EQ(11, animation_node->SpecifiedTiming().EndTimeInternal());
}
TEST(AnimationAnimationEffectTest, Events) {
@@ -709,13 +709,13 @@ TEST(AnimationAnimationEffectTest, TimeToEffectChange) {
// Item ends before iteration finishes.
animation_node->UpdateInheritedTime(3.4);
- EXPECT_EQ(AnimationEffect::kPhaseActive, animation_node->GetPhase());
+ EXPECT_EQ(Timing::kPhaseActive, animation_node->GetPhase());
EXPECT_EQ(3.4, animation_node->TakeLocalTime());
EXPECT_TRUE(std::isinf(animation_node->TakeTimeToNextIteration()));
// Item has finished.
animation_node->UpdateInheritedTime(3.5);
- EXPECT_EQ(AnimationEffect::kPhaseAfter, animation_node->GetPhase());
+ EXPECT_EQ(Timing::kPhaseAfter, animation_node->GetPhase());
EXPECT_EQ(3.5, animation_node->TakeLocalTime());
EXPECT_TRUE(std::isinf(animation_node->TakeTimeToNextIteration()));
}
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 f542174a70b..99816032fc2 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
@@ -222,7 +222,7 @@ const QualifiedName* AnimationInputHelpers::KeyframeAttributeToSVGAttribute(
!IsSVGPrefixed(property))
return nullptr;
- if (IsSVGSMILElement(svg_element))
+ if (IsA<SVGSMILElement>(svg_element))
return nullptr;
String unprefixed_property = RemoveSVGPrefix(property);
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 1ea358cf30d..787cc7691fb 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
@@ -7,7 +7,7 @@
#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/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
namespace blink {
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 aed787727f6..9b5d232b2e9 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
@@ -3,7 +3,7 @@
// found in the LICENSE file.
#include "third_party/blink/public/web/web_script_source.h"
-#include "third_party/blink/renderer/core/animation/element_animation.h"
+#include "third_party/blink/renderer/core/animation/animatable.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"
@@ -37,8 +37,6 @@ TEST_F(AnimationSimTest, CustomPropertyBaseComputedStyle) {
ScopedStackedCSSPropertyAnimationsForTest stacked_css_property_animation(
true);
- WebView().GetPage()->Animator().Clock().DisableSyntheticTimeForTesting();
-
SimRequest main_resource("https://example.com/", "text/html");
LoadURL("https://example.com/");
main_resource.Complete("<div id=\"target\"></div>");
@@ -68,14 +66,14 @@ TEST_F(AnimationSimTest, CustomPropertyBaseComputedStyle) {
// target.animate({'--x': '100%'}, 1000);
auto* keyframe = MakeGarbageCollected<StringKeyframe>();
- keyframe->SetCSSPropertyValue("--x", GetDocument().GetPropertyRegistry(),
- "100%", GetDocument().GetSecureContextMode(),
+ keyframe->SetCSSPropertyValue("--x", "100%",
+ GetDocument().GetSecureContextMode(),
GetDocument().ElementSheet().Contents());
StringKeyframeVector keyframes;
keyframes.push_back(keyframe);
Timing timing;
timing.iteration_duration = AnimationTimeDelta::FromSecondsD(1);
- ElementAnimation::animateInternal(
+ Animatable::animateInternal(
*target, MakeGarbageCollected<StringKeyframeEffectModel>(keyframes),
timing);
@@ -90,14 +88,14 @@ TEST_F(AnimationSimTest, CustomPropertyBaseComputedStyle) {
// target.animate({'--x': '100%'}, 1000);
keyframe = MakeGarbageCollected<StringKeyframe>();
- keyframe->SetCSSPropertyValue("--x", GetDocument().GetPropertyRegistry(),
- "100%", GetDocument().GetSecureContextMode(),
+ keyframe->SetCSSPropertyValue("--x", "100%",
+ GetDocument().GetSecureContextMode(),
GetDocument().ElementSheet().Contents());
keyframes.clear();
keyframes.push_back(std::move(keyframe));
- timing = Timing::Defaults();
+ timing = Timing();
timing.iteration_duration = AnimationTimeDelta::FromSecondsD(1);
- ElementAnimation::animateInternal(
+ Animatable::animateInternal(
*target, MakeGarbageCollected<StringKeyframeEffectModel>(keyframes),
timing);
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 c9e49edbdc8..a6b0f84a9aa 100644
--- a/chromium/third_party/blink/renderer/core/animation/animation_test.cc
+++ b/chromium/third_party/blink/renderer/core/animation/animation_test.cc
@@ -42,12 +42,13 @@
#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/pending_animations.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/dom/dom_node_ids.h"
#include "third_party/blink/renderer/core/dom/qualified_name.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/heap/heap.h"
#include "third_party/blink/renderer/platform/testing/histogram_tester.h"
#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
@@ -55,9 +56,9 @@
namespace blink {
-class AnimationAnimationTest : public RenderingTest {
+class AnimationAnimationTestNoCompositing : public RenderingTest {
public:
- AnimationAnimationTest()
+ AnimationAnimationTestNoCompositing()
: RenderingTest(MakeGarbageCollected<SingleChildLocalFrameClient>()) {}
void SetUp() override {
@@ -67,10 +68,8 @@ class AnimationAnimationTest : public RenderingTest {
}
void SetUpWithoutStartingTimeline() {
- page_holder = std::make_unique<DummyPageHolder>();
- document = &page_holder->GetDocument();
- document->GetAnimationClock().ResetTimeForTesting();
- timeline = DocumentTimeline::Create(document.Get());
+ GetDocument().GetAnimationClock().ResetTimeForTesting();
+ timeline = GetDocument().Timeline();
timeline->ResetForTesting();
animation = timeline->Play(nullptr);
animation->setStartTime(0, false);
@@ -111,7 +110,7 @@ class AnimationAnimationTest : public RenderingTest {
// Get rid of the default animation.
animation->cancel();
- EnableCompositing();
+ RunDocumentLifecycle();
SetBodyInnerHTML("<div id='target'></div>");
@@ -143,8 +142,8 @@ class AnimationAnimationTest : public RenderingTest {
// animation can be pushed to the compositor.
UpdateAllLifecyclePhasesForTest();
- document->GetAnimationClock().UpdateTime(base::TimeTicks());
- document->GetPendingAnimations().Update(nullptr, true);
+ GetDocument().GetAnimationClock().UpdateTime(base::TimeTicks());
+ GetDocument().GetPendingAnimations().Update(nullptr, true);
}
KeyframeEffectModelBase* MakeEmptyEffectModel() {
@@ -163,24 +162,43 @@ class AnimationAnimationTest : public RenderingTest {
const PaintArtifactCompositor* paint_artifact_compositor = nullptr;
if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled() ||
RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) {
- paint_artifact_compositor =
- document->GetFrame()->View()->GetPaintArtifactCompositorForTesting();
+ paint_artifact_compositor = GetDocument()
+ .GetFrame()
+ ->View()
+ ->GetPaintArtifactCompositorForTesting();
}
- document->GetAnimationClock().UpdateTime(
+ GetDocument().GetAnimationClock().UpdateTime(
base::TimeTicks() + base::TimeDelta::FromSecondsD(time));
- document->GetPendingAnimations().Update(paint_artifact_compositor, false);
+ GetDocument().GetPendingAnimations().Update(paint_artifact_compositor,
+ false);
// The timeline does not know about our animation, so we have to explicitly
// call update().
return animation->Update(kTimingUpdateForAnimationFrame);
}
- Persistent<Document> document;
Persistent<DocumentTimeline> timeline;
Persistent<Animation> animation;
- std::unique_ptr<DummyPageHolder> page_holder;
};
-TEST_F(AnimationAnimationTest, InitialState) {
+class AnimationAnimationTestCompositing
+ : public AnimationAnimationTestNoCompositing {
+ void SetUp() override {
+ EnableCompositing();
+ AnimationAnimationTestNoCompositing::SetUp();
+ }
+};
+
+class AnimationAnimationTestCompositeAfterPaint
+ : public AnimationAnimationTestNoCompositing {
+ void SetUp() override {
+ EnableCompositing();
+ AnimationAnimationTestNoCompositing::SetUp();
+ }
+
+ ScopedCompositeAfterPaintForTest enable_cap{true};
+};
+
+TEST_F(AnimationAnimationTestNoCompositing, InitialState) {
SetUpWithoutStartingTimeline();
animation = timeline->Play(nullptr);
EXPECT_EQ(Animation::kPending, animation->PlayStateInternal());
@@ -198,20 +216,20 @@ TEST_F(AnimationAnimationTest, InitialState) {
EXPECT_EQ(0, animation->StartTimeInternal());
}
-TEST_F(AnimationAnimationTest, CurrentTimeDoesNotSetOutdated) {
+TEST_F(AnimationAnimationTestNoCompositing, CurrentTimeDoesNotSetOutdated) {
EXPECT_FALSE(animation->Outdated());
EXPECT_EQ(0, animation->CurrentTimeInternal());
EXPECT_FALSE(animation->Outdated());
// FIXME: We should split simulateFrame into a version that doesn't update
// the animation and one that does, as most of the tests don't require
// update() to be called.
- document->GetAnimationClock().UpdateTime(base::TimeTicks() +
- base::TimeDelta::FromSecondsD(10));
+ GetDocument().GetAnimationClock().UpdateTime(
+ base::TimeTicks() + base::TimeDelta::FromSecondsD(10));
EXPECT_EQ(10, animation->CurrentTimeInternal());
EXPECT_FALSE(animation->Outdated());
}
-TEST_F(AnimationAnimationTest, SetCurrentTime) {
+TEST_F(AnimationAnimationTestNoCompositing, SetCurrentTime) {
EXPECT_EQ(Animation::kRunning, animation->PlayStateInternal());
animation->SetCurrentTimeInternal(10);
EXPECT_EQ(Animation::kRunning, animation->PlayStateInternal());
@@ -221,7 +239,7 @@ TEST_F(AnimationAnimationTest, SetCurrentTime) {
EXPECT_EQ(20, animation->CurrentTimeInternal());
}
-TEST_F(AnimationAnimationTest, SetCurrentTimeNegative) {
+TEST_F(AnimationAnimationTestNoCompositing, SetCurrentTimeNegative) {
animation->SetCurrentTimeInternal(-10);
EXPECT_EQ(Animation::kRunning, animation->PlayStateInternal());
EXPECT_EQ(-10, animation->CurrentTimeInternal());
@@ -237,7 +255,7 @@ TEST_F(AnimationAnimationTest, SetCurrentTimeNegative) {
EXPECT_EQ(-10, animation->CurrentTimeInternal());
}
-TEST_F(AnimationAnimationTest,
+TEST_F(AnimationAnimationTestNoCompositing,
SetCurrentTimeNegativeWithoutSimultaneousPlaybackRateChange) {
SimulateFrame(20);
EXPECT_EQ(20, animation->CurrentTimeInternal());
@@ -251,7 +269,7 @@ TEST_F(AnimationAnimationTest,
EXPECT_EQ(Animation::kFinished, animation->PlayStateInternal());
}
-TEST_F(AnimationAnimationTest, SetCurrentTimePastContentEnd) {
+TEST_F(AnimationAnimationTestNoCompositing, SetCurrentTimePastContentEnd) {
animation->setCurrentTime(50 * 1000, false);
EXPECT_EQ(Animation::kFinished, animation->PlayStateInternal());
EXPECT_EQ(50, animation->CurrentTimeInternal());
@@ -269,7 +287,7 @@ TEST_F(AnimationAnimationTest, SetCurrentTimePastContentEnd) {
EXPECT_EQ(10, animation->CurrentTimeInternal());
}
-TEST_F(AnimationAnimationTest, SetCurrentTimeMax) {
+TEST_F(AnimationAnimationTestNoCompositing, SetCurrentTimeMax) {
animation->SetCurrentTimeInternal(std::numeric_limits<double>::max());
EXPECT_EQ(std::numeric_limits<double>::max(),
animation->CurrentTimeInternal());
@@ -278,7 +296,7 @@ TEST_F(AnimationAnimationTest, SetCurrentTimeMax) {
animation->CurrentTimeInternal());
}
-TEST_F(AnimationAnimationTest, SetCurrentTimeSetsStartTime) {
+TEST_F(AnimationAnimationTestNoCompositing, SetCurrentTimeSetsStartTime) {
EXPECT_EQ(0, animation->startTime());
animation->setCurrentTime(1000, false);
EXPECT_EQ(-1000, animation->startTime());
@@ -287,7 +305,7 @@ TEST_F(AnimationAnimationTest, SetCurrentTimeSetsStartTime) {
EXPECT_EQ(2000, animation->currentTime());
}
-TEST_F(AnimationAnimationTest, SetStartTime) {
+TEST_F(AnimationAnimationTestNoCompositing, SetStartTime) {
SimulateFrame(20);
EXPECT_EQ(Animation::kRunning, animation->PlayStateInternal());
EXPECT_EQ(0, animation->StartTimeInternal());
@@ -303,7 +321,7 @@ TEST_F(AnimationAnimationTest, SetStartTime) {
EXPECT_EQ(Animation::kFinished, animation->PlayStateInternal());
}
-TEST_F(AnimationAnimationTest, SetStartTimeLimitsAnimation) {
+TEST_F(AnimationAnimationTestNoCompositing, SetStartTimeLimitsAnimation) {
animation->setStartTime(-50 * 1000, false);
EXPECT_EQ(Animation::kFinished, animation->PlayStateInternal());
EXPECT_EQ(30, animation->CurrentTimeInternal());
@@ -315,7 +333,7 @@ TEST_F(AnimationAnimationTest, SetStartTimeLimitsAnimation) {
EXPECT_TRUE(animation->Limited());
}
-TEST_F(AnimationAnimationTest, SetStartTimeOnLimitedAnimation) {
+TEST_F(AnimationAnimationTestNoCompositing, SetStartTimeOnLimitedAnimation) {
SimulateFrame(30);
animation->setStartTime(-10 * 1000, false);
EXPECT_EQ(Animation::kFinished, animation->PlayStateInternal());
@@ -327,7 +345,7 @@ TEST_F(AnimationAnimationTest, SetStartTimeOnLimitedAnimation) {
EXPECT_TRUE(animation->Limited());
}
-TEST_F(AnimationAnimationTest, StartTimePauseFinish) {
+TEST_F(AnimationAnimationTestNoCompositing, StartTimePauseFinish) {
NonThrowableExceptionState exception_state;
animation->pause();
EXPECT_EQ(Animation::kPending, animation->PlayStateInternal());
@@ -337,7 +355,7 @@ TEST_F(AnimationAnimationTest, StartTimePauseFinish) {
EXPECT_EQ(-30000, animation->startTime());
}
-TEST_F(AnimationAnimationTest, FinishWhenPaused) {
+TEST_F(AnimationAnimationTestNoCompositing, FinishWhenPaused) {
NonThrowableExceptionState exception_state;
animation->pause();
EXPECT_EQ(Animation::kPending, animation->PlayStateInternal());
@@ -347,7 +365,7 @@ TEST_F(AnimationAnimationTest, FinishWhenPaused) {
EXPECT_EQ(Animation::kFinished, animation->PlayStateInternal());
}
-TEST_F(AnimationAnimationTest, StartTimeFinishPause) {
+TEST_F(AnimationAnimationTestNoCompositing, StartTimeFinishPause) {
NonThrowableExceptionState exception_state;
animation->finish(exception_state);
EXPECT_EQ(-30 * 1000, animation->startTime());
@@ -355,7 +373,7 @@ TEST_F(AnimationAnimationTest, StartTimeFinishPause) {
EXPECT_FALSE(animation->startTime());
}
-TEST_F(AnimationAnimationTest, StartTimeWithZeroPlaybackRate) {
+TEST_F(AnimationAnimationTestNoCompositing, StartTimeWithZeroPlaybackRate) {
animation->setPlaybackRate(0);
EXPECT_EQ(Animation::kPending, animation->PlayStateInternal());
EXPECT_FALSE(animation->startTime());
@@ -363,7 +381,7 @@ TEST_F(AnimationAnimationTest, StartTimeWithZeroPlaybackRate) {
EXPECT_EQ(Animation::kRunning, animation->PlayStateInternal());
}
-TEST_F(AnimationAnimationTest, PausePlay) {
+TEST_F(AnimationAnimationTestNoCompositing, PausePlay) {
SimulateFrame(10);
animation->pause();
EXPECT_EQ(Animation::kPending, animation->PlayStateInternal());
@@ -381,7 +399,7 @@ TEST_F(AnimationAnimationTest, PausePlay) {
EXPECT_EQ(20, animation->CurrentTimeInternal());
}
-TEST_F(AnimationAnimationTest, PlayRewindsToStart) {
+TEST_F(AnimationAnimationTestNoCompositing, PlayRewindsToStart) {
animation->SetCurrentTimeInternal(30);
animation->play();
EXPECT_EQ(0, animation->CurrentTimeInternal());
@@ -402,7 +420,7 @@ TEST_F(AnimationAnimationTest, PlayRewindsToStart) {
EXPECT_EQ(Animation::kRunning, animation->PlayStateInternal());
}
-TEST_F(AnimationAnimationTest, PlayRewindsToEnd) {
+TEST_F(AnimationAnimationTestNoCompositing, PlayRewindsToEnd) {
animation->setPlaybackRate(-1);
animation->play();
EXPECT_EQ(30, animation->CurrentTimeInternal());
@@ -423,7 +441,8 @@ TEST_F(AnimationAnimationTest, PlayRewindsToEnd) {
EXPECT_EQ(Animation::kRunning, animation->PlayStateInternal());
}
-TEST_F(AnimationAnimationTest, PlayWithPlaybackRateZeroDoesNotSeek) {
+TEST_F(AnimationAnimationTestNoCompositing,
+ PlayWithPlaybackRateZeroDoesNotSeek) {
animation->setPlaybackRate(0);
animation->play();
EXPECT_EQ(0, animation->CurrentTimeInternal());
@@ -437,7 +456,7 @@ TEST_F(AnimationAnimationTest, PlayWithPlaybackRateZeroDoesNotSeek) {
EXPECT_EQ(-10, animation->CurrentTimeInternal());
}
-TEST_F(AnimationAnimationTest,
+TEST_F(AnimationAnimationTestNoCompositing,
PlayAfterPauseWithPlaybackRateZeroUpdatesPlayState) {
animation->pause();
animation->setPlaybackRate(0);
@@ -447,7 +466,7 @@ TEST_F(AnimationAnimationTest,
EXPECT_EQ(Animation::kRunning, animation->PlayStateInternal());
}
-TEST_F(AnimationAnimationTest, Reverse) {
+TEST_F(AnimationAnimationTestNoCompositing, Reverse) {
animation->SetCurrentTimeInternal(10);
animation->pause();
animation->reverse();
@@ -460,7 +479,8 @@ TEST_F(AnimationAnimationTest, Reverse) {
EXPECT_EQ(-1, animation->playbackRate());
}
-TEST_F(AnimationAnimationTest, ReverseDoesNothingWithPlaybackRateZero) {
+TEST_F(AnimationAnimationTestNoCompositing,
+ ReverseDoesNothingWithPlaybackRateZero) {
animation->SetCurrentTimeInternal(10);
animation->setPlaybackRate(0);
animation->pause();
@@ -470,20 +490,20 @@ TEST_F(AnimationAnimationTest, ReverseDoesNothingWithPlaybackRateZero) {
EXPECT_EQ(10, animation->CurrentTimeInternal());
}
-TEST_F(AnimationAnimationTest, ReverseSeeksToStart) {
+TEST_F(AnimationAnimationTestNoCompositing, ReverseSeeksToStart) {
animation->SetCurrentTimeInternal(-10);
animation->setPlaybackRate(-1);
animation->reverse();
EXPECT_EQ(0, animation->CurrentTimeInternal());
}
-TEST_F(AnimationAnimationTest, ReverseSeeksToEnd) {
+TEST_F(AnimationAnimationTestNoCompositing, ReverseSeeksToEnd) {
animation->setCurrentTime(40 * 1000, false);
animation->reverse();
EXPECT_EQ(30, animation->CurrentTimeInternal());
}
-TEST_F(AnimationAnimationTest, ReverseBeyondLimit) {
+TEST_F(AnimationAnimationTestNoCompositing, ReverseBeyondLimit) {
animation->SetCurrentTimeInternal(40);
animation->setPlaybackRate(-1);
animation->reverse();
@@ -496,7 +516,7 @@ TEST_F(AnimationAnimationTest, ReverseBeyondLimit) {
EXPECT_EQ(30, animation->CurrentTimeInternal());
}
-TEST_F(AnimationAnimationTest, Finish) {
+TEST_F(AnimationAnimationTestNoCompositing, Finish) {
NonThrowableExceptionState exception_state;
animation->finish(exception_state);
EXPECT_EQ(30, animation->CurrentTimeInternal());
@@ -508,14 +528,14 @@ TEST_F(AnimationAnimationTest, Finish) {
EXPECT_EQ(Animation::kFinished, animation->PlayStateInternal());
}
-TEST_F(AnimationAnimationTest, FinishAfterEffectEnd) {
+TEST_F(AnimationAnimationTestNoCompositing, FinishAfterEffectEnd) {
NonThrowableExceptionState exception_state;
animation->setCurrentTime(40 * 1000, false);
animation->finish(exception_state);
EXPECT_EQ(40, animation->CurrentTimeInternal());
}
-TEST_F(AnimationAnimationTest, FinishBeforeStart) {
+TEST_F(AnimationAnimationTestNoCompositing, FinishBeforeStart) {
NonThrowableExceptionState exception_state;
animation->SetCurrentTimeInternal(-10);
animation->setPlaybackRate(-1);
@@ -523,7 +543,8 @@ TEST_F(AnimationAnimationTest, FinishBeforeStart) {
EXPECT_EQ(0, animation->CurrentTimeInternal());
}
-TEST_F(AnimationAnimationTest, FinishDoesNothingWithPlaybackRateZero) {
+TEST_F(AnimationAnimationTestNoCompositing,
+ FinishDoesNothingWithPlaybackRateZero) {
DummyExceptionStateForTesting exception_state;
animation->SetCurrentTimeInternal(10);
animation->setPlaybackRate(0);
@@ -532,7 +553,7 @@ TEST_F(AnimationAnimationTest, FinishDoesNothingWithPlaybackRateZero) {
EXPECT_TRUE(exception_state.HadException());
}
-TEST_F(AnimationAnimationTest, FinishRaisesException) {
+TEST_F(AnimationAnimationTestNoCompositing, FinishRaisesException) {
Timing timing;
timing.iteration_duration = AnimationTimeDelta::FromSecondsD(1);
timing.iteration_count = std::numeric_limits<double>::infinity();
@@ -548,7 +569,7 @@ TEST_F(AnimationAnimationTest, FinishRaisesException) {
exception_state.CodeAs<DOMExceptionCode>());
}
-TEST_F(AnimationAnimationTest, LimitingAtEffectEnd) {
+TEST_F(AnimationAnimationTestNoCompositing, LimitingAtEffectEnd) {
SimulateFrame(30);
EXPECT_EQ(30, animation->CurrentTimeInternal());
EXPECT_TRUE(animation->Limited());
@@ -557,7 +578,7 @@ TEST_F(AnimationAnimationTest, LimitingAtEffectEnd) {
EXPECT_FALSE(animation->Paused());
}
-TEST_F(AnimationAnimationTest, LimitingAtStart) {
+TEST_F(AnimationAnimationTestNoCompositing, LimitingAtStart) {
SimulateFrame(30);
animation->setPlaybackRate(-2);
SimulateFrame(30);
@@ -569,14 +590,14 @@ TEST_F(AnimationAnimationTest, LimitingAtStart) {
EXPECT_FALSE(animation->Paused());
}
-TEST_F(AnimationAnimationTest, LimitingWithNoEffect) {
+TEST_F(AnimationAnimationTestNoCompositing, LimitingWithNoEffect) {
animation->setEffect(nullptr);
EXPECT_TRUE(animation->Limited());
SimulateFrame(30);
EXPECT_EQ(0, animation->CurrentTimeInternal());
}
-TEST_F(AnimationAnimationTest, SetPlaybackRate) {
+TEST_F(AnimationAnimationTestNoCompositing, SetPlaybackRate) {
animation->setPlaybackRate(2);
SimulateFrame(0);
EXPECT_EQ(2, animation->playbackRate());
@@ -585,7 +606,7 @@ TEST_F(AnimationAnimationTest, SetPlaybackRate) {
EXPECT_EQ(20, animation->CurrentTimeInternal());
}
-TEST_F(AnimationAnimationTest, SetPlaybackRateWhilePaused) {
+TEST_F(AnimationAnimationTestNoCompositing, SetPlaybackRateWhilePaused) {
SimulateFrame(10);
animation->pause();
animation->setPlaybackRate(2);
@@ -597,7 +618,7 @@ TEST_F(AnimationAnimationTest, SetPlaybackRateWhilePaused) {
EXPECT_EQ(20, animation->CurrentTimeInternal());
}
-TEST_F(AnimationAnimationTest, SetPlaybackRateWhileLimited) {
+TEST_F(AnimationAnimationTestNoCompositing, SetPlaybackRateWhileLimited) {
SimulateFrame(40);
EXPECT_EQ(30, animation->CurrentTimeInternal());
animation->setPlaybackRate(2);
@@ -610,7 +631,7 @@ TEST_F(AnimationAnimationTest, SetPlaybackRateWhileLimited) {
EXPECT_EQ(10, animation->CurrentTimeInternal());
}
-TEST_F(AnimationAnimationTest, SetPlaybackRateZero) {
+TEST_F(AnimationAnimationTestNoCompositing, SetPlaybackRateZero) {
SimulateFrame(0);
SimulateFrame(10);
animation->setPlaybackRate(0);
@@ -622,7 +643,7 @@ TEST_F(AnimationAnimationTest, SetPlaybackRateZero) {
EXPECT_EQ(20, animation->CurrentTimeInternal());
}
-TEST_F(AnimationAnimationTest, SetPlaybackRateMax) {
+TEST_F(AnimationAnimationTestNoCompositing, SetPlaybackRateMax) {
animation->setPlaybackRate(std::numeric_limits<double>::max());
SimulateFrame(0);
EXPECT_EQ(std::numeric_limits<double>::max(), animation->playbackRate());
@@ -631,7 +652,7 @@ TEST_F(AnimationAnimationTest, SetPlaybackRateMax) {
EXPECT_EQ(30, animation->CurrentTimeInternal());
}
-TEST_F(AnimationAnimationTest, UpdatePlaybackRate) {
+TEST_F(AnimationAnimationTestNoCompositing, UpdatePlaybackRate) {
animation->updatePlaybackRate(2);
EXPECT_EQ(1, animation->playbackRate());
@@ -643,7 +664,7 @@ TEST_F(AnimationAnimationTest, UpdatePlaybackRate) {
EXPECT_EQ(20, animation->CurrentTimeInternal());
}
-TEST_F(AnimationAnimationTest, UpdatePlaybackRateWhilePaused) {
+TEST_F(AnimationAnimationTestNoCompositing, UpdatePlaybackRateWhilePaused) {
animation->pause();
// Pending playback rate on pending-paused animation is picked up after async
@@ -663,7 +684,7 @@ TEST_F(AnimationAnimationTest, UpdatePlaybackRateWhilePaused) {
EXPECT_EQ(3, animation->playbackRate());
}
-TEST_F(AnimationAnimationTest, UpdatePlaybackRateWhileLimited) {
+TEST_F(AnimationAnimationTestNoCompositing, UpdatePlaybackRateWhileLimited) {
NonThrowableExceptionState exception_state;
animation->finish(exception_state);
EXPECT_EQ(30, animation->CurrentTimeInternal());
@@ -677,7 +698,7 @@ TEST_F(AnimationAnimationTest, UpdatePlaybackRateWhileLimited) {
EXPECT_EQ(2, animation->playbackRate());
}
-TEST_F(AnimationAnimationTest, UpdatePlaybackRateWhileRunning) {
+TEST_F(AnimationAnimationTestNoCompositing, UpdatePlaybackRateWhileRunning) {
animation->play();
SimulateFrame(1);
animation->updatePlaybackRate(2);
@@ -692,7 +713,7 @@ TEST_F(AnimationAnimationTest, UpdatePlaybackRateWhileRunning) {
EXPECT_EQ(2, animation->playbackRate());
}
-TEST_F(AnimationAnimationTest, SetEffect) {
+TEST_F(AnimationAnimationTestNoCompositing, SetEffect) {
animation = timeline->Play(nullptr);
animation->setStartTime(0, false);
AnimationEffect* effect1 = MakeAnimation();
@@ -708,7 +729,7 @@ TEST_F(AnimationAnimationTest, SetEffect) {
EXPECT_EQ(effect2, animation->effect());
}
-TEST_F(AnimationAnimationTest, SetEffectLimitsAnimation) {
+TEST_F(AnimationAnimationTestNoCompositing, SetEffectLimitsAnimation) {
animation->SetCurrentTimeInternal(20);
animation->setEffect(MakeAnimation(10));
EXPECT_EQ(20, animation->CurrentTimeInternal());
@@ -717,7 +738,7 @@ TEST_F(AnimationAnimationTest, SetEffectLimitsAnimation) {
EXPECT_EQ(20, animation->CurrentTimeInternal());
}
-TEST_F(AnimationAnimationTest, SetEffectUnlimitsAnimation) {
+TEST_F(AnimationAnimationTestNoCompositing, SetEffectUnlimitsAnimation) {
animation->SetCurrentTimeInternal(40);
animation->setEffect(MakeAnimation(60));
EXPECT_FALSE(animation->Limited());
@@ -726,7 +747,7 @@ TEST_F(AnimationAnimationTest, SetEffectUnlimitsAnimation) {
EXPECT_EQ(50, animation->CurrentTimeInternal());
}
-TEST_F(AnimationAnimationTest, EmptyAnimationsDontUpdateEffects) {
+TEST_F(AnimationAnimationTestNoCompositing, EmptyAnimationsDontUpdateEffects) {
animation = timeline->Play(nullptr);
animation->Update(kTimingUpdateOnDemand);
EXPECT_EQ(std::numeric_limits<double>::infinity(),
@@ -737,7 +758,7 @@ TEST_F(AnimationAnimationTest, EmptyAnimationsDontUpdateEffects) {
animation->TimeToEffectChange());
}
-TEST_F(AnimationAnimationTest, AnimationsDisassociateFromEffect) {
+TEST_F(AnimationAnimationTestNoCompositing, AnimationsDisassociateFromEffect) {
AnimationEffect* animation_node = animation->effect();
Animation* animation2 = timeline->Play(animation_node);
EXPECT_EQ(nullptr, animation->effect());
@@ -745,7 +766,7 @@ TEST_F(AnimationAnimationTest, AnimationsDisassociateFromEffect) {
EXPECT_EQ(nullptr, animation2->effect());
}
-TEST_F(AnimationAnimationTest, AnimationsReturnTimeToNextEffect) {
+TEST_F(AnimationAnimationTestNoCompositing, AnimationsReturnTimeToNextEffect) {
Timing timing;
timing.start_delay = 1;
timing.iteration_duration = AnimationTimeDelta::FromSecondsD(1);
@@ -755,52 +776,62 @@ TEST_F(AnimationAnimationTest, AnimationsReturnTimeToNextEffect) {
animation = timeline->Play(keyframe_effect);
animation->setStartTime(0, false);
+ // Next effect change at end of start delay.
SimulateFrame(0);
EXPECT_EQ(1, animation->TimeToEffectChange());
+ // Next effect change at end of start delay.
SimulateFrame(0.5);
EXPECT_EQ(0.5, animation->TimeToEffectChange());
+ // Start of active phase.
SimulateFrame(1);
EXPECT_EQ(0, animation->TimeToEffectChange());
+ // Still in active phase.
SimulateFrame(1.5);
EXPECT_EQ(0, animation->TimeToEffectChange());
+ // Start of the after phase. Next effect change at end of after phase.
SimulateFrame(2);
- EXPECT_EQ(std::numeric_limits<double>::infinity(),
- animation->TimeToEffectChange());
+ EXPECT_EQ(1, animation->TimeToEffectChange());
+ // Still in effect if fillmode = forward|both.
SimulateFrame(3);
EXPECT_EQ(std::numeric_limits<double>::infinity(),
animation->TimeToEffectChange());
+ // Reset to start of animation. Next effect at the end of the start delay.
animation->SetCurrentTimeInternal(0);
SimulateFrame(3);
EXPECT_EQ(1, animation->TimeToEffectChange());
+ // Start delay is scaled by playback rate.
animation->setPlaybackRate(2);
SimulateFrame(3);
EXPECT_EQ(0.5, animation->TimeToEffectChange());
+ // Effectively a paused animation.
animation->setPlaybackRate(0);
animation->Update(kTimingUpdateOnDemand);
EXPECT_EQ(std::numeric_limits<double>::infinity(),
animation->TimeToEffectChange());
+ // Reversed animation from end time. Next effect after end delay.
animation->SetCurrentTimeInternal(3);
animation->setPlaybackRate(-1);
animation->Update(kTimingUpdateOnDemand);
SimulateFrame(3);
EXPECT_EQ(1, animation->TimeToEffectChange());
+ // End delay is scaled by playback rate.
animation->setPlaybackRate(-2);
animation->Update(kTimingUpdateOnDemand);
SimulateFrame(3);
EXPECT_EQ(0.5, animation->TimeToEffectChange());
}
-TEST_F(AnimationAnimationTest, TimeToNextEffectWhenPaused) {
+TEST_F(AnimationAnimationTestNoCompositing, TimeToNextEffectWhenPaused) {
EXPECT_EQ(0, animation->TimeToEffectChange());
animation->pause();
animation->Update(kTimingUpdateOnDemand);
@@ -808,7 +839,8 @@ TEST_F(AnimationAnimationTest, TimeToNextEffectWhenPaused) {
animation->TimeToEffectChange());
}
-TEST_F(AnimationAnimationTest, TimeToNextEffectWhenCancelledBeforeStart) {
+TEST_F(AnimationAnimationTestNoCompositing,
+ TimeToNextEffectWhenCancelledBeforeStart) {
EXPECT_EQ(0, animation->TimeToEffectChange());
animation->SetCurrentTimeInternal(-8);
animation->setPlaybackRate(2);
@@ -823,7 +855,7 @@ TEST_F(AnimationAnimationTest, TimeToNextEffectWhenCancelledBeforeStart) {
animation->TimeToEffectChange());
}
-TEST_F(AnimationAnimationTest,
+TEST_F(AnimationAnimationTestNoCompositing,
TimeToNextEffectWhenCancelledBeforeStartReverse) {
EXPECT_EQ(0, animation->TimeToEffectChange());
animation->SetCurrentTimeInternal(9);
@@ -839,7 +871,8 @@ TEST_F(AnimationAnimationTest,
animation->TimeToEffectChange());
}
-TEST_F(AnimationAnimationTest, TimeToNextEffectSimpleCancelledBeforeStart) {
+TEST_F(AnimationAnimationTestNoCompositing,
+ TimeToNextEffectSimpleCancelledBeforeStart) {
EXPECT_EQ(0, animation->TimeToEffectChange());
EXPECT_EQ(Animation::kRunning, animation->PlayStateInternal());
animation->cancel();
@@ -851,8 +884,8 @@ TEST_F(AnimationAnimationTest, TimeToNextEffectSimpleCancelledBeforeStart) {
animation->TimeToEffectChange());
}
-TEST_F(AnimationAnimationTest, AttachedAnimations) {
- Persistent<Element> element = document->CreateElementForBinding("foo");
+TEST_F(AnimationAnimationTestNoCompositing, AttachedAnimations) {
+ Persistent<Element> element = GetDocument().CreateElementForBinding("foo");
Timing timing;
auto* keyframe_effect = MakeGarbageCollected<KeyframeEffect>(
@@ -867,13 +900,13 @@ TEST_F(AnimationAnimationTest, AttachedAnimations) {
EXPECT_TRUE(element->GetElementAnimations()->Animations().IsEmpty());
}
-TEST_F(AnimationAnimationTest, HasLowerPriority) {
+TEST_F(AnimationAnimationTestNoCompositing, HasLowerPriority) {
Animation* animation1 = timeline->Play(nullptr);
Animation* animation2 = timeline->Play(nullptr);
EXPECT_TRUE(Animation::HasLowerPriority(animation1, animation2));
}
-TEST_F(AnimationAnimationTest, PlayAfterCancel) {
+TEST_F(AnimationAnimationTestNoCompositing, PlayAfterCancel) {
animation->cancel();
EXPECT_EQ(Animation::kIdle, animation->PlayStateInternal());
EXPECT_TRUE(std::isnan(animation->currentTime()));
@@ -888,7 +921,7 @@ TEST_F(AnimationAnimationTest, PlayAfterCancel) {
EXPECT_EQ(10 * 1000, animation->startTime());
}
-TEST_F(AnimationAnimationTest, PlayBackwardsAfterCancel) {
+TEST_F(AnimationAnimationTestNoCompositing, PlayBackwardsAfterCancel) {
animation->setPlaybackRate(-1);
animation->setCurrentTime(15 * 1000, false);
SimulateFrame(0);
@@ -906,7 +939,7 @@ TEST_F(AnimationAnimationTest, PlayBackwardsAfterCancel) {
EXPECT_EQ(40 * 1000, animation->startTime());
}
-TEST_F(AnimationAnimationTest, ReverseAfterCancel) {
+TEST_F(AnimationAnimationTestNoCompositing, ReverseAfterCancel) {
animation->cancel();
EXPECT_EQ(Animation::kIdle, animation->PlayStateInternal());
EXPECT_TRUE(std::isnan(animation->currentTime()));
@@ -921,7 +954,7 @@ TEST_F(AnimationAnimationTest, ReverseAfterCancel) {
EXPECT_EQ(40 * 1000, animation->startTime());
}
-TEST_F(AnimationAnimationTest, FinishAfterCancel) {
+TEST_F(AnimationAnimationTestNoCompositing, FinishAfterCancel) {
NonThrowableExceptionState exception_state;
animation->cancel();
EXPECT_EQ(Animation::kIdle, animation->PlayStateInternal());
@@ -933,7 +966,7 @@ TEST_F(AnimationAnimationTest, FinishAfterCancel) {
EXPECT_EQ(Animation::kFinished, animation->PlayStateInternal());
}
-TEST_F(AnimationAnimationTest, PauseAfterCancel) {
+TEST_F(AnimationAnimationTestNoCompositing, PauseAfterCancel) {
animation->cancel();
EXPECT_EQ(Animation::kIdle, animation->PlayStateInternal());
EXPECT_TRUE(std::isnan(animation->currentTime()));
@@ -944,10 +977,8 @@ TEST_F(AnimationAnimationTest, PauseAfterCancel) {
EXPECT_FALSE(animation->startTime());
}
-TEST_F(AnimationAnimationTest, NoCompositeWithoutCompositedElementId) {
- ScopedCompositeAfterPaintForTest enable_cap(true);
- EnableCompositing();
-
+TEST_F(AnimationAnimationTestCompositeAfterPaint,
+ NoCompositeWithoutCompositedElementId) {
SetBodyInnerHTML(
"<div id='foo' style='position: relative; will-change: "
"opacity;'>composited</div>"
@@ -986,7 +1017,8 @@ TEST_F(AnimationAnimationTest, NoCompositeWithoutCompositedElementId) {
// played and then paused before any start time is set (either blink or
// compositor side), the pausing must still set compositor pending or the pause
// won't be synced.
-TEST_F(AnimationAnimationTest, SetCompositorPendingWithUnresolvedStartTimes) {
+TEST_F(AnimationAnimationTestCompositing,
+ SetCompositorPendingWithUnresolvedStartTimes) {
ResetWithCompositedAnimation();
// At this point, the animation exists on both the compositor and blink side,
@@ -1003,7 +1035,7 @@ TEST_F(AnimationAnimationTest, SetCompositorPendingWithUnresolvedStartTimes) {
EXPECT_TRUE(animation->CompositorPendingForTesting());
}
-TEST_F(AnimationAnimationTest, PreCommitWithUnresolvedStartTimes) {
+TEST_F(AnimationAnimationTestCompositing, PreCommitWithUnresolvedStartTimes) {
ResetWithCompositedAnimation();
// At this point, the animation exists on both the compositor and blink side,
@@ -1028,7 +1060,7 @@ int GenerateHistogramValue(CompositorAnimations::FailureReason reason) {
}
} // namespace
-TEST_F(AnimationAnimationTest, PreCommitRecordsHistograms) {
+TEST_F(AnimationAnimationTestCompositing, PreCommitRecordsHistograms) {
const std::string histogram_name =
"Blink.Animation.CompositedAnimationFailureReason";
@@ -1094,7 +1126,7 @@ TEST_F(AnimationAnimationTest, PreCommitRecordsHistograms) {
}
}
-TEST_F(AnimationAnimationTest, SetKeyframesCausesCompositorPending) {
+TEST_F(AnimationAnimationTestCompositing, SetKeyframesCausesCompositorPending) {
ResetWithCompositedAnimation();
// At this point, the animation exists on both the compositor and blink side,
@@ -1124,4 +1156,61 @@ TEST_F(AnimationAnimationTest, SetKeyframesCausesCompositorPending) {
EXPECT_TRUE(animation->CompositorPendingForTesting());
}
+// Verifies correctness of scroll linked animation current and start times in
+// various animation states.
+TEST_F(AnimationAnimationTestNoCompositing, ScrollLinkedAnimationCreation) {
+ 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"));
+ PaintLayerScrollableArea* scrollable_area = scroller->GetScrollableArea();
+ 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);
+
+ NonThrowableExceptionState exception_state;
+ Animation* scroll_animation =
+ Animation::Create(MakeAnimation(), scroll_timeline, exception_state);
+
+ // Verify start and current times in Idle state.
+ bool is_null;
+ scroll_animation->startTime(is_null);
+ EXPECT_TRUE(is_null);
+ scroll_animation->currentTime(is_null);
+ EXPECT_TRUE(is_null);
+
+ scroll_animation->play();
+
+ // Verify start and current times in Pending state.
+ scroll_animation->startTime(is_null);
+ EXPECT_TRUE(is_null);
+ EXPECT_EQ(0, scroll_animation->currentTime(is_null));
+ EXPECT_FALSE(is_null);
+
+ UpdateAllLifecyclePhasesForTest();
+ // Verify start and current times in Playing state.
+ EXPECT_EQ(0, scroll_animation->startTime(is_null));
+ EXPECT_FALSE(is_null);
+ EXPECT_EQ(20, scroll_animation->currentTime(is_null));
+ EXPECT_FALSE(is_null);
+
+ // Verify current time after scroll.
+ scrollable_area->SetScrollOffset(ScrollOffset(0, 40), kProgrammaticScroll);
+ EXPECT_EQ(40, scroll_animation->currentTime(is_null));
+ EXPECT_FALSE(is_null);
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/animation/animation_test_helper.cc b/chromium/third_party/blink/renderer/core/animation/animation_test_helper.cc
index a913190ee55..dc54c2f0062 100644
--- a/chromium/third_party/blink/renderer/core/animation/animation_test_helper.cc
+++ b/chromium/third_party/blink/renderer/core/animation/animation_test_helper.cc
@@ -8,6 +8,8 @@
#include "third_party/blink/renderer/core/animation/css_interpolation_environment.h"
#include "third_party/blink/renderer/core/animation/css_interpolation_types_map.h"
#include "third_party/blink/renderer/core/animation/invalidatable_interpolation.h"
+#include "third_party/blink/renderer/core/css/css_pending_interpolation_value.h"
+#include "third_party/blink/renderer/core/css/resolver/style_cascade.h"
#include "third_party/blink/renderer/core/css/resolver/style_resolver_state.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/element.h"
@@ -15,6 +17,39 @@
namespace blink {
+namespace {
+
+class TestAnimator : public StyleCascade::Animator {
+ STACK_ALLOCATED();
+
+ public:
+ TestAnimator(StyleResolverState& state,
+ StyleCascade& cascade,
+ CSSInterpolationTypesMap& map,
+ const ActiveInterpolations& interpolations)
+ : state_(state),
+ cascade_(cascade),
+ map_(map),
+ interpolations_(interpolations) {}
+
+ void Apply(const CSSProperty&,
+ const cssvalue::CSSPendingInterpolationValue& value,
+ StyleCascade::Resolver& resolver) override {
+ // Ignore CSSProperty here. We assume this function is only called once
+ // for each invocation of EnsureInterpolatedValueCached.
+ CSSInterpolationEnvironment environment(map_, state_, &cascade_, &resolver);
+ InvalidatableInterpolation::ApplyStack(interpolations_, environment);
+ }
+
+ private:
+ StyleResolverState& state_;
+ StyleCascade& cascade_;
+ CSSInterpolationTypesMap& map_;
+ const ActiveInterpolations& interpolations_;
+};
+
+} // namespace
+
void SetV8ObjectPropertyAsString(v8::Isolate* isolate,
v8::Local<v8::Object> object,
const StringView& name,
@@ -43,13 +78,26 @@ void EnsureInterpolatedValueCached(const ActiveInterpolations& interpolations,
// require our callers to propertly register every animation they pass in
// here, which the current tests do not do.
auto style = ComputedStyle::Create();
- StyleResolverState state(document, element, nullptr /* pseudo_element */,
+ StyleResolverState state(document, *element, nullptr /* pseudo_element */,
style.get(), style.get());
state.SetStyle(style);
CSSInterpolationTypesMap map(state.GetDocument().GetPropertyRegistry(),
state.GetDocument());
- CSSInterpolationEnvironment environment(map, state, nullptr);
- InvalidatableInterpolation::ApplyStack(interpolations, environment);
+ if (RuntimeEnabledFeatures::CSSCascadeEnabled()) {
+ // We must apply the animation effects via StyleCascade when the cascade
+ // is enabled.
+ StyleCascade cascade(state);
+ auto type = cssvalue::CSSPendingInterpolationValue::Type::kCSSProperty;
+ auto* pending = cssvalue::CSSPendingInterpolationValue::Create(type);
+ auto origin = StyleCascade::Origin::kAuthor;
+ cascade.Add(*CSSPropertyName::From("--unused"), pending, origin);
+
+ TestAnimator animator(state, cascade, map, interpolations);
+ cascade.Apply(animator);
+ } else {
+ CSSInterpolationEnvironment environment(map, state, nullptr);
+ InvalidatableInterpolation::ApplyStack(interpolations, environment);
+ }
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/animation/animation_time_delta.h b/chromium/third_party/blink/renderer/core/animation/animation_time_delta.h
index d8d08da4e83..64cca32f1ab 100644
--- a/chromium/third_party/blink/renderer/core/animation/animation_time_delta.h
+++ b/chromium/third_party/blink/renderer/core/animation/animation_time_delta.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_ANIMATION_TIME_DELTA_H_
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include <limits>
#include <ostream>
@@ -109,7 +109,7 @@ CORE_EXPORT std::ostream& operator<<(std::ostream& os,
// When compiling in TimeDelta-based mode, AnimationTimeDelta is equivalent to
// base::TimeDelta.
-using AnimationTimeDelta = TimeDelta;
+using AnimationTimeDelta = base::TimeDelta;
#endif
diff --git a/chromium/third_party/blink/renderer/core/animation/animation_timeline.h b/chromium/third_party/blink/renderer/core/animation/animation_timeline.h
index 4d06d1542c5..792d74de7f9 100644
--- a/chromium/third_party/blink/renderer/core/animation/animation_timeline.h
+++ b/chromium/third_party/blink/renderer/core/animation/animation_timeline.h
@@ -10,6 +10,9 @@
namespace blink {
+class Animation;
+class Document;
+
class CORE_EXPORT AnimationTimeline : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
@@ -18,9 +21,25 @@ class CORE_EXPORT AnimationTimeline : public ScriptWrappable {
virtual double currentTime(bool&) = 0;
+ base::Optional<double> CurrentTime() {
+ bool is_null;
+ double current_time_ms = currentTime(is_null);
+ return is_null ? base::nullopt : base::make_optional(current_time_ms);
+ }
+
+ base::Optional<double> CurrentTimeSeconds() {
+ base::Optional<double> current_time_ms = CurrentTime();
+ if (current_time_ms)
+ return current_time_ms.value() / 1000;
+ return current_time_ms;
+ }
+
virtual bool IsDocumentTimeline() const { return false; }
virtual bool IsScrollTimeline() const { return false; }
virtual bool IsActive() const = 0;
+ virtual Document* GetDocument() = 0;
+ virtual void AnimationAttached(Animation*) = 0;
+ virtual void AnimationDetached(Animation*) = 0;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/animation/animation_timeline.idl b/chromium/third_party/blink/renderer/core/animation/animation_timeline.idl
index 4d4d6ea92f5..cf19ed3f89b 100644
--- a/chromium/third_party/blink/renderer/core/animation/animation_timeline.idl
+++ b/chromium/third_party/blink/renderer/core/animation/animation_timeline.idl
@@ -5,7 +5,8 @@
// https://drafts.csswg.org/web-animations/#the-animationtimeline-interface
[
- RuntimeEnabled=WebAnimationsAPI
+ RuntimeEnabled=WebAnimationsAPI,
+ Exposed=Window
] interface AnimationTimeline {
readonly attribute double? currentTime;
};
diff --git a/chromium/third_party/blink/renderer/core/animation/color_property_functions.cc b/chromium/third_party/blink/renderer/core/animation/color_property_functions.cc
index 67d8cb41cec..0c2b4df7bdf 100644
--- a/chromium/third_party/blink/renderer/core/animation/color_property_functions.cc
+++ b/chromium/third_party/blink/renderer/core/animation/color_property_functions.cc
@@ -64,33 +64,33 @@ OptionalStyleColor ColorPropertyFunctions::GetVisitedColor(
const ComputedStyle& style) {
switch (property.PropertyID()) {
case CSSPropertyID::kBackgroundColor:
- return style.VisitedLinkBackgroundColor();
+ return style.InternalVisitedBackgroundColor();
case CSSPropertyID::kBorderLeftColor:
- return style.VisitedLinkBorderLeftColor();
+ return style.InternalVisitedBorderLeftColor();
case CSSPropertyID::kBorderRightColor:
- return style.VisitedLinkBorderRightColor();
+ return style.InternalVisitedBorderRightColor();
case CSSPropertyID::kBorderTopColor:
- return style.VisitedLinkBorderTopColor();
+ return style.InternalVisitedBorderTopColor();
case CSSPropertyID::kBorderBottomColor:
- return style.VisitedLinkBorderBottomColor();
+ return style.InternalVisitedBorderBottomColor();
case CSSPropertyID::kCaretColor:
// TODO(rego): "auto" value for caret-color should not interpolate
// (http://crbug.com/676295).
- if (style.VisitedLinkCaretColor().IsAutoColor())
+ if (style.InternalVisitedCaretColor().IsAutoColor())
return StyleColor::CurrentColor();
- return style.VisitedLinkCaretColor().ToStyleColor();
+ return style.InternalVisitedCaretColor().ToStyleColor();
case CSSPropertyID::kColor:
- return style.VisitedLinkColor();
+ return style.InternalVisitedColor();
case CSSPropertyID::kOutlineColor:
- return style.VisitedLinkOutlineColor();
+ return style.InternalVisitedOutlineColor();
case CSSPropertyID::kColumnRuleColor:
- return style.VisitedLinkColumnRuleColor();
+ return style.InternalVisitedColumnRuleColor();
case CSSPropertyID::kWebkitTextEmphasisColor:
- return style.VisitedLinkTextEmphasisColor();
+ return style.InternalVisitedTextEmphasisColor();
case CSSPropertyID::kWebkitTextFillColor:
- return style.VisitedLinkTextFillColor();
+ return style.InternalVisitedTextFillColor();
case CSSPropertyID::kWebkitTextStrokeColor:
- return style.VisitedLinkTextStrokeColor();
+ return style.InternalVisitedTextStrokeColor();
case CSSPropertyID::kFloodColor:
return style.FloodColor();
case CSSPropertyID::kLightingColor:
@@ -100,7 +100,7 @@ OptionalStyleColor ColorPropertyFunctions::GetVisitedColor(
case CSSPropertyID::kWebkitTapHighlightColor:
return style.TapHighlightColor();
case CSSPropertyID::kTextDecorationColor:
- return style.VisitedLinkTextDecorationColor();
+ return style.InternalVisitedTextDecorationColor();
default:
NOTREACHED();
return nullptr;
@@ -163,24 +163,24 @@ void ColorPropertyFunctions::SetVisitedColor(const CSSProperty& property,
const Color& color) {
switch (property.PropertyID()) {
case CSSPropertyID::kBackgroundColor:
- style.SetVisitedLinkBackgroundColor(color);
+ style.SetInternalVisitedBackgroundColor(color);
return;
case CSSPropertyID::kBorderBottomColor:
- style.SetVisitedLinkBorderBottomColor(color);
+ style.SetInternalVisitedBorderBottomColor(color);
return;
case CSSPropertyID::kBorderLeftColor:
- style.SetVisitedLinkBorderLeftColor(color);
+ style.SetInternalVisitedBorderLeftColor(color);
return;
case CSSPropertyID::kBorderRightColor:
- style.SetVisitedLinkBorderRightColor(color);
+ style.SetInternalVisitedBorderRightColor(color);
return;
case CSSPropertyID::kBorderTopColor:
- style.SetVisitedLinkBorderTopColor(color);
+ style.SetInternalVisitedBorderTopColor(color);
return;
case CSSPropertyID::kCaretColor:
- return style.SetVisitedLinkCaretColor(color);
+ return style.SetInternalVisitedCaretColor(color);
case CSSPropertyID::kColor:
- style.SetVisitedLinkColor(color);
+ style.SetInternalVisitedColor(color);
return;
case CSSPropertyID::kFloodColor:
style.SetFloodColor(color);
@@ -189,19 +189,19 @@ void ColorPropertyFunctions::SetVisitedColor(const CSSProperty& property,
style.SetLightingColor(color);
return;
case CSSPropertyID::kOutlineColor:
- style.SetVisitedLinkOutlineColor(color);
+ style.SetInternalVisitedOutlineColor(color);
return;
case CSSPropertyID::kStopColor:
style.SetStopColor(color);
return;
case CSSPropertyID::kTextDecorationColor:
- style.SetVisitedLinkTextDecorationColor(color);
+ style.SetInternalVisitedTextDecorationColor(color);
return;
case CSSPropertyID::kColumnRuleColor:
- style.SetVisitedLinkColumnRuleColor(color);
+ style.SetInternalVisitedColumnRuleColor(color);
return;
case CSSPropertyID::kWebkitTextStrokeColor:
- style.SetVisitedLinkTextStrokeColor(color);
+ style.SetInternalVisitedTextStrokeColor(color);
return;
default:
NOTREACHED();
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 ba983689848..be4f5e1fa50 100644
--- a/chromium/third_party/blink/renderer/core/animation/compositor_animations.cc
+++ b/chromium/third_party/blink/renderer/core/animation/compositor_animations.cc
@@ -35,6 +35,7 @@
#include <memory>
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/core/animation/animation_effect.h"
+#include "third_party/blink/renderer/core/animation/css/compositor_keyframe_color.h"
#include "third_party/blink/renderer/core/animation/css/compositor_keyframe_double.h"
#include "third_party/blink/renderer/core/animation/css/compositor_keyframe_filter_operations.h"
#include "third_party/blink/renderer/core/animation/css/compositor_keyframe_transform.h"
@@ -51,6 +52,7 @@
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/platform/animation/animation_translation_util.h"
#include "third_party/blink/renderer/platform/animation/compositor_animation.h"
+#include "third_party/blink/renderer/platform/animation/compositor_color_animation_curve.h"
#include "third_party/blink/renderer/platform/animation/compositor_filter_animation_curve.h"
#include "third_party/blink/renderer/platform/animation/compositor_filter_keyframe.h"
#include "third_party/blink/renderer/platform/animation/compositor_float_animation_curve.h"
@@ -227,7 +229,7 @@ CompositorAnimations::CheckCanStartEffectOnCompositor(
}
const PropertySpecificKeyframeVector& keyframes =
- keyframe_effect.GetPropertySpecificKeyframes(property);
+ *keyframe_effect.GetPropertySpecificKeyframes(property);
DCHECK_GE(keyframes.size(), 2U);
for (const auto& keyframe : keyframes) {
if (keyframe->Composite() != EffectModel::kCompositeReplace &&
@@ -253,7 +255,6 @@ CompositorAnimations::CheckCanStartEffectOnCompositor(
}
break;
case CSSPropertyID::kFilter:
- case CSSPropertyID::kBackdropFilter:
if (keyframe->GetCompositorKeyframeValue() &&
ToCompositorKeyframeFilterOperations(
keyframe->GetCompositorKeyframeValue())
@@ -262,13 +263,24 @@ CompositorAnimations::CheckCanStartEffectOnCompositor(
reasons |= kFilterRelatedPropertyMayMovePixels;
}
break;
- case CSSPropertyID::kVariable:
+ case CSSPropertyID::kBackdropFilter:
+ // Backdrop-filter pixel moving filters do not change the layer bounds
+ // like regular filters do, so they can still be composited.
+ break;
+ case CSSPropertyID::kVariable: {
// Custom properties are supported only in the case of
// OffMainThreadCSSPaintEnabled, and even then only for some specific
// property types. Otherwise they are treated as unsupported.
- if (keyframe->GetCompositorKeyframeValue()) {
+ const CompositorKeyframeValue* keyframe_value =
+ keyframe->GetCompositorKeyframeValue();
+ if (keyframe_value) {
DCHECK(RuntimeEnabledFeatures::OffMainThreadCSSPaintEnabled());
- DCHECK(keyframe->GetCompositorKeyframeValue()->IsDouble());
+ DCHECK(keyframe_value->IsDouble() || keyframe_value->IsColor());
+ // TODO: Add support for keyframes containing different types
+ if (keyframes.front()->GetCompositorKeyframeValue()->GetType() !=
+ keyframe_value->GetType()) {
+ reasons |= kMixedKeyframeValueTypes;
+ }
} else {
// We skip the rest of the loop in this case for the same reason as
// unsupported CSS properties - see below.
@@ -276,6 +288,7 @@ CompositorAnimations::CheckCanStartEffectOnCompositor(
continue;
}
break;
+ }
default:
// We skip the rest of the loop in this case for two reasons:
// i. Getting a CompositorElementId below will DCHECK if we pass it
@@ -333,37 +346,27 @@ CompositorAnimations::CheckCanStartElementOnCompositor(
if (!Platform::Current()->IsThreadedAnimationEnabled())
reasons |= kAcceleratedAnimationsDisabled;
- LayoutObject* layout_object = target_element.GetLayoutObject();
- if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) {
+ if (const auto* layout_object = target_element.GetLayoutObject()) {
// We query paint property tree state below to determine whether the
- // animation is compositable. There is a known lifecycle violation where an
- // animation can be cancelled during style update. See
- // CompositorAnimations::cancelAnimationOnCompositor and
- // http://crbug.com/676456. When this is fixed we would like to enable
- // the DCHECK below.
- // DCHECK(document().lifecycle().state() >=
- // DocumentLifecycle::PrePaintClean);
- DCHECK(layout_object);
-
- if (!layout_object->UniqueId())
- reasons |= kTargetHasInvalidCompositingState;
-
+ // animation is compositable. TODO(crbug.com/676456): There is a known
+ // lifecycle violation where an animation can be cancelled during style
+ // update. See CompositorAnimations::CancelAnimationOnCompositor().
+ // When this is fixed we would like to enable the DCHECK below.
+ // DCHECK_GE(GetDocument().Lifecycle().GetState(),
+ // DocumentLifecycle::kPrePaintClean);
+ bool has_direct_compositing_reasons = false;
if (const auto* paint_properties =
layout_object->FirstFragment().PaintProperties()) {
- const TransformPaintPropertyNode* transform_node =
- paint_properties->Transform();
- const EffectPaintPropertyNode* effect_node = paint_properties->Effect();
- bool has_direct_compositing_reasons =
- (transform_node && transform_node->HasDirectCompositingReasons()) ||
- (effect_node && effect_node->HasDirectCompositingReasons());
- if (!has_direct_compositing_reasons)
- reasons |= kTargetHasInvalidCompositingState;
+ const auto* transform = paint_properties->Transform();
+ const auto* effect = paint_properties->Effect();
+ has_direct_compositing_reasons =
+ (transform && transform->HasDirectCompositingReasons()) ||
+ (effect && effect->HasDirectCompositingReasons());
}
- } else {
- if (!layout_object ||
- layout_object->GetCompositingState() != kPaintsIntoOwnBacking) {
+ if (!has_direct_compositing_reasons)
reasons |= kTargetHasInvalidCompositingState;
- }
+ } else {
+ reasons |= kTargetHasInvalidCompositingState;
}
return reasons;
@@ -479,11 +482,6 @@ void CompositorAnimations::PauseAnimationForTestingOnCompositor(
const Animation& animation,
int id,
double pause_time) {
- // FIXME: CheckCanStartAnimationOnCompositor queries compositingState, which
- // is not necessarily up to date.
- // https://code.google.com/p/chromium/issues/detail?id=339847
- DisableCompositingQueryAsserts disabler;
-
DCHECK_EQ(CheckCanStartElementOnCompositor(element), kNoFailure);
CompositorAnimation* compositor_animation =
animation.GetCompositorAnimation();
@@ -598,6 +596,16 @@ void AddKeyframeToCurve(CompositorFloatAnimationCurve& curve,
curve.AddKeyframe(float_keyframe);
}
+void AddKeyframeToCurve(CompositorColorAnimationCurve& curve,
+ Keyframe::PropertySpecificKeyframe* keyframe,
+ const CompositorKeyframeValue* value,
+ const TimingFunction& keyframe_timing_function) {
+ CompositorColorKeyframe color_keyframe(
+ keyframe->Offset(), ToCompositorKeyframeColor(value)->ToColor(),
+ keyframe_timing_function);
+ curve.AddKeyframe(color_keyframe);
+}
+
void AddKeyframeToCurve(CompositorTransformAnimationCurve& curve,
Keyframe::PropertySpecificKeyframe* keyframe,
const CompositorKeyframeValue* value,
@@ -649,6 +657,7 @@ void CompositorAnimations::GetAnimationOnCompositor(
PropertyHandleSet properties = effect.Properties();
DCHECK(!properties.IsEmpty());
for (const auto& property : properties) {
+ AtomicString custom_property_name = "";
// If the animation duration is infinite, it doesn't make sense to scale
// the keyframe offset, so use a scale of 1.0. This is connected to
// the known issue of how the Web Animations spec handles infinite
@@ -657,7 +666,7 @@ void CompositorAnimations::GetAnimationOnCompositor(
if (!std::isfinite(scale))
scale = 1.0;
const PropertySpecificKeyframeVector& values =
- effect.GetPropertySpecificKeyframes(property);
+ *effect.GetPropertySpecificKeyframes(property);
compositor_target_property::Type target_property;
std::unique_ptr<CompositorAnimationCurve> curve;
@@ -701,13 +710,23 @@ void CompositorAnimations::GetAnimationOnCompositor(
}
case CSSPropertyID::kVariable: {
DCHECK(RuntimeEnabledFeatures::OffMainThreadCSSPaintEnabled());
+ custom_property_name = property.CustomPropertyName();
target_property = compositor_target_property::CSS_CUSTOM_PROPERTY;
- // TODO(kevers): Extend support to non-float types.
- auto float_curve = std::make_unique<CompositorFloatAnimationCurve>();
- AddKeyframesToCurve(*float_curve, values);
- float_curve->SetTimingFunction(*timing.timing_function);
- float_curve->SetScaledDuration(scale);
- curve = std::move(float_curve);
+
+ // Create curve based on the keyframe value type
+ if (values.front()->GetCompositorKeyframeValue()->IsColor()) {
+ auto color_curve = std::make_unique<CompositorColorAnimationCurve>();
+ AddKeyframesToCurve(*color_curve, values);
+ color_curve->SetTimingFunction(*timing.timing_function);
+ color_curve->SetScaledDuration(scale);
+ curve = std::move(color_curve);
+ } else {
+ auto float_curve = std::make_unique<CompositorFloatAnimationCurve>();
+ AddKeyframesToCurve(*float_curve, values);
+ float_curve->SetTimingFunction(*timing.timing_function);
+ float_curve->SetScaledDuration(scale);
+ curve = std::move(float_curve);
+ }
break;
}
default:
@@ -717,7 +736,7 @@ void CompositorAnimations::GetAnimationOnCompositor(
DCHECK(curve.get());
auto keyframe_model = std::make_unique<CompositorKeyframeModel>(
- *curve, target_property, 0, group);
+ *curve, target_property, 0, group, std::move(custom_property_name));
if (start_time)
keyframe_model->SetStartTime(start_time.value());
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 deedee2cf84..3b222c9fcd4 100644
--- a/chromium/third_party/blink/renderer/core/animation/compositor_animations.h
+++ b/chromium/third_party/blink/renderer/core/animation/compositor_animations.h
@@ -37,7 +37,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/animation/timing_function.h"
#include "third_party/blink/renderer/platform/graphics/compositor_element_id.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
@@ -90,12 +90,13 @@ class CORE_EXPORT CompositorAnimations {
kFilterRelatedPropertyMayMovePixels = 1 << 12,
kUnsupportedCSSProperty = 1 << 13,
kMultipleTransformAnimationsOnSameTarget = 1 << 14,
+ kMixedKeyframeValueTypes = 1 << 15,
// The maximum number of flags in this enum (excluding itself). New flags
// should increment this number but it should never be decremented because
// the values are used in UMA histograms. It should also be noted that it
// excludes the kNoFailure value.
- kFailureReasonCount = 15,
+ kFailureReasonCount = 16,
};
static FailureReasons CheckCanStartAnimationOnCompositor(
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 f38984ddcf3..358dfd06f0b 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
@@ -60,6 +60,7 @@
#include "third_party/blink/renderer/core/style/filter_operations.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/animation/compositor_color_animation_curve.h"
#include "third_party/blink/renderer/platform/animation/compositor_float_animation_curve.h"
#include "third_party/blink/renderer/platform/animation/compositor_float_keyframe.h"
#include "third_party/blink/renderer/platform/animation/compositor_keyframe_model.h"
@@ -74,6 +75,7 @@
#include "third_party/blink/renderer/platform/transforms/transform_operations.h"
#include "third_party/blink/renderer/platform/transforms/translate_transform_operation.h"
#include "third_party/blink/renderer/platform/wtf/hash_functions.h"
+#include "third_party/skia/include/core/SkColor.h"
namespace blink {
@@ -99,8 +101,8 @@ class AnimationCompositorAnimationsTest : public PaintTestConfigurations,
Persistent<DocumentTimeline> timeline_;
void SetUp() override {
- RenderingTest::SetUp();
EnableCompositing();
+ RenderingTest::SetUp();
linear_timing_function_ = LinearTimingFunction::Shared();
cubic_ease_timing_function_ = CubicBezierTimingFunction::Preset(
CubicBezierTimingFunction::EaseType::EASE);
@@ -125,7 +127,7 @@ class AnimationCompositorAnimationsTest : public PaintTestConfigurations,
GetAnimationClock().ResetTimeForTesting();
- timeline_ = DocumentTimeline::Create(&GetDocument());
+ timeline_ = GetDocument().Timeline();
timeline_->ResetForTesting();
// Using will-change ensures that this object will need paint properties.
@@ -177,12 +179,6 @@ class AnimationCompositorAnimationsTest : public PaintTestConfigurations,
void GetAnimationOnCompositor(
Timing& timing,
StringKeyframeEffectModel& effect,
- Vector<std::unique_ptr<CompositorKeyframeModel>>& keyframe_models) {
- GetAnimationOnCompositor(timing, effect, keyframe_models, 1);
- }
- void GetAnimationOnCompositor(
- Timing& timing,
- StringKeyframeEffectModel& effect,
Vector<std::unique_ptr<CompositorKeyframeModel>>& keyframe_models,
double animation_playback_rate) {
CompositorAnimations::GetAnimationOnCompositor(
@@ -232,8 +228,7 @@ class AnimationCompositorAnimationsTest : public PaintTestConfigurations,
const String& value,
double offset = 0) {
auto* keyframe = MakeGarbageCollected<StringKeyframe>();
- keyframe->SetCSSPropertyValue(AtomicString(property_name),
- GetDocument().GetPropertyRegistry(), value,
+ keyframe->SetCSSPropertyValue(AtomicString(property_name), value,
GetDocument().GetSecureContextMode(),
GetDocument().ElementSheet().Contents());
keyframe->SetComposite(EffectModel::kCompositeReplace);
@@ -467,7 +462,7 @@ class AnimationCompositorAnimationsTest : public PaintTestConfigurations,
void BeginFrame() {
helper_.GetWebView()->MainFrameWidget()->BeginFrame(
- WTF::CurrentTimeTicks(), false /* record_main_frame_metrics */);
+ base::TimeTicks::Now(), false /* record_main_frame_metrics */);
}
void ForceFullCompositingUpdate() {
@@ -592,8 +587,10 @@ TEST_P(AnimationCompositorAnimationsTest,
ScopedOffMainThreadCSSPaintForTest off_main_thread_css_paint(true);
RegisterProperty(GetDocument(), "--foo", "<number>", "0", false);
RegisterProperty(GetDocument(), "--bar", "<length>", "10px", false);
+ RegisterProperty(GetDocument(), "--loo", "<color>", "rgb(0, 0, 0)", false);
SetCustomProperty("--foo", "10");
SetCustomProperty("--bar", "10px");
+ SetCustomProperty("--loo", "rgb(0, 255, 0)");
auto style = GetDocument().EnsureStyleResolver().StyleForElement(element_);
EXPECT_TRUE(style->NonInheritedVariables());
@@ -603,11 +600,20 @@ TEST_P(AnimationCompositorAnimationsTest,
EXPECT_TRUE(style->NonInheritedVariables()
->GetData(AtomicString("--bar"))
.value_or(nullptr));
+ EXPECT_TRUE(style->NonInheritedVariables()
+ ->GetData(AtomicString("--loo"))
+ .value_or(nullptr));
StringKeyframe* keyframe = CreateReplaceOpKeyframe("--foo", "10");
EXPECT_EQ(DuplicateSingleKeyframeAndTestIsCandidateOnResult(keyframe),
CompositorAnimations::kNoFailure);
+ // Color-valued properties are supported
+ StringKeyframe* color_keyframe =
+ CreateReplaceOpKeyframe("--loo", "rgb(0, 255, 0)");
+ EXPECT_EQ(DuplicateSingleKeyframeAndTestIsCandidateOnResult(color_keyframe),
+ CompositorAnimations::kNoFailure);
+
// Length-valued properties are not compositable.
StringKeyframe* non_animatable_keyframe =
CreateReplaceOpKeyframe("--bar", "10px");
@@ -867,10 +873,10 @@ TEST_P(AnimationCompositorAnimationsTest,
effect1->SnapshotAllCompositorKeyframesIfNecessary(*element_.Get(), *style,
nullptr);
- EXPECT_EQ(2u,
- effect1->GetPropertySpecificKeyframes(target_property1h).size());
- EXPECT_FALSE(effect1->GetPropertySpecificKeyframes(target_property1h)[0]
- ->GetCompositorKeyframeValue());
+ const auto& keyframes1 =
+ *effect1->GetPropertySpecificKeyframes(target_property1h);
+ EXPECT_EQ(2u, keyframes1.size());
+ EXPECT_FALSE(keyframes1[0]->GetCompositorKeyframeValue());
EXPECT_EQ(1u, effect1->Properties().size());
EXPECT_TRUE(CheckCanStartEffectOnCompositor(timing_, *element_.Get(),
animation1, *effect1) &
@@ -890,10 +896,10 @@ TEST_P(AnimationCompositorAnimationsTest,
effect2->SnapshotAllCompositorKeyframesIfNecessary(*inline_.Get(), *style,
nullptr);
- EXPECT_EQ(2u,
- effect2->GetPropertySpecificKeyframes(target_property2h).size());
- EXPECT_TRUE(effect2->GetPropertySpecificKeyframes(target_property2h)[0]
- ->GetCompositorKeyframeValue());
+ const auto& keyframes2 =
+ *effect2->GetPropertySpecificKeyframes(target_property2h);
+ EXPECT_EQ(2u, keyframes2.size());
+ EXPECT_TRUE(keyframes2[0]->GetCompositorKeyframeValue());
EXPECT_EQ(1u, effect2->Properties().size());
EXPECT_TRUE(CheckCanStartEffectOnCompositor(timing_, *inline_.Get(),
animation2, *effect2) &
@@ -916,10 +922,10 @@ TEST_P(AnimationCompositorAnimationsTest,
effect3->SnapshotAllCompositorKeyframesIfNecessary(*element_.Get(), *style,
nullptr);
- EXPECT_EQ(2u,
- effect3->GetPropertySpecificKeyframes(target_property3h).size());
- EXPECT_TRUE(effect3->GetPropertySpecificKeyframes(target_property3h)[0]
- ->GetCompositorKeyframeValue());
+ const auto& keyframes3 =
+ *effect3->GetPropertySpecificKeyframes(target_property3h);
+ EXPECT_EQ(2u, keyframes3.size());
+ EXPECT_TRUE(keyframes3[0]->GetCompositorKeyframeValue());
EXPECT_EQ(1u, effect3->Properties().size());
EXPECT_TRUE(CheckCanStartEffectOnCompositor(timing_, *element_.Get(),
animation3, *effect3) &
@@ -1525,6 +1531,26 @@ TEST_P(AnimationCompositorAnimationsTest,
}
TEST_P(AnimationCompositorAnimationsTest,
+ CreateCustomFloatPropertyAnimationWithNonAsciiName) {
+ ScopedOffMainThreadCSSPaintForTest off_main_thread_css_paint(true);
+
+ String property_name = "--東京都";
+ RegisterProperty(GetDocument(), property_name, "<number>", "0", false);
+ SetCustomProperty(property_name, "10");
+
+ StringKeyframeEffectModel* effect = CreateKeyframeEffectModel(
+ CreateReplaceOpKeyframe(property_name, "10", 0),
+ CreateReplaceOpKeyframe(property_name, "20", 1.0));
+
+ std::unique_ptr<CompositorKeyframeModel> keyframe_model =
+ ConvertToCompositorAnimation(*effect);
+ EXPECT_EQ(compositor_target_property::CSS_CUSTOM_PROPERTY,
+ keyframe_model->TargetProperty());
+ EXPECT_EQ(keyframe_model->GetCustomPropertyNameForTesting(),
+ property_name.Utf8().data());
+}
+
+TEST_P(AnimationCompositorAnimationsTest,
CreateSimpleCustomFloatPropertyAnimation) {
ScopedOffMainThreadCSSPaintForTest off_main_thread_css_paint(true);
@@ -1559,6 +1585,54 @@ TEST_P(AnimationCompositorAnimationsTest,
}
TEST_P(AnimationCompositorAnimationsTest,
+ CreateSimpleCustomColorPropertyAnimation) {
+ ScopedOffMainThreadCSSPaintForTest off_main_thread_css_paint(true);
+
+ RegisterProperty(GetDocument(), "--foo", "<color>", "rgb(0, 0, 0)", false);
+ SetCustomProperty("--foo", "rgb(0, 0, 0)");
+
+ StringKeyframeEffectModel* effect = CreateKeyframeEffectModel(
+ CreateReplaceOpKeyframe("--foo", "rgb(0, 0, 0)", 0),
+ CreateReplaceOpKeyframe("--foo", "rgb(0, 255, 0)", 1.0));
+
+ std::unique_ptr<CompositorKeyframeModel> keyframe_model =
+ ConvertToCompositorAnimation(*effect);
+ EXPECT_EQ(compositor_target_property::CSS_CUSTOM_PROPERTY,
+ keyframe_model->TargetProperty());
+
+ std::unique_ptr<CompositorColorAnimationCurve> keyframed_color_curve =
+ keyframe_model->ColorCurveForTesting();
+
+ CompositorColorAnimationCurve::Keyframes keyframes =
+ keyframed_color_curve->KeyframesForTesting();
+ ASSERT_EQ(2UL, keyframes.size());
+
+ EXPECT_EQ(0, keyframes[0]->Time());
+ EXPECT_EQ(SkColorSetRGB(0, 0, 0), keyframes[0]->Value());
+ EXPECT_EQ(TimingFunction::Type::LINEAR,
+ keyframes[0]->GetTimingFunctionForTesting()->GetType());
+
+ EXPECT_EQ(1.0, keyframes[1]->Time());
+ EXPECT_EQ(SkColorSetRGB(0, 0xFF, 0), keyframes[1]->Value());
+ EXPECT_EQ(TimingFunction::Type::LINEAR,
+ keyframes[1]->GetTimingFunctionForTesting()->GetType());
+}
+
+TEST_P(AnimationCompositorAnimationsTest, MixedCustomPropertyAnimation) {
+ ScopedOffMainThreadCSSPaintForTest off_main_thread_css_paint(true);
+
+ RegisterProperty(GetDocument(), "--foo", "<number> | <color>", "0", false);
+ SetCustomProperty("--foo", "0");
+
+ StringKeyframeEffectModel* effect = CreateKeyframeEffectModel(
+ CreateReplaceOpKeyframe("--foo", "20", 0),
+ CreateReplaceOpKeyframe("--foo", "rgb(0, 255, 0)", 1.0));
+
+ EXPECT_TRUE(CanStartEffectOnCompositor(timing_, *effect) &
+ CompositorAnimations::kMixedKeyframeValueTypes);
+}
+
+TEST_P(AnimationCompositorAnimationsTest,
CancelIncompatibleCompositorAnimations) {
Persistent<HeapVector<Member<StringKeyframe>>> key_frames =
MakeGarbageCollected<HeapVector<Member<StringKeyframe>>>();
@@ -1631,11 +1705,9 @@ void UpdateDummyEffectNode(ObjectPaintProperties& properties,
}
} // namespace
+
TEST_P(AnimationCompositorAnimationsTest,
CanStartElementOnCompositorTransformBasedOnPaintProperties) {
- if (!RuntimeEnabledFeatures::CompositeAfterPaintEnabled())
- return;
-
Persistent<Element> element = GetDocument().CreateElementForBinding("shared");
LayoutObjectProxy* layout_object = LayoutObjectProxy::Create(element.Get());
layout_object->EnsureIdForTestingProxy();
@@ -1668,9 +1740,6 @@ TEST_P(AnimationCompositorAnimationsTest,
TEST_P(AnimationCompositorAnimationsTest,
CanStartElementOnCompositorEffectBasedOnPaintProperties) {
- if (!RuntimeEnabledFeatures::CompositeAfterPaintEnabled())
- return;
-
Persistent<Element> element = GetDocument().CreateElementForBinding("shared");
LayoutObjectProxy* layout_object = LayoutObjectProxy::Create(element.Get());
layout_object->EnsureIdForTestingProxy();
@@ -1766,8 +1835,9 @@ TEST_P(AnimationCompositorAnimationsTest, TrackRafAnimationNoneRegistered) {
}
TEST_P(AnimationCompositorAnimationsTest, CompositedTransformAnimation) {
- // TODO(wangxianzhu): Fix this test for CompositeAfterPaint.
- if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled())
+ if (!RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled() ||
+ // TODO(wangxianzhu): Fix this test for CompositeAfterPaint.
+ RuntimeEnabledFeatures::CompositeAfterPaintEnabled())
return;
LoadTestData("transform-animation.html");
@@ -1778,22 +1848,20 @@ TEST_P(AnimationCompositorAnimationsTest, CompositedTransformAnimation) {
ASSERT_NE(nullptr, properties);
const auto* transform = properties->Transform();
ASSERT_NE(nullptr, transform);
- if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled() ||
- RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) {
- EXPECT_TRUE(transform->HasDirectCompositingReasons());
- EXPECT_TRUE(transform->HasActiveTransformAnimation());
- // Make sure the animation state is initialized in paint properties.
- auto* property_trees =
- document->View()->RootCcLayer()->layer_tree_host()->property_trees();
- auto* cc_transform = property_trees->transform_tree.Node(
- property_trees->element_id_to_transform_node_index
- [transform->GetCompositorElementId()]);
- ASSERT_NE(nullptr, cc_transform);
- EXPECT_TRUE(cc_transform->has_potential_animation);
- EXPECT_TRUE(cc_transform->is_currently_animating);
- EXPECT_EQ(cc::kNotScaled, cc_transform->starting_animation_scale);
- EXPECT_EQ(cc::kNotScaled, cc_transform->maximum_animation_scale);
- }
+ EXPECT_TRUE(transform->HasDirectCompositingReasons());
+ EXPECT_TRUE(transform->HasActiveTransformAnimation());
+
+ // Make sure the animation state is initialized in paint properties.
+ auto* property_trees =
+ document->View()->RootCcLayer()->layer_tree_host()->property_trees();
+ auto* cc_transform = property_trees->transform_tree.Node(
+ property_trees->element_id_to_transform_node_index
+ [transform->GetCompositorElementId()]);
+ ASSERT_NE(nullptr, cc_transform);
+ EXPECT_TRUE(cc_transform->has_potential_animation);
+ EXPECT_TRUE(cc_transform->is_currently_animating);
+ EXPECT_EQ(cc::kNotScaled, cc_transform->starting_animation_scale);
+ EXPECT_EQ(cc::kNotScaled, cc_transform->maximum_animation_scale);
// Make sure the animation is started on the compositor.
EXPECT_EQ(CheckCanStartElementOnCompositor(*target),
@@ -1805,8 +1873,9 @@ TEST_P(AnimationCompositorAnimationsTest, CompositedTransformAnimation) {
}
TEST_P(AnimationCompositorAnimationsTest, CompositedScaleAnimation) {
- // TODO(wangxianzhu): Fix this test for CompositeAfterPaint.
- if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled())
+ if (!RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled() ||
+ // TODO(wangxianzhu): Fix this test for CompositeAfterPaint.
+ RuntimeEnabledFeatures::CompositeAfterPaintEnabled())
return;
LoadTestData("scale-animation.html");
@@ -1817,22 +1886,20 @@ TEST_P(AnimationCompositorAnimationsTest, CompositedScaleAnimation) {
ASSERT_NE(nullptr, properties);
const auto* transform = properties->Transform();
ASSERT_NE(nullptr, transform);
- if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled() ||
- RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) {
- EXPECT_TRUE(transform->HasDirectCompositingReasons());
- EXPECT_TRUE(transform->HasActiveTransformAnimation());
- // Make sure the animation state is initialized in paint properties.
- auto* property_trees =
- document->View()->RootCcLayer()->layer_tree_host()->property_trees();
- auto* cc_transform = property_trees->transform_tree.Node(
- property_trees->element_id_to_transform_node_index
- [transform->GetCompositorElementId()]);
- ASSERT_NE(nullptr, cc_transform);
- EXPECT_TRUE(cc_transform->has_potential_animation);
- EXPECT_TRUE(cc_transform->is_currently_animating);
- EXPECT_EQ(2.f, cc_transform->starting_animation_scale);
- EXPECT_EQ(5.f, cc_transform->maximum_animation_scale);
- }
+ EXPECT_TRUE(transform->HasDirectCompositingReasons());
+ EXPECT_TRUE(transform->HasActiveTransformAnimation());
+
+ // Make sure the animation state is initialized in paint properties.
+ auto* property_trees =
+ document->View()->RootCcLayer()->layer_tree_host()->property_trees();
+ auto* cc_transform = property_trees->transform_tree.Node(
+ property_trees->element_id_to_transform_node_index
+ [transform->GetCompositorElementId()]);
+ ASSERT_NE(nullptr, cc_transform);
+ EXPECT_TRUE(cc_transform->has_potential_animation);
+ EXPECT_TRUE(cc_transform->is_currently_animating);
+ EXPECT_EQ(2.f, cc_transform->starting_animation_scale);
+ EXPECT_EQ(5.f, cc_transform->maximum_animation_scale);
// Make sure the animation is started on the compositor.
EXPECT_EQ(CheckCanStartElementOnCompositor(*target),
diff --git a/chromium/third_party/blink/renderer/core/animation/css/compositor_keyframe_color.h b/chromium/third_party/blink/renderer/core/animation/css/compositor_keyframe_color.h
new file mode 100644
index 00000000000..8a83f4a92a4
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/animation/css/compositor_keyframe_color.h
@@ -0,0 +1,36 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_CSS_COMPOSITOR_KEYFRAME_COLOR_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_CSS_COMPOSITOR_KEYFRAME_COLOR_H_
+
+#include "third_party/blink/renderer/core/animation/css/compositor_keyframe_value.h"
+#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/skia/include/core/SkColor.h"
+
+namespace blink {
+
+class CORE_EXPORT CompositorKeyframeColor final
+ : public CompositorKeyframeValue {
+ public:
+ CompositorKeyframeColor(SkColor color) : color_(color) {}
+ ~CompositorKeyframeColor() override = default;
+
+ static CompositorKeyframeColor* Create(SkColor color) {
+ return MakeGarbageCollected<CompositorKeyframeColor>(color);
+ }
+
+ SkColor ToColor() const { return color_; }
+
+ private:
+ Type GetType() const override { return Type::kColor; }
+
+ SkColor color_;
+};
+
+DEFINE_COMPOSITOR_KEYFRAME_VALUE_TYPE_CASTS(CompositorKeyframeColor, IsColor());
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_CSS_COMPOSITOR_KEYFRAME_COLOR_H_
diff --git a/chromium/third_party/blink/renderer/core/animation/css/compositor_keyframe_value.h b/chromium/third_party/blink/renderer/core/animation/css/compositor_keyframe_value.h
index cec31057fa9..26bef21a63e 100644
--- a/chromium/third_party/blink/renderer/core/animation/css/compositor_keyframe_value.h
+++ b/chromium/third_party/blink/renderer/core/animation/css/compositor_keyframe_value.h
@@ -21,17 +21,17 @@ class CORE_EXPORT CompositorKeyframeValue
return GetType() == Type::kFilterOperations;
}
bool IsTransform() const { return GetType() == Type::kTransform; }
+ bool IsColor() const { return GetType() == Type::kColor; }
virtual void Trace(Visitor*) {}
- protected:
enum class Type {
kDouble,
kFilterOperations,
kTransform,
+ kColor,
};
- private:
virtual Type GetType() const = 0;
};
diff --git a/chromium/third_party/blink/renderer/core/animation/css/compositor_keyframe_value_factory.cc b/chromium/third_party/blink/renderer/core/animation/css/compositor_keyframe_value_factory.cc
index 306e8a5c626..44b5febf135 100644
--- a/chromium/third_party/blink/renderer/core/animation/css/compositor_keyframe_value_factory.cc
+++ b/chromium/third_party/blink/renderer/core/animation/css/compositor_keyframe_value_factory.cc
@@ -5,10 +5,12 @@
#include "third_party/blink/renderer/core/animation/css/compositor_keyframe_value_factory.h"
#include "third_party/blink/renderer/core/animation/compositor_animations.h"
+#include "third_party/blink/renderer/core/animation/css/compositor_keyframe_color.h"
#include "third_party/blink/renderer/core/animation/css/compositor_keyframe_double.h"
#include "third_party/blink/renderer/core/animation/css/compositor_keyframe_filter_operations.h"
#include "third_party/blink/renderer/core/animation/css/compositor_keyframe_transform.h"
#include "third_party/blink/renderer/core/animation/property_handle.h"
+#include "third_party/blink/renderer/core/css/css_color_value.h"
#include "third_party/blink/renderer/core/css/properties/css_property.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
@@ -68,11 +70,22 @@ CompositorKeyframeValue* CompositorKeyframeValueFactory::Create(
}
const AtomicString& property_name = property.CustomPropertyName();
const CSSValue* value = style.GetVariableValue(property_name);
+
const auto* primitive_value = DynamicTo<CSSPrimitiveValue>(value);
- if (!primitive_value || !primitive_value->IsNumber())
- return nullptr;
+ if (primitive_value && primitive_value->IsNumber()) {
+ return CompositorKeyframeDouble::Create(
+ primitive_value->GetFloatValue());
+ }
- return CompositorKeyframeDouble::Create(primitive_value->GetFloatValue());
+ // TODO: Add supported for interpolable color values from
+ // CSSIdentifierValue when given a value of currentcolor
+ if (const auto* color_value = DynamicTo<cssvalue::CSSColorValue>(value)) {
+ Color color = color_value->Value();
+ return CompositorKeyframeColor::Create(SkColorSetARGB(
+ color.Alpha(), color.Red(), color.Green(), color.Blue()));
+ }
+
+ return nullptr;
}
default:
NOTREACHED();
diff --git a/chromium/third_party/blink/renderer/core/animation/css/compositor_keyframe_value_factory.h b/chromium/third_party/blink/renderer/core/animation/css/compositor_keyframe_value_factory.h
index 3a75ba3bca1..d4e55a9a6b1 100644
--- a/chromium/third_party/blink/renderer/core/animation/css/compositor_keyframe_value_factory.h
+++ b/chromium/third_party/blink/renderer/core/animation/css/compositor_keyframe_value_factory.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_CSS_COMPOSITOR_KEYFRAME_VALUE_FACTORY_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_CSS_COMPOSITOR_KEYFRAME_VALUE_FACTORY_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/animation/css/css_animation_update.h b/chromium/third_party/blink/renderer/core/animation/css/css_animation_update.h
index bfe0f26c679..bc051a4a598 100644
--- a/chromium/third_party/blink/renderer/core/animation/css/css_animation_update.h
+++ b/chromium/third_party/blink/renderer/core/animation/css/css_animation_update.h
@@ -12,7 +12,7 @@
#include "third_party/blink/renderer/core/animation/keyframe_effect_model.h"
#include "third_party/blink/renderer/core/css/css_keyframes_rule.h"
#include "third_party/blink/renderer/core/css/css_property_equality.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
@@ -97,7 +97,7 @@ namespace blink {
// This class stores the CSS Animations/Transitions information we use during a
// style recalc. This includes updates to animations/transitions as well as the
// Interpolations to be applied.
-class CSSAnimationUpdate final {
+class CORE_EXPORT CSSAnimationUpdate final {
DISALLOW_NEW();
public:
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 29de56af684..9a28ae4d004 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
@@ -65,13 +65,13 @@
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/events/animation_event.h"
#include "third_party/blink/renderer/core/events/transition_event.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/layout/layout_object.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/style_property_shorthand.h"
#include "third_party/blink/renderer/platform/animation/timing_function.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
namespace blink {
@@ -376,7 +376,7 @@ void CSSAnimations::CalculateAnimationUpdate(CSSAnimationUpdate& update,
Timing specified_timing = timing;
scoped_refptr<TimingFunction> keyframe_timing_function =
timing.timing_function;
- timing.timing_function = Timing::Defaults().timing_function;
+ timing.timing_function = Timing().timing_function;
StyleRuleKeyframes* keyframes_rule =
resolver->FindKeyframesRule(element_for_scoping, name);
@@ -494,12 +494,6 @@ void CSSAnimations::MaybeApplyPendingUpdate(Element* element) {
previous_active_interpolations_for_standard_animations_.swap(
pending_update_.ActiveInterpolationsForStandardAnimations());
- // FIXME: cancelling, pausing, unpausing animations all query
- // compositingState, which is not necessarily up to date here
- // since we call this from recalc style.
- // https://code.google.com/p/chromium/issues/detail?id=339847
- DisableCompositingQueryAsserts disabler;
-
for (wtf_size_t paused_index :
pending_update_.AnimationIndicesWithPauseToggled()) {
Animation& animation = *running_animations_[paused_index]->animation;
@@ -565,7 +559,7 @@ void CSSAnimations::MaybeApplyPendingUpdate(Element* element) {
Animation* animation = transitions_.Take(property).animation;
KeyframeEffect* effect = ToKeyframeEffect(animation->effect());
- if (effect->HasActiveAnimationsOnCompositor(property) &&
+ if (effect && effect->HasActiveAnimationsOnCompositor(property) &&
pending_update_.NewTransitions().find(property) !=
pending_update_.NewTransitions().end() &&
!animation->Limited()) {
@@ -677,7 +671,7 @@ void CSSAnimations::CalculateTransitionUpdateForProperty(
state.update.CancelTransition(property);
KeyframeEffect* effect =
ToKeyframeEffect(running_transition->animation->effect());
- if (effect->HasActiveAnimationsOnCompositor())
+ if (effect && effect->HasActiveAnimationsOnCompositor())
retargeted_compositor_transition = running_transition;
DCHECK(!state.animating_element->GetElementAnimations() ||
!state.animating_element->GetElementAnimations()
@@ -1142,21 +1136,21 @@ bool CSSAnimations::AnimationEventDelegate::RequiresIterationEvents(
void CSSAnimations::AnimationEventDelegate::OnEventCondition(
const AnimationEffect& animation_node) {
- const AnimationEffect::Phase current_phase = animation_node.GetPhase();
+ const Timing::Phase current_phase = animation_node.GetPhase();
const double current_iteration = animation_node.CurrentIteration();
if (previous_phase_ != current_phase &&
- (current_phase == AnimationEffect::kPhaseActive ||
- current_phase == AnimationEffect::kPhaseAfter) &&
- (previous_phase_ == AnimationEffect::kPhaseNone ||
- previous_phase_ == AnimationEffect::kPhaseBefore)) {
+ (current_phase == Timing::kPhaseActive ||
+ current_phase == Timing::kPhaseAfter) &&
+ (previous_phase_ == Timing::kPhaseNone ||
+ previous_phase_ == Timing::kPhaseBefore)) {
const double start_delay = animation_node.SpecifiedTiming().start_delay;
const double elapsed_time = start_delay < 0 ? -start_delay : 0;
MaybeDispatch(Document::kAnimationStartListener,
event_type_names::kAnimationstart, elapsed_time);
}
- if (current_phase == AnimationEffect::kPhaseActive &&
+ if (current_phase == Timing::kPhaseActive &&
previous_phase_ == current_phase &&
previous_iteration_ != current_iteration) {
// We fire only a single event for all iterations that terminate
@@ -1171,11 +1165,11 @@ void CSSAnimations::AnimationEventDelegate::OnEventCondition(
elapsed_time.InSecondsF());
}
- if (current_phase == AnimationEffect::kPhaseAfter &&
- previous_phase_ != AnimationEffect::kPhaseAfter) {
+ if (current_phase == Timing::kPhaseAfter &&
+ previous_phase_ != Timing::kPhaseAfter) {
MaybeDispatch(Document::kAnimationEndListener,
event_type_names::kAnimationend,
- animation_node.RepeatedDuration());
+ animation_node.SpecifiedTiming().ActiveDuration());
}
previous_phase_ = current_phase;
@@ -1193,12 +1187,12 @@ EventTarget* CSSAnimations::TransitionEventDelegate::GetEventTarget() const {
void CSSAnimations::TransitionEventDelegate::OnEventCondition(
const AnimationEffect& animation_node) {
- const AnimationEffect::Phase current_phase = animation_node.GetPhase();
+ const Timing::Phase current_phase = animation_node.GetPhase();
if (current_phase == previous_phase_)
return;
if (GetDocument().HasListenerType(Document::kTransitionRunListener)) {
- if (previous_phase_ == AnimationEffect::kPhaseNone) {
+ if (previous_phase_ == Timing::kPhaseNone) {
EnqueueEvent(
event_type_names::kTransitionrun,
StartTimeFromDelay(animation_node.SpecifiedTiming().start_delay));
@@ -1206,16 +1200,16 @@ void CSSAnimations::TransitionEventDelegate::OnEventCondition(
}
if (GetDocument().HasListenerType(Document::kTransitionStartListener)) {
- if ((current_phase == AnimationEffect::kPhaseActive ||
- current_phase == AnimationEffect::kPhaseAfter) &&
- (previous_phase_ == AnimationEffect::kPhaseNone ||
- previous_phase_ == AnimationEffect::kPhaseBefore)) {
+ if ((current_phase == Timing::kPhaseActive ||
+ current_phase == Timing::kPhaseAfter) &&
+ (previous_phase_ == Timing::kPhaseNone ||
+ previous_phase_ == Timing::kPhaseBefore)) {
EnqueueEvent(
event_type_names::kTransitionstart,
StartTimeFromDelay(animation_node.SpecifiedTiming().start_delay));
- } else if ((current_phase == AnimationEffect::kPhaseActive ||
- current_phase == AnimationEffect::kPhaseBefore) &&
- previous_phase_ == AnimationEffect::kPhaseAfter) {
+ } else if ((current_phase == Timing::kPhaseActive ||
+ current_phase == Timing::kPhaseBefore) &&
+ previous_phase_ == Timing::kPhaseAfter) {
// If the transition is progressing backwards it is considered to have
// started at the end position.
EnqueueEvent(
@@ -1225,16 +1219,16 @@ void CSSAnimations::TransitionEventDelegate::OnEventCondition(
}
if (GetDocument().HasListenerType(Document::kTransitionEndListener)) {
- if (current_phase == AnimationEffect::kPhaseAfter &&
- (previous_phase_ == AnimationEffect::kPhaseActive ||
- previous_phase_ == AnimationEffect::kPhaseBefore ||
- previous_phase_ == AnimationEffect::kPhaseNone)) {
+ if (current_phase == Timing::kPhaseAfter &&
+ (previous_phase_ == Timing::kPhaseActive ||
+ previous_phase_ == Timing::kPhaseBefore ||
+ previous_phase_ == Timing::kPhaseNone)) {
EnqueueEvent(
event_type_names::kTransitionend,
animation_node.SpecifiedTiming().iteration_duration->InSecondsF());
- } else if (current_phase == AnimationEffect::kPhaseBefore &&
- (previous_phase_ == AnimationEffect::kPhaseActive ||
- previous_phase_ == AnimationEffect::kPhaseAfter)) {
+ } else if (current_phase == Timing::kPhaseBefore &&
+ (previous_phase_ == Timing::kPhaseActive ||
+ previous_phase_ == Timing::kPhaseAfter)) {
// If the transition is progressing backwards it is considered to have
// ended at the start position.
EnqueueEvent(
@@ -1244,13 +1238,13 @@ void CSSAnimations::TransitionEventDelegate::OnEventCondition(
}
if (GetDocument().HasListenerType(Document::kTransitionCancelListener)) {
- if (current_phase == AnimationEffect::kPhaseNone) {
+ if (current_phase == Timing::kPhaseNone) {
// Per the css-transitions-2 spec, transitioncancel is fired with the
// "active time of the animation at the moment it was cancelled,
// calculated using a fill mode of both".
double cancel_active_time = CalculateActiveTime(
- animation_node.RepeatedDuration(), Timing::FillMode::BOTH,
- animation_node.LocalTime(), previous_phase_,
+ animation_node.SpecifiedTiming().ActiveDuration(),
+ Timing::FillMode::BOTH, animation_node.LocalTime(), previous_phase_,
animation_node.SpecifiedTiming());
EnqueueEvent(event_type_names::kTransitioncancel, cancel_active_time);
}
diff --git a/chromium/third_party/blink/renderer/core/animation/css/css_animations.h b/chromium/third_party/blink/renderer/core/animation/css/css_animations.h
index ae17144a071..3d50f5b19db 100644
--- a/chromium/third_party/blink/renderer/core/animation/css/css_animations.h
+++ b/chromium/third_party/blink/renderer/core/animation/css/css_animations.h
@@ -51,7 +51,7 @@ class Element;
class StylePropertyShorthand;
class StyleResolver;
-class CSSAnimations final {
+class CORE_EXPORT CSSAnimations final {
DISALLOW_NEW();
public:
@@ -205,7 +205,7 @@ class CSSAnimations final {
AnimationEventDelegate(Element* animation_target, const AtomicString& name)
: animation_target_(animation_target),
name_(name),
- previous_phase_(AnimationEffect::kPhaseNone),
+ previous_phase_(Timing::kPhaseNone),
previous_iteration_(NullValue()) {}
bool RequiresIterationEvents(const AnimationEffect&) override;
void OnEventCondition(const AnimationEffect&) override;
@@ -221,7 +221,7 @@ class CSSAnimations final {
double elapsed_time);
Member<Element> animation_target_;
const AtomicString name_;
- AnimationEffect::Phase previous_phase_;
+ Timing::Phase previous_phase_;
double previous_iteration_;
};
@@ -231,7 +231,7 @@ class CSSAnimations final {
const PropertyHandle& property)
: transition_target_(transition_target),
property_(property),
- previous_phase_(AnimationEffect::kPhaseNone) {}
+ previous_phase_(Timing::kPhaseNone) {}
bool RequiresIterationEvents(const AnimationEffect&) override {
return false;
}
@@ -248,7 +248,7 @@ class CSSAnimations final {
Member<Element> transition_target_;
PropertyHandle property_;
- AnimationEffect::Phase previous_phase_;
+ Timing::Phase previous_phase_;
};
DISALLOW_COPY_AND_ASSIGN(CSSAnimations);
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 d029e8afe6a..a1d95df3681 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
@@ -22,10 +22,12 @@ class CSSAnimationsTest : public RenderingTest {
void SetUp() override {
platform()->SetAutoAdvanceNowToPendingTasks(false);
- // Advance timer manually as RenderingTest expects the time to be non-zero.
- platform()->AdvanceClockSeconds(1.);
- RenderingTest::SetUp();
EnableCompositing();
+ RenderingTest::SetUp();
+ SetUpAnimationClockForTesting();
+ // Advance timer to document time.
+ platform()->AdvanceClockSeconds(
+ GetDocument().Timeline().ZeroTime().since_origin().InSecondsF());
}
void TearDown() override {
@@ -35,14 +37,19 @@ class CSSAnimationsTest : public RenderingTest {
void StartAnimationOnCompositor(Animation* animation) {
static_cast<CompositorAnimationDelegate*>(animation)
- ->NotifyAnimationStarted(
- (CurrentTimeTicks() - base::TimeTicks()).InSecondsF(),
- animation->CompositorGroup());
+ ->NotifyAnimationStarted(platform()
+ ->test_task_runner()
+ ->NowTicks()
+ .since_origin()
+ .InSecondsF(),
+ animation->CompositorGroup());
}
void AdvanceClockSeconds(double seconds) {
platform()->AdvanceClockSeconds(seconds);
platform()->RunUntilIdle();
+ GetPage().Animator().ServiceScriptedAnimations(
+ platform()->test_task_runner()->NowTicks());
}
double GetContrastFilterAmount(Element* element) {
@@ -53,6 +60,11 @@ class CSSAnimationsTest : public RenderingTest {
return static_cast<const BasicComponentTransferFilterOperation*>(filter)
->Amount();
}
+
+ private:
+ void SetUpAnimationClockForTesting() {
+ GetPage().Animator().Clock().ResetTimeForTesting();
+ }
};
// Verify that a composited animation is retargeted according to its composited
@@ -79,15 +91,13 @@ TEST_F(CSSAnimationsTest, RetargetedTransition) {
// Starting the second transition should retarget the active transition.
element->setAttribute(html_names::kClassAttr, "contrast2");
- GetPage().Animator().ServiceScriptedAnimations(CurrentTimeTicks());
UpdateAllLifecyclePhasesForTest();
- EXPECT_NEAR(0.6, GetContrastFilterAmount(element), 0.00000000001);
+ EXPECT_NEAR(0.6, GetContrastFilterAmount(element), 0.0000000001);
// As it has been retargeted, advancing halfway should go to 0.3.
AdvanceClockSeconds(0.5);
- GetPage().Animator().ServiceScriptedAnimations(CurrentTimeTicks());
UpdateAllLifecyclePhasesForTest();
- EXPECT_NEAR(0.3, GetContrastFilterAmount(element), 0.00000000001);
+ EXPECT_NEAR(0.3, GetContrastFilterAmount(element), 0.0000000001);
}
// Test that when an incompatible in progress compositor transition
diff --git a/chromium/third_party/blink/renderer/core/animation/css/css_timing_data.h b/chromium/third_party/blink/renderer/core/animation/css/css_timing_data.h
index 8d119074397..1d0ee6a3908 100644
--- a/chromium/third_party/blink/renderer/core/animation/css/css_timing_data.h
+++ b/chromium/third_party/blink/renderer/core/animation/css/css_timing_data.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/platform/animation/timing_function.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/animation/css_angle_interpolation_type.cc b/chromium/third_party/blink/renderer/core/animation/css_angle_interpolation_type.cc
index c0db244170f..832abb898d7 100644
--- a/chromium/third_party/blink/renderer/core/animation/css_angle_interpolation_type.cc
+++ b/chromium/third_party/blink/renderer/core/animation/css_angle_interpolation_type.cc
@@ -4,6 +4,7 @@
#include "third_party/blink/renderer/core/animation/css_angle_interpolation_type.h"
+#include "third_party/blink/renderer/core/css/css_numeric_literal_value.h"
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
namespace blink {
@@ -29,8 +30,8 @@ const CSSValue* CSSAngleInterpolationType::CreateCSSValue(
const InterpolableValue& value,
const NonInterpolableValue*,
const StyleResolverState&) const {
- return CSSPrimitiveValue::Create(ToInterpolableNumber(value).Value(),
- CSSPrimitiveValue::UnitType::kDegrees);
+ return CSSNumericLiteralValue::Create(ToInterpolableNumber(value).Value(),
+ CSSPrimitiveValue::UnitType::kDegrees);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/animation/css_custom_length_interpolation_type.cc b/chromium/third_party/blink/renderer/core/animation/css_custom_length_interpolation_type.cc
new file mode 100644
index 00000000000..b1e0986b5a6
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/animation/css_custom_length_interpolation_type.cc
@@ -0,0 +1,51 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/animation/css_custom_length_interpolation_type.h"
+
+#include "third_party/blink/renderer/core/animation/length_interpolation_functions.h"
+#include "third_party/blink/renderer/core/css/css_primitive_value.h"
+
+namespace blink {
+
+namespace {
+
+bool HasPercentage(const NonInterpolableValue* non_interpolable_value) {
+ return LengthInterpolationFunctions::HasPercentage(non_interpolable_value);
+}
+
+bool HasPercentage(const InterpolationValue& value) {
+ return HasPercentage(value.non_interpolable_value.get());
+}
+
+} // namespace
+
+InterpolationValue CSSCustomLengthInterpolationType::MaybeConvertNeutral(
+ const InterpolationValue&,
+ ConversionCheckers&) const {
+ return InterpolationValue(
+ LengthInterpolationFunctions::CreateNeutralInterpolableValue());
+}
+
+InterpolationValue CSSCustomLengthInterpolationType::MaybeConvertValue(
+ const CSSValue& value,
+ const StyleResolverState*,
+ ConversionCheckers&) const {
+ InterpolationValue interpolation_value =
+ LengthInterpolationFunctions::MaybeConvertCSSValue(value);
+ if (HasPercentage(interpolation_value))
+ return nullptr;
+ return interpolation_value;
+}
+
+const CSSValue* CSSCustomLengthInterpolationType::CreateCSSValue(
+ const InterpolableValue& interpolable_value,
+ const NonInterpolableValue* non_interpolable_value,
+ const StyleResolverState&) const {
+ DCHECK(!HasPercentage(non_interpolable_value));
+ return LengthInterpolationFunctions::CreateCSSValue(
+ interpolable_value, non_interpolable_value, kValueRangeAll);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/animation/css_custom_length_interpolation_type.h b/chromium/third_party/blink/renderer/core/animation/css_custom_length_interpolation_type.h
new file mode 100644
index 00000000000..1b20ad93fb9
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/animation/css_custom_length_interpolation_type.h
@@ -0,0 +1,59 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_CSS_CUSTOM_LENGTH_INTERPOLATION_TYPE_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_CSS_CUSTOM_LENGTH_INTERPOLATION_TYPE_H_
+
+#include "third_party/blink/renderer/core/animation/css_interpolation_type.h"
+
+namespace blink {
+
+class CSSCustomLengthInterpolationType : public CSSInterpolationType {
+ public:
+ CSSCustomLengthInterpolationType(PropertyHandle property,
+ const PropertyRegistration* registration)
+ : CSSInterpolationType(property, registration) {
+ DCHECK(property.IsCSSCustomProperty());
+ }
+
+ InterpolationValue MaybeConvertNeutral(const InterpolationValue& underlying,
+ ConversionCheckers&) const final;
+ InterpolationValue MaybeConvertValue(const CSSValue&,
+ const StyleResolverState*,
+ ConversionCheckers&) const final;
+
+ const CSSValue* CreateCSSValue(const InterpolableValue&,
+ const NonInterpolableValue*,
+ const StyleResolverState&) const final;
+
+ private:
+ // These methods only apply to CSSInterpolationTypes used by standard CSS
+ // properties.
+ // CSSCustomLengthInterpolationType is only accessible via registered custom
+ // CSS properties.
+ InterpolationValue MaybeConvertStandardPropertyUnderlyingValue(
+ const ComputedStyle&) const final {
+ NOTREACHED();
+ return nullptr;
+ }
+ void ApplyStandardPropertyValue(const InterpolableValue&,
+ const NonInterpolableValue*,
+ StyleResolverState&) const final {
+ NOTREACHED();
+ }
+ InterpolationValue MaybeConvertInitial(const StyleResolverState&,
+ ConversionCheckers&) const final {
+ NOTREACHED();
+ return nullptr;
+ }
+ InterpolationValue MaybeConvertInherit(const StyleResolverState&,
+ ConversionCheckers&) const final {
+ NOTREACHED();
+ return nullptr;
+ }
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_CSS_CUSTOM_LENGTH_INTERPOLATION_TYPE_H_
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 25eba0fe7d5..be7a9bada05 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
@@ -20,17 +20,25 @@ DEFINE_NON_INTERPOLABLE_VALUE_TYPE(CSSDefaultNonInterpolableValue);
InterpolationValue CSSDefaultInterpolationType::MaybeConvertSingle(
const PropertySpecificKeyframe& keyframe,
- const InterpolationEnvironment&,
+ const InterpolationEnvironment& environment,
const InterpolationValue&,
ConversionCheckers&) const {
- if (!ToCSSPropertySpecificKeyframe(keyframe).Value()) {
+ const CSSValue* css_value = ToCSSPropertySpecificKeyframe(keyframe).Value();
+
+ if (!css_value) {
DCHECK(keyframe.IsNeutral());
return nullptr;
}
- return InterpolationValue(
- std::make_unique<InterpolableList>(0),
- CSSDefaultNonInterpolableValue::Create(
- ToCSSPropertySpecificKeyframe(keyframe).Value()));
+
+ if (RuntimeEnabledFeatures::CSSCascadeEnabled()) {
+ css_value = ToCSSInterpolationEnvironment(environment)
+ .Resolve(GetProperty(), css_value);
+ if (!css_value)
+ return nullptr;
+ }
+
+ return InterpolationValue(std::make_unique<InterpolableList>(0),
+ CSSDefaultNonInterpolableValue::Create(css_value));
}
void CSSDefaultInterpolationType::Apply(
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 9addee2037e..5bc7819639a 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
@@ -8,6 +8,7 @@
#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_numeric_literal_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"
@@ -59,8 +60,8 @@ class CSSImageNonInterpolableValue : public NonInterpolableValue {
return end_;
return MakeGarbageCollected<cssvalue::CSSCrossfadeValue>(
start_, end_,
- CSSPrimitiveValue::Create(progress,
- CSSPrimitiveValue::UnitType::kNumber));
+ CSSNumericLiteralValue::Create(progress,
+ CSSPrimitiveValue::UnitType::kNumber));
}
DECLARE_NON_INTERPOLABLE_VALUE_TYPE();
diff --git a/chromium/third_party/blink/renderer/core/animation/css_interpolation_environment.h b/chromium/third_party/blink/renderer/core/animation/css_interpolation_environment.h
index 03f270ca387..789ee655a65 100644
--- a/chromium/third_party/blink/renderer/core/animation/css_interpolation_environment.h
+++ b/chromium/third_party/blink/renderer/core/animation/css_interpolation_environment.h
@@ -6,6 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_CSS_INTERPOLATION_ENVIRONMENT_H_
#include "third_party/blink/renderer/core/animation/interpolation_environment.h"
+#include "third_party/blink/renderer/core/css/resolver/style_cascade.h"
#include "third_party/blink/renderer/core/css/resolver/style_resolver_state.h"
namespace blink {
@@ -24,6 +25,16 @@ class CSSInterpolationEnvironment : public InterpolationEnvironment {
variable_resolver_(variable_resolver) {}
explicit CSSInterpolationEnvironment(const InterpolationTypesMap& map,
+ StyleResolverState& state,
+ StyleCascade* cascade,
+ StyleCascade::Resolver* cascade_resolver)
+ : InterpolationEnvironment(map),
+ state_(&state),
+ style_(state.Style()),
+ cascade_(cascade),
+ cascade_resolver_(cascade_resolver) {}
+
+ explicit CSSInterpolationEnvironment(const InterpolationTypesMap& map,
const ComputedStyle& style)
: InterpolationEnvironment(map), style_(&style) {}
@@ -43,17 +54,36 @@ class CSSInterpolationEnvironment : public InterpolationEnvironment {
return *style_;
}
- bool HasVariableResolver() const { return variable_resolver_; }
+ bool HasVariableResolver() const {
+ DCHECK(!RuntimeEnabledFeatures::CSSCascadeEnabled());
+ return variable_resolver_;
+ }
+ // TODO(crbug.com/985023): This effective violates const.
CSSVariableResolver& VariableResolver() const {
+ DCHECK(!RuntimeEnabledFeatures::CSSCascadeEnabled());
DCHECK(HasVariableResolver());
return *variable_resolver_;
}
+ // TODO(crbug.com/985023): This effective violates const.
+ const CSSValue* Resolve(const PropertyHandle& property,
+ const CSSValue* value) const {
+ DCHECK(RuntimeEnabledFeatures::CSSCascadeEnabled());
+ DCHECK(cascade_);
+ DCHECK(cascade_resolver_);
+ if (!value)
+ return value;
+ return cascade_->Resolve(property.GetCSSPropertyName(), *value,
+ *cascade_resolver_);
+ }
+
private:
StyleResolverState* state_ = nullptr;
const ComputedStyle* style_ = nullptr;
CSSVariableResolver* variable_resolver_ = nullptr;
+ StyleCascade* cascade_ = nullptr;
+ StyleCascade::Resolver* cascade_resolver_ = nullptr;
};
DEFINE_TYPE_CASTS(CSSInterpolationEnvironment,
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 1643a750cae..a3dd8766d32 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
@@ -19,6 +19,7 @@
#include "third_party/blink/renderer/core/css/property_registration.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_cascade.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/core/style/data_equivalency.h"
@@ -26,8 +27,7 @@
namespace blink {
-class ResolvedVariableChecker
- : public CSSInterpolationType::CSSConversionChecker {
+class ResolvedVariableChecker : public CSSInterpolationType::ConversionChecker {
public:
ResolvedVariableChecker(CSSPropertyID property,
const CSSValue* variable_reference,
@@ -37,14 +37,21 @@ class ResolvedVariableChecker
resolved_value_(resolved_value) {}
private:
- bool IsValid(const StyleResolverState& state,
- const InterpolationValue& underlying) const final {
+ bool IsValid(const InterpolationEnvironment& environment,
+ const InterpolationValue&) const final {
+ const auto& css_environment = ToCSSInterpolationEnvironment(environment);
// TODO(alancutter): Just check the variables referenced instead of doing a
// full CSSValue resolve.
bool omit_animation_tainted = false;
- const CSSValue* resolved_value =
- CSSVariableResolver(state).ResolveVariableReferences(
- property_, *variable_reference_, omit_animation_tainted);
+ const CSSValue* resolved_value = nullptr;
+ if (RuntimeEnabledFeatures::CSSCascadeEnabled()) {
+ resolved_value = css_environment.Resolve(
+ PropertyHandle(CSSProperty::Get(property_)), variable_reference_);
+ } else {
+ const StyleResolverState& state = css_environment.GetState();
+ resolved_value = CSSVariableResolver(state).ResolveVariableReferences(
+ property_, *variable_reference_, omit_animation_tainted);
+ }
return DataEquivalent(resolved_value_.Get(), resolved_value);
}
@@ -94,14 +101,22 @@ class ResolvedRegisteredCustomPropertyChecker
private:
bool IsValid(const InterpolationEnvironment& environment,
const InterpolationValue&) const final {
- DCHECK(ToCSSInterpolationEnvironment(environment).HasVariableResolver());
- bool cycle_detected = false;
- scoped_refptr<CSSVariableData> resolved_tokens =
- ToCSSInterpolationEnvironment(environment)
- .VariableResolver()
- .ResolveCustomPropertyAnimationKeyframe(*declaration_,
- cycle_detected);
- DCHECK(!cycle_detected);
+ const auto& css_environment = ToCSSInterpolationEnvironment(environment);
+ scoped_refptr<CSSVariableData> resolved_tokens = nullptr;
+ if (RuntimeEnabledFeatures::CSSCascadeEnabled()) {
+ const CSSValue* resolved = css_environment.Resolve(
+ PropertyHandle(declaration_->GetName()), declaration_);
+ if (const auto* decl = DynamicTo<CSSCustomPropertyDeclaration>(resolved))
+ resolved_tokens = decl->Value();
+ } else {
+ DCHECK(css_environment.HasVariableResolver());
+ bool cycle_detected = false;
+ resolved_tokens = ToCSSInterpolationEnvironment(environment)
+ .VariableResolver()
+ .ResolveCustomPropertyAnimationKeyframe(
+ *declaration_, cycle_detected);
+ DCHECK(!cycle_detected);
+ }
return DataEquivalent(resolved_tokens, resolved_tokens_);
}
@@ -145,18 +160,23 @@ InterpolationValue CSSInterpolationType::MaybeConvertSingleInternal(
return MaybeConvertNeutral(underlying, conversion_checkers);
if (GetProperty().IsCSSCustomProperty()) {
- DCHECK(css_environment.HasVariableResolver());
return MaybeConvertCustomPropertyDeclaration(
- To<CSSCustomPropertyDeclaration>(*value), state,
- css_environment.VariableResolver(), conversion_checkers);
+ To<CSSCustomPropertyDeclaration>(*value), environment,
+ conversion_checkers);
}
if (value->IsVariableReferenceValue() ||
value->IsPendingSubstitutionValue()) {
- bool omit_animation_tainted = false;
- const CSSValue* resolved_value =
- CSSVariableResolver(state).ResolveVariableReferences(
- CssProperty().PropertyID(), *value, omit_animation_tainted);
+ const CSSValue* resolved_value = nullptr;
+ if (RuntimeEnabledFeatures::CSSCascadeEnabled()) {
+ resolved_value = css_environment.Resolve(GetProperty(), value);
+ } else {
+ bool omit_animation_tainted = false;
+ resolved_value = CSSVariableResolver(state).ResolveVariableReferences(
+ CssProperty().PropertyID(), *value, omit_animation_tainted);
+ }
+
+ DCHECK(resolved_value);
conversion_checkers.push_back(std::make_unique<ResolvedVariableChecker>(
CssProperty().PropertyID(), value, resolved_value));
value = resolved_value;
@@ -176,9 +196,12 @@ InterpolationValue CSSInterpolationType::MaybeConvertSingleInternal(
InterpolationValue CSSInterpolationType::MaybeConvertCustomPropertyDeclaration(
const CSSCustomPropertyDeclaration& declaration,
- const StyleResolverState& state,
- CSSVariableResolver& variable_resolver,
+ const InterpolationEnvironment& environment,
ConversionCheckers& conversion_checkers) const {
+ const CSSInterpolationEnvironment& css_environment =
+ ToCSSInterpolationEnvironment(environment);
+ const StyleResolverState& state = css_environment.GetState();
+
const AtomicString& name = declaration.GetName();
DCHECK_EQ(GetProperty().CustomPropertyName(), name);
@@ -209,10 +232,20 @@ InterpolationValue CSSInterpolationType::MaybeConvertCustomPropertyDeclaration(
scoped_refptr<CSSVariableData> resolved_tokens;
if (declaration.Value()->NeedsVariableResolution()) {
- bool cycle_detected = false;
- resolved_tokens = variable_resolver.ResolveCustomPropertyAnimationKeyframe(
- declaration, cycle_detected);
- DCHECK(!cycle_detected);
+ if (RuntimeEnabledFeatures::CSSCascadeEnabled()) {
+ const CSSValue* resolved =
+ css_environment.Resolve(GetProperty(), &declaration);
+ if (const auto* decl = DynamicTo<CSSCustomPropertyDeclaration>(resolved))
+ resolved_tokens = decl->Value();
+ } else {
+ CSSVariableResolver& variable_resolver =
+ css_environment.VariableResolver();
+ bool cycle_detected = false;
+ resolved_tokens =
+ variable_resolver.ResolveCustomPropertyAnimationKeyframe(
+ declaration, cycle_detected);
+ DCHECK(!cycle_detected);
+ }
conversion_checkers.push_back(
std::make_unique<ResolvedRegisteredCustomPropertyChecker>(
declaration, resolved_tokens));
@@ -283,8 +316,23 @@ void CSSInterpolationType::ApplyCustomPropertyValue(
scoped_refptr<CSSVariableData> variable_data = CSSVariableData::Create(
CSSParserTokenRange(tokens), is_animation_tainted,
needs_variable_resolution, KURL(), WTF::TextEncoding());
- ComputedStyle& style = *state.Style();
const PropertyHandle property = GetProperty();
+
+ if (RuntimeEnabledFeatures::CSSCascadeEnabled()) {
+ // When cascade is enabled, we need to go through the StyleBuilder,
+ // since the computed value is produced during ApplyProperty. (Without
+ // this, we'd end up with values like 10em on the computed style).
+ //
+ // TODO(andruud): Avoid making the CSSCustomPropertyDeclaration by allowing
+ // any CSSValue in CustomProperty::ApplyValue.
+ const CSSValue* value = MakeGarbageCollected<CSSCustomPropertyDeclaration>(
+ property.CustomPropertyName(), std::move(variable_data));
+ StyleBuilder::ApplyProperty(GetProperty().GetCSSPropertyName(), state,
+ *value);
+ return;
+ }
+
+ ComputedStyle& style = *state.Style();
const AtomicString& property_name = property.CustomPropertyName();
bool inherits = Registration().Inherits();
style.SetVariableData(property_name, std::move(variable_data), inherits);
diff --git a/chromium/third_party/blink/renderer/core/animation/css_interpolation_type.h b/chromium/third_party/blink/renderer/core/animation/css_interpolation_type.h
index ae8df46e78c..9d38ab838cc 100644
--- a/chromium/third_party/blink/renderer/core/animation/css_interpolation_type.h
+++ b/chromium/third_party/blink/renderer/core/animation/css_interpolation_type.h
@@ -12,7 +12,6 @@
namespace blink {
class CSSCustomPropertyDeclaration;
-class CSSVariableResolver;
class ComputedStyle;
class PropertyRegistration;
class StyleResolverState;
@@ -87,8 +86,7 @@ class CORE_EXPORT CSSInterpolationType : public InterpolationType {
InterpolationValue MaybeConvertCustomPropertyDeclaration(
const CSSCustomPropertyDeclaration&,
- const StyleResolverState&,
- CSSVariableResolver&,
+ const InterpolationEnvironment&,
ConversionCheckers&) const;
const PropertyRegistration& Registration() const {
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 e60c294470a..a7c0644219c 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
@@ -12,6 +12,7 @@
#include "third_party/blink/renderer/core/animation/css_border_image_length_box_interpolation_type.h"
#include "third_party/blink/renderer/core/animation/css_clip_interpolation_type.h"
#include "third_party/blink/renderer/core/animation/css_color_interpolation_type.h"
+#include "third_party/blink/renderer/core/animation/css_custom_length_interpolation_type.h"
#include "third_party/blink/renderer/core/animation/css_custom_list_interpolation_type.h"
#include "third_party/blink/renderer/core/animation/css_default_interpolation_type.h"
#include "third_party/blink/renderer/core/animation/css_filter_list_interpolation_type.h"
@@ -28,6 +29,7 @@
#include "third_party/blink/renderer/core/animation/css_offset_rotate_interpolation_type.h"
#include "third_party/blink/renderer/core/animation/css_paint_interpolation_type.h"
#include "third_party/blink/renderer/core/animation/css_path_interpolation_type.h"
+#include "third_party/blink/renderer/core/animation/css_percentage_interpolation_type.h"
#include "third_party/blink/renderer/core/animation/css_position_axis_list_interpolation_type.h"
#include "third_party/blink/renderer/core/animation/css_position_interpolation_type.h"
#include "third_party/blink/renderer/core/animation/css_ray_interpolation_type.h"
@@ -383,10 +385,14 @@ CreateInterpolationTypeForCSSSyntax(CSSSyntaxType syntax,
return std::make_unique<CSSColorInterpolationType>(property,
&registration);
case CSSSyntaxType::kLength:
+ return std::make_unique<CSSCustomLengthInterpolationType>(property,
+ &registration);
case CSSSyntaxType::kLengthPercentage:
- case CSSSyntaxType::kPercentage:
return std::make_unique<CSSLengthInterpolationType>(property,
&registration);
+ case CSSSyntaxType::kPercentage:
+ return std::make_unique<CSSPercentageInterpolationType>(property,
+ &registration);
case CSSSyntaxType::kNumber:
return std::make_unique<CSSNumberInterpolationType>(property,
&registration);
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 7b7fb41c2c4..0d278ac104b 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
@@ -10,7 +10,6 @@
#include "base/memory/ptr_util.h"
#include "third_party/blink/renderer/core/animation/length_interpolation_functions.h"
#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_identifier_value.h"
#include "third_party/blink/renderer/core/css/resolver/style_builder.h"
#include "third_party/blink/renderer/core/css/resolver/style_resolver_state.h"
diff --git a/chromium/third_party/blink/renderer/core/animation/css_number_interpolation_type.cc b/chromium/third_party/blink/renderer/core/animation/css_number_interpolation_type.cc
index 303f5ab0102..54893a3ecd2 100644
--- a/chromium/third_party/blink/renderer/core/animation/css_number_interpolation_type.cc
+++ b/chromium/third_party/blink/renderer/core/animation/css_number_interpolation_type.cc
@@ -9,6 +9,7 @@
#include "base/memory/ptr_util.h"
#include "base/optional.h"
#include "third_party/blink/renderer/core/animation/number_property_functions.h"
+#include "third_party/blink/renderer/core/css/css_numeric_literal_value.h"
#include "third_party/blink/renderer/core/css/resolver/style_builder.h"
#include "third_party/blink/renderer/core/css/resolver/style_resolver_state.h"
@@ -38,8 +39,9 @@ const CSSValue* CSSNumberInterpolationType::CreateCSSValue(
const NonInterpolableValue*,
const StyleResolverState&) const {
double number = ToInterpolableNumber(value).Value();
- return CSSPrimitiveValue::Create(round_to_integer_ ? round(number) : number,
- CSSPrimitiveValue::UnitType::kNumber);
+ return CSSNumericLiteralValue::Create(
+ round_to_integer_ ? round(number) : number,
+ CSSPrimitiveValue::UnitType::kNumber);
}
InterpolationValue CSSNumberInterpolationType::CreateNumberValue(
@@ -105,11 +107,12 @@ void CSSNumberInterpolationType::ApplyStandardPropertyValue(
double clamped_number = NumberPropertyFunctions::ClampNumber(
CssProperty(), ToInterpolableNumber(interpolable_value).Value());
if (!NumberPropertyFunctions::SetNumber(CssProperty(), *state.Style(),
- clamped_number))
+ clamped_number)) {
StyleBuilder::ApplyProperty(
GetProperty().GetCSSProperty(), state,
- *CSSPrimitiveValue::Create(clamped_number,
- CSSPrimitiveValue::UnitType::kNumber));
+ *CSSNumericLiteralValue::Create(clamped_number,
+ CSSPrimitiveValue::UnitType::kNumber));
+ }
}
} // 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 7ca959a39fe..e5b9a9a08d3 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
@@ -133,11 +133,11 @@ void CSSPaintInterpolationType::ApplyStandardPropertyValue(
switch (CssProperty().PropertyID()) {
case CSSPropertyID::kFill:
mutable_svg_style.SetFillPaint(SVGPaint(color));
- mutable_svg_style.SetVisitedLinkFillPaint(SVGPaint(color));
+ mutable_svg_style.SetInternalVisitedFillPaint(SVGPaint(color));
break;
case CSSPropertyID::kStroke:
mutable_svg_style.SetStrokePaint(SVGPaint(color));
- mutable_svg_style.SetVisitedLinkStrokePaint(SVGPaint(color));
+ mutable_svg_style.SetInternalVisitedStrokePaint(SVGPaint(color));
break;
default:
NOTREACHED();
diff --git a/chromium/third_party/blink/renderer/core/animation/css_percentage_interpolation_type.cc b/chromium/third_party/blink/renderer/core/animation/css_percentage_interpolation_type.cc
new file mode 100644
index 00000000000..46408b17701
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/animation/css_percentage_interpolation_type.cc
@@ -0,0 +1,37 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/animation/css_percentage_interpolation_type.h"
+
+#include "third_party/blink/renderer/core/css/css_numeric_literal_value.h"
+
+namespace blink {
+
+InterpolationValue CSSPercentageInterpolationType::MaybeConvertNeutral(
+ const InterpolationValue&,
+ ConversionCheckers&) const {
+ return InterpolationValue(std::make_unique<InterpolableNumber>(0));
+}
+
+InterpolationValue CSSPercentageInterpolationType::MaybeConvertValue(
+ const CSSValue& value,
+ const StyleResolverState*,
+ ConversionCheckers&) const {
+ auto* primitive_value = DynamicTo<CSSPrimitiveValue>(value);
+ if (!primitive_value || !primitive_value->IsPercentage())
+ return nullptr;
+ return InterpolationValue(
+ std::make_unique<InterpolableNumber>(primitive_value->GetDoubleValue()));
+}
+
+const CSSValue* CSSPercentageInterpolationType::CreateCSSValue(
+ const InterpolableValue& value,
+ const NonInterpolableValue*,
+ const StyleResolverState&) const {
+ return CSSNumericLiteralValue::Create(
+ ToInterpolableNumber(value).Value(),
+ CSSPrimitiveValue::UnitType::kPercentage);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/animation/css_percentage_interpolation_type.h b/chromium/third_party/blink/renderer/core/animation/css_percentage_interpolation_type.h
new file mode 100644
index 00000000000..e39ee2404b6
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/animation/css_percentage_interpolation_type.h
@@ -0,0 +1,59 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_CSS_PERCENTAGE_INTERPOLATION_TYPE_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_CSS_PERCENTAGE_INTERPOLATION_TYPE_H_
+
+#include "third_party/blink/renderer/core/animation/css_interpolation_type.h"
+
+namespace blink {
+
+class CSSPercentageInterpolationType : public CSSInterpolationType {
+ public:
+ CSSPercentageInterpolationType(PropertyHandle property,
+ const PropertyRegistration* registration)
+ : CSSInterpolationType(property, registration) {
+ DCHECK(property.IsCSSCustomProperty());
+ }
+
+ InterpolationValue MaybeConvertNeutral(const InterpolationValue& underlying,
+ ConversionCheckers&) const final;
+ InterpolationValue MaybeConvertValue(const CSSValue&,
+ const StyleResolverState*,
+ ConversionCheckers&) const final;
+
+ const CSSValue* CreateCSSValue(const InterpolableValue&,
+ const NonInterpolableValue*,
+ const StyleResolverState&) const final;
+
+ private:
+ // These methods only apply to CSSInterpolationTypes used by standard CSS
+ // properties.
+ // CSSPercentageInterpolationType is only accessible via registered custom CSS
+ // properties.
+ InterpolationValue MaybeConvertStandardPropertyUnderlyingValue(
+ const ComputedStyle&) const final {
+ NOTREACHED();
+ return nullptr;
+ }
+ void ApplyStandardPropertyValue(const InterpolableValue&,
+ const NonInterpolableValue*,
+ StyleResolverState&) const final {
+ NOTREACHED();
+ }
+ InterpolationValue MaybeConvertInitial(const StyleResolverState&,
+ ConversionCheckers&) const final {
+ NOTREACHED();
+ return nullptr;
+ }
+ InterpolationValue MaybeConvertInherit(const StyleResolverState&,
+ ConversionCheckers&) const final {
+ NOTREACHED();
+ return nullptr;
+ }
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_CSS_PERCENTAGE_INTERPOLATION_TYPE_H_
diff --git a/chromium/third_party/blink/renderer/core/animation/css_resolution_interpolation_type.cc b/chromium/third_party/blink/renderer/core/animation/css_resolution_interpolation_type.cc
index af862cd3517..14756aa9f08 100644
--- a/chromium/third_party/blink/renderer/core/animation/css_resolution_interpolation_type.cc
+++ b/chromium/third_party/blink/renderer/core/animation/css_resolution_interpolation_type.cc
@@ -4,6 +4,7 @@
#include "third_party/blink/renderer/core/animation/css_resolution_interpolation_type.h"
+#include "third_party/blink/renderer/core/css/css_numeric_literal_value.h"
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
namespace blink {
@@ -19,8 +20,7 @@ InterpolationValue CSSResolutionInterpolationType::MaybeConvertValue(
const StyleResolverState*,
ConversionCheckers&) const {
auto* primitive_value = DynamicTo<CSSPrimitiveValue>(value);
- if (!primitive_value ||
- !CSSPrimitiveValue::IsResolution(primitive_value->TypeWithCalcResolved()))
+ if (!primitive_value || !primitive_value->IsResolution())
return nullptr;
return InterpolationValue(std::make_unique<InterpolableNumber>(
primitive_value->ComputeDotsPerPixel()));
@@ -30,8 +30,9 @@ const CSSValue* CSSResolutionInterpolationType::CreateCSSValue(
const InterpolableValue& value,
const NonInterpolableValue*,
const StyleResolverState&) const {
- return CSSPrimitiveValue::Create(ToInterpolableNumber(value).Value(),
- CSSPrimitiveValue::UnitType::kDotsPerPixel);
+ return CSSNumericLiteralValue::Create(
+ ToInterpolableNumber(value).Value(),
+ CSSPrimitiveValue::UnitType::kDotsPerPixel);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/animation/css_scale_interpolation_type.cc b/chromium/third_party/blink/renderer/core/animation/css_scale_interpolation_type.cc
index 6229fa89034..7e001a96411 100644
--- a/chromium/third_party/blink/renderer/core/animation/css_scale_interpolation_type.cc
+++ b/chromium/third_party/blink/renderer/core/animation/css_scale_interpolation_type.cc
@@ -174,13 +174,21 @@ InterpolationValue CSSScaleInterpolationType::MaybeConvertValue(
const auto& list = To<CSSValueList>(value);
DCHECK(list.length() >= 1 && list.length() <= 3);
- Scale scale(1, 1, 1);
- for (wtf_size_t i = 0; i < list.length(); i++) {
- const CSSValue& item = list.Item(i);
- scale.array[i] = To<CSSPrimitiveValue>(item).GetDoubleValue();
+ if (list.length() == 1) {
+ double scale = To<CSSPrimitiveValue>(list.Item(0)).GetDoubleValue();
+ // single value defines a 2d scale according to the spec
+ // see https://drafts.csswg.org/css-transforms-2/#propdef-scale
+ return Scale(scale, scale, 1).CreateInterpolationValue();
+ } else if (list.length() == 2) {
+ double x_scale = To<CSSPrimitiveValue>(list.Item(0)).GetDoubleValue();
+ double y_scale = To<CSSPrimitiveValue>(list.Item(1)).GetDoubleValue();
+ return Scale(x_scale, y_scale, 1).CreateInterpolationValue();
+ } else {
+ double x_scale = To<CSSPrimitiveValue>(list.Item(0)).GetDoubleValue();
+ double y_scale = To<CSSPrimitiveValue>(list.Item(1)).GetDoubleValue();
+ double z_scale = To<CSSPrimitiveValue>(list.Item(2)).GetDoubleValue();
+ return Scale(x_scale, y_scale, z_scale).CreateInterpolationValue();
}
-
- return scale.CreateInterpolationValue();
}
void CSSScaleInterpolationType::AdditiveKeyframeHook(
diff --git a/chromium/third_party/blink/renderer/core/animation/css_time_interpolation_type.cc b/chromium/third_party/blink/renderer/core/animation/css_time_interpolation_type.cc
index 1b1980ddc39..6f41dba301a 100644
--- a/chromium/third_party/blink/renderer/core/animation/css_time_interpolation_type.cc
+++ b/chromium/third_party/blink/renderer/core/animation/css_time_interpolation_type.cc
@@ -4,6 +4,7 @@
#include "third_party/blink/renderer/core/animation/css_time_interpolation_type.h"
+#include "third_party/blink/renderer/core/css/css_numeric_literal_value.h"
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
namespace blink {
@@ -29,8 +30,8 @@ const CSSValue* CSSTimeInterpolationType::CreateCSSValue(
const InterpolableValue& value,
const NonInterpolableValue*,
const StyleResolverState&) const {
- return CSSPrimitiveValue::Create(ToInterpolableNumber(value).Value(),
- CSSPrimitiveValue::UnitType::kSeconds);
+ return CSSNumericLiteralValue::Create(ToInterpolableNumber(value).Value(),
+ CSSPrimitiveValue::UnitType::kSeconds);
}
} // namespace blink
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 1dd8f99ddd8..a26c050f9ba 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
@@ -9,6 +9,7 @@
#include "third_party/blink/renderer/core/animation/css_position_axis_list_interpolation_type.h"
#include "third_party/blink/renderer/core/animation/length_interpolation_functions.h"
#include "third_party/blink/renderer/core/animation/list_interpolation_functions.h"
+#include "third_party/blink/renderer/core/css/css_numeric_literal_value.h"
#include "third_party/blink/renderer/core/css/css_value_list.h"
namespace blink {
@@ -29,7 +30,7 @@ class CSSTransformOriginInterpolationType
3, [&list](wtf_size_t index) {
if (index == list.length()) {
return LengthInterpolationFunctions::MaybeConvertCSSValue(
- *CSSPrimitiveValue::Create(
+ *CSSNumericLiteralValue::Create(
0, CSSPrimitiveValue::UnitType::kPixels));
}
const CSSValue& item = list.Item(index);
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 1173a1b99eb..e596f3534d8 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
@@ -14,6 +14,7 @@
#include "third_party/blink/renderer/core/css/property_registration.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_cascade.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
@@ -27,12 +28,15 @@ class CycleChecker : public InterpolationType::ConversionChecker {
private:
bool IsValid(const InterpolationEnvironment& environment,
const InterpolationValue&) const final {
- DCHECK(ToCSSInterpolationEnvironment(environment).HasVariableResolver());
- CSSVariableResolver& variable_resolver =
- ToCSSInterpolationEnvironment(environment).VariableResolver();
+ const auto& css_environment = ToCSSInterpolationEnvironment(environment);
bool cycle_detected = false;
- variable_resolver.ResolveCustomPropertyAnimationKeyframe(*declaration_,
- cycle_detected);
+ if (RuntimeEnabledFeatures::CSSCascadeEnabled()) {
+ cycle_detected = !css_environment.Resolve(
+ PropertyHandle(declaration_->GetName()), declaration_);
+ } else {
+ css_environment.VariableResolver().ResolveCustomPropertyAnimationKeyframe(
+ *declaration_, cycle_detected);
+ }
return cycle_detected == cycle_detected_;
}
@@ -63,12 +67,16 @@ InterpolationValue CSSVarCycleInterpolationType::MaybeConvertSingle(
return nullptr;
}
- DCHECK(ToCSSInterpolationEnvironment(environment).HasVariableResolver());
- CSSVariableResolver& variable_resolver =
- ToCSSInterpolationEnvironment(environment).VariableResolver();
+ const auto& css_environment = ToCSSInterpolationEnvironment(environment);
+
bool cycle_detected = false;
- variable_resolver.ResolveCustomPropertyAnimationKeyframe(declaration,
- cycle_detected);
+ if (RuntimeEnabledFeatures::CSSCascadeEnabled()) {
+ cycle_detected = !css_environment.Resolve(GetProperty(), &declaration);
+ } else {
+ css_environment.VariableResolver().ResolveCustomPropertyAnimationKeyframe(
+ declaration, cycle_detected);
+ }
+
conversion_checkers.push_back(
std::make_unique<CycleChecker>(declaration, cycle_detected));
return cycle_detected ? CreateCycleDetectedValue() : nullptr;
diff --git a/chromium/third_party/blink/renderer/core/animation/document_animation.h b/chromium/third_party/blink/renderer/core/animation/document_animation.h
index 2cb59cb8fb4..33c5eedfb4e 100644
--- a/chromium/third_party/blink/renderer/core/animation/document_animation.h
+++ b/chromium/third_party/blink/renderer/core/animation/document_animation.h
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/animation/animation.h"
#include "third_party/blink/renderer/core/animation/document_timeline.h"
#include "third_party/blink/renderer/core/dom/document.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 9fdcfe109fa..18704dd4ee7 100644
--- a/chromium/third_party/blink/renderer/core/animation/document_animations.h
+++ b/chromium/third_party/blink/renderer/core/animation/document_animations.h
@@ -34,7 +34,7 @@
#include "base/optional.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/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 920e8e8ddb7..7c19e649a3b 100644
--- a/chromium/third_party/blink/renderer/core/animation/document_timeline.cc
+++ b/chromium/third_party/blink/renderer/core/animation/document_timeline.cc
@@ -52,6 +52,23 @@ bool CompareAnimations(const Member<Animation>& left,
const Member<Animation>& right) {
return Animation::HasLowerPriority(left.Get(), right.Get());
}
+
+// Returns the current animation time for a given |document|. This is
+// the animation clock time capped to be at least this document's
+// ZeroTime() such that the animation time is never negative when converted.
+base::TimeTicks CurrentAnimationTime(const Document* document) {
+ base::TimeTicks animation_time = document->GetAnimationClock().CurrentTime();
+ base::TimeTicks document_zero_time = document->Timeline().ZeroTime();
+
+ // The AnimationClock time may be null or less than the local document's
+ // zero time if we have not generated any frames for this document yet. If
+ // so, assume animation_time is the document zero time.
+ if (animation_time < document_zero_time)
+ return document_zero_time;
+
+ return animation_time;
+}
+
} // namespace
// This value represents 1 frame at 30Hz plus a little bit of wiggle room.
@@ -59,7 +76,7 @@ bool CompareAnimations(const Member<Animation>& left,
const double DocumentTimeline::kMinimumDelay = 0.04;
DocumentTimeline* DocumentTimeline::Create(Document* document,
- TimeDelta origin_time,
+ base::TimeDelta origin_time,
PlatformTiming* timing) {
return MakeGarbageCollected<DocumentTimeline>(document, origin_time, timing);
}
@@ -69,15 +86,16 @@ DocumentTimeline* DocumentTimeline::Create(
const DocumentTimelineOptions* options) {
Document* document = To<Document>(execution_context);
return MakeGarbageCollected<DocumentTimeline>(
- document, TimeDelta::FromMillisecondsD(options->originTime()), nullptr);
+ document, base::TimeDelta::FromMillisecondsD(options->originTime()),
+ nullptr);
}
DocumentTimeline::DocumentTimeline(Document* document,
- TimeDelta origin_time,
+ base::TimeDelta origin_time,
PlatformTiming* timing)
: document_(document),
origin_time_(origin_time),
- zero_time_(TimeTicks() + origin_time_),
+ zero_time_(base::TimeTicks() + origin_time_),
zero_time_initialized_(false),
outdated_animation_count_(0),
playback_rate_(1),
@@ -97,10 +115,10 @@ bool DocumentTimeline::IsActive() const {
return document_->GetPage();
}
-void DocumentTimeline::AnimationAttached(Animation& animation) {
- DCHECK_EQ(animation.TimelineInternal(), this);
- DCHECK(!animations_.Contains(&animation));
- animations_.insert(&animation);
+void DocumentTimeline::AnimationAttached(Animation* animation) {
+ DCHECK_EQ(&animation->GetDocument()->Timeline(), this);
+ DCHECK(!animations_.Contains(animation));
+ animations_.insert(animation);
}
Animation* DocumentTimeline::Play(AnimationEffect* child) {
@@ -186,7 +204,7 @@ void DocumentTimeline::ScheduleNextService() {
}
void DocumentTimeline::DocumentTimelineTiming::WakeAfter(double duration) {
- TimeDelta duration_delta = TimeDelta::FromSecondsD(duration);
+ base::TimeDelta duration_delta = base::TimeDelta::FromSecondsD(duration);
if (timer_.IsActive() && timer_.NextFireInterval() < duration_delta)
return;
timer_.StartOneShot(duration_delta, FROM_HERE);
@@ -202,7 +220,7 @@ void DocumentTimeline::DocumentTimelineTiming::Trace(blink::Visitor* visitor) {
DocumentTimeline::PlatformTiming::Trace(visitor);
}
-TimeTicks DocumentTimeline::ZeroTime() {
+base::TimeTicks DocumentTimeline::ZeroTime() {
if (!zero_time_initialized_ && document_->Loader()) {
zero_time_ = document_->Loader()->GetTiming().ReferenceMonotonicTime() +
origin_time_;
@@ -212,27 +230,32 @@ TimeTicks DocumentTimeline::ZeroTime() {
}
void DocumentTimeline::ResetForTesting() {
- zero_time_ = TimeTicks() + origin_time_;
+ zero_time_ = base::TimeTicks() + origin_time_;
zero_time_initialized_ = true;
playback_rate_ = 1;
last_current_time_internal_ = 0;
}
+void DocumentTimeline::SetTimingForTesting(PlatformTiming* timing) {
+ timing_ = timing;
+}
+
double DocumentTimeline::currentTime(bool& is_null) {
return CurrentTimeInternal(is_null) * 1000;
}
-// TODO(npm): change the return type to base::Optional<TimeTicks>.
+// TODO(npm): change the return type to base::Optional<base::TimeTicks>.
double DocumentTimeline::CurrentTimeInternal(bool& is_null) {
if (!IsActive()) {
is_null = true;
return std::numeric_limits<double>::quiet_NaN();
}
- double result = playback_rate_ == 0
- ? ZeroTime().since_origin().InSecondsF()
- : (GetDocument()->GetAnimationClock().CurrentTime() -
- ZeroTime().since_origin().InSecondsF()) *
- playback_rate_;
+
+ double result =
+ playback_rate_ == 0
+ ? ZeroTime().since_origin().InSecondsF()
+ : (CurrentAnimationTime(GetDocument()) - ZeroTime()).InSecondsF() *
+ playback_rate_;
is_null = std::isnan(result);
// This looks like it could never be NaN here.
DCHECK(!is_null);
@@ -294,12 +317,11 @@ void DocumentTimeline::SetPlaybackRate(double playback_rate) {
return;
double current_time = CurrentTimeInternal();
playback_rate_ = playback_rate;
- double zero_time_seconds =
- playback_rate == 0 ? current_time
- : GetDocument()->GetAnimationClock().CurrentTime() -
- current_time / playback_rate;
zero_time_ =
- base::TimeTicks() + base::TimeDelta::FromSecondsD(zero_time_seconds);
+ playback_rate == 0
+ ? base::TimeTicks() + base::TimeDelta::FromSecondsD(current_time)
+ : CurrentAnimationTime(GetDocument()) -
+ base::TimeDelta::FromSecondsD(current_time / playback_rate);
zero_time_initialized_ = true;
// Corresponding compositor animation may need to be restarted to pick up
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 ce4350a6a60..080957bcc37 100644
--- a/chromium/third_party/blink/renderer/core/animation/document_timeline.h
+++ b/chromium/third_party/blink/renderer/core/animation/document_timeline.h
@@ -68,15 +68,16 @@ class CORE_EXPORT DocumentTimeline : public AnimationTimeline {
virtual void Trace(blink::Visitor* visitor) {}
};
- static DocumentTimeline* Create(Document*,
- TimeDelta origin_time = TimeDelta(),
- PlatformTiming* = nullptr);
+ static DocumentTimeline* Create(
+ Document*,
+ base::TimeDelta origin_time = base::TimeDelta(),
+ PlatformTiming* = nullptr);
// Web Animations API IDL constructor
static DocumentTimeline* Create(ExecutionContext*,
const DocumentTimelineOptions*);
- DocumentTimeline(Document*, TimeDelta origin_time, PlatformTiming*);
+ DocumentTimeline(Document*, base::TimeDelta origin_time, PlatformTiming*);
~DocumentTimeline() override = default;
bool IsDocumentTimeline() const final { return true; }
@@ -87,7 +88,10 @@ class CORE_EXPORT DocumentTimeline : public AnimationTimeline {
Animation* Play(AnimationEffect*);
HeapVector<Member<Animation>> getAnimations();
- void AnimationAttached(Animation&);
+ void AnimationAttached(Animation*) override;
+ // animations_ is a map of weak members so there is no need to explicitly
+ // clean it up.
+ void AnimationDetached(Animation*) override {}
bool IsActive() const override;
bool HasPendingUpdates() const {
@@ -96,7 +100,7 @@ class CORE_EXPORT DocumentTimeline : public AnimationTimeline {
wtf_size_t PendingAnimationsCount() const {
return animations_needing_update_.size();
}
- TimeTicks ZeroTime();
+ base::TimeTicks ZeroTime();
double currentTime(bool& is_null) override;
double currentTime();
double CurrentTimeInternal(bool& is_null);
@@ -118,9 +122,10 @@ class CORE_EXPORT DocumentTimeline : public AnimationTimeline {
return compositor_timeline_.get();
}
- Document* GetDocument() { return document_.Get(); }
+ Document* GetDocument() override { return document_.Get(); }
void Wake();
void ResetForTesting();
+ void SetTimingForTesting(PlatformTiming* timing);
bool HasAnimations() { return !animations_.IsEmpty(); }
void Trace(blink::Visitor*) override;
@@ -130,10 +135,10 @@ class CORE_EXPORT DocumentTimeline : public AnimationTimeline {
// Origin time for the timeline relative to the time origin of the document.
// Provided when the timeline is constructed. See
// https://drafts.csswg.org/web-animations/#dom-documenttimelineoptions-origintime.
- TimeDelta origin_time_;
+ base::TimeDelta origin_time_;
// The origin time. This is computed by adding |origin_time_| to the time
// origin of the document.
- TimeTicks zero_time_;
+ base::TimeTicks zero_time_;
bool zero_time_initialized_;
unsigned outdated_animation_count_;
// Animations which will be updated on the next frame
diff --git a/chromium/third_party/blink/renderer/core/animation/document_timeline.idl b/chromium/third_party/blink/renderer/core/animation/document_timeline.idl
index 8a5aed4f1ec..4244b5a8e16 100644
--- a/chromium/third_party/blink/renderer/core/animation/document_timeline.idl
+++ b/chromium/third_party/blink/renderer/core/animation/document_timeline.idl
@@ -7,6 +7,7 @@
[
Constructor(optional DocumentTimelineOptions options),
ConstructorCallWith=ExecutionContext,
- RuntimeEnabled=WebAnimationsAPI
+ RuntimeEnabled=WebAnimationsAPI,
+ Exposed=Window
] interface DocumentTimeline : AnimationTimeline {
};
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 78feffbcc21..d32736e9008 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
@@ -70,8 +70,9 @@ class AnimationDocumentTimelineTest : public PageTestBase {
GetAnimationClock().ResetTimeForTesting();
element = Element::Create(QualifiedName::Null(), document.Get());
platform_timing = MakeGarbageCollected<MockPlatformTiming>();
- timeline =
- DocumentTimeline::Create(document.Get(), TimeDelta(), platform_timing);
+ timeline = document->Timeline();
+ timeline->SetTimingForTesting(platform_timing);
+
timeline->ResetForTesting();
ASSERT_EQ(0, timeline->CurrentTimeInternal());
}
@@ -106,6 +107,24 @@ class AnimationDocumentTimelineTest : public PageTestBase {
double MinimumDelay() { return DocumentTimeline::kMinimumDelay; }
};
+class AnimationDocumentTimelineRealTimeTest : public PageTestBase {
+ protected:
+ void SetUp() override {
+ PageTestBase::SetUp(IntSize());
+ document = &GetDocument();
+ timeline = document->Timeline();
+ }
+
+ void TearDown() override {
+ document.Release();
+ timeline.Release();
+ ThreadState::Current()->CollectAllGarbageForTesting();
+ }
+
+ Persistent<Document> document;
+ Persistent<DocumentTimeline> timeline;
+};
+
TEST_F(AnimationDocumentTimelineTest, EmptyKeyframeAnimation) {
auto* effect =
MakeGarbageCollected<StringKeyframeEffectModel>(StringKeyframeVector());
@@ -165,7 +184,7 @@ TEST_F(AnimationDocumentTimelineTest, EffectiveTime) {
auto* document_without_frame = MakeGarbageCollected<Document>();
DocumentTimeline* inactive_timeline = DocumentTimeline::Create(
- document_without_frame, TimeDelta(), platform_timing);
+ document_without_frame, base::TimeDelta(), platform_timing);
EXPECT_EQ(0, inactive_timeline->EffectiveTime());
is_null = false;
@@ -174,7 +193,7 @@ TEST_F(AnimationDocumentTimelineTest, EffectiveTime) {
}
TEST_F(AnimationDocumentTimelineTest, PlaybackRateNormal) {
- TimeTicks zero_time = timeline->ZeroTime();
+ base::TimeTicks zero_time = timeline->ZeroTime();
bool is_null;
timeline->SetPlaybackRate(1.0);
@@ -193,7 +212,7 @@ TEST_F(AnimationDocumentTimelineTest, PlaybackRateNormal) {
}
TEST_F(AnimationDocumentTimelineTest, PlaybackRateNormalWithOriginTime) {
- TimeDelta origin_time = TimeDelta::FromSeconds(-1000);
+ base::TimeDelta origin_time = base::TimeDelta::FromSeconds(-1000);
timeline =
DocumentTimeline::Create(document.Get(), origin_time, platform_timing);
timeline->ResetForTesting();
@@ -201,19 +220,19 @@ TEST_F(AnimationDocumentTimelineTest, PlaybackRateNormalWithOriginTime) {
bool is_null;
EXPECT_EQ(1.0, timeline->PlaybackRate());
- EXPECT_EQ(TimeTicks() + origin_time, timeline->ZeroTime());
+ EXPECT_EQ(base::TimeTicks() + origin_time, timeline->ZeroTime());
EXPECT_EQ(1000, timeline->CurrentTimeInternal());
EXPECT_EQ(1000, timeline->CurrentTimeInternal(is_null));
EXPECT_FALSE(is_null);
GetAnimationClock().UpdateTime(TimeTicksFromSecondsD(100));
- EXPECT_EQ(TimeTicks() + origin_time, timeline->ZeroTime());
+ EXPECT_EQ(base::TimeTicks() + origin_time, timeline->ZeroTime());
EXPECT_EQ(1100, timeline->CurrentTimeInternal());
EXPECT_EQ(1100, timeline->CurrentTimeInternal(is_null));
EXPECT_FALSE(is_null);
GetAnimationClock().UpdateTime(TimeTicksFromSecondsD(200));
- EXPECT_EQ(TimeTicks() + origin_time, timeline->ZeroTime());
+ EXPECT_EQ(base::TimeTicks() + origin_time, timeline->ZeroTime());
EXPECT_EQ(1200, timeline->CurrentTimeInternal());
EXPECT_EQ(1200, timeline->CurrentTimeInternal(is_null));
EXPECT_FALSE(is_null);
@@ -223,7 +242,7 @@ TEST_F(AnimationDocumentTimelineTest, PlaybackRatePause) {
bool is_null;
GetAnimationClock().UpdateTime(TimeTicksFromSecondsD(100));
- EXPECT_EQ(TimeTicks(), timeline->ZeroTime());
+ EXPECT_EQ(base::TimeTicks(), timeline->ZeroTime());
EXPECT_EQ(100, timeline->CurrentTimeInternal());
EXPECT_EQ(100, timeline->CurrentTimeInternal(is_null));
EXPECT_FALSE(is_null);
@@ -248,18 +267,18 @@ TEST_F(AnimationDocumentTimelineTest, PlaybackRatePause) {
TEST_F(AnimationDocumentTimelineTest, PlaybackRatePauseWithOriginTime) {
bool is_null;
- TimeDelta origin_time = TimeDelta::FromSeconds(-1000);
+ base::TimeDelta origin_time = base::TimeDelta::FromSeconds(-1000);
timeline =
DocumentTimeline::Create(document.Get(), origin_time, platform_timing);
timeline->ResetForTesting();
- EXPECT_EQ(TimeTicks() + origin_time, timeline->ZeroTime());
+ EXPECT_EQ(base::TimeTicks() + origin_time, timeline->ZeroTime());
EXPECT_EQ(1000, timeline->CurrentTimeInternal());
EXPECT_EQ(1000, timeline->CurrentTimeInternal(is_null));
EXPECT_FALSE(is_null);
GetAnimationClock().UpdateTime(TimeTicksFromSecondsD(100));
- EXPECT_EQ(TimeTicks() + origin_time, timeline->ZeroTime());
+ EXPECT_EQ(base::TimeTicks() + origin_time, timeline->ZeroTime());
EXPECT_EQ(1100, timeline->CurrentTimeInternal());
EXPECT_EQ(1100, timeline->CurrentTimeInternal(is_null));
EXPECT_FALSE(is_null);
@@ -289,7 +308,7 @@ TEST_F(AnimationDocumentTimelineTest, PlaybackRateSlow) {
bool is_null;
GetAnimationClock().UpdateTime(TimeTicksFromSecondsD(100));
- EXPECT_EQ(TimeTicks(), timeline->ZeroTime());
+ EXPECT_EQ(base::TimeTicks(), timeline->ZeroTime());
EXPECT_EQ(100, timeline->CurrentTimeInternal());
EXPECT_EQ(100, timeline->CurrentTimeInternal(is_null));
EXPECT_FALSE(is_null);
@@ -315,7 +334,7 @@ TEST_F(AnimationDocumentTimelineTest, PlaybackRateFast) {
bool is_null;
GetAnimationClock().UpdateTime(TimeTicksFromSecondsD(100));
- EXPECT_EQ(TimeTicks(), timeline->ZeroTime());
+ EXPECT_EQ(base::TimeTicks(), timeline->ZeroTime());
EXPECT_EQ(100, timeline->CurrentTimeInternal());
EXPECT_EQ(100, timeline->CurrentTimeInternal(is_null));
EXPECT_FALSE(is_null);
@@ -341,7 +360,7 @@ TEST_F(AnimationDocumentTimelineTest, PlaybackRateFastWithOriginTime) {
bool is_null;
timeline = DocumentTimeline::Create(
- document.Get(), TimeDelta::FromSeconds(-1000), platform_timing);
+ document.Get(), base::TimeDelta::FromSeconds(-1000), platform_timing);
timeline->ResetForTesting();
GetAnimationClock().UpdateTime(TimeTicksFromSecondsD(100));
@@ -435,4 +454,20 @@ TEST_F(AnimationDocumentTimelineTest, PlayAfterDocumentDeref) {
timeline->Play(keyframe_effect);
}
+// Ensure that origin time is correctly calculated even when the animation
+// clock has not yet been initialized.
+TEST_F(AnimationDocumentTimelineRealTimeTest,
+ PlaybackRateChangeUninitalizedAnimationClock) {
+ GetAnimationClock().ResetTimeForTesting();
+ EXPECT_TRUE(GetAnimationClock().CurrentTime().is_null());
+ EXPECT_FALSE(
+ document->Loader()->GetTiming().ReferenceMonotonicTime().is_null());
+
+ base::TimeDelta origin_time = base::TimeDelta::FromSeconds(1000);
+ timeline = DocumentTimeline::Create(document.Get(), origin_time);
+ timeline->SetPlaybackRate(0.5);
+ EXPECT_EQ(origin_time * 2,
+ timeline->ZeroTime() - document->Timeline().ZeroTime());
+}
+
} // namespace blink
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 6e793806d22..fc0b9127d56 100644
--- a/chromium/third_party/blink/renderer/core/animation/effect_input.cc
+++ b/chromium/third_party/blink/renderer/core/animation/effect_input.cc
@@ -94,9 +94,9 @@ void SetKeyframeValue(Element* element,
if (css_property != CSSPropertyID::kInvalid) {
MutableCSSPropertyValueSet::SetResult set_result =
css_property == CSSPropertyID::kVariable
- ? keyframe.SetCSSPropertyValue(
- AtomicString(property), document.GetPropertyRegistry(), value,
- document.GetSecureContextMode(), style_sheet_contents)
+ ? keyframe.SetCSSPropertyValue(AtomicString(property), value,
+ document.GetSecureContextMode(),
+ style_sheet_contents)
: keyframe.SetCSSPropertyValue(css_property, value,
document.GetSecureContextMode(),
style_sheet_contents);
@@ -222,7 +222,7 @@ void AddPropertyValuePairsForKeyframe(
// By spec, we must sort the properties in "ascending order by the Unicode
// codepoints that define each property name."
std::sort(keyframe_properties.begin(), keyframe_properties.end(),
- WTF::CodePointCompareLessThan);
+ WTF::CodeUnitCompareLessThan);
v8::TryCatch try_catch(isolate);
for (const auto& property : keyframe_properties) {
@@ -485,7 +485,7 @@ StringKeyframeVector ConvertObjectForm(Element* element,
// By spec, we must sort the properties in "ascending order by the Unicode
// codepoints that define each property name."
std::sort(keyframe_properties.begin(), keyframe_properties.end(),
- WTF::CodePointCompareLessThan);
+ WTF::CodeUnitCompareLessThan);
for (const auto& property : keyframe_properties) {
if (property == "offset" || property == "composite" ||
diff --git a/chromium/third_party/blink/renderer/core/animation/effect_input.h b/chromium/third_party/blink/renderer/core/animation/effect_input.h
index dacaff0213f..29141e9ddf3 100644
--- a/chromium/third_party/blink/renderer/core/animation/effect_input.h
+++ b/chromium/third_party/blink/renderer/core/animation/effect_input.h
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/animation/effect_model.h"
#include "third_party/blink/renderer/core/animation/keyframe_effect_model.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
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 f662694c1a6..1f7f2aeb066 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
@@ -24,7 +24,7 @@ class AnimationEffectStackTest : public PageTestBase {
void SetUp() override {
PageTestBase::SetUp(IntSize());
GetDocument().GetAnimationClock().ResetTimeForTesting();
- timeline = DocumentTimeline::Create(&GetDocument());
+ timeline = GetDocument().Timeline();
element = GetDocument().CreateElementForBinding("foo");
}
@@ -35,7 +35,7 @@ class AnimationEffectStackTest : public PageTestBase {
return animation;
}
- void UpdateTimeline(TimeDelta time) {
+ void UpdateTimeline(base::TimeDelta time) {
GetDocument().GetAnimationClock().UpdateTime(
GetDocument().Timeline().ZeroTime() + time);
timeline->ServiceAnimations(kTimingUpdateForAnimationFrame);
@@ -180,7 +180,7 @@ TEST_F(AnimationEffectStackTest, ForwardsFillDiscarding) {
// to keep the ActiveInterpolationsMap in a Persistent.
Persistent<ActiveInterpolationsMap> interpolations;
- UpdateTimeline(TimeDelta::FromSeconds(11));
+ UpdateTimeline(base::TimeDelta::FromSeconds(11));
ThreadState::Current()->CollectAllGarbageForTesting();
interpolations = MakeGarbageCollected<ActiveInterpolationsMap>(
EffectStack::ActiveInterpolations(
@@ -190,7 +190,7 @@ TEST_F(AnimationEffectStackTest, ForwardsFillDiscarding) {
EXPECT_EQ(GetFontSizeValue(*interpolations), 3);
EXPECT_EQ(3u, SampledEffectCount());
- UpdateTimeline(TimeDelta::FromSeconds(13));
+ UpdateTimeline(base::TimeDelta::FromSeconds(13));
ThreadState::Current()->CollectAllGarbageForTesting();
interpolations = MakeGarbageCollected<ActiveInterpolationsMap>(
EffectStack::ActiveInterpolations(
@@ -200,7 +200,7 @@ TEST_F(AnimationEffectStackTest, ForwardsFillDiscarding) {
EXPECT_EQ(GetFontSizeValue(*interpolations), 3);
EXPECT_EQ(3u, SampledEffectCount());
- UpdateTimeline(TimeDelta::FromSeconds(15));
+ UpdateTimeline(base::TimeDelta::FromSeconds(15));
ThreadState::Current()->CollectAllGarbageForTesting();
interpolations = MakeGarbageCollected<ActiveInterpolationsMap>(
EffectStack::ActiveInterpolations(
@@ -210,7 +210,7 @@ TEST_F(AnimationEffectStackTest, ForwardsFillDiscarding) {
EXPECT_EQ(GetFontSizeValue(*interpolations), 3);
EXPECT_EQ(2u, SampledEffectCount());
- UpdateTimeline(TimeDelta::FromSeconds(17));
+ UpdateTimeline(base::TimeDelta::FromSeconds(17));
ThreadState::Current()->CollectAllGarbageForTesting();
interpolations = MakeGarbageCollected<ActiveInterpolationsMap>(
EffectStack::ActiveInterpolations(
diff --git a/chromium/third_party/blink/renderer/core/animation/element_animations.cc b/chromium/third_party/blink/renderer/core/animation/element_animations.cc
index 91375f7ff72..375a6d86458 100644
--- a/chromium/third_party/blink/renderer/core/animation/element_animations.cc
+++ b/chromium/third_party/blink/renderer/core/animation/element_animations.cc
@@ -173,4 +173,16 @@ void ElementAnimations::ClearBaseComputedStyle() {
base_computed_style_ = nullptr;
}
+bool ElementAnimations::AnimationsPreserveAxisAlignment() const {
+ for (const auto& entry : animations_) {
+ const Animation& animation = *entry.key;
+ DCHECK(animation.effect());
+ DCHECK(animation.effect()->IsKeyframeEffect());
+ const KeyframeEffect& effect = *ToKeyframeEffect(animation.effect());
+ if (!effect.AnimationsPreserveAxisAlignment())
+ return false;
+ }
+ return true;
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/animation/element_animations.h b/chromium/third_party/blink/renderer/core/animation/element_animations.h
index 63743d1c174..b1ed18d7643 100644
--- a/chromium/third_party/blink/renderer/core/animation/element_animations.h
+++ b/chromium/third_party/blink/renderer/core/animation/element_animations.h
@@ -84,6 +84,8 @@ class CORE_EXPORT ElementAnimations
void UpdateBaseComputedStyle(const ComputedStyle*);
void ClearBaseComputedStyle();
+ bool AnimationsPreserveAxisAlignment() const;
+
void Trace(blink::Visitor*);
private:
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 607e90a91b7..a1da642c383 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
@@ -48,26 +48,6 @@ DEFINE_NON_INTERPOLABLE_VALUE_TYPE_CASTS(FilterNonInterpolableValue);
namespace {
-double DefaultParameter(FilterOperation::OperationType type) {
- switch (type) {
- case FilterOperation::BRIGHTNESS:
- case FilterOperation::GRAYSCALE:
- case FilterOperation::SATURATE:
- case FilterOperation::SEPIA:
- return 1;
-
- case FilterOperation::CONTRAST:
- case FilterOperation::HUE_ROTATE:
- case FilterOperation::INVERT:
- case FilterOperation::OPACITY:
- return 0;
-
- default:
- NOTREACHED();
- return 0;
- }
-}
-
double ClampParameter(double value, FilterOperation::OperationType type) {
switch (type) {
case FilterOperation::BRIGHTNESS:
@@ -110,26 +90,11 @@ InterpolationValue filter_interpolation_functions::MaybeConvertCSSFilter(
case FilterOperation::INVERT:
case FilterOperation::OPACITY:
case FilterOperation::SATURATE:
- case FilterOperation::SEPIA: {
- double amount = DefaultParameter(type);
- if (filter.length() == 1) {
- const CSSPrimitiveValue& first_value =
- To<CSSPrimitiveValue>(filter.Item(0));
- amount = first_value.GetDoubleValue();
- if (first_value.IsPercentage())
- amount /= 100;
- }
- result.interpolable_value = std::make_unique<InterpolableNumber>(amount);
- break;
- }
-
- case FilterOperation::HUE_ROTATE: {
- double angle = DefaultParameter(type);
- if (filter.length() == 1)
- angle = To<CSSPrimitiveValue>(filter.Item(0)).ComputeDegrees();
- result.interpolable_value = std::make_unique<InterpolableNumber>(angle);
+ case FilterOperation::SEPIA:
+ case FilterOperation::HUE_ROTATE:
+ result.interpolable_value = std::make_unique<InterpolableNumber>(
+ FilterOperationResolver::ResolveNumericArgumentForFunction(filter));
break;
- }
case FilterOperation::BLUR: {
if (filter.length() == 0)
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 35840e4e8be..35b6b81cbe3 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
@@ -7,7 +7,7 @@
#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/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.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 939c679db96..7331c601471 100644
--- a/chromium/third_party/blink/renderer/core/animation/inert_effect.cc
+++ b/chromium/third_party/blink/renderer/core/animation/inert_effect.cc
@@ -53,7 +53,7 @@ void InertEffect::Sample(HeapVector<Member<Interpolation>>& result) const {
double iteration = CurrentIteration();
DCHECK_GE(iteration, 0);
model_->Sample(clampTo<int>(iteration, 0), Progress().value(),
- IterationDuration(), result);
+ SpecifiedTiming().IterationDuration(), result);
}
double InertEffect::CalculateTimeToEffectChange(bool, double, double) const {
diff --git a/chromium/third_party/blink/renderer/core/animation/interpolation_effect.cc b/chromium/third_party/blink/renderer/core/animation/interpolation_effect.cc
index 5f5af62f89c..814730f118f 100644
--- a/chromium/third_party/blink/renderer/core/animation/interpolation_effect.cc
+++ b/chromium/third_party/blink/renderer/core/animation/interpolation_effect.cc
@@ -4,13 +4,10 @@
#include "third_party/blink/renderer/core/animation/interpolation_effect.h"
-#include "third_party/blink/renderer/platform/animation/animation_utilities.h"
-
namespace blink {
void InterpolationEffect::GetActiveInterpolations(
double fraction,
- double iteration_duration,
HeapVector<Member<Interpolation>>& result) const {
wtf_size_t existing_size = result.size();
wtf_size_t result_index = 0;
@@ -23,8 +20,7 @@ void InterpolationEffect::GetActiveInterpolations(
record_length ? (fraction - record->start_) / record_length : 0.0;
if (record->easing_) {
local_fraction = record->easing_->Evaluate(
- local_fraction, TimingFunction::LimitDirection::RIGHT,
- AccuracyForDuration(iteration_duration));
+ local_fraction, TimingFunction::LimitDirection::RIGHT);
}
interpolation->Interpolate(0, local_fraction);
if (result_index < existing_size)
diff --git a/chromium/third_party/blink/renderer/core/animation/interpolation_effect.h b/chromium/third_party/blink/renderer/core/animation/interpolation_effect.h
index 78cfee54a8a..b8d5dfe79ca 100644
--- a/chromium/third_party/blink/renderer/core/animation/interpolation_effect.h
+++ b/chromium/third_party/blink/renderer/core/animation/interpolation_effect.h
@@ -30,7 +30,6 @@ class CORE_EXPORT InterpolationEffect
}
void GetActiveInterpolations(double fraction,
- double iteration_duration,
HeapVector<Member<Interpolation>>&) const;
void AddInterpolation(Interpolation* interpolation,
diff --git a/chromium/third_party/blink/renderer/core/animation/interpolation_effect_test.cc b/chromium/third_party/blink/renderer/core/animation/interpolation_effect_test.cc
index 2ed3176bda8..8cab75b7dd6 100644
--- a/chromium/third_party/blink/renderer/core/animation/interpolation_effect_test.cc
+++ b/chromium/third_party/blink/renderer/core/animation/interpolation_effect_test.cc
@@ -13,8 +13,6 @@ namespace blink {
namespace {
-const double kInterpolationTestDuration = 1.0;
-
double GetInterpolableNumber(Interpolation* value) {
TransitionInterpolation* interpolation = ToTransitionInterpolation(value);
std::unique_ptr<TypedInterpolationValue> interpolated_value =
@@ -45,28 +43,26 @@ TEST(AnimationInterpolationEffectTest, SingleInterpolation) {
CreateInterpolation(0, 10), scoped_refptr<TimingFunction>(), 0, 1, -1, 2);
HeapVector<Member<Interpolation>> active_interpolations;
- interpolation_effect->GetActiveInterpolations(-2, kInterpolationTestDuration,
- active_interpolations);
+ interpolation_effect->GetActiveInterpolations(-2, active_interpolations);
EXPECT_EQ(0ul, active_interpolations.size());
- interpolation_effect->GetActiveInterpolations(
- -0.5, kInterpolationTestDuration, active_interpolations);
+ interpolation_effect->GetActiveInterpolations(-0.5, active_interpolations);
EXPECT_EQ(1ul, active_interpolations.size());
EXPECT_EQ(-5, GetInterpolableNumber(active_interpolations.at(0)));
- interpolation_effect->GetActiveInterpolations(0.5, kInterpolationTestDuration,
- active_interpolations);
+ interpolation_effect->GetActiveInterpolations(0.5, active_interpolations);
EXPECT_EQ(1ul, active_interpolations.size());
EXPECT_FLOAT_EQ(5, GetInterpolableNumber(active_interpolations.at(0)));
- interpolation_effect->GetActiveInterpolations(1.5, kInterpolationTestDuration,
- active_interpolations);
+ interpolation_effect->GetActiveInterpolations(1.5, active_interpolations);
EXPECT_EQ(1ul, active_interpolations.size());
EXPECT_FLOAT_EQ(15, GetInterpolableNumber(active_interpolations.at(0)));
- interpolation_effect->GetActiveInterpolations(3, kInterpolationTestDuration,
- active_interpolations);
+ interpolation_effect->GetActiveInterpolations(3, active_interpolations);
EXPECT_EQ(0ul, active_interpolations.size());
+
+ interpolation_effect->GetActiveInterpolations(0, active_interpolations);
+ EXPECT_EQ(1ul, active_interpolations.size());
}
TEST(AnimationInterpolationEffectTest, MultipleInterpolations) {
@@ -82,43 +78,33 @@ TEST(AnimationInterpolationEffectTest, MultipleInterpolations) {
CubicBezierTimingFunction::EaseType::EASE),
0.5, 1.5, 0.5, 1.5);
+ // ease = cubicBezier(0.25, 0.1, 0.25, 1)
+ // ease(0.5) = 0.8024033877399112
+
HeapVector<Member<Interpolation>> active_interpolations;
- interpolation_effect->GetActiveInterpolations(
- -0.5, kInterpolationTestDuration, active_interpolations);
+ interpolation_effect->GetActiveInterpolations(-0.5, active_interpolations);
EXPECT_EQ(0ul, active_interpolations.size());
- interpolation_effect->GetActiveInterpolations(0, kInterpolationTestDuration,
- active_interpolations);
+ interpolation_effect->GetActiveInterpolations(0, active_interpolations);
EXPECT_EQ(1ul, active_interpolations.size());
EXPECT_FLOAT_EQ(0, GetInterpolableNumber(active_interpolations.at(0)));
- interpolation_effect->GetActiveInterpolations(0.5, kInterpolationTestDuration,
- active_interpolations);
+ interpolation_effect->GetActiveInterpolations(0.5, active_interpolations);
EXPECT_EQ(2ul, active_interpolations.size());
EXPECT_FLOAT_EQ(0.5f, GetInterpolableNumber(active_interpolations.at(0)));
EXPECT_FLOAT_EQ(1, GetInterpolableNumber(active_interpolations.at(1)));
- interpolation_effect->GetActiveInterpolations(1, kInterpolationTestDuration,
- active_interpolations);
- EXPECT_EQ(2ul, active_interpolations.size());
- EXPECT_FLOAT_EQ(10, GetInterpolableNumber(active_interpolations.at(0)));
- EXPECT_FLOAT_EQ(5.0282884f,
- GetInterpolableNumber(active_interpolations.at(1)));
-
- interpolation_effect->GetActiveInterpolations(
- 1, kInterpolationTestDuration * 1000, active_interpolations);
+ interpolation_effect->GetActiveInterpolations(1, active_interpolations);
EXPECT_EQ(2ul, active_interpolations.size());
EXPECT_FLOAT_EQ(10, GetInterpolableNumber(active_interpolations.at(0)));
- EXPECT_FLOAT_EQ(5.0120168f,
+ EXPECT_FLOAT_EQ(5.0120169f,
GetInterpolableNumber(active_interpolations.at(1)));
- interpolation_effect->GetActiveInterpolations(1.5, kInterpolationTestDuration,
- active_interpolations);
+ interpolation_effect->GetActiveInterpolations(1.5, active_interpolations);
EXPECT_EQ(1ul, active_interpolations.size());
EXPECT_FLOAT_EQ(12.5f, GetInterpolableNumber(active_interpolations.at(0)));
- interpolation_effect->GetActiveInterpolations(2, kInterpolationTestDuration,
- active_interpolations);
+ interpolation_effect->GetActiveInterpolations(2, active_interpolations);
EXPECT_EQ(1ul, active_interpolations.size());
EXPECT_FLOAT_EQ(15, GetInterpolableNumber(active_interpolations.at(0)));
}
diff --git a/chromium/third_party/blink/renderer/core/animation/interpolation_environment.h b/chromium/third_party/blink/renderer/core/animation/interpolation_environment.h
index ade6a672427..c9e518a56fb 100644
--- a/chromium/third_party/blink/renderer/core/animation/interpolation_environment.h
+++ b/chromium/third_party/blink/renderer/core/animation/interpolation_environment.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_INTERPOLATION_ENVIRONMENT_H_
#include "third_party/blink/renderer/core/animation/interpolation_types_map.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/animation/interpolation_type.h b/chromium/third_party/blink/renderer/core/animation/interpolation_type.h
index ff850c51cc3..431d50dd590 100644
--- a/chromium/third_party/blink/renderer/core/animation/interpolation_type.h
+++ b/chromium/third_party/blink/renderer/core/animation/interpolation_type.h
@@ -16,7 +16,7 @@
#include "third_party/blink/renderer/core/animation/underlying_value_owner.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/animation/invalidatable_interpolation.cc b/chromium/third_party/blink/renderer/core/animation/invalidatable_interpolation.cc
index 4b99e714690..ca3994dbbac 100644
--- a/chromium/third_party/blink/renderer/core/animation/invalidatable_interpolation.cc
+++ b/chromium/third_party/blink/renderer/core/animation/invalidatable_interpolation.cc
@@ -271,19 +271,21 @@ void InvalidatableInterpolation::ApplyStack(
current_interpolation.SetFlagIfInheritUsed(environment);
double underlying_fraction = current_interpolation.UnderlyingFraction();
if (underlying_fraction == 0 || !underlying_value_owner ||
- underlying_value_owner.GetType() != current_value->GetType())
+ underlying_value_owner.GetType() != current_value->GetType()) {
underlying_value_owner.Set(current_value);
- else
+ } else {
current_value->GetType().Composite(
underlying_value_owner, underlying_fraction, current_value->Value(),
current_interpolation.current_fraction_);
+ }
}
- if (should_apply && underlying_value_owner)
+ if (should_apply && underlying_value_owner) {
underlying_value_owner.GetType().Apply(
*underlying_value_owner.Value().interpolable_value,
underlying_value_owner.Value().non_interpolable_value.get(),
environment);
+ }
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/animation/keyframe.h b/chromium/third_party/blink/renderer/core/animation/keyframe.h
index 3b28d902bb0..928ac7410e2 100644
--- a/chromium/third_party/blink/renderer/core/animation/keyframe.h
+++ b/chromium/third_party/blink/renderer/core/animation/keyframe.h
@@ -13,7 +13,7 @@
#include "third_party/blink/renderer/core/animation/property_handle.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
namespace blink {
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 da241c6972a..3fb57f27a53 100644
--- a/chromium/third_party/blink/renderer/core/animation/keyframe_effect.cc
+++ b/chromium/third_party/blink/renderer/core/animation/keyframe_effect.cc
@@ -32,19 +32,19 @@
#include "third_party/blink/renderer/bindings/core/v8/unrestricted_double_or_keyframe_effect_options.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_object_builder.h"
+#include "third_party/blink/renderer/core/animation/css/compositor_keyframe_transform.h"
#include "third_party/blink/renderer/core/animation/effect_input.h"
#include "third_party/blink/renderer/core/animation/element_animations.h"
-#include "third_party/blink/renderer/core/animation/keyframe_effect_options.h"
#include "third_party/blink/renderer/core/animation/sampled_effect.h"
#include "third_party/blink/renderer/core/animation/timing_input.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/use_counter.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/core/svg/svg_element.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
namespace blink {
@@ -275,10 +275,6 @@ bool KeyframeEffect::HasActiveAnimationsOnCompositor(
bool KeyframeEffect::CancelAnimationOnCompositor(
CompositorAnimation* compositor_animation) {
- // FIXME: cancelAnimationOnCompositor is called from withins style recalc.
- // This queries compositingState, which is not necessarily up to date.
- // https://code.google.com/p/chromium/issues/detail?id=339847
- DisableCompositingQueryAsserts disabler;
if (!HasActiveAnimationsOnCompositor())
return false;
if (!target_ || !target_->GetLayoutObject())
@@ -333,6 +329,47 @@ void KeyframeEffect::Trace(blink::Visitor* visitor) {
AnimationEffect::Trace(visitor);
}
+bool KeyframeEffect::AnimationsPreserveAxisAlignment(
+ const PropertyHandle& property) const {
+ const auto* keyframes = Model()->GetPropertySpecificKeyframes(property);
+ if (!keyframes)
+ return true;
+ for (const auto& keyframe : *keyframes) {
+ const auto* value = keyframe->GetCompositorKeyframeValue();
+ if (!value)
+ continue;
+ DCHECK(value->IsTransform());
+ const auto& transform_operations =
+ ToCompositorKeyframeTransform(value)->GetTransformOperations();
+ if (!transform_operations.PreservesAxisAlignment())
+ return false;
+ }
+ return true;
+}
+
+namespace {
+
+static const size_t num_transform_properties = 4;
+
+const CSSProperty** TransformProperties() {
+ static const CSSProperty* kTransformProperties[num_transform_properties] = {
+ &GetCSSPropertyTransform(), &GetCSSPropertyScale(),
+ &GetCSSPropertyRotate(), &GetCSSPropertyTranslate()};
+ return kTransformProperties;
+}
+
+} // namespace
+
+bool KeyframeEffect::AnimationsPreserveAxisAlignment() const {
+ static const auto** properties = TransformProperties();
+ for (size_t i = 0; i < num_transform_properties; i++) {
+ if (!AnimationsPreserveAxisAlignment(PropertyHandle(*properties[i])))
+ return false;
+ }
+
+ return true;
+}
+
EffectModel::CompositeOperation KeyframeEffect::CompositeInternal() const {
return model_->Composite();
}
@@ -351,12 +388,12 @@ void KeyframeEffect::ApplyEffects() {
bool changed = false;
if (sampled_effect_) {
changed = model_->Sample(clampTo<int>(iteration, 0), Progress().value(),
- IterationDuration(),
+ SpecifiedTiming().IterationDuration(),
sampled_effect_->MutableInterpolations());
} else {
HeapVector<Member<Interpolation>> interpolations;
model_->Sample(clampTo<int>(iteration, 0), Progress().value(),
- IterationDuration(), interpolations);
+ SpecifiedTiming().IterationDuration(), interpolations);
if (!interpolations.IsEmpty()) {
auto* sampled_effect =
MakeGarbageCollected<SampledEffect>(this, owner_->SequenceNumber());
@@ -436,19 +473,20 @@ double KeyframeEffect::CalculateTimeToEffectChange(
double local_time,
double time_to_next_iteration) const {
const double start_time = SpecifiedTiming().start_delay;
- const double end_time_minus_end_delay = start_time + RepeatedDuration();
+ const double end_time_minus_end_delay =
+ start_time + SpecifiedTiming().ActiveDuration();
const double end_time =
end_time_minus_end_delay + SpecifiedTiming().end_delay;
const double after_time = std::min(end_time_minus_end_delay, end_time);
switch (GetPhase()) {
- case kPhaseNone:
+ case Timing::kPhaseNone:
return std::numeric_limits<double>::infinity();
- case kPhaseBefore:
+ case Timing::kPhaseBefore:
DCHECK_GE(start_time, local_time);
return forwards ? start_time - local_time
: std::numeric_limits<double>::infinity();
- case kPhaseActive:
+ case Timing::kPhaseActive:
if (forwards) {
// Need service to apply fill / fire events.
const double time_to_end = after_time - local_time;
@@ -458,13 +496,16 @@ double KeyframeEffect::CalculateTimeToEffectChange(
return time_to_end;
}
return 0;
- case kPhaseAfter:
+ case Timing::kPhaseAfter:
DCHECK_GE(local_time, after_time);
- // If this KeyframeEffect is still in effect then it will need to update
- // when its parent goes out of effect. We have no way of knowing when
- // that will be, however, so the parent will need to supply it.
- return forwards ? std::numeric_limits<double>::infinity()
- : local_time - after_time;
+ if (forwards) {
+ // If an animation has a positive-valued end delay, we need an
+ // additional tick at the end time to ensure that the finished event is
+ // delivered.
+ return end_time > local_time ? end_time - local_time
+ : std::numeric_limits<double>::infinity();
+ }
+ return local_time - after_time;
default:
NOTREACHED();
return std::numeric_limits<double>::infinity();
@@ -478,14 +519,14 @@ bool KeyframeEffect::HasIncompatibleStyle() const {
if (!target_->GetComputedStyle())
return false;
- bool affects_transform = Affects(PropertyHandle(GetCSSPropertyTransform())) ||
- Affects(PropertyHandle(GetCSSPropertyScale())) ||
- Affects(PropertyHandle(GetCSSPropertyRotate())) ||
- Affects(PropertyHandle(GetCSSPropertyTranslate()));
-
if (HasActiveAnimationsOnCompositor()) {
- if (target_->GetComputedStyle()->HasOffset() && affects_transform)
- return true;
+ if (target_->GetComputedStyle()->HasOffset()) {
+ static const auto** properties = TransformProperties();
+ for (size_t i = 0; i < num_transform_properties; i++) {
+ if (Affects(PropertyHandle(*properties[i])))
+ return true;
+ }
+ }
return HasMultipleTransformProperties();
}
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 5c5c7e6eb31..5d43efc2fb5 100644
--- a/chromium/third_party/blink/renderer/core/animation/keyframe_effect.h
+++ b/chromium/third_party/blink/renderer/core/animation/keyframe_effect.h
@@ -123,6 +123,8 @@ class CORE_EXPORT KeyframeEffect final : public AnimationEffect {
void Trace(blink::Visitor*) override;
+ bool AnimationsPreserveAxisAlignment() const;
+
private:
EffectModel::CompositeOperation CompositeInternal() const;
@@ -140,6 +142,8 @@ class CORE_EXPORT KeyframeEffect final : public AnimationEffect {
bool HasIncompatibleStyle() const;
bool HasMultipleTransformProperties() const;
+ bool AnimationsPreserveAxisAlignment(const PropertyHandle&) const;
+
Member<Element> target_;
Member<KeyframeEffectModelBase> model_;
Member<SampledEffect> sampled_effect_;
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 99f14661a98..101f64db425 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
@@ -39,10 +39,10 @@
#include "third_party/blink/renderer/core/css/property_registry.h"
#include "third_party/blink/renderer/core/css/resolver/style_resolver.h"
#include "third_party/blink/renderer/core/dom/document.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/platform/animation/animation_utilities.h"
#include "third_party/blink/renderer/platform/geometry/float_box.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/transforms/transformation_matrix.h"
#include "third_party/blink/renderer/platform/wtf/text/string_hash.h"
@@ -87,8 +87,7 @@ bool KeyframeEffectModelBase::Sample(
last_iteration_ = iteration;
last_fraction_ = fraction;
last_iteration_duration_ = iteration_duration;
- interpolation_effect_->GetActiveInterpolations(
- fraction, iteration_duration.InSecondsF(), result);
+ interpolation_effect_->GetActiveInterpolations(fraction, result);
return changed;
}
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 970d670903f..2d2a2e60255 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
@@ -93,10 +93,13 @@ class CORE_EXPORT KeyframeEffectModelBase : public EffectModel {
CompositeOperation Composite() const { return composite_; }
void SetComposite(CompositeOperation composite) { composite_ = composite; }
- const PropertySpecificKeyframeVector& GetPropertySpecificKeyframes(
+ const PropertySpecificKeyframeVector* GetPropertySpecificKeyframes(
const PropertyHandle& property) const {
EnsureKeyframeGroups();
- return keyframe_groups_->at(property)->Keyframes();
+ const auto keyframe_group_iter = keyframe_groups_->find(property);
+ if (keyframe_group_iter == keyframe_groups_->end())
+ return nullptr;
+ return &keyframe_group_iter->value->Keyframes();
}
using KeyframeGroupMap =
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 832f4f37536..e7f8668b512 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
@@ -32,6 +32,9 @@
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/core/animation/animation_test_helper.h"
+#include "third_party/blink/renderer/core/animation/css/compositor_keyframe_color.h"
+#include "third_party/blink/renderer/core/animation/css/compositor_keyframe_double.h"
+#include "third_party/blink/renderer/core/animation/css/compositor_keyframe_value_factory.h"
#include "third_party/blink/renderer/core/animation/css_default_interpolation_type.h"
#include "third_party/blink/renderer/core/animation/invalidatable_interpolation.h"
#include "third_party/blink/renderer/core/animation/string_keyframe.h"
@@ -45,6 +48,7 @@
#include "third_party/blink/renderer/core/testing/page_test_base.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
+#include "third_party/skia/include/core/SkColor.h"
namespace blink {
@@ -68,8 +72,10 @@ class AnimationKeyframeEffectModel : public PageTestBase {
EXPECT_TRUE(typed_value->GetInterpolableValue().IsList());
const InterpolableList* list =
ToInterpolableList(&typed_value->GetInterpolableValue());
- EXPECT_FLOAT_EQ(expected_value,
- ToInterpolableNumber(list->Get(0))->Value());
+ // Lengths are computed in logical units, which are quantized to 64ths of
+ // a pixel.
+ EXPECT_NEAR(expected_value, ToInterpolableNumber(list->Get(0))->Value(),
+ /*abs_error=*/0.02);
}
void ExpectNonInterpolableValue(const String& expected_value,
@@ -112,23 +118,53 @@ StringKeyframeVector KeyframesAtZeroAndOne(CSSPropertyID property,
StringKeyframeVector KeyframesAtZeroAndOne(
AtomicString property_name,
- const PropertyRegistry* property_registry,
const String& zero_value,
const String& one_value) {
StringKeyframeVector keyframes(2);
keyframes[0] = MakeGarbageCollected<StringKeyframe>();
keyframes[0]->SetOffset(0.0);
keyframes[0]->SetCSSPropertyValue(
- property_name, property_registry, zero_value,
- SecureContextMode::kInsecureContext, nullptr);
+ property_name, zero_value, SecureContextMode::kInsecureContext, nullptr);
keyframes[1] = MakeGarbageCollected<StringKeyframe>();
keyframes[1]->SetOffset(1.0);
- keyframes[1]->SetCSSPropertyValue(property_name, property_registry, one_value,
- SecureContextMode::kInsecureContext,
- nullptr);
+ keyframes[1]->SetCSSPropertyValue(
+ property_name, one_value, SecureContextMode::kInsecureContext, nullptr);
return keyframes;
}
+const PropertySpecificKeyframeVector& ConstructEffectAndGetKeyframes(
+ const AtomicString& property_name,
+ const AtomicString& type,
+ Document* document,
+ Element* element,
+ const String& zero_value,
+ const String& one_value,
+ ExceptionState& exception_state) {
+ PropertyDescriptor* property_descriptor = PropertyDescriptor::Create();
+ property_descriptor->setName(property_name);
+ property_descriptor->setSyntax(type);
+ property_descriptor->setInitialValue(zero_value);
+ property_descriptor->setInherits(false);
+ PropertyRegistration::registerProperty(document, property_descriptor,
+ exception_state);
+
+ StringKeyframeVector keyframes =
+ KeyframesAtZeroAndOne(property_name, zero_value, one_value);
+
+ element->style()->setProperty(document, property_name, zero_value,
+ g_empty_string, exception_state);
+
+ auto* effect = MakeGarbageCollected<StringKeyframeEffectModel>(keyframes);
+
+ auto style = document->EnsureStyleResolver().StyleForElement(element);
+
+ // Snapshot should update first time after construction
+ EXPECT_TRUE(effect->SnapshotAllCompositorKeyframesIfNecessary(
+ *element, *style, nullptr));
+
+ return *effect->GetPropertySpecificKeyframes(PropertyHandle(property_name));
+}
+
void ExpectProperty(CSSPropertyID property,
Interpolation* interpolation_value) {
InvalidatableInterpolation* interpolation =
@@ -204,10 +240,11 @@ TEST_F(AnimationKeyframeEffectModel, CompositeEaseIn) {
keyframes[1]->SetComposite(EffectModel::kCompositeReplace);
auto* effect = MakeGarbageCollected<StringKeyframeEffectModel>(keyframes);
HeapVector<Member<Interpolation>> values;
+ // CubicBezier(0.42, 0, 1, 1)(0.6) = 0.4291197695757142.
effect->Sample(0, 0.6, kDuration, values);
- ExpectLengthValue(3.8579516, values.at(0));
+ ExpectLengthValue(3.85824, values.at(0));
effect->Sample(0, 0.6, kDuration * 100, values);
- ExpectLengthValue(3.8582394, values.at(0));
+ ExpectLengthValue(3.85824, values.at(0));
}
TEST_F(AnimationKeyframeEffectModel, CompositeCubicBezier) {
@@ -216,12 +253,13 @@ TEST_F(AnimationKeyframeEffectModel, CompositeCubicBezier) {
keyframes[0]->SetComposite(EffectModel::kCompositeReplace);
keyframes[0]->SetEasing(CubicBezierTimingFunction::Create(0.42, 0, 0.58, 1));
keyframes[1]->SetComposite(EffectModel::kCompositeReplace);
+ // CubicBezier(0.42, 0, 0.58, 1)(0.6) = 0.6681161300485039.
auto* effect = MakeGarbageCollected<StringKeyframeEffectModel>(keyframes);
HeapVector<Member<Interpolation>> values;
effect->Sample(0, 0.6, kDuration, values);
- ExpectLengthValue(4.3363357, values.at(0));
+ ExpectLengthValue(4.336232, values.at(0));
effect->Sample(0, 0.6, kDuration * 1000, values);
- ExpectLengthValue(4.3362322, values.at(0));
+ ExpectLengthValue(4.336232, values.at(0));
}
TEST_F(AnimationKeyframeEffectModel, ExtrapolateReplaceNonInterpolable) {
@@ -572,7 +610,7 @@ TEST_F(AnimationKeyframeEffectModel, AddSyntheticKeyframes) {
auto* effect = MakeGarbageCollected<StringKeyframeEffectModel>(keyframes);
const StringPropertySpecificKeyframeVector& property_specific_keyframes =
- effect->GetPropertySpecificKeyframes(
+ *effect->GetPropertySpecificKeyframes(
PropertyHandle(GetCSSPropertyLeft()));
EXPECT_EQ(3U, property_specific_keyframes.size());
EXPECT_DOUBLE_EQ(0.0, property_specific_keyframes[0]->Offset());
@@ -598,10 +636,9 @@ TEST_F(AnimationKeyframeEffectModel, CompositorSnapshotUpdateBasic) {
const CompositorKeyframeValue* value;
// Compositor keyframe value should be empty before snapshot
- value = effect
- ->GetPropertySpecificKeyframes(
- PropertyHandle(GetCSSPropertyOpacity()))[0]
- ->GetCompositorKeyframeValue();
+ const auto& empty_keyframes = *effect->GetPropertySpecificKeyframes(
+ PropertyHandle(GetCSSPropertyOpacity()));
+ value = empty_keyframes[0]->GetCompositorKeyframeValue();
EXPECT_FALSE(value);
// Snapshot should update first time after construction
@@ -616,10 +653,9 @@ TEST_F(AnimationKeyframeEffectModel, CompositorSnapshotUpdateBasic) {
*element, *style, nullptr));
// Compositor keyframe value should be available after snapshot
- value = effect
- ->GetPropertySpecificKeyframes(
- PropertyHandle(GetCSSPropertyOpacity()))[0]
- ->GetCompositorKeyframeValue();
+ const auto& available_keyframes = *effect->GetPropertySpecificKeyframes(
+ PropertyHandle(GetCSSPropertyOpacity()));
+ value = available_keyframes[0]->GetCompositorKeyframeValue();
EXPECT_TRUE(value);
EXPECT_TRUE(value->IsDouble());
}
@@ -637,10 +673,9 @@ TEST_F(AnimationKeyframeEffectModel,
*element, *style, nullptr));
const CompositorKeyframeValue* value;
- value = effect
- ->GetPropertySpecificKeyframes(
- PropertyHandle(GetCSSPropertyOpacity()))[0]
- ->GetCompositorKeyframeValue();
+ const auto& keyframes = *effect->GetPropertySpecificKeyframes(
+ PropertyHandle(GetCSSPropertyOpacity()));
+ value = keyframes[0]->GetCompositorKeyframeValue();
EXPECT_TRUE(value);
EXPECT_TRUE(value->IsDouble());
@@ -651,10 +686,9 @@ TEST_F(AnimationKeyframeEffectModel,
// Snapshot should update after changing keyframes
EXPECT_TRUE(effect->SnapshotAllCompositorKeyframesIfNecessary(
*element, *style, nullptr));
- value = effect
- ->GetPropertySpecificKeyframes(
- PropertyHandle(GetCSSPropertyFilter()))[0]
- ->GetCompositorKeyframeValue();
+ const auto& updated_keyframes = *effect->GetPropertySpecificKeyframes(
+ PropertyHandle(GetCSSPropertyFilter()));
+ value = updated_keyframes[0]->GetCompositorKeyframeValue();
EXPECT_TRUE(value);
EXPECT_TRUE(value->IsFilterOperations());
}
@@ -662,39 +696,95 @@ TEST_F(AnimationKeyframeEffectModel,
TEST_F(AnimationKeyframeEffectModel, CompositorSnapshotUpdateCustomProperty) {
ScopedOffMainThreadCSSPaintForTest off_main_thread_css_paint(true);
DummyExceptionStateForTesting exception_state;
- 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());
-
- StringKeyframeVector keyframes = KeyframesAtZeroAndOne(
- AtomicString("--foo"), GetDocument().GetPropertyRegistry(), "0", "100");
-
- element->style()->setProperty(&GetDocument(), "--foo", "0", g_empty_string,
- exception_state);
- EXPECT_FALSE(exception_state.HadException());
- auto* effect = MakeGarbageCollected<StringKeyframeEffectModel>(keyframes);
+ // Compositor keyframe value available after snapshot
+ const CompositorKeyframeValue* value =
+ ConstructEffectAndGetKeyframes("--foo", "<number>", &GetDocument(),
+ element, "0", "100", exception_state)[1]
+ ->GetCompositorKeyframeValue();
+ ASSERT_FALSE(exception_state.HadException());
- auto style = GetDocument().EnsureStyleResolver().StyleForElement(element);
+ // Test value holds the correct number type
+ EXPECT_TRUE(value);
+ EXPECT_TRUE(value->IsDouble());
+ EXPECT_EQ(ToCompositorKeyframeDouble(value)->ToDouble(), 100);
+}
- const CompositorKeyframeValue* value;
+TEST_F(AnimationKeyframeEffectModel, CompositorUpdateColorProperty) {
+ ScopedOffMainThreadCSSPaintForTest off_main_thread_css_paint(true);
+ DummyExceptionStateForTesting exception_state;
- // Snapshot should update first time after construction
- EXPECT_TRUE(effect->SnapshotAllCompositorKeyframesIfNecessary(
- *element, *style, nullptr));
+ element->style()->setProperty(&GetDocument(), "color", "rgb(0, 255, 0)",
+ g_empty_string, exception_state);
// Compositor keyframe value available after snapshot
- value = effect
- ->GetPropertySpecificKeyframes(
- PropertyHandle(AtomicString("--foo")))[0]
- ->GetCompositorKeyframeValue();
- EXPECT_TRUE(value);
- EXPECT_TRUE(value->IsDouble());
+ const CompositorKeyframeValue* value_rgb =
+ ConstructEffectAndGetKeyframes("--rgb", "<color>", &GetDocument(),
+ element, "rgb(0, 0, 0)", "rgb(0, 255, 0)",
+ exception_state)[1]
+ ->GetCompositorKeyframeValue();
+ const CompositorKeyframeValue* value_hsl =
+ ConstructEffectAndGetKeyframes("--hsl", "<color>", &GetDocument(),
+ element, "hsl(0, 0%, 0%)",
+ "hsl(120, 100%, 50%)", exception_state)[1]
+ ->GetCompositorKeyframeValue();
+ const CompositorKeyframeValue* value_name =
+ ConstructEffectAndGetKeyframes("--named", "<color>", &GetDocument(),
+ element, "black", "lime",
+ exception_state)[1]
+ ->GetCompositorKeyframeValue();
+ const CompositorKeyframeValue* value_hex =
+ ConstructEffectAndGetKeyframes("--hex", "<color>", &GetDocument(),
+ element, "#000000", "#00FF00",
+ exception_state)[1]
+ ->GetCompositorKeyframeValue();
+ const CompositorKeyframeValue* value_curr =
+ ConstructEffectAndGetKeyframes("--curr", "<color>", &GetDocument(),
+ element, "#000000", "currentcolor",
+ exception_state)[1]
+ ->GetCompositorKeyframeValue();
+ const PropertySpecificKeyframeVector& values_mixed =
+ ConstructEffectAndGetKeyframes("--mixed", "<color>", &GetDocument(),
+ element, "#000000", "lime",
+ exception_state);
+ ASSERT_FALSE(exception_state.HadException());
+
+ // Test rgb color input
+ EXPECT_TRUE(value_rgb);
+ EXPECT_TRUE(value_rgb->IsColor());
+ EXPECT_EQ(ToCompositorKeyframeColor(value_rgb)->ToColor(), SK_ColorGREEN);
+
+ // Test hsl color input
+ EXPECT_TRUE(value_hsl);
+ EXPECT_TRUE(value_hsl->IsColor());
+ EXPECT_EQ(ToCompositorKeyframeColor(value_hsl)->ToColor(), SK_ColorGREEN);
+
+ // Test named color input
+ EXPECT_TRUE(value_name);
+ EXPECT_TRUE(value_name->IsColor());
+ EXPECT_EQ(ToCompositorKeyframeColor(value_name)->ToColor(), SK_ColorGREEN);
+
+ // Test hex color input
+ EXPECT_TRUE(value_hex);
+ EXPECT_TRUE(value_hex->IsColor());
+ EXPECT_EQ(ToCompositorKeyframeColor(value_hex)->ToColor(), SK_ColorGREEN);
+
+ // currentcolor is a CSSIdentifierValue not a color
+ EXPECT_FALSE(value_curr);
+
+ // Ensure both frames are consistent when values are mixed
+ const CompositorKeyframeValue* value_mixed0 =
+ values_mixed[0]->GetCompositorKeyframeValue();
+ const CompositorKeyframeValue* value_mixed1 =
+ values_mixed[1]->GetCompositorKeyframeValue();
+
+ EXPECT_TRUE(value_mixed0);
+ EXPECT_TRUE(value_mixed0->IsColor());
+ EXPECT_EQ(ToCompositorKeyframeColor(value_mixed0)->ToColor(), SK_ColorBLACK);
+
+ EXPECT_TRUE(value_mixed1);
+ EXPECT_TRUE(value_mixed1->IsColor());
+ EXPECT_EQ(ToCompositorKeyframeColor(value_mixed1)->ToColor(), SK_ColorGREEN);
}
} // namespace blink
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 49c46cfaa5a..7545f7e9338 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
@@ -42,6 +42,31 @@ class KeyframeEffectTest : public PageTestBase {
StringKeyframeVector());
}
+ // Returns a two-frame effect updated styles.
+ KeyframeEffect* GetTwoFrameEffect(const CSSPropertyID& property,
+ const String& value_a,
+ const String& value_b) {
+ StringKeyframeVector keyframes(2);
+ keyframes[0] = MakeGarbageCollected<StringKeyframe>();
+ keyframes[0]->SetOffset(0.0);
+ keyframes[0]->SetCSSPropertyValue(
+ property, value_a, SecureContextMode::kInsecureContext, nullptr);
+ keyframes[1] = MakeGarbageCollected<StringKeyframe>();
+ keyframes[1]->SetOffset(1.0);
+ keyframes[1]->SetCSSPropertyValue(
+ property, value_b, SecureContextMode::kInsecureContext, nullptr);
+ auto* model = MakeGarbageCollected<StringKeyframeEffectModel>(keyframes);
+ Timing timing;
+ auto* effect = MakeGarbageCollected<KeyframeEffect>(element, model, timing);
+ // Ensure GetCompositorKeyframeValue is updated which would normally happen
+ // when applying the animation styles.
+ UpdateAllLifecyclePhasesForTest();
+ model->SnapshotAllCompositorKeyframesIfNecessary(
+ *element, *element->GetComputedStyle(), nullptr);
+
+ return effect;
+ }
+
Persistent<Element> element;
};
@@ -188,7 +213,7 @@ TEST_F(AnimationKeyframeEffectV8Test, KeyframeCompositeOverridesEffect) {
PropertyHandle property(GetCSSPropertyWidth());
const PropertySpecificKeyframeVector& keyframes =
- effect->Model()->GetPropertySpecificKeyframes(property);
+ *effect->Model()->GetPropertySpecificKeyframes(property);
EXPECT_EQ(EffectModel::kCompositeReplace, keyframes[0]->Composite());
EXPECT_EQ(EffectModel::kCompositeAdd, keyframes[1]->Composite());
@@ -346,22 +371,26 @@ TEST_F(KeyframeEffectTest, TimeToEffectChange) {
Animation* animation = GetDocument().Timeline().Play(keyframe_effect);
double inf = std::numeric_limits<double>::infinity();
+ // Beginning of the animation.
EXPECT_EQ(100, keyframe_effect->TimeToForwardsEffectChange());
EXPECT_EQ(inf, keyframe_effect->TimeToReverseEffectChange());
+ // End of the before phase.
animation->SetCurrentTimeInternal(100);
EXPECT_EQ(100, keyframe_effect->TimeToForwardsEffectChange());
EXPECT_EQ(0, keyframe_effect->TimeToReverseEffectChange());
+ // Nearing the end of the active phase.
animation->SetCurrentTimeInternal(199);
EXPECT_EQ(1, keyframe_effect->TimeToForwardsEffectChange());
EXPECT_EQ(0, keyframe_effect->TimeToReverseEffectChange());
+ // End of the active phase.
animation->SetCurrentTimeInternal(200);
- // End-exclusive.
- EXPECT_EQ(inf, keyframe_effect->TimeToForwardsEffectChange());
+ EXPECT_EQ(100, keyframe_effect->TimeToForwardsEffectChange());
EXPECT_EQ(0, keyframe_effect->TimeToReverseEffectChange());
+ // End of the animation.
animation->SetCurrentTimeInternal(300);
EXPECT_EQ(inf, keyframe_effect->TimeToForwardsEffectChange());
EXPECT_EQ(100, keyframe_effect->TimeToReverseEffectChange());
@@ -447,23 +476,47 @@ TEST_F(KeyframeEffectTest, CheckCanStartAnimationOnCompositorBadTarget) {
MakeGarbageCollected<KeyframeEffect>(element, effect_model, timing);
// If the target has a CSS offset we can't composite it.
+ element->SetInlineStyleProperty(CSSPropertyID::kOffsetPosition, "50px 50px");
UpdateAllLifecyclePhasesForTest();
- element->MutableComputedStyle()->SetOffsetPosition(
- LengthPoint(Length::Percent(50.0), Length::Auto()));
+
ASSERT_TRUE(element->GetComputedStyle()->HasOffset());
EXPECT_TRUE(keyframe_effect->CheckCanStartAnimationOnCompositor(
nullptr, animation_playback_rate) &
CompositorAnimations::kTargetHasCSSOffset);
// If the target has multiple transform properties we can't composite it.
+ element->SetInlineStyleProperty(CSSPropertyID::kRotate, "90deg");
+ element->SetInlineStyleProperty(CSSPropertyID::kScale, "2 1");
UpdateAllLifecyclePhasesForTest();
- element->MutableComputedStyle()->SetRotate(
- RotateTransformOperation::Create(100, TransformOperation::kRotateX));
- element->MutableComputedStyle()->SetScale(
- ScaleTransformOperation::Create(2, 1, TransformOperation::kScaleX));
+
EXPECT_TRUE(keyframe_effect->CheckCanStartAnimationOnCompositor(
nullptr, animation_playback_rate) &
CompositorAnimations::kTargetHasMultipleTransformProperties);
}
+TEST_F(KeyframeEffectTest, TranslationTransformsPreserveAxisAlignment) {
+ auto* effect =
+ GetTwoFrameEffect(CSSPropertyID::kTransform, "translate(10px, 10px)",
+ "translate(20px, 20px)");
+ EXPECT_TRUE(effect->AnimationsPreserveAxisAlignment());
+}
+
+TEST_F(KeyframeEffectTest, ScaleTransformsPreserveAxisAlignment) {
+ auto* effect =
+ GetTwoFrameEffect(CSSPropertyID::kTransform, "scale(2)", "scale(3)");
+ EXPECT_TRUE(effect->AnimationsPreserveAxisAlignment());
+}
+
+TEST_F(KeyframeEffectTest, RotationTransformsDoNotPreserveAxisAlignment) {
+ auto* effect = GetTwoFrameEffect(CSSPropertyID::kTransform, "rotate(10deg)",
+ "rotate(20deg)");
+
+ EXPECT_FALSE(effect->AnimationsPreserveAxisAlignment());
+}
+
+TEST_F(KeyframeEffectTest, RotationsDoNotPreserveAxisAlignment) {
+ auto* effect = GetTwoFrameEffect(CSSPropertyID::kRotate, "10deg", "20deg");
+ EXPECT_FALSE(effect->AnimationsPreserveAxisAlignment());
+}
+
} // namespace blink
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 c5ec0f72985..58eba51f8ae 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
@@ -4,7 +4,9 @@
#include "third_party/blink/renderer/core/animation/length_interpolation_functions.h"
-#include "third_party/blink/renderer/core/css/css_calculation_value.h"
+#include "third_party/blink/renderer/core/css/css_math_expression_node.h"
+#include "third_party/blink/renderer/core/css/css_math_function_value.h"
+#include "third_party/blink/renderer/core/css/css_numeric_literal_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/geometry/calculation_value.h"
@@ -134,6 +136,11 @@ bool LengthInterpolationFunctions::NonInterpolableValuesAreCompatible(
return true;
}
+bool LengthInterpolationFunctions::HasPercentage(
+ const NonInterpolableValue* non_interpolable_value) {
+ return CSSLengthNonInterpolableValue::HasPercentage(non_interpolable_value);
+}
+
void LengthInterpolationFunctions::Composite(
std::unique_ptr<InterpolableValue>& underlying_interpolable_value,
scoped_refptr<NonInterpolableValue>& underlying_non_interpolable_value,
@@ -211,8 +218,8 @@ const CSSValue* LengthInterpolationFunctions::CreateCSSValue(
bool has_percentage =
CSSLengthNonInterpolableValue::HasPercentage(non_interpolable_value);
- CSSCalcExpressionNode* root_node = nullptr;
- CSSPrimitiveValue* first_value = nullptr;
+ CSSMathExpressionNode* root_node = nullptr;
+ CSSNumericLiteralValue* first_value = nullptr;
for (wtf_size_t i = 0; i < CSSPrimitiveValue::kLengthUnitTypeCount; i++) {
double value = ToInterpolableNumber(*interpolable_list.Get(i)).Value();
@@ -220,30 +227,31 @@ const CSSValue* LengthInterpolationFunctions::CreateCSSValue(
(i != CSSPrimitiveValue::kUnitTypePercentage || !has_percentage)) {
continue;
}
- CSSPrimitiveValue* current_value =
- CSSPrimitiveValue::Create(value, IndexToUnitType(i));
+ CSSNumericLiteralValue* current_value =
+ CSSNumericLiteralValue::Create(value, IndexToUnitType(i));
if (!first_value) {
DCHECK(!root_node);
first_value = current_value;
continue;
}
- CSSCalcExpressionNode* current_node =
- CSSCalcValue::CreateExpressionNode(current_value);
+ CSSMathExpressionNode* current_node =
+ CSSMathExpressionNumericLiteral::Create(current_value);
if (!root_node) {
- root_node = CSSCalcValue::CreateExpressionNode(first_value);
+ root_node = CSSMathExpressionNumericLiteral::Create(first_value);
}
- root_node =
- CSSCalcValue::CreateExpressionNode(root_node, current_node, kCalcAdd);
+ root_node = CSSMathExpressionBinaryOperation::Create(
+ root_node, current_node, CSSMathOperator::kAdd);
}
if (root_node) {
- return CSSPrimitiveValue::Create(CSSCalcValue::Create(root_node));
+ return CSSMathFunctionValue::Create(root_node);
}
if (first_value) {
return first_value;
}
- return CSSPrimitiveValue::Create(0, CSSPrimitiveValue::UnitType::kPixels);
+ return CSSNumericLiteralValue::Create(0,
+ CSSPrimitiveValue::UnitType::kPixels);
}
} // 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 841ae0ebf8b..e765860d930 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
@@ -30,6 +30,7 @@ class LengthInterpolationFunctions {
InterpolationValue&& end);
static bool NonInterpolableValuesAreCompatible(const NonInterpolableValue*,
const NonInterpolableValue*);
+ static bool HasPercentage(const NonInterpolableValue*);
static void Composite(std::unique_ptr<InterpolableValue>&,
scoped_refptr<NonInterpolableValue>&,
double underlying_fraction,
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 43e2f83d4b4..2253c0aecb0 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
@@ -8,7 +8,7 @@
#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/geometry/length.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/animation/list_interpolation_functions.h b/chromium/third_party/blink/renderer/core/animation/list_interpolation_functions.h
index 15491312b9d..9682f590bf0 100644
--- a/chromium/third_party/blink/renderer/core/animation/list_interpolation_functions.h
+++ b/chromium/third_party/blink/renderer/core/animation/list_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/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/animation/list_interpolation_functions_test.cc b/chromium/third_party/blink/renderer/core/animation/list_interpolation_functions_test.cc
index 22ca8a75f93..c99edeeab89 100644
--- a/chromium/third_party/blink/renderer/core/animation/list_interpolation_functions_test.cc
+++ b/chromium/third_party/blink/renderer/core/animation/list_interpolation_functions_test.cc
@@ -5,7 +5,6 @@
#include "third_party/blink/renderer/core/animation/list_interpolation_functions.h"
#include <utility>
-#include <vector>
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/core/animation/css_number_interpolation_type.h"
@@ -47,7 +46,7 @@ inline const TestNonInterpolableValue& ToTestNonInterpolableValue(
// Creates an InterpolationValue containing a list of interpolable and
// non-interpolable values from the pairs of input.
InterpolationValue CreateInterpolableList(
- const std::vector<std::pair<double, int>>& values) {
+ const Vector<std::pair<double, int>>& values) {
return ListInterpolationFunctions::CreateList(
values.size(), [&values](size_t i) {
return InterpolationValue(
@@ -58,7 +57,7 @@ InterpolationValue CreateInterpolableList(
// Creates an InterpolationValue which contains a list of interpolable values,
// but a non-interpolable list of nullptrs.
-InterpolationValue CreateInterpolableList(const std::vector<double>& values) {
+InterpolationValue CreateInterpolableList(const Vector<double>& values) {
return ListInterpolationFunctions::CreateList(
values.size(), [&values](size_t i) {
return InterpolationValue(
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 759658147ea..39e492a4043 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
@@ -7,7 +7,7 @@
#include "base/optional.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/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/animation/path_interpolation_functions.h b/chromium/third_party/blink/renderer/core/animation/path_interpolation_functions.h
index 96b91cc8b36..a545f0239be 100644
--- a/chromium/third_party/blink/renderer/core/animation/path_interpolation_functions.h
+++ b/chromium/third_party/blink/renderer/core/animation/path_interpolation_functions.h
@@ -8,7 +8,7 @@
#include <memory>
#include "third_party/blink/renderer/core/animation/interpolation_type.h"
#include "third_party/blink/renderer/core/svg/svg_path_byte_stream.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/animation/pending_animations.cc b/chromium/third_party/blink/renderer/core/animation/pending_animations.cc
index 2bbc247254b..47aa306666e 100644
--- a/chromium/third_party/blink/renderer/core/animation/pending_animations.cc
+++ b/chromium/third_party/blink/renderer/core/animation/pending_animations.cc
@@ -44,13 +44,13 @@ void PendingAnimations::Add(Animation* animation) {
DCHECK_EQ(pending_.Find(animation), kNotFound);
pending_.push_back(animation);
- Document* document = animation->TimelineInternal()->GetDocument();
+ Document* document = animation->GetDocument();
if (document->View())
document->View()->ScheduleAnimation();
bool visible = document->GetPage() && document->GetPage()->IsPageVisible();
if (!visible && !timer_.IsActive()) {
- timer_.StartOneShot(TimeDelta(), FROM_HERE);
+ timer_.StartOneShot(base::TimeDelta(), FROM_HERE);
}
}
@@ -78,8 +78,7 @@ bool PendingAnimations::Update(
}
if (animation->Playing() && !animation->startTime() &&
- animation->TimelineInternal() &&
- animation->TimelineInternal()->IsActive()) {
+ animation->timeline() && animation->timeline()->IsActive()) {
waiting_for_start_time.push_back(animation.Get());
}
} else {
@@ -96,14 +95,18 @@ bool PendingAnimations::Update(
} else {
for (auto& animation : waiting_for_start_time) {
DCHECK(!animation->startTime());
+ // TODO(crbug.com/916117): Handle start time of scroll-linked animations.
animation->NotifyCompositorStartTime(
- animation->TimelineInternal()->CurrentTimeInternal());
+ animation->timeline()->CurrentTimeSeconds().value_or(0));
}
}
// FIXME: The postCommit should happen *after* the commit, not before.
- for (auto& animation : animations)
- animation->PostCommit(animation->TimelineInternal()->CurrentTimeInternal());
+ for (auto& animation : animations) {
+ // TODO(crbug.com/916117): Handle NaN current time of scroll timeline.
+ animation->PostCommit(
+ animation->timeline()->CurrentTimeSeconds().value_or(0));
+ }
DCHECK(pending_.IsEmpty());
DCHECK(start_on_compositor || deferred.IsEmpty());
@@ -124,7 +127,8 @@ bool PendingAnimations::Update(
}
// If not, go ahead and start any animations that were waiting.
- NotifyCompositorAnimationStarted(CurrentTimeTicksInSeconds());
+ NotifyCompositorAnimationStarted(
+ base::TimeTicks::Now().since_origin().InSecondsF());
DCHECK_EQ(pending_.size(), deferred.size());
return false;
@@ -140,8 +144,7 @@ void PendingAnimations::NotifyCompositorAnimationStarted(
for (auto animation : animations) {
if (animation->startTime() ||
animation->PlayStateInternal() != Animation::kPending ||
- !animation->TimelineInternal() ||
- !animation->TimelineInternal()->IsActive()) {
+ !animation->timeline() || !animation->timeline()->IsActive()) {
// Already started or no longer relevant.
continue;
}
@@ -150,9 +153,13 @@ void PendingAnimations::NotifyCompositorAnimationStarted(
waiting_for_compositor_animation_start_.push_back(animation);
continue;
}
+ DCHECK(animation->timeline()->IsDocumentTimeline());
animation->NotifyCompositorStartTime(
monotonic_animation_start_time -
- animation->TimelineInternal()->ZeroTime().since_origin().InSecondsF());
+ ToDocumentTimeline(animation->timeline())
+ ->ZeroTime()
+ .since_origin()
+ .InSecondsF());
}
}
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 39fb5a06787..4263c65f39c 100644
--- a/chromium/third_party/blink/renderer/core/animation/property_handle.h
+++ b/chromium/third_party/blink/renderer/core/animation/property_handle.h
@@ -10,7 +10,7 @@
#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/dom/qualified_name.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
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 cefbba9571c..b35a6952194 100644
--- a/chromium/third_party/blink/renderer/core/animation/sampled_effect.h
+++ b/chromium/third_party/blink/renderer/core/animation/sampled_effect.h
@@ -9,7 +9,7 @@
#include "third_party/blink/renderer/core/animation/animation.h"
#include "third_party/blink/renderer/core/animation/interpolation.h"
#include "third_party/blink/renderer/core/animation/keyframe_effect.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
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 47546bf6745..1c91e9f713b 100644
--- a/chromium/third_party/blink/renderer/core/animation/scroll_timeline.cc
+++ b/chromium/third_party/blink/renderer/core/animation/scroll_timeline.cc
@@ -4,7 +4,6 @@
#include "third_party/blink/renderer/core/animation/scroll_timeline.h"
-#include "third_party/blink/renderer/core/css/css_calculation_value.h"
#include "third_party/blink/renderer/core/css/css_to_length_conversion_data.h"
#include "third_party/blink/renderer/core/css/parser/css_tokenizer.h"
#include "third_party/blink/renderer/core/css/properties/css_parsing_utils.h"
@@ -22,7 +21,7 @@ namespace {
using ActiveScrollTimelineSet = HeapHashCountedSet<WeakMember<Node>>;
ActiveScrollTimelineSet& GetActiveScrollTimelineSet() {
DEFINE_STATIC_LOCAL(Persistent<ActiveScrollTimelineSet>, set,
- (new ActiveScrollTimelineSet));
+ (MakeGarbageCollected<ActiveScrollTimelineSet>()));
return *set;
}
@@ -109,18 +108,20 @@ ScrollTimeline* ScrollTimeline::Create(Document& document,
}
return MakeGarbageCollected<ScrollTimeline>(
- scroll_source, orientation, start_scroll_offset, end_scroll_offset,
- options->timeRange().GetAsDouble(),
+ &document, scroll_source, orientation, start_scroll_offset,
+ end_scroll_offset, options->timeRange().GetAsDouble(),
Timing::StringToFillMode(options->fill()));
}
-ScrollTimeline::ScrollTimeline(Element* scroll_source,
+ScrollTimeline::ScrollTimeline(Document* document,
+ Element* scroll_source,
ScrollDirection orientation,
CSSPrimitiveValue* start_scroll_offset,
CSSPrimitiveValue* end_scroll_offset,
double time_range,
Timing::FillMode fill)
- : scroll_source_(scroll_source),
+ : document_(document),
+ scroll_source_(scroll_source),
resolved_scroll_source_(ResolveScrollSource(scroll_source_)),
orientation_(orientation),
start_scroll_offset_(start_scroll_offset),
@@ -309,7 +310,7 @@ void ScrollTimeline::ResolveScrollStartAndEnd(
}
}
-void ScrollTimeline::AttachAnimation() {
+void ScrollTimeline::AnimationAttached(Animation*) {
if (!resolved_scroll_source_)
return;
@@ -327,7 +328,7 @@ void ScrollTimeline::AttachAnimation() {
object->SetNeedsPaintPropertyUpdate();
}
-void ScrollTimeline::DetachAnimation() {
+void ScrollTimeline::AnimationDetached(Animation*) {
if (!resolved_scroll_source_)
return;
@@ -348,6 +349,7 @@ void ScrollTimeline::DetachAnimation() {
}
void ScrollTimeline::Trace(blink::Visitor* visitor) {
+ visitor->Trace(document_);
visitor->Trace(scroll_source_);
visitor->Trace(resolved_scroll_source_);
visitor->Trace(start_scroll_offset_);
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 e71e10f8845..bbfc2fa6424 100644
--- a/chromium/third_party/blink/renderer/core/animation/scroll_timeline.h
+++ b/chromium/third_party/blink/renderer/core/animation/scroll_timeline.h
@@ -40,7 +40,8 @@ class CORE_EXPORT ScrollTimeline final : public AnimationTimeline {
ScrollTimelineOptions*,
ExceptionState&);
- ScrollTimeline(Element*,
+ ScrollTimeline(Document*,
+ Element*,
ScrollDirection,
CSSPrimitiveValue*,
CSSPrimitiveValue*,
@@ -50,6 +51,7 @@ class CORE_EXPORT ScrollTimeline final : public AnimationTimeline {
// AnimationTimeline implementation.
double currentTime(bool& is_null) final;
bool IsScrollTimeline() const override { return true; }
+ Document* GetDocument() override { return document_; }
// ScrollTimeline is not active if scrollSource is null, does not currently
// have a CSS layout box, or if its layout box is not a scroll container.
// https://github.com/WICG/scroll-animations/issues/31
@@ -82,8 +84,8 @@ class CORE_EXPORT ScrollTimeline final : public AnimationTimeline {
// Must be called when this ScrollTimeline is attached/detached from an
// animation.
- void AttachAnimation();
- void DetachAnimation();
+ void AnimationAttached(Animation*) override;
+ void AnimationDetached(Animation*) override;
void Trace(blink::Visitor*) override;
@@ -95,6 +97,7 @@ class CORE_EXPORT ScrollTimeline final : public AnimationTimeline {
static bool HasActiveScrollTimeline(Node* node);
private:
+ Member<Document> document_;
// 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_;
diff --git a/chromium/third_party/blink/renderer/core/animation/scroll_timeline.idl b/chromium/third_party/blink/renderer/core/animation/scroll_timeline.idl
index 329f260f86b..bd0cd9c86a0 100644
--- a/chromium/third_party/blink/renderer/core/animation/scroll_timeline.idl
+++ b/chromium/third_party/blink/renderer/core/animation/scroll_timeline.idl
@@ -9,7 +9,8 @@
ConstructorCallWith=Document,
MeasureAs=ScrollTimelineConstructor,
RaisesException=Constructor,
- RuntimeEnabled=AnimationWorklet
+ RuntimeEnabled=ScrollTimeline,
+ Exposed=Window
] interface ScrollTimeline : AnimationTimeline {
readonly attribute Element? scrollSource;
readonly attribute ScrollDirection orientation;
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 0ea38b93c9a..6e5bbe92422 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
@@ -13,11 +13,15 @@
namespace blink {
-using ScrollTimelineTest = RenderingTest;
+class ScrollTimelineTest : public RenderingTest {
+ void SetUp() override {
+ EnableCompositing();
+ RenderingTest::SetUp();
+ }
+};
TEST_F(ScrollTimelineTest,
AttachingAndDetachingAnimationCausesCompositingUpdate) {
- EnableCompositing();
SetBodyInnerHTML(R"HTML(
<style>#scroller { overflow: scroll; width: 100px; height: 100px; }</style>
@@ -47,13 +51,13 @@ TEST_F(ScrollTimelineTest,
EXPECT_EQ(kNotComposited, scroller->Layer()->GetCompositingState());
// Now attach an animation. This should require a compositing update.
- scroll_timeline->AttachAnimation();
+ scroll_timeline->AnimationAttached(nullptr);
UpdateAllLifecyclePhasesForTest();
EXPECT_NE(scroller->Layer()->GetCompositingState(), kNotComposited);
// Now detach an animation. This should again require a compositing update.
- scroll_timeline->DetachAnimation();
+ scroll_timeline->AnimationDetached(nullptr);
UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(scroller->Layer()->GetCompositingState(), kNotComposited);
@@ -231,7 +235,7 @@ TEST_F(ScrollTimelineTest, AttachOrDetachAnimationWithNullScrollSource) {
CSSPrimitiveValue* start_scroll_offset = nullptr;
CSSPrimitiveValue* end_scroll_offset = nullptr;
ScrollTimeline* scroll_timeline = MakeGarbageCollected<ScrollTimeline>(
- scroll_source, ScrollTimeline::Block, start_scroll_offset,
+ &GetDocument(), scroll_source, ScrollTimeline::Block, start_scroll_offset,
end_scroll_offset, 100, Timing::FillMode::NONE);
// Sanity checks.
@@ -239,8 +243,8 @@ TEST_F(ScrollTimelineTest, AttachOrDetachAnimationWithNullScrollSource) {
ASSERT_EQ(scroll_timeline->ResolvedScrollSource(), nullptr);
// These calls should be no-ops in this mode, and shouldn't crash.
- scroll_timeline->AttachAnimation();
- scroll_timeline->DetachAnimation();
+ scroll_timeline->AnimationAttached(nullptr);
+ scroll_timeline->AnimationDetached(nullptr);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/animation/scroll_timeline_util_test.cc b/chromium/third_party/blink/renderer/core/animation/scroll_timeline_util_test.cc
index 2897cc740ae..b22caec41f8 100644
--- a/chromium/third_party/blink/renderer/core/animation/scroll_timeline_util_test.cc
+++ b/chromium/third_party/blink/renderer/core/animation/scroll_timeline_util_test.cc
@@ -82,7 +82,7 @@ TEST_F(ScrollTimelineUtilTest, ToCompositorScrollTimelineNullScrollSource) {
CSSPrimitiveValue* start_scroll_offset = nullptr;
CSSPrimitiveValue* end_scroll_offset = nullptr;
ScrollTimeline* timeline = MakeGarbageCollected<ScrollTimeline>(
- scroll_source, ScrollTimeline::Block, start_scroll_offset,
+ &GetDocument(), scroll_source, ScrollTimeline::Block, start_scroll_offset,
end_scroll_offset, 100, Timing::FillMode::NONE);
std::unique_ptr<CompositorScrollTimeline> compositor_timeline =
diff --git a/chromium/third_party/blink/renderer/core/animation/string_keyframe.cc b/chromium/third_party/blink/renderer/core/animation/string_keyframe.cc
index f43b0f77daa..6439f736f37 100644
--- a/chromium/third_party/blink/renderer/core/animation/string_keyframe.cc
+++ b/chromium/third_party/blink/renderer/core/animation/string_keyframe.cc
@@ -8,6 +8,8 @@
#include "third_party/blink/renderer/core/animation/animation_input_helpers.h"
#include "third_party/blink/renderer/core/animation/css/css_animations.h"
#include "third_party/blink/renderer/core/css/css_custom_property_declaration.h"
+#include "third_party/blink/renderer/core/css/css_keyframe_shorthand_value.h"
+#include "third_party/blink/renderer/core/css/parser/css_parser.h"
#include "third_party/blink/renderer/core/css/resolver/style_resolver.h"
#include "third_party/blink/renderer/core/style_property_shorthand.h"
#include "third_party/blink/renderer/core/svg/svg_element.h"
@@ -15,8 +17,39 @@
namespace blink {
+namespace {
+
+// Returns handle for the given CSSProperty.
+// |value| is required only for custom properties.
+PropertyHandle ToPropertyHandle(const CSSProperty& property,
+ const CSSValue* value) {
+ if (property.IDEquals(CSSPropertyID::kVariable)) {
+ return PropertyHandle(To<CSSCustomPropertyDeclaration>(*value).GetName());
+ } else {
+ return PropertyHandle(property, false);
+ }
+}
+
+const CSSValue* GetOrCreateCSSValueFrom(
+ const CSSProperty& property,
+ const MutableCSSPropertyValueSet& property_value_set) {
+ DCHECK_NE(property.PropertyID(), CSSPropertyID::kInvalid);
+ DCHECK_NE(property.PropertyID(), CSSPropertyID::kVariable);
+ if (!property.IsShorthand())
+ return property_value_set.GetPropertyCSSValue(property.PropertyID());
+
+ // For shorthands create a special wrapper value, |CSSKeyframeShorthandValue|,
+ // which can be used to correctly serialize it given longhands that are
+ // present in this set.
+ return MakeGarbageCollected<CSSKeyframeShorthandValue>(
+ property_value_set.ImmutableCopyIfNeeded());
+}
+
+} // namespace
+
StringKeyframe::StringKeyframe(const StringKeyframe& copy_from)
: Keyframe(copy_from.offset_, copy_from.composite_, copy_from.easing_),
+ input_properties_(copy_from.input_properties_),
css_property_map_(copy_from.css_property_map_->MutableCopy()),
presentation_attribute_map_(
copy_from.presentation_attribute_map_->MutableCopy()),
@@ -24,35 +57,71 @@ StringKeyframe::StringKeyframe(const StringKeyframe& copy_from)
MutableCSSPropertyValueSet::SetResult StringKeyframe::SetCSSPropertyValue(
const AtomicString& property_name,
- const PropertyRegistry* registry,
const String& value,
SecureContextMode secure_context_mode,
StyleSheetContents* style_sheet_contents) {
bool is_animation_tainted = true;
- return css_property_map_->SetProperty(
- property_name, registry, value, false, secure_context_mode,
- style_sheet_contents, is_animation_tainted);
+ MutableCSSPropertyValueSet::SetResult result = css_property_map_->SetProperty(
+ property_name, value, false, secure_context_mode, style_sheet_contents,
+ is_animation_tainted);
+
+ const CSSValue* parsed_value =
+ css_property_map_->GetPropertyCSSValue(property_name);
+
+ if (result.did_parse && parsed_value) {
+ // Per specification we only keep properties around which are parsable.
+ input_properties_.Set(PropertyHandle(property_name), *parsed_value);
+ }
+
+ return result;
}
MutableCSSPropertyValueSet::SetResult StringKeyframe::SetCSSPropertyValue(
- CSSPropertyID property,
+ CSSPropertyID property_id,
const String& value,
SecureContextMode secure_context_mode,
StyleSheetContents* style_sheet_contents) {
- DCHECK_NE(property, CSSPropertyID::kInvalid);
- if (CSSAnimations::IsAnimationAffectingProperty(CSSProperty::Get(property))) {
+ DCHECK_NE(property_id, CSSPropertyID::kInvalid);
+ DCHECK_NE(property_id, CSSPropertyID::kVariable);
+ const CSSProperty& property = CSSProperty::Get(property_id);
+
+ if (CSSAnimations::IsAnimationAffectingProperty(property)) {
bool did_parse = true;
bool did_change = false;
return MutableCSSPropertyValueSet::SetResult{did_parse, did_change};
}
- return css_property_map_->SetProperty(
- property, value, false, secure_context_mode, style_sheet_contents);
+
+ // Use a temporary set for shorthands so that its longhands are stored
+ // separately and can later be used to construct a special shorthand value.
+ bool use_temporary_set = property.IsShorthand();
+
+ auto* property_value_set =
+ use_temporary_set ? MakeGarbageCollected<MutableCSSPropertyValueSet>(
+ css_property_map_->CssParserMode())
+ : css_property_map_.Get();
+
+ MutableCSSPropertyValueSet::SetResult result =
+ property_value_set->SetProperty(
+ property_id, value, false, secure_context_mode, style_sheet_contents);
+
+ const CSSValue* parsed_value =
+ GetOrCreateCSSValueFrom(property, *property_value_set);
+ if (result.did_parse && parsed_value) {
+ // Per specification we only keep properties around which are parsable.
+ input_properties_.Set(PropertyHandle(property), parsed_value);
+ }
+
+ if (use_temporary_set)
+ css_property_map_->MergeAndOverrideOnConflict(property_value_set);
+
+ return result;
}
void StringKeyframe::SetCSSPropertyValue(const CSSProperty& property,
const CSSValue& value) {
DCHECK_NE(property.PropertyID(), CSSPropertyID::kInvalid);
DCHECK(!CSSAnimations::IsAnimationAffectingProperty(property));
+ input_properties_.Set(ToPropertyHandle(property, &value), value);
css_property_map_->SetProperty(property.PropertyID(), value, false);
}
@@ -85,13 +154,7 @@ PropertyHandleSet StringKeyframe::Properties() const {
DCHECK(!property.IsShorthand())
<< "Web Animations: Encountered unexpanded shorthand CSS property ("
<< static_cast<int>(property.PropertyID()) << ").";
- if (property.IDEquals(CSSPropertyID::kVariable)) {
- properties.insert(PropertyHandle(
- To<CSSCustomPropertyDeclaration>(property_reference.Value())
- .GetName()));
- } else {
- properties.insert(PropertyHandle(property, false));
- }
+ properties.insert(ToPropertyHandle(property, &property_reference.Value()));
}
for (unsigned i = 0; i < presentation_attribute_map_->PropertyCount(); ++i) {
@@ -117,25 +180,41 @@ bool StringKeyframe::HasCssProperty() const {
void StringKeyframe::AddKeyframePropertiesToV8Object(
V8ObjectBuilder& object_builder) const {
Keyframe::AddKeyframePropertiesToV8Object(object_builder);
+ for (const auto& entry : input_properties_) {
+ const PropertyHandle& property_handle = entry.key;
+ const CSSValue* property_value = entry.value;
+ String property_name =
+ AnimationInputHelpers::PropertyHandleToKeyframeAttribute(
+ property_handle);
+
+ object_builder.Add(property_name, property_value->CssText());
+ }
+
+ // Legacy code path for SVG and Presentation attributes.
+ //
+ // TODO(816956): Move these to input_properties_ and remove this. Note that
+ // this code path is not well tested given that removing it didn't cause any
+ // test failures.
for (const PropertyHandle& property : Properties()) {
+ if (property.IsCSSProperty())
+ continue;
+
String property_name =
AnimationInputHelpers::PropertyHandleToKeyframeAttribute(property);
- String value;
- if (property.IsCSSProperty()) {
- value = CssPropertyValue(property).CssText();
- } else if (property.IsPresentationAttribute()) {
+ String property_value;
+ if (property.IsPresentationAttribute()) {
const auto& attribute = property.PresentationAttribute();
- value = PresentationAttributeValue(attribute).CssText();
+ property_value = PresentationAttributeValue(attribute).CssText();
} else {
DCHECK(property.IsSVGAttribute());
- value = SvgPropertyValue(property.SvgAttribute());
+ property_value = SvgPropertyValue(property.SvgAttribute());
}
-
- object_builder.Add(property_name, value);
+ object_builder.Add(property_name, property_value);
}
}
void StringKeyframe::Trace(Visitor* visitor) {
+ visitor->Trace(input_properties_);
visitor->Trace(css_property_map_);
visitor->Trace(presentation_attribute_map_);
Keyframe::Trace(visitor);
diff --git a/chromium/third_party/blink/renderer/core/animation/string_keyframe.h b/chromium/third_party/blink/renderer/core/animation/string_keyframe.h
index f874880831d..87c9a03937c 100644
--- a/chromium/third_party/blink/renderer/core/animation/string_keyframe.h
+++ b/chromium/third_party/blink/renderer/core/animation/string_keyframe.h
@@ -37,7 +37,6 @@ class CORE_EXPORT StringKeyframe : public Keyframe {
MutableCSSPropertyValueSet::SetResult SetCSSPropertyValue(
const AtomicString& property_name,
- const PropertyRegistry*,
const String& value,
SecureContextMode,
StyleSheetContents*);
@@ -165,6 +164,28 @@ class CORE_EXPORT StringKeyframe : public Keyframe {
bool IsStringKeyframe() const override { return true; }
+ // The unresolved property and their values. This is needed for correct
+ // implementation of KeyframeEffect.getKeyframes(). We use a single list for
+ // CSS, SVG properties. The only requirement for a property value to be
+ // in this list is that it parses correctly.
+ //
+ // See: https://drafts.csswg.org/web-animations/#keyframes-section
+ HeapHashMap<PropertyHandle, Member<const CSSValue>> input_properties_;
+
+ // The resolved properties are computed from unresolved ones applying these
+ // steps:
+ // 1. Resolve conflicts when multiple properties map to same underlying
+ // one (e.g., margin, margin-top)
+ // 2. Expand shorthands to longhands
+ // 3. Expand logical properties to physical ones
+ //
+ // See:
+ // https://drafts.csswg.org/web-animations/#calculating-computed-keyframes
+ //
+ // TODO(816956): AFAICT we don't do (1) at the moment rather we parse and feed
+ // values into the MutableCSSPropertyValueSet which keeps replacing values as
+ // they come in. I am not sure if it leads to the same conflict resolution
+ // that web-animation expects. This needs more investigation.
Member<MutableCSSPropertyValueSet> css_property_map_;
Member<MutableCSSPropertyValueSet> presentation_attribute_map_;
HashMap<const QualifiedName*, String> svg_attribute_map_;
diff --git a/chromium/third_party/blink/renderer/core/animation/timing.cc b/chromium/third_party/blink/renderer/core/animation/timing.cc
index 606f94ee73c..a23f37389c5 100644
--- a/chromium/third_party/blink/renderer/core/animation/timing.cc
+++ b/chromium/third_party/blink/renderer/core/animation/timing.cc
@@ -3,7 +3,10 @@
// found in the LICENSE file.
#include "third_party/blink/renderer/core/animation/timing.h"
+
+#include "third_party/blink/renderer/core/animation/computed_effect_timing.h"
#include "third_party/blink/renderer/core/animation/effect_timing.h"
+#include "third_party/blink/renderer/core/animation/timing_calculations.h"
namespace blink {
@@ -52,6 +55,35 @@ String Timing::PlaybackDirectionString(PlaybackDirection playback_direction) {
return "normal";
}
+Timing::FillMode Timing::ResolvedFillMode(bool is_keyframe_effect) const {
+ if (fill_mode != Timing::FillMode::AUTO)
+ return fill_mode;
+
+ // https://drafts.csswg.org/web-animations/#the-effecttiming-dictionaries
+ if (is_keyframe_effect)
+ return Timing::FillMode::NONE;
+ return Timing::FillMode::BOTH;
+}
+
+AnimationTimeDelta Timing::IterationDuration() const {
+ AnimationTimeDelta result = iteration_duration.value_or(AnimationTimeDelta());
+ DCHECK_GE(result, AnimationTimeDelta());
+ return result;
+}
+
+double Timing::ActiveDuration() const {
+ const double result =
+ MultiplyZeroAlwaysGivesZero(IterationDuration(), iteration_count);
+ DCHECK_GE(result, 0);
+ return result;
+}
+
+double Timing::EndTimeInternal() const {
+ // Per the spec, the end time has a lower bound of 0.0:
+ // https://drafts.csswg.org/web-animations-1/#end-time
+ return std::max(start_delay + ActiveDuration() + end_delay, 0.0);
+}
+
EffectTiming* Timing::ConvertToEffectTiming() const {
EffectTiming* effect_timing = EffectTiming::Create();
@@ -73,4 +105,48 @@ EffectTiming* Timing::ConvertToEffectTiming() const {
return effect_timing;
}
+ComputedEffectTiming* Timing::getComputedTiming(
+ const Timing::CalculatedTiming& calculated_timing,
+ bool is_keyframe_effect) const {
+ ComputedEffectTiming* computed_timing = ComputedEffectTiming::Create();
+
+ // ComputedEffectTiming members.
+ computed_timing->setEndTime(EndTimeInternal() * 1000);
+ computed_timing->setActiveDuration(ActiveDuration() * 1000);
+
+ if (IsNull(calculated_timing.local_time)) {
+ computed_timing->setLocalTimeToNull();
+ } else {
+ computed_timing->setLocalTime(calculated_timing.local_time * 1000);
+ }
+
+ if (calculated_timing.is_in_effect) {
+ computed_timing->setProgress(calculated_timing.progress.value());
+ computed_timing->setCurrentIteration(calculated_timing.current_iteration);
+ } else {
+ 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(start_delay * 1000);
+ computed_timing->setEndDelay(end_delay * 1000);
+ computed_timing->setFill(
+ Timing::FillModeString(ResolvedFillMode(is_keyframe_effect)));
+ computed_timing->setIterationStart(iteration_start);
+ computed_timing->setIterations(iteration_count);
+
+ UnrestrictedDoubleOrString duration;
+ duration.SetUnrestrictedDouble(IterationDuration().InMillisecondsF());
+ computed_timing->setDuration(duration);
+
+ computed_timing->setDirection(Timing::PlaybackDirectionString(direction));
+ computed_timing->setEasing(timing_function->ToString());
+
+ return computed_timing;
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/animation/timing.h b/chromium/third_party/blink/renderer/core/animation/timing.h
index 9b0fd2dae7c..5d0cc8c76a2 100644
--- a/chromium/third_party/blink/renderer/core/animation/timing.h
+++ b/chromium/third_party/blink/renderer/core/animation/timing.h
@@ -37,17 +37,34 @@
#include "third_party/blink/renderer/core/style/data_equivalency.h"
#include "third_party/blink/renderer/platform/animation/compositor_keyframe_model.h"
#include "third_party/blink/renderer/platform/animation/timing_function.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
namespace blink {
class EffectTiming;
+class ComputedEffectTiming;
+
+static inline bool IsNull(double value) {
+ return std::isnan(value);
+}
+
+static inline double NullValue() {
+ return std::numeric_limits<double>::quiet_NaN();
+}
struct CORE_EXPORT Timing {
USING_FAST_MALLOC(Timing);
public:
+ // Note that logic in CSSAnimations depends on the order of these values.
+ enum Phase {
+ kPhaseBefore,
+ kPhaseActive,
+ kPhaseAfter,
+ kPhaseNone,
+ };
+
using FillMode = CompositorKeyframeModel::FillMode;
using PlaybackDirection = CompositorKeyframeModel::Direction;
@@ -55,11 +72,6 @@ struct CORE_EXPORT Timing {
static FillMode StringToFillMode(const String&);
static String PlaybackDirectionString(PlaybackDirection);
- static const Timing& Defaults() {
- DEFINE_STATIC_LOCAL(Timing, timing, ());
- return timing;
- }
-
Timing()
: start_delay(0),
end_delay(0),
@@ -81,6 +93,14 @@ struct CORE_EXPORT Timing {
DCHECK(timing_function);
}
+ // https://drafts.csswg.org/web-animations-1/#iteration-duration
+ AnimationTimeDelta IterationDuration() const;
+
+ // https://drafts.csswg.org/web-animations-1/#active-duration
+ double ActiveDuration() const;
+ double EndTimeInternal() const;
+
+ Timing::FillMode ResolvedFillMode(bool is_animation) const;
EffectTiming* ConvertToEffectTiming() const;
bool operator==(const Timing& other) const {
@@ -105,6 +125,23 @@ struct CORE_EXPORT Timing {
PlaybackDirection direction;
scoped_refptr<TimingFunction> timing_function;
+
+ struct CalculatedTiming {
+ DISALLOW_NEW();
+ Phase phase;
+ double current_iteration;
+ base::Optional<double> progress;
+ bool is_current;
+ bool is_in_effect;
+ bool is_in_play;
+ double local_time = NullValue();
+ double time_to_forwards_effect_change;
+ double time_to_reverse_effect_change;
+ };
+
+ ComputedEffectTiming* getComputedTiming(
+ const Timing::CalculatedTiming& calculated_timing,
+ bool is_keyframe_effect) const;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/animation/timing_calculations.h b/chromium/third_party/blink/renderer/core/animation/timing_calculations.h
index b2d2c0765eb..362055da049 100644
--- a/chromium/third_party/blink/renderer/core/animation/timing_calculations.h
+++ b/chromium/third_party/blink/renderer/core/animation/timing_calculations.h
@@ -33,7 +33,6 @@
#include "third_party/blink/renderer/core/animation/animation_effect.h"
#include "third_party/blink/renderer/core/animation/timing.h"
-#include "third_party/blink/renderer/platform/animation/animation_utilities.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
namespace blink {
@@ -48,6 +47,12 @@ inline bool IsWithinEpsilon(double a, double b) {
inline bool LessThanOrEqualToWithinEpsilon(double a, double b) {
return a <= b || IsWithinEpsilon(a, b);
}
+
+inline bool EndsOnIterationBoundary(double iteration_count,
+ double iteration_start) {
+ DCHECK(std::isfinite(iteration_count));
+ return !fmod(iteration_count + iteration_start, 1);
+}
} // namespace
static inline double MultiplyZeroAlwaysGivesZero(double x, double y) {
@@ -63,14 +68,14 @@ static inline double MultiplyZeroAlwaysGivesZero(AnimationTimeDelta x,
}
// https://drafts.csswg.org/web-animations-1/#animation-effect-phases-and-states
-static inline AnimationEffect::Phase CalculatePhase(
+static inline Timing::Phase CalculatePhase(
double active_duration,
double local_time,
AnimationEffect::AnimationDirection direction,
const Timing& specified) {
DCHECK_GE(active_duration, 0);
if (IsNull(local_time))
- return AnimationEffect::kPhaseNone;
+ return Timing::kPhaseNone;
double end_time = std::max(
specified.start_delay + active_duration + specified.end_delay, 0.0);
double before_active_boundary_time =
@@ -78,41 +83,42 @@ static inline AnimationEffect::Phase CalculatePhase(
if (local_time < before_active_boundary_time ||
(local_time == before_active_boundary_time &&
direction == AnimationEffect::AnimationDirection::kBackwards)) {
- return AnimationEffect::kPhaseBefore;
+ return Timing::kPhaseBefore;
}
double active_after_boundary_time = std::max(
std::min(specified.start_delay + active_duration, end_time), 0.0);
if (local_time > active_after_boundary_time ||
(local_time == active_after_boundary_time &&
direction == AnimationEffect::AnimationDirection::kForwards)) {
- return AnimationEffect::kPhaseAfter;
+ return Timing::kPhaseAfter;
}
- return AnimationEffect::kPhaseActive;
+ return Timing::kPhaseActive;
}
+// https://drafts.csswg.org/web-animations/#calculating-the-active-time
static inline double CalculateActiveTime(double active_duration,
Timing::FillMode fill_mode,
double local_time,
- AnimationEffect::Phase phase,
+ Timing::Phase phase,
const Timing& specified) {
DCHECK_GE(active_duration, 0);
switch (phase) {
- case AnimationEffect::kPhaseBefore:
+ case Timing::kPhaseBefore:
if (fill_mode == Timing::FillMode::BACKWARDS ||
fill_mode == Timing::FillMode::BOTH)
return std::max(local_time - specified.start_delay, 0.0);
return NullValue();
- case AnimationEffect::kPhaseActive:
+ case Timing::kPhaseActive:
return local_time - specified.start_delay;
- case AnimationEffect::kPhaseAfter:
+ case Timing::kPhaseAfter:
if (fill_mode == Timing::FillMode::FORWARDS ||
fill_mode == Timing::FillMode::BOTH) {
return std::max(
0.0, std::min(active_duration, local_time - specified.start_delay));
}
return NullValue();
- case AnimationEffect::kPhaseNone:
+ case Timing::kPhaseNone:
DCHECK(IsNull(local_time));
return NullValue();
default:
@@ -121,73 +127,10 @@ static inline double CalculateActiveTime(double active_duration,
}
}
-static inline double CalculateOffsetActiveTime(double active_duration,
- double active_time,
- double start_offset) {
- DCHECK_GE(active_duration, 0);
- DCHECK_GE(start_offset, 0);
-
- if (IsNull(active_time))
- return NullValue();
-
- DCHECK(active_time >= 0 &&
- LessThanOrEqualToWithinEpsilon(active_time, active_duration));
-
- if (!std::isfinite(active_time))
- return std::numeric_limits<double>::infinity();
-
- return active_time + start_offset;
-}
-
-static inline bool EndsOnIterationBoundary(double iteration_count,
- double iteration_start) {
- DCHECK(std::isfinite(iteration_count));
- return !fmod(iteration_count + iteration_start, 1);
-}
-
-// TODO(crbug.com/630915): Align this function with current Web Animations spec
-// text.
-static inline double CalculateIterationTime(double iteration_duration,
- double repeated_duration,
- double offset_active_time,
- double start_offset,
- AnimationEffect::Phase phase,
- const Timing& specified) {
- DCHECK_GT(iteration_duration, 0);
- DCHECK_EQ(repeated_duration,
- MultiplyZeroAlwaysGivesZero(iteration_duration,
- specified.iteration_count));
-
- if (IsNull(offset_active_time))
- return NullValue();
-
- DCHECK_GE(offset_active_time, 0);
- DCHECK(LessThanOrEqualToWithinEpsilon(offset_active_time,
- repeated_duration + start_offset));
-
- if (!std::isfinite(offset_active_time) ||
- (offset_active_time - start_offset == repeated_duration &&
- specified.iteration_count &&
- EndsOnIterationBoundary(specified.iteration_count,
- specified.iteration_start)))
- return iteration_duration;
-
- DCHECK(std::isfinite(offset_active_time));
- double iteration_time = fmod(offset_active_time, iteration_duration);
-
- // This implements step 3 of
- // https://drafts.csswg.org/web-animations/#calculating-the-simple-iteration-progress
- if (iteration_time == 0 && phase == AnimationEffect::kPhaseAfter &&
- repeated_duration != 0 && offset_active_time != 0)
- return iteration_duration;
-
- return iteration_time;
-}
-
// Calculates the overall progress, which describes the number of iterations
// that have completed (including partial iterations).
// https://drafts.csswg.org/web-animations/#calculating-the-overall-progress
-static inline double CalculateOverallProgress(AnimationEffect::Phase phase,
+static inline double CalculateOverallProgress(Timing::Phase phase,
double active_time,
double iteration_duration,
double iteration_count,
@@ -199,7 +142,7 @@ static inline double CalculateOverallProgress(AnimationEffect::Phase phase,
// 2. Calculate an initial value for overall progress.
double overall_progress = 0;
if (IsWithinEpsilon(iteration_duration, 0)) {
- if (phase != AnimationEffect::kPhaseBefore)
+ if (phase != Timing::kPhaseBefore)
overall_progress = iteration_count;
} else {
overall_progress = active_time / iteration_duration;
@@ -214,13 +157,12 @@ static inline double CalculateOverallProgress(AnimationEffect::Phase phase,
// effect.
// https://drafts.csswg.org/web-animations/#calculating-the-simple-iteration
// -progress
-static inline double CalculateSimpleIterationProgress(
- AnimationEffect::Phase phase,
- double overall_progress,
- double iteration_start,
- double active_time,
- double active_duration,
- double iteration_count) {
+static inline double CalculateSimpleIterationProgress(Timing::Phase phase,
+ double overall_progress,
+ double iteration_start,
+ double active_time,
+ double active_duration,
+ double iteration_count) {
// 1. If the overall progress is unresolved, return unresolved.
if (IsNull(overall_progress))
return NullValue();
@@ -239,8 +181,7 @@ static inline double CalculateSimpleIterationProgress(
// * the iteration count is not equal to zero.
// let the simple iteration progress be 1.0.
if (IsWithinEpsilon(simple_iteration_progress, 0.0) &&
- (phase == AnimationEffect::kPhaseActive ||
- phase == AnimationEffect::kPhaseAfter) &&
+ (phase == Timing::kPhaseActive || phase == Timing::kPhaseAfter) &&
IsWithinEpsilon(active_time, active_duration) &&
!IsWithinEpsilon(iteration_count, 0.0)) {
simple_iteration_progress = 1.0;
@@ -252,7 +193,7 @@ static inline double CalculateSimpleIterationProgress(
// https://drafts.csswg.org/web-animations/#calculating-the-current-iteration
static inline double CalculateCurrentIteration(
- AnimationEffect::Phase phase,
+ Timing::Phase phase,
double active_time,
double iteration_count,
double overall_progress,
@@ -263,7 +204,7 @@ static inline double CalculateCurrentIteration(
// 2. If the animation effect is in the after phase and the iteration count
// is infinity, return infinity.
- if (phase == AnimationEffect::kPhaseAfter && std::isinf(iteration_count)) {
+ if (phase == Timing::kPhaseAfter && std::isinf(iteration_count)) {
return std::numeric_limits<double>::infinity();
}
@@ -323,7 +264,7 @@ static inline double CalculateDirectedProgress(
// https://drafts.csswg.org/web-animations/#calculating-the-transformed-progress
static inline double CalculateTransformedProgress(
- AnimationEffect::Phase phase,
+ Timing::Phase phase,
double directed_progress,
double iteration_duration,
bool is_current_direction_forward,
@@ -334,16 +275,15 @@ static inline double CalculateTransformedProgress(
// Set the before flag to indicate if at the leading edge of an iteration.
// This is used to determine if the left or right limit should be used if at a
// discontinuity in the timing function.
- bool before = is_current_direction_forward
- ? phase == AnimationEffect::kPhaseBefore
- : phase == AnimationEffect::kPhaseAfter;
+ bool before = is_current_direction_forward ? phase == Timing::kPhaseBefore
+ : phase == Timing::kPhaseAfter;
TimingFunction::LimitDirection limit_direction =
before ? TimingFunction::LimitDirection::LEFT
: TimingFunction::LimitDirection::RIGHT;
// Snap boundaries to correctly render step timing functions at 0 and 1.
// (crbug.com/949373)
- if (phase == AnimationEffect::kPhaseAfter) {
+ if (phase == Timing::kPhaseAfter) {
if (is_current_direction_forward && IsWithinEpsilon(directed_progress, 1)) {
directed_progress = 1;
} else if (!is_current_direction_forward &&
@@ -354,8 +294,72 @@ static inline double CalculateTransformedProgress(
// Return the result of evaluating the animation effect’s timing function
// passing directed progress as the input progress value.
- return timing_function->Evaluate(directed_progress, limit_direction,
- AccuracyForDuration(iteration_duration));
+ return timing_function->Evaluate(directed_progress, limit_direction);
+}
+
+// Offsets the active time by how far into the animation we start (i.e. the
+// product of the iteration start and iteration duration). This is not part of
+// the Web Animations spec; it is used for calculating the time until the next
+// iteration to optimize scheduling.
+static inline double CalculateOffsetActiveTime(double active_duration,
+ double active_time,
+ double start_offset) {
+ DCHECK_GE(active_duration, 0);
+ DCHECK_GE(start_offset, 0);
+
+ if (IsNull(active_time))
+ return NullValue();
+
+ DCHECK(active_time >= 0 &&
+ LessThanOrEqualToWithinEpsilon(active_time, active_duration));
+
+ if (!std::isfinite(active_time))
+ return std::numeric_limits<double>::infinity();
+
+ return active_time + start_offset;
+}
+
+// Maps the offset active time into 'iteration time space'[0], aka the offset
+// into the current iteration. This is not part of the Web Animations spec (note
+// that the section linked below is non-normative); it is used for calculating
+// the time until the next iteration to optimize scheduling.
+//
+// [0] https://drafts.csswg.org/web-animations-1/#iteration-time-space
+static inline double CalculateIterationTime(double iteration_duration,
+ double active_duration,
+ double offset_active_time,
+ double start_offset,
+ Timing::Phase phase,
+ const Timing& specified) {
+ DCHECK_GT(iteration_duration, 0);
+ DCHECK_EQ(active_duration,
+ MultiplyZeroAlwaysGivesZero(iteration_duration,
+ specified.iteration_count));
+
+ if (IsNull(offset_active_time))
+ return NullValue();
+
+ DCHECK_GE(offset_active_time, 0);
+ DCHECK(LessThanOrEqualToWithinEpsilon(offset_active_time,
+ active_duration + start_offset));
+
+ if (!std::isfinite(offset_active_time) ||
+ (offset_active_time - start_offset == active_duration &&
+ specified.iteration_count &&
+ EndsOnIterationBoundary(specified.iteration_count,
+ specified.iteration_start)))
+ return iteration_duration;
+
+ DCHECK(std::isfinite(offset_active_time));
+ double iteration_time = fmod(offset_active_time, iteration_duration);
+
+ // This implements step 3 of
+ // https://drafts.csswg.org/web-animations/#calculating-the-simple-iteration-progress
+ if (iteration_time == 0 && phase == Timing::kPhaseAfter &&
+ active_duration != 0 && offset_active_time != 0)
+ return iteration_duration;
+
+ return iteration_time;
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/animation/timing_calculations_test.cc b/chromium/third_party/blink/renderer/core/animation/timing_calculations_test.cc
index 9a7f297f45d..7af7add93b0 100644
--- a/chromium/third_party/blink/renderer/core/animation/timing_calculations_test.cc
+++ b/chromium/third_party/blink/renderer/core/animation/timing_calculations_test.cc
@@ -43,40 +43,37 @@ TEST(AnimationTimingCalculationsTest, ActiveTime) {
// Before Phase
timing.start_delay = 10;
- EXPECT_TRUE(
- IsNull(CalculateActiveTime(20, Timing::FillMode::FORWARDS, 0,
- AnimationEffect::kPhaseBefore, timing)));
- EXPECT_TRUE(IsNull(CalculateActiveTime(
- 20, Timing::FillMode::NONE, 0, AnimationEffect::kPhaseBefore, timing)));
+ EXPECT_TRUE(IsNull(CalculateActiveTime(20, Timing::FillMode::FORWARDS, 0,
+ Timing::kPhaseBefore, timing)));
+ EXPECT_TRUE(IsNull(CalculateActiveTime(20, Timing::FillMode::NONE, 0,
+ Timing::kPhaseBefore, timing)));
EXPECT_EQ(0, CalculateActiveTime(20, Timing::FillMode::BACKWARDS, 0,
- AnimationEffect::kPhaseBefore, timing));
+ Timing::kPhaseBefore, timing));
EXPECT_EQ(0, CalculateActiveTime(20, Timing::FillMode::BOTH, 0,
- AnimationEffect::kPhaseBefore, timing));
+ Timing::kPhaseBefore, timing));
timing.start_delay = -10;
EXPECT_EQ(5, CalculateActiveTime(20, Timing::FillMode::BACKWARDS, -5,
- AnimationEffect::kPhaseBefore, timing));
+ Timing::kPhaseBefore, timing));
// Active Phase
timing.start_delay = 10;
EXPECT_EQ(5, CalculateActiveTime(20, Timing::FillMode::FORWARDS, 15,
- AnimationEffect::kPhaseActive, timing));
+ Timing::kPhaseActive, timing));
// After Phase
timing.start_delay = 10;
EXPECT_EQ(21, CalculateActiveTime(21, Timing::FillMode::FORWARDS, 45,
- AnimationEffect::kPhaseAfter, timing));
+ Timing::kPhaseAfter, timing));
EXPECT_EQ(21, CalculateActiveTime(21, Timing::FillMode::BOTH, 45,
- AnimationEffect::kPhaseAfter, timing));
- EXPECT_TRUE(
- IsNull(CalculateActiveTime(21, Timing::FillMode::BACKWARDS, 45,
- AnimationEffect::kPhaseAfter, timing)));
- EXPECT_TRUE(IsNull(CalculateActiveTime(
- 21, Timing::FillMode::NONE, 45, AnimationEffect::kPhaseAfter, timing)));
+ Timing::kPhaseAfter, timing));
+ EXPECT_TRUE(IsNull(CalculateActiveTime(21, Timing::FillMode::BACKWARDS, 45,
+ Timing::kPhaseAfter, timing)));
+ EXPECT_TRUE(IsNull(CalculateActiveTime(21, Timing::FillMode::NONE, 45,
+ Timing::kPhaseAfter, timing)));
// None
- EXPECT_TRUE(
- IsNull(CalculateActiveTime(32, Timing::FillMode::NONE, NullValue(),
- AnimationEffect::kPhaseNone, timing)));
+ EXPECT_TRUE(IsNull(CalculateActiveTime(
+ 32, Timing::FillMode::NONE, NullValue(), Timing::kPhaseNone, timing)));
}
TEST(AnimationTimingCalculationsTest, OffsetActiveTime) {
@@ -104,70 +101,70 @@ TEST(AnimationTimingCalculationsTest, IterationTime) {
Timing timing;
// calculateIterationTime(
- // iterationDuration, repeatedDuration, scaledActiveTime, startOffset,
+ // iterationDuration, activeDuration, scaledActiveTime, startOffset,
// phase, timing)
// if the scaled active time is null
- EXPECT_TRUE(IsNull(CalculateIterationTime(
- 1, 1, NullValue(), 1, AnimationEffect::kPhaseActive, timing)));
+ EXPECT_TRUE(IsNull(CalculateIterationTime(1, 1, NullValue(), 1,
+ Timing::kPhaseActive, timing)));
// if (complex-conditions)...
- EXPECT_EQ(12, CalculateIterationTime(12, 12, 12, 0,
- AnimationEffect::kPhaseActive, timing));
+ EXPECT_EQ(
+ 12, CalculateIterationTime(12, 12, 12, 0, Timing::kPhaseActive, timing));
// otherwise
timing.iteration_count = 10;
- EXPECT_EQ(5, CalculateIterationTime(10, 100, 25, 4,
- AnimationEffect::kPhaseActive, timing));
- EXPECT_EQ(7, CalculateIterationTime(11, 110, 29, 1,
- AnimationEffect::kPhaseActive, timing));
+ EXPECT_EQ(
+ 5, CalculateIterationTime(10, 100, 25, 4, Timing::kPhaseActive, timing));
+ EXPECT_EQ(
+ 7, CalculateIterationTime(11, 110, 29, 1, Timing::kPhaseActive, timing));
timing.iteration_start = 1.1;
- EXPECT_EQ(8, CalculateIterationTime(12, 120, 20, 7,
- AnimationEffect::kPhaseActive, timing));
+ EXPECT_EQ(
+ 8, CalculateIterationTime(12, 120, 20, 7, Timing::kPhaseActive, timing));
- // Edge case for offset_active_time being within epsilon of (repeated_duration
+ // Edge case for offset_active_time being within epsilon of (active_duration
// + start_offset). https://crbug.com/962138
timing.iteration_count = 1;
const double offset_active_time = 1.3435713716800004;
const double iteration_duration = 1.3435713716800002;
- const double repeated_duration = 1.3435713716800002;
+ const double active_duration = 1.3435713716800002;
EXPECT_NEAR(2.22045e-16,
- CalculateIterationTime(iteration_duration, repeated_duration,
+ CalculateIterationTime(iteration_duration, active_duration,
offset_active_time, 0,
- AnimationEffect::kPhaseActive, timing),
+ Timing::kPhaseActive, timing),
std::numeric_limits<float>::epsilon());
}
TEST(AnimationTimingCalculationsTest, OverallProgress) {
// If the active time is null.
- EXPECT_TRUE(IsNull(CalculateOverallProgress(AnimationEffect::kPhaseAfter,
+ EXPECT_TRUE(IsNull(CalculateOverallProgress(Timing::kPhaseAfter,
/*active_time=*/NullValue(),
/*iteration_duration=*/1.0,
/*iteration_count=*/1.0,
/*iteration_start=*/1.0)));
// If iteration duration is zero, calculate progress based on iteration count.
- EXPECT_EQ(3, CalculateOverallProgress(AnimationEffect::kPhaseActive,
+ EXPECT_EQ(3, CalculateOverallProgress(Timing::kPhaseActive,
/*active_time=*/3.0,
/*iteration_duration=*/0.0,
/*iteration_count=*/3.0,
/*iteration_start=*/0.0));
// ...unless in before phase, in which case progress is zero.
- EXPECT_EQ(0, CalculateOverallProgress(AnimationEffect::kPhaseBefore,
+ EXPECT_EQ(0, CalculateOverallProgress(Timing::kPhaseBefore,
/*active_time=*/3.0,
/*iteration_duration=*/0.0,
/*iteration_count=*/3.0,
/*iteration_start=*/0.0));
// Edge case for duration being within Epsilon of zero.
// crbug.com/954558
- EXPECT_EQ(1, CalculateOverallProgress(AnimationEffect::kPhaseActive,
+ EXPECT_EQ(1, CalculateOverallProgress(Timing::kPhaseActive,
/*active_time=*/3.0,
/*iteration_duration=*/1e-18,
/*iteration_count=*/1.0,
/*iteration_start=*/0.0));
// Otherwise.
- EXPECT_EQ(3.0, CalculateOverallProgress(AnimationEffect::kPhaseAfter,
+ EXPECT_EQ(3.0, CalculateOverallProgress(Timing::kPhaseAfter,
/*active_time=*/2.5,
/*iteration_duration=*/1.0,
/*iteration_count=*/0.0,
@@ -177,7 +174,7 @@ TEST(AnimationTimingCalculationsTest, OverallProgress) {
TEST(AnimationTimingCalculationsTest, CalculateSimpleIterationProgress) {
// If the overall progress is null.
EXPECT_TRUE(
- IsNull(CalculateSimpleIterationProgress(AnimationEffect::kPhaseAfter,
+ IsNull(CalculateSimpleIterationProgress(Timing::kPhaseAfter,
/*overall_progress=*/NullValue(),
/*iteration_start=*/1.0,
/*active_time=*/NullValue(),
@@ -186,7 +183,7 @@ TEST(AnimationTimingCalculationsTest, CalculateSimpleIterationProgress) {
// If the overall progress is infinite.
const double inf = std::numeric_limits<double>::infinity();
- EXPECT_EQ(0.5, CalculateSimpleIterationProgress(AnimationEffect::kPhaseAfter,
+ EXPECT_EQ(0.5, CalculateSimpleIterationProgress(Timing::kPhaseAfter,
/*overall_progress=*/inf,
/*iteration_start=*/1.5,
/*active_time=*/0.0,
@@ -194,7 +191,7 @@ TEST(AnimationTimingCalculationsTest, CalculateSimpleIterationProgress) {
/*iteration_count=*/inf));
// Precisely on an iteration boundary.
- EXPECT_EQ(1.0, CalculateSimpleIterationProgress(AnimationEffect::kPhaseAfter,
+ EXPECT_EQ(1.0, CalculateSimpleIterationProgress(Timing::kPhaseAfter,
/*overall_progress=*/3.0,
/*iteration_start=*/0.0,
/*active_time=*/3.0,
@@ -202,7 +199,7 @@ TEST(AnimationTimingCalculationsTest, CalculateSimpleIterationProgress) {
/*iteration_count=*/3.0));
// Otherwise.
- EXPECT_EQ(0.5, CalculateSimpleIterationProgress(AnimationEffect::kPhaseAfter,
+ EXPECT_EQ(0.5, CalculateSimpleIterationProgress(Timing::kPhaseAfter,
/*overall_progress=*/2.5,
/*iteration_start=*/0.0,
/*active_time=*/2.5,
@@ -213,7 +210,7 @@ TEST(AnimationTimingCalculationsTest, CalculateSimpleIterationProgress) {
TEST(AnimationTimingCalculationsTest, CurrentIteration) {
// If the active time is null.
EXPECT_TRUE(
- IsNull(CalculateCurrentIteration(AnimationEffect::kPhaseAfter,
+ IsNull(CalculateCurrentIteration(Timing::kPhaseAfter,
/*active_time=*/NullValue(),
/*iteration_count=*/1.0,
/*overall_progress=*/NullValue(),
@@ -221,7 +218,7 @@ TEST(AnimationTimingCalculationsTest, CurrentIteration) {
// If the iteration count is infinite.
const double inf = std::numeric_limits<double>::infinity();
- EXPECT_EQ(inf, CalculateCurrentIteration(AnimationEffect::kPhaseAfter,
+ EXPECT_EQ(inf, CalculateCurrentIteration(Timing::kPhaseAfter,
/*active_time=*/1.0,
/*iteration_count=*/inf,
/*overall_progress=*/inf,
@@ -229,7 +226,7 @@ TEST(AnimationTimingCalculationsTest, CurrentIteration) {
// Hold the endpoint of the final iteration of ending precisely on an
// iteration boundary.
- EXPECT_EQ(2, CalculateCurrentIteration(AnimationEffect::kPhaseAfter,
+ EXPECT_EQ(2, CalculateCurrentIteration(Timing::kPhaseAfter,
/*active_time=*/3.0,
/*iteration_count=*/3.0,
/*overall_progress=*/3.0,
@@ -237,14 +234,14 @@ TEST(AnimationTimingCalculationsTest, CurrentIteration) {
// Edge case for zero-duration animation.
// crbug.com/954558
- EXPECT_EQ(0, CalculateCurrentIteration(AnimationEffect::kPhaseAfter,
+ EXPECT_EQ(0, CalculateCurrentIteration(Timing::kPhaseAfter,
/*active_time=*/0.0,
/*iteration_count=*/1.0,
/*overall_progress=*/0.0,
/*simple_iteration_progress=*/1.0));
// Otherwise.
- EXPECT_EQ(2, CalculateCurrentIteration(AnimationEffect::kPhaseAfter,
+ EXPECT_EQ(2, CalculateCurrentIteration(Timing::kPhaseAfter,
/*active_time=*/2.5,
/*iteration_count=*/0.0,
/*overall_progress=*/2.5,
@@ -328,57 +325,53 @@ TEST(AnimationTimingCalculationsTest, TransformedProgress) {
// directed_progress is null.
EXPECT_TRUE(IsNull(CalculateTransformedProgress(
- AnimationEffect::kPhaseActive, NullValue(), 1, true, timing_function)));
+ Timing::kPhaseActive, NullValue(), 1, true, timing_function)));
// At step boundaries.
// Forward direction.
- EXPECT_EQ(0, CalculateTransformedProgress(AnimationEffect::kPhaseBefore, 0, 1,
- true, timing_function));
- EXPECT_EQ(0, CalculateTransformedProgress(AnimationEffect::kPhaseBefore, 0.25,
- 1, true, timing_function));
- EXPECT_EQ(0.25, CalculateTransformedProgress(AnimationEffect::kPhaseAfter,
- 0.25, 1, true, timing_function));
- EXPECT_EQ(0.25, CalculateTransformedProgress(AnimationEffect::kPhaseBefore,
- 0.5, 1, true, timing_function));
- EXPECT_EQ(0.5, CalculateTransformedProgress(AnimationEffect::kPhaseAfter, 0.5,
- 1, true, timing_function));
- EXPECT_EQ(0.5, CalculateTransformedProgress(AnimationEffect::kPhaseBefore,
- 0.75, 1, true, timing_function));
- EXPECT_EQ(0.75, CalculateTransformedProgress(AnimationEffect::kPhaseAfter,
- 0.75, 1, true, timing_function));
- EXPECT_EQ(0.75, CalculateTransformedProgress(AnimationEffect::kPhaseBefore, 1,
- 1, true, timing_function));
- EXPECT_EQ(1, CalculateTransformedProgress(AnimationEffect::kPhaseAfter, 1, 1,
- true, timing_function));
+ EXPECT_EQ(0, CalculateTransformedProgress(Timing::kPhaseBefore, 0, 1, true,
+ timing_function));
+ EXPECT_EQ(0, CalculateTransformedProgress(Timing::kPhaseBefore, 0.25, 1, true,
+ timing_function));
+ EXPECT_EQ(0.25, CalculateTransformedProgress(Timing::kPhaseAfter, 0.25, 1,
+ true, timing_function));
+ EXPECT_EQ(0.25, CalculateTransformedProgress(Timing::kPhaseBefore, 0.5, 1,
+ true, timing_function));
+ EXPECT_EQ(0.5, CalculateTransformedProgress(Timing::kPhaseAfter, 0.5, 1, true,
+ timing_function));
+ EXPECT_EQ(0.5, CalculateTransformedProgress(Timing::kPhaseBefore, 0.75, 1,
+ true, timing_function));
+ EXPECT_EQ(0.75, CalculateTransformedProgress(Timing::kPhaseAfter, 0.75, 1,
+ true, timing_function));
+ EXPECT_EQ(0.75, CalculateTransformedProgress(Timing::kPhaseBefore, 1, 1, true,
+ timing_function));
+ EXPECT_EQ(1, CalculateTransformedProgress(Timing::kPhaseAfter, 1, 1, true,
+ timing_function));
// Reverse direction.
- EXPECT_EQ(1, CalculateTransformedProgress(AnimationEffect::kPhaseBefore, 1, 1,
- false, timing_function));
- EXPECT_EQ(0.75, CalculateTransformedProgress(AnimationEffect::kPhaseAfter, 1,
- 1, false, timing_function));
- EXPECT_EQ(0.75,
- CalculateTransformedProgress(AnimationEffect::kPhaseBefore, 0.75, 1,
- false, timing_function));
- EXPECT_EQ(0.5, CalculateTransformedProgress(AnimationEffect::kPhaseAfter,
- 0.75, 1, false, timing_function));
- EXPECT_EQ(0.5, CalculateTransformedProgress(AnimationEffect::kPhaseBefore,
- 0.5, 1, false, timing_function));
- EXPECT_EQ(0.25, CalculateTransformedProgress(AnimationEffect::kPhaseAfter,
- 0.5, 1, false, timing_function));
- EXPECT_EQ(0.25,
- CalculateTransformedProgress(AnimationEffect::kPhaseBefore, 0.25, 1,
- false, timing_function));
- EXPECT_EQ(0, CalculateTransformedProgress(AnimationEffect::kPhaseAfter, 0.25,
- 1, false, timing_function));
+ EXPECT_EQ(1, CalculateTransformedProgress(Timing::kPhaseBefore, 1, 1, false,
+ timing_function));
+ EXPECT_EQ(0.75, CalculateTransformedProgress(Timing::kPhaseAfter, 1, 1, false,
+ timing_function));
+ EXPECT_EQ(0.75, CalculateTransformedProgress(Timing::kPhaseBefore, 0.75, 1,
+ false, timing_function));
+ EXPECT_EQ(0.5, CalculateTransformedProgress(Timing::kPhaseAfter, 0.75, 1,
+ false, timing_function));
+ EXPECT_EQ(0.5, CalculateTransformedProgress(Timing::kPhaseBefore, 0.5, 1,
+ false, timing_function));
+ EXPECT_EQ(0.25, CalculateTransformedProgress(Timing::kPhaseAfter, 0.5, 1,
+ false, timing_function));
+ EXPECT_EQ(0.25, CalculateTransformedProgress(Timing::kPhaseBefore, 0.25, 1,
+ false, timing_function));
+ EXPECT_EQ(0, CalculateTransformedProgress(Timing::kPhaseAfter, 0.25, 1, false,
+ timing_function));
// Edges cases
- EXPECT_EQ(
- 1, CalculateTransformedProgress(AnimationEffect::kPhaseAfter, 1 - 1e-16,
- 1, true, timing_function));
+ EXPECT_EQ(1, CalculateTransformedProgress(Timing::kPhaseAfter, 1 - 1e-16, 1,
+ true, timing_function));
scoped_refptr<TimingFunction> step_start_timing_function =
StepsTimingFunction::Create(4, StepsTimingFunction::StepPosition::START);
- EXPECT_EQ(0,
- CalculateTransformedProgress(AnimationEffect::kPhaseAfter, 1e-16, 1,
- false, step_start_timing_function));
+ EXPECT_EQ(0, CalculateTransformedProgress(Timing::kPhaseAfter, 1e-16, 1,
+ false, step_start_timing_function));
}
} // namespace blink
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 92a29c8f80d..13ee259b599 100644
--- a/chromium/third_party/blink/renderer/core/animation/timing_input.cc
+++ b/chromium/third_party/blink/renderer/core/animation/timing_input.cc
@@ -62,7 +62,7 @@ Timing TimingInput::Convert(
Document* document,
ExceptionState& exception_state) {
if (options.IsNull()) {
- return Timing::Defaults();
+ return Timing();
}
if (options.IsKeyframeEffectOptions()) {
@@ -86,9 +86,8 @@ Timing TimingInput::Convert(
const UnrestrictedDoubleOrKeyframeAnimationOptions& options,
Document* document,
ExceptionState& exception_state) {
- if (options.IsNull()) {
- return Timing::Defaults();
- }
+ if (options.IsNull())
+ return Timing();
if (options.IsKeyframeAnimationOptions()) {
return ConvertEffectTiming(options.GetAsKeyframeAnimationOptions(),
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 b9a6a329d7f..0df7f407b0e 100644
--- a/chromium/third_party/blink/renderer/core/animation/timing_input.h
+++ b/chromium/third_party/blink/renderer/core/animation/timing_input.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/animation/timing.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/animation/typed_interpolation_value.h b/chromium/third_party/blink/renderer/core/animation/typed_interpolation_value.h
index 389df39c2c8..32b6a404bcb 100644
--- a/chromium/third_party/blink/renderer/core/animation/typed_interpolation_value.h
+++ b/chromium/third_party/blink/renderer/core/animation/typed_interpolation_value.h
@@ -10,7 +10,7 @@
#include "base/memory/ptr_util.h"
#include "third_party/blink/renderer/core/animation/interpolation_value.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/animation/underlying_value_owner.h b/chromium/third_party/blink/renderer/core/animation/underlying_value_owner.h
index 111aa473dbb..7ead3f8329a 100644
--- a/chromium/third_party/blink/renderer/core/animation/underlying_value_owner.h
+++ b/chromium/third_party/blink/renderer/core/animation/underlying_value_owner.h
@@ -10,7 +10,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/animation/typed_interpolation_value.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/clipboard/clipboard_utilities.cc b/chromium/third_party/blink/renderer/core/clipboard/clipboard_utilities.cc
index a2eec822fc0..b7628cf5dcd 100644
--- a/chromium/third_party/blink/renderer/core/clipboard/clipboard_utilities.cc
+++ b/chromium/third_party/blink/renderer/core/clipboard/clipboard_utilities.cc
@@ -65,9 +65,15 @@ String ConvertURIListToURL(const String& uri_list) {
}
static String EscapeForHTML(const String& str) {
- std::string output =
- net::EscapeForHTML(StringUTF8Adaptor(str).AsStringPiece());
- return String(output.c_str());
+ // net::EscapeForHTML can work on 8-bit Latin-1 strings as well as 16-bit
+ // strings.
+ if (str.Is8Bit()) {
+ auto result = net::EscapeForHTML(
+ {reinterpret_cast<const char*>(str.Characters8()), str.length()});
+ return String(result.data(), result.size());
+ }
+ auto result = net::EscapeForHTML({str.Characters16(), str.length()});
+ return String(result.data(), result.size());
}
String URLToImageMarkup(const KURL& url, const String& title) {
diff --git a/chromium/third_party/blink/renderer/core/clipboard/clipboard_utilities_test.cc b/chromium/third_party/blink/renderer/core/clipboard/clipboard_utilities_test.cc
new file mode 100644
index 00000000000..a0338751287
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/clipboard/clipboard_utilities_test.cc
@@ -0,0 +1,46 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/clipboard/clipboard_utilities.h"
+
+#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/renderer/platform/weborigin/kurl.h"
+#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
+
+namespace blink {
+
+TEST(ClipboardUtilitiesTest, URLToImageMarkupNonASCII) {
+ // U+00E7 "Latin Small Letter C with Cedilla" is outside ASCII.
+ // It has the UTF-8 encoding 0xC3 0xA7, but Blink interprets 8-bit string
+ // literals as Latin-1 in most cases.
+ String markup_with_non_ascii =
+ URLToImageMarkup(KURL(NullURL(),
+ "http://test.example/fran\xe7"
+ "ais.png"),
+ "Fran\xe7"
+ "ais");
+ EXPECT_EQ(
+ "<img src=\"http://test.example/fran%C3%A7ais.png\" alt=\"Fran\xe7"
+ "ais\"/>",
+ markup_with_non_ascii);
+ EXPECT_EQ(
+ "<img src=\"http://test.example/fran%C3%A7ais.png\" alt=\"Fran\xc3\xa7"
+ "ais\"/>",
+ markup_with_non_ascii.Utf8());
+}
+
+TEST(ClipboardUtilitiesTest, URLToImageMarkupEmbeddedNull) {
+ // Null characters, though strange, should also work.
+ const char kURLWithNull[] = "http://test.example/\0.png";
+ const char kTitleWithNull[] = "\0";
+ const char kExpectedOutputWithNull[] =
+ "<img src=\"http://test.example/%00.png\" alt=\"\0\"/>";
+ EXPECT_EQ(
+ String(kExpectedOutputWithNull, sizeof(kExpectedOutputWithNull) - 1),
+ URLToImageMarkup(
+ KURL(NullURL(), String(kURLWithNull, sizeof(kURLWithNull) - 1)),
+ String(kTitleWithNull, sizeof(kTitleWithNull) - 1)));
+}
+
+} // namespace blink
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 ff792028520..0b4a308f9b5 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
@@ -144,7 +144,8 @@ File* DataObjectItem::GetAsFile() const {
data->AppendBytes(png_data.data(), png_data.size());
const uint64_t length = data->length();
auto blob = BlobDataHandle::Create(std::move(data), length);
- return File::Create("image.png", CurrentTimeMS(), std::move(blob));
+ return File::Create("image.png", base::Time::Now().ToDoubleT() * 1000.0,
+ std::move(blob));
}
}
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 0769fa7377d..b7160ec51b2 100644
--- a/chromium/third_party/blink/renderer/core/clipboard/data_transfer.cc
+++ b/chromium/third_party/blink/renderer/core/clipboard/data_transfer.cc
@@ -101,10 +101,9 @@ class DraggedNodeImageBuilder {
// object contains transparency and there are other elements in the same
// stacking context which stacked below.
PaintLayer* layer = dragged_layout_object->EnclosingLayer();
- if (!layer->GetLayoutObject().StyleRef().IsStackingContext()) {
- layer =
- PaintLayerStackingNode::AncestorStackingContextNode(layer)->Layer();
- }
+ if (!layer->GetLayoutObject().StyleRef().IsStackingContext())
+ layer = layer->AncestorStackingContext();
+
IntRect absolute_bounding_box =
dragged_layout_object->AbsoluteBoundingBoxRectIncludingDescendants();
// TODO(chrishtr): consider using the root frame's visible rect instead
diff --git a/chromium/third_party/blink/renderer/core/clipboard/data_transfer.idl b/chromium/third_party/blink/renderer/core/clipboard/data_transfer.idl
index ef5113e1e61..96b269f04ec 100644
--- a/chromium/third_party/blink/renderer/core/clipboard/data_transfer.idl
+++ b/chromium/third_party/blink/renderer/core/clipboard/data_transfer.idl
@@ -29,7 +29,8 @@
// https://html.spec.whatwg.org/C/#the-datatransfer-interface
[
- Constructor
+ Constructor,
+ Exposed=Window
] interface DataTransfer {
attribute DOMString dropEffect;
attribute DOMString effectAllowed;
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 76e02205ed1..111da3f6f34 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
@@ -71,16 +71,13 @@ void DataTransferItem::getAsString(ScriptState* script_state,
if (!callback || item_->Kind() != DataObjectItem::kStringKind)
return;
- auto* v8persistent_callback = ToV8PersistentCallbackFunction(callback);
ExecutionContext* context = ExecutionContext::From(script_state);
- probe::AsyncTaskScheduled(context, "DataTransferItem.getAsString",
- v8persistent_callback);
+ probe::AsyncTaskScheduled(context, "DataTransferItem.getAsString", callback);
context->GetTaskRunner(TaskType::kUserInteraction)
->PostTask(FROM_HERE,
WTF::Bind(&DataTransferItem::RunGetAsStringTask,
WrapPersistent(this), WrapPersistent(context),
- WrapPersistent(v8persistent_callback),
- item_->GetAsString()));
+ WrapPersistent(callback), item_->GetAsString()));
}
File* DataTransferItem::getAsFile() const {
@@ -94,10 +91,9 @@ DataTransferItem::DataTransferItem(DataTransfer* data_transfer,
DataObjectItem* item)
: data_transfer_(data_transfer), item_(item) {}
-void DataTransferItem::RunGetAsStringTask(
- ExecutionContext* context,
- V8PersistentCallbackFunction<V8FunctionStringCallback>* callback,
- const String& data) {
+void DataTransferItem::RunGetAsStringTask(ExecutionContext* context,
+ V8FunctionStringCallback* callback,
+ const String& data) {
DCHECK(callback);
probe::AsyncTask async_task(context, callback);
if (context)
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 c930a457d80..230098ec500 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
@@ -64,10 +64,9 @@ class CORE_EXPORT DataTransferItem final : public ScriptWrappable {
void Trace(blink::Visitor*) override;
private:
- void RunGetAsStringTask(
- ExecutionContext*,
- V8PersistentCallbackFunction<V8FunctionStringCallback>*,
- const String& data);
+ void RunGetAsStringTask(ExecutionContext*,
+ V8FunctionStringCallback*,
+ const String& data);
Member<DataTransfer> data_transfer_;
Member<DataObjectItem> item_;
diff --git a/chromium/third_party/blink/renderer/core/clipboard/data_transfer_item.idl b/chromium/third_party/blink/renderer/core/clipboard/data_transfer_item.idl
index 5d9d4bac13f..3e163a8fad4 100644
--- a/chromium/third_party/blink/renderer/core/clipboard/data_transfer_item.idl
+++ b/chromium/third_party/blink/renderer/core/clipboard/data_transfer_item.idl
@@ -30,7 +30,9 @@
// https://html.spec.whatwg.org/C/#the-datatransferitem-interface
-interface DataTransferItem {
+[
+ Exposed=Window
+] interface DataTransferItem {
readonly attribute DOMString kind;
readonly attribute DOMString type;
[CallWith=ScriptState] void getAsString(FunctionStringCallback? callback);
diff --git a/chromium/third_party/blink/renderer/core/clipboard/data_transfer_item_list.idl b/chromium/third_party/blink/renderer/core/clipboard/data_transfer_item_list.idl
index 1b31f75cfa3..240358558fc 100644
--- a/chromium/third_party/blink/renderer/core/clipboard/data_transfer_item_list.idl
+++ b/chromium/third_party/blink/renderer/core/clipboard/data_transfer_item_list.idl
@@ -30,7 +30,9 @@
// https://html.spec.whatwg.org/C/#the-datatransferitemlist-interface
-interface DataTransferItemList {
+[
+ Exposed=Window
+] interface DataTransferItemList {
readonly attribute unsigned long length;
[ImplementedAs=item] getter DataTransferItem (unsigned long index);
[RaisesException] DataTransferItem? add(DOMString data, DOMString type);
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 c8f57fa6e07..ad2ab35078c 100644
--- a/chromium/third_party/blink/renderer/core/clipboard/system_clipboard.cc
+++ b/chromium/third_party/blink/renderer/core/clipboard/system_clipboard.cc
@@ -72,18 +72,17 @@ bool SystemClipboard::IsHTMLAvailable() {
uint64_t SystemClipboard::SequenceNumber() {
if (!IsValidBufferType(buffer_))
return 0;
-
uint64_t result = 0;
clipboard_->GetSequenceNumber(buffer_, &result);
return result;
}
Vector<String> SystemClipboard::ReadAvailableTypes() {
+ if (!IsValidBufferType(buffer_))
+ return {};
Vector<String> types;
- if (IsValidBufferType(buffer_)) {
- bool unused;
- clipboard_->ReadAvailableTypes(buffer_, &types, &unused);
- }
+ bool contains_filenames; // Unused argument.
+ clipboard_->ReadAvailableTypes(buffer_, &types, &contains_filenames);
return types;
}
@@ -152,9 +151,10 @@ String SystemClipboard::ReadRTF() {
}
SkBitmap SystemClipboard::ReadImage(mojom::ClipboardBuffer buffer) {
+ if (!IsValidBufferType(buffer))
+ return SkBitmap();
SkBitmap image;
- if (IsValidBufferType(buffer))
- clipboard_->ReadImage(buffer, &image);
+ clipboard_->ReadImage(buffer, &image);
return image;
}
diff --git a/chromium/third_party/blink/renderer/core/clipboard/system_clipboard.h b/chromium/third_party/blink/renderer/core/clipboard/system_clipboard.h
index 038ec507dc8..6b75bddff73 100644
--- a/chromium/third_party/blink/renderer/core/clipboard/system_clipboard.h
+++ b/chromium/third_party/blink/renderer/core/clipboard/system_clipboard.h
@@ -7,7 +7,7 @@
#include "third_party/blink/public/mojom/clipboard/clipboard.mojom-blink.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
diff --git a/chromium/third_party/blink/renderer/core/content_capture/BUILD.gn b/chromium/third_party/blink/renderer/core/content_capture/BUILD.gn
index 1282f765ea4..5a45b0620bd 100644
--- a/chromium/third_party/blink/renderer/core/content_capture/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/content_capture/BUILD.gn
@@ -12,8 +12,6 @@ blink_core_sources("content_capture") {
"content_capture_task.h",
"content_capture_task_histogram_reporter.cc",
"content_capture_task_histogram_reporter.h",
- "content_holder.cc",
- "content_holder.h",
"sent_nodes.cc",
"sent_nodes.h",
"task_session.cc",
diff --git a/chromium/third_party/blink/renderer/core/content_capture/DEPS b/chromium/third_party/blink/renderer/core/content_capture/DEPS
index 01e64c0c118..c9bd3407b6c 100644
--- a/chromium/third_party/blink/renderer/core/content_capture/DEPS
+++ b/chromium/third_party/blink/renderer/core/content_capture/DEPS
@@ -1,6 +1,5 @@
include_rules = [
"+base/logging.h",
- "+cc/paint/node_holder.h",
- "+cc/paint/text_holder.h",
+ "+cc/paint/node_id.h",
"+cc/trees/layer_tree_host.h",
]
diff --git a/chromium/third_party/blink/renderer/core/content_capture/README.md b/chromium/third_party/blink/renderer/core/content_capture/README.md
index bb87b29c2bd..f22965328e3 100644
--- a/chromium/third_party/blink/renderer/core/content_capture/README.md
+++ b/chromium/third_party/blink/renderer/core/content_capture/README.md
@@ -5,24 +5,9 @@
This directory contains ContentCapture which is for capturing on-screen text
content and streaming it to a client.
-The implementation injects a cc::NodeHolder into cc::DrawTextBlobOp in paint
+The implementation injects a cc::NodeId into cc::DrawTextBlobOp in paint
stage, schedules a best-effort task to retrieve on-screen text content (using
-an r-tree to capture all cc::NodeHolder intersecting the screen), and streams
+an r-tree to capture all cc::NodeId intersecting the screen), and streams
the text out through ContentCaptureClient interface. The ContentCaptureTask is
a best-effort task in the idle queue and could be paused if there are
higher-priority tasks.
-
-There are two ways to associate cc::NodeHolder with Node which are being
-compared. One of these approaches will be removed once performance data is
-available.
-
- 1. NodeHolder::Type::kID where the ID from DOMNodeIds::IdForNode() is used to
-identify nodes.
- 2. NodeHolder::Type::kTextHolder which uses ContentCapture’s implementation of
-cc::TextHolder to identify the node. Since the NodeHolder is captured and sent
-out in a separate task, the Node could be removed. To avoid using removed
-Nodes, a weak pointer to Node is implemented. This weak pointer will be reset
-when the Node associated with the LayoutText is destroyed. Though a Node can be
-associated with multiple LayoutObjects, only the main LayoutObject has the
-pointer back to Node, so it isn’t a problem to use the removing of LayoutText
-to reset the pointer to the Node.
diff --git a/chromium/third_party/blink/renderer/core/content_capture/content_capture_manager.cc b/chromium/third_party/blink/renderer/core/content_capture/content_capture_manager.cc
index 830d92fef50..c0e166ff3a2 100644
--- a/chromium/third_party/blink/renderer/core/content_capture/content_capture_manager.cc
+++ b/chromium/third_party/blink/renderer/core/content_capture/content_capture_manager.cc
@@ -4,7 +4,6 @@
#include "third_party/blink/renderer/core/content_capture/content_capture_manager.h"
-#include "third_party/blink/renderer/core/content_capture/content_holder.h"
#include "third_party/blink/renderer/core/content_capture/sent_nodes.h"
#include "third_party/blink/renderer/core/dom/dom_node_ids.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
@@ -12,9 +11,8 @@
namespace blink {
-ContentCaptureManager::ContentCaptureManager(LocalFrame& local_frame_root,
- NodeHolder::Type type)
- : local_frame_root_(&local_frame_root), node_holder_type_(type) {
+ContentCaptureManager::ContentCaptureManager(LocalFrame& local_frame_root)
+ : local_frame_root_(&local_frame_root) {
DCHECK(local_frame_root.IsLocalRoot());
sent_nodes_ = MakeGarbageCollected<SentNodes>();
task_session_ = MakeGarbageCollected<TaskSession>(*sent_nodes_);
@@ -22,16 +20,14 @@ ContentCaptureManager::ContentCaptureManager(LocalFrame& local_frame_root,
ContentCaptureManager::~ContentCaptureManager() = default;
-NodeHolder ContentCaptureManager::GetNodeHolder(Node& node) {
+DOMNodeId ContentCaptureManager::GetNodeId(Node& node) {
if (first_node_holder_created_) {
ScheduleTask(ContentCaptureTask::ScheduleReason::kContentChange);
} else {
ScheduleTask(ContentCaptureTask::ScheduleReason::kFirstContentChange);
first_node_holder_created_ = true;
}
- if (node_holder_type_ == NodeHolder::Type::kID)
- return NodeHolder(DOMNodeIds::IdForNode(&node));
- return NodeHolder(base::MakeRefCounted<ContentHolder>(node));
+ return DOMNodeIds::IdForNode(&node);
}
void ContentCaptureManager::ScheduleTask(
@@ -48,20 +44,12 @@ ContentCaptureManager::CreateContentCaptureTask() {
*task_session_);
}
-void ContentCaptureManager::NotifyNodeDetached(const NodeHolder& node_holder) {
- task_session_->OnNodeDetached(node_holder);
+void ContentCaptureManager::NotifyNodeDetached(const Node& node) {
+ task_session_->OnNodeDetached(node);
}
-void ContentCaptureManager::OnLayoutTextWillBeDestroyed(
- NodeHolder node_holder) {
- DCHECK(!node_holder.is_empty);
- NotifyNodeDetached(node_holder);
- if (node_holder.type == NodeHolder::Type::kTextHolder) {
- ContentHolder* content_holder =
- static_cast<ContentHolder*>(node_holder.text_holder.get());
- if (content_holder)
- content_holder->OnNodeDetachedFromLayoutTree();
- }
+void ContentCaptureManager::OnLayoutTextWillBeDestroyed(const Node& node) {
+ NotifyNodeDetached(node);
ScheduleTask(ContentCaptureTask::ScheduleReason::kContentChange);
}
@@ -69,8 +57,8 @@ void ContentCaptureManager::OnScrollPositionChanged() {
ScheduleTask(ContentCaptureTask::ScheduleReason::kScrolling);
}
-void ContentCaptureManager::OnNodeTextChanged(const NodeHolder& node_holder) {
- task_session_->OnNodeChanged(node_holder);
+void ContentCaptureManager::OnNodeTextChanged(Node& node) {
+ task_session_->OnNodeChanged(node);
ScheduleTask(ContentCaptureTask::ScheduleReason::kContentChange);
}
diff --git a/chromium/third_party/blink/renderer/core/content_capture/content_capture_manager.h b/chromium/third_party/blink/renderer/core/content_capture/content_capture_manager.h
index fd8a0feadfd..d38c5a0544c 100644
--- a/chromium/third_party/blink/renderer/core/content_capture/content_capture_manager.h
+++ b/chromium/third_party/blink/renderer/core/content_capture/content_capture_manager.h
@@ -7,8 +7,8 @@
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/core/content_capture/content_capture_task.h"
-#include "third_party/blink/renderer/core/content_capture/content_holder.h"
#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/platform/graphics/dom_node_id.h"
namespace blink {
@@ -21,23 +21,23 @@ class SentNodes;
class CORE_EXPORT ContentCaptureManager
: public GarbageCollectedFinalized<ContentCaptureManager> {
public:
- ContentCaptureManager(LocalFrame& local_frame_root, NodeHolder::Type type);
+ explicit ContentCaptureManager(LocalFrame& local_frame_root);
virtual ~ContentCaptureManager();
// Creates and returns NodeHolder for the given |node|, and schedules
// ContentCaptureTask if it isn't already scheduled.
// Can't use const Node& for parameter, because |node| is passed to
// DOMNodeIds::IdForNode(Node*).
- NodeHolder GetNodeHolder(Node& node);
+ DOMNodeId GetNodeId(Node& node);
// Invokes when the |node_holder| asscociated LayoutText will be destroyed.
- void OnLayoutTextWillBeDestroyed(NodeHolder node_holder);
+ void OnLayoutTextWillBeDestroyed(const Node& node);
// Invokes when scroll position was changed.
void OnScrollPositionChanged();
// Invokes when text node content was changed.
- void OnNodeTextChanged(const NodeHolder& node_holder);
+ void OnNodeTextChanged(Node& node);
// Invokes when the local_frame_root shutdown.
void Shutdown();
@@ -53,16 +53,13 @@ class CORE_EXPORT ContentCaptureManager
TaskSession& GetTaskSessionForTesting() const { return *task_session_; }
private:
- void NotifyNodeDetached(const NodeHolder& node_holder);
+ void NotifyNodeDetached(const Node& node);
void ScheduleTask(ContentCaptureTask::ScheduleReason reason);
scoped_refptr<ContentCaptureTask> content_capture_idle_task_;
Member<LocalFrame> local_frame_root_;
- // Indicates the NodeHolder::Type should be used.
- NodeHolder::Type node_holder_type_;
-
// Indicates if the first NodeHolder is created.
bool first_node_holder_created_ = false;
diff --git a/chromium/third_party/blink/renderer/core/content_capture/content_capture_task.cc b/chromium/third_party/blink/renderer/core/content_capture/content_capture_task.cc
index ce7e3955c79..a6d0a07a93e 100644
--- a/chromium/third_party/blink/renderer/core/content_capture/content_capture_task.cc
+++ b/chromium/third_party/blink/renderer/core/content_capture/content_capture_task.cc
@@ -8,7 +8,6 @@
#include "cc/trees/layer_tree_host.h"
#include "third_party/blink/public/web/web_content_capture_client.h"
#include "third_party/blink/public/web/web_content_holder.h"
-#include "third_party/blink/renderer/core/content_capture/content_holder.h"
#include "third_party/blink/renderer/core/dom/dom_node_ids.h"
#include "third_party/blink/renderer/core/frame/local_frame_client.h"
#include "third_party/blink/renderer/core/layout/layout_text.h"
@@ -27,7 +26,7 @@ ContentCaptureTask::ContentCaptureTask(LocalFrame& local_frame_root,
->GetTaskTimingParameters(task_short_delay_, task_long_delay_);
// The histogram is all about time, just disable it if high resolution isn't
// supported.
- if (TimeTicks::IsHighResolution()) {
+ if (base::TimeTicks::IsHighResolution()) {
histogram_reporter_ =
base::MakeRefCounted<ContentCaptureTaskHistogramReporter>();
task_session_->SetSentNodeCountCallback(
@@ -44,7 +43,7 @@ void ContentCaptureTask::Shutdown() {
local_frame_root_ = nullptr;
}
-bool ContentCaptureTask::CaptureContent(std::vector<cc::NodeHolder>& data) {
+bool ContentCaptureTask::CaptureContent(Vector<cc::NodeId>& data) {
if (captured_content_for_testing_) {
data = captured_content_for_testing_.value();
return true;
@@ -53,8 +52,15 @@ bool ContentCaptureTask::CaptureContent(std::vector<cc::NodeHolder>& data) {
// lifecycle step so we need to early-out in many cases.
if (const auto* root_frame_view = local_frame_root_->View()) {
if (const auto* cc_layer = root_frame_view->RootCcLayer()) {
- if (auto* layer_tree_host = cc_layer->layer_tree_host())
- return layer_tree_host->CaptureContent(&data);
+ if (auto* layer_tree_host = cc_layer->layer_tree_host()) {
+ std::vector<cc::NodeId> content;
+ if (layer_tree_host->CaptureContent(&content)) {
+ for (auto c : content)
+ data.push_back(std::move(c));
+ return true;
+ }
+ return false;
+ }
}
}
return false;
@@ -62,13 +68,13 @@ bool ContentCaptureTask::CaptureContent(std::vector<cc::NodeHolder>& data) {
bool ContentCaptureTask::CaptureContent() {
DCHECK(task_session_);
- std::vector<cc::NodeHolder> buffer;
+ Vector<cc::NodeId> buffer;
if (histogram_reporter_)
histogram_reporter_->OnCaptureContentStarted();
bool result = CaptureContent(buffer);
if (histogram_reporter_)
histogram_reporter_->OnCaptureContentEnded(buffer.size());
- if (!buffer.empty())
+ if (!buffer.IsEmpty())
task_session_->SetCapturedContent(buffer);
return result;
}
@@ -82,20 +88,19 @@ void ContentCaptureTask::SendContent(
if (histogram_reporter_)
histogram_reporter_->OnSendContentStarted();
- std::vector<scoped_refptr<WebContentHolder>> content_batch;
+ WebVector<WebContentHolder> content_batch;
content_batch.reserve(kBatchSize);
// Only send changed content after the new content was sent.
bool sending_changed_content = !doc_session.HasUnsentCapturedContent();
while (content_batch.size() < kBatchSize) {
- scoped_refptr<ContentHolder> content_holder;
+ Node* node;
if (sending_changed_content)
- content_holder = doc_session.GetNextChangedContentHolder();
+ node = doc_session.GetNextChangedNode();
else
- content_holder = doc_session.GetNextUnsentContentHolder();
- if (!content_holder)
+ node = doc_session.GetNextUnsentNode();
+ if (!node)
break;
- content_batch.push_back(
- base::MakeRefCounted<WebContentHolder>(content_holder));
+ content_batch.emplace_back(WebContentHolder(*node));
}
if (!content_batch.empty()) {
if (sending_changed_content) {
@@ -203,7 +208,7 @@ void ContentCaptureTask::ScheduleInternal(ScheduleReason reason) {
if (is_scheduled_)
return;
- TimeDelta delay;
+ base::TimeDelta delay;
switch (reason) {
case ScheduleReason::kFirstContentChange:
case ScheduleReason::kScrolling:
diff --git a/chromium/third_party/blink/renderer/core/content_capture/content_capture_task.h b/chromium/third_party/blink/renderer/core/content_capture/content_capture_task.h
index 01941c8d90b..a428a4fb48b 100644
--- a/chromium/third_party/blink/renderer/core/content_capture/content_capture_task.h
+++ b/chromium/third_party/blink/renderer/core/content_capture/content_capture_task.h
@@ -6,14 +6,14 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_CONTENT_CAPTURE_CONTENT_CAPTURE_TASK_H_
#include <memory>
-#include <vector>
-#include "cc/paint/node_holder.h"
+#include "cc/paint/node_id.h"
#include "third_party/blink/renderer/core/content_capture/content_capture_task_histogram_reporter.h"
#include "third_party/blink/renderer/core/content_capture/task_session.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/timer.h"
#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
+#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
@@ -59,7 +59,7 @@ class CORE_EXPORT ContentCaptureTask : public RefCounted<ContentCaptureTask> {
}
void SetCapturedContentForTesting(
- const std::vector<cc::NodeHolder>& captured_content) {
+ const Vector<cc::NodeId>& captured_content) {
captured_content_for_testing_ = captured_content;
}
@@ -94,7 +94,7 @@ class CORE_EXPORT ContentCaptureTask : public RefCounted<ContentCaptureTask> {
void SendContent(TaskSession::DocumentSession& doc_session);
void ScheduleInternal(ScheduleReason reason);
- bool CaptureContent(std::vector<cc::NodeHolder>& data);
+ bool CaptureContent(Vector<cc::NodeId>& data);
bool is_scheduled_ = false;
@@ -112,7 +112,7 @@ class CORE_EXPORT ContentCaptureTask : public RefCounted<ContentCaptureTask> {
base::TimeDelta task_long_delay_;
scoped_refptr<ContentCaptureTaskHistogramReporter> histogram_reporter_;
base::Optional<TaskState> task_stop_for_testing_;
- base::Optional<std::vector<cc::NodeHolder>> captured_content_for_testing_;
+ base::Optional<Vector<cc::NodeId>> captured_content_for_testing_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/content_capture/content_capture_task_histogram_reporter.cc b/chromium/third_party/blink/renderer/core/content_capture/content_capture_task_histogram_reporter.cc
index 7c3834b2bad..c2afc2de80a 100644
--- a/chromium/third_party/blink/renderer/core/content_capture/content_capture_task_histogram_reporter.cc
+++ b/chromium/third_party/blink/renderer/core/content_capture/content_capture_task_histogram_reporter.cc
@@ -10,7 +10,6 @@ namespace blink {
// static
constexpr char ContentCaptureTaskHistogramReporter::kCaptureContentTime[];
-constexpr char ContentCaptureTaskHistogramReporter::kCaptureOneContentTime[];
constexpr char ContentCaptureTaskHistogramReporter::kCaptureContentDelayTime[];
constexpr char ContentCaptureTaskHistogramReporter::kSendContentTime[];
constexpr char ContentCaptureTaskHistogramReporter::kSentContentCount[];
@@ -21,7 +20,6 @@ ContentCaptureTaskHistogramReporter::ContentCaptureTaskHistogramReporter()
30000,
50),
capture_content_time_histogram_(kCaptureContentTime, 0, 50000, 50),
- capture_one_content_time_histogram_(kCaptureOneContentTime, 0, 50000, 50),
send_content_time_histogram_(kSendContentTime, 0, 50000, 50),
sent_content_count_histogram_(kSentContentCount, 0, 10000, 50) {}
@@ -31,11 +29,11 @@ ContentCaptureTaskHistogramReporter::~ContentCaptureTaskHistogramReporter() =
void ContentCaptureTaskHistogramReporter::OnContentChanged() {
if (content_change_time_)
return;
- content_change_time_ = WTF::CurrentTimeTicks();
+ content_change_time_ = base::TimeTicks::Now();
}
void ContentCaptureTaskHistogramReporter::OnCaptureContentStarted() {
- capture_content_start_time_ = WTF::CurrentTimeTicks();
+ capture_content_start_time_ = base::TimeTicks::Now();
}
void ContentCaptureTaskHistogramReporter::OnCaptureContentEnded(
@@ -49,21 +47,19 @@ void ContentCaptureTaskHistogramReporter::OnCaptureContentEnded(
// Gives content_change_time_ to the change occurred while sending the
// content.
captured_content_change_time_ = std::move(content_change_time_);
- base::TimeDelta delta = WTF::CurrentTimeTicks() - capture_content_start_time_;
+ base::TimeDelta delta = base::TimeTicks::Now() - capture_content_start_time_;
capture_content_time_histogram_.CountMicroseconds(delta);
- capture_one_content_time_histogram_.CountMicroseconds(delta /
- captured_content_count);
}
void ContentCaptureTaskHistogramReporter::OnSendContentStarted() {
- send_content_start_time_ = WTF::CurrentTimeTicks();
+ send_content_start_time_ = base::TimeTicks::Now();
}
void ContentCaptureTaskHistogramReporter::OnSendContentEnded(
size_t sent_content_count) {
- TimeTicks now = WTF::CurrentTimeTicks();
+ base::TimeTicks now = base::TimeTicks::Now();
if (captured_content_change_time_) {
- TimeTicks content_change_time = captured_content_change_time_.value();
+ base::TimeTicks content_change_time = captured_content_change_time_.value();
captured_content_change_time_.reset();
capture_content_delay_time_histogram_.CountMilliseconds(
now - content_change_time);
diff --git a/chromium/third_party/blink/renderer/core/content_capture/content_capture_task_histogram_reporter.h b/chromium/third_party/blink/renderer/core/content_capture/content_capture_task_histogram_reporter.h
index 49d53895dc0..fad03b77c87 100644
--- a/chromium/third_party/blink/renderer/core/content_capture/content_capture_task_histogram_reporter.h
+++ b/chromium/third_party/blink/renderer/core/content_capture/content_capture_task_histogram_reporter.h
@@ -7,7 +7,7 @@
#include "base/optional.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
@@ -22,8 +22,6 @@ class CORE_EXPORT ContentCaptureTaskHistogramReporter
"ContentCapture.CaptureContentDelayTime";
static constexpr char kCaptureContentTime[] =
"ContentCapture.CaptureContentTime";
- static constexpr char kCaptureOneContentTime[] =
- "ContentCapture.CaptureOneContentTime";
static constexpr char kSendContentTime[] = "ContentCapture.SendContentTime";
static constexpr char kSentContentCount[] = "ContentCapture.SentContentCount";
@@ -39,15 +37,15 @@ class CORE_EXPORT ContentCaptureTaskHistogramReporter
private:
// The time of first content change since the last content captured.
- base::Optional<WTF::TimeTicks> content_change_time_;
+ base::Optional<base::TimeTicks> content_change_time_;
// The copy of |content_change_time| after the content has been captured; we
// need to record the time the content has been sent, |content_change_time_|
// shall be released for the next content change.
- base::Optional<WTF::TimeTicks> captured_content_change_time_;
+ base::Optional<base::TimeTicks> captured_content_change_time_;
// The time to start capturing content.
- WTF::TimeTicks capture_content_start_time_;
+ base::TimeTicks capture_content_start_time_;
// The time to start sending content.
- WTF::TimeTicks send_content_start_time_;
+ base::TimeTicks send_content_start_time_;
// Records time from first content change to content that has been sent, its
// range is 500ms from to 30s.
@@ -55,10 +53,6 @@ class CORE_EXPORT ContentCaptureTaskHistogramReporter
// Records time to capture the content, its range is from 0 to 50,000
// microseconds.
CustomCountHistogram capture_content_time_histogram_;
- // Records time to capture one content, this is the average of all captured
- // content for a specific ContentCapture, its range is from 0 to 50,000
- // microseconds.
- CustomCountHistogram capture_one_content_time_histogram_;
// Records time to send the content, its range is from 0 to 50,000
// microseconds.
CustomCountHistogram send_content_time_histogram_;
diff --git a/chromium/third_party/blink/renderer/core/content_capture/content_capture_test.cc b/chromium/third_party/blink/renderer/core/content_capture/content_capture_test.cc
index 4f615d77b0c..8fa581645f2 100644
--- a/chromium/third_party/blink/renderer/core/content_capture/content_capture_test.cc
+++ b/chromium/third_party/blink/renderer/core/content_capture/content_capture_test.cc
@@ -24,14 +24,8 @@ namespace blink {
class WebContentCaptureClientTestHelper : public WebContentCaptureClient {
public:
- WebContentCaptureClientTestHelper(NodeHolder::Type type)
- : node_holder_type_(type) {}
~WebContentCaptureClientTestHelper() override = default;
- NodeHolder::Type GetNodeHolderType() const override {
- return node_holder_type_;
- }
-
void GetTaskTimingParameters(base::TimeDelta& short_delay,
base::TimeDelta& long_delay) const override {
short_delay = GetTaskShortDelay();
@@ -46,57 +40,52 @@ class WebContentCaptureClientTestHelper : public WebContentCaptureClient {
return base::TimeDelta::FromMilliseconds(500);
}
- void DidCaptureContent(
- const std::vector<scoped_refptr<WebContentHolder>>& data,
- bool first_data) override {
+ void DidCaptureContent(const WebVector<WebContentHolder>& data,
+ bool first_data) override {
data_ = data;
first_data_ = first_data;
- for (auto d : data)
- all_text_.push_back(d->GetValue().Utf8());
+ for (auto& d : data)
+ all_text_.push_back(d.GetValue().Utf8());
}
- void DidUpdateContent(
- const std::vector<scoped_refptr<WebContentHolder>>& data) override {
+ void DidUpdateContent(const WebVector<WebContentHolder>& data) override {
updated_data_ = data;
- for (auto d : data)
- updated_text_.push_back(d->GetValue().Utf8());
+ for (auto& d : data)
+ updated_text_.push_back(d.GetValue().Utf8());
}
- void DidRemoveContent(const std::vector<int64_t>& data) override {
+ void DidRemoveContent(WebVector<int64_t> data) override {
removed_data_ = data;
}
bool FirstData() const { return first_data_; }
- const std::vector<scoped_refptr<WebContentHolder>>& Data() const {
- return data_;
- }
+ const WebVector<WebContentHolder>& Data() const { return data_; }
- const std::vector<scoped_refptr<WebContentHolder>>& UpdatedData() const {
+ const WebVector<WebContentHolder>& UpdatedData() const {
return updated_data_;
}
- const std::vector<std::string>& AllText() const { return all_text_; }
+ const Vector<std::string>& AllText() const { return all_text_; }
- const std::vector<std::string>& UpdatedText() const { return updated_text_; }
+ const Vector<std::string>& UpdatedText() const { return updated_text_; }
- const std::vector<int64_t>& RemovedData() const { return removed_data_; }
+ const WebVector<int64_t>& RemovedData() const { return removed_data_; }
void ResetResults() {
first_data_ = false;
- data_.clear();
- updated_data_.clear();
- removed_data_.clear();
+ data_.Clear();
+ updated_data_.Clear();
+ removed_data_.Clear();
}
private:
bool first_data_ = false;
- std::vector<scoped_refptr<WebContentHolder>> data_;
- std::vector<scoped_refptr<WebContentHolder>> updated_data_;
- std::vector<int64_t> removed_data_;
- NodeHolder::Type node_holder_type_;
- std::vector<std::string> all_text_;
- std::vector<std::string> updated_text_;
+ WebVector<WebContentHolder> data_;
+ WebVector<WebContentHolder> updated_data_;
+ WebVector<int64_t> removed_data_;
+ Vector<std::string> all_text_;
+ Vector<std::string> updated_text_;
};
class ContentCaptureTaskTestHelper : public ContentCaptureTask {
@@ -128,8 +117,7 @@ class ContentCaptureManagerTestHelper : public ContentCaptureManager {
ContentCaptureManagerTestHelper(
LocalFrame& local_frame_root,
WebContentCaptureClientTestHelper& content_capture_client)
- : ContentCaptureManager(local_frame_root,
- content_capture_client.GetNodeHolderType()) {
+ : ContentCaptureManager(local_frame_root) {
content_capture_task_ = base::MakeRefCounted<ContentCaptureTaskTestHelper>(
local_frame_root, GetTaskSessionForTesting(), content_capture_client);
}
@@ -160,15 +148,13 @@ class ContentCaptureLocalFrameClientHelper : public EmptyLocalFrameClient {
WebContentCaptureClient& client_;
};
-class ContentCaptureTest
- : public PageTestBase,
- public ::testing::WithParamInterface<NodeHolder::Type> {
+class ContentCaptureTest : public PageTestBase {
public:
ContentCaptureTest() { EnablePlatform(); }
void SetUp() override {
content_capture_client_ =
- std::make_unique<WebContentCaptureClientTestHelper>(GetParam());
+ std::make_unique<WebContentCaptureClientTestHelper>();
local_frame_client_ =
MakeGarbageCollected<ContentCaptureLocalFrameClientHelper>(
*content_capture_client_);
@@ -194,7 +180,7 @@ class ContentCaptureTest
// Setup captured content to ContentCaptureTask, it isn't necessary once
// ContentCaptureManager is created by LocalFrame.
content_capture_manager_->GetContentCaptureTask()
- ->SetCapturedContentForTesting(node_holders_);
+ ->SetCapturedContentForTesting(node_ids_);
}
void CreateTextNodeAndNotifyManager() {
@@ -205,8 +191,8 @@ class ContentCaptureTest
Element* div_element = GetElementById("d1");
div_element->appendChild(element);
UpdateAllLifecyclePhasesForTest();
- created_node_holder_ = GetContentCaptureManager()->GetNodeHolder(*node);
- std::vector<NodeHolder> captured_content{created_node_holder_};
+ created_node_id_ = GetContentCaptureManager()->GetNodeId(*node);
+ Vector<DOMNodeId> captured_content{created_node_id_};
content_capture_manager_->GetContentCaptureTask()
->SetCapturedContentForTesting(captured_content);
}
@@ -233,20 +219,38 @@ class ContentCaptureTest
platform()->RunForPeriod(GetWebContentCaptureClient()->GetTaskLongDelay());
}
- void RemoveNode(NodeHolder node_holder, Node* node) {
+ void RemoveNode(Node* node) {
// Remove the node.
node->remove();
- GetContentCaptureManager()->OnLayoutTextWillBeDestroyed(node_holder);
+ GetContentCaptureManager()->OnLayoutTextWillBeDestroyed(*node);
+ }
+
+ void RemoveUnsentNode(const WebVector<WebContentHolder>& sent_nodes) {
+ // Find a node isn't in sent_nodes
+ for (auto node : nodes_) {
+ bool found_in_sent = false;
+ for (auto& sent : sent_nodes) {
+ found_in_sent = (node->nodeValue().Utf8().c_str() == sent.GetValue());
+ if (found_in_sent)
+ break;
+ }
+ if (!found_in_sent) {
+ RemoveNode(node);
+ return;
+ }
+ }
+ // Didn't find unsent nodes.
+ NOTREACHED();
}
size_t GetExpectedFirstResultSize() { return ContentCaptureTask::kBatchSize; }
size_t GetExpectedSecondResultSize() {
- return node_holders_.size() - GetExpectedFirstResultSize();
+ return node_ids_.size() - GetExpectedFirstResultSize();
}
- const std::vector<NodeHolder>& NodeHolders() const { return node_holders_; }
- const std::vector<Node*> Nodes() const { return nodes_; }
+ const Vector<DOMNodeId>& NodeIds() const { return node_ids_; }
+ const Vector<Persistent<Node>> Nodes() const { return nodes_; }
private:
void ResetResult() {
@@ -255,8 +259,7 @@ class ContentCaptureTest
// TODO(michaelbai): Remove this once integrate with LayoutText.
void InitNodeHolders() {
- std::vector<std::string> ids{"p1", "p2", "p3", "p4",
- "p5", "p6", "p7", "p8"};
+ Vector<std::string> ids{"p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8"};
for (auto id : ids) {
Node* node = GetElementById(id.c_str())->firstChild();
CHECK(node);
@@ -264,24 +267,19 @@ class ContentCaptureTest
CHECK(layout_object);
CHECK(layout_object->IsText());
nodes_.push_back(node);
- node_holders_.push_back(GetContentCaptureManager()->GetNodeHolder(*node));
+ node_ids_.push_back(GetContentCaptureManager()->GetNodeId(*node));
}
}
- std::vector<Node*> nodes_;
- std::vector<NodeHolder> node_holders_;
+ Vector<Persistent<Node>> nodes_;
+ Vector<DOMNodeId> node_ids_;
std::unique_ptr<WebContentCaptureClientTestHelper> content_capture_client_;
Persistent<ContentCaptureManagerTestHelper> content_capture_manager_;
Persistent<ContentCaptureLocalFrameClientHelper> local_frame_client_;
- NodeHolder created_node_holder_;
+ DOMNodeId created_node_id_ = kInvalidDOMNodeId;
};
-INSTANTIATE_TEST_SUITE_P(,
- ContentCaptureTest,
- testing::Values(NodeHolder::Type::kID,
- NodeHolder::Type::kTextHolder));
-
-TEST_P(ContentCaptureTest, Basic) {
+TEST_F(ContentCaptureTest, Basic) {
RunContentCaptureTask();
EXPECT_EQ(ContentCaptureTask::TaskState::kStop,
GetContentCaptureTask()->GetTaskStateForTesting());
@@ -290,7 +288,7 @@ TEST_P(ContentCaptureTest, Basic) {
GetWebContentCaptureClient()->Data().size());
}
-TEST_P(ContentCaptureTest, PauseAndResume) {
+TEST_F(ContentCaptureTest, PauseAndResume) {
// The task stops before captures content.
GetContentCaptureTask()->SetTaskStopState(
ContentCaptureTask::TaskState::kCaptureContent);
@@ -330,7 +328,7 @@ TEST_P(ContentCaptureTest, PauseAndResume) {
GetWebContentCaptureClient()->Data().size());
}
-TEST_P(ContentCaptureTest, NodeOnlySendOnce) {
+TEST_F(ContentCaptureTest, NodeOnlySendOnce) {
// Send all nodes
RunContentCaptureTask();
EXPECT_FALSE(GetWebContentCaptureClient()->Data().empty());
@@ -343,7 +341,7 @@ TEST_P(ContentCaptureTest, NodeOnlySendOnce) {
EXPECT_TRUE(GetWebContentCaptureClient()->RemovedData().empty());
}
-TEST_P(ContentCaptureTest, RemoveNodeBeforeSendingOut) {
+TEST_F(ContentCaptureTest, RemoveNodeBeforeSendingOut) {
// Capture the content, but didn't send them.
GetContentCaptureTask()->SetTaskStopState(
ContentCaptureTask::TaskState::kProcessCurrentSession);
@@ -351,7 +349,7 @@ TEST_P(ContentCaptureTest, RemoveNodeBeforeSendingOut) {
EXPECT_TRUE(GetWebContentCaptureClient()->Data().empty());
// Remove the node and sent the captured content out.
- RemoveNode(NodeHolders().at(0), Nodes().at(0));
+ RemoveNode(Nodes().at(0));
GetContentCaptureTask()->SetTaskStopState(
ContentCaptureTask::TaskState::kProcessRetryTask);
RunContentCaptureTask();
@@ -369,7 +367,7 @@ TEST_P(ContentCaptureTest, RemoveNodeBeforeSendingOut) {
EXPECT_EQ(0u, GetWebContentCaptureClient()->RemovedData().size());
}
-TEST_P(ContentCaptureTest, RemoveNodeInBetweenSendingOut) {
+TEST_F(ContentCaptureTest, RemoveNodeInBetweenSendingOut) {
// Capture the content, but didn't send them.
GetContentCaptureTask()->SetTaskStopState(
ContentCaptureTask::TaskState::kProcessCurrentSession);
@@ -384,9 +382,8 @@ TEST_P(ContentCaptureTest, RemoveNodeInBetweenSendingOut) {
GetWebContentCaptureClient()->Data().size());
EXPECT_EQ(0u, GetWebContentCaptureClient()->RemovedData().size());
- // This depends on the DocumentSession returning the unsent nodes reversely.
- // Remove the first node and sent the captured content out.
- RemoveNode(NodeHolders().at(0), Nodes().at(0));
+ // This relies on each node to have different value.
+ RemoveUnsentNode(GetWebContentCaptureClient()->Data());
GetContentCaptureTask()->SetTaskStopState(
ContentCaptureTask::TaskState::kProcessRetryTask);
RunContentCaptureTask();
@@ -400,7 +397,7 @@ TEST_P(ContentCaptureTest, RemoveNodeInBetweenSendingOut) {
EXPECT_EQ(0u, GetWebContentCaptureClient()->RemovedData().size());
}
-TEST_P(ContentCaptureTest, RemoveNodeAfterSendingOut) {
+TEST_F(ContentCaptureTest, RemoveNodeAfterSendingOut) {
// Captures the content, but didn't send them.
GetContentCaptureTask()->SetTaskStopState(
ContentCaptureTask::TaskState::kProcessCurrentSession);
@@ -422,13 +419,13 @@ TEST_P(ContentCaptureTest, RemoveNodeAfterSendingOut) {
EXPECT_EQ(0u, GetWebContentCaptureClient()->RemovedData().size());
// Remove the node.
- RemoveNode(NodeHolders().at(0), Nodes().at(0));
+ RemoveNode(Nodes().at(0));
RunLongDelayContentCaptureTask();
EXPECT_EQ(0u, GetWebContentCaptureClient()->Data().size());
EXPECT_EQ(1u, GetWebContentCaptureClient()->RemovedData().size());
}
-TEST_P(ContentCaptureTest, TaskHistogramReporter) {
+TEST_F(ContentCaptureTest, TaskHistogramReporter) {
// This performs gc for all DocumentSession, flushes the existing
// SentContentCount and give a clean baseline for histograms.
// We are not sure if it always work, maybe still be the source of flaky.
@@ -443,8 +440,6 @@ TEST_P(ContentCaptureTest, TaskHistogramReporter) {
histograms.ExpectTotalCount(
ContentCaptureTaskHistogramReporter::kCaptureContentTime, 0u);
histograms.ExpectTotalCount(
- ContentCaptureTaskHistogramReporter::kCaptureOneContentTime, 0u);
- histograms.ExpectTotalCount(
ContentCaptureTaskHistogramReporter::kSendContentTime, 0u);
histograms.ExpectTotalCount(
ContentCaptureTaskHistogramReporter::kCaptureContentDelayTime, 0u);
@@ -459,8 +454,6 @@ TEST_P(ContentCaptureTest, TaskHistogramReporter) {
histograms.ExpectTotalCount(
ContentCaptureTaskHistogramReporter::kCaptureContentTime, 1u);
histograms.ExpectTotalCount(
- ContentCaptureTaskHistogramReporter::kCaptureOneContentTime, 1u);
- histograms.ExpectTotalCount(
ContentCaptureTaskHistogramReporter::kSendContentTime, 0u);
histograms.ExpectTotalCount(
ContentCaptureTaskHistogramReporter::kCaptureContentDelayTime, 0u);
@@ -477,8 +470,6 @@ TEST_P(ContentCaptureTest, TaskHistogramReporter) {
histograms.ExpectTotalCount(
ContentCaptureTaskHistogramReporter::kCaptureContentTime, 1u);
histograms.ExpectTotalCount(
- ContentCaptureTaskHistogramReporter::kCaptureOneContentTime, 1u);
- histograms.ExpectTotalCount(
ContentCaptureTaskHistogramReporter::kSendContentTime, 1u);
histograms.ExpectTotalCount(
ContentCaptureTaskHistogramReporter::kCaptureContentDelayTime, 1u);
@@ -494,8 +485,6 @@ TEST_P(ContentCaptureTest, TaskHistogramReporter) {
histograms.ExpectTotalCount(
ContentCaptureTaskHistogramReporter::kCaptureContentTime, 1u);
histograms.ExpectTotalCount(
- ContentCaptureTaskHistogramReporter::kCaptureOneContentTime, 1u);
- histograms.ExpectTotalCount(
ContentCaptureTaskHistogramReporter::kSendContentTime, 2u);
histograms.ExpectTotalCount(
ContentCaptureTaskHistogramReporter::kCaptureContentDelayTime, 1u);
@@ -510,8 +499,6 @@ TEST_P(ContentCaptureTest, TaskHistogramReporter) {
histograms.ExpectTotalCount(
ContentCaptureTaskHistogramReporter::kCaptureContentTime, 2u);
histograms.ExpectTotalCount(
- ContentCaptureTaskHistogramReporter::kCaptureOneContentTime, 2u);
- histograms.ExpectTotalCount(
ContentCaptureTaskHistogramReporter::kSendContentTime, 3u);
histograms.ExpectTotalCount(
ContentCaptureTaskHistogramReporter::kCaptureContentDelayTime, 2u);
@@ -523,8 +510,6 @@ TEST_P(ContentCaptureTest, TaskHistogramReporter) {
histograms.ExpectTotalCount(
ContentCaptureTaskHistogramReporter::kCaptureContentTime, 2u);
histograms.ExpectTotalCount(
- ContentCaptureTaskHistogramReporter::kCaptureOneContentTime, 2u);
- histograms.ExpectTotalCount(
ContentCaptureTaskHistogramReporter::kSendContentTime, 3u);
histograms.ExpectTotalCount(
ContentCaptureTaskHistogramReporter::kCaptureContentDelayTime, 2u);
@@ -537,13 +522,11 @@ TEST_P(ContentCaptureTest, TaskHistogramReporter) {
// TODO(michaelbai): use RenderingTest instead of PageTestBase for multiple
// frame test.
-class ContentCaptureSimTest
- : public SimTest,
- public ::testing::WithParamInterface<NodeHolder::Type> {
+class ContentCaptureSimTest : public SimTest {
public:
static const char* kEditableContent;
- ContentCaptureSimTest() : client_(GetParam()), child_client_(GetParam()) {}
+ ContentCaptureSimTest() : client_(), child_client_() {}
void SetUp() override {
SimTest::SetUp();
MainFrame().SetContentCaptureClient(&client_);
@@ -571,9 +554,9 @@ class ContentCaptureSimTest
} else if (type == ContentType::kChildFrame) {
SetCapturedContent(child_frame_content_);
} else if (type == ContentType::kAll) {
- std::vector<NodeHolder> holders(main_frame_content_);
- holders.insert(holders.end(), child_frame_content_.begin(),
- child_frame_content_.end());
+ Vector<DOMNodeId> holders(main_frame_content_);
+ holders.AppendRange(child_frame_content_.begin(),
+ child_frame_content_.end());
SetCapturedContent(holders);
}
}
@@ -597,11 +580,11 @@ class ContentCaptureSimTest
DeleteNodeContent(GetDocument(), "editable_id", offset, length);
}
- const std::vector<std::string>& MainFrameExpectedText() const {
+ const Vector<std::string>& MainFrameExpectedText() const {
return main_frame_expected_text_;
}
- const std::vector<std::string>& ChildFrameExpectedText() const {
+ const Vector<std::string>& ChildFrameExpectedText() const {
return child_frame_expected_text_;
}
@@ -654,8 +637,8 @@ class ContentCaptureSimTest
}
void InitMainFrameNodeHolders() {
- std::vector<std::string> ids = {"p1", "p2", "p3", "p4", "p5",
- "p6", "p7", "s8", "editable_id"};
+ Vector<std::string> ids = {"p1", "p2", "p3", "p4", "p5",
+ "p6", "p7", "s8", "editable_id"};
main_frame_expected_text_ = {
"Hello World1", "Hello World2", "Hello World3",
"Hello World4", "Hello World5", "Hello World6",
@@ -665,24 +648,24 @@ class ContentCaptureSimTest
}
void InitChildFrameNodeHolders(const Document& doc) {
- std::vector<std::string> ids = {"c1", "c2"};
+ Vector<std::string> ids = {"c1", "c2"};
child_frame_expected_text_ = {"Hello World11", "Hello World12"};
InitNodeHolders(child_frame_content_, ids, doc);
EXPECT_EQ(2u, child_frame_content_.size());
}
- void InitNodeHolders(std::vector<NodeHolder>& buffer,
- const std::vector<std::string>& ids,
+ void InitNodeHolders(Vector<DOMNodeId>& buffer,
+ const Vector<std::string>& ids,
const Document& document) {
for (auto id : ids) {
LayoutText* layout_text = ToLayoutText(
document.getElementById(id.c_str())->firstChild()->GetLayoutObject());
- EXPECT_TRUE(layout_text->HasNodeHolder());
- buffer.push_back(layout_text->EnsureNodeHolder());
+ EXPECT_TRUE(layout_text->HasNodeId());
+ buffer.push_back(layout_text->EnsureNodeId());
}
}
- void AddNodeToDocument(Document& doc, std::vector<NodeHolder>& buffer) {
+ void AddNodeToDocument(Document& doc, Vector<DOMNodeId>& buffer) {
Node* node = doc.createTextNode("New Text");
Element* element = Element::Create(html_names::kPTag, &doc);
element->appendChild(node);
@@ -690,8 +673,8 @@ class ContentCaptureSimTest
div_element->appendChild(element);
Compositor().BeginFrame();
LayoutText* layout_text = ToLayoutText(node->GetLayoutObject());
- EXPECT_TRUE(layout_text->HasNodeHolder());
- buffer.insert(buffer.begin(), layout_text->EnsureNodeHolder());
+ EXPECT_TRUE(layout_text->HasNodeId());
+ buffer.push_front(layout_text->EnsureNodeId());
}
void InsertNodeContent(Document& doc,
@@ -713,7 +696,7 @@ class ContentCaptureSimTest
Compositor().BeginFrame();
}
- void SetCapturedContent(const std::vector<NodeHolder>& captured_content) {
+ void SetCapturedContent(const Vector<DOMNodeId>& captured_content) {
GetDocument()
.GetFrame()
->LocalFrameRoot()
@@ -722,10 +705,10 @@ class ContentCaptureSimTest
->SetCapturedContentForTesting(captured_content);
}
- std::vector<std::string> main_frame_expected_text_;
- std::vector<std::string> child_frame_expected_text_;
- std::vector<NodeHolder> main_frame_content_;
- std::vector<NodeHolder> child_frame_content_;
+ Vector<std::string> main_frame_expected_text_;
+ Vector<std::string> child_frame_expected_text_;
+ Vector<DOMNodeId> main_frame_content_;
+ Vector<DOMNodeId> child_frame_content_;
WebContentCaptureClientTestHelper client_;
WebContentCaptureClientTestHelper child_client_;
Persistent<Document> child_document_;
@@ -733,12 +716,7 @@ class ContentCaptureSimTest
const char* ContentCaptureSimTest::kEditableContent = "editable";
-INSTANTIATE_TEST_SUITE_P(,
- ContentCaptureSimTest,
- testing::Values(NodeHolder::Type::kID,
- NodeHolder::Type::kTextHolder));
-
-TEST_P(ContentCaptureSimTest, MultiFrame) {
+TEST_F(ContentCaptureSimTest, MultiFrame) {
SetCapturedContent(ContentType::kAll);
RunContentCaptureTaskUntil(ContentCaptureTask::TaskState::kStop);
EXPECT_EQ(4u, Client().Data().size());
@@ -749,7 +727,7 @@ TEST_P(ContentCaptureSimTest, MultiFrame) {
testing::UnorderedElementsAreArray(ChildFrameExpectedText()));
}
-TEST_P(ContentCaptureSimTest, AddNodeToMultiFrame) {
+TEST_F(ContentCaptureSimTest, AddNodeToMultiFrame) {
SetCapturedContent(ContentType::kMainFrame);
// Stops after capturing content.
RunContentCaptureTaskUntil(
@@ -791,7 +769,7 @@ TEST_P(ContentCaptureSimTest, AddNodeToMultiFrame) {
EXPECT_TRUE(ChildClient().FirstData());
}
-TEST_P(ContentCaptureSimTest, ChangeNode) {
+TEST_F(ContentCaptureSimTest, ChangeNode) {
SetCapturedContent(ContentType::kMainFrame);
RunContentCaptureTaskUntil(ContentCaptureTask::TaskState::kStop);
EXPECT_EQ(4u, Client().Data().size());
@@ -799,7 +777,7 @@ TEST_P(ContentCaptureSimTest, ChangeNode) {
EXPECT_TRUE(ChildClient().Data().empty());
EXPECT_THAT(Client().AllText(),
testing::UnorderedElementsAreArray(MainFrameExpectedText()));
- std::vector<std::string> expected_text_update;
+ Vector<std::string> expected_text_update;
std::string insert_text = "content ";
// Changed content to 'content editable'.
@@ -833,7 +811,7 @@ TEST_P(ContentCaptureSimTest, ChangeNode) {
testing::UnorderedElementsAreArray(expected_text_update));
}
-TEST_P(ContentCaptureSimTest, ChangeNodeBeforeCapture) {
+TEST_F(ContentCaptureSimTest, ChangeNodeBeforeCapture) {
// Changed content to 'content editable' before capture.
std::string insert_text = "content ";
InsertMainFrameEditableContent(insert_text, 0);
@@ -860,7 +838,7 @@ TEST_P(ContentCaptureSimTest, ChangeNodeBeforeCapture) {
testing::UnorderedElementsAreArray(MainFrameExpectedText()));
}
-TEST_P(ContentCaptureSimTest, DeleteNodeContent) {
+TEST_F(ContentCaptureSimTest, DeleteNodeContent) {
SetCapturedContent(ContentType::kMainFrame);
RunContentCaptureTaskUntil(ContentCaptureTask::TaskState::kStop);
EXPECT_EQ(4u, Client().Data().size());
@@ -876,7 +854,7 @@ TEST_P(ContentCaptureSimTest, DeleteNodeContent) {
EXPECT_EQ(1u, Client().UpdatedData().size());
EXPECT_FALSE(Client().FirstData());
EXPECT_TRUE(ChildClient().Data().empty());
- std::vector<std::string> expected_text_update;
+ Vector<std::string> expected_text_update;
expected_text_update.push_back("edit");
EXPECT_THAT(Client().UpdatedText(),
testing::UnorderedElementsAreArray(expected_text_update));
diff --git a/chromium/third_party/blink/renderer/core/content_capture/content_holder.cc b/chromium/third_party/blink/renderer/core/content_capture/content_holder.cc
deleted file mode 100644
index 6e33164a581..00000000000
--- a/chromium/third_party/blink/renderer/core/content_capture/content_holder.cc
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright 2019 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "third_party/blink/renderer/core/content_capture/content_holder.h"
-
-#include "third_party/blink/renderer/core/dom/node.h"
-#include "third_party/blink/renderer/core/layout/layout_object.h"
-
-namespace blink {
-
-ContentHolder::ContentHolder(Node& node) : node_(&node) {}
-
-ContentHolder::~ContentHolder() {}
-
-String ContentHolder::GetValue() const {
- DCHECK(IsValid());
- if (node_)
- return node_->nodeValue();
- return String();
-}
-
-IntRect ContentHolder::GetBoundingBox() const {
- DCHECK(IsValid());
- if (node_ && node_->GetLayoutObject())
- return EnclosingIntRect(node_->GetLayoutObject()->VisualRectInDocument());
- return IntRect();
-}
-
-uint64_t ContentHolder::GetId() const {
- DCHECK(IsValid());
- if (node_)
- return reinterpret_cast<uint64_t>(node_.Get());
- return 0;
-}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/content_capture/content_holder.h b/chromium/third_party/blink/renderer/core/content_capture/content_holder.h
deleted file mode 100644
index cc0f33cc963..00000000000
--- a/chromium/third_party/blink/renderer/core/content_capture/content_holder.h
+++ /dev/null
@@ -1,47 +0,0 @@
-// Copyright 2019 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CONTENT_CAPTURE_CONTENT_HOLDER_H_
-#define THIRD_PARTY_BLINK_RENDERER_CORE_CONTENT_CAPTURE_CONTENT_HOLDER_H_
-
-#include "cc/paint/node_holder.h"
-#include "cc/paint/text_holder.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/heap/member.h"
-#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
-
-namespace blink {
-
-using NodeHolder = cc::NodeHolder;
-
-class Node;
-
-class CORE_EXPORT ContentHolder : public cc::TextHolder {
- public:
- ContentHolder(Node& node);
- ~ContentHolder() override;
-
- bool IsValid() const { return node_; }
-
- String GetValue() const;
- IntRect GetBoundingBox() const;
- uint64_t GetId() const;
-
- void SetHasSent() { has_sent_ = true; }
- bool HasSent() const { return has_sent_; }
-
- const Node* GetNode() { return node_; }
-
- void OnNodeDetachedFromLayoutTree() { node_ = nullptr; }
-
- private:
- bool has_sent_ = false;
-
- UntracedMember<const Node> node_;
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CONTENT_CAPTURE_CONTENT_HOLDER_H_
diff --git a/chromium/third_party/blink/renderer/core/content_capture/task_session.cc b/chromium/third_party/blink/renderer/core/content_capture/task_session.cc
index 5b14b14a6c0..ce4ae094187 100644
--- a/chromium/third_party/blink/renderer/core/content_capture/task_session.cc
+++ b/chromium/third_party/blink/renderer/core/content_capture/task_session.cc
@@ -6,7 +6,6 @@
#include <utility>
-#include "third_party/blink/renderer/core/content_capture/content_holder.h"
#include "third_party/blink/renderer/core/content_capture/sent_nodes.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/dom_node_ids.h"
@@ -23,84 +22,56 @@ TaskSession::DocumentSession::~DocumentSession() {
callback_.value().Run(total_sent_nodes_);
}
-void TaskSession::DocumentSession::AddNodeHolder(cc::NodeHolder node_holder) {
- captured_content_.push_back(node_holder);
+void TaskSession::DocumentSession::AddCapturedNode(Node& node) {
+ captured_content_.insert(WeakMember<Node>(&node));
}
void TaskSession::DocumentSession::AddDetachedNode(int64_t id) {
- detached_nodes_.push_back(id);
+ detached_nodes_.emplace_back(id);
}
-void TaskSession::DocumentSession::AddChangedNodeHolder(
- cc::NodeHolder node_holder) {
- changed_content_.push_back(node_holder);
+void TaskSession::DocumentSession::AddChangedNode(Node& node) {
+ changed_content_.insert(WeakMember<Node>(&node));
}
-std::vector<int64_t> TaskSession::DocumentSession::MoveDetachedNodes() {
+WebVector<int64_t> TaskSession::DocumentSession::MoveDetachedNodes() {
return std::move(detached_nodes_);
}
-scoped_refptr<blink::ContentHolder>
-TaskSession::DocumentSession::GetNextUnsentContentHolder() {
- scoped_refptr<ContentHolder> content_holder;
- while (!captured_content_.empty() && !content_holder) {
- auto node_holder = captured_content_.back();
- if (node_holder.type == cc::NodeHolder::Type::kID) {
- Node* node = DOMNodeIds::NodeForId(node_holder.id);
- if (node && node->GetLayoutObject() && !sent_nodes_->HasSent(*node)) {
- sent_nodes_->OnSent(*node);
- content_holder = base::MakeRefCounted<ContentHolder>(*node);
- }
- } else if (node_holder.type == cc::NodeHolder::Type::kTextHolder &&
- node_holder.text_holder) {
- content_holder = scoped_refptr<ContentHolder>(
- static_cast<ContentHolder*>(node_holder.text_holder.get()));
- if (content_holder && content_holder->IsValid() &&
- !content_holder->HasSent()) {
- content_holder->SetHasSent();
- } else {
- content_holder.reset();
- }
+Node* TaskSession::DocumentSession::GetNextUnsentNode() {
+ while (!captured_content_.IsEmpty()) {
+ Node* node = captured_content_.TakeAny().Get();
+ if (node && node->GetLayoutObject() && !sent_nodes_->HasSent(*node)) {
+ sent_nodes_->OnSent(*node);
+ total_sent_nodes_++;
+ return node;
}
- captured_content_.pop_back();
}
- if (content_holder)
- total_sent_nodes_++;
- return content_holder;
-}
-
-scoped_refptr<blink::ContentHolder>
-TaskSession::DocumentSession::GetNextChangedContentHolder() {
- scoped_refptr<ContentHolder> content_holder;
- while (!changed_content_.empty() && !content_holder) {
- auto node_holder = changed_content_.back();
- if (node_holder.type == cc::NodeHolder::Type::kID) {
- Node* node = DOMNodeIds::NodeForId(node_holder.id);
- if (node && node->GetLayoutObject())
- content_holder = base::MakeRefCounted<ContentHolder>(*node);
- } else if (node_holder.type == cc::NodeHolder::Type::kTextHolder &&
- node_holder.text_holder) {
- content_holder = scoped_refptr<ContentHolder>(
- static_cast<ContentHolder*>(node_holder.text_holder.get()));
- if (content_holder && !content_holder->IsValid())
- content_holder.reset();
+ return nullptr;
+}
+
+Node* TaskSession::DocumentSession::GetNextChangedNode() {
+ while (!changed_content_.IsEmpty()) {
+ Node* node = changed_content_.TakeAny().Get();
+ if (node && node->GetLayoutObject()) {
+ total_sent_nodes_++;
+ return node;
}
- changed_content_.pop_back();
}
- if (content_holder)
- total_sent_nodes_++;
- return content_holder;
+ return nullptr;
}
void TaskSession::DocumentSession::Trace(blink::Visitor* visitor) {
+ visitor->Trace(captured_content_);
visitor->Trace(sent_nodes_);
visitor->Trace(document_);
+ visitor->Trace(changed_content_);
}
void TaskSession::DocumentSession::Reset() {
changed_content_.clear();
captured_content_.clear();
- detached_nodes_.clear();
+ detached_nodes_.Clear();
}
TaskSession::TaskSession(SentNodes& sent_nodes) : sent_nodes_(sent_nodes) {}
@@ -116,78 +87,43 @@ TaskSession::DocumentSession* TaskSession::GetNextUnsentDocumentSession() {
}
void TaskSession::SetCapturedContent(
- const std::vector<cc::NodeHolder>& captured_content) {
+ const Vector<cc::NodeId>& captured_content) {
DCHECK(!HasUnsentData());
- DCHECK(!captured_content.empty());
+ DCHECK(!captured_content.IsEmpty());
GroupCapturedContentByDocument(captured_content);
has_unsent_data_ = true;
}
void TaskSession::GroupCapturedContentByDocument(
- const std::vector<cc::NodeHolder>& captured_content) {
- for (const cc::NodeHolder& node_holder : captured_content) {
- if (const Node* node = GetNode(node_holder)) {
- node = changed_nodes_.Take(node);
- if (node) {
+ const Vector<cc::NodeId>& captured_content) {
+ for (const cc::NodeId& node_id : captured_content) {
+ if (Node* node = DOMNodeIds::NodeForId(node_id)) {
+ if (changed_nodes_.Take(node)) {
// The changed node might not be sent.
- if (GetNodeIf(true, node_holder)) {
- EnsureDocumentSession(node->GetDocument())
- .AddChangedNodeHolder(node_holder);
+ if (sent_nodes_->HasSent(*node)) {
+ EnsureDocumentSession(node->GetDocument()).AddChangedNode(*node);
} else {
- EnsureDocumentSession(node->GetDocument()).AddNodeHolder(node_holder);
+ EnsureDocumentSession(node->GetDocument()).AddCapturedNode(*node);
}
continue;
}
- }
- if (const Node* node = GetNodeIf(false /* sent */, node_holder)) {
- EnsureDocumentSession(node->GetDocument()).AddNodeHolder(node_holder);
+ if (!sent_nodes_->HasSent(*node)) {
+ EnsureDocumentSession(node->GetDocument()).AddCapturedNode(*node);
+ }
}
}
}
-void TaskSession::OnNodeDetached(const cc::NodeHolder& node_holder) {
- if (const Node* node = GetNodeIf(true /* sent */, node_holder)) {
- EnsureDocumentSession(node->GetDocument())
- .AddDetachedNode(reinterpret_cast<int64_t>(node));
+void TaskSession::OnNodeDetached(const Node& node) {
+ if (sent_nodes_->HasSent(node)) {
+ EnsureDocumentSession(node.GetDocument())
+ .AddDetachedNode(reinterpret_cast<int64_t>(&node));
has_unsent_data_ = true;
}
}
-void TaskSession::OnNodeChanged(const cc::NodeHolder& node_holder) {
- if (const Node* node = GetNode(node_holder)) {
- changed_nodes_.insert(WeakMember<const Node>(node));
- }
-}
-
-const Node* TaskSession::GetNodeIf(bool sent,
- const cc::NodeHolder& node_holder) const {
- Node* node = nullptr;
- if (node_holder.type == cc::NodeHolder::Type::kID) {
- node = DOMNodeIds::NodeForId(node_holder.id);
- if (node && (sent_nodes_->HasSent(*node) == sent))
- return node;
- } else if (node_holder.type == cc::NodeHolder::Type::kTextHolder) {
- ContentHolder* content_holder =
- static_cast<ContentHolder*>(node_holder.text_holder.get());
- if (content_holder && content_holder->IsValid() &&
- (content_holder->HasSent() == sent)) {
- return content_holder->GetNode();
- }
- }
- return nullptr;
-}
-
-const Node* TaskSession::GetNode(const cc::NodeHolder& node_holder) const {
- if (node_holder.type == cc::NodeHolder::Type::kID)
- return DOMNodeIds::NodeForId(node_holder.id);
-
- if (node_holder.type == cc::NodeHolder::Type::kTextHolder) {
- ContentHolder* content_holder =
- static_cast<ContentHolder*>(node_holder.text_holder.get());
- if (content_holder)
- return content_holder->GetNode();
- }
- return nullptr;
+void TaskSession::OnNodeChanged(Node& node) {
+ changed_nodes_.insert(WeakMember<Node>(&node));
}
TaskSession::DocumentSession& TaskSession::EnsureDocumentSession(
diff --git a/chromium/third_party/blink/renderer/core/content_capture/task_session.h b/chromium/third_party/blink/renderer/core/content_capture/task_session.h
index b91c1ac3589..e648a52f396 100644
--- a/chromium/third_party/blink/renderer/core/content_capture/task_session.h
+++ b/chromium/third_party/blink/renderer/core/content_capture/task_session.h
@@ -6,19 +6,19 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_CONTENT_CAPTURE_TASK_SESSION_H_
#include <utility>
-#include <vector>
#include "base/callback.h"
#include "base/memory/scoped_refptr.h"
-#include "cc/paint/node_holder.h"
+#include "cc/paint/node_id.h"
+#include "third_party/blink/public/platform/web_vector.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
#include "third_party/blink/renderer/platform/heap/heap_allocator.h"
#include "third_party/blink/renderer/platform/heap/member.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
+#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
-class ContentHolder;
class Document;
class SentNodes;
@@ -35,7 +35,7 @@ class SentNodes;
// they are saved to the DocumentSession directly.
//
// ContentCaptureTask gets the data per document by using
-// GetUnsentDocumentSession() and GetNextUnsentContentHolder(), and must send
+// GetUnsentDocumentSession() and GetNextUnsentNode(), and must send
// all data out before capturing on-screen content again.
class TaskSession : public GarbageCollectedFinalized<TaskSession> {
public:
@@ -52,26 +52,27 @@ class TaskSession : public GarbageCollectedFinalized<TaskSession> {
SentNodes& sent_nodes,
SentNodeCountCallback& call_back);
~DocumentSession();
- void AddNodeHolder(cc::NodeHolder node_holder);
+ void AddCapturedNode(Node& node);
void AddDetachedNode(int64_t id);
- void AddChangedNodeHolder(cc::NodeHolder node);
+ void AddChangedNode(Node& node);
bool HasUnsentData() const {
return HasUnsentCapturedContent() || HasUnsentChangedContent() ||
HasUnsentDetachedNodes();
}
- bool HasUnsentCapturedContent() const { return !captured_content_.empty(); }
- bool HasUnsentChangedContent() const { return !changed_content_.empty(); }
+ bool HasUnsentCapturedContent() const {
+ return !captured_content_.IsEmpty();
+ }
+ bool HasUnsentChangedContent() const { return !changed_content_.IsEmpty(); }
bool HasUnsentDetachedNodes() const { return !detached_nodes_.empty(); }
- std::vector<int64_t> MoveDetachedNodes();
+ WebVector<int64_t> MoveDetachedNodes();
const Document* GetDocument() const { return document_; }
bool FirstDataHasSent() const { return first_data_has_sent_; }
void SetFirstDataHasSent() { first_data_has_sent_ = true; }
- // Removes the unsent node from |captured_content_|, and returns it as
- // ContentHolder.
- scoped_refptr<ContentHolder> GetNextUnsentContentHolder();
+ // Removes the unsent node from |captured_content_|, and returns it.
+ Node* GetNextUnsentNode();
- scoped_refptr<ContentHolder> GetNextChangedContentHolder();
+ Node* GetNextChangedNode();
// Resets the |captured_content_| and the |detached_nodes_|, shall only be
// used if those data doesn't need to be sent, e.g. there is no
@@ -82,20 +83,20 @@ class TaskSession : public GarbageCollectedFinalized<TaskSession> {
private:
// The captured content that belongs to this document.
- std::vector<cc::NodeHolder> captured_content_;
+ HeapHashSet<WeakMember<Node>> captured_content_;
// The list of content id of node that has been detached from the
// LayoutTree.
- std::vector<int64_t> detached_nodes_;
+ WebVector<int64_t> detached_nodes_;
WeakMember<const Document> document_;
Member<SentNodes> sent_nodes_;
// The list of changed nodes that needs to be sent.
- std::vector<cc::NodeHolder> changed_content_;
+ HeapHashSet<WeakMember<Node>> changed_content_;
bool first_data_has_sent_ = false;
// This is for the metrics to record the total node that has been sent.
size_t total_sent_nodes_ = 0;
// Histogram could be disabed in low time resolution OS, see
- // TimeTicks::IsHighResolution and ContentCaptureTask.
+ // base::TimeTicks::IsHighResolution and ContentCaptureTask.
base::Optional<SentNodeCountCallback> callback_;
};
@@ -106,11 +107,11 @@ class TaskSession : public GarbageCollectedFinalized<TaskSession> {
// This can only be invoked when all data has been sent (i.e. HasUnsentData()
// returns False).
- void SetCapturedContent(const std::vector<cc::NodeHolder>& captured_content);
+ void SetCapturedContent(const Vector<cc::NodeId>& captured_content);
- void OnNodeDetached(const cc::NodeHolder& node_holder);
+ void OnNodeDetached(const Node& node);
- void OnNodeChanged(const cc::NodeHolder& node_holder);
+ void OnNodeChanged(Node& node);
bool HasUnsentData() const { return has_unsent_data_; }
@@ -125,16 +126,14 @@ class TaskSession : public GarbageCollectedFinalized<TaskSession> {
private:
void GroupCapturedContentByDocument(
- const std::vector<cc::NodeHolder>& captured_content);
+ const Vector<cc::NodeId>& captured_content);
DocumentSession& EnsureDocumentSession(const Document& doc);
DocumentSession* GetDocumentSession(const Document& document) const;
- const Node* GetNodeIf(bool sent, const cc::NodeHolder& node_holder) const;
- const Node* GetNode(const cc::NodeHolder& node_holder) const;
Member<SentNodes> sent_nodes_;
// The list of node whose value has changed.
- HeapHashSet<WeakMember<const Node>> changed_nodes_;
+ HeapHashSet<WeakMember<Node>> changed_nodes_;
// This owns the DocumentSession which is released along with Document.
HeapHashMap<WeakMember<const Document>, Member<DocumentSession>>
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 f716487b0d0..3ddadb1bd89 100644
--- a/chromium/third_party/blink/renderer/core/core_idl_files.gni
+++ b/chromium/third_party/blink/renderer/core/core_idl_files.gni
@@ -63,6 +63,7 @@ core_idl_files =
"css/css_style_rule.idl",
"css/css_style_sheet.idl",
"css/css_supports_rule.idl",
+ "css/css_property_rule.idl",
"css/css_viewport_rule.idl",
"css/font_face.idl",
"css/font_face_set.idl",
@@ -128,8 +129,6 @@ core_idl_files =
"dom/node_list.idl",
"dom/processing_instruction.idl",
"dom/range.idl",
- "dom/scripted_task_queue.idl",
- "dom/scripted_task_queue_controller.idl",
"dom/static_range.idl",
"dom/text.idl",
"dom/tree_walker.idl",
@@ -326,16 +325,18 @@ core_idl_files =
"page/scrolling/scroll_state.idl",
"resize_observer/resize_observer.idl",
"resize_observer/resize_observer_entry.idl",
+ "streams/byte_length_queuing_strategy.idl",
+ "streams/count_queuing_strategy.idl",
"streams/readable_stream.idl",
"streams/readable_stream_default_controller.idl",
"streams/readable_stream_default_reader.idl",
"streams/transform_stream.idl",
"streams/transform_stream_default_controller.idl",
+ "streams/underlying_sink_base.idl",
+ "streams/underlying_source_base.idl",
"streams/writable_stream.idl",
"streams/writable_stream_default_controller.idl",
"streams/writable_stream_default_writer.idl",
- "streams/underlying_source_base.idl",
- "streams/underlying_sink_base.idl",
"svg/svg_a_element.idl",
"svg/svg_angle.idl",
"svg/svg_animate_element.idl",
@@ -434,6 +435,7 @@ core_idl_files =
"svg/svg_unit_types.idl",
"svg/svg_use_element.idl",
"svg/svg_view_element.idl",
+ "timing/largest_contentful_paint.idl",
"timing/layout_shift.idl",
"timing/memory_info.idl",
"timing/performance.idl",
@@ -469,10 +471,6 @@ core_idl_files =
"typed_arrays/uint8_array.idl",
"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",
"workers/worker_location.idl",
@@ -523,8 +521,8 @@ core_idl_with_modules_dependency_files =
# interfaces with static bindings (in bindings/core/v8/)
core_dependency_idl_files =
get_path_info([
+ "animation/animatable.idl",
"animation/document_animation.idl",
- "animation/element_animation.idl",
"css/font_face_source.idl",
"css/property_registration.idl",
"css/cssom/css_unit_values.idl",
@@ -569,7 +567,6 @@ core_dependency_idl_files =
"timing/window_performance.idl",
"timing/worker_global_scope_performance.idl",
"workers/abstract_worker.idl",
- "workers/experimental/window_task_worklet.idl",
"xml/document_xpath_evaluator.idl",
],
"abspath")
@@ -698,10 +695,15 @@ core_dictionary_idl_files =
"mojo/mojo_write_data_result.idl",
"mojo/test/mojo_interface_request_event_init.idl",
"page/scrolling/scroll_state_init.idl",
+ "streams/queuing_strategy_init.idl",
"timing/performance_mark_options.idl",
"timing/performance_measure_options.idl",
"timing/performance_observer_init.idl",
+ "timing/profiler_frame.idl",
"timing/profiler_init_options.idl",
+ "timing/profiler_sample.idl",
+ "timing/profiler_stack.idl",
+ "timing/profiler_trace.idl",
"trustedtypes/trusted_type_policy_options.idl",
"workers/worker_options.idl",
"workers/worklet_options.idl",
diff --git a/chromium/third_party/blink/renderer/core/core_initializer.h b/chromium/third_party/blink/renderer/core/core_initializer.h
index 084f62e7e18..c0d14e20a49 100644
--- a/chromium/third_party/blink/renderer/core/core_initializer.h
+++ b/chromium/third_party/blink/renderer/core/core_initializer.h
@@ -35,7 +35,7 @@
#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"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/css/BUILD.gn b/chromium/third_party/blink/renderer/core/css/BUILD.gn
index 36dafd97444..927e68c5587 100644
--- a/chromium/third_party/blink/renderer/core/css/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/css/BUILD.gn
@@ -25,8 +25,6 @@ blink_core_sources("css") {
"css_border_image.h",
"css_border_image_slice_value.cc",
"css_border_image_slice_value.h",
- "css_calculation_value.cc",
- "css_calculation_value.h",
"css_color_value.cc",
"css_color_value.h",
"css_computed_style_declaration.cc",
@@ -102,16 +100,27 @@ blink_core_sources("css") {
"css_invalid_variable_value.h",
"css_keyframe_rule.cc",
"css_keyframe_rule.h",
+ "css_keyframe_shorthand_value.cc",
+ "css_keyframe_shorthand_value.h",
"css_keyframes_rule.cc",
"css_keyframes_rule.h",
"css_layout_function_value.cc",
"css_layout_function_value.h",
"css_markup.cc",
"css_markup.h",
+ "css_math_expression_node.cc",
+ "css_math_expression_node.h",
+ "css_math_function_value.cc",
+ "css_math_function_value.h",
+ "css_math_operator.cc",
+ "css_math_operator.h",
"css_media_rule.cc",
"css_media_rule.h",
"css_namespace_rule.cc",
"css_namespace_rule.h",
+ "css_numeric_literal_value.cc",
+ "css_numeric_literal_value.h",
+ "css_origin_clean.h",
"css_page_rule.cc",
"css_page_rule.h",
"css_paint_image_generator.cc",
@@ -120,6 +129,8 @@ blink_core_sources("css") {
"css_paint_value.h",
"css_path_value.cc",
"css_path_value.h",
+ "css_pending_interpolation_value.cc",
+ "css_pending_interpolation_value.h",
"css_pending_substitution_value.cc",
"css_pending_substitution_value.h",
"css_primitive_value.cc",
@@ -130,6 +141,8 @@ blink_core_sources("css") {
"css_property_id_templates.h",
"css_property_name.cc",
"css_property_name.h",
+ "css_property_rule.cc",
+ "css_property_rule.h",
"css_property_source_data.cc",
"css_property_source_data.h",
"css_property_value.cc",
@@ -168,7 +181,6 @@ 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",
@@ -422,6 +434,7 @@ blink_core_sources("css") {
"properties/computed_style_utils.h",
"properties/css_direction_aware_resolver.cc",
"properties/css_direction_aware_resolver.h",
+ "properties/css_exposure.h",
"properties/css_parsing_utils.cc",
"properties/css_parsing_utils.h",
"properties/css_property.cc",
@@ -477,10 +490,14 @@ blink_core_sources("css") {
"resolver/selector_filter_parent_scope.h",
"resolver/style_adjuster.cc",
"resolver/style_adjuster.h",
+ "resolver/style_animator.cc",
+ "resolver/style_animator.h",
"resolver/style_builder.cc",
"resolver/style_builder.h",
"resolver/style_builder_converter.cc",
"resolver/style_builder_converter.h",
+ "resolver/style_cascade.cc",
+ "resolver/style_cascade.h",
"resolver/style_resolver.cc",
"resolver/style_resolver.h",
"resolver/style_resolver_state.cc",
@@ -564,13 +581,14 @@ blink_core_tests("unit_tests") {
sources = [
"active_style_sheets_test.cc",
"affected_by_pseudo_test.cc",
- "css_calculation_value_test.cc",
"css_computed_style_declaration_test.cc",
"css_font_face_source_test.cc",
"css_gradient_value_test.cc",
"css_invalid_variable_value_test.cc",
+ "css_math_expression_node_test.cc",
"css_page_rule_test.cc",
"css_paint_value_test.cc",
+ "css_pending_interpolation_value_test.cc",
"css_primitive_value_test.cc",
"css_property_name_test.cc",
"css_property_value_set_test.cc",
@@ -610,8 +628,10 @@ blink_core_tests("unit_tests") {
"parser/media_condition_test.cc",
"parser/sizes_attribute_parser_test.cc",
"parser/sizes_calc_parser_test.cc",
+ "properties/css_exposure_test.cc",
"properties/css_parsing_utils_test.cc",
"properties/css_property_ref_test.cc",
+ "properties/css_property_test.cc",
"properties/longhands/custom_property_test.cc",
"resolver/css_variable_data_test.cc",
"resolver/css_variable_resolver_test.cc",
@@ -620,6 +640,8 @@ blink_core_tests("unit_tests") {
"resolver/match_result_test.cc",
"resolver/selector_filter_parent_scope_test.cc",
"resolver/style_adjuster_test.cc",
+ "resolver/style_cascade_test.cc",
+ "resolver/style_resolver_test.cc",
"rule_feature_set_test.cc",
"rule_set_test.cc",
"selector_query_test.cc",
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 50111ce3cd0..71b74cf2c96 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
@@ -170,6 +170,7 @@ AbstractPropertySetCSSStyleDeclaration::GetPropertyCSSValueInternal(
const CSSValue*
AbstractPropertySetCSSStyleDeclaration::GetPropertyCSSValueInternal(
AtomicString custom_property_name) {
+ DCHECK_EQ(CSSPropertyID::kVariable, cssPropertyID(custom_property_name));
return PropertySet().GetPropertyCSSValue(custom_property_name);
}
@@ -194,11 +195,11 @@ void AbstractPropertySetCSSStyleDeclaration::SetPropertyInternal(
AtomicString atomic_name(custom_property_name);
bool is_animation_tainted = IsKeyframeStyle();
- did_change = PropertySet()
- .SetProperty(atomic_name, GetPropertyRegistry(), value,
- important, secure_context_mode,
- ContextStyleSheet(), is_animation_tainted)
- .did_change;
+ did_change =
+ PropertySet()
+ .SetProperty(atomic_name, value, important, secure_context_mode,
+ ContextStyleSheet(), is_animation_tainted)
+ .did_change;
} else {
did_change = PropertySet()
.SetProperty(unresolved_property, value, important,
diff --git a/chromium/third_party/blink/renderer/core/css/abstract_property_set_css_style_declaration.h b/chromium/third_party/blink/renderer/core/css/abstract_property_set_css_style_declaration.h
index 0549d014bb6..e6e7d68239f 100644
--- a/chromium/third_party/blink/renderer/core/css/abstract_property_set_css_style_declaration.h
+++ b/chromium/third_party/blink/renderer/core/css/abstract_property_set_css_style_declaration.h
@@ -36,7 +36,6 @@ class Element;
class ExceptionState;
class ExecutionContext;
class MutableCSSPropertyValueSet;
-class PropertyRegistry;
class StyleSheetContents;
class AbstractPropertySetCSSStyleDeclaration : public CSSStyleDeclaration {
@@ -84,7 +83,6 @@ class AbstractPropertySetCSSStyleDeclaration : public CSSStyleDeclaration {
virtual void WillMutate() {}
virtual void DidMutate(MutationType) {}
virtual MutableCSSPropertyValueSet& PropertySet() const = 0;
- virtual PropertyRegistry* GetPropertyRegistry() const = 0;
virtual bool IsKeyframeStyle() const { return false; }
};
diff --git a/chromium/third_party/blink/renderer/core/css/basic_shape_functions.cc b/chromium/third_party/blink/renderer/core/css/basic_shape_functions.cc
index a9c160dd718..f6418d3e514 100644
--- a/chromium/third_party/blink/renderer/core/css/basic_shape_functions.cc
+++ b/chromium/third_party/blink/renderer/core/css/basic_shape_functions.cc
@@ -31,6 +31,7 @@
#include "third_party/blink/renderer/core/css/css_basic_shape_values.h"
#include "third_party/blink/renderer/core/css/css_identifier_value.h"
+#include "third_party/blink/renderer/core/css/css_numeric_literal_value.h"
#include "third_party/blink/renderer/core/css/css_primitive_value_mappings.h"
#include "third_party/blink/renderer/core/css/css_ray_value.h"
#include "third_party/blink/renderer/core/css/css_value_pair.h"
@@ -122,8 +123,8 @@ CSSValue* ValueForBasicShape(const ComputedStyle& style,
case BasicShape::kStyleRayType: {
const StyleRay& ray = To<StyleRay>(*basic_shape);
return MakeGarbageCollected<cssvalue::CSSRayValue>(
- *CSSPrimitiveValue::Create(ray.Angle(),
- CSSPrimitiveValue::UnitType::kDegrees),
+ *CSSNumericLiteralValue::Create(
+ ray.Angle(), CSSPrimitiveValue::UnitType::kDegrees),
*CSSIdentifierValue::Create(RaySizeToKeyword(ray.Size())),
(ray.Contain() ? CSSIdentifierValue::Create(CSSValueID::kContain)
: nullptr));
@@ -169,8 +170,10 @@ CSSValue* ValueForBasicShape(const ComputedStyle& style,
const Vector<Length>& values = polygon->Values();
for (unsigned i = 0; i < values.size(); i += 2) {
polygon_value->AppendPoint(
- CSSPrimitiveValue::Create(values.at(i), style.EffectiveZoom()),
- CSSPrimitiveValue::Create(values.at(i + 1), style.EffectiveZoom()));
+ CSSPrimitiveValue::CreateFromLength(values.at(i),
+ style.EffectiveZoom()),
+ CSSPrimitiveValue::CreateFromLength(values.at(i + 1),
+ style.EffectiveZoom()));
}
return polygon_value;
}
@@ -179,14 +182,14 @@ CSSValue* ValueForBasicShape(const ComputedStyle& style,
auto* inset_value =
MakeGarbageCollected<cssvalue::CSSBasicShapeInsetValue>();
- inset_value->SetTop(
- CSSPrimitiveValue::Create(inset->Top(), style.EffectiveZoom()));
- inset_value->SetRight(
- CSSPrimitiveValue::Create(inset->Right(), style.EffectiveZoom()));
- inset_value->SetBottom(
- CSSPrimitiveValue::Create(inset->Bottom(), style.EffectiveZoom()));
- inset_value->SetLeft(
- CSSPrimitiveValue::Create(inset->Left(), style.EffectiveZoom()));
+ inset_value->SetTop(CSSPrimitiveValue::CreateFromLength(
+ inset->Top(), style.EffectiveZoom()));
+ inset_value->SetRight(CSSPrimitiveValue::CreateFromLength(
+ inset->Right(), style.EffectiveZoom()));
+ inset_value->SetBottom(CSSPrimitiveValue::CreateFromLength(
+ inset->Bottom(), style.EffectiveZoom()));
+ inset_value->SetLeft(CSSPrimitiveValue::CreateFromLength(
+ inset->Left(), style.EffectiveZoom()));
inset_value->SetTopLeftRadius(
ValueForLengthSize(inset->TopLeftRadius(), style));
diff --git a/chromium/third_party/blink/renderer/core/css/css.dict b/chromium/third_party/blink/renderer/core/css/css.dict
index 350336a4629..9ace694a4fb 100644
--- a/chromium/third_party/blink/renderer/core/css/css.dict
+++ b/chromium/third_party/blink/renderer/core/css/css.dict
@@ -910,6 +910,7 @@
"no-preference"
"light"
"dark"
+"active"
# at-rules
"@charset"
diff --git a/chromium/third_party/blink/renderer/core/css/css_axis_value.cc b/chromium/third_party/blink/renderer/core/css/css_axis_value.cc
index b0183b89a66..81e2585e3f4 100644
--- a/chromium/third_party/blink/renderer/core/css/css_axis_value.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_axis_value.cc
@@ -5,6 +5,7 @@
#include "third_party/blink/renderer/core/css/css_axis_value.h"
#include "third_party/blink/renderer/core/css/css_identifier_value.h"
+#include "third_party/blink/renderer/core/css/css_numeric_literal_value.h"
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
@@ -32,9 +33,12 @@ CSSAxisValue::CSSAxisValue(CSSValueID axis_name)
default:
NOTREACHED();
}
- Append(*CSSPrimitiveValue::Create(x, CSSPrimitiveValue::UnitType::kNumber));
- Append(*CSSPrimitiveValue::Create(y, CSSPrimitiveValue::UnitType::kNumber));
- Append(*CSSPrimitiveValue::Create(z, CSSPrimitiveValue::UnitType::kNumber));
+ Append(
+ *CSSNumericLiteralValue::Create(x, CSSPrimitiveValue::UnitType::kNumber));
+ Append(
+ *CSSNumericLiteralValue::Create(y, CSSPrimitiveValue::UnitType::kNumber));
+ Append(
+ *CSSNumericLiteralValue::Create(z, CSSPrimitiveValue::UnitType::kNumber));
}
CSSAxisValue::CSSAxisValue(double x, double y, double z)
@@ -51,9 +55,12 @@ CSSAxisValue::CSSAxisValue(double x, double y, double z)
z = 1;
axis_name_ = CSSValueID::kZ;
}
- Append(*CSSPrimitiveValue::Create(x, CSSPrimitiveValue::UnitType::kNumber));
- Append(*CSSPrimitiveValue::Create(y, CSSPrimitiveValue::UnitType::kNumber));
- Append(*CSSPrimitiveValue::Create(z, CSSPrimitiveValue::UnitType::kNumber));
+ Append(
+ *CSSNumericLiteralValue::Create(x, CSSPrimitiveValue::UnitType::kNumber));
+ Append(
+ *CSSNumericLiteralValue::Create(y, CSSPrimitiveValue::UnitType::kNumber));
+ Append(
+ *CSSNumericLiteralValue::Create(z, CSSPrimitiveValue::UnitType::kNumber));
}
String CSSAxisValue::CustomCSSText() const {
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 2639c9edbe6..8c8aa51739e 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
@@ -30,6 +30,7 @@
#include "third_party/blink/renderer/core/css/css_basic_shape_values.h"
#include "third_party/blink/renderer/core/css/css_identifier_value.h"
+#include "third_party/blink/renderer/core/css/css_numeric_literal_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/geometry/length.h"
@@ -90,9 +91,9 @@ static CSSValuePair* BuildSerializablePositionOffset(CSSValue* offset,
if ((side == CSSValueID::kRight || side == CSSValueID::kBottom) &&
amount->IsPercentage()) {
side = default_side;
- amount =
- CSSPrimitiveValue::Create(100 - amount->GetFloatValue(),
- CSSPrimitiveValue::UnitType::kPercentage);
+ amount = CSSNumericLiteralValue::Create(
+ 100 - amount->GetFloatValue(),
+ CSSPrimitiveValue::UnitType::kPercentage);
}
} else {
amount = To<CSSPrimitiveValue>(offset);
@@ -100,14 +101,14 @@ static CSSValuePair* BuildSerializablePositionOffset(CSSValue* offset,
if (side == CSSValueID::kCenter) {
side = default_side;
- amount =
- CSSPrimitiveValue::Create(50, CSSPrimitiveValue::UnitType::kPercentage);
- } else if (!amount || (amount->IsLength() && !amount->GetFloatValue())) {
+ amount = CSSNumericLiteralValue::Create(
+ 50, CSSPrimitiveValue::UnitType::kPercentage);
+ } else if (!amount || (amount->IsLength() && amount->IsZero())) {
if (side == CSSValueID::kRight || side == CSSValueID::kBottom)
- amount = CSSPrimitiveValue::Create(
+ amount = CSSNumericLiteralValue::Create(
100, CSSPrimitiveValue::UnitType::kPercentage);
else
- amount = CSSPrimitiveValue::Create(
+ amount = CSSNumericLiteralValue::Create(
0, CSSPrimitiveValue::UnitType::kPercentage);
side = default_side;
}
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
deleted file mode 100644
index 53ae6c4121c..00000000000
--- a/chromium/third_party/blink/renderer/core/css/css_calculation_value.cc
+++ /dev/null
@@ -1,865 +0,0 @@
-/*
- * Copyright (C) 2011, 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/core/css/css_calculation_value.h"
-
-#include "third_party/blink/renderer/core/css/css_primitive_value_mappings.h"
-#include "third_party/blink/renderer/core/css/resolver/style_resolver.h"
-#include "third_party/blink/renderer/platform/wtf/math_extras.h"
-#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
-
-static const int maxExpressionDepth = 100;
-
-enum ParseState { OK, TooDeep, NoMoreTokens };
-
-namespace blink {
-
-static CalculationCategory UnitCategory(CSSPrimitiveValue::UnitType type) {
- switch (type) {
- case CSSPrimitiveValue::UnitType::kNumber:
- case CSSPrimitiveValue::UnitType::kInteger:
- return kCalcNumber;
- case CSSPrimitiveValue::UnitType::kPercentage:
- return kCalcPercent;
- case CSSPrimitiveValue::UnitType::kEms:
- case CSSPrimitiveValue::UnitType::kExs:
- case CSSPrimitiveValue::UnitType::kPixels:
- case CSSPrimitiveValue::UnitType::kCentimeters:
- case CSSPrimitiveValue::UnitType::kMillimeters:
- case CSSPrimitiveValue::UnitType::kQuarterMillimeters:
- case CSSPrimitiveValue::UnitType::kInches:
- case CSSPrimitiveValue::UnitType::kPoints:
- case CSSPrimitiveValue::UnitType::kPicas:
- case CSSPrimitiveValue::UnitType::kUserUnits:
- case CSSPrimitiveValue::UnitType::kRems:
- case CSSPrimitiveValue::UnitType::kChs:
- case CSSPrimitiveValue::UnitType::kViewportWidth:
- case CSSPrimitiveValue::UnitType::kViewportHeight:
- case CSSPrimitiveValue::UnitType::kViewportMin:
- case CSSPrimitiveValue::UnitType::kViewportMax:
- return kCalcLength;
- case CSSPrimitiveValue::UnitType::kDegrees:
- case CSSPrimitiveValue::UnitType::kGradians:
- case CSSPrimitiveValue::UnitType::kRadians:
- case CSSPrimitiveValue::UnitType::kTurns:
- return kCalcAngle;
- case CSSPrimitiveValue::UnitType::kMilliseconds:
- case CSSPrimitiveValue::UnitType::kSeconds:
- return kCalcTime;
- case CSSPrimitiveValue::UnitType::kHertz:
- case CSSPrimitiveValue::UnitType::kKilohertz:
- return kCalcFrequency;
- default:
- return kCalcOther;
- }
-}
-
-static bool HasDoubleValue(CSSPrimitiveValue::UnitType type) {
- switch (type) {
- case CSSPrimitiveValue::UnitType::kNumber:
- case CSSPrimitiveValue::UnitType::kPercentage:
- case CSSPrimitiveValue::UnitType::kEms:
- case CSSPrimitiveValue::UnitType::kExs:
- case CSSPrimitiveValue::UnitType::kChs:
- case CSSPrimitiveValue::UnitType::kRems:
- case CSSPrimitiveValue::UnitType::kPixels:
- case CSSPrimitiveValue::UnitType::kCentimeters:
- case CSSPrimitiveValue::UnitType::kMillimeters:
- case CSSPrimitiveValue::UnitType::kQuarterMillimeters:
- case CSSPrimitiveValue::UnitType::kInches:
- case CSSPrimitiveValue::UnitType::kPoints:
- case CSSPrimitiveValue::UnitType::kPicas:
- case CSSPrimitiveValue::UnitType::kUserUnits:
- case CSSPrimitiveValue::UnitType::kDegrees:
- case CSSPrimitiveValue::UnitType::kRadians:
- case CSSPrimitiveValue::UnitType::kGradians:
- case CSSPrimitiveValue::UnitType::kTurns:
- case CSSPrimitiveValue::UnitType::kMilliseconds:
- case CSSPrimitiveValue::UnitType::kSeconds:
- case CSSPrimitiveValue::UnitType::kHertz:
- case CSSPrimitiveValue::UnitType::kKilohertz:
- case CSSPrimitiveValue::UnitType::kViewportWidth:
- case CSSPrimitiveValue::UnitType::kViewportHeight:
- case CSSPrimitiveValue::UnitType::kViewportMin:
- case CSSPrimitiveValue::UnitType::kViewportMax:
- case CSSPrimitiveValue::UnitType::kDotsPerPixel:
- case CSSPrimitiveValue::UnitType::kDotsPerInch:
- case CSSPrimitiveValue::UnitType::kDotsPerCentimeter:
- case CSSPrimitiveValue::UnitType::kFraction:
- case CSSPrimitiveValue::UnitType::kInteger:
- return true;
- case CSSPrimitiveValue::UnitType::kUnknown:
- case CSSPrimitiveValue::UnitType::kCalc:
- case CSSPrimitiveValue::UnitType::kCalcPercentageWithNumber:
- case CSSPrimitiveValue::UnitType::kCalcPercentageWithLength:
- case CSSPrimitiveValue::UnitType::kCalcLengthWithNumber:
- case CSSPrimitiveValue::UnitType::kCalcPercentageWithLengthAndNumber:
- case CSSPrimitiveValue::UnitType::kQuirkyEms:
- return false;
- };
- NOTREACHED();
- return false;
-}
-
-static String BuildCSSText(const String& expression) {
- StringBuilder result;
- result.Append("calc");
- bool expression_has_single_term = expression[0] != '(';
- if (expression_has_single_term)
- result.Append('(');
- result.Append(expression);
- if (expression_has_single_term)
- result.Append(')');
- return result.ToString();
-}
-
-String CSSCalcValue::CustomCSSText() const {
- return BuildCSSText(expression_->CustomCSSText());
-}
-
-bool CSSCalcValue::Equals(const CSSCalcValue& other) const {
- return DataEquivalent(expression_, other.expression_);
-}
-
-double CSSCalcValue::ClampToPermittedRange(double value) const {
- return non_negative_ && value < 0 ? 0 : value;
-}
-
-double CSSCalcValue::DoubleValue() const {
- return ClampToPermittedRange(expression_->DoubleValue());
-}
-
-double CSSCalcValue::ComputeLengthPx(
- const CSSToLengthConversionData& conversion_data) const {
- return ClampToPermittedRange(expression_->ComputeLengthPx(conversion_data));
-}
-
-class CSSCalcPrimitiveValue final : public CSSCalcExpressionNode {
- public:
- static CSSCalcPrimitiveValue* Create(CSSPrimitiveValue* value,
- bool is_integer) {
- return MakeGarbageCollected<CSSCalcPrimitiveValue>(value, is_integer);
- }
-
- static CSSCalcPrimitiveValue* Create(double value,
- CSSPrimitiveValue::UnitType type,
- bool is_integer) {
- if (std::isnan(value) || std::isinf(value))
- return nullptr;
- 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(); }
-
- void AccumulatePixelsAndPercent(
- const CSSToLengthConversionData& conversion_data,
- PixelsAndPercent& value,
- float multiplier) const override {
- switch (category_) {
- case kCalcLength:
- value.pixels = clampTo<float>(
- value.pixels +
- value_->ComputeLength<double>(conversion_data) * multiplier);
- break;
- case kCalcPercent:
- DCHECK(value_->IsPercentage());
- value.percent = clampTo<float>(value.percent +
- value_->GetDoubleValue() * multiplier);
- break;
- case kCalcNumber:
- // TODO(alancutter): Stop treating numbers like pixels unconditionally
- // in calcs to be able to accomodate border-image-width
- // https://drafts.csswg.org/css-backgrounds-3/#the-border-image-width
- value.pixels = clampTo<float>(value.pixels +
- value_->GetDoubleValue() *
- conversion_data.Zoom() * multiplier);
- break;
- default:
- NOTREACHED();
- }
- }
-
- double DoubleValue() const override {
- if (HasDoubleValue(TypeWithCalcResolved()))
- return value_->GetDoubleValue();
- NOTREACHED();
- return 0;
- }
-
- double ComputeLengthPx(
- const CSSToLengthConversionData& conversion_data) const override {
- switch (category_) {
- case kCalcLength:
- return value_->ComputeLength<double>(conversion_data);
- case kCalcNumber:
- case kCalcPercent:
- return value_->GetDoubleValue();
- case kCalcAngle:
- case kCalcFrequency:
- case kCalcPercentLength:
- case kCalcPercentNumber:
- case kCalcTime:
- case kCalcLengthNumber:
- case kCalcPercentLengthNumber:
- case kCalcOther:
- NOTREACHED();
- break;
- }
- NOTREACHED();
- return 0;
- }
-
- void AccumulateLengthArray(CSSLengthArray& length_array,
- double multiplier) const override {
- DCHECK_NE(Category(), kCalcNumber);
- value_->AccumulateLengthArray(length_array, multiplier);
- }
-
- bool operator==(const CSSCalcExpressionNode& other) const override {
- if (GetType() != other.GetType())
- return false;
-
- return DataEquivalent(
- value_, static_cast<const CSSCalcPrimitiveValue&>(other).value_);
- }
-
- Type GetType() const override { return kCssCalcPrimitiveValue; }
- CSSPrimitiveValue::UnitType TypeWithCalcResolved() const override {
- return value_->TypeWithCalcResolved();
- }
- const CSSCalcExpressionNode* LeftExpressionNode() const override {
- NOTREACHED();
- return nullptr;
- }
-
- const CSSCalcExpressionNode* RightExpressionNode() const override {
- NOTREACHED();
- return nullptr;
- }
-
- CalcOperator OperatorType() const override {
- NOTREACHED();
- return kCalcAdd;
- }
-
- void Trace(blink::Visitor* visitor) override {
- visitor->Trace(value_);
- CSSCalcExpressionNode::Trace(visitor);
- }
-
- private:
- Member<CSSPrimitiveValue> value_;
-};
-
-static const CalculationCategory kAddSubtractResult[kCalcOther][kCalcOther] = {
- /* CalcNumber */ {kCalcNumber, kCalcLengthNumber, kCalcPercentNumber,
- kCalcPercentNumber, kCalcOther, kCalcOther, kCalcOther,
- kCalcOther, kCalcLengthNumber, kCalcPercentLengthNumber},
- /* CalcLength */
- {kCalcLengthNumber, kCalcLength, kCalcPercentLength, kCalcOther,
- kCalcPercentLength, kCalcOther, kCalcOther, kCalcOther, kCalcLengthNumber,
- kCalcPercentLengthNumber},
- /* CalcPercent */
- {kCalcPercentNumber, kCalcPercentLength, kCalcPercent, kCalcPercentNumber,
- kCalcPercentLength, kCalcOther, kCalcOther, kCalcOther,
- kCalcPercentLengthNumber, kCalcPercentLengthNumber},
- /* CalcPercentNumber */
- {kCalcPercentNumber, kCalcPercentLengthNumber, kCalcPercentNumber,
- kCalcPercentNumber, kCalcPercentLengthNumber, kCalcOther, kCalcOther,
- kCalcOther, kCalcOther, kCalcPercentLengthNumber},
- /* CalcPercentLength */
- {kCalcPercentLengthNumber, kCalcPercentLength, kCalcPercentLength,
- kCalcPercentLengthNumber, kCalcPercentLength, kCalcOther, kCalcOther,
- kCalcOther, kCalcOther, kCalcPercentLengthNumber},
- /* CalcAngle */
- {kCalcOther, kCalcOther, kCalcOther, kCalcOther, kCalcOther, kCalcAngle,
- kCalcOther, kCalcOther, kCalcOther, kCalcOther},
- /* CalcTime */
- {kCalcOther, kCalcOther, kCalcOther, kCalcOther, kCalcOther, kCalcOther,
- kCalcTime, kCalcOther, kCalcOther, kCalcOther},
- /* CalcFrequency */
- {kCalcOther, kCalcOther, kCalcOther, kCalcOther, kCalcOther, kCalcOther,
- kCalcOther, kCalcFrequency, kCalcOther, kCalcOther},
- /* CalcLengthNumber */
- {kCalcLengthNumber, kCalcLengthNumber, kCalcPercentLengthNumber,
- kCalcPercentLengthNumber, kCalcPercentLengthNumber, kCalcOther, kCalcOther,
- kCalcOther, kCalcLengthNumber, kCalcPercentLengthNumber},
- /* CalcPercentLengthNumber */
- {kCalcPercentLengthNumber, kCalcPercentLengthNumber,
- kCalcPercentLengthNumber, kCalcPercentLengthNumber,
- kCalcPercentLengthNumber, kCalcOther, kCalcOther, kCalcOther,
- kCalcPercentLengthNumber, kCalcPercentLengthNumber}};
-
-static CalculationCategory DetermineCategory(
- const CSSCalcExpressionNode& left_side,
- const CSSCalcExpressionNode& right_side,
- CalcOperator op) {
- CalculationCategory left_category = left_side.Category();
- CalculationCategory right_category = right_side.Category();
-
- if (left_category == kCalcOther || right_category == kCalcOther)
- return kCalcOther;
-
- switch (op) {
- case kCalcAdd:
- case kCalcSubtract:
- return kAddSubtractResult[left_category][right_category];
- case kCalcMultiply:
- if (left_category != kCalcNumber && right_category != kCalcNumber)
- return kCalcOther;
- return left_category == kCalcNumber ? right_category : left_category;
- case kCalcDivide:
- if (right_category != kCalcNumber || right_side.IsZero())
- return kCalcOther;
- return left_category;
- }
-
- NOTREACHED();
- return kCalcOther;
-}
-
-static bool IsIntegerResult(const CSSCalcExpressionNode* left_side,
- const CSSCalcExpressionNode* right_side,
- CalcOperator op) {
- // Not testing for actual integer values.
- // Performs W3C spec's type checking for calc integers.
- // http://www.w3.org/TR/css3-values/#calc-type-checking
- return op != kCalcDivide && left_side->IsInteger() && right_side->IsInteger();
-}
-
-class CSSCalcBinaryOperation final : public CSSCalcExpressionNode {
- public:
- static CSSCalcExpressionNode* Create(CSSCalcExpressionNode* left_side,
- CSSCalcExpressionNode* right_side,
- CalcOperator op) {
- DCHECK_NE(left_side->Category(), kCalcOther);
- DCHECK_NE(right_side->Category(), kCalcOther);
-
- CalculationCategory new_category =
- DetermineCategory(*left_side, *right_side, op);
- if (new_category == kCalcOther)
- return nullptr;
-
- return MakeGarbageCollected<CSSCalcBinaryOperation>(left_side, right_side,
- op, new_category);
- }
-
- static CSSCalcExpressionNode* CreateSimplified(
- CSSCalcExpressionNode* left_side,
- CSSCalcExpressionNode* right_side,
- CalcOperator op) {
- CalculationCategory left_category = left_side->Category();
- CalculationCategory right_category = right_side->Category();
- DCHECK_NE(left_category, kCalcOther);
- DCHECK_NE(right_category, kCalcOther);
-
- bool is_integer = IsIntegerResult(left_side, right_side, op);
-
- // Simplify numbers.
- if (left_category == kCalcNumber && right_category == kCalcNumber) {
- return CSSCalcPrimitiveValue::Create(
- EvaluateOperator(left_side->DoubleValue(), right_side->DoubleValue(),
- op),
- CSSPrimitiveValue::UnitType::kNumber, is_integer);
- }
-
- // Simplify addition and subtraction between same types.
- if (op == kCalcAdd || op == kCalcSubtract) {
- if (left_category == right_side->Category()) {
- CSSPrimitiveValue::UnitType left_type =
- left_side->TypeWithCalcResolved();
- if (HasDoubleValue(left_type)) {
- CSSPrimitiveValue::UnitType right_type =
- right_side->TypeWithCalcResolved();
- if (left_type == right_type)
- return CSSCalcPrimitiveValue::Create(
- EvaluateOperator(left_side->DoubleValue(),
- right_side->DoubleValue(), op),
- left_type, is_integer);
- CSSPrimitiveValue::UnitCategory left_unit_category =
- CSSPrimitiveValue::UnitTypeToUnitCategory(left_type);
- if (left_unit_category != CSSPrimitiveValue::kUOther &&
- left_unit_category ==
- CSSPrimitiveValue::UnitTypeToUnitCategory(right_type)) {
- CSSPrimitiveValue::UnitType canonical_type =
- CSSPrimitiveValue::CanonicalUnitTypeForCategory(
- left_unit_category);
- if (canonical_type != CSSPrimitiveValue::UnitType::kUnknown) {
- double left_value = clampTo<double>(
- left_side->DoubleValue() *
- CSSPrimitiveValue::ConversionToCanonicalUnitsScaleFactor(
- left_type));
- double right_value = clampTo<double>(
- right_side->DoubleValue() *
- CSSPrimitiveValue::ConversionToCanonicalUnitsScaleFactor(
- right_type));
- return CSSCalcPrimitiveValue::Create(
- EvaluateOperator(left_value, right_value, op), canonical_type,
- is_integer);
- }
- }
- }
- }
- } else {
- // Simplify multiplying or dividing by a number for simplifiable types.
- DCHECK(op == kCalcMultiply || op == kCalcDivide);
- CSSCalcExpressionNode* number_side = GetNumberSide(left_side, right_side);
- if (!number_side)
- return Create(left_side, right_side, op);
- if (number_side == left_side && op == kCalcDivide)
- return nullptr;
- CSSCalcExpressionNode* other_side =
- left_side == number_side ? right_side : left_side;
-
- double number = number_side->DoubleValue();
- if (std::isnan(number) || std::isinf(number))
- return nullptr;
- if (op == kCalcDivide && !number)
- return nullptr;
-
- CSSPrimitiveValue::UnitType other_type =
- other_side->TypeWithCalcResolved();
- if (HasDoubleValue(other_type))
- return CSSCalcPrimitiveValue::Create(
- EvaluateOperator(other_side->DoubleValue(), number, op), other_type,
- is_integer);
- }
-
- 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(
- const CSSToLengthConversionData& conversion_data,
- PixelsAndPercent& value,
- float multiplier) const override {
- switch (operator_) {
- case kCalcAdd:
- left_side_->AccumulatePixelsAndPercent(conversion_data, value,
- multiplier);
- right_side_->AccumulatePixelsAndPercent(conversion_data, value,
- multiplier);
- break;
- case kCalcSubtract:
- left_side_->AccumulatePixelsAndPercent(conversion_data, value,
- multiplier);
- right_side_->AccumulatePixelsAndPercent(conversion_data, value,
- -multiplier);
- break;
- case kCalcMultiply:
- DCHECK_NE((left_side_->Category() == kCalcNumber),
- (right_side_->Category() == kCalcNumber));
- if (left_side_->Category() == kCalcNumber)
- right_side_->AccumulatePixelsAndPercent(
- conversion_data, value, multiplier * left_side_->DoubleValue());
- else
- left_side_->AccumulatePixelsAndPercent(
- conversion_data, value, multiplier * right_side_->DoubleValue());
- break;
- case kCalcDivide:
- DCHECK_EQ(right_side_->Category(), kCalcNumber);
- left_side_->AccumulatePixelsAndPercent(
- conversion_data, value, multiplier / right_side_->DoubleValue());
- break;
- default:
- NOTREACHED();
- }
- }
-
- double DoubleValue() const override {
- return Evaluate(left_side_->DoubleValue(), right_side_->DoubleValue());
- }
-
- double ComputeLengthPx(
- const CSSToLengthConversionData& conversion_data) const override {
- const double left_value = left_side_->ComputeLengthPx(conversion_data);
- const double right_value = right_side_->ComputeLengthPx(conversion_data);
- return Evaluate(left_value, right_value);
- }
-
- void AccumulateLengthArray(CSSLengthArray& length_array,
- double multiplier) const override {
- switch (operator_) {
- case kCalcAdd:
- left_side_->AccumulateLengthArray(length_array, multiplier);
- right_side_->AccumulateLengthArray(length_array, multiplier);
- break;
- case kCalcSubtract:
- left_side_->AccumulateLengthArray(length_array, multiplier);
- right_side_->AccumulateLengthArray(length_array, -multiplier);
- break;
- case kCalcMultiply:
- DCHECK_NE((left_side_->Category() == kCalcNumber),
- (right_side_->Category() == kCalcNumber));
- if (left_side_->Category() == kCalcNumber)
- right_side_->AccumulateLengthArray(
- length_array, multiplier * left_side_->DoubleValue());
- else
- left_side_->AccumulateLengthArray(
- length_array, multiplier * right_side_->DoubleValue());
- break;
- case kCalcDivide:
- DCHECK_EQ(right_side_->Category(), kCalcNumber);
- left_side_->AccumulateLengthArray(
- length_array, multiplier / right_side_->DoubleValue());
- break;
- default:
- NOTREACHED();
- }
- }
-
- static String BuildCSSText(const String& left_expression,
- const String& right_expression,
- CalcOperator op) {
- StringBuilder result;
- result.Append('(');
- result.Append(left_expression);
- result.Append(' ');
- result.Append(static_cast<char>(op));
- result.Append(' ');
- result.Append(right_expression);
- result.Append(')');
-
- return result.ToString();
- }
-
- String CustomCSSText() const override {
- return BuildCSSText(left_side_->CustomCSSText(),
- right_side_->CustomCSSText(), operator_);
- }
-
- bool operator==(const CSSCalcExpressionNode& exp) const override {
- if (GetType() != exp.GetType())
- return false;
-
- const CSSCalcBinaryOperation& other =
- static_cast<const CSSCalcBinaryOperation&>(exp);
- return DataEquivalent(left_side_, other.left_side_) &&
- DataEquivalent(right_side_, other.right_side_) &&
- operator_ == other.operator_;
- }
-
- Type GetType() const override { return kCssCalcBinaryOperation; }
- const CSSCalcExpressionNode* LeftExpressionNode() const override {
- return left_side_;
- }
-
- const CSSCalcExpressionNode* RightExpressionNode() const override {
- return right_side_;
- }
-
- CalcOperator OperatorType() const override { return operator_; }
-
- CSSPrimitiveValue::UnitType TypeWithCalcResolved() const override {
- switch (category_) {
- case kCalcNumber:
- DCHECK_EQ(left_side_->Category(), kCalcNumber);
- DCHECK_EQ(right_side_->Category(), kCalcNumber);
- return CSSPrimitiveValue::UnitType::kNumber;
- case kCalcLength:
- case kCalcPercent: {
- if (left_side_->Category() == kCalcNumber)
- return right_side_->TypeWithCalcResolved();
- if (right_side_->Category() == kCalcNumber)
- return left_side_->TypeWithCalcResolved();
- CSSPrimitiveValue::UnitType left_type =
- left_side_->TypeWithCalcResolved();
- if (left_type == right_side_->TypeWithCalcResolved())
- return left_type;
- return CSSPrimitiveValue::UnitType::kUnknown;
- }
- case kCalcAngle:
- return CSSPrimitiveValue::UnitType::kDegrees;
- case kCalcTime:
- return CSSPrimitiveValue::UnitType::kMilliseconds;
- case kCalcFrequency:
- return CSSPrimitiveValue::UnitType::kHertz;
- case kCalcPercentLength:
- case kCalcPercentNumber:
- case kCalcLengthNumber:
- case kCalcPercentLengthNumber:
- case kCalcOther:
- return CSSPrimitiveValue::UnitType::kUnknown;
- }
- NOTREACHED();
- return CSSPrimitiveValue::UnitType::kUnknown;
- }
-
- void Trace(blink::Visitor* visitor) override {
- visitor->Trace(left_side_);
- visitor->Trace(right_side_);
- CSSCalcExpressionNode::Trace(visitor);
- }
-
- private:
- static CSSCalcExpressionNode* GetNumberSide(
- CSSCalcExpressionNode* left_side,
- CSSCalcExpressionNode* right_side) {
- if (left_side->Category() == kCalcNumber)
- return left_side;
- if (right_side->Category() == kCalcNumber)
- return right_side;
- return nullptr;
- }
-
- double Evaluate(double left_side, double right_side) const {
- return EvaluateOperator(left_side, right_side, operator_);
- }
-
- static double EvaluateOperator(double left_value,
- double right_value,
- CalcOperator op) {
- switch (op) {
- case kCalcAdd:
- return clampTo<double>(left_value + right_value);
- case kCalcSubtract:
- return clampTo<double>(left_value - right_value);
- case kCalcMultiply:
- return clampTo<double>(left_value * right_value);
- case kCalcDivide:
- if (right_value)
- return clampTo<double>(left_value / right_value);
- return std::numeric_limits<double>::quiet_NaN();
- }
- return 0;
- }
-
- const Member<CSSCalcExpressionNode> left_side_;
- const Member<CSSCalcExpressionNode> right_side_;
- const CalcOperator operator_;
-};
-
-static ParseState CheckDepthAndIndex(int* depth, CSSParserTokenRange tokens) {
- (*depth)++;
- if (tokens.AtEnd())
- return NoMoreTokens;
- if (*depth > maxExpressionDepth)
- return TooDeep;
- return OK;
-}
-
-class CSSCalcExpressionNodeParser {
- STACK_ALLOCATED();
-
- public:
- CSSCalcExpressionNodeParser() {}
-
- CSSCalcExpressionNode* ParseCalc(CSSParserTokenRange tokens) {
- Value result;
- tokens.ConsumeWhitespace();
- bool ok = ParseValueExpression(tokens, 0, &result);
- if (!ok || !tokens.AtEnd())
- return nullptr;
- return result.value;
- }
-
- private:
- struct Value {
- STACK_ALLOCATED();
-
- public:
- Member<CSSCalcExpressionNode> value;
- };
-
- char OperatorValue(const CSSParserToken& token) {
- if (token.GetType() == kDelimiterToken)
- return token.Delimiter();
- return 0;
- }
-
- bool ParseValue(CSSParserTokenRange& tokens, Value* result) {
- CSSParserToken token = tokens.ConsumeIncludingWhitespace();
- if (!(token.GetType() == kNumberToken ||
- token.GetType() == kPercentageToken ||
- token.GetType() == kDimensionToken))
- return false;
-
- CSSPrimitiveValue::UnitType type = token.GetUnitType();
- if (UnitCategory(type) == kCalcOther)
- return false;
-
- result->value = CSSCalcPrimitiveValue::Create(
- CSSPrimitiveValue::Create(token.NumericValue(), type),
- token.GetNumericValueType() == kIntegerValueType);
-
- return true;
- }
-
- bool ParseValueTerm(CSSParserTokenRange& tokens, int depth, Value* result) {
- if (CheckDepthAndIndex(&depth, tokens) != OK)
- return false;
-
- if (tokens.Peek().GetType() == kLeftParenthesisToken ||
- tokens.Peek().FunctionId() == CSSValueID::kCalc) {
- CSSParserTokenRange inner_range = tokens.ConsumeBlock();
- tokens.ConsumeWhitespace();
- inner_range.ConsumeWhitespace();
- if (!ParseValueExpression(inner_range, depth, result))
- return false;
- result->value->SetIsNestedCalc();
- return true;
- }
-
- return ParseValue(tokens, result);
- }
-
- bool ParseValueMultiplicativeExpression(CSSParserTokenRange& tokens,
- int depth,
- Value* result) {
- if (CheckDepthAndIndex(&depth, tokens) != OK)
- return false;
-
- if (!ParseValueTerm(tokens, depth, result))
- return false;
-
- while (!tokens.AtEnd()) {
- char operator_character = OperatorValue(tokens.Peek());
- if (operator_character != kCalcMultiply &&
- operator_character != kCalcDivide)
- break;
- tokens.ConsumeIncludingWhitespace();
-
- Value rhs;
- if (!ParseValueTerm(tokens, depth, &rhs))
- return false;
-
- result->value = CSSCalcBinaryOperation::CreateSimplified(
- result->value, rhs.value,
- static_cast<CalcOperator>(operator_character));
-
- if (!result->value)
- return false;
- }
-
- return true;
- }
-
- bool ParseAdditiveValueExpression(CSSParserTokenRange& tokens,
- int depth,
- Value* result) {
- if (CheckDepthAndIndex(&depth, tokens) != OK)
- return false;
-
- if (!ParseValueMultiplicativeExpression(tokens, depth, result))
- return false;
-
- while (!tokens.AtEnd()) {
- char operator_character = OperatorValue(tokens.Peek());
- if (operator_character != kCalcAdd && operator_character != kCalcSubtract)
- break;
- if ((&tokens.Peek() - 1)->GetType() != kWhitespaceToken)
- return false; // calc(1px+ 2px) is invalid
- tokens.Consume();
- if (tokens.Peek().GetType() != kWhitespaceToken)
- return false; // calc(1px +2px) is invalid
- tokens.ConsumeIncludingWhitespace();
-
- Value rhs;
- if (!ParseValueMultiplicativeExpression(tokens, depth, &rhs))
- return false;
-
- result->value = CSSCalcBinaryOperation::CreateSimplified(
- result->value, rhs.value,
- static_cast<CalcOperator>(operator_character));
-
- if (!result->value)
- return false;
- }
-
- return true;
- }
-
- bool ParseValueExpression(CSSParserTokenRange& tokens,
- int depth,
- Value* result) {
- return ParseAdditiveValueExpression(tokens, depth, result);
- }
-};
-
-CSSCalcExpressionNode* CSSCalcValue::CreateExpressionNode(
- CSSPrimitiveValue* value,
- bool is_integer) {
- return CSSCalcPrimitiveValue::Create(value, is_integer);
-}
-
-CSSCalcExpressionNode* CSSCalcValue::CreateExpressionNode(
- CSSCalcExpressionNode* left_side,
- CSSCalcExpressionNode* right_side,
- CalcOperator op) {
- return CSSCalcBinaryOperation::Create(left_side, right_side, op);
-}
-
-CSSCalcExpressionNode* CSSCalcValue::CreateExpressionNode(double pixels,
- double percent) {
- return CreateExpressionNode(
- CreateExpressionNode(
- CSSPrimitiveValue::Create(percent,
- CSSPrimitiveValue::UnitType::kPercentage),
- percent == trunc(percent)),
- CreateExpressionNode(CSSPrimitiveValue::Create(
- pixels, CSSPrimitiveValue::UnitType::kPixels),
- pixels == trunc(pixels)),
- kCalcAdd);
-}
-
-CSSCalcValue* CSSCalcValue::Create(const CSSParserTokenRange& tokens,
- ValueRange range) {
- CSSCalcExpressionNodeParser parser;
- CSSCalcExpressionNode* expression = parser.ParseCalc(tokens);
-
- return expression ? MakeGarbageCollected<CSSCalcValue>(expression, range)
- : nullptr;
-}
-
-CSSCalcValue* CSSCalcValue::Create(CSSCalcExpressionNode* expression,
- ValueRange 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
deleted file mode 100644
index 609924e4964..00000000000
--- a/chromium/third_party/blink/renderer/core/css/css_calculation_value.h
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
- * Copyright (C) 2011, 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_CORE_CSS_CSS_CALCULATION_VALUE_H_
-#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_CALCULATION_VALUE_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_value.h"
-#include "third_party/blink/renderer/core/css/parser/css_parser_token_range.h"
-#include "third_party/blink/renderer/platform/geometry/calculation_value.h"
-#include "third_party/blink/renderer/platform/wtf/forward.h"
-
-namespace blink {
-
-class CalculationValue;
-
-enum CalcOperator {
- kCalcAdd = '+',
- kCalcSubtract = '-',
- kCalcMultiply = '*',
- kCalcDivide = '/'
-};
-
-// The order of this enum should not change since its elements are used as
-// indices in the addSubtractResult matrix.
-enum CalculationCategory {
- kCalcNumber = 0,
- kCalcLength,
- kCalcPercent,
- kCalcPercentNumber,
- kCalcPercentLength,
- kCalcAngle,
- kCalcTime,
- kCalcFrequency,
- kCalcLengthNumber,
- kCalcPercentLengthNumber,
- kCalcOther
-};
-
-class CSSCalcExpressionNode : public GarbageCollected<CSSCalcExpressionNode> {
- public:
- enum Type { kCssCalcPrimitiveValue = 1, kCssCalcBinaryOperation };
-
- virtual bool IsZero() const = 0;
- virtual double DoubleValue() const = 0;
- virtual double ComputeLengthPx(const CSSToLengthConversionData&) const = 0;
- virtual void AccumulateLengthArray(CSSLengthArray&,
- double multiplier) const = 0;
- virtual void AccumulatePixelsAndPercent(const CSSToLengthConversionData&,
- PixelsAndPercent&,
- float multiplier = 1) const = 0;
- virtual String CustomCSSText() const = 0;
- virtual bool operator==(const CSSCalcExpressionNode& other) const {
- return category_ == other.category_ && is_integer_ == other.is_integer_;
- }
- virtual Type GetType() const = 0;
- virtual const CSSCalcExpressionNode* LeftExpressionNode() const = 0;
- virtual const CSSCalcExpressionNode* RightExpressionNode() const = 0;
- virtual CalcOperator OperatorType() const = 0;
-
- CalculationCategory Category() const { return category_; }
- virtual CSSPrimitiveValue::UnitType TypeWithCalcResolved() const = 0;
- bool IsInteger() const { return is_integer_; }
-
- bool IsNestedCalc() const { return is_nested_calc_; }
- void SetIsNestedCalc() { is_nested_calc_ = true; }
-
- virtual void Trace(blink::Visitor* visitor) {}
-
- protected:
- CSSCalcExpressionNode(CalculationCategory category, bool is_integer)
- : category_(category), is_integer_(is_integer) {
- DCHECK_NE(category, kCalcOther);
- }
-
- CalculationCategory category_;
- bool is_integer_;
- bool is_nested_calc_ = false;
-};
-
-class CORE_EXPORT CSSCalcValue : public GarbageCollected<CSSCalcValue> {
- public:
- static CSSCalcValue* Create(const CSSParserTokenRange&, ValueRange);
- static CSSCalcValue* Create(CSSCalcExpressionNode*,
- ValueRange = kValueRangeAll);
-
- static CSSCalcExpressionNode* CreateExpressionNode(CSSPrimitiveValue*,
- bool is_integer = false);
- static CSSCalcExpressionNode* CreateExpressionNode(CSSCalcExpressionNode*,
- CSSCalcExpressionNode*,
- CalcOperator);
- 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);
- expression_->AccumulatePixelsAndPercent(conversion_data, value);
- return CalculationValue::Create(
- value, non_negative_ ? kValueRangeNonNegative : kValueRangeAll);
- }
- CalculationCategory Category() const { return expression_->Category(); }
- bool IsInt() const { return expression_->IsInteger(); }
- double DoubleValue() const;
- bool IsNegative() const { return expression_->DoubleValue() < 0; }
- ValueRange PermittedValueRange() {
- return non_negative_ ? kValueRangeNonNegative : kValueRangeAll;
- }
- double ComputeLengthPx(const CSSToLengthConversionData&) const;
- void AccumulateLengthArray(CSSLengthArray& length_array,
- double multiplier) const {
- expression_->AccumulateLengthArray(length_array, multiplier);
- }
- CSSCalcExpressionNode* ExpressionNode() const { return expression_.Get(); }
-
- String CustomCSSText() const;
- bool Equals(const CSSCalcValue&) const;
-
- void Trace(blink::Visitor* visitor) { visitor->Trace(expression_); }
-
- private:
- double ClampToPermittedRange(double) const;
-
- const Member<CSSCalcExpressionNode> expression_;
- const bool non_negative_;
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_CALCULATION_VALUE_H_
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 f8ebf9aa54c..9b5dbb5e3c8 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
@@ -39,12 +39,12 @@
#include "third_party/blink/renderer/core/css/zoom_adjusted_pixel_value.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"
#include "third_party/blink/renderer/core/html/html_frame_owner_element.h"
#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/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
namespace blink {
@@ -229,7 +229,7 @@ const Vector<const CSSProperty*>&
CSSComputedStyleDeclaration::ComputableProperties() {
DEFINE_STATIC_LOCAL(Vector<const CSSProperty*>, properties, ());
if (properties.IsEmpty()) {
- CSSProperty::FilterEnabledCSSPropertiesIntoVector(
+ CSSProperty::FilterWebExposedCSSPropertiesIntoVector(
kComputedPropertyArray, base::size(kComputedPropertyArray), properties);
}
return properties;
@@ -334,13 +334,18 @@ LayoutObject* CSSComputedStyleDeclaration::StyledLayoutObject() const {
}
const CSSValue* CSSComputedStyleDeclaration::GetPropertyCSSValue(
- AtomicString custom_property_name) const {
- Node* styled_node = StyledNode();
- if (!styled_node)
+ CSSPropertyID property_id) const {
+ if (property_id == CSSPropertyID::kVariable) {
+ // TODO(https://crbug.com/980160): Disallow calling this function with
+ // kVariable.
return nullptr;
+ }
+ return GetPropertyCSSValue(CSSPropertyName(property_id));
+}
- CSSPropertyRef ref(custom_property_name, styled_node->GetDocument());
- return GetPropertyCSSValue(ref.GetProperty());
+const CSSValue* CSSComputedStyleDeclaration::GetPropertyCSSValue(
+ AtomicString custom_property_name) const {
+ return GetPropertyCSSValue(CSSPropertyName(custom_property_name));
}
HeapHashMap<AtomicString, Member<const CSSValue>>
@@ -354,7 +359,7 @@ CSSComputedStyleDeclaration::GetVariables() const {
}
const CSSValue* CSSComputedStyleDeclaration::GetPropertyCSSValue(
- const CSSProperty& property_class) const {
+ const CSSPropertyName& property_name) const {
Node* styled_node = StyledNode();
if (!styled_node)
return nullptr;
@@ -370,7 +375,10 @@ const CSSValue* CSSComputedStyleDeclaration::GetPropertyCSSValue(
// TODO(futhark@chromium.org): There is an open question what the computed
// style should be in a display:none iframe. If the property we are querying
// is not layout dependent, we will not update the iframe layout box here.
- if (property_class.IsLayoutDependentProperty() ||
+ bool is_layout_dependent_property =
+ !property_name.IsCustomProperty() &&
+ CSSProperty::Get(property_name.Id()).IsLayoutDependentProperty();
+ if (is_layout_dependent_property ||
document.GetStyleEngine().HasViewportDependentMediaQueries()) {
owner->GetDocument().UpdateStyleAndLayout();
// The style recalc could have caused the styled node to be discarded or
@@ -381,6 +389,11 @@ const CSSValue* CSSComputedStyleDeclaration::GetPropertyCSSValue(
document.UpdateStyleAndLayoutTreeForNode(styled_node);
+ CSSPropertyRef ref(property_name, document);
+ if (!ref.IsValid())
+ return nullptr;
+ const CSSProperty& property_class = ref.GetProperty();
+
// The style recalc could have caused the styled node to be discarded or
// replaced if it was a PseudoElement so we need to update it.
styled_node = StyledNode();
@@ -415,7 +428,7 @@ String CSSComputedStyleDeclaration::GetPropertyValue(
node_->GetDocument(),
WebFeature::kGetComputedStyleForWebkitAppearanceExcludeDevTools);
}
- const CSSValue* value = GetPropertyCSSValue(CSSProperty::Get(property_id));
+ const CSSValue* value = GetPropertyCSSValue(property_id);
if (value)
return value->CssText();
return "";
@@ -452,7 +465,7 @@ bool CSSComputedStyleDeclaration::CssPropertyMatches(
return true;
}
}
- const CSSValue* value = GetPropertyCSSValue(CSSProperty::Get(property_id));
+ const CSSValue* value = GetPropertyCSSValue(property_id);
return DataEquivalent(value, &property_value);
}
@@ -467,7 +480,7 @@ MutableCSSPropertyValueSet* CSSComputedStyleDeclaration::CopyPropertiesInSet(
list.ReserveInitialCapacity(properties.size());
for (unsigned i = 0; i < properties.size(); ++i) {
const CSSProperty& property = *properties[i];
- const CSSValue* value = GetPropertyCSSValue(property);
+ const CSSValue* value = GetPropertyCSSValue(property.GetCSSPropertyName());
if (value)
list.push_back(CSSPropertyValue(property, *value, false));
}
@@ -536,11 +549,12 @@ const CSSValue* CSSComputedStyleDeclaration::GetPropertyCSSValueInternal(
UseCounter::Count(node_->GetDocument(),
WebFeature::kGetComputedStyleWebkitAppearance);
}
- return GetPropertyCSSValue(CSSProperty::Get(property_id));
+ return GetPropertyCSSValue(property_id);
}
const CSSValue* CSSComputedStyleDeclaration::GetPropertyCSSValueInternal(
AtomicString custom_property_name) {
+ DCHECK_EQ(CSSPropertyID::kVariable, cssPropertyID(custom_property_name));
return GetPropertyCSSValue(custom_property_name);
}
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 b9ccd3fa1a8..0b699ed9794 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
@@ -54,8 +54,9 @@ class CORE_EXPORT CSSComputedStyleDeclaration final
MutableCSSPropertyValueSet* CopyProperties() const;
- const CSSValue* GetPropertyCSSValue(const CSSProperty&) const;
+ const CSSValue* GetPropertyCSSValue(CSSPropertyID) const;
const CSSValue* GetPropertyCSSValue(AtomicString custom_property_name) const;
+ const CSSValue* GetPropertyCSSValue(const CSSPropertyName&) const;
HeapHashMap<AtomicString, Member<const CSSValue>> GetVariables() const;
const CSSValue* GetFontSizeCSSValuePreferringKeyword() const;
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 3742da249e6..363015e35de 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
@@ -102,4 +102,16 @@ TEST_F(CSSComputedStyleDeclarationTest, NeedsAdjacentStyleRecalc) {
EXPECT_TRUE(container->NeedsAdjacentStyleRecalc());
}
+TEST_F(CSSComputedStyleDeclarationTest,
+ NoCrashWhenCallingGetPropertyCSSValueWithVariable) {
+ UpdateAllLifecyclePhasesForTest();
+ Element* target = GetDocument().body();
+ auto* computed = MakeGarbageCollected<CSSComputedStyleDeclaration>(target);
+ ASSERT_TRUE(computed);
+ const CSSValue* result =
+ computed->GetPropertyCSSValue(CSSPropertyID::kVariable);
+ EXPECT_FALSE(result);
+ // Don't crash.
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/css_condition_rule.idl b/chromium/third_party/blink/renderer/core/css/css_condition_rule.idl
index 824a340d4be..a2d8b3ef307 100644
--- a/chromium/third_party/blink/renderer/core/css/css_condition_rule.idl
+++ b/chromium/third_party/blink/renderer/core/css/css_condition_rule.idl
@@ -4,7 +4,9 @@
// https://drafts.csswg.org/css-conditional/#the-cssconditionrule-interface
-interface CSSConditionRule : CSSGroupingRule {
+[
+ Exposed=Window
+] interface CSSConditionRule : CSSGroupingRule {
// TODO(xing.xu): readonly should be removed.
readonly attribute DOMString conditionText;
};
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 089a92e4d9a..14d1a8cf075 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
@@ -52,17 +52,24 @@ CSSDefaultStyleSheets& CSSDefaultStyleSheets::Instance() {
}
static const MediaQueryEvaluator& ScreenEval() {
- DEFINE_STATIC_LOCAL(Persistent<MediaQueryEvaluator>, static_screen_eval,
+ DEFINE_STATIC_LOCAL(const Persistent<MediaQueryEvaluator>, static_screen_eval,
(MakeGarbageCollected<MediaQueryEvaluator>("screen")));
return *static_screen_eval;
}
static const MediaQueryEvaluator& PrintEval() {
- DEFINE_STATIC_LOCAL(Persistent<MediaQueryEvaluator>, static_print_eval,
+ DEFINE_STATIC_LOCAL(const Persistent<MediaQueryEvaluator>, static_print_eval,
(MakeGarbageCollected<MediaQueryEvaluator>("print")));
return *static_print_eval;
}
+static const MediaQueryEvaluator& ForcedColorsEval() {
+ DEFINE_STATIC_LOCAL(
+ Persistent<MediaQueryEvaluator>, forced_colors_eval,
+ (MakeGarbageCollected<MediaQueryEvaluator>("forced-colors")));
+ return *forced_colors_eval;
+}
+
static StyleSheetContents* ParseUASheet(const String& str) {
// UA stylesheets always parse in the insecure context mode.
auto* sheet = MakeGarbageCollected<StyleSheetContents>(
@@ -91,22 +98,24 @@ CSSDefaultStyleSheets::CSSDefaultStyleSheets()
#if DCHECK_IS_ON()
default_style_->CompactRulesIfNeeded();
- default_print_style_->CompactRulesIfNeeded();
default_quirks_style_->CompactRulesIfNeeded();
+ default_print_style_->CompactRulesIfNeeded();
+ default_forced_color_style_->CompactRulesIfNeeded();
DCHECK(default_style_->UniversalRules()->IsEmpty());
- DCHECK(default_print_style_->UniversalRules()->IsEmpty());
DCHECK(default_quirks_style_->UniversalRules()->IsEmpty());
+ DCHECK(default_print_style_->UniversalRules()->IsEmpty());
+ DCHECK(default_forced_color_style_->UniversalRules()->IsEmpty());
#endif
}
void CSSDefaultStyleSheets::PrepareForLeakDetection() {
// Clear the optional style sheets.
- media_controls_style_sheet_.Clear();
mobile_viewport_style_sheet_.Clear();
television_viewport_style_sheet_.Clear();
xhtml_mobile_profile_style_sheet_.Clear();
svg_style_sheet_.Clear();
mathml_style_sheet_.Clear();
+ media_controls_style_sheet_.Clear();
fullscreen_style_sheet_.Clear();
// Initialize the styles that have the lazily loaded style sheets.
InitializeDefaultStyles();
@@ -116,12 +125,15 @@ void CSSDefaultStyleSheets::PrepareForLeakDetection() {
void CSSDefaultStyleSheets::InitializeDefaultStyles() {
// This must be called only from constructor / PrepareForLeakDetection.
default_style_ = MakeGarbageCollected<RuleSet>();
- default_print_style_ = MakeGarbageCollected<RuleSet>();
default_quirks_style_ = MakeGarbageCollected<RuleSet>();
+ default_print_style_ = MakeGarbageCollected<RuleSet>();
+ default_forced_color_style_ = MakeGarbageCollected<RuleSet>();
default_style_->AddRulesFromSheet(DefaultStyleSheet(), ScreenEval());
- default_print_style_->AddRulesFromSheet(DefaultStyleSheet(), PrintEval());
default_quirks_style_->AddRulesFromSheet(QuirksStyleSheet(), ScreenEval());
+ default_print_style_->AddRulesFromSheet(DefaultStyleSheet(), PrintEval());
+ default_forced_color_style_->AddRulesFromSheet(DefaultStyleSheet(),
+ ForcedColorsEval());
}
RuleSet* CSSDefaultStyleSheets::DefaultViewSourceStyle() {
@@ -220,6 +232,7 @@ void CSSDefaultStyleSheets::Trace(blink::Visitor* visitor) {
visitor->Trace(default_quirks_style_);
visitor->Trace(default_print_style_);
visitor->Trace(default_view_source_style_);
+ visitor->Trace(default_forced_color_style_);
visitor->Trace(default_style_sheet_);
visitor->Trace(mobile_viewport_style_sheet_);
visitor->Trace(television_viewport_style_sheet_);
diff --git a/chromium/third_party/blink/renderer/core/css/css_default_style_sheets.h b/chromium/third_party/blink/renderer/core/css/css_default_style_sheets.h
index bc67b935091..c712758762d 100644
--- a/chromium/third_party/blink/renderer/core/css/css_default_style_sheets.h
+++ b/chromium/third_party/blink/renderer/core/css/css_default_style_sheets.h
@@ -27,7 +27,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
@@ -51,6 +51,9 @@ class CSSDefaultStyleSheets
RuleSet* DefaultQuirksStyle() { return default_quirks_style_.Get(); }
RuleSet* DefaultPrintStyle() { return default_print_style_.Get(); }
RuleSet* DefaultViewSourceStyle();
+ RuleSet* DefaultForcedColorStyle() {
+ return default_forced_color_style_.Get();
+ }
StyleSheetContents* EnsureMobileViewportStyleSheet();
StyleSheetContents* EnsureTelevisionViewportStyleSheet();
@@ -94,6 +97,7 @@ class CSSDefaultStyleSheets
Member<RuleSet> default_quirks_style_;
Member<RuleSet> default_print_style_;
Member<RuleSet> default_view_source_style_;
+ Member<RuleSet> default_forced_color_style_;
Member<StyleSheetContents> default_style_sheet_;
Member<StyleSheetContents> mobile_viewport_style_sheet_;
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 4cfafe20fd5..6824c185f60 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
@@ -32,10 +32,10 @@
#include "third_party/blink/renderer/core/css/font_face_set_document.h"
#include "third_party/blink/renderer/core/css/font_face_set_worker.h"
#include "third_party/blink/renderer/core/css/remote_font_face_source.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
#include "third_party/blink/renderer/platform/fonts/font_description.h"
#include "third_party/blink/renderer/platform/fonts/simple_font_data.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
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 8f0b38b3d90..6f93e387355 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
@@ -32,7 +32,7 @@
#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"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
#include "third_party/blink/renderer/platform/wtf/linked_hash_set.h"
diff --git a/chromium/third_party/blink/renderer/core/css/css_font_face_source_test.cc b/chromium/third_party/blink/renderer/core/css/css_font_face_source_test.cc
index 62ffbf43a47..9ef1fca2bb8 100644
--- a/chromium/third_party/blink/renderer/core/css/css_font_face_source_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_font_face_source_test.cc
@@ -18,8 +18,8 @@ class DummyFontFaceSource : public CSSFontFaceSource {
scoped_refptr<SimpleFontData> CreateFontData(
const FontDescription&,
const FontSelectionCapabilities&) override {
- return SimpleFontData::Create(FontPlatformData(SkTypeface::MakeDefault(),
- CString(), 0, false, false));
+ return SimpleFontData::Create(FontPlatformData(
+ SkTypeface::MakeDefault(), std::string(), 0, false, false));
}
DummyFontFaceSource() = default;
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 b7b52c32148..463397f6552 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
@@ -85,8 +85,12 @@ FontResource& CSSFontFaceSrcValue::Fetch(ExecutionContext* context,
FontResourceClient* client) const {
if (!fetched_) {
ResourceRequest resource_request(absolute_resource_);
- resource_request.SetHttpReferrer(SecurityPolicy::GenerateReferrer(
- referrer_.referrer_policy, resource_request.Url(), referrer_.referrer));
+ resource_request.SetReferrerPolicy(
+ ReferrerPolicyResolveDefault(referrer_.referrer_policy),
+ ResourceRequest::SetReferrerPolicyLocation::kCSSFontFaceSrcValueFetch);
+ resource_request.SetReferrerString(
+ referrer_.referrer,
+ ResourceRequest::SetReferrerStringLocation::kCSSFontFaceSrcValueFetch);
ResourceLoaderOptions options;
options.initiator_info.name = fetch_initiator_type_names::kCSS;
FetchParameters params(resource_request, options);
@@ -95,6 +99,7 @@ FontResource& CSSFontFaceSrcValue::Fetch(ExecutionContext* context,
params.SetCacheAwareLoadingEnabled(kIsCacheAwareLoadingEnabled);
}
params.SetContentSecurityCheck(should_check_content_security_policy_);
+ params.SetFromOriginDirtyStyleSheet(origin_clean_ != OriginClean::kTrue);
const SecurityOrigin* security_origin = context->GetSecurityOrigin();
// Local fonts are accessible from file: URLs even when
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 9e821a72d22..b2cf3037717 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
@@ -27,6 +27,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_FONT_FACE_SRC_VALUE_H_
#include "base/memory/scoped_refptr.h"
+#include "third_party/blink/renderer/core/css/css_origin_clean.h"
#include "third_party/blink/renderer/core/css/css_value.h"
#include "third_party/blink/renderer/core/loader/resource/font_resource.h"
#include "third_party/blink/renderer/platform/weborigin/referrer.h"
@@ -43,17 +44,19 @@ class CORE_EXPORT CSSFontFaceSrcValue : public CSSValue {
const String& specified_resource,
const String& absolute_resource,
const Referrer& referrer,
- ContentSecurityPolicyDisposition should_check_content_security_policy) {
+ ContentSecurityPolicyDisposition should_check_content_security_policy,
+ OriginClean origin_clean) {
return MakeGarbageCollected<CSSFontFaceSrcValue>(
specified_resource, absolute_resource, referrer, false,
- should_check_content_security_policy);
+ should_check_content_security_policy, origin_clean);
}
static CSSFontFaceSrcValue* CreateLocal(
const String& absolute_resource,
- ContentSecurityPolicyDisposition should_check_content_security_policy) {
+ ContentSecurityPolicyDisposition should_check_content_security_policy,
+ OriginClean origin_clean) {
return MakeGarbageCollected<CSSFontFaceSrcValue>(
g_empty_string, absolute_resource, Referrer(), true,
- should_check_content_security_policy);
+ should_check_content_security_policy, origin_clean);
}
CSSFontFaceSrcValue(
@@ -61,14 +64,16 @@ class CORE_EXPORT CSSFontFaceSrcValue : public CSSValue {
const String& absolute_resource,
const Referrer& referrer,
bool local,
- ContentSecurityPolicyDisposition should_check_content_security_policy)
+ ContentSecurityPolicyDisposition should_check_content_security_policy,
+ OriginClean origin_clean)
: 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) {}
+ should_check_content_security_policy),
+ origin_clean_(origin_clean) {}
const String& GetResource() const { return absolute_resource_; }
const String& Format() const { return format_; }
@@ -94,12 +99,13 @@ class CORE_EXPORT CSSFontFaceSrcValue : public CSSValue {
private:
void RestoreCachedResourceIfNeeded(ExecutionContext*) const;
- String absolute_resource_;
- String specified_resource_;
+ const String absolute_resource_;
+ const String specified_resource_;
String format_;
- Referrer referrer_;
- bool is_local_;
- ContentSecurityPolicyDisposition should_check_content_security_policy_;
+ const Referrer referrer_;
+ const bool is_local_;
+ const ContentSecurityPolicyDisposition should_check_content_security_policy_;
+ const OriginClean origin_clean_;
class FontResourceHelper
: public GarbageCollectedFinalized<FontResourceHelper>,
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
index e65dd40ea22..882239c5b16 100644
--- 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
@@ -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://drafts.csswg.org/css-fonts-4/#om-fontfeaturevalues
+
[
RuntimeEnabled=CSSFontFeatureValues
] interface CSSFontFeatureValuesRule : CSSRule {
diff --git a/chromium/third_party/blink/renderer/core/css/css_font_selector.cc b/chromium/third_party/blink/renderer/core/css/css_font_selector.cc
index 655e3d125d6..bfdec0b18ac 100644
--- a/chromium/third_party/blink/renderer/core/css/css_font_selector.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_font_selector.cc
@@ -34,11 +34,11 @@
#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/frame/use_counter.h"
#include "third_party/blink/renderer/core/loader/frame_loader.h"
#include "third_party/blink/renderer/platform/fonts/font_cache.h"
#include "third_party/blink/renderer/platform/fonts/font_selector_client.h"
#include "third_party/blink/renderer/platform/fonts/simple_font_data.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/css/css_gradient_value.cc b/chromium/third_party/blink/renderer/core/css/css_gradient_value.cc
index 71a6350e8dd..165d0a4ec80 100644
--- a/chromium/third_party/blink/renderer/core/css/css_gradient_value.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_gradient_value.cc
@@ -31,8 +31,9 @@
#include <utility>
#include "base/stl_util.h"
-#include "third_party/blink/renderer/core/css/css_calculation_value.h"
#include "third_party/blink/renderer/core/css/css_identifier_value.h"
+#include "third_party/blink/renderer/core/css/css_math_expression_node.h"
+#include "third_party/blink/renderer/core/css/css_math_function_value.h"
#include "third_party/blink/renderer/core/css/css_to_length_conversion_data.h"
#include "third_party/blink/renderer/core/css/css_value_pair.h"
#include "third_party/blink/renderer/core/css_value_keywords.h"
@@ -503,12 +504,13 @@ void CSSGradientValue::AddStops(
} else if (stop.offset_->IsLength() ||
stop.offset_->IsCalculatedPercentageWithLength()) {
float length;
- if (stop.offset_->IsLength())
+ if (stop.offset_->IsLength()) {
length = stop.offset_->ComputeLength<float>(conversion_data);
- else
- length = stop.offset_->CssCalcValue()
+ } else {
+ length = To<CSSMathFunctionValue>(stop.offset_.Get())
->ToCalcValue(conversion_data)
->Evaluate(gradient_length);
+ }
stops[i].offset = (gradient_length > 0) ? length / gradient_length : 0;
} else if (stop.offset_->IsAngle()) {
stops[i].offset = stop.offset_->ComputeDegrees() / 360.0f;
@@ -682,7 +684,7 @@ static float PositionFromValue(const CSSValue* value,
sign * primitive_value->GetFloatValue() / 100.f * edge_distance;
if (primitive_value->IsCalculatedPercentageWithLength())
- return origin + sign * primitive_value->CssCalcValue()
+ return origin + sign * To<CSSMathFunctionValue>(primitive_value)
->ToCalcValue(conversion_data)
->Evaluate(edge_distance);
diff --git a/chromium/third_party/blink/renderer/core/css/css_grouping_rule.cc b/chromium/third_party/blink/renderer/core/css/css_grouping_rule.cc
index 93b790cb13e..89df799a8f8 100644
--- a/chromium/third_party/blink/renderer/core/css/css_grouping_rule.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_grouping_rule.cc
@@ -34,9 +34,9 @@
#include "third_party/blink/renderer/core/css/css_style_sheet.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/frame/use_counter.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.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_image_generator_value.cc b/chromium/third_party/blink/renderer/core/css/css_image_generator_value.cc
index c2227e8bc39..d3c55fe5a68 100644
--- a/chromium/third_party/blink/renderer/core/css/css_image_generator_value.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_image_generator_value.cc
@@ -70,7 +70,7 @@ void GeneratedImageCache::RemoveSize(const FloatSize& size) {
}
CSSImageGeneratorValue::CSSImageGeneratorValue(ClassType class_type)
- : CSSValue(class_type) {}
+ : CSSValue(class_type), keep_alive_(PERSISTENT_FROM_HERE) {}
CSSImageGeneratorValue::~CSSImageGeneratorValue() = default;
diff --git a/chromium/third_party/blink/renderer/core/css/css_image_generator_value.h b/chromium/third_party/blink/renderer/core/css/css_image_generator_value.h
index 55597af20f2..cd29fffbe22 100644
--- a/chromium/third_party/blink/renderer/core/css/css_image_generator_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_image_generator_value.h
@@ -26,13 +26,12 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_IMAGE_GENERATOR_VALUE_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_IMAGE_GENERATOR_VALUE_H_
-#include <map>
#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"
#include "third_party/blink/renderer/platform/geometry/float_size.h"
#include "third_party/blink/renderer/platform/heap/self_keep_alive.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/casting.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
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 a8cd7be2bfc..8f4478580b8 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
@@ -64,9 +64,8 @@ void CSSImageSetValue::FillImageSet() {
ImageWithScale image;
image.image_url = image_url;
- image.referrer = SecurityPolicy::GenerateReferrer(
- image_value.GetReferrer().referrer_policy, KURL(image_url),
- image_value.GetReferrer().referrer);
+ image.referrer.referrer = image_value.GetReferrer().referrer;
+ image.referrer.referrer_policy = image_value.GetReferrer().referrer_policy;
image.scale_factor = scale_factor;
images_in_set_.push_back(image);
++i;
@@ -114,7 +113,13 @@ StyleImage* CSSImageSetValue::CacheImage(
// transforms. https://bugs.webkit.org/show_bug.cgi?id=81698
ImageWithScale image = BestImageForScaleFactor(device_scale_factor);
ResourceRequest resource_request(document.CompleteURL(image.image_url));
- resource_request.SetHttpReferrer(image.referrer);
+ resource_request.SetReferrerPolicy(
+ ReferrerPolicyResolveDefault(image.referrer.referrer_policy),
+ ResourceRequest::SetReferrerPolicyLocation::
+ kCSSImageSetValueCacheImage);
+ resource_request.SetReferrerString(
+ image.referrer.referrer, ResourceRequest::SetReferrerStringLocation::
+ kCSSImageSetValueCacheImage);
ResourceLoaderOptions options;
options.initiator_info.name = parser_mode_ == kUASheetMode
? fetch_initiator_type_names::kUacss
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 dbe8ea70c5b..de879b89b1e 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
@@ -31,7 +31,7 @@
#include "third_party/blink/renderer/platform/loader/fetch/cross_origin_attribute_value.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h"
#include "third_party/blink/renderer/platform/weborigin/referrer.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/casting.h"
namespace blink {
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 f0b8c041292..6ce4ffe5964 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
@@ -40,17 +40,21 @@ namespace blink {
CSSImageValue::CSSImageValue(const AtomicString& raw_value,
const KURL& url,
const Referrer& referrer,
- StyleImage* image)
+ StyleImage* image,
+ OriginClean origin_clean)
: CSSValue(kImageClass),
relative_url_(raw_value),
referrer_(referrer),
absolute_url_(url.GetString()),
- cached_image_(image) {}
+ cached_image_(image),
+ origin_clean_(origin_clean) {}
-CSSImageValue::CSSImageValue(const AtomicString& absolute_url)
+CSSImageValue::CSSImageValue(const AtomicString& absolute_url,
+ OriginClean origin_clean)
: CSSValue(kImageClass),
relative_url_(absolute_url),
- absolute_url_(absolute_url) {}
+ absolute_url_(absolute_url),
+ origin_clean_(OriginClean::kFalse) {}
CSSImageValue::~CSSImageValue() = default;
@@ -62,8 +66,12 @@ StyleImage* CSSImageValue::CacheImage(
if (absolute_url_.IsEmpty())
ReResolveURL(document);
ResourceRequest resource_request(absolute_url_);
- resource_request.SetHttpReferrer(SecurityPolicy::GenerateReferrer(
- referrer_.referrer_policy, resource_request.Url(), referrer_.referrer));
+ resource_request.SetReferrerPolicy(
+ ReferrerPolicyResolveDefault(referrer_.referrer_policy),
+ ResourceRequest::SetReferrerPolicyLocation::kCSSImageValueCacheImage);
+ resource_request.SetReferrerString(
+ referrer_.referrer,
+ ResourceRequest::SetReferrerStringLocation::kCSSImageValueCacheImage);
ResourceLoaderOptions options;
options.initiator_info.name = initiator_name_.IsEmpty()
? fetch_initiator_type_names::kCSS
@@ -92,6 +100,9 @@ StyleImage* CSSImageValue::CacheImage(
params.SetLazyImageDeferred();
}
+ if (origin_clean_ != OriginClean::kTrue)
+ params.SetFromOriginDirtyStyleSheet(true);
+
cached_image_ = MakeGarbageCollected<StyleFetchedImage>(document, params,
is_lazily_loaded);
}
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 347b3cd3371..b8ab4d34e76 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
@@ -23,6 +23,7 @@
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/css/css_origin_clean.h"
#include "third_party/blink/renderer/core/css/css_value.h"
#include "third_party/blink/renderer/platform/loader/fetch/cross_origin_attribute_value.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h"
@@ -38,35 +39,43 @@ class ComputedStyle;
class CORE_EXPORT CSSImageValue : public CSSValue {
public:
- static CSSImageValue* Create(const KURL& url, StyleImage* image = nullptr) {
- return Create(url.GetString(), url, Referrer(), image);
+ static CSSImageValue* Create(const KURL& url,
+ OriginClean origin_clean,
+ StyleImage* image = nullptr) {
+ return Create(url.GetString(), url, Referrer(), origin_clean, image);
}
static CSSImageValue* Create(const AtomicString& relative_url,
const KURL& absolute_url,
+ OriginClean origin_clean,
StyleImage* image = nullptr) {
- return Create(relative_url, absolute_url, Referrer(), image);
+ return Create(relative_url, absolute_url, Referrer(), origin_clean, image);
}
static CSSImageValue* Create(const String& raw_value,
const KURL& url,
const Referrer& referrer,
+ OriginClean origin_clean,
StyleImage* image = nullptr) {
- return Create(AtomicString(raw_value), url, referrer, image);
+ return Create(AtomicString(raw_value), url, referrer, origin_clean, image);
}
static CSSImageValue* Create(const AtomicString& raw_value,
const KURL& url,
const Referrer& referrer,
+ OriginClean origin_clean,
StyleImage* image = nullptr) {
- return MakeGarbageCollected<CSSImageValue>(raw_value, url, referrer, image);
+ return MakeGarbageCollected<CSSImageValue>(raw_value, url, referrer, image,
+ origin_clean);
}
- static CSSImageValue* Create(const AtomicString& absolute_url) {
- return MakeGarbageCollected<CSSImageValue>(absolute_url);
+ static CSSImageValue* Create(const AtomicString& absolute_url,
+ OriginClean origin_clean) {
+ return MakeGarbageCollected<CSSImageValue>(absolute_url, origin_clean);
}
CSSImageValue(const AtomicString& raw_value,
const KURL&,
const Referrer&,
- StyleImage*);
- CSSImageValue(const AtomicString& absolute_url);
+ StyleImage*,
+ OriginClean origin_clean);
+ CSSImageValue(const AtomicString& absolute_url, OriginClean origin_clean);
~CSSImageValue();
bool IsCachePending() const { return !cached_image_; }
@@ -95,11 +104,12 @@ class CORE_EXPORT CSSImageValue : public CSSValue {
bool KnownToBeOpaque(const Document&, const ComputedStyle&) const;
CSSImageValue* ValueWithURLMadeAbsolute() const {
- return Create(KURL(absolute_url_), cached_image_.Get());
+ return Create(KURL(absolute_url_), origin_clean_, cached_image_.Get());
}
CSSImageValue* Clone() const {
- return Create(relative_url_, KURL(absolute_url_), cached_image_.Get());
+ return Create(relative_url_, KURL(absolute_url_), origin_clean_,
+ cached_image_.Get());
}
void SetInitiator(const AtomicString& name) { initiator_name_ = name; }
@@ -115,6 +125,10 @@ class CORE_EXPORT CSSImageValue : public CSSValue {
// Cached image data.
mutable AtomicString absolute_url_;
mutable Member<StyleImage> cached_image_;
+
+ // Whether the stylesheet that requested this image is origin-clean:
+ // https://drafts.csswg.org/cssom-1/#concept-css-style-sheet-origin-clean-flag
+ const OriginClean origin_clean_;
};
template <>
diff --git a/chromium/third_party/blink/renderer/core/css/css_keyframe_rule.idl b/chromium/third_party/blink/renderer/core/css/css_keyframe_rule.idl
index 07cbc1ce8d9..59b9325c98b 100644
--- a/chromium/third_party/blink/renderer/core/css/css_keyframe_rule.idl
+++ b/chromium/third_party/blink/renderer/core/css/css_keyframe_rule.idl
@@ -28,7 +28,9 @@
// https://drafts.csswg.org/css-animations/#interface-csskeyframerule
-interface CSSKeyframeRule : CSSRule {
+[
+ Exposed=Window
+] interface CSSKeyframeRule : CSSRule {
[RaisesException=Setter] attribute DOMString keyText;
[SameObject, PutForwards=cssText] readonly attribute CSSStyleDeclaration style;
};
diff --git a/chromium/third_party/blink/renderer/core/css/css_keyframe_shorthand_value.cc b/chromium/third_party/blink/renderer/core/css/css_keyframe_shorthand_value.cc
new file mode 100644
index 00000000000..a5d33566389
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/css_keyframe_shorthand_value.cc
@@ -0,0 +1,32 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/css/css_keyframe_shorthand_value.h"
+
+namespace blink {
+
+CSSKeyframeShorthandValue::CSSKeyframeShorthandValue(
+ ImmutableCSSPropertyValueSet* properties)
+ : CSSValue(kKeyframeShorthandClass), properties_(properties) {}
+
+String CSSKeyframeShorthandValue::CustomCSSText() const {
+ // All property/value pairs belong to the same shorthand so we grab the id
+ // from the first one.
+ CSSPropertyID my_shorthand = properties_->PropertyAt(0).ShorthandID();
+#if DCHECK_IS_ON()
+ for (unsigned i = 0; i < properties_->PropertyCount(); i++) {
+ DCHECK_EQ(my_shorthand, properties_->PropertyAt(i).ShorthandID())
+ << "These are not the longhands you're looking for.";
+ }
+#endif
+
+ return properties_->GetPropertyValue(my_shorthand);
+}
+
+void CSSKeyframeShorthandValue::TraceAfterDispatch(blink::Visitor* visitor) {
+ visitor->Trace(properties_);
+ CSSValue::TraceAfterDispatch(visitor);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/css_keyframe_shorthand_value.h b/chromium/third_party/blink/renderer/core/css/css_keyframe_shorthand_value.h
new file mode 100644
index 00000000000..bcc149c4ffa
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/css_keyframe_shorthand_value.h
@@ -0,0 +1,62 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_KEYFRAME_SHORTHAND_VALUE_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_KEYFRAME_SHORTHAND_VALUE_H_
+
+#include "third_party/blink/renderer/core/css/css_value.h"
+#include "third_party/blink/renderer/platform/wtf/casting.h"
+
+#include "third_party/blink/renderer/core/css/style_property_serializer.h"
+
+namespace blink {
+
+// The special value is used to keep around individual longhand css
+// property/values that resulted from parsing a shorthand value. This way we can
+// reconstruct the shorthand back from them.
+//
+// Context:
+//
+// Web Animation specs requires that we keep around and return a parsed
+// shorthand name/value pair if they are present in keyframes. However Blink css
+// parser does not keep around shorthands and instead produces longhands.
+// Instead of updating the css parser engine to preserve shorthands (which is a
+// large undertaking) we are taking a shortcut here that allows us to use
+// existing logic that enables serialization of a shorthand given its longhands
+// i.e., `StylePropertySerializer`. To this end, this class is be used to wrap
+// and store longhands produced by a single shorthand as part of animation
+// keyframe logic.
+//
+// For more information see:
+// - `StringKeyframe::SetCSSPropertyValue()`
+// - https://drafts.csswg.org/web-animations/#process-a-keyframes-argument
+
+class CSSKeyframeShorthandValue : public CSSValue {
+ public:
+ // Assumes that all property/value pairs that are present in the input set are
+ // longhands for the same shorthand property/value pair.
+ CSSKeyframeShorthandValue(ImmutableCSSPropertyValueSet*);
+
+ String CustomCSSText() const;
+
+ bool Equals(const CSSKeyframeShorthandValue& other) const {
+ return properties_ == other.properties_;
+ }
+
+ void TraceAfterDispatch(blink::Visitor*);
+
+ private:
+ Member<ImmutableCSSPropertyValueSet> properties_;
+};
+
+template <>
+struct DowncastTraits<CSSKeyframeShorthandValue> {
+ static bool AllowFrom(const CSSValue& value) {
+ return value.IsShorthandWrapperValue();
+ }
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_KEYFRAME_SHORTHAND_VALUE_H_
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 c2e25d8ff17..f689b784401 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
@@ -33,8 +33,8 @@
#include "third_party/blink/renderer/core/css/parser/css_parser.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/use_counter.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.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_keyframes_rule.idl b/chromium/third_party/blink/renderer/core/css/css_keyframes_rule.idl
index 01e48fd9a9a..17e8616d76a 100644
--- a/chromium/third_party/blink/renderer/core/css/css_keyframes_rule.idl
+++ b/chromium/third_party/blink/renderer/core/css/css_keyframes_rule.idl
@@ -28,7 +28,9 @@
// https://drafts.csswg.org/css-animations/#interface-csskeyframesrule
-interface CSSKeyframesRule : CSSRule {
+[
+ Exposed=Window
+] interface CSSKeyframesRule : CSSRule {
attribute DOMString name;
readonly attribute CSSRuleList cssRules;
diff --git a/chromium/third_party/blink/renderer/core/css/css_math_expression_node.cc b/chromium/third_party/blink/renderer/core/css/css_math_expression_node.cc
new file mode 100644
index 00000000000..e12acc649e4
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/css_math_expression_node.cc
@@ -0,0 +1,860 @@
+/*
+ * Copyright (C) 2011, 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/core/css/css_math_expression_node.h"
+
+#include "third_party/blink/renderer/core/css/css_numeric_literal_value.h"
+#include "third_party/blink/renderer/core/css/css_primitive_value_mappings.h"
+#include "third_party/blink/renderer/core/css/resolver/style_resolver.h"
+#include "third_party/blink/renderer/platform/wtf/math_extras.h"
+#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
+
+static const int maxExpressionDepth = 100;
+
+enum ParseState { OK, TooDeep, NoMoreTokens };
+
+namespace blink {
+
+static CalculationCategory UnitCategory(CSSPrimitiveValue::UnitType type) {
+ switch (type) {
+ case CSSPrimitiveValue::UnitType::kNumber:
+ case CSSPrimitiveValue::UnitType::kInteger:
+ return kCalcNumber;
+ case CSSPrimitiveValue::UnitType::kPercentage:
+ return kCalcPercent;
+ case CSSPrimitiveValue::UnitType::kEms:
+ case CSSPrimitiveValue::UnitType::kExs:
+ case CSSPrimitiveValue::UnitType::kPixels:
+ case CSSPrimitiveValue::UnitType::kCentimeters:
+ case CSSPrimitiveValue::UnitType::kMillimeters:
+ case CSSPrimitiveValue::UnitType::kQuarterMillimeters:
+ case CSSPrimitiveValue::UnitType::kInches:
+ case CSSPrimitiveValue::UnitType::kPoints:
+ case CSSPrimitiveValue::UnitType::kPicas:
+ case CSSPrimitiveValue::UnitType::kUserUnits:
+ case CSSPrimitiveValue::UnitType::kRems:
+ case CSSPrimitiveValue::UnitType::kChs:
+ case CSSPrimitiveValue::UnitType::kViewportWidth:
+ case CSSPrimitiveValue::UnitType::kViewportHeight:
+ case CSSPrimitiveValue::UnitType::kViewportMin:
+ case CSSPrimitiveValue::UnitType::kViewportMax:
+ return kCalcLength;
+ case CSSPrimitiveValue::UnitType::kDegrees:
+ case CSSPrimitiveValue::UnitType::kGradians:
+ case CSSPrimitiveValue::UnitType::kRadians:
+ case CSSPrimitiveValue::UnitType::kTurns:
+ return kCalcAngle;
+ case CSSPrimitiveValue::UnitType::kMilliseconds:
+ case CSSPrimitiveValue::UnitType::kSeconds:
+ return kCalcTime;
+ case CSSPrimitiveValue::UnitType::kHertz:
+ case CSSPrimitiveValue::UnitType::kKilohertz:
+ return kCalcFrequency;
+ default:
+ return kCalcOther;
+ }
+}
+
+static bool HasDoubleValue(CSSPrimitiveValue::UnitType type) {
+ switch (type) {
+ case CSSPrimitiveValue::UnitType::kNumber:
+ case CSSPrimitiveValue::UnitType::kPercentage:
+ case CSSPrimitiveValue::UnitType::kEms:
+ case CSSPrimitiveValue::UnitType::kExs:
+ case CSSPrimitiveValue::UnitType::kChs:
+ case CSSPrimitiveValue::UnitType::kRems:
+ case CSSPrimitiveValue::UnitType::kPixels:
+ case CSSPrimitiveValue::UnitType::kCentimeters:
+ case CSSPrimitiveValue::UnitType::kMillimeters:
+ case CSSPrimitiveValue::UnitType::kQuarterMillimeters:
+ case CSSPrimitiveValue::UnitType::kInches:
+ case CSSPrimitiveValue::UnitType::kPoints:
+ case CSSPrimitiveValue::UnitType::kPicas:
+ case CSSPrimitiveValue::UnitType::kUserUnits:
+ case CSSPrimitiveValue::UnitType::kDegrees:
+ case CSSPrimitiveValue::UnitType::kRadians:
+ case CSSPrimitiveValue::UnitType::kGradians:
+ case CSSPrimitiveValue::UnitType::kTurns:
+ case CSSPrimitiveValue::UnitType::kMilliseconds:
+ case CSSPrimitiveValue::UnitType::kSeconds:
+ case CSSPrimitiveValue::UnitType::kHertz:
+ case CSSPrimitiveValue::UnitType::kKilohertz:
+ case CSSPrimitiveValue::UnitType::kViewportWidth:
+ case CSSPrimitiveValue::UnitType::kViewportHeight:
+ case CSSPrimitiveValue::UnitType::kViewportMin:
+ case CSSPrimitiveValue::UnitType::kViewportMax:
+ case CSSPrimitiveValue::UnitType::kDotsPerPixel:
+ case CSSPrimitiveValue::UnitType::kDotsPerInch:
+ case CSSPrimitiveValue::UnitType::kDotsPerCentimeter:
+ case CSSPrimitiveValue::UnitType::kFraction:
+ case CSSPrimitiveValue::UnitType::kInteger:
+ return true;
+ default:
+ return false;
+ }
+}
+
+// ------ Start of CSSMathExpressionNumericLiteral member functions ------
+
+// static
+CSSMathExpressionNumericLiteral* CSSMathExpressionNumericLiteral::Create(
+ CSSNumericLiteralValue* value,
+ bool is_integer) {
+ return MakeGarbageCollected<CSSMathExpressionNumericLiteral>(value,
+ is_integer);
+}
+
+// static
+CSSMathExpressionNumericLiteral* CSSMathExpressionNumericLiteral::Create(
+ double value,
+ CSSPrimitiveValue::UnitType type,
+ bool is_integer) {
+ if (std::isnan(value) || std::isinf(value))
+ return nullptr;
+ return MakeGarbageCollected<CSSMathExpressionNumericLiteral>(
+ CSSNumericLiteralValue::Create(value, type), is_integer);
+}
+
+CSSMathExpressionNumericLiteral::CSSMathExpressionNumericLiteral(
+ CSSNumericLiteralValue* value,
+ bool is_integer)
+ : CSSMathExpressionNode(UnitCategory(value->GetType()), is_integer),
+ value_(value) {}
+
+bool CSSMathExpressionNumericLiteral::IsZero() const {
+ return !value_->GetDoubleValue();
+}
+
+String CSSMathExpressionNumericLiteral::CustomCSSText() const {
+ return value_->CssText();
+}
+
+void CSSMathExpressionNumericLiteral::AccumulatePixelsAndPercent(
+ const CSSToLengthConversionData& conversion_data,
+ PixelsAndPercent& value,
+ float multiplier) const {
+ switch (category_) {
+ case kCalcLength:
+ value.pixels = clampTo<float>(
+ value.pixels +
+ value_->ComputeLength<double>(conversion_data) * multiplier);
+ break;
+ case kCalcPercent:
+ DCHECK(value_->IsPercentage());
+ value.percent =
+ clampTo<float>(value.percent + value_->GetDoubleValue() * multiplier);
+ break;
+ case kCalcNumber:
+ // TODO(alancutter): Stop treating numbers like pixels unconditionally
+ // in calcs to be able to accomodate border-image-width
+ // https://drafts.csswg.org/css-backgrounds-3/#the-border-image-width
+ value.pixels = clampTo<float>(value.pixels + value_->GetDoubleValue() *
+ conversion_data.Zoom() *
+ multiplier);
+ break;
+ default:
+ NOTREACHED();
+ }
+}
+
+double CSSMathExpressionNumericLiteral::DoubleValue() const {
+ if (HasDoubleValue(ResolvedUnitType()))
+ return value_->GetDoubleValue();
+ NOTREACHED();
+ return 0;
+}
+
+base::Optional<double>
+CSSMathExpressionNumericLiteral::ComputeValueInCanonicalUnit() const {
+ switch (category_) {
+ case kCalcNumber:
+ case kCalcPercent:
+ return value_->DoubleValue();
+ case kCalcLength:
+ if (CSSPrimitiveValue::IsRelativeUnit(value_->GetType()))
+ return base::nullopt;
+ U_FALLTHROUGH;
+ case kCalcAngle:
+ case kCalcTime:
+ case kCalcFrequency:
+ return value_->DoubleValue() *
+ CSSPrimitiveValue::ConversionToCanonicalUnitsScaleFactor(
+ value_->GetType());
+ default:
+ return base::nullopt;
+ }
+}
+
+double CSSMathExpressionNumericLiteral::ComputeLengthPx(
+ const CSSToLengthConversionData& conversion_data) const {
+ switch (category_) {
+ case kCalcLength:
+ return value_->ComputeLength<double>(conversion_data);
+ case kCalcNumber:
+ case kCalcPercent:
+ case kCalcAngle:
+ case kCalcFrequency:
+ case kCalcPercentLength:
+ case kCalcPercentNumber:
+ case kCalcTime:
+ case kCalcLengthNumber:
+ case kCalcPercentLengthNumber:
+ case kCalcOther:
+ NOTREACHED();
+ break;
+ }
+ NOTREACHED();
+ return 0;
+}
+
+void CSSMathExpressionNumericLiteral::AccumulateLengthArray(
+ CSSLengthArray& length_array,
+ double multiplier) const {
+ DCHECK_NE(Category(), kCalcNumber);
+ value_->AccumulateLengthArray(length_array, multiplier);
+}
+
+bool CSSMathExpressionNumericLiteral::operator==(
+ const CSSMathExpressionNode& other) const {
+ if (!other.IsNumericLiteral())
+ return false;
+
+ return DataEquivalent(value_,
+ To<CSSMathExpressionNumericLiteral>(other).value_);
+}
+
+CSSPrimitiveValue::UnitType CSSMathExpressionNumericLiteral::ResolvedUnitType()
+ const {
+ return value_->GetType();
+}
+
+bool CSSMathExpressionNumericLiteral::IsComputationallyIndependent() const {
+ return value_->IsComputationallyIndependent();
+}
+
+void CSSMathExpressionNumericLiteral::Trace(blink::Visitor* visitor) {
+ visitor->Trace(value_);
+ CSSMathExpressionNode::Trace(visitor);
+}
+
+// ------ End of CSSMathExpressionNumericLiteral member functions
+
+static const CalculationCategory kAddSubtractResult[kCalcOther][kCalcOther] = {
+ /* CalcNumber */ {kCalcNumber, kCalcLengthNumber, kCalcPercentNumber,
+ kCalcPercentNumber, kCalcOther, kCalcOther, kCalcOther,
+ kCalcOther, kCalcLengthNumber, kCalcPercentLengthNumber},
+ /* CalcLength */
+ {kCalcLengthNumber, kCalcLength, kCalcPercentLength, kCalcOther,
+ kCalcPercentLength, kCalcOther, kCalcOther, kCalcOther, kCalcLengthNumber,
+ kCalcPercentLengthNumber},
+ /* CalcPercent */
+ {kCalcPercentNumber, kCalcPercentLength, kCalcPercent, kCalcPercentNumber,
+ kCalcPercentLength, kCalcOther, kCalcOther, kCalcOther,
+ kCalcPercentLengthNumber, kCalcPercentLengthNumber},
+ /* CalcPercentNumber */
+ {kCalcPercentNumber, kCalcPercentLengthNumber, kCalcPercentNumber,
+ kCalcPercentNumber, kCalcPercentLengthNumber, kCalcOther, kCalcOther,
+ kCalcOther, kCalcOther, kCalcPercentLengthNumber},
+ /* CalcPercentLength */
+ {kCalcPercentLengthNumber, kCalcPercentLength, kCalcPercentLength,
+ kCalcPercentLengthNumber, kCalcPercentLength, kCalcOther, kCalcOther,
+ kCalcOther, kCalcOther, kCalcPercentLengthNumber},
+ /* CalcAngle */
+ {kCalcOther, kCalcOther, kCalcOther, kCalcOther, kCalcOther, kCalcAngle,
+ kCalcOther, kCalcOther, kCalcOther, kCalcOther},
+ /* CalcTime */
+ {kCalcOther, kCalcOther, kCalcOther, kCalcOther, kCalcOther, kCalcOther,
+ kCalcTime, kCalcOther, kCalcOther, kCalcOther},
+ /* CalcFrequency */
+ {kCalcOther, kCalcOther, kCalcOther, kCalcOther, kCalcOther, kCalcOther,
+ kCalcOther, kCalcFrequency, kCalcOther, kCalcOther},
+ /* CalcLengthNumber */
+ {kCalcLengthNumber, kCalcLengthNumber, kCalcPercentLengthNumber,
+ kCalcPercentLengthNumber, kCalcPercentLengthNumber, kCalcOther, kCalcOther,
+ kCalcOther, kCalcLengthNumber, kCalcPercentLengthNumber},
+ /* CalcPercentLengthNumber */
+ {kCalcPercentLengthNumber, kCalcPercentLengthNumber,
+ kCalcPercentLengthNumber, kCalcPercentLengthNumber,
+ kCalcPercentLengthNumber, kCalcOther, kCalcOther, kCalcOther,
+ kCalcPercentLengthNumber, kCalcPercentLengthNumber}};
+
+static CalculationCategory DetermineCategory(
+ const CSSMathExpressionNode& left_side,
+ const CSSMathExpressionNode& right_side,
+ CSSMathOperator op) {
+ CalculationCategory left_category = left_side.Category();
+ CalculationCategory right_category = right_side.Category();
+
+ if (left_category == kCalcOther || right_category == kCalcOther)
+ return kCalcOther;
+
+ switch (op) {
+ case CSSMathOperator::kAdd:
+ case CSSMathOperator::kSubtract:
+ return kAddSubtractResult[left_category][right_category];
+ case CSSMathOperator::kMultiply:
+ if (left_category != kCalcNumber && right_category != kCalcNumber)
+ return kCalcOther;
+ return left_category == kCalcNumber ? right_category : left_category;
+ case CSSMathOperator::kDivide:
+ if (right_category != kCalcNumber || right_side.IsZero())
+ return kCalcOther;
+ return left_category;
+ default:
+ break;
+ }
+
+ NOTREACHED();
+ return kCalcOther;
+}
+
+static bool IsIntegerResult(const CSSMathExpressionNode* left_side,
+ const CSSMathExpressionNode* right_side,
+ CSSMathOperator op) {
+ // Not testing for actual integer values.
+ // Performs W3C spec's type checking for calc integers.
+ // http://www.w3.org/TR/css3-values/#calc-type-checking
+ return op != CSSMathOperator::kDivide && left_side->IsInteger() &&
+ right_side->IsInteger();
+}
+
+// ------ Start of CSSMathExpressionBinaryOperation member functions ------
+
+// static
+CSSMathExpressionNode* CSSMathExpressionBinaryOperation::Create(
+ CSSMathExpressionNode* left_side,
+ CSSMathExpressionNode* right_side,
+ CSSMathOperator op) {
+ DCHECK_NE(left_side->Category(), kCalcOther);
+ DCHECK_NE(right_side->Category(), kCalcOther);
+
+ CalculationCategory new_category =
+ DetermineCategory(*left_side, *right_side, op);
+ if (new_category == kCalcOther)
+ return nullptr;
+
+ return MakeGarbageCollected<CSSMathExpressionBinaryOperation>(
+ left_side, right_side, op, new_category);
+}
+
+// static
+CSSMathExpressionNode* CSSMathExpressionBinaryOperation::CreateSimplified(
+ CSSMathExpressionNode* left_side,
+ CSSMathExpressionNode* right_side,
+ CSSMathOperator op) {
+ CalculationCategory left_category = left_side->Category();
+ CalculationCategory right_category = right_side->Category();
+ DCHECK_NE(left_category, kCalcOther);
+ DCHECK_NE(right_category, kCalcOther);
+
+ bool is_integer = IsIntegerResult(left_side, right_side, op);
+
+ // Simplify numbers.
+ if (left_category == kCalcNumber && right_category == kCalcNumber) {
+ return CSSMathExpressionNumericLiteral::Create(
+ EvaluateOperator(left_side->DoubleValue(), right_side->DoubleValue(),
+ op),
+ CSSPrimitiveValue::UnitType::kNumber, is_integer);
+ }
+
+ // Simplify addition and subtraction between same types.
+ if (op == CSSMathOperator::kAdd || op == CSSMathOperator::kSubtract) {
+ if (left_category == right_side->Category()) {
+ CSSPrimitiveValue::UnitType left_type = left_side->ResolvedUnitType();
+ if (HasDoubleValue(left_type)) {
+ CSSPrimitiveValue::UnitType right_type = right_side->ResolvedUnitType();
+ if (left_type == right_type) {
+ return CSSMathExpressionNumericLiteral::Create(
+ EvaluateOperator(left_side->DoubleValue(),
+ right_side->DoubleValue(), op),
+ left_type, is_integer);
+ }
+ CSSPrimitiveValue::UnitCategory left_unit_category =
+ CSSPrimitiveValue::UnitTypeToUnitCategory(left_type);
+ if (left_unit_category != CSSPrimitiveValue::kUOther &&
+ left_unit_category ==
+ CSSPrimitiveValue::UnitTypeToUnitCategory(right_type)) {
+ CSSPrimitiveValue::UnitType canonical_type =
+ CSSPrimitiveValue::CanonicalUnitTypeForCategory(
+ left_unit_category);
+ if (canonical_type != CSSPrimitiveValue::UnitType::kUnknown) {
+ double left_value = clampTo<double>(
+ left_side->DoubleValue() *
+ CSSPrimitiveValue::ConversionToCanonicalUnitsScaleFactor(
+ left_type));
+ double right_value = clampTo<double>(
+ right_side->DoubleValue() *
+ CSSPrimitiveValue::ConversionToCanonicalUnitsScaleFactor(
+ right_type));
+ return CSSMathExpressionNumericLiteral::Create(
+ EvaluateOperator(left_value, right_value, op), canonical_type,
+ is_integer);
+ }
+ }
+ }
+ }
+ } else {
+ // Simplify multiplying or dividing by a number for simplifiable types.
+ DCHECK(op == CSSMathOperator::kMultiply || op == CSSMathOperator::kDivide);
+ CSSMathExpressionNode* number_side = GetNumberSide(left_side, right_side);
+ if (!number_side)
+ return Create(left_side, right_side, op);
+ if (number_side == left_side && op == CSSMathOperator::kDivide)
+ return nullptr;
+ CSSMathExpressionNode* other_side =
+ left_side == number_side ? right_side : left_side;
+
+ double number = number_side->DoubleValue();
+ if (std::isnan(number) || std::isinf(number))
+ return nullptr;
+ if (op == CSSMathOperator::kDivide && !number)
+ return nullptr;
+
+ CSSPrimitiveValue::UnitType other_type = other_side->ResolvedUnitType();
+ if (HasDoubleValue(other_type)) {
+ return CSSMathExpressionNumericLiteral::Create(
+ EvaluateOperator(other_side->DoubleValue(), number, op), other_type,
+ is_integer);
+ }
+ }
+
+ return Create(left_side, right_side, op);
+}
+
+CSSMathExpressionBinaryOperation::CSSMathExpressionBinaryOperation(
+ CSSMathExpressionNode* left_side,
+ CSSMathExpressionNode* right_side,
+ CSSMathOperator op,
+ CalculationCategory category)
+ : CSSMathExpressionNode(category,
+ IsIntegerResult(left_side, right_side, op)),
+ left_side_(left_side),
+ right_side_(right_side),
+ operator_(op) {}
+
+bool CSSMathExpressionBinaryOperation::IsZero() const {
+ return !DoubleValue();
+}
+
+void CSSMathExpressionBinaryOperation::AccumulatePixelsAndPercent(
+ const CSSToLengthConversionData& conversion_data,
+ PixelsAndPercent& value,
+ float multiplier) const {
+ switch (operator_) {
+ case CSSMathOperator::kAdd:
+ left_side_->AccumulatePixelsAndPercent(conversion_data, value,
+ multiplier);
+ right_side_->AccumulatePixelsAndPercent(conversion_data, value,
+ multiplier);
+ break;
+ case CSSMathOperator::kSubtract:
+ left_side_->AccumulatePixelsAndPercent(conversion_data, value,
+ multiplier);
+ right_side_->AccumulatePixelsAndPercent(conversion_data, value,
+ -multiplier);
+ break;
+ case CSSMathOperator::kMultiply:
+ DCHECK_NE((left_side_->Category() == kCalcNumber),
+ (right_side_->Category() == kCalcNumber));
+ if (left_side_->Category() == kCalcNumber) {
+ right_side_->AccumulatePixelsAndPercent(
+ conversion_data, value, multiplier * left_side_->DoubleValue());
+ } else {
+ left_side_->AccumulatePixelsAndPercent(
+ conversion_data, value, multiplier * right_side_->DoubleValue());
+ }
+ break;
+ case CSSMathOperator::kDivide:
+ DCHECK_EQ(right_side_->Category(), kCalcNumber);
+ left_side_->AccumulatePixelsAndPercent(
+ conversion_data, value, multiplier / right_side_->DoubleValue());
+ break;
+ default:
+ NOTREACHED();
+ }
+}
+
+double CSSMathExpressionBinaryOperation::DoubleValue() const {
+ DCHECK(HasDoubleValue(ResolvedUnitType())) << CustomCSSText();
+ return Evaluate(left_side_->DoubleValue(), right_side_->DoubleValue());
+}
+
+static bool HasCanonicalUnit(CalculationCategory category) {
+ return category == kCalcNumber || category == kCalcLength ||
+ category == kCalcPercent || category == kCalcAngle ||
+ category == kCalcTime || category == kCalcFrequency;
+}
+
+base::Optional<double>
+CSSMathExpressionBinaryOperation::ComputeValueInCanonicalUnit() const {
+ if (!HasCanonicalUnit(category_))
+ return base::nullopt;
+
+ base::Optional<double> left_value = left_side_->ComputeValueInCanonicalUnit();
+ if (!left_value)
+ return base::nullopt;
+
+ base::Optional<double> right_value =
+ right_side_->ComputeValueInCanonicalUnit();
+ if (!right_value)
+ return base::nullopt;
+
+ return Evaluate(*left_value, *right_value);
+}
+
+double CSSMathExpressionBinaryOperation::ComputeLengthPx(
+ const CSSToLengthConversionData& conversion_data) const {
+ DCHECK_EQ(kCalcLength, Category());
+ double left_value;
+ if (left_side_->Category() == kCalcLength) {
+ left_value = left_side_->ComputeLengthPx(conversion_data);
+ } else {
+ DCHECK_EQ(kCalcNumber, left_side_->Category());
+ left_value = left_side_->DoubleValue();
+ }
+ double right_value;
+ if (right_side_->Category() == kCalcLength) {
+ right_value = right_side_->ComputeLengthPx(conversion_data);
+ } else {
+ DCHECK_EQ(kCalcNumber, right_side_->Category());
+ right_value = right_side_->DoubleValue();
+ }
+ return Evaluate(left_value, right_value);
+}
+
+void CSSMathExpressionBinaryOperation::AccumulateLengthArray(
+ CSSLengthArray& length_array,
+ double multiplier) const {
+ switch (operator_) {
+ case CSSMathOperator::kAdd:
+ left_side_->AccumulateLengthArray(length_array, multiplier);
+ right_side_->AccumulateLengthArray(length_array, multiplier);
+ break;
+ case CSSMathOperator::kSubtract:
+ left_side_->AccumulateLengthArray(length_array, multiplier);
+ right_side_->AccumulateLengthArray(length_array, -multiplier);
+ break;
+ case CSSMathOperator::kMultiply:
+ DCHECK_NE((left_side_->Category() == kCalcNumber),
+ (right_side_->Category() == kCalcNumber));
+ if (left_side_->Category() == kCalcNumber) {
+ right_side_->AccumulateLengthArray(
+ length_array, multiplier * left_side_->DoubleValue());
+ } else {
+ left_side_->AccumulateLengthArray(
+ length_array, multiplier * right_side_->DoubleValue());
+ }
+ break;
+ case CSSMathOperator::kDivide:
+ DCHECK_EQ(right_side_->Category(), kCalcNumber);
+ left_side_->AccumulateLengthArray(
+ length_array, multiplier / right_side_->DoubleValue());
+ break;
+ default:
+ NOTREACHED();
+ }
+}
+
+bool CSSMathExpressionBinaryOperation::IsComputationallyIndependent() const {
+ if (Category() != kCalcLength && Category() != kCalcPercentLength)
+ return true;
+ return left_side_->IsComputationallyIndependent() &&
+ right_side_->IsComputationallyIndependent();
+}
+
+// static
+String CSSMathExpressionBinaryOperation::BuildCSSText(
+ const String& left_expression,
+ const String& right_expression,
+ CSSMathOperator op) {
+ StringBuilder result;
+ result.Append('(');
+ result.Append(left_expression);
+ result.Append(' ');
+ result.Append(ToString(op));
+ result.Append(' ');
+ result.Append(right_expression);
+ result.Append(')');
+
+ return result.ToString();
+}
+
+String CSSMathExpressionBinaryOperation::CustomCSSText() const {
+ return BuildCSSText(left_side_->CustomCSSText(), right_side_->CustomCSSText(),
+ operator_);
+}
+
+bool CSSMathExpressionBinaryOperation::operator==(
+ const CSSMathExpressionNode& exp) const {
+ if (!exp.IsBinaryOperation())
+ return false;
+
+ const CSSMathExpressionBinaryOperation& other =
+ To<CSSMathExpressionBinaryOperation>(exp);
+ return DataEquivalent(left_side_, other.left_side_) &&
+ DataEquivalent(right_side_, other.right_side_) &&
+ operator_ == other.operator_;
+}
+
+CSSPrimitiveValue::UnitType CSSMathExpressionBinaryOperation::ResolvedUnitType()
+ const {
+ switch (category_) {
+ case kCalcNumber:
+ DCHECK_EQ(left_side_->Category(), kCalcNumber);
+ DCHECK_EQ(right_side_->Category(), kCalcNumber);
+ return CSSPrimitiveValue::UnitType::kNumber;
+ case kCalcLength:
+ case kCalcPercent: {
+ if (left_side_->Category() == kCalcNumber)
+ return right_side_->ResolvedUnitType();
+ if (right_side_->Category() == kCalcNumber)
+ return left_side_->ResolvedUnitType();
+ CSSPrimitiveValue::UnitType left_type = left_side_->ResolvedUnitType();
+ if (left_type == right_side_->ResolvedUnitType())
+ return left_type;
+ return CSSPrimitiveValue::UnitType::kUnknown;
+ }
+ case kCalcAngle:
+ return CSSPrimitiveValue::UnitType::kDegrees;
+ case kCalcTime:
+ return CSSPrimitiveValue::UnitType::kMilliseconds;
+ case kCalcFrequency:
+ return CSSPrimitiveValue::UnitType::kHertz;
+ case kCalcPercentLength:
+ case kCalcPercentNumber:
+ case kCalcLengthNumber:
+ case kCalcPercentLengthNumber:
+ case kCalcOther:
+ return CSSPrimitiveValue::UnitType::kUnknown;
+ }
+ NOTREACHED();
+ return CSSPrimitiveValue::UnitType::kUnknown;
+}
+
+void CSSMathExpressionBinaryOperation::Trace(blink::Visitor* visitor) {
+ visitor->Trace(left_side_);
+ visitor->Trace(right_side_);
+ CSSMathExpressionNode::Trace(visitor);
+}
+
+// static
+CSSMathExpressionNode* CSSMathExpressionBinaryOperation::GetNumberSide(
+ CSSMathExpressionNode* left_side,
+ CSSMathExpressionNode* right_side) {
+ if (left_side->Category() == kCalcNumber)
+ return left_side;
+ if (right_side->Category() == kCalcNumber)
+ return right_side;
+ return nullptr;
+}
+
+// static
+double CSSMathExpressionBinaryOperation::EvaluateOperator(double left_value,
+ double right_value,
+ CSSMathOperator op) {
+ switch (op) {
+ case CSSMathOperator::kAdd:
+ return clampTo<double>(left_value + right_value);
+ case CSSMathOperator::kSubtract:
+ return clampTo<double>(left_value - right_value);
+ case CSSMathOperator::kMultiply:
+ return clampTo<double>(left_value * right_value);
+ case CSSMathOperator::kDivide:
+ if (right_value)
+ return clampTo<double>(left_value / right_value);
+ return std::numeric_limits<double>::quiet_NaN();
+ default:
+ NOTREACHED();
+ break;
+ }
+ return 0;
+}
+
+// ------ End of CSSMathExpressionBinaryOperation member functions ------
+
+static ParseState CheckDepthAndIndex(int* depth, CSSParserTokenRange tokens) {
+ (*depth)++;
+ if (tokens.AtEnd())
+ return NoMoreTokens;
+ if (*depth > maxExpressionDepth)
+ return TooDeep;
+ return OK;
+}
+
+class CSSMathExpressionNodeParser {
+ STACK_ALLOCATED();
+
+ public:
+ CSSMathExpressionNodeParser() {}
+
+ CSSMathExpressionNode* ParseCalc(CSSParserTokenRange tokens) {
+ tokens.ConsumeWhitespace();
+ CSSMathExpressionNode* result = ParseValueExpression(tokens, 0);
+ if (!result || !tokens.AtEnd())
+ return nullptr;
+ return result;
+ }
+
+ private:
+ CSSMathExpressionNode* ParseValue(CSSParserTokenRange& tokens) {
+ CSSParserToken token = tokens.ConsumeIncludingWhitespace();
+ if (!(token.GetType() == kNumberToken ||
+ token.GetType() == kPercentageToken ||
+ token.GetType() == kDimensionToken))
+ return nullptr;
+
+ CSSPrimitiveValue::UnitType type = token.GetUnitType();
+ if (UnitCategory(type) == kCalcOther)
+ return nullptr;
+
+ return CSSMathExpressionNumericLiteral::Create(
+ CSSNumericLiteralValue::Create(token.NumericValue(), type),
+ token.GetNumericValueType() == kIntegerValueType);
+ }
+
+ CSSMathExpressionNode* ParseValueTerm(CSSParserTokenRange& tokens,
+ int depth) {
+ if (CheckDepthAndIndex(&depth, tokens) != OK)
+ return nullptr;
+
+ if (tokens.Peek().GetType() == kLeftParenthesisToken ||
+ tokens.Peek().FunctionId() == CSSValueID::kCalc) {
+ CSSParserTokenRange inner_range = tokens.ConsumeBlock();
+ tokens.ConsumeWhitespace();
+ inner_range.ConsumeWhitespace();
+ CSSMathExpressionNode* result = ParseValueExpression(inner_range, depth);
+ if (!result)
+ return nullptr;
+ result->SetIsNestedCalc();
+ return result;
+ }
+
+ return ParseValue(tokens);
+ }
+
+ CSSMathExpressionNode* ParseValueMultiplicativeExpression(
+ CSSParserTokenRange& tokens,
+ int depth) {
+ if (CheckDepthAndIndex(&depth, tokens) != OK)
+ return nullptr;
+
+ CSSMathExpressionNode* result = ParseValueTerm(tokens, depth);
+ if (!result)
+ return nullptr;
+
+ while (!tokens.AtEnd()) {
+ CSSMathOperator math_operator = ParseCSSArithmeticOperator(tokens.Peek());
+ if (math_operator != CSSMathOperator::kMultiply &&
+ math_operator != CSSMathOperator::kDivide)
+ break;
+ tokens.ConsumeIncludingWhitespace();
+
+ CSSMathExpressionNode* rhs = ParseValueTerm(tokens, depth);
+ if (!rhs)
+ return nullptr;
+
+ result = CSSMathExpressionBinaryOperation::CreateSimplified(
+ result, rhs, math_operator);
+
+ if (!result)
+ return nullptr;
+ }
+
+ return result;
+ }
+
+ CSSMathExpressionNode* ParseAdditiveValueExpression(
+ CSSParserTokenRange& tokens,
+ int depth) {
+ if (CheckDepthAndIndex(&depth, tokens) != OK)
+ return nullptr;
+
+ CSSMathExpressionNode* result =
+ ParseValueMultiplicativeExpression(tokens, depth);
+ if (!result)
+ return nullptr;
+
+ while (!tokens.AtEnd()) {
+ CSSMathOperator math_operator = ParseCSSArithmeticOperator(tokens.Peek());
+ if (math_operator != CSSMathOperator::kAdd &&
+ math_operator != CSSMathOperator::kSubtract)
+ break;
+ if ((&tokens.Peek() - 1)->GetType() != kWhitespaceToken)
+ return nullptr; // calc(1px+ 2px) is invalid
+ tokens.Consume();
+ if (tokens.Peek().GetType() != kWhitespaceToken)
+ return nullptr; // calc(1px +2px) is invalid
+ tokens.ConsumeIncludingWhitespace();
+
+ CSSMathExpressionNode* rhs =
+ ParseValueMultiplicativeExpression(tokens, depth);
+ if (!rhs)
+ return nullptr;
+
+ result = CSSMathExpressionBinaryOperation::CreateSimplified(
+ result, rhs, math_operator);
+
+ if (!result)
+ return nullptr;
+ }
+
+ return result;
+ }
+
+ CSSMathExpressionNode* ParseValueExpression(CSSParserTokenRange& tokens,
+ int depth) {
+ return ParseAdditiveValueExpression(tokens, depth);
+ }
+};
+
+// static
+CSSMathExpressionNode* CSSMathExpressionNode::CreateFromPixelsAndPercent(
+ double pixels,
+ double percent) {
+ return CSSMathExpressionBinaryOperation::Create(
+ CSSMathExpressionNumericLiteral::Create(
+ CSSNumericLiteralValue::Create(
+ percent, CSSPrimitiveValue::UnitType::kPercentage),
+ percent == trunc(percent)),
+ CSSMathExpressionNumericLiteral::Create(
+ CSSNumericLiteralValue::Create(pixels,
+ CSSPrimitiveValue::UnitType::kPixels),
+ pixels == trunc(pixels)),
+ CSSMathOperator::kAdd);
+}
+
+// static
+CSSMathExpressionNode* CSSMathExpressionNode::ParseCalc(
+ const CSSParserTokenRange& tokens) {
+ CSSMathExpressionNodeParser parser;
+ return parser.ParseCalc(tokens);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/css_math_expression_node.h b/chromium/third_party/blink/renderer/core/css/css_math_expression_node.h
new file mode 100644
index 00000000000..b435b018575
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/css_math_expression_node.h
@@ -0,0 +1,242 @@
+/*
+ * Copyright (C) 2011, 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_CORE_CSS_CSS_MATH_EXPRESSION_NODE_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_MATH_EXPRESSION_NODE_H_
+
+#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/css/css_math_operator.h"
+#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/geometry/calculation_value.h"
+#include "third_party/blink/renderer/platform/wtf/forward.h"
+
+namespace blink {
+
+class CSSNumericLiteralValue;
+
+// The order of this enum should not change since its elements are used as
+// indices in the addSubtractResult matrix.
+enum CalculationCategory {
+ kCalcNumber = 0,
+ kCalcLength,
+ kCalcPercent,
+ kCalcPercentNumber,
+ kCalcPercentLength,
+ kCalcAngle,
+ kCalcTime,
+ kCalcFrequency,
+ kCalcLengthNumber,
+ kCalcPercentLengthNumber,
+ kCalcOther
+};
+
+class CORE_EXPORT CSSMathExpressionNode
+ : public GarbageCollected<CSSMathExpressionNode> {
+ public:
+ static CSSMathExpressionNode* CreateFromPixelsAndPercent(double pixels,
+ double percent);
+ static CSSMathExpressionNode* ParseCalc(const CSSParserTokenRange& tokens);
+
+ virtual bool IsNumericLiteral() const { return false; }
+ virtual bool IsBinaryOperation() const { return false; }
+
+ virtual bool IsZero() const = 0;
+
+ // Resolves the expression into one value *without doing any type conversion*.
+ // Hits DCHECK if type conversion is required.
+ virtual double DoubleValue() const = 0;
+
+ virtual double ComputeLengthPx(const CSSToLengthConversionData&) const = 0;
+ virtual void AccumulateLengthArray(CSSLengthArray&,
+ double multiplier) const = 0;
+ virtual void AccumulatePixelsAndPercent(const CSSToLengthConversionData&,
+ PixelsAndPercent&,
+ float multiplier = 1) const = 0;
+
+ // Evaluates the expression with type conversion (e.g., cm -> px) handled, and
+ // returns the result value in the canonical unit of the corresponding
+ // category (see https://www.w3.org/TR/css3-values/#canonical-unit).
+ // TODO(crbug.com/984372): We currently use 'ms' as the canonical unit of
+ // <time>. Switch to 's' to follow the spec.
+ // Returns |nullopt| on evaluation failures due to the following reasons:
+ // - The category doesn't have a canonical unit (e.g., |kCalcPercentLength|).
+ // - A type conversion that doesn't have a fixed conversion ratio is needed
+ // (e.g., between 'px' and 'em').
+ // - There's an unsupported calculation, e.g., dividing two lengths.
+ virtual base::Optional<double> ComputeValueInCanonicalUnit() const = 0;
+
+ virtual String CustomCSSText() const = 0;
+ virtual bool operator==(const CSSMathExpressionNode& other) const {
+ return category_ == other.category_ && is_integer_ == other.is_integer_;
+ }
+
+ virtual bool IsComputationallyIndependent() const = 0;
+
+ CalculationCategory Category() const { return category_; }
+
+ // Returns the unit type of the math expression *without doing any type
+ // conversion* (e.g., 1px + 1em needs type conversion to resolve).
+ // Returns |UnitType::kUnknown| if type conversion is required.
+ virtual CSSPrimitiveValue::UnitType ResolvedUnitType() const = 0;
+
+ bool IsInteger() const { return is_integer_; }
+
+ bool IsNestedCalc() const { return is_nested_calc_; }
+ void SetIsNestedCalc() { is_nested_calc_ = true; }
+
+ virtual void Trace(blink::Visitor* visitor) {}
+
+ protected:
+ CSSMathExpressionNode(CalculationCategory category, bool is_integer)
+ : category_(category), is_integer_(is_integer) {
+ DCHECK_NE(category, kCalcOther);
+ }
+
+ CalculationCategory category_;
+ bool is_integer_;
+ bool is_nested_calc_ = false;
+};
+
+class CORE_EXPORT CSSMathExpressionNumericLiteral final
+ : public CSSMathExpressionNode {
+ public:
+ static CSSMathExpressionNumericLiteral* Create(CSSNumericLiteralValue* value,
+ bool is_integer = false);
+ static CSSMathExpressionNumericLiteral*
+ Create(double value, CSSPrimitiveValue::UnitType type, bool is_integer);
+
+ CSSMathExpressionNumericLiteral(CSSNumericLiteralValue* value,
+ bool is_integer);
+
+ bool IsNumericLiteral() const final { return true; }
+
+ bool IsZero() const final;
+ String CustomCSSText() const final;
+ void AccumulatePixelsAndPercent(
+ const CSSToLengthConversionData& conversion_data,
+ PixelsAndPercent& value,
+ float multiplier) const final;
+ double DoubleValue() const final;
+ base::Optional<double> ComputeValueInCanonicalUnit() const final;
+ double ComputeLengthPx(
+ const CSSToLengthConversionData& conversion_data) const final;
+ void AccumulateLengthArray(CSSLengthArray& length_array,
+ double multiplier) const final;
+ bool IsComputationallyIndependent() const final;
+ bool operator==(const CSSMathExpressionNode& other) const final;
+ CSSPrimitiveValue::UnitType ResolvedUnitType() const final;
+ void Trace(blink::Visitor* visitor) final;
+
+ private:
+ Member<CSSNumericLiteralValue> value_;
+};
+
+template <>
+struct DowncastTraits<CSSMathExpressionNumericLiteral> {
+ static bool AllowFrom(const CSSMathExpressionNode& node) {
+ return node.IsNumericLiteral();
+ }
+};
+
+class CORE_EXPORT CSSMathExpressionBinaryOperation final
+ : public CSSMathExpressionNode {
+ public:
+ static CSSMathExpressionNode* Create(CSSMathExpressionNode* left_side,
+ CSSMathExpressionNode* right_side,
+ CSSMathOperator op);
+ static CSSMathExpressionNode* CreateSimplified(
+ CSSMathExpressionNode* left_side,
+ CSSMathExpressionNode* right_side,
+ CSSMathOperator op);
+
+ CSSMathExpressionBinaryOperation(CSSMathExpressionNode* left_side,
+ CSSMathExpressionNode* right_side,
+ CSSMathOperator op,
+ CalculationCategory category);
+
+ const CSSMathExpressionNode* LeftExpressionNode() const { return left_side_; }
+ const CSSMathExpressionNode* RightExpressionNode() const {
+ return right_side_;
+ }
+ CSSMathOperator OperatorType() const { return operator_; }
+
+ bool IsBinaryOperation() const final { return true; }
+
+ bool IsZero() const final;
+ void AccumulatePixelsAndPercent(
+ const CSSToLengthConversionData& conversion_data,
+ PixelsAndPercent& value,
+ float multiplier) const final;
+ double DoubleValue() const final;
+ base::Optional<double> ComputeValueInCanonicalUnit() const final;
+ double ComputeLengthPx(
+ const CSSToLengthConversionData& conversion_data) const final;
+ void AccumulateLengthArray(CSSLengthArray& length_array,
+ double multiplier) const final;
+ bool IsComputationallyIndependent() const final;
+ String CustomCSSText() const final;
+ bool operator==(const CSSMathExpressionNode& exp) const final;
+ CSSPrimitiveValue::UnitType ResolvedUnitType() const final;
+ void Trace(blink::Visitor* visitor) final;
+
+ private:
+ static CSSMathExpressionNode* GetNumberSide(
+ CSSMathExpressionNode* left_side,
+ CSSMathExpressionNode* right_side);
+
+ static String BuildCSSText(const String& left_expression,
+ const String& right_expression,
+ CSSMathOperator op);
+
+ double Evaluate(double left_side, double right_side) const {
+ return EvaluateOperator(left_side, right_side, operator_);
+ }
+
+ static double EvaluateOperator(double left_value,
+ double right_value,
+ CSSMathOperator op);
+
+ const Member<CSSMathExpressionNode> left_side_;
+ const Member<CSSMathExpressionNode> right_side_;
+ const CSSMathOperator operator_;
+};
+
+template <>
+struct DowncastTraits<CSSMathExpressionBinaryOperation> {
+ static bool AllowFrom(const CSSMathExpressionNode& node) {
+ return node.IsBinaryOperation();
+ }
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_MATH_EXPRESSION_NODE_H_
diff --git a/chromium/third_party/blink/renderer/core/css/css_calculation_value_test.cc b/chromium/third_party/blink/renderer/core/css/css_math_expression_node_test.cc
index 476ea35887f..8541924455b 100644
--- a/chromium/third_party/blink/renderer/core/css/css_calculation_value_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_math_expression_node_test.cc
@@ -28,9 +28,10 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "third_party/blink/renderer/core/css/css_calculation_value.h"
+#include "third_party/blink/renderer/core/css/css_math_expression_node.h"
#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/renderer/core/css/css_numeric_literal_value.h"
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
#include "third_party/blink/renderer/core/css/css_property_value_set.h"
#include "third_party/blink/renderer/core/css/css_to_length_conversion_data.h"
@@ -48,7 +49,7 @@ namespace {
void TestAccumulatePixelsAndPercent(
const CSSToLengthConversionData& conversion_data,
- CSSCalcExpressionNode* expression,
+ CSSMathExpressionNode* expression,
float expected_pixels,
float expected_percent) {
PixelsAndPercent value(0, 0);
@@ -85,63 +86,64 @@ TEST(CSSCalculationValue, AccumulatePixelsAndPercent) {
TestAccumulatePixelsAndPercent(
conversion_data,
- CSSCalcValue::CreateExpressionNode(
- CSSPrimitiveValue::Create(10, CSSPrimitiveValue::UnitType::kPixels),
+ CSSMathExpressionNumericLiteral::Create(
+ CSSNumericLiteralValue::Create(10,
+ CSSPrimitiveValue::UnitType::kPixels),
true),
50, 0);
TestAccumulatePixelsAndPercent(
conversion_data,
- CSSCalcValue::CreateExpressionNode(
- CSSCalcValue::CreateExpressionNode(
- CSSPrimitiveValue::Create(10,
- CSSPrimitiveValue::UnitType::kPixels),
+ CSSMathExpressionBinaryOperation::Create(
+ CSSMathExpressionNumericLiteral::Create(
+ CSSNumericLiteralValue::Create(
+ 10, CSSPrimitiveValue::UnitType::kPixels),
true),
- CSSCalcValue::CreateExpressionNode(
- CSSPrimitiveValue::Create(20,
- CSSPrimitiveValue::UnitType::kPixels),
+ CSSMathExpressionNumericLiteral::Create(
+ CSSNumericLiteralValue::Create(
+ 20, CSSPrimitiveValue::UnitType::kPixels),
true),
- kCalcAdd),
+ CSSMathOperator::kAdd),
150, 0);
TestAccumulatePixelsAndPercent(
conversion_data,
- CSSCalcValue::CreateExpressionNode(
- CSSCalcValue::CreateExpressionNode(
- CSSPrimitiveValue::Create(1,
- CSSPrimitiveValue::UnitType::kInches),
+ CSSMathExpressionBinaryOperation::Create(
+ CSSMathExpressionNumericLiteral::Create(
+ CSSNumericLiteralValue::Create(
+ 1, CSSPrimitiveValue::UnitType::kInches),
true),
- CSSCalcValue::CreateExpressionNode(
- CSSPrimitiveValue::Create(2,
- CSSPrimitiveValue::UnitType::kNumber),
+ CSSMathExpressionNumericLiteral::Create(
+ CSSNumericLiteralValue::Create(
+ 2, CSSPrimitiveValue::UnitType::kNumber),
true),
- kCalcMultiply),
+ CSSMathOperator::kMultiply),
960, 0);
TestAccumulatePixelsAndPercent(
conversion_data,
- CSSCalcValue::CreateExpressionNode(
- CSSCalcValue::CreateExpressionNode(
- CSSCalcValue::CreateExpressionNode(
- CSSPrimitiveValue::Create(
+ CSSMathExpressionBinaryOperation::Create(
+ CSSMathExpressionBinaryOperation::Create(
+ CSSMathExpressionNumericLiteral::Create(
+ CSSNumericLiteralValue::Create(
50, CSSPrimitiveValue::UnitType::kPixels),
true),
- CSSCalcValue::CreateExpressionNode(
- CSSPrimitiveValue::Create(
+ CSSMathExpressionNumericLiteral::Create(
+ CSSNumericLiteralValue::Create(
0.25, CSSPrimitiveValue::UnitType::kNumber),
false),
- kCalcMultiply),
- CSSCalcValue::CreateExpressionNode(
- CSSCalcValue::CreateExpressionNode(
- CSSPrimitiveValue::Create(
+ CSSMathOperator::kMultiply),
+ CSSMathExpressionBinaryOperation::Create(
+ CSSMathExpressionNumericLiteral::Create(
+ CSSNumericLiteralValue::Create(
20, CSSPrimitiveValue::UnitType::kPixels),
true),
- CSSCalcValue::CreateExpressionNode(
- CSSPrimitiveValue::Create(
+ CSSMathExpressionNumericLiteral::Create(
+ CSSNumericLiteralValue::Create(
40, CSSPrimitiveValue::UnitType::kPercentage),
false),
- kCalcSubtract),
- kCalcSubtract),
+ CSSMathOperator::kSubtract),
+ CSSMathOperator::kSubtract),
-37.5, 40);
}
diff --git a/chromium/third_party/blink/renderer/core/css/css_math_function_value.cc b/chromium/third_party/blink/renderer/core/css/css_math_function_value.cc
new file mode 100644
index 00000000000..9a2ec3a8c92
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/css_math_function_value.cc
@@ -0,0 +1,127 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/css/css_math_function_value.h"
+
+#include "third_party/blink/renderer/core/css/css_math_expression_node.h"
+#include "third_party/blink/renderer/platform/geometry/length.h"
+#include "third_party/blink/renderer/platform/wtf/size_assertions.h"
+#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
+
+namespace blink {
+
+struct SameSizeAsCSSMathFunctionValue : CSSPrimitiveValue {
+ Member<void*> expression;
+};
+ASSERT_SIZE(CSSMathFunctionValue, SameSizeAsCSSMathFunctionValue);
+
+void CSSMathFunctionValue::TraceAfterDispatch(blink::Visitor* visitor) {
+ visitor->Trace(expression_);
+ CSSPrimitiveValue::TraceAfterDispatch(visitor);
+}
+
+CSSMathFunctionValue::CSSMathFunctionValue(CSSMathExpressionNode* expression,
+ ValueRange range)
+ : CSSPrimitiveValue(kMathFunctionClass), expression_(expression) {
+ is_non_negative_math_function_ = range == kValueRangeNonNegative;
+}
+
+// static
+CSSMathFunctionValue* CSSMathFunctionValue::Create(
+ CSSMathExpressionNode* expression,
+ ValueRange range) {
+ if (!expression)
+ return nullptr;
+ return MakeGarbageCollected<CSSMathFunctionValue>(expression, range);
+}
+
+// static
+CSSMathFunctionValue* CSSMathFunctionValue::Create(const Length& length,
+ float zoom) {
+ const CalculationValue& calc = length.GetCalculationValue();
+ return Create(CSSMathExpressionNode::CreateFromPixelsAndPercent(
+ calc.Pixels() / zoom, calc.Percent()),
+ calc.GetValueRange());
+}
+
+bool CSSMathFunctionValue::MayHaveRelativeUnit() const {
+ UnitType resolved_type = expression_->ResolvedUnitType();
+ return IsRelativeUnit(resolved_type) || resolved_type == UnitType::kUnknown;
+}
+
+double CSSMathFunctionValue::DoubleValue() const {
+ return ClampToPermittedRange(expression_->DoubleValue());
+}
+
+double CSSMathFunctionValue::ComputeSeconds() const {
+ DCHECK_EQ(kCalcTime, expression_->Category());
+ // TODO(crbug.com/984372): We currently use 'ms' as the canonical unit of
+ // <time>. Switch to 's' to follow the spec.
+ return *expression_->ComputeValueInCanonicalUnit() / 1000;
+}
+
+double CSSMathFunctionValue::ComputeDegrees() const {
+ DCHECK_EQ(kCalcAngle, expression_->Category());
+ return *expression_->ComputeValueInCanonicalUnit();
+}
+
+double CSSMathFunctionValue::ComputeLengthPx(
+ const CSSToLengthConversionData& conversion_data) const {
+ // |CSSToLengthConversionData| only resolves relative length units, but not
+ // percentages.
+ DCHECK_EQ(kCalcLength, expression_->Category());
+ return ClampToPermittedRange(expression_->ComputeLengthPx(conversion_data));
+}
+
+void CSSMathFunctionValue::AccumulateLengthArray(CSSLengthArray& length_array,
+ double multiplier) const {
+ expression_->AccumulateLengthArray(length_array, multiplier);
+}
+
+Length CSSMathFunctionValue::ConvertToLength(
+ const CSSToLengthConversionData& conversion_data) const {
+ return Length(ToCalcValue(conversion_data));
+}
+
+static String BuildCSSText(const String& expression) {
+ StringBuilder result;
+ result.Append("calc");
+ bool expression_has_single_term = expression[0] != '(';
+ if (expression_has_single_term)
+ result.Append('(');
+ result.Append(expression);
+ if (expression_has_single_term)
+ result.Append(')');
+ return result.ToString();
+}
+
+String CSSMathFunctionValue::CustomCSSText() const {
+ return BuildCSSText(expression_->CustomCSSText());
+}
+
+bool CSSMathFunctionValue::Equals(const CSSMathFunctionValue& other) const {
+ return DataEquivalent(expression_, other.expression_);
+}
+
+double CSSMathFunctionValue::ClampToPermittedRange(double value) const {
+ return IsNonNegative() && value < 0 ? 0 : value;
+}
+
+bool CSSMathFunctionValue::IsZero() const {
+ if (expression_->ResolvedUnitType() == UnitType::kUnknown)
+ return false;
+ return expression_->IsZero();
+}
+
+bool CSSMathFunctionValue::IsPx() const {
+ // TODO(crbug.com/979895): This is the result of refactoring, which might be
+ // an existing bug. Fix it if necessary.
+ return Category() == kCalcLength;
+}
+
+bool CSSMathFunctionValue::IsComputationallyIndependent() const {
+ return expression_->IsComputationallyIndependent();
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/css_math_function_value.h b/chromium/third_party/blink/renderer/core/css/css_math_function_value.h
new file mode 100644
index 00000000000..1e1d9b2aeb3
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/css_math_function_value.h
@@ -0,0 +1,93 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_MATH_FUNCTION_VALUE_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_MATH_FUNCTION_VALUE_H_
+
+#include "third_party/blink/renderer/core/css/css_math_expression_node.h"
+#include "third_party/blink/renderer/core/css/css_primitive_value.h"
+
+namespace blink {
+
+// Numeric values that involve math functions (calc(), min(), max(), etc). This
+// is the equivalence of CSS Typed OM's |CSSMathValue| in the |CSSValue| class
+// hierarchy.
+class CORE_EXPORT CSSMathFunctionValue : public CSSPrimitiveValue {
+ public:
+ static CSSMathFunctionValue* Create(const Length&, float zoom);
+ static CSSMathFunctionValue* Create(CSSMathExpressionNode*,
+ ValueRange = kValueRangeAll);
+
+ CSSMathFunctionValue(CSSMathExpressionNode* expression, ValueRange range);
+
+ CSSMathExpressionNode* ExpressionNode() const { return expression_; }
+
+ scoped_refptr<CalculationValue> ToCalcValue(
+ const CSSToLengthConversionData& conversion_data) const {
+ PixelsAndPercent value(0, 0);
+ expression_->AccumulatePixelsAndPercent(conversion_data, value);
+ return CalculationValue::Create(value, PermittedValueRange());
+ }
+
+ bool MayHaveRelativeUnit() const;
+
+ CalculationCategory Category() const { return expression_->Category(); }
+ bool IsAngle() const { return Category() == kCalcAngle; }
+ bool IsLength() const { return Category() == kCalcLength; }
+ bool IsNumber() const { return Category() == kCalcNumber; }
+ bool IsPercentage() const { return Category() == kCalcPercent; }
+ bool IsTime() const { return Category() == kCalcTime; }
+
+ bool IsPx() const;
+
+ bool IsInt() const { return expression_->IsInteger(); }
+ bool IsNegative() const { return expression_->DoubleValue() < 0; }
+ ValueRange PermittedValueRange() const {
+ return IsNonNegative() ? kValueRangeNonNegative : kValueRangeAll;
+ }
+
+ bool IsZero() const;
+
+ bool IsComputationallyIndependent() const;
+
+ // TODO(crbug.com/979895): The semantics of this function is still not very
+ // clear. Do not add new callers before further refactoring and cleanups.
+ // |DoubleValue()| can be called only when the the math expression can be
+ // resolved into a single numeric value *without any type conversion* (e.g.,
+ // between px and em). Otherwise, it hits a DCHECK.
+ double DoubleValue() const;
+
+ double ComputeSeconds() const;
+ double ComputeDegrees() const;
+ double ComputeLengthPx(
+ const CSSToLengthConversionData& conversion_data) const;
+
+ void AccumulateLengthArray(CSSLengthArray& length_array,
+ double multiplier) const;
+ Length ConvertToLength(
+ const CSSToLengthConversionData& conversion_data) const;
+
+ String CustomCSSText() const;
+ bool Equals(const CSSMathFunctionValue& other) const;
+
+ void TraceAfterDispatch(blink::Visitor* visitor);
+
+ private:
+ bool IsNonNegative() const { return is_non_negative_math_function_; }
+
+ double ClampToPermittedRange(double) const;
+
+ Member<CSSMathExpressionNode> expression_;
+};
+
+template <>
+struct DowncastTraits<CSSMathFunctionValue> {
+ static bool AllowFrom(const CSSValue& value) {
+ return value.IsMathFunctionValue();
+ }
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_MATH_FUNCTION_VALUE_H_
diff --git a/chromium/third_party/blink/renderer/core/css/css_math_operator.cc b/chromium/third_party/blink/renderer/core/css/css_math_operator.cc
new file mode 100644
index 00000000000..38abe530b13
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/css_math_operator.cc
@@ -0,0 +1,45 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/css/css_math_operator.h"
+
+#include "third_party/blink/renderer/core/css/parser/css_parser_token.h"
+#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
+
+namespace blink {
+
+CSSMathOperator ParseCSSArithmeticOperator(const CSSParserToken& token) {
+ if (token.GetType() != kDelimiterToken)
+ return CSSMathOperator::kInvalid;
+ switch (token.Delimiter()) {
+ case '+':
+ return CSSMathOperator::kAdd;
+ case '-':
+ return CSSMathOperator::kSubtract;
+ case '*':
+ return CSSMathOperator::kMultiply;
+ case '/':
+ return CSSMathOperator::kDivide;
+ default:
+ return CSSMathOperator::kInvalid;
+ }
+}
+
+String ToString(CSSMathOperator op) {
+ switch (op) {
+ case CSSMathOperator::kAdd:
+ return "+";
+ case CSSMathOperator::kSubtract:
+ return "-";
+ case CSSMathOperator::kMultiply:
+ return "*";
+ case CSSMathOperator::kDivide:
+ return "/";
+ default:
+ NOTREACHED();
+ return String();
+ }
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/css_math_operator.h b/chromium/third_party/blink/renderer/core/css/css_math_operator.h
new file mode 100644
index 00000000000..99fb20dbac8
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/css_math_operator.h
@@ -0,0 +1,21 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_MATH_OPERATOR_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_MATH_OPERATOR_H_
+
+#include "third_party/blink/renderer/platform/wtf/forward.h"
+
+namespace blink {
+
+class CSSParserToken;
+
+enum class CSSMathOperator { kAdd, kSubtract, kMultiply, kDivide, kInvalid };
+
+CSSMathOperator ParseCSSArithmeticOperator(const CSSParserToken& token);
+String ToString(CSSMathOperator);
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_MATH_OPERATOR_H_
diff --git a/chromium/third_party/blink/renderer/core/css/css_numeric_literal_value.cc b/chromium/third_party/blink/renderer/core/css/css_numeric_literal_value.cc
new file mode 100644
index 00000000000..5bef4f6da46
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/css_numeric_literal_value.cc
@@ -0,0 +1,257 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/css/css_numeric_literal_value.h"
+
+#include "build/build_config.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/wtf/size_assertions.h"
+#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
+
+namespace blink {
+
+struct SameSizeAsCSSNumericLiteralValue : CSSPrimitiveValue {
+ double num;
+};
+ASSERT_SIZE(CSSNumericLiteralValue, SameSizeAsCSSNumericLiteralValue);
+
+void CSSNumericLiteralValue::TraceAfterDispatch(blink::Visitor* visitor) {
+ CSSPrimitiveValue::TraceAfterDispatch(visitor);
+}
+
+CSSNumericLiteralValue::CSSNumericLiteralValue(double num, UnitType type)
+ : CSSPrimitiveValue(kNumericLiteralClass), num_(num) {
+ DCHECK(std::isfinite(num));
+ DCHECK_NE(UnitType::kUnknown, type);
+ numeric_literal_unit_type_ = static_cast<unsigned>(type);
+}
+
+// static
+CSSNumericLiteralValue* CSSNumericLiteralValue::Create(double value,
+ UnitType type) {
+ // TODO(timloh): This looks wrong.
+ if (std::isinf(value))
+ value = 0;
+
+ if (value < 0 || value > CSSValuePool::kMaximumCacheableIntegerValue)
+ return MakeGarbageCollected<CSSNumericLiteralValue>(value, type);
+
+ int int_value = clampTo<int>(value);
+ if (value != int_value)
+ return MakeGarbageCollected<CSSNumericLiteralValue>(value, type);
+
+ CSSValuePool& pool = CssValuePool();
+ CSSNumericLiteralValue* result = nullptr;
+ switch (type) {
+ case CSSPrimitiveValue::UnitType::kPixels:
+ result = pool.PixelCacheValue(int_value);
+ if (!result) {
+ result = pool.SetPixelCacheValue(
+ int_value,
+ MakeGarbageCollected<CSSNumericLiteralValue>(value, type));
+ }
+ return result;
+ case CSSPrimitiveValue::UnitType::kPercentage:
+ result = pool.PercentCacheValue(int_value);
+ if (!result) {
+ result = pool.SetPercentCacheValue(
+ int_value,
+ MakeGarbageCollected<CSSNumericLiteralValue>(value, type));
+ }
+ return result;
+ case CSSPrimitiveValue::UnitType::kNumber:
+ case CSSPrimitiveValue::UnitType::kInteger:
+ result = pool.NumberCacheValue(int_value);
+ if (!result) {
+ result = pool.SetNumberCacheValue(
+ int_value, MakeGarbageCollected<CSSNumericLiteralValue>(
+ value, CSSPrimitiveValue::UnitType::kInteger));
+ }
+ return result;
+ default:
+ return MakeGarbageCollected<CSSNumericLiteralValue>(value, type);
+ }
+}
+
+double CSSNumericLiteralValue::ComputeSeconds() const {
+ DCHECK(IsTime());
+ UnitType current_type = GetType();
+ if (current_type == UnitType::kSeconds)
+ return num_;
+ if (current_type == UnitType::kMilliseconds)
+ return num_ / 1000;
+ NOTREACHED();
+ return 0;
+}
+
+double CSSNumericLiteralValue::ComputeDegrees() const {
+ DCHECK(IsAngle());
+ UnitType current_type = GetType();
+ switch (current_type) {
+ case UnitType::kDegrees:
+ return num_;
+ case UnitType::kRadians:
+ return rad2deg(num_);
+ case UnitType::kGradians:
+ return grad2deg(num_);
+ case UnitType::kTurns:
+ return turn2deg(num_);
+ default:
+ NOTREACHED();
+ return 0;
+ }
+}
+
+double CSSNumericLiteralValue::ComputeDotsPerPixel() const {
+ DCHECK(IsResolution());
+ return DoubleValue() * ConversionToCanonicalUnitsScaleFactor(GetType());
+}
+
+double CSSNumericLiteralValue::ComputeLengthPx(
+ const CSSToLengthConversionData& conversion_data) const {
+ DCHECK(IsLength());
+ return conversion_data.ZoomedComputedPixels(num_, GetType());
+}
+
+void CSSNumericLiteralValue::AccumulateLengthArray(CSSLengthArray& length_array,
+ double multiplier) const {
+ LengthUnitType length_type;
+ bool conversion_success = UnitTypeToLengthUnitType(GetType(), length_type);
+ DCHECK(conversion_success);
+ length_array.values[length_type] +=
+ num_ * ConversionToCanonicalUnitsScaleFactor(GetType()) * multiplier;
+ length_array.type_flags.set(length_type);
+}
+
+bool CSSNumericLiteralValue::IsComputationallyIndependent() const {
+ if (!IsLength())
+ return true;
+ if (IsViewportPercentageLength())
+ return true;
+ return !IsRelativeUnit(GetType());
+}
+
+static String FormatNumber(double number, const char* suffix) {
+#if defined(OS_WIN) && _MSC_VER < 1900
+ unsigned oldFormat = _set_output_format(_TWO_DIGIT_EXPONENT);
+#endif
+ String result = String::Format("%.6g%s", number, suffix);
+#if defined(OS_WIN) && _MSC_VER < 1900
+ _set_output_format(oldFormat);
+#endif
+ return result;
+}
+
+String CSSNumericLiteralValue::CustomCSSText() const {
+ String text;
+ switch (GetType()) {
+ case UnitType::kUnknown:
+ // FIXME
+ break;
+ case UnitType::kInteger:
+ text = String::Number(GetIntValue());
+ break;
+ case UnitType::kNumber:
+ case UnitType::kPercentage:
+ case UnitType::kEms:
+ case UnitType::kQuirkyEms:
+ case UnitType::kExs:
+ case UnitType::kRems:
+ case UnitType::kChs:
+ case UnitType::kPixels:
+ case UnitType::kCentimeters:
+ case UnitType::kDotsPerPixel:
+ case UnitType::kDotsPerInch:
+ case UnitType::kDotsPerCentimeter:
+ case UnitType::kMillimeters:
+ case UnitType::kQuarterMillimeters:
+ case UnitType::kInches:
+ case UnitType::kPoints:
+ case UnitType::kPicas:
+ case UnitType::kUserUnits:
+ case UnitType::kDegrees:
+ case UnitType::kRadians:
+ case UnitType::kGradians:
+ case UnitType::kMilliseconds:
+ case UnitType::kSeconds:
+ case UnitType::kHertz:
+ case UnitType::kKilohertz:
+ case UnitType::kTurns:
+ case UnitType::kFraction:
+ case UnitType::kViewportWidth:
+ case UnitType::kViewportHeight:
+ case UnitType::kViewportMin:
+ case UnitType::kViewportMax: {
+ // The following integers are minimal and maximum integers which can
+ // be represented in non-exponential format with 6 digit precision.
+ constexpr int kMinInteger = -999999;
+ constexpr int kMaxInteger = 999999;
+ double value = To<CSSNumericLiteralValue>(this)->DoubleValue();
+ // If the value is small integer, go the fast path.
+ if (value < kMinInteger || value > kMaxInteger ||
+ std::trunc(value) != value) {
+ text = FormatNumber(value, UnitTypeToString(GetType()));
+ } else {
+ StringBuilder builder;
+ int int_value = value;
+ const char* unit_type = UnitTypeToString(GetType());
+ builder.AppendNumber(int_value);
+ builder.Append(unit_type, strlen(unit_type));
+ text = builder.ToString();
+ }
+ } break;
+ default:
+ NOTREACHED();
+ break;
+ }
+ return text;
+}
+
+bool CSSNumericLiteralValue::Equals(const CSSNumericLiteralValue& other) const {
+ if (GetType() != other.GetType())
+ return false;
+
+ switch (GetType()) {
+ case UnitType::kUnknown:
+ return false;
+ case UnitType::kNumber:
+ case UnitType::kInteger:
+ case UnitType::kPercentage:
+ case UnitType::kEms:
+ case UnitType::kExs:
+ case UnitType::kRems:
+ case UnitType::kPixels:
+ case UnitType::kCentimeters:
+ case UnitType::kDotsPerPixel:
+ case UnitType::kDotsPerInch:
+ case UnitType::kDotsPerCentimeter:
+ case UnitType::kMillimeters:
+ case UnitType::kQuarterMillimeters:
+ case UnitType::kInches:
+ case UnitType::kPoints:
+ case UnitType::kPicas:
+ case UnitType::kUserUnits:
+ case UnitType::kDegrees:
+ case UnitType::kRadians:
+ case UnitType::kGradians:
+ case UnitType::kMilliseconds:
+ case UnitType::kSeconds:
+ case UnitType::kHertz:
+ case UnitType::kKilohertz:
+ case UnitType::kTurns:
+ case UnitType::kViewportWidth:
+ case UnitType::kViewportHeight:
+ case UnitType::kViewportMin:
+ case UnitType::kViewportMax:
+ case UnitType::kFraction:
+ return num_ == other.num_;
+ case UnitType::kQuirkyEms:
+ return false;
+ default:
+ return false;
+ }
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/css_numeric_literal_value.h b/chromium/third_party/blink/renderer/core/css/css_numeric_literal_value.h
new file mode 100644
index 00000000000..8e356841f25
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/css_numeric_literal_value.h
@@ -0,0 +1,80 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_NUMERIC_LITERAL_VALUE_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_NUMERIC_LITERAL_VALUE_H_
+
+#include "third_party/blink/renderer/core/css/css_primitive_value.h"
+
+namespace blink {
+
+// Numeric values that can be expressed as a single unit (or a naked number or
+// percentage). The equivalence of CSS Typed OM's |CSSUnitValue| in the
+// |CSSValue| class hierarchy.
+class CORE_EXPORT CSSNumericLiteralValue : public CSSPrimitiveValue {
+ public:
+ static CSSNumericLiteralValue* Create(double num, UnitType);
+
+ CSSNumericLiteralValue(double num, UnitType type);
+
+ UnitType GetType() const {
+ return static_cast<UnitType>(numeric_literal_unit_type_);
+ }
+
+ bool IsAngle() const { return CSSPrimitiveValue::IsAngle(GetType()); }
+ bool IsFontRelativeLength() const {
+ return GetType() == UnitType::kQuirkyEms || GetType() == UnitType::kEms ||
+ GetType() == UnitType::kExs || GetType() == UnitType::kRems ||
+ GetType() == UnitType::kChs;
+ }
+ bool IsQuirkyEms() const { return GetType() == UnitType::kQuirkyEms; }
+ bool IsViewportPercentageLength() const {
+ return CSSPrimitiveValue::IsViewportPercentageLength(GetType());
+ }
+ bool IsLength() const { return CSSPrimitiveValue::IsLength(GetType()); }
+ bool IsPx() const { return GetType() == UnitType::kPixels; }
+ bool IsNumber() const {
+ return GetType() == UnitType::kNumber || GetType() == UnitType::kInteger;
+ }
+ bool IsInteger() const { return GetType() == UnitType::kInteger; }
+ bool IsPercentage() const { return GetType() == UnitType::kPercentage; }
+ bool IsTime() const { return CSSPrimitiveValue::IsTime(GetType()); }
+ bool IsResolution() const {
+ return CSSPrimitiveValue::IsResolution(GetType());
+ }
+ bool IsFlex() const { return CSSPrimitiveValue::IsFlex(GetType()); }
+
+ bool IsZero() const { return !DoubleValue(); }
+
+ bool IsComputationallyIndependent() const;
+
+ double DoubleValue() const { return num_; }
+ double ComputeSeconds() const;
+ double ComputeDegrees() const;
+ double ComputeDotsPerPixel() const;
+
+ double ComputeLengthPx(
+ const CSSToLengthConversionData& conversion_data) const;
+ void AccumulateLengthArray(CSSLengthArray& length_array,
+ double multiplier) const;
+
+ String CustomCSSText() const;
+ bool Equals(const CSSNumericLiteralValue& other) const;
+
+ void TraceAfterDispatch(blink::Visitor* visitor);
+
+ private:
+ double num_;
+};
+
+template <>
+struct DowncastTraits<CSSNumericLiteralValue> {
+ static bool AllowFrom(const CSSValue& value) {
+ return value.IsNumericLiteralValue();
+ }
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_NUMERIC_LITERAL_VALUE_H_
diff --git a/chromium/third_party/blink/renderer/core/css/css_origin_clean.h b/chromium/third_party/blink/renderer/core/css/css_origin_clean.h
new file mode 100644
index 00000000000..a9468336c6d
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/css_origin_clean.h
@@ -0,0 +1,11 @@
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_ORIGIN_CLEAN_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_ORIGIN_CLEAN_H_
+
+namespace blink {
+
+// https://drafts.csswg.org/cssom-1/#concept-css-style-sheet-origin-clean-flag
+enum class OriginClean { kFalse, kTrue };
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_ORIGIN_CLEAN_H_
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 8e12c17f900..916a4561287 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
@@ -52,7 +52,8 @@ class CORE_EXPORT CSSPaintImageGenerator
// The |container_size| is the container size with subpixel snapping.
virtual scoped_refptr<Image> Paint(const ImageResourceObserver&,
const FloatSize& container_size,
- const CSSStyleValueVector*) = 0;
+ const CSSStyleValueVector*,
+ float device_scale_factor) = 0;
virtual const Vector<CSSPropertyID>& NativeInvalidationProperties() const = 0;
virtual const Vector<AtomicString>& CustomInvalidationProperties() 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 944dacb2c70..a4c875a55cb 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
@@ -5,11 +5,15 @@
#include "third_party/blink/renderer/core/css/css_paint_value.h"
#include "third_party/blink/renderer/core/css/css_custom_ident_value.h"
+#include "third_party/blink/renderer/core/css/css_paint_image_generator.h"
#include "third_party/blink/renderer/core/css/css_syntax_descriptor.h"
#include "third_party/blink/renderer/core/css/cssom/paint_worklet_deferred_image.h"
#include "third_party/blink/renderer/core/css/cssom/paint_worklet_input.h"
#include "third_party/blink/renderer/core/css/cssom/style_value_factory.h"
+#include "third_party/blink/renderer/core/css/properties/computed_style_utils.h"
+#include "third_party/blink/renderer/core/frame/local_frame.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/graphics/image.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
@@ -18,7 +22,8 @@ namespace blink {
CSSPaintValue::CSSPaintValue(CSSCustomIdentValue* name)
: CSSImageGeneratorValue(kPaintClass),
name_(name),
- paint_image_generator_observer_(MakeGarbageCollected<Observer>(this)) {}
+ paint_image_generator_observer_(MakeGarbageCollected<Observer>(this)),
+ paint_off_thread_(true) {}
CSSPaintValue::CSSPaintValue(
CSSCustomIdentValue* name,
@@ -60,39 +65,70 @@ scoped_refptr<Image> CSSPaintValue::GetImage(
GetName(), document, paint_image_generator_observer_);
}
+ // If the generator isn't ready yet, we have nothing to paint. Our
+ // |paint_image_generator_observer_| will cause us to be called again once the
+ // generator is ready.
+ if (!generator_->IsImageGeneratorReady())
+ return nullptr;
+
+ if (!ParseInputArguments(document))
+ return nullptr;
+
+ // TODO(crbug.com/946515): Break dependency on LayoutObject.
+ const LayoutObject& layout_object = static_cast<const LayoutObject&>(client);
+
+ // TODO(crbug.com/716231): Remove this hack once zoom_for_dsf is enabled on
+ // all platforms (currently not enabled on Mac).
+ float device_scale_factor = 1;
+ if (layout_object.GetFrame() && layout_object.GetFrame()->GetPage()) {
+ // The value of DeviceScaleFactorDeprecated would be 1 on a platform where
+ // zoom_for_dsf is enabled, even if we run chrome with
+ // --force-device-scale-factor with a value that is not 1.
+ device_scale_factor =
+ layout_object.GetFrame()->GetPage()->DeviceScaleFactorDeprecated();
+ }
+
// For Off-Thread PaintWorklet, we just collect the necessary inputs together
// and defer the actual JavaScript call until much later (during cc Raster).
if (RuntimeEnabledFeatures::OffMainThreadCSSPaintEnabled()) {
- // If the main-thread does not yet know about this painter, there is no
- // point sending it to cc - they won't be able to paint it. Once (or if) a
- // matching painter is registered the |paint_image_generator_observer_| will
- // cause us to be repainted.
- if (!generator_->IsImageGeneratorReady())
- return nullptr;
-
- // TODO(crbug.com/946515): Break dependency on LayoutObject.
- const LayoutObject& layout_object =
- static_cast<const LayoutObject&>(client);
- Vector<CSSPropertyID> native_properties =
- generator_->NativeInvalidationProperties();
- Vector<AtomicString> custom_properties =
- generator_->CustomInvalidationProperties();
- float zoom = layout_object.StyleRef().EffectiveZoom();
- PaintWorkletStylePropertyMap::CrossThreadData style_data =
- PaintWorkletStylePropertyMap::BuildCrossThreadData(
- document, style, layout_object.GetNode(), native_properties,
- custom_properties);
- scoped_refptr<PaintWorkletInput> input =
- base::MakeRefCounted<PaintWorkletInput>(GetName(), target_size, zoom,
- generator_->WorkletId(),
- std::move(style_data));
- return PaintWorkletDeferredImage::Create(std::move(input), target_size);
+ if (paint_off_thread_) {
+ Vector<CSSPropertyID> native_properties =
+ generator_->NativeInvalidationProperties();
+ Vector<AtomicString> custom_properties =
+ generator_->CustomInvalidationProperties();
+ float zoom = layout_object.StyleRef().EffectiveZoom();
+ auto style_data = PaintWorkletStylePropertyMap::BuildCrossThreadData(
+ document, style, layout_object.GetNode(), native_properties,
+ custom_properties);
+ paint_off_thread_ = style_data.has_value();
+ if (paint_off_thread_) {
+ Vector<std::unique_ptr<CrossThreadStyleValue>>
+ cross_thread_input_arguments;
+ BuildInputArgumentValues(cross_thread_input_arguments);
+ scoped_refptr<PaintWorkletInput> input =
+ base::MakeRefCounted<PaintWorkletInput>(
+ GetName(), target_size, zoom, generator_->WorkletId(),
+ std::move(style_data.value()),
+ std::move(cross_thread_input_arguments));
+ return PaintWorkletDeferredImage::Create(std::move(input), target_size);
+ }
+ }
}
- if (!ParseInputArguments(document))
- return nullptr;
+ return generator_->Paint(client, target_size, parsed_input_arguments_,
+ device_scale_factor);
+}
- return generator_->Paint(client, target_size, parsed_input_arguments_);
+void CSSPaintValue::BuildInputArgumentValues(
+ Vector<std::unique_ptr<CrossThreadStyleValue>>&
+ cross_thread_input_arguments) {
+ if (!parsed_input_arguments_)
+ return;
+ for (const auto& style_value : *parsed_input_arguments_) {
+ std::unique_ptr<CrossThreadStyleValue> cross_thread_style =
+ ComputedStyleUtils::CrossThreadStyleValueFromCSSStyleValue(style_value);
+ cross_thread_input_arguments.push_back(std::move(cross_thread_style));
+ }
}
bool CSSPaintValue::ParseInputArguments(const Document& document) {
@@ -103,9 +139,7 @@ bool CSSPaintValue::ParseInputArguments(const Document& document) {
!RuntimeEnabledFeatures::CSSPaintAPIArgumentsEnabled())
return true;
- if (!generator_->IsImageGeneratorReady())
- return false;
-
+ DCHECK(generator_->IsImageGeneratorReady());
const Vector<CSSSyntaxDescriptor>& input_argument_types =
generator_->InputArgumentTypes();
if (argument_variable_data_.size() != input_argument_types.size()) {
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 9c9530736c3..91433563dd8 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
@@ -10,6 +10,7 @@
#include "third_party/blink/renderer/core/css/css_image_generator_value.h"
#include "third_party/blink/renderer/core/css/css_paint_image_generator.h"
#include "third_party/blink/renderer/core/css/css_variable_data.h"
+#include "third_party/blink/renderer/core/css/cssom/cross_thread_style_value.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/wtf/casting.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
@@ -50,6 +51,14 @@ class CORE_EXPORT CSSPaintValue : public CSSImageGeneratorValue {
return generator_ ? &generator_->CustomInvalidationProperties() : nullptr;
}
+ const CSSStyleValueVector* GetParsedInputArgumentsForTesting() {
+ return parsed_input_arguments_;
+ }
+ void BuildInputArgumentValuesForTesting(
+ Vector<std::unique_ptr<CrossThreadStyleValue>>& style_value) {
+ BuildInputArgumentValues(style_value);
+ }
+
void TraceAfterDispatch(blink::Visitor*);
private:
@@ -74,6 +83,9 @@ class CORE_EXPORT CSSPaintValue : public CSSImageGeneratorValue {
bool ParseInputArguments(const Document&);
+ void BuildInputArgumentValues(
+ Vector<std::unique_ptr<CrossThreadStyleValue>>&);
+
bool input_arguments_invalid_ = false;
Member<CSSCustomIdentValue> name_;
@@ -81,6 +93,7 @@ class CORE_EXPORT CSSPaintValue : public CSSImageGeneratorValue {
Member<Observer> paint_image_generator_observer_;
Member<CSSStyleValueVector> parsed_input_arguments_;
Vector<scoped_refptr<CSSVariableData>> argument_variable_data_;
+ bool paint_off_thread_;
};
template <>
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 33978311a70..7fead3923bc 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
@@ -29,16 +29,29 @@ using testing::Values;
namespace blink {
namespace {
+enum {
+ kCSSPaintAPIArguments = 1 << 0,
+ kOffMainThreadCSSPaint = 1 << 1,
+};
+
class CSSPaintValueTest : public RenderingTest,
- public ::testing::WithParamInterface<bool> {
+ public ::testing::WithParamInterface<unsigned>,
+ private ScopedCSSPaintAPIArgumentsForTest,
+ private ScopedOffMainThreadCSSPaintForTest {
public:
- CSSPaintValueTest() : scoped_off_main_thread_css_paint_(GetParam()) {}
-
- private:
- ScopedOffMainThreadCSSPaintForTest scoped_off_main_thread_css_paint_;
+ CSSPaintValueTest()
+ : ScopedCSSPaintAPIArgumentsForTest(GetParam() & kCSSPaintAPIArguments),
+ ScopedOffMainThreadCSSPaintForTest(GetParam() &
+ kOffMainThreadCSSPaint) {}
};
-INSTANTIATE_TEST_SUITE_P(, CSSPaintValueTest, Values(false, true));
+INSTANTIATE_TEST_SUITE_P(,
+ CSSPaintValueTest,
+ Values(0,
+ kCSSPaintAPIArguments,
+ kOffMainThreadCSSPaint,
+ kCSSPaintAPIArguments |
+ kOffMainThreadCSSPaint));
class MockCSSPaintImageGenerator : public CSSPaintImageGenerator {
public:
@@ -53,10 +66,11 @@ class MockCSSPaintImageGenerator : public CSSPaintImageGenerator {
.WillByDefault(ReturnRef(input_argument_types_));
}
- MOCK_METHOD3(Paint,
+ MOCK_METHOD4(Paint,
scoped_refptr<Image>(const ImageResourceObserver&,
const FloatSize& container_size,
- const CSSStyleValueVector*));
+ const CSSStyleValueVector*,
+ float device_scale_factor));
MOCK_CONST_METHOD0(NativeInvalidationProperties, Vector<CSSPropertyID>&());
MOCK_CONST_METHOD0(CustomInvalidationProperties, Vector<AtomicString>&());
MOCK_CONST_METHOD0(HasAlpha, bool());
@@ -93,14 +107,6 @@ TEST_P(CSSPaintValueTest, DelayPaintUntilGeneratorReady) {
ProvideOverrideGenerator);
const FloatSize target_size(100, 100);
- if (RuntimeEnabledFeatures::OffMainThreadCSSPaintEnabled()) {
- // In off-thread CSS Paint, the actual paint call is deferred.
- EXPECT_CALL(*mock_generator, Paint(_, _, _)).Times(0);
- } else {
- ON_CALL(*mock_generator, Paint(_, _, _))
- .WillByDefault(
- Return(PaintGeneratedImage::Create(nullptr, target_size)));
- }
SetBodyInnerHTML(R"HTML(
<div id="target"></div>
@@ -111,12 +117,22 @@ TEST_P(CSSPaintValueTest, DelayPaintUntilGeneratorReady) {
auto* ident = MakeGarbageCollected<CSSCustomIdentValue>("testpainter");
CSSPaintValue* paint_value = MakeGarbageCollected<CSSPaintValue>(ident);
- // Initially the generator is not ready, so GetImage should fail.
+ // Initially the generator is not ready, so GetImage should fail (and no paint
+ // should happen).
+ EXPECT_CALL(*mock_generator, Paint(_, _, _, _)).Times(0);
EXPECT_FALSE(
paint_value->GetImage(*target, GetDocument(), style, target_size));
// Now mark the generator as ready - GetImage should then succeed.
- EXPECT_CALL(*mock_generator, IsImageGeneratorReady()).WillOnce(Return(true));
+ ON_CALL(*mock_generator, IsImageGeneratorReady()).WillByDefault(Return(true));
+ // In off-thread CSS Paint, the actual paint call is deferred and so will
+ // never happen.
+ if (!RuntimeEnabledFeatures::OffMainThreadCSSPaintEnabled()) {
+ EXPECT_CALL(*mock_generator, Paint(_, _, _, _))
+ .WillRepeatedly(
+ Return(PaintGeneratedImage::Create(nullptr, target_size)));
+ }
+
EXPECT_TRUE(
paint_value->GetImage(*target, GetDocument(), style, target_size));
}
@@ -171,4 +187,14 @@ TEST_P(CSSPaintValueTest, DoNotPaintWhenAncestorHasLink) {
FloatSize(100, 100)));
}
+TEST_P(CSSPaintValueTest, BuildInputArgumentValuesNotCrash) {
+ auto* ident = MakeGarbageCollected<CSSCustomIdentValue>("testpainter");
+ CSSPaintValue* paint_value = MakeGarbageCollected<CSSPaintValue>(ident);
+
+ ASSERT_EQ(paint_value->GetParsedInputArgumentsForTesting(), nullptr);
+ Vector<std::unique_ptr<CrossThreadStyleValue>> cross_thread_input_arguments;
+ paint_value->BuildInputArgumentValuesForTesting(cross_thread_input_arguments);
+ EXPECT_EQ(cross_thread_input_arguments.size(), 0u);
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/css_pending_interpolation_value.cc b/chromium/third_party/blink/renderer/core/css/css_pending_interpolation_value.cc
new file mode 100644
index 00000000000..d9756e104f9
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/css_pending_interpolation_value.cc
@@ -0,0 +1,19 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/css/css_pending_interpolation_value.h"
+#include "third_party/blink/renderer/core/css/css_value_pool.h"
+
+namespace blink {
+namespace cssvalue {
+
+CSSPendingInterpolationValue* CSSPendingInterpolationValue::Create(Type type) {
+ return CssValuePool().PendingInterpolationValue(type);
+}
+
+CSSPendingInterpolationValue::CSSPendingInterpolationValue(Type type)
+ : CSSValue(kPendingInterpolationClass), type_(type) {}
+
+} // namespace cssvalue
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/css_pending_interpolation_value.h b/chromium/third_party/blink/renderer/core/css/css_pending_interpolation_value.h
new file mode 100644
index 00000000000..cc8ee8371e6
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/css_pending_interpolation_value.h
@@ -0,0 +1,61 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_PENDING_INTERPOLATION_VALUE_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_PENDING_INTERPOLATION_VALUE_H_
+
+#include "third_party/blink/renderer/core/css/css_property_name.h"
+#include "third_party/blink/renderer/core/css/css_value.h"
+#include "third_party/blink/renderer/platform/wtf/casting.h"
+
+namespace blink {
+
+namespace cssvalue {
+
+// A CSSPendingInterpolationValue represents a value which we don't yet know
+// what is, but we know that it's the result of an ongoing interpolation.
+// It is a way for interpolations to participate in the cascade, without
+// knowing the exact value cascade-time.
+//
+// See StyleCascade::Animator for more information.
+class CORE_EXPORT CSSPendingInterpolationValue : public CSSValue {
+ public:
+ enum class Type {
+ kCSSProperty,
+ kPresentationAttribute,
+ };
+
+ static CSSPendingInterpolationValue* Create(Type);
+ CSSPendingInterpolationValue(Type);
+
+ bool IsCSSProperty() const { return type_ == Type::kCSSProperty; }
+ bool IsPresentationAttribute() const {
+ return type_ == Type::kPresentationAttribute;
+ }
+ bool Equals(const CSSPendingInterpolationValue& v) const {
+ return type_ == v.type_;
+ }
+
+ String CustomCSSText() const { return ""; }
+
+ void TraceAfterDispatch(blink::Visitor* visitor) {
+ CSSValue::TraceAfterDispatch(visitor);
+ }
+
+ private:
+ Type type_;
+};
+
+} // namespace cssvalue
+
+template <>
+struct DowncastTraits<cssvalue::CSSPendingInterpolationValue> {
+ static bool AllowFrom(const CSSValue& value) {
+ return value.IsPendingInterpolationValue();
+ }
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_PENDING_INTERPOLATION_VALUE_H_
diff --git a/chromium/third_party/blink/renderer/core/css/css_pending_interpolation_value_test.cc b/chromium/third_party/blink/renderer/core/css/css_pending_interpolation_value_test.cc
new file mode 100644
index 00000000000..99ac8d4953e
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/css_pending_interpolation_value_test.cc
@@ -0,0 +1,55 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/css/css_pending_interpolation_value.h"
+
+#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/renderer/core/css/css_test_helpers.h"
+#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
+
+namespace blink {
+namespace {
+
+using namespace cssvalue;
+using Type = CSSPendingInterpolationValue::Type;
+
+CSSPendingInterpolationValue* Create(Type type) {
+ return CSSPendingInterpolationValue::Create(type);
+}
+
+TEST(CSSPendingInterpolationValueTest, Create) {
+ EXPECT_TRUE(Create(Type::kCSSProperty));
+ EXPECT_TRUE(Create(Type::kPresentationAttribute));
+}
+
+TEST(CSSPendingInterpolationValueTest, Pool) {
+ const auto* value1 = Create(Type::kCSSProperty);
+ const auto* value2 = Create(Type::kCSSProperty);
+ const auto* value3 = Create(Type::kPresentationAttribute);
+ const auto* value4 = Create(Type::kPresentationAttribute);
+ EXPECT_EQ(value1, value2);
+ EXPECT_EQ(value3, value4);
+ EXPECT_NE(value1, value4);
+}
+
+TEST(CSSPendingInterpolationValueTest, Equals) {
+ const auto* value1 = Create(Type::kCSSProperty);
+ const auto* value2 = Create(Type::kCSSProperty);
+ const auto* value3 = Create(Type::kPresentationAttribute);
+ const auto* value4 = Create(Type::kPresentationAttribute);
+ EXPECT_TRUE(value1->Equals(*value2));
+ EXPECT_TRUE(value2->Equals(*value1));
+ EXPECT_TRUE(value3->Equals(*value4));
+ EXPECT_TRUE(value4->Equals(*value3));
+ EXPECT_FALSE(value1->Equals(*value4));
+ EXPECT_FALSE(value4->Equals(*value1));
+}
+
+TEST(CSSPendingInterpolationValueTest, CustomCSSText) {
+ EXPECT_EQ("", Create(Type::kCSSProperty)->CustomCSSText());
+ EXPECT_EQ("", Create(Type::kPresentationAttribute)->CustomCSSText());
+}
+
+} // namespace
+} // namespace blink
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 6e843c5de88..8b897099f7b 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
@@ -24,8 +24,10 @@
#include <cmath>
#include "build/build_config.h"
-#include "third_party/blink/renderer/core/css/css_calculation_value.h"
#include "third_party/blink/renderer/core/css/css_markup.h"
+#include "third_party/blink/renderer/core/css/css_math_expression_node.h"
+#include "third_party/blink/renderer/core/css/css_math_function_value.h"
+#include "third_party/blink/renderer/core/css/css_numeric_literal_value.h"
#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"
@@ -48,7 +50,6 @@ const int kMinValueForCssLength = INT_MIN / kFixedPointDenominator + 2;
} // namespace
struct SameSizeAsCSSPrimitiveValue : CSSValue {
- double num;
};
ASSERT_SIZE(CSSPrimitiveValue, SameSizeAsCSSPrimitiveValue);
@@ -92,181 +93,133 @@ CSSPrimitiveValue::UnitCategory CSSPrimitiveValue::UnitTypeToUnitCategory(
}
}
-CSSPrimitiveValue* CSSPrimitiveValue::Create(double value, UnitType type) {
- // TODO(timloh): This looks wrong.
- if (std::isinf(value))
- value = 0;
+bool CSSPrimitiveValue::IsCalculatedPercentageWithLength() const {
+ // TODO(crbug.com/979895): Move this function to |CSSMathFunctionValue|.
+ return IsCalculated() &&
+ To<CSSMathFunctionValue>(this)->Category() == kCalcPercentLength;
+}
- if (value < 0 || value > CSSValuePool::kMaximumCacheableIntegerValue)
- return MakeGarbageCollected<CSSPrimitiveValue>(value, type);
+bool CSSPrimitiveValue::IsFontRelativeLength() const {
+ // TODO(crbug.com/979895): Move this function to |CSSNumericLiteralValue|.
+ return IsNumericLiteralValue() &&
+ To<CSSNumericLiteralValue>(this)->IsFontRelativeLength();
+}
- int int_value = clampTo<int>(value);
- if (value != int_value)
- return MakeGarbageCollected<CSSPrimitiveValue>(value, type);
+bool CSSPrimitiveValue::IsResolution() const {
+ // TODO(style-dev): Either support math functions on resolutions; or provide a
+ // justification for not supporting it, and move this function to
+ // |CSSNumericLiteralValue|.
+ return IsNumericLiteralValue() &&
+ To<CSSNumericLiteralValue>(this)->IsResolution();
+}
- CSSValuePool& pool = CssValuePool();
- CSSPrimitiveValue* result = nullptr;
- switch (type) {
- case CSSPrimitiveValue::UnitType::kPixels:
- result = pool.PixelCacheValue(int_value);
- 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, 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, MakeGarbageCollected<CSSPrimitiveValue>(
- value, CSSPrimitiveValue::UnitType::kInteger));
- return result;
- default:
- return MakeGarbageCollected<CSSPrimitiveValue>(value, type);
- }
+bool CSSPrimitiveValue::IsFlex() const {
+ // TODO(style-dev): Either support math functions on flexible lengths; or
+ // provide a justification for not supporting it, and move this function to
+ // |CSSNumericLiteralValue|.
+ return IsNumericLiteralValue() && To<CSSNumericLiteralValue>(this)->IsFlex();
}
-CSSPrimitiveValue::UnitType CSSPrimitiveValue::TypeWithCalcResolved() const {
- if (GetType() != UnitType::kCalc)
- return GetType();
+bool CSSPrimitiveValue::IsAngle() const {
+ if (IsNumericLiteralValue())
+ return To<CSSNumericLiteralValue>(this)->IsAngle();
+ return To<CSSMathFunctionValue>(this)->IsAngle();
+}
- switch (value_.calc->Category()) {
- case kCalcAngle:
- return UnitType::kDegrees;
- case kCalcFrequency:
- return UnitType::kHertz;
- case kCalcNumber:
- return UnitType::kNumber;
- case kCalcPercent:
- return UnitType::kPercentage;
- case kCalcLength:
- return UnitType::kPixels;
- case kCalcPercentNumber:
- return UnitType::kCalcPercentageWithNumber;
- case kCalcPercentLength:
- return UnitType::kCalcPercentageWithLength;
- case kCalcLengthNumber:
- return UnitType::kCalcLengthWithNumber;
- case kCalcPercentLengthNumber:
- return UnitType::kCalcPercentageWithLengthAndNumber;
- case kCalcTime:
- return UnitType::kMilliseconds;
- case kCalcOther:
- return UnitType::kUnknown;
- }
- return UnitType::kUnknown;
+bool CSSPrimitiveValue::IsLength() const {
+ if (IsNumericLiteralValue())
+ return To<CSSNumericLiteralValue>(this)->IsLength();
+ return To<CSSMathFunctionValue>(this)->IsLength();
+}
+
+bool CSSPrimitiveValue::IsPx() const {
+ if (IsNumericLiteralValue())
+ return To<CSSNumericLiteralValue>(this)->IsPx();
+ return To<CSSMathFunctionValue>(this)->IsPx();
+}
+
+bool CSSPrimitiveValue::IsNumber() const {
+ if (IsNumericLiteralValue())
+ return To<CSSNumericLiteralValue>(this)->IsNumber();
+ return To<CSSMathFunctionValue>(this)->IsNumber();
+}
+
+bool CSSPrimitiveValue::IsInteger() const {
+ // TODO(style-dev): Support integer math functions properly.
+ return IsNumericLiteralValue() &&
+ To<CSSNumericLiteralValue>(this)->IsInteger();
+}
+
+bool CSSPrimitiveValue::IsPercentage() const {
+ if (IsNumericLiteralValue())
+ return To<CSSNumericLiteralValue>(this)->IsPercentage();
+ return To<CSSMathFunctionValue>(this)->IsPercentage();
}
-CSSPrimitiveValue::CSSPrimitiveValue(double num, UnitType type)
- : CSSValue(kPrimitiveClass) {
- Init(type);
- DCHECK(std::isfinite(num));
- value_.num = num;
+bool CSSPrimitiveValue::IsTime() const {
+ if (IsNumericLiteralValue())
+ return To<CSSNumericLiteralValue>(this)->IsTime();
+ return To<CSSMathFunctionValue>(this)->IsTime();
}
-CSSPrimitiveValue::CSSPrimitiveValue(const Length& length, float zoom)
- : CSSValue(kPrimitiveClass) {
+bool CSSPrimitiveValue::IsComputationallyIndependent() const {
+ if (IsNumericLiteralValue())
+ return To<CSSNumericLiteralValue>(this)->IsComputationallyIndependent();
+ return To<CSSMathFunctionValue>(this)->IsComputationallyIndependent();
+}
+
+CSSPrimitiveValue::CSSPrimitiveValue(ClassType class_type)
+ : CSSValue(class_type) {}
+
+// static
+CSSPrimitiveValue* CSSPrimitiveValue::CreateFromLength(const Length& length,
+ float zoom) {
switch (length.GetType()) {
case Length::kPercent:
- Init(UnitType::kPercentage);
- DCHECK(std::isfinite(length.Percent()));
- value_.num = length.Percent();
- break;
+ return CSSNumericLiteralValue::Create(length.Percent(),
+ UnitType::kPercentage);
case Length::kFixed:
- Init(UnitType::kPixels);
- value_.num = length.Value() / zoom;
- break;
+ return CSSNumericLiteralValue::Create(length.Value() / zoom,
+ UnitType::kPixels);
case Length::kCalculated: {
const CalculationValue& calc = length.GetCalculationValue();
- if (calc.Pixels() && calc.Percent()) {
- Init(CSSCalcValue::Create(CSSCalcValue::CreateExpressionNode(
- calc.Pixels() / zoom, calc.Percent()),
- calc.GetValueRange()));
- break;
- }
+ if (calc.Pixels() && calc.Percent())
+ return CSSMathFunctionValue::Create(length, zoom);
if (calc.Percent()) {
- Init(UnitType::kPercentage);
- value_.num = calc.Percent();
- } else {
- Init(UnitType::kPixels);
- value_.num = calc.Pixels() / zoom;
+ double num = calc.Percent();
+ if (num < 0 && calc.IsNonNegative())
+ num = 0;
+ return CSSNumericLiteralValue::Create(num, UnitType::kPercentage);
}
- if (value_.num < 0 && calc.IsNonNegative())
- value_.num = 0;
- break;
+ double num = calc.Pixels() / zoom;
+ if (num < 0 && calc.IsNonNegative())
+ num = 0;
+ return CSSNumericLiteralValue::Create(num, UnitType::kPixels);
}
- case Length::kAuto:
- case Length::kMinContent:
- case Length::kMaxContent:
- case Length::kFillAvailable:
- case Length::kFitContent:
- case Length::kExtendToZoom:
- case Length::kDeviceWidth:
- case Length::kDeviceHeight:
- case Length::kMaxSizeNone:
- NOTREACHED();
+ default:
break;
}
+ NOTREACHED();
+ return nullptr;
}
-void CSSPrimitiveValue::Init(UnitType type) {
- primitive_unit_type_ = static_cast<unsigned>(type);
-}
-
-void CSSPrimitiveValue::Init(CSSCalcValue* c) {
- Init(UnitType::kCalc);
- value_.calc = c;
-}
-
-CSSPrimitiveValue::~CSSPrimitiveValue() = default;
-
double CSSPrimitiveValue::ComputeSeconds() const {
- DCHECK(IsTime() ||
- (IsCalculated() && CssCalcValue()->Category() == kCalcTime));
- UnitType current_type =
- IsCalculated() ? CssCalcValue()->ExpressionNode()->TypeWithCalcResolved()
- : GetType();
- if (current_type == UnitType::kSeconds)
- return GetDoubleValue();
- if (current_type == UnitType::kMilliseconds)
- return GetDoubleValue() / 1000;
- NOTREACHED();
- return 0;
+ if (IsCalculated())
+ return To<CSSMathFunctionValue>(this)->ComputeSeconds();
+ return To<CSSNumericLiteralValue>(this)->ComputeSeconds();
}
double CSSPrimitiveValue::ComputeDegrees() const {
- DCHECK(IsAngle() ||
- (IsCalculated() && CssCalcValue()->Category() == kCalcAngle));
- UnitType current_type =
- IsCalculated() ? CssCalcValue()->ExpressionNode()->TypeWithCalcResolved()
- : GetType();
- switch (current_type) {
- case UnitType::kDegrees:
- return GetDoubleValue();
- case UnitType::kRadians:
- return rad2deg(GetDoubleValue());
- case UnitType::kGradians:
- return grad2deg(GetDoubleValue());
- case UnitType::kTurns:
- return turn2deg(GetDoubleValue());
- default:
- NOTREACHED();
- return 0;
- }
+ if (IsCalculated())
+ return To<CSSMathFunctionValue>(this)->ComputeDegrees();
+ return To<CSSNumericLiteralValue>(this)->ComputeDegrees();
}
double CSSPrimitiveValue::ComputeDotsPerPixel() const {
- UnitType current_type = TypeWithCalcResolved();
- DCHECK(IsResolution(current_type));
- return GetDoubleValue() * ConversionToCanonicalUnitsScaleFactor(current_type);
+ // TODO(style-dev): Either support math functions on resolutions; or provide a
+ // justification for not supporting it.
+ DCHECK(IsNumericLiteralValue());
+ return To<CSSNumericLiteralValue>(this)->ComputeDotsPerPixel();
}
template <>
@@ -324,28 +277,22 @@ double CSSPrimitiveValue::ComputeLength(
double CSSPrimitiveValue::ComputeLengthDouble(
const CSSToLengthConversionData& conversion_data) const {
- if (GetType() == UnitType::kCalc)
- return value_.calc->ComputeLengthPx(conversion_data);
- return conversion_data.ZoomedComputedPixels(GetDoubleValue(), GetType());
+ if (IsCalculated())
+ return To<CSSMathFunctionValue>(this)->ComputeLengthPx(conversion_data);
+ return To<CSSNumericLiteralValue>(this)->ComputeLengthPx(conversion_data);
}
void CSSPrimitiveValue::AccumulateLengthArray(CSSLengthArray& length_array,
double multiplier) const {
DCHECK_EQ(length_array.values.size(),
static_cast<unsigned>(kLengthUnitTypeCount));
-
- if (GetType() == UnitType::kCalc) {
- CssCalcValue()->AccumulateLengthArray(length_array, multiplier);
+ if (IsCalculated()) {
+ To<CSSMathFunctionValue>(this)->AccumulateLengthArray(length_array,
+ multiplier);
return;
}
-
- LengthUnitType length_type;
- bool conversion_success = UnitTypeToLengthUnitType(GetType(), length_type);
- DCHECK(conversion_success);
- length_array.values[length_type] +=
- value_.num * ConversionToCanonicalUnitsScaleFactor(GetType()) *
- multiplier;
- length_array.type_flags.set(length_type);
+ To<CSSNumericLiteralValue>(this)->AccumulateLengthArray(length_array,
+ multiplier);
}
double CSSPrimitiveValue::ConversionToCanonicalUnitsScaleFactor(
@@ -411,11 +358,17 @@ Length CSSPrimitiveValue::ConvertToLength(
if (IsPercentage())
return Length::Percent(GetDoubleValue());
DCHECK(IsCalculated());
- return Length(CssCalcValue()->ToCalcValue(conversion_data));
+ return To<CSSMathFunctionValue>(this)->ConvertToLength(conversion_data);
}
double CSSPrimitiveValue::GetDoubleValue() const {
- return GetType() != UnitType::kCalc ? value_.num : value_.calc->DoubleValue();
+ return IsCalculated() ? To<CSSMathFunctionValue>(this)->DoubleValue()
+ : To<CSSNumericLiteralValue>(this)->DoubleValue();
+}
+
+bool CSSPrimitiveValue::IsZero() const {
+ return IsCalculated() ? To<CSSMathFunctionValue>(this)->IsZero()
+ : To<CSSNumericLiteralValue>(this)->IsZero();
}
CSSPrimitiveValue::UnitType CSSPrimitiveValue::CanonicalUnitTypeForCategory(
@@ -519,17 +472,6 @@ CSSPrimitiveValue::UnitType CSSPrimitiveValue::LengthUnitTypeToUnitType(
return CSSPrimitiveValue::UnitType::kUnknown;
}
-static String FormatNumber(double number, const char* suffix) {
-#if defined(OS_WIN) && _MSC_VER < 1900
- unsigned oldFormat = _set_output_format(_TWO_DIGIT_EXPONENT);
-#endif
- String result = String::Format("%.6g%s", number, suffix);
-#if defined(OS_WIN) && _MSC_VER < 1900
- _set_output_format(oldFormat);
-#endif
- return result;
-}
-
const char* CSSPrimitiveValue::UnitTypeToString(UnitType type) {
switch (type) {
case UnitType::kNumber:
@@ -593,12 +535,7 @@ const char* CSSPrimitiveValue::UnitTypeToString(UnitType type) {
return "vmin";
case UnitType::kViewportMax:
return "vmax";
- case UnitType::kUnknown:
- case UnitType::kCalc:
- case UnitType::kCalcPercentageWithNumber:
- case UnitType::kCalcPercentageWithLength:
- case UnitType::kCalcLengthWithNumber:
- case UnitType::kCalcPercentageWithLengthAndNumber:
+ default:
break;
}
NOTREACHED();
@@ -606,136 +543,12 @@ const char* CSSPrimitiveValue::UnitTypeToString(UnitType type) {
}
String CSSPrimitiveValue::CustomCSSText() const {
- String text;
- switch (GetType()) {
- case UnitType::kUnknown:
- // FIXME
- break;
- case UnitType::kInteger:
- text = String::Number(GetIntValue());
- break;
- case UnitType::kNumber:
- case UnitType::kPercentage:
- case UnitType::kEms:
- case UnitType::kQuirkyEms:
- case UnitType::kExs:
- case UnitType::kRems:
- case UnitType::kChs:
- case UnitType::kPixels:
- case UnitType::kCentimeters:
- case UnitType::kDotsPerPixel:
- case UnitType::kDotsPerInch:
- case UnitType::kDotsPerCentimeter:
- case UnitType::kMillimeters:
- case UnitType::kQuarterMillimeters:
- case UnitType::kInches:
- case UnitType::kPoints:
- case UnitType::kPicas:
- case UnitType::kUserUnits:
- case UnitType::kDegrees:
- case UnitType::kRadians:
- case UnitType::kGradians:
- case UnitType::kMilliseconds:
- case UnitType::kSeconds:
- case UnitType::kHertz:
- case UnitType::kKilohertz:
- case UnitType::kTurns:
- case UnitType::kFraction:
- case UnitType::kViewportWidth:
- case UnitType::kViewportHeight:
- case UnitType::kViewportMin:
- case UnitType::kViewportMax: {
- // The following integers are minimal and maximum integers which can
- // be represented in non-exponential format with 6 digit precision.
- constexpr int kMinInteger = -999999;
- constexpr int kMaxInteger = 999999;
- // If the value_.num is small integer, go the fast path.
- if (value_.num < kMinInteger || value_.num > kMaxInteger ||
- std::trunc(value_.num) != value_.num) {
- text = FormatNumber(value_.num, UnitTypeToString(GetType()));
- } else {
- StringBuilder builder;
- int value = value_.num;
- const char* unit_type = UnitTypeToString(GetType());
- builder.AppendNumber(value);
- builder.Append(unit_type, strlen(unit_type));
- text = builder.ToString();
- }
- } break;
- case UnitType::kCalc:
- text = value_.calc->CustomCSSText();
- break;
- case UnitType::kCalcPercentageWithNumber:
- case UnitType::kCalcPercentageWithLength:
- case UnitType::kCalcLengthWithNumber:
- case UnitType::kCalcPercentageWithLengthAndNumber:
- NOTREACHED();
- break;
- }
-
- return text;
-}
-
-bool CSSPrimitiveValue::Equals(const CSSPrimitiveValue& other) const {
- if (GetType() != other.GetType())
- return false;
-
- switch (GetType()) {
- case UnitType::kUnknown:
- return false;
- case UnitType::kNumber:
- case UnitType::kInteger:
- case UnitType::kPercentage:
- case UnitType::kEms:
- case UnitType::kExs:
- case UnitType::kRems:
- case UnitType::kPixels:
- case UnitType::kCentimeters:
- case UnitType::kDotsPerPixel:
- case UnitType::kDotsPerInch:
- case UnitType::kDotsPerCentimeter:
- case UnitType::kMillimeters:
- case UnitType::kQuarterMillimeters:
- case UnitType::kInches:
- case UnitType::kPoints:
- case UnitType::kPicas:
- case UnitType::kUserUnits:
- case UnitType::kDegrees:
- case UnitType::kRadians:
- case UnitType::kGradians:
- case UnitType::kMilliseconds:
- case UnitType::kSeconds:
- case UnitType::kHertz:
- case UnitType::kKilohertz:
- case UnitType::kTurns:
- case UnitType::kViewportWidth:
- case UnitType::kViewportHeight:
- case UnitType::kViewportMin:
- case UnitType::kViewportMax:
- case UnitType::kFraction:
- return value_.num == other.value_.num;
- case UnitType::kCalc:
- return value_.calc && other.value_.calc &&
- value_.calc->Equals(*other.value_.calc);
- case UnitType::kChs:
- case UnitType::kCalcPercentageWithNumber:
- case UnitType::kCalcPercentageWithLength:
- case UnitType::kCalcLengthWithNumber:
- case UnitType::kCalcPercentageWithLengthAndNumber:
- case UnitType::kQuirkyEms:
- return false;
- }
- return false;
+ if (IsCalculated())
+ return To<CSSMathFunctionValue>(this)->CustomCSSText();
+ return To<CSSNumericLiteralValue>(this)->CustomCSSText();
}
void CSSPrimitiveValue::TraceAfterDispatch(blink::Visitor* visitor) {
- switch (GetType()) {
- case UnitType::kCalc:
- visitor->Trace(value_.calc);
- break;
- default:
- break;
- }
CSSValue::TraceAfterDispatch(visitor);
}
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 a7d134111a0..98a2eae1b55 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
@@ -35,7 +35,6 @@
namespace blink {
-class CSSCalcValue;
class CSSToLengthConversionData;
class Length;
@@ -62,8 +61,8 @@ inline float RoundForImpreciseConversion(double value) {
return static_cast<float>(value);
}
-// CSSPrimitiveValue stores numeric data types (e.g. 1, 10px, 4%) and calc()
-// values (e.g. calc(3px + 2em)).
+// Common interface for numeric data types, including both literals (e.g. 1,
+// 10px, 4%) and values involving math functions (e.g. calc(3px + 2em)).
class CORE_EXPORT CSSPrimitiveValue : public CSSValue {
public:
// These units are iterated through, so be careful when adding or changing the
@@ -106,11 +105,6 @@ class CORE_EXPORT CSSPrimitiveValue : public CSSValue {
// Other units
kFraction,
kInteger,
- kCalc,
- kCalcPercentageWithNumber,
- kCalcPercentageWithLength,
- kCalcLengthWithNumber,
- kCalcPercentageWithLengthAndNumber,
// This value is used to handle quirky margins in reflow roots (body, td,
// and th) like WinIE. The basic idea is that a stylesheet can use the value
@@ -165,16 +159,8 @@ class CORE_EXPORT CSSPrimitiveValue : public CSSValue {
return unit == UnitType::kDegrees || unit == UnitType::kRadians ||
unit == UnitType::kGradians || unit == UnitType::kTurns;
}
- bool IsAngle() const { return IsAngle(TypeWithCalcResolved()); }
- bool IsFontRelativeLength() const {
- return GetType() == UnitType::kQuirkyEms || GetType() == UnitType::kEms ||
- GetType() == UnitType::kExs || GetType() == UnitType::kRems ||
- GetType() == UnitType::kChs;
- }
- bool IsQuirkyEms() const { return GetType() == UnitType::kQuirkyEms; }
- bool IsViewportPercentageLength() const {
- return IsViewportPercentageLength(GetType());
- }
+ bool IsAngle() const;
+ bool IsFontRelativeLength() const;
static bool IsViewportPercentageLength(UnitType type) {
return type >= UnitType::kViewportWidth && type <= UnitType::kViewportMax;
}
@@ -187,59 +173,38 @@ class CORE_EXPORT CSSPrimitiveValue : public CSSValue {
type == UnitType::kExs || type == UnitType::kRems ||
type == UnitType::kChs || IsViewportPercentageLength(type);
}
- bool IsLength() const { return IsLength(TypeWithCalcResolved()); }
- bool IsNumber() const {
- return TypeWithCalcResolved() == UnitType::kNumber ||
- TypeWithCalcResolved() == UnitType::kInteger;
- }
- bool IsPercentage() const {
- return TypeWithCalcResolved() == UnitType::kPercentage;
- }
- bool IsPx() const { return TypeWithCalcResolved() == UnitType::kPixels; }
+ bool IsLength() const;
+ bool IsNumber() const;
+ bool IsInteger() const;
+ bool IsPercentage() const;
+ bool IsPx() const;
static bool IsTime(UnitType unit) {
return unit == UnitType::kSeconds || unit == UnitType::kMilliseconds;
}
- bool IsTime() const { return IsTime(TypeWithCalcResolved()); }
+ bool IsTime() const;
static bool IsFrequency(UnitType unit) {
return unit == UnitType::kHertz || unit == UnitType::kKilohertz;
}
- bool IsCalculated() const { return GetType() == UnitType::kCalc; }
- bool IsCalculatedPercentageWithNumber() const {
- return TypeWithCalcResolved() == UnitType::kCalcPercentageWithNumber;
- }
- bool IsCalculatedPercentageWithLength() const {
- return TypeWithCalcResolved() == UnitType::kCalcPercentageWithLength;
- }
+ bool IsCalculated() const { return IsMathFunctionValue(); }
+ bool IsCalculatedPercentageWithLength() const;
static bool IsResolution(UnitType type) {
return type >= UnitType::kDotsPerPixel &&
type <= UnitType::kDotsPerCentimeter;
}
- bool IsResolution() const { return IsResolution(GetType()); }
+ bool IsResolution() const;
static bool IsFlex(UnitType unit) { return unit == UnitType::kFraction; }
- bool IsFlex() const { return IsFlex(GetType()); }
+ bool IsFlex() const;
- static CSSPrimitiveValue* Create(double value, UnitType);
- static CSSPrimitiveValue* Create(const Length& value, float zoom) {
- return MakeGarbageCollected<CSSPrimitiveValue>(value, zoom);
- }
+ // https://drafts.css-houdini.org/css-properties-values-api-1/#computationally-independent
+ // A property value is computationally independent if it can be converted into
+ // a computed value using only the value of the property on the element, and
+ // "global" information that cannot be changed by CSS.
+ bool IsComputationallyIndependent() const;
- // TODO(sashab): Remove this.
- template <typename T>
- static CSSPrimitiveValue* Create(T 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;
+ // Creates either a |CSSNumericLiteralValue| or a |CSSMathFunctionValue|,
+ // depending on whether |value| is calculated or not. We should never create a
+ // |CSSPrimitiveValue| that's not of any of its subclasses.
+ static CSSPrimitiveValue* CreateFromLength(const Length& value, float zoom);
double ComputeDegrees() const;
double ComputeSeconds() const;
@@ -252,6 +217,14 @@ class CORE_EXPORT CSSPrimitiveValue : public CSSValue {
// Converts to a Length (Fixed, Percent or Calculated)
Length ConvertToLength(const CSSToLengthConversionData&) const;
+ bool IsZero() const;
+
+ // TODO(crbug.com/979895): The semantics of these untyped getters are not very
+ // clear if |this| is a math function. Do not add new callers before further
+ // refactoring and cleanups.
+ // These getters can be called only when |this| is a numeric literal or a math
+ // expression can be resolved into a single numeric value *without any type
+ // conversion* (e.g., between px and em). Otherwise, it hits a DCHECK.
double GetDoubleValue() const;
float GetFloatValue() const { return GetValue<float>(); }
int GetIntValue() const { return GetValue<int>(); }
@@ -260,11 +233,6 @@ class CORE_EXPORT CSSPrimitiveValue : public CSSValue {
return clampTo<T>(GetDoubleValue());
}
- CSSCalcValue* CssCalcValue() const {
- DCHECK(IsCalculated());
- return value_.calc;
- }
-
template <typename T>
inline T ConvertTo() const; // Defined in CSSPrimitiveValueMappings.h
@@ -277,8 +245,6 @@ class CORE_EXPORT CSSPrimitiveValue : public CSSValue {
String CustomCSSText() const;
- bool Equals(const CSSPrimitiveValue&) const;
-
void TraceAfterDispatch(blink::Visitor*);
static UnitType CanonicalUnitTypeForCategory(UnitCategory);
@@ -289,32 +255,14 @@ class CORE_EXPORT CSSPrimitiveValue : public CSSValue {
static bool UnitTypeToLengthUnitType(UnitType, LengthUnitType&);
static UnitType LengthUnitTypeToUnitType(LengthUnitType);
- private:
- static void Create(int); // compile-time guard
- static void Create(unsigned); // compile-time guard
- template <typename T>
- operator T*(); // compile-time guard
+ protected:
+ explicit CSSPrimitiveValue(ClassType class_type);
// Code generated by css_primitive_value_unit_trie.cc.tmpl
static UnitType StringToUnitType(const LChar*, unsigned length);
static UnitType StringToUnitType(const UChar*, unsigned length);
- void Init(UnitType);
- void Init(const Length&);
- void Init(CSSCalcValue*);
-
double ComputeLengthDouble(const CSSToLengthConversionData&) const;
-
- inline UnitType GetType() const {
- return static_cast<UnitType>(primitive_unit_type_);
- }
-
- union {
- double num;
- // FIXME: oilpan: Should be a member, but no support for members in unions.
- // Just trace the raw ptr for now.
- CSSCalcValue* calc;
- } value_;
};
using CSSLengthArray = CSSPrimitiveValue::CSSLengthArray;
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 ff08262a3fe..755063b48f9 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
@@ -32,7 +32,6 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_PRIMITIVE_VALUE_MAPPINGS_H_
#include "cc/input/scroll_snap_data.h"
-#include "third_party/blink/renderer/core/css/css_calculation_value.h"
#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_reflection_direction.h"
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
index b1c55ffec75..eb7f504224b 100644
--- 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
@@ -5,7 +5,9 @@
#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"
+#include "third_party/blink/renderer/core/css/css_math_expression_node.h"
+#include "third_party/blink/renderer/core/css/css_math_function_value.h"
+#include "third_party/blink/renderer/core/css/css_numeric_literal_value.h"
namespace blink {
namespace {
@@ -17,15 +19,15 @@ struct UnitValue {
UnitType unit_type;
};
-CSSPrimitiveValue* Create(UnitValue v) {
- return CSSPrimitiveValue::Create(v.value, v.unit_type);
+CSSNumericLiteralValue* Create(UnitValue v) {
+ return CSSNumericLiteralValue::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)));
+ return CSSMathFunctionValue::Create(CSSMathExpressionBinaryOperation::Create(
+ CSSMathExpressionNumericLiteral::Create(Create(a)),
+ CSSMathExpressionNumericLiteral::Create(Create(b)),
+ CSSMathOperator::kAdd));
}
TEST(CSSPrimitiveValueTest, IsTime) {
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 1611163451e..132294a4830 100644
--- a/chromium/third_party/blink/renderer/core/css/css_properties.json5
+++ b/chromium/third_party/blink/renderer/core/css/css_properties.json5
@@ -70,8 +70,8 @@
"legacy",
"mask_box",
"mask_layer",
- "svg_paint",
"transition",
+ "visited_color",
],
},
@@ -292,15 +292,21 @@
// Tweaks how we choose defaults for getter, setter, initial and type_name.
// For example, setting this to BlendMode will make us use a setter of
// setBlendMode
+ // - initial
+ // The static function to invoke on ComputedStyleInitialValues,
+ // SVGComputedStyle, or FontBuilder to retrieve the initial value.
+ // Defaults to e.g. InitialBorderBottomLeft.
// - getter
- // The ComputedStyle getter, defaults to e.g. borderBottomLeft
+ // The ComputedStyle getter, defaults to e.g. BorderBottomLeft
// - setter
- // The ComputedStyle setter, defaults to e.g. setBorderBottomLeft
+ // The ComputedStyle setter, defaults to e.g. GetBorderBottomLeft
// - type_name
// The computed type for the property. Only required for the default value
// application, defaults to e.g. EDisplay
name_for_methods: {
},
+ initial: {
+ },
getter: {
},
setter: {
@@ -348,8 +354,9 @@
physical_group: {
valid_type: "str",
valid_values: ["border", "border-color", "border-style", "border-width",
- "inset", "margin", "max-size", "min-size", "padding",
- "scroll-margin", "scroll-padding", "size"],
+ "inset", "margin", "max-size", "min-size", "overflow",
+ "padding", "scroll-margin", "scroll-padding", "size",
+ "visited-border-color"],
}
},
@@ -375,11 +382,25 @@
valid_type: "bool",
},
- // - valid_for_visited_link
- // Most CSS properties do not apply to :visited and :link for privacy
- // reasons. Mark properties which apply to :visited and :link by setting
- // this flag to true.
- valid_for_visited_link: {
+ // - visited_property_for: "other-property"
+ // CSS properties that are allowed in :visited selectors each have an
+ // internal "companion" property with the visited value. For privacy reasons
+ // CSSOM APIs must return computed values as if links aren't visited, but
+ // for rendering purposes we need the value with the :visited rules applied.
+ //
+ // This means that the regular property (e.g. background-color) represents
+ // the value as seen by CSSOM, and the -internal-visited counterpart (e.g.
+ // -internal-visited-background-color) represents the same property as seen
+ // by painting.
+ visited_property_for: {
+ valid_type: "str",
+ },
+
+ // - affected_by_forced_colors
+ // The property value will be overridden with the default value defined in
+ // the forced colors UA style sheet when forced colors mode is enabled and
+ // forced-color-adjust is set to auto.
+ affected_by_forced_colors: {
default: false,
valid_type: "bool",
},
@@ -485,7 +506,19 @@
attribute: "TimingFunction",
},
priority: "Animation",
- keywords: ["linear", "ease", "ease-in", "ease-out", "ease-in-out", "step-start", "step-end"],
+ keywords: [
+ "linear",
+ "ease",
+ "ease-in",
+ "ease-out",
+ "ease-in-out",
+ "jump-both",
+ "jump-end",
+ "jump-none",
+ "jump-start",
+ "step-start",
+ "step-end"
+ ],
typedom_types: ["Keyword"],
separator: ",",
},
@@ -530,7 +563,18 @@
attribute: "TimingFunction",
},
priority: "Animation",
- keywords: ["linear", "ease", "ease-in", "ease-out", "ease-in-out", "step-start", "step-end"],
+ keywords: [
+ "linear",
+ "ease",
+ "ease-in",
+ "ease-out",
+ "ease-in-out",
+ "jump-both",
+ "jump-end",
+ "jump-none",
+ "jump-start",
+ "step-start",
+ "step-end"],
typedom_types: ["Keyword"],
separator: ",",
},
@@ -553,7 +597,7 @@
priority: "High",
keywords: ["currentcolor"],
typedom_types: ["Keyword"],
- valid_for_visited_link: true,
+ affected_by_forced_colors: true,
},
{
name: "direction",
@@ -750,6 +794,17 @@
priority: "High",
},
{
+ name: "forced-color-adjust",
+ property_methods: ["CSSValueFromComputedStyleInternal"],
+ inherited: true,
+ runtime_flag: "ForcedColors",
+ field_template: "keyword",
+ priority: "High",
+ keywords: ["auto", "none"],
+ typedom_types: ["Keyword"],
+ default_value: "auto",
+ },
+ {
name: "-webkit-locale",
property_methods: ["ParseSingleValue", "CSSValueFromComputedStyleInternal"],
inherited: true,
@@ -938,7 +993,7 @@
style_builder_template_args: {
initial_color: "ComputedStyleInitialValues::InitialBackgroundColor",
},
- valid_for_visited_link: true,
+ affected_by_forced_colors: true,
},
{
name: "background-image",
@@ -1031,7 +1086,7 @@
typedom_types: ["Keyword"],
converter: "ConvertStyleColor",
style_builder_template: "color",
- valid_for_visited_link: true,
+ affected_by_forced_colors: true,
},
{
name: "border-bottom-left-radius",
@@ -1157,7 +1212,7 @@
typedom_types: ["Keyword"],
converter: "ConvertStyleColor",
style_builder_template: "color",
- valid_for_visited_link: true,
+ affected_by_forced_colors: true,
},
{
name: "border-left-style",
@@ -1200,7 +1255,7 @@
typedom_types: ["Keyword"],
converter: "ConvertStyleColor",
style_builder_template: "color",
- valid_for_visited_link: true,
+ affected_by_forced_colors: true,
},
{
name: "border-right-style",
@@ -1243,7 +1298,7 @@
typedom_types: ["Keyword"],
converter: "ConvertStyleColor",
style_builder_template: "color",
- valid_for_visited_link: true,
+ affected_by_forced_colors: true,
},
{
name: "border-top-left-radius",
@@ -1321,6 +1376,7 @@
converter: "ConvertShadowList",
keywords: ["none"],
typedom_types: ["Keyword"],
+ affected_by_forced_colors: true,
},
{
name: "box-sizing",
@@ -1398,7 +1454,6 @@
style_builder_custom_functions: ["initial", "inherit", "value"],
keywords: ["auto", "currentcolor"],
typedom_types: ["Keyword"],
- valid_for_visited_link: true,
},
{
name: "clear",
@@ -1617,13 +1672,10 @@
interpolable: true,
inherited: true,
svg: true,
+ initial: "InitialFillPaint",
setter: "SetFillPaint",
+ getter: "FillPaint",
converter: "ConvertSVGPaint",
- style_builder_template: "svg_paint",
- style_builder_template_args: {
- paint_type: "FillPaint",
- },
- valid_for_visited_link: true,
},
{
name: "fill-opacity",
@@ -2360,7 +2412,7 @@
typedom_types: ["Keyword"],
converter: "ConvertStyleColor",
style_builder_template: "color",
- valid_for_visited_link: true,
+ affected_by_forced_colors: true,
},
{
name: "outline-offset",
@@ -2424,6 +2476,22 @@
typedom_types: ["Keyword"]
},
{
+ name: "overflow-inline",
+ direction_aware_options: {
+ resolver: "inline",
+ physical_group: "overflow",
+ },
+ runtime_flag: "CSSLogicalOverflow",
+ },
+ {
+ name: "overflow-block",
+ direction_aware_options: {
+ resolver: "block",
+ physical_group: "overflow",
+ },
+ runtime_flag: "CSSLogicalOverflow",
+ },
+ {
name: "overflow-x",
property_methods: ["CSSValueFromComputedStyleInternal"],
field_template: "keyword",
@@ -2446,6 +2514,20 @@
type_name: "EOverflow",
},
{
+ name: "overscroll-behavior-inline",
+ direction_aware_options: {
+ resolver: "inline",
+ physical_group: "overscroll-behavior",
+ },
+ },
+ {
+ name: "overscroll-behavior-block",
+ direction_aware_options: {
+ resolver: "block",
+ physical_group: "overscroll-behavior",
+ },
+ },
+ {
name: "overscroll-behavior-x",
property_methods: ["CSSValueFromComputedStyleInternal"],
field_template: "keyword",
@@ -2934,13 +3016,10 @@
interpolable: true,
inherited: true,
svg: true,
+ initial: "InitialStrokePaint",
setter: "SetStrokePaint",
+ getter: "StrokePaint",
converter: "ConvertSVGPaint",
- style_builder_template: "svg_paint",
- style_builder_template_args: {
- paint_type: "StrokePaint",
- },
- valid_for_visited_link: true,
},
{
name: "stroke-dasharray",
@@ -3092,7 +3171,6 @@
typedom_types: ["Keyword"],
converter: "ConvertStyleColor",
style_builder_template: "color",
- valid_for_visited_link: true,
},
{
name: "text-decoration-line",
@@ -3172,7 +3250,8 @@
type_name: "ShadowList",
converter: "ConvertShadowList",
keywords: ["none"],
- typedom_types: ["Keyword"]
+ typedom_types: ["Keyword"],
+ affected_by_forced_colors: true,
},
{
name: "text-size-adjust",
@@ -3556,7 +3635,7 @@
typedom_types: ["Keyword"],
converter: "ConvertStyleColor",
style_builder_template: "color",
- valid_for_visited_link: true,
+ affected_by_forced_colors: true,
},
{
name: "column-rule-style",
@@ -3856,6 +3935,7 @@
field_template: "<color>",
default_value: "LayoutTheme::TapHighlightColor()",
converter: "ConvertColor",
+ affected_by_forced_colors: true,
},
{
name: "-webkit-text-combine",
@@ -3875,7 +3955,6 @@
computed_style_custom_functions: ["getter", "setter"],
converter: "ConvertStyleColor",
style_builder_template: "color",
- valid_for_visited_link: true,
},
{
name: "-webkit-text-emphasis-position",
@@ -3906,7 +3985,6 @@
computed_style_custom_functions: ["getter", "setter"],
converter: "ConvertStyleColor",
style_builder_template: "color",
- valid_for_visited_link: true,
},
{
name: "-webkit-text-security",
@@ -3916,7 +3994,6 @@
field_template: "keyword",
keywords: ["none", "disc", "circle", "square"],
default_value: "none",
- valid_for_visited_link: true,
},
{
name: "-webkit-text-stroke-color",
@@ -3931,7 +4008,6 @@
computed_style_custom_functions: ["getter", "setter"],
converter: "ConvertStyleColor",
style_builder_template: "color",
- valid_for_visited_link: true,
},
{
name: "-webkit-text-stroke-width",
@@ -4135,6 +4211,7 @@
resolver: "inline-start",
physical_group: "margin",
},
+ typedom_types: ["Length", "Percentage"],
keywords: ["auto"]
},
{
@@ -4144,6 +4221,7 @@
resolver: "inline-end",
physical_group: "margin",
},
+ typedom_types: ["Length", "Percentage"],
keywords: ["auto"]
},
{
@@ -4153,6 +4231,7 @@
resolver: "block-start",
physical_group: "margin",
},
+ typedom_types: ["Length", "Percentage"],
keywords: ["auto"]
},
{
@@ -4162,6 +4241,7 @@
resolver: "block-end",
physical_group: "margin",
},
+ typedom_types: ["Length", "Percentage"],
keywords: ["auto"]
},
{
@@ -4170,7 +4250,8 @@
direction_aware_options: {
resolver: "inline-start",
physical_group: "padding",
- }
+ },
+ typedom_types: ["Length", "Percentage"]
},
{
name: "padding-inline-end",
@@ -4178,7 +4259,8 @@
direction_aware_options: {
resolver: "inline-end",
physical_group: "padding",
- }
+ },
+ typedom_types: ["Length", "Percentage"]
},
{
name: "padding-block-start",
@@ -4186,7 +4268,8 @@
direction_aware_options: {
resolver: "block-start",
physical_group: "padding",
- }
+ },
+ typedom_types: ["Length", "Percentage"]
},
{
name: "padding-block-end",
@@ -4194,7 +4277,8 @@
direction_aware_options: {
resolver: "block-end",
physical_group: "padding",
- }
+ },
+ typedom_types: ["Length", "Percentage"]
},
{
name: "border-inline-start-width",
@@ -4214,7 +4298,6 @@
{
name: "border-inline-start-color",
property_methods: ["ParseSingleValue"],
- valid_for_visited_link: true,
direction_aware_options: {
resolver: "inline-start",
physical_group: "border-color",
@@ -4238,7 +4321,6 @@
{
name: "border-inline-end-color",
property_methods: ["ParseSingleValue"],
- valid_for_visited_link: true,
direction_aware_options: {
resolver: "inline-end",
physical_group: "border-color",
@@ -4262,7 +4344,6 @@
{
name: "border-block-start-color",
property_methods: ["ParseSingleValue"],
- valid_for_visited_link: true,
direction_aware_options: {
resolver: "block-start",
physical_group: "border-color",
@@ -4286,7 +4367,6 @@
{
name: "border-block-end-color",
property_methods: ["ParseSingleValue"],
- valid_for_visited_link: true,
direction_aware_options: {
resolver: "block-end",
physical_group: "border-color",
@@ -4299,7 +4379,8 @@
direction_aware_options: {
resolver: "inline-start",
physical_group: "inset",
- }
+ },
+ typedom_types: ["Length", "Percentage"]
},
{
name: "inset-inline-end",
@@ -4308,7 +4389,8 @@
direction_aware_options: {
resolver: "inline-end",
physical_group: "inset",
- }
+ },
+ typedom_types: ["Length", "Percentage"]
},
{
name: "inset-block-start",
@@ -4317,7 +4399,8 @@
direction_aware_options: {
resolver: "block-start",
physical_group: "inset",
- }
+ },
+ typedom_types: ["Length", "Percentage"]
},
{
name: "inset-block-end",
@@ -4326,7 +4409,8 @@
direction_aware_options: {
resolver: "block-end",
physical_group: "inset",
- }
+ },
+ typedom_types: ["Length", "Percentage"]
},
// Non-standard direction aware properties
@@ -4503,6 +4587,24 @@
is_property: false,
runtime_flag: "DisplayCutoutAPI",
},
+ {
+ name: "syntax",
+ is_descriptor: true,
+ is_property: false,
+ runtime_flag: "CSSVariables2AtProperty",
+ },
+ {
+ name: "initial-value",
+ is_descriptor: true,
+ is_property: false,
+ runtime_flag: "CSSVariables2AtProperty",
+ },
+ {
+ name: "inherits",
+ is_descriptor: true,
+ is_property: false,
+ runtime_flag: "CSSVariables2AtProperty",
+ },
// Shorthands
{
@@ -4840,7 +4942,7 @@
},
{
name: "list-style",
- longhands: ["list-style-type", "list-style-position", "list-style-image"],
+ longhands: ["list-style-position", "list-style-image", "list-style-type"],
property_methods: ["ParseShorthand", "CSSValueFromComputedStyleInternal"],
},
{
@@ -5059,6 +5161,270 @@
property_methods: ["ParseShorthand"],
},
+ // Visited properties.
+ {
+ name: "-internal-visited-color",
+ visited_property_for: "color",
+ property_methods: ["ParseSingleValue", "ColorIncludingFallback"],
+ inherited: true,
+ field_group: "inherited",
+ field_template: "external",
+ include_paths: ["third_party/blink/renderer/platform/graphics/color.h"],
+ default_value: "Color::kBlack",
+ type_name: "Color",
+ computed_style_custom_functions: ["getter", "setter"],
+ style_builder_custom_functions: ['value'],
+ style_builder_template: "visited_color",
+ style_builder_template_args: {
+ initial_color: "ComputedStyleInitialValues::InitialColor",
+ },
+ priority: "High",
+ },
+ {
+ name: "-internal-visited-caret-color",
+ visited_property_for: "caret-color",
+ property_methods: ["ParseSingleValue", "ColorIncludingFallback"],
+ inherited: true,
+ field_group: "*",
+ field_template: "external",
+ include_paths: ["third_party/blink/renderer/platform/graphics/color.h"],
+ default_value: "Color()",
+ type_name: "Color",
+ converter: "ConvertStyleAutoColor",
+ computed_style_custom_functions: ["getter", "setter"],
+ style_builder_template: "visited_color",
+ style_builder_template_args: {
+ initial_color: "StyleAutoColor::AutoColor",
+ },
+ },
+ {
+ name: "-internal-visited-column-rule-color",
+ visited_property_for: "column-rule-color",
+ property_methods: ["ParseSingleValue", "ColorIncludingFallback"],
+ field_group: "*->multi-col",
+ field_template: "external",
+ include_paths: ["third_party/blink/renderer/core/css/style_color.h"],
+ default_value: "StyleColor::CurrentColor()",
+ type_name: "StyleColor",
+ computed_style_custom_functions: ["getter","setter"],
+ converter: "ConvertStyleColor",
+ style_builder_template: "visited_color",
+ },
+ {
+ name: "-internal-visited-background-color",
+ visited_property_for: "background-color",
+ property_methods: ["ParseSingleValue", "ColorIncludingFallback"],
+ field_group: "*",
+ field_template: "external",
+ include_paths: ["third_party/blink/renderer/core/css/style_color.h"],
+ default_value: "StyleColor(Color::kTransparent)",
+ type_name: "StyleColor",
+ computed_style_custom_functions: ["getter", "setter"],
+ converter: "ConvertStyleColor",
+ style_builder_template: "visited_color",
+ style_builder_template_args: {
+ initial_color: "ComputedStyleInitialValues::InitialBackgroundColor",
+ },
+ },
+ {
+ name: "-internal-visited-border-left-color",
+ visited_property_for: "border-left-color",
+ property_methods: ["ParseSingleValue", "ColorIncludingFallback"],
+ field_group: "*",
+ field_template: "external",
+ include_paths: ["third_party/blink/renderer/core/css/style_color.h"],
+ default_value: "StyleColor::CurrentColor()",
+ type_name: "StyleColor",
+ computed_style_custom_functions: ["getter", "setter"],
+ converter: "ConvertStyleColor",
+ style_builder_template: "visited_color",
+ },
+ {
+ name: "-internal-visited-border-right-color",
+ visited_property_for: "border-right-color",
+ property_methods: ["ParseSingleValue", "ColorIncludingFallback"],
+ field_group: "*",
+ field_template: "external",
+ include_paths: ["third_party/blink/renderer/core/css/style_color.h"],
+ default_value: "StyleColor::CurrentColor()",
+ type_name: "StyleColor",
+ computed_style_custom_functions: ["getter", "setter"],
+ converter: "ConvertStyleColor",
+ style_builder_template: "visited_color",
+ },
+ {
+ name: "-internal-visited-border-top-color",
+ visited_property_for: "border-top-color",
+ property_methods: ["ParseSingleValue", "ColorIncludingFallback"],
+ field_group: "*",
+ field_template: "external",
+ include_paths: ["third_party/blink/renderer/core/css/style_color.h"],
+ default_value: "StyleColor::CurrentColor()",
+ type_name: "StyleColor",
+ computed_style_custom_functions: ["getter", "setter"],
+ converter: "ConvertStyleColor",
+ style_builder_template: "visited_color",
+ },
+ {
+ name: "-internal-visited-border-bottom-color",
+ visited_property_for: "border-bottom-color",
+ property_methods: ["ParseSingleValue", "ColorIncludingFallback"],
+ field_group: "*",
+ field_template: "external",
+ include_paths: ["third_party/blink/renderer/core/css/style_color.h"],
+ default_value: "StyleColor::CurrentColor()",
+ type_name: "StyleColor",
+ computed_style_custom_functions: ["getter", "setter"],
+ converter: "ConvertStyleColor",
+ style_builder_template: "visited_color",
+ },
+ {
+ name: "-internal-visited-border-inline-start-color",
+ visited_property_for: "border-inline-start-color",
+ property_methods: ["ParseSingleValue"],
+ direction_aware_options: {
+ resolver: "inline-start",
+ physical_group: "visited-border-color",
+ },
+ },
+ {
+ name: "-internal-visited-border-inline-end-color",
+ visited_property_for: "border-inline-end-color",
+ property_methods: ["ParseSingleValue"],
+ direction_aware_options: {
+ resolver: "inline-end",
+ physical_group: "visited-border-color",
+ },
+ },
+ {
+ name: "-internal-visited-border-block-start-color",
+ visited_property_for: "border-block-start-color",
+ property_methods: ["ParseSingleValue"],
+ direction_aware_options: {
+ resolver: "block-start",
+ physical_group: "visited-border-color",
+ },
+ },
+ {
+ name: "-internal-visited-border-block-end-color",
+ visited_property_for: "border-block-end-color",
+ property_methods: ["ParseSingleValue"],
+ direction_aware_options: {
+ resolver: "block-end",
+ physical_group: "visited-border-color",
+ },
+ },
+ {
+ name: "-internal-visited-fill",
+ visited_property_for: "fill",
+ property_methods: ["ParseSingleValue"],
+ inherited: true,
+ svg: true,
+ initial: "InitialFillPaint",
+ setter: "SetInternalVisitedFillPaint",
+ getter: "FillPaint",
+ converter: "ConvertSVGPaint",
+ },
+ {
+ name: "-internal-visited-outline-color",
+ visited_property_for: "outline-color",
+ property_methods: ["ParseSingleValue", "ColorIncludingFallback"],
+ field_group: "*",
+ field_template: "external",
+ include_paths: ["third_party/blink/renderer/core/css/style_color.h"],
+ default_value: "StyleColor::CurrentColor()",
+ type_name: "StyleColor",
+ computed_style_custom_functions: ["getter", "setter"],
+ converter: "ConvertStyleColor",
+ style_builder_template: "visited_color",
+ },
+ {
+ name: "-internal-visited-stroke",
+ visited_property_for: "stroke",
+ property_methods: ["ParseSingleValue"],
+ inherited: true,
+ svg: true,
+ initial: "InitialStrokePaint",
+ setter: "SetInternalVisitedStrokePaint",
+ getter: "StrokePaint",
+ converter: "ConvertSVGPaint",
+ },
+ {
+ name: "-internal-visited-text-decoration-color",
+ visited_property_for: "text-decoration-color",
+ property_methods: ["ParseSingleValue", "ColorIncludingFallback"],
+ field_group: "*",
+ field_template: "external",
+ include_paths: ["third_party/blink/renderer/core/css/style_color.h"],
+ default_value: "StyleColor::CurrentColor()",
+ type_name: "StyleColor",
+ computed_style_custom_functions: ["getter", "setter"],
+ converter: "ConvertStyleColor",
+ style_builder_template: "visited_color",
+ },
+ {
+ name: "-internal-visited-text-emphasis-color",
+ visited_property_for: "-webkit-text-emphasis-color",
+ property_methods: ["ParseSingleValue", "ColorIncludingFallback"],
+ inherited: true,
+ field_group: "*",
+ field_template: "external",
+ include_paths: ["third_party/blink/renderer/platform/graphics/color.h"],
+ default_value: "Color()",
+ type_name: "Color",
+ computed_style_custom_functions: ["getter", "setter"],
+ converter: "ConvertStyleColor",
+ style_builder_template: "visited_color",
+ style_builder_template_args: {
+ initial_color: "blink::Color",
+ },
+ },
+ {
+ name: "-internal-visited-text-fill-color",
+ visited_property_for: "-webkit-text-fill-color",
+ property_methods: ["ParseSingleValue", "ColorIncludingFallback"],
+ inherited: true,
+ field_group: "*",
+ field_template: "external",
+ include_paths: ["third_party/blink/renderer/platform/graphics/color.h"],
+ default_value: "Color()",
+ type_name: "Color",
+ computed_style_custom_functions: ["getter", "setter"],
+ converter: "ConvertStyleColor",
+ style_builder_template: "visited_color",
+ style_builder_template_args: {
+ initial_color: "blink::Color",
+ },
+ },
+ {
+ name: "-internal-visited-text-stroke-color",
+ visited_property_for: "-webkit-text-stroke-color",
+ property_methods: ["ParseSingleValue", "ColorIncludingFallback"],
+ inherited: true,
+ field_group: "*",
+ field_template: "external",
+ include_paths: ["third_party/blink/renderer/platform/graphics/color.h"],
+ default_value: "Color()",
+ type_name: "Color",
+ computed_style_custom_functions: ["getter", "setter"],
+ converter: "ConvertStyleColor",
+ style_builder_template: "visited_color",
+ style_builder_template_args: {
+ initial_color: "blink::Color",
+ },
+ },
+ {
+ name: "-internal-effective-zoom",
+ property_methods: ["ParseSingleValue"],
+ inherited: true,
+ field_template: "primitive",
+ type_name: "float",
+ default_value: "1.0f",
+ field_group: "*",
+ priority: "High",
+ style_builder_custom_functions: ["initial", "inherit", "value"],
+ },
+
// Aliases; these map to the same CSSPropertyID
{
name: "-epub-caption-side",
diff --git a/chromium/third_party/blink/renderer/core/css/css_property_equality.cc b/chromium/third_party/blink/renderer/core/css/css_property_equality.cc
index 8205c1216f8..367b33951bb 100644
--- a/chromium/third_party/blink/renderer/core/css/css_property_equality.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_property_equality.cc
@@ -70,7 +70,8 @@ bool CSSPropertyEquality::PropertiesEqual(const PropertyHandle& property,
switch (property.GetCSSProperty().PropertyID()) {
case CSSPropertyID::kBackgroundColor:
return a.BackgroundColor() == b.BackgroundColor() &&
- a.VisitedLinkBackgroundColor() == b.VisitedLinkBackgroundColor();
+ a.InternalVisitedBackgroundColor() ==
+ b.InternalVisitedBackgroundColor();
case CSSPropertyID::kBackgroundImage:
return FillLayersEqual<CSSPropertyID::kBackgroundImage>(
a.BackgroundLayers(), b.BackgroundLayers());
@@ -87,8 +88,8 @@ bool CSSPropertyEquality::PropertiesEqual(const PropertyHandle& property,
return a.BaselineShiftValue() == b.BaselineShiftValue();
case CSSPropertyID::kBorderBottomColor:
return a.BorderBottomColor() == b.BorderBottomColor() &&
- a.VisitedLinkBorderBottomColor() ==
- b.VisitedLinkBorderBottomColor();
+ a.InternalVisitedBorderBottomColor() ==
+ b.InternalVisitedBorderBottomColor();
case CSSPropertyID::kBorderBottomLeftRadius:
return a.BorderBottomLeftRadius() == b.BorderBottomLeftRadius();
case CSSPropertyID::kBorderBottomRightRadius:
@@ -105,17 +106,20 @@ bool CSSPropertyEquality::PropertiesEqual(const PropertyHandle& property,
return a.BorderImageWidth() == b.BorderImageWidth();
case CSSPropertyID::kBorderLeftColor:
return a.BorderLeftColor() == b.BorderLeftColor() &&
- a.VisitedLinkBorderLeftColor() == b.VisitedLinkBorderLeftColor();
+ a.InternalVisitedBorderLeftColor() ==
+ b.InternalVisitedBorderLeftColor();
case CSSPropertyID::kBorderLeftWidth:
return a.BorderLeftWidth() == b.BorderLeftWidth();
case CSSPropertyID::kBorderRightColor:
return a.BorderRightColor() == b.BorderRightColor() &&
- a.VisitedLinkBorderRightColor() == b.VisitedLinkBorderRightColor();
+ a.InternalVisitedBorderRightColor() ==
+ b.InternalVisitedBorderRightColor();
case CSSPropertyID::kBorderRightWidth:
return a.BorderRightWidth() == b.BorderRightWidth();
case CSSPropertyID::kBorderTopColor:
return a.BorderTopColor() == b.BorderTopColor() &&
- a.VisitedLinkBorderTopColor() == b.VisitedLinkBorderTopColor();
+ a.InternalVisitedBorderTopColor() ==
+ b.InternalVisitedBorderTopColor();
case CSSPropertyID::kBorderTopLeftRadius:
return a.BorderTopLeftRadius() == b.BorderTopLeftRadius();
case CSSPropertyID::kBorderTopRightRadius:
@@ -128,18 +132,18 @@ bool CSSPropertyEquality::PropertiesEqual(const PropertyHandle& property,
return DataEquivalent(a.BoxShadow(), b.BoxShadow());
case CSSPropertyID::kCaretColor:
return a.CaretColor() == b.CaretColor() &&
- a.VisitedLinkCaretColor() == b.VisitedLinkCaretColor();
+ a.InternalVisitedCaretColor() == b.InternalVisitedCaretColor();
case CSSPropertyID::kClip:
return a.Clip() == b.Clip();
case CSSPropertyID::kColor:
return a.GetColor() == b.GetColor() &&
- a.VisitedLinkColor() == b.VisitedLinkColor();
+ a.InternalVisitedColor() == b.InternalVisitedColor();
case CSSPropertyID::kFill: {
const SVGComputedStyle& a_svg = a.SvgStyle();
const SVGComputedStyle& b_svg = b.SvgStyle();
return a_svg.FillPaint().EqualTypeOrColor(b_svg.FillPaint()) &&
- a_svg.VisitedLinkFillPaint().EqualTypeOrColor(
- b_svg.VisitedLinkFillPaint());
+ a_svg.InternalVisitedFillPaint().EqualTypeOrColor(
+ b_svg.InternalVisitedFillPaint());
}
case CSSPropertyID::kFillOpacity:
return a.FillOpacity() == b.FillOpacity();
@@ -218,7 +222,7 @@ bool CSSPropertyEquality::PropertiesEqual(const PropertyHandle& property,
return a.Orphans() == b.Orphans();
case CSSPropertyID::kOutlineColor:
return a.OutlineColor() == b.OutlineColor() &&
- a.VisitedLinkOutlineColor() == b.VisitedLinkOutlineColor();
+ a.InternalVisitedOutlineColor() == b.InternalVisitedOutlineColor();
case CSSPropertyID::kOutlineOffset:
return a.OutlineOffset() == b.OutlineOffset();
case CSSPropertyID::kOutlineWidth:
@@ -247,8 +251,8 @@ bool CSSPropertyEquality::PropertiesEqual(const PropertyHandle& property,
const SVGComputedStyle& a_svg = a.SvgStyle();
const SVGComputedStyle& b_svg = b.SvgStyle();
return a_svg.StrokePaint().EqualTypeOrColor(b_svg.StrokePaint()) &&
- a_svg.VisitedLinkStrokePaint().EqualTypeOrColor(
- b_svg.VisitedLinkStrokePaint());
+ a_svg.InternalVisitedStrokePaint().EqualTypeOrColor(
+ b_svg.InternalVisitedStrokePaint());
}
case CSSPropertyID::kStrokeDasharray:
return a.StrokeDashArray() == b.StrokeDashArray();
@@ -262,8 +266,8 @@ bool CSSPropertyEquality::PropertiesEqual(const PropertyHandle& property,
return a.StrokeWidth() == b.StrokeWidth();
case CSSPropertyID::kTextDecorationColor:
return a.TextDecorationColor() == b.TextDecorationColor() &&
- a.VisitedLinkTextDecorationColor() ==
- b.VisitedLinkTextDecorationColor();
+ a.InternalVisitedTextDecorationColor() ==
+ b.InternalVisitedTextDecorationColor();
case CSSPropertyID::kTextDecorationSkipInk:
return a.TextDecorationSkipInk() == b.TextDecorationSkipInk();
case CSSPropertyID::kTextIndent:
@@ -294,7 +298,8 @@ bool CSSPropertyEquality::PropertiesEqual(const PropertyHandle& property,
return a.RowGap() == b.RowGap();
case CSSPropertyID::kColumnRuleColor:
return a.ColumnRuleColor() == b.ColumnRuleColor() &&
- a.VisitedLinkColumnRuleColor() == b.VisitedLinkColumnRuleColor();
+ a.InternalVisitedColumnRuleColor() ==
+ b.InternalVisitedColumnRuleColor();
case CSSPropertyID::kColumnRuleWidth:
return a.ColumnRuleWidth() == b.ColumnRuleWidth();
case CSSPropertyID::kColumnWidth:
@@ -329,7 +334,8 @@ bool CSSPropertyEquality::PropertiesEqual(const PropertyHandle& property,
a.PerspectiveOriginY() == b.PerspectiveOriginY();
case CSSPropertyID::kWebkitTextStrokeColor:
return a.TextStrokeColor() == b.TextStrokeColor() &&
- a.VisitedLinkTextStrokeColor() == b.VisitedLinkTextStrokeColor();
+ a.InternalVisitedTextStrokeColor() ==
+ b.InternalVisitedTextStrokeColor();
case CSSPropertyID::kTransform:
return a.Transform() == b.Transform();
case CSSPropertyID::kTranslate:
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 33fe623e74f..93e0e603354 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
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_PROPERTY_EQUALITY_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/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/css/css_property_rule.cc b/chromium/third_party/blink/renderer/core/css/css_property_rule.cc
new file mode 100644
index 00000000000..643b1e86cb3
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/css_property_rule.cc
@@ -0,0 +1,49 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/css/css_property_rule.h"
+
+#include "third_party/blink/renderer/core/css/css_property_value_set.h"
+#include "third_party/blink/renderer/core/css/style_rule.h"
+#include "third_party/blink/renderer/core/css/style_rule_css_style_declaration.h"
+#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
+
+namespace blink {
+
+CSSPropertyRule::CSSPropertyRule(StyleRuleProperty* property_rule,
+ CSSStyleSheet* sheet)
+ : CSSRule(sheet), property_rule_(property_rule) {}
+
+CSSPropertyRule::~CSSPropertyRule() = default;
+
+CSSStyleDeclaration* CSSPropertyRule::style() const {
+ if (!properties_cssom_wrapper_) {
+ properties_cssom_wrapper_ =
+ MakeGarbageCollected<StyleRuleCSSStyleDeclaration>(
+ property_rule_->MutableProperties(),
+ const_cast<CSSPropertyRule*>(this));
+ }
+
+ return properties_cssom_wrapper_.Get();
+}
+
+String CSSPropertyRule::cssText() const {
+ // TODO(https://crbug.com/978783): Implement this.
+ return "";
+}
+
+void CSSPropertyRule::Reattach(StyleRuleBase* rule) {
+ DCHECK(rule);
+ property_rule_ = To<StyleRuleProperty>(rule);
+ if (properties_cssom_wrapper_)
+ properties_cssom_wrapper_->Reattach(property_rule_->MutableProperties());
+}
+
+void CSSPropertyRule::Trace(blink::Visitor* visitor) {
+ visitor->Trace(property_rule_);
+ visitor->Trace(properties_cssom_wrapper_);
+ CSSRule::Trace(visitor);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/css_property_rule.h b/chromium/third_party/blink/renderer/core/css/css_property_rule.h
new file mode 100644
index 00000000000..e977bb35fdc
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/css_property_rule.h
@@ -0,0 +1,48 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_PROPERTY_RULE_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_PROPERTY_RULE_H_
+
+#include "third_party/blink/renderer/core/css/css_rule.h"
+#include "third_party/blink/renderer/platform/heap/handle.h"
+#include "third_party/blink/renderer/platform/wtf/casting.h"
+
+namespace blink {
+
+class CSSStyleDeclaration;
+class StyleRuleProperty;
+class StyleRuleCSSStyleDeclaration;
+
+class CSSPropertyRule final : public CSSRule {
+ DEFINE_WRAPPERTYPEINFO();
+
+ public:
+ CSSPropertyRule(StyleRuleProperty*, CSSStyleSheet*);
+ ~CSSPropertyRule() override;
+
+ String cssText() const override;
+ void Reattach(StyleRuleBase*) override;
+
+ CSSStyleDeclaration* style() const;
+
+ void Trace(blink::Visitor*) override;
+
+ private:
+ CSSRule::Type type() const override { return kPropertyRule; }
+
+ Member<StyleRuleProperty> property_rule_;
+ mutable Member<StyleRuleCSSStyleDeclaration> properties_cssom_wrapper_;
+};
+
+template <>
+struct DowncastTraits<CSSPropertyRule> {
+ static bool AllowFrom(const CSSRule& rule) {
+ return rule.type() == CSSRule::kPropertyRule;
+ }
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_PROPERTY_RULE_H_
diff --git a/chromium/third_party/blink/renderer/core/css/css_property_rule.idl b/chromium/third_party/blink/renderer/core/css/css_property_rule.idl
new file mode 100644
index 00000000000..6ab4ed76dfd
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/css_property_rule.idl
@@ -0,0 +1,9 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+[
+ RuntimeEnabled=CSSVariables2AtProperty
+] interface CSSPropertyRule : CSSRule {
+ readonly attribute CSSStyleDeclaration style;
+};
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 85599a8db8d..730ddf8eb2d 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
@@ -25,7 +25,7 @@
#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/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -60,7 +60,7 @@ struct CSSPropertyValueMetadata {
unsigned inherited_ : 1;
};
-class CSSPropertyValue {
+class CORE_EXPORT CSSPropertyValue {
DISALLOW_NEW();
public:
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 c3e018e029a..50ae3d7403e 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
@@ -30,14 +30,13 @@
#include "third_party/blink/renderer/core/css/properties/css_property.h"
#include "third_party/blink/renderer/core/css/style_property_serializer.h"
#include "third_party/blink/renderer/core/css/style_sheet_contents.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/style_property_shorthand.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#ifndef NDEBUG
#include <stdio.h>
-#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
#endif
namespace blink {
@@ -132,7 +131,7 @@ static bool IsPropertyMatch(const CSSPropertyValueMetadata& metadata,
// Only enabled properties should be part of the style.
#if DCHECK_IS_ON()
DCHECK(!result ||
- CSSProperty::Get(resolveCSSPropertyID(property_id)).IsEnabled());
+ CSSProperty::Get(resolveCSSPropertyID(property_id)).IsWebExposed());
#endif
return result;
}
@@ -381,7 +380,6 @@ MutableCSSPropertyValueSet::SetResult MutableCSSPropertyValueSet::SetProperty(
MutableCSSPropertyValueSet::SetResult MutableCSSPropertyValueSet::SetProperty(
const AtomicString& custom_property_name,
- const PropertyRegistry* registry,
const String& value,
bool important,
SecureContextMode secure_context_mode,
@@ -393,8 +391,8 @@ MutableCSSPropertyValueSet::SetResult MutableCSSPropertyValueSet::SetProperty(
return MutableCSSPropertyValueSet::SetResult{did_parse, did_change};
}
return CSSParser::ParseValueForCustomProperty(
- this, custom_property_name, registry, value, important,
- secure_context_mode, context_style_sheet, is_animation_tainted);
+ this, custom_property_name, value, important, secure_context_mode,
+ context_style_sheet, is_animation_tainted);
}
void MutableCSSPropertyValueSet::SetProperty(CSSPropertyID property_id,
@@ -507,7 +505,7 @@ void MutableCSSPropertyValueSet::Clear() {
property_vector_.clear();
}
-inline bool ContainsId(const CSSProperty** set,
+inline bool ContainsId(const CSSProperty* const set[],
unsigned length,
CSSPropertyID id) {
for (unsigned i = 0; i < length; ++i) {
@@ -517,8 +515,9 @@ inline bool ContainsId(const CSSProperty** set,
return false;
}
-bool MutableCSSPropertyValueSet::RemovePropertiesInSet(const CSSProperty** set,
- unsigned length) {
+bool MutableCSSPropertyValueSet::RemovePropertiesInSet(
+ const CSSProperty* const set[],
+ unsigned length) {
if (property_vector_.IsEmpty())
return false;
@@ -663,7 +662,7 @@ static_assert(sizeof(CSSPropertyValueSet) ==
#ifndef NDEBUG
void CSSPropertyValueSet::ShowStyle() {
- fprintf(stderr, "%s\n", AsText().Ascii().data());
+ fprintf(stderr, "%s\n", AsText().Ascii().c_str());
}
#endif
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 02f601982c2..67b353d351a 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
@@ -39,7 +39,6 @@ namespace blink {
class CSSStyleDeclaration;
class ImmutableCSSPropertyValueSet;
class MutableCSSPropertyValueSet;
-class PropertyRegistry;
class StyleSheetContents;
enum class SecureContextMode;
@@ -252,7 +251,6 @@ class CORE_EXPORT MutableCSSPropertyValueSet : public CSSPropertyValueSet {
SecureContextMode,
StyleSheetContents* context_style_sheet = nullptr);
SetResult SetProperty(const AtomicString& custom_property_name,
- const PropertyRegistry*,
const String& value,
bool important,
SecureContextMode,
@@ -268,7 +266,7 @@ class CORE_EXPORT MutableCSSPropertyValueSet : public CSSPropertyValueSet {
template <typename T> // CSSPropertyID or AtomicString
bool RemoveProperty(T property, String* return_text = nullptr);
- bool RemovePropertiesInSet(const CSSProperty** set, unsigned length);
+ bool RemovePropertiesInSet(const CSSProperty* const set[], unsigned length);
void RemoveEquivalentProperties(const CSSPropertyValueSet*);
void RemoveEquivalentProperties(const CSSStyleDeclaration*);
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 d44ffbff666..3036f6ea9b7 100644
--- a/chromium/third_party/blink/renderer/core/css/css_rule.h
+++ b/chromium/third_party/blink/renderer/core/css/css_rule.h
@@ -42,6 +42,8 @@ class CORE_EXPORT CSSRule : public ScriptWrappable {
public:
~CSSRule() override = default;
+ // The values must match the table in [1]. See also css_rule.idl.
+ // [1] https://wiki.csswg.org/spec/cssom-constants
enum Type {
kStyleRule = 1,
kCharsetRule = 2,
@@ -55,6 +57,11 @@ class CORE_EXPORT CSSRule : public ScriptWrappable {
kSupportsRule = 12,
kFontFeatureValuesRule = 14,
kViewportRule = 15,
+ // Experimental features below. Such features must be greater than 1000:
+ // the 0-1000 range is reserved by the CSS Working Group.
+ //
+ // TODO(https://crbug.com/978781): Spec a proper number.
+ kPropertyRule = 1001,
};
virtual Type type() const = 0;
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 49e771e6df0..d63735b882f 100644
--- a/chromium/third_party/blink/renderer/core/css/css_rule.idl
+++ b/chromium/third_party/blink/renderer/core/css/css_rule.idl
@@ -53,4 +53,8 @@
// CSS Device Adaptation
// https://drafts.csswg.org/css-device-adapt/#css-rule-interface
[RuntimeEnabled=CSSViewport] const unsigned short VIEWPORT_RULE = 15;
+
+ // CSS Properties and Values Level 1
+ // TODO(https://crbug.com/978781): Spec a proper number.
+ [RuntimeEnabled=CSSVariables2AtProperty] const unsigned short PROPERTY_RULE = 1001;
};
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 d68bd27a763..e441087e457 100644
--- a/chromium/third_party/blink/renderer/core/css/css_selector.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_selector.cc
@@ -461,19 +461,21 @@ static CSSSelector::PseudoType NameToPseudoType(const AtomicString& name,
#ifndef NDEBUG
void CSSSelector::Show(int indent) const {
- printf("%*sSelectorText(): %s\n", indent, "", SelectorText().Ascii().data());
+ printf("%*sSelectorText(): %s\n", indent, "", SelectorText().Ascii().c_str());
printf("%*smatch_: %d\n", indent, "", match_);
if (match_ != kTag)
- printf("%*sValue(): %s\n", indent, "", Value().Ascii().data());
+ printf("%*sValue(): %s\n", indent, "", Value().Ascii().c_str());
printf("%*sGetPseudoType(): %d\n", indent, "", GetPseudoType());
- if (match_ == kTag)
+ if (match_ == kTag) {
printf("%*sTagQName().LocalName(): %s\n", indent, "",
- TagQName().LocalName().Ascii().data());
+ TagQName().LocalName().Ascii().c_str());
+ }
printf("%*sIsAttributeSelector(): %d\n", indent, "", IsAttributeSelector());
- if (IsAttributeSelector())
+ if (IsAttributeSelector()) {
printf("%*sAttribute(): %s\n", indent, "",
- Attribute().LocalName().Ascii().data());
- printf("%*sArgument(): %s\n", indent, "", Argument().Ascii().data());
+ Attribute().LocalName().Ascii().c_str());
+ }
+ printf("%*sArgument(): %s\n", indent, "", Argument().Ascii().c_str());
printf("%*sSpecificity(): %u\n", indent, "", Specificity());
if (TagHistory()) {
printf("\n%*s--> (Relation() == %d)\n", indent, "", Relation());
@@ -485,7 +487,7 @@ void CSSSelector::Show(int indent) const {
void CSSSelector::Show() const {
printf("\n******* CSSSelector::Show(\"%s\") *******\n",
- SelectorText().Ascii().data());
+ SelectorText().Ascii().c_str());
Show(2);
printf("******* end *******\n");
}
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 86652324ef7..592ae1760eb 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
@@ -27,11 +27,11 @@
#include "third_party/blink/renderer/core/css/css_selector_list.h"
#include <memory>
-#include <vector>
#include "third_party/blink/renderer/core/css/parser/css_parser_selector.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/text/string_builder.h"
+#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace {
// CSSSelector is one of the top types that consume renderer memory,
@@ -89,9 +89,8 @@ CSSSelectorList CSSSelectorList::ConcatenateListExpansion(
return list;
}
-std::vector<const CSSSelector*> SelectorBoundaries(
- const CSSSelectorList& list) {
- std::vector<const CSSSelector*> result;
+Vector<const CSSSelector*> SelectorBoundaries(const CSSSelectorList& list) {
+ Vector<const CSSSelector*> result;
for (const CSSSelector* s = list.First(); s; s = list.Next(*s)) {
result.push_back(s);
}
@@ -134,8 +133,7 @@ void AddToList(CSSSelector*& destination,
CSSSelectorList CSSSelectorList::ExpandedFirstPseudoClass() const {
DCHECK(this->RequiresExpansion());
unsigned original_length = this->ComputeLength();
- std::vector<const CSSSelector*> selector_boundaries =
- SelectorBoundaries(*this);
+ Vector<const CSSSelector*> selector_boundaries = SelectorBoundaries(*this);
size_t begin = 0;
CSSSelectorList transformed = this->Copy();
@@ -156,7 +154,7 @@ CSSSelectorList CSSSelectorList::ExpandedFirstPseudoClass() const {
unsigned inner_selector_length =
simple_selector->SelectorList()->ComputeLength();
- std::vector<const CSSSelector*> selector_arg_boundaries =
+ Vector<const CSSSelector*> selector_arg_boundaries =
SelectorBoundaries(*simple_selector->SelectorList());
wtf_size_t num_args =
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 f159a22b6de..6e143c94af0 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
@@ -72,7 +72,7 @@ void CSSSelectorWatch::CallbackSelectorChangeTimerFired(TimerBase*) {
if (timer_expirations_ < 1) {
timer_expirations_++;
- callback_selector_change_timer_.StartOneShot(TimeDelta(), FROM_HERE);
+ callback_selector_change_timer_.StartOneShot(base::TimeDelta(), FROM_HERE);
return;
}
if (GetSupplementable()->GetFrame()) {
@@ -131,7 +131,8 @@ void CSSSelectorWatch::UpdateSelectorMatches(
} else {
timer_expirations_ = 0;
if (!callback_selector_change_timer_.IsActive()) {
- callback_selector_change_timer_.StartOneShot(TimeDelta(), FROM_HERE);
+ callback_selector_change_timer_.StartOneShot(base::TimeDelta(),
+ FROM_HERE);
}
}
}
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 4307bee895c..697a1b6eb9c 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
@@ -140,9 +140,9 @@ CSSPropertyID CssPropertyInfo(const AtomicString& name) {
if (unresolved_property == CSSPropertyID::kVariable)
unresolved_property = CSSPropertyID::kInvalid;
map.insert(name, unresolved_property);
- DCHECK(
- !isValidCSSPropertyID(unresolved_property) ||
- CSSProperty::Get(resolveCSSPropertyID(unresolved_property)).IsEnabled());
+ DCHECK(!isValidCSSPropertyID(unresolved_property) ||
+ CSSProperty::Get(resolveCSSPropertyID(unresolved_property))
+ .IsWebExposed());
return unresolved_property;
}
@@ -171,7 +171,7 @@ bool CSSStyleDeclaration::AnonymousNamedSetter(ScriptState* script_state,
return false;
// We create the ExceptionState manually due to performance issues: adding
// [RaisesException] to the IDL causes the bindings layer to expensively
- // create a CString to set the ExceptionState's |property_name| argument,
+ // create a std::string to set the ExceptionState's |property_name| argument,
// while we can use CSSProperty::GetPropertyName() here (see bug 829408).
ExceptionState exception_state(
script_state->GetIsolate(), ExceptionState::kSetterContext,
@@ -195,17 +195,17 @@ void CSSStyleDeclaration::NamedPropertyEnumerator(Vector<String>& names,
for (CSSPropertyID property_id : CSSPropertyIDList()) {
const CSSProperty& property_class =
CSSProperty::Get(resolveCSSPropertyID(property_id));
- if (property_class.IsEnabled())
+ if (property_class.IsWebExposed())
property_names.push_back(property_class.GetJSPropertyName());
}
for (CSSPropertyID property_id : kCSSPropertyAliasList) {
const CSSUnresolvedProperty* property_class =
CSSUnresolvedProperty::GetAliasProperty(property_id);
- if (property_class->IsEnabled())
+ if (property_class->IsWebExposed())
property_names.push_back(property_class->GetJSPropertyName());
}
std::sort(property_names.begin(), property_names.end(),
- WTF::CodePointCompareLessThan);
+ WTF::CodeUnitCompareLessThan);
}
names = property_names;
}
diff --git a/chromium/third_party/blink/renderer/core/css/css_supports_rule.idl b/chromium/third_party/blink/renderer/core/css/css_supports_rule.idl
index 705a387da25..2cfb26558a6 100644
--- a/chromium/third_party/blink/renderer/core/css/css_supports_rule.idl
+++ b/chromium/third_party/blink/renderer/core/css/css_supports_rule.idl
@@ -28,5 +28,7 @@
// https://drafts.csswg.org/css-conditional/#the-csssupportsrule-interface
-interface CSSSupportsRule : CSSConditionRule {
+[
+ Exposed=Window
+] interface CSSSupportsRule : CSSConditionRule {
};
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
deleted file mode 100644
index 926d064fa8f..00000000000
--- a/chromium/third_party/blink/renderer/core/css/css_syntax_component.cc
+++ /dev/null
@@ -1,63 +0,0 @@
-// Copyright 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#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
index bda4962f8cc..a4e11012a48 100644
--- a/chromium/third_party/blink/renderer/core/css/css_syntax_component.h
+++ b/chromium/third_party/blink/renderer/core/css/css_syntax_component.h
@@ -7,13 +7,11 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/css/css_value.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
-class CSSStyleValue;
-
enum class CSSSyntaxType {
kTokenStream,
kIdent,
@@ -58,8 +56,6 @@ class CSSSyntaxComponent {
return repeat_ == CSSSyntaxRepeat::kSpaceSeparated ? ' ' : ',';
}
- bool CanTake(const CSSStyleValue&) const;
-
private:
CSSSyntaxType type_;
String string_; // Only used when type_ is CSSSyntaxType::kIdent
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 de4646188bd..276a7aaf94a 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
@@ -127,19 +127,6 @@ const CSSValue* ConsumeSyntaxComponent(const CSSSyntaxComponent& syntax,
} // namespace
-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 {
- return Match(value);
-}
-
const CSSValue* CSSSyntaxDescriptor::Parse(CSSParserTokenRange range,
const CSSParserContext* context,
bool is_animation_tainted) const {
@@ -161,6 +148,17 @@ const CSSValue* CSSSyntaxDescriptor::Parse(CSSParserTokenRange range,
is_animation_tainted);
}
+CSSSyntaxDescriptor CSSSyntaxDescriptor::IsolatedCopy() const {
+ Vector<CSSSyntaxComponent> syntax_components_copy;
+ syntax_components_copy.ReserveCapacity(syntax_components_.size());
+ for (const auto& syntax_component : syntax_components_) {
+ syntax_components_copy.push_back(CSSSyntaxComponent(
+ syntax_component.GetType(), syntax_component.GetString().IsolatedCopy(),
+ syntax_component.GetRepeat()));
+ }
+ return CSSSyntaxDescriptor(std::move(syntax_components_copy));
+}
+
CSSSyntaxDescriptor::CSSSyntaxDescriptor(Vector<CSSSyntaxComponent> components)
: syntax_components_(std::move(components)) {
DCHECK(syntax_components_.size());
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 5ea14950240..86d3f7333d8 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
@@ -7,6 +7,7 @@
#include "third_party/blink/renderer/core/css/css_syntax_component.h"
#include "third_party/blink/renderer/core/css/parser/css_parser_token_range.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_copier.h"
namespace blink {
@@ -18,8 +19,6 @@ 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 IsTokenStream() const {
return syntax_components_.size() == 1 &&
syntax_components_[0].GetType() == CSSSyntaxType::kTokenStream;
@@ -34,6 +33,8 @@ class CORE_EXPORT CSSSyntaxDescriptor {
return Components() != a.Components();
}
+ CSSSyntaxDescriptor IsolatedCopy() const;
+
private:
friend class CSSSyntaxStringParser;
friend class CSSSyntaxStringParserTest;
@@ -48,4 +49,21 @@ class CORE_EXPORT CSSSyntaxDescriptor {
} // namespace blink
+namespace WTF {
+
+template <wtf_size_t inlineCapacity, typename Allocator>
+struct CrossThreadCopier<
+ Vector<blink::CSSSyntaxDescriptor, inlineCapacity, Allocator>> {
+ using Type = Vector<blink::CSSSyntaxDescriptor, inlineCapacity, Allocator>;
+ static Type Copy(const Type& value) {
+ Type result;
+ result.ReserveInitialCapacity(value.size());
+ for (const auto& element : value)
+ result.push_back(element.IsolatedCopy());
+ return result;
+ }
+};
+
+} // namespace WTF
+
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_SYNTAX_DESCRIPTOR_H_
diff --git a/chromium/third_party/blink/renderer/core/css/css_syntax_string_parser.h b/chromium/third_party/blink/renderer/core/css/css_syntax_string_parser.h
index d681a907e50..4ad11fd2ba0 100644
--- a/chromium/third_party/blink/renderer/core/css/css_syntax_string_parser.h
+++ b/chromium/third_party/blink/renderer/core/css/css_syntax_string_parser.h
@@ -8,7 +8,7 @@
#include "base/optional.h"
#include "third_party/blink/renderer/core/css/css_syntax_descriptor.h"
#include "third_party/blink/renderer/core/css/parser/css_tokenizer_input_stream.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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
index f86d38bde1a..e4fd4c73adf 100644
--- a/chromium/third_party/blink/renderer/core/css/css_test_helpers.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_test_helpers.cc
@@ -9,7 +9,12 @@
#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/css_variable_data.h"
+#include "third_party/blink/renderer/core/css/parser/css_parser_context.h"
+#include "third_party/blink/renderer/core/css/parser/css_parser_local_context.h"
+#include "third_party/blink/renderer/core/css/parser/css_property_parser.h"
#include "third_party/blink/renderer/core/css/parser/css_tokenizer.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/property_descriptor.h"
#include "third_party/blink/renderer/core/css/property_registration.h"
#include "third_party/blink/renderer/core/css/property_registry.h"
@@ -47,7 +52,7 @@ RuleSet& TestStyleSheet::GetRuleSet() {
return rule_set;
}
-void TestStyleSheet::AddCSSRules(const char* css_text, bool is_empty_sheet) {
+void TestStyleSheet::AddCSSRules(const String& css_text, bool is_empty_sheet) {
TextPosition position;
unsigned sheet_length = style_sheet_->length();
style_sheet_->Contents()->ParseStringAtPosition(css_text, position);
@@ -87,5 +92,20 @@ const CSSValue* CreateCustomIdent(AtomicString s) {
return MakeGarbageCollected<CSSCustomIdentValue>(s);
}
+const CSSValue* ParseLonghand(Document& document,
+ const CSSProperty& property,
+ const String& value) {
+ const auto* longhand = DynamicTo<Longhand>(property);
+ if (!longhand)
+ return nullptr;
+
+ const auto* context = MakeGarbageCollected<CSSParserContext>(document);
+ CSSParserLocalContext local_context;
+ auto tokens = CSSTokenizer(value).TokenizeToEOF();
+ CSSParserTokenRange range(tokens);
+
+ return longhand->ParseSingleValue(range, *context, local_context);
+}
+
} // 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
index cdb0e4aa20a..3a9c1efc4dd 100644
--- a/chromium/third_party/blink/renderer/core/css/css_test_helpers.h
+++ b/chromium/third_party/blink/renderer/core/css/css_test_helpers.h
@@ -7,7 +7,7 @@
#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"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -15,6 +15,7 @@ class Document;
class CSSStyleSheet;
class CSSVariableData;
class CSSValue;
+class CSSProperty;
namespace css_test_helpers {
@@ -33,7 +34,7 @@ class TestStyleSheet {
const Document& GetDocument() { return *document_; }
- void AddCSSRules(const char* rule_text, bool is_empty_sheet = false);
+ void AddCSSRules(const String& rule_text, bool is_empty_sheet = false);
RuleSet& GetRuleSet();
CSSRuleList* CssRules();
@@ -50,6 +51,9 @@ void RegisterProperty(Document& document,
scoped_refptr<CSSVariableData> CreateVariableData(String);
const CSSValue* CreateCustomIdent(AtomicString);
+const CSSValue* ParseLonghand(Document& document,
+ const CSSProperty&,
+ const String& value);
} // namespace css_test_helpers
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/css_timing_function_value.cc b/chromium/third_party/blink/renderer/core/css/css_timing_function_value.cc
index c58c41013e6..91529f53a87 100644
--- a/chromium/third_party/blink/renderer/core/css/css_timing_function_value.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_timing_function_value.cc
@@ -47,10 +47,33 @@ String CSSStepsTimingFunctionValue::CustomCSSText() const {
case StepsTimingFunction::StepPosition::START:
step_position_string = "start";
break;
+
case StepsTimingFunction::StepPosition::END:
- step_position_string = "end";
+ step_position_string = "";
+ break;
+
+ case StepsTimingFunction::StepPosition::JUMP_BOTH:
+ step_position_string = "jump-both";
+ break;
+
+ case StepsTimingFunction::StepPosition::JUMP_END:
+ step_position_string = "";
break;
+
+ case StepsTimingFunction::StepPosition::JUMP_NONE:
+ step_position_string = "jump-none";
+ break;
+
+ case StepsTimingFunction::StepPosition::JUMP_START:
+ step_position_string = "jump-start";
}
+
+ // https://drafts.csswg.org/css-easing-1/#serialization
+ // If the step position is jump-end or end, serialize as steps(<integer>).
+ // Otherwise, serialize as steps(<integer>, <step-position>).
+ if (step_position_string.IsEmpty())
+ return "steps(" + String::Number(steps_) + ')';
+
return "steps(" + String::Number(steps_) + ", " + step_position_string + ')';
}
diff --git a/chromium/third_party/blink/renderer/core/css/css_to_length_conversion_data.h b/chromium/third_party/blink/renderer/core/css/css_to_length_conversion_data.h
index eb3fb866e59..fa46b4fea6c 100644
--- a/chromium/third_party/blink/renderer/core/css/css_to_length_conversion_data.h
+++ b/chromium/third_party/blink/renderer/core/css/css_to_length_conversion_data.h
@@ -35,7 +35,7 @@
#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/platform/geometry/double_size.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
diff --git a/chromium/third_party/blink/renderer/core/css/css_unset_value.h b/chromium/third_party/blink/renderer/core/css/css_unset_value.h
index 56ff720ec80..91f23e06e35 100644
--- a/chromium/third_party/blink/renderer/core/css/css_unset_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_unset_value.h
@@ -6,6 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_UNSET_VALUE_H_
#include "base/memory/scoped_refptr.h"
+#include "base/util/type_safety/pass_key.h"
#include "third_party/blink/renderer/core/css/css_value.h"
#include "third_party/blink/renderer/platform/wtf/casting.h"
@@ -19,9 +20,7 @@ class CORE_EXPORT CSSUnsetValue : public CSSValue {
public:
static CSSUnsetValue* Create();
- // Only construct through MakeGarbageCollected for the initial value. Use
- // Create() to get the pooled value.
- CSSUnsetValue() : CSSValue(kUnsetClass) {}
+ explicit CSSUnsetValue(util::PassKey<CSSValuePool>) : CSSValue(kUnsetClass) {}
String CustomCSSText() const;
@@ -30,9 +29,6 @@ class CORE_EXPORT CSSUnsetValue : public CSSValue {
void TraceAfterDispatch(blink::Visitor* visitor) {
CSSValue::TraceAfterDispatch(visitor);
}
-
- private:
- friend class ::blink::CSSValuePool;
};
} // namespace cssvalue
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 1e56eae2652..1c0a54ad5d7 100644
--- a/chromium/third_party/blink/renderer/core/css/css_value.cc
+++ b/chromium/third_party/blink/renderer/core/css/css_value.cc
@@ -53,9 +53,13 @@
#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_keyframe_shorthand_value.h"
#include "third_party/blink/renderer/core/css/css_layout_function_value.h"
+#include "third_party/blink/renderer/core/css/css_math_function_value.h"
+#include "third_party/blink/renderer/core/css/css_numeric_literal_value.h"
#include "third_party/blink/renderer/core/css/css_paint_value.h"
#include "third_party/blink/renderer/core/css/css_path_value.h"
+#include "third_party/blink/renderer/core/css/css_pending_interpolation_value.h"
#include "third_party/blink/renderer/core/css/css_pending_substitution_value.h"
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
#include "third_party/blink/renderer/core/css/css_quad_value.h"
@@ -95,7 +99,7 @@ CSSValue* CSSValue::Create(const Length& value, float zoom) {
case Length::kPercent:
case Length::kFixed:
case Length::kCalculated:
- return CSSPrimitiveValue::Create(value, zoom);
+ return CSSPrimitiveValue::CreateFromLength(value, zoom);
case Length::kDeviceWidth:
case Length::kDeviceHeight:
case Length::kMaxSizeNone:
@@ -214,12 +218,16 @@ bool CSSValue::operator==(const CSSValue& other) const {
return CompareCSSValues<CSSGridTemplateAreasValue>(*this, other);
case kPathClass:
return CompareCSSValues<CSSPathValue>(*this, other);
- case kPrimitiveClass:
- return CompareCSSValues<CSSPrimitiveValue>(*this, other);
+ case kNumericLiteralClass:
+ return CompareCSSValues<CSSNumericLiteralValue>(*this, other);
+ case kMathFunctionClass:
+ return CompareCSSValues<CSSMathFunctionValue>(*this, other);
case kRayClass:
return CompareCSSValues<CSSRayValue>(*this, other);
case kIdentifierClass:
return CompareCSSValues<CSSIdentifierValue>(*this, other);
+ case kKeyframeShorthandClass:
+ return CompareCSSValues<CSSKeyframeShorthandValue>(*this, other);
case kQuadClass:
return CompareCSSValues<CSSQuadValue>(*this, other);
case kReflectClass:
@@ -245,6 +253,8 @@ bool CSSValue::operator==(const CSSValue& other) const {
return CompareCSSValues<CSSImageSetValue>(*this, other);
case kCSSContentDistributionClass:
return CompareCSSValues<CSSContentDistributionValue>(*this, other);
+ case kPendingInterpolationClass:
+ return CompareCSSValues<CSSPendingInterpolationValue>(*this, other);
case kCustomPropertyDeclarationClass:
return CompareCSSValues<CSSCustomPropertyDeclaration>(*this, other);
case kVariableReferenceClass:
@@ -324,12 +334,16 @@ String CSSValue::CssText() const {
return To<CSSGridTemplateAreasValue>(this)->CustomCSSText();
case kPathClass:
return To<CSSPathValue>(this)->CustomCSSText();
- case kPrimitiveClass:
- return To<CSSPrimitiveValue>(this)->CustomCSSText();
+ case kNumericLiteralClass:
+ return To<CSSNumericLiteralValue>(this)->CustomCSSText();
+ case kMathFunctionClass:
+ return To<CSSMathFunctionValue>(this)->CustomCSSText();
case kRayClass:
return To<CSSRayValue>(this)->CustomCSSText();
case kIdentifierClass:
return To<CSSIdentifierValue>(this)->CustomCSSText();
+ case kKeyframeShorthandClass:
+ return To<CSSKeyframeShorthandValue>(this)->CustomCSSText();
case kQuadClass:
return To<CSSQuadValue>(this)->CustomCSSText();
case kReflectClass:
@@ -354,6 +368,8 @@ String CSSValue::CssText() const {
return To<CSSImageSetValue>(this)->CustomCSSText();
case kCSSContentDistributionClass:
return To<CSSContentDistributionValue>(this)->CustomCSSText();
+ case kPendingInterpolationClass:
+ return To<CSSPendingInterpolationValue>(this)->CustomCSSText();
case kVariableReferenceClass:
return To<CSSVariableReferenceValue>(this)->CustomCSSText();
case kCustomPropertyDeclarationClass:
@@ -462,8 +478,11 @@ void CSSValue::FinalizeGarbageCollectedObject() {
case kPathClass:
To<CSSPathValue>(this)->~CSSPathValue();
return;
- case kPrimitiveClass:
- To<CSSPrimitiveValue>(this)->~CSSPrimitiveValue();
+ case kNumericLiteralClass:
+ To<CSSNumericLiteralValue>(this)->~CSSNumericLiteralValue();
+ return;
+ case kMathFunctionClass:
+ To<CSSMathFunctionValue>(this)->~CSSMathFunctionValue();
return;
case kRayClass:
To<CSSRayValue>(this)->~CSSRayValue();
@@ -471,6 +490,9 @@ void CSSValue::FinalizeGarbageCollectedObject() {
case kIdentifierClass:
To<CSSIdentifierValue>(this)->~CSSIdentifierValue();
return;
+ case kKeyframeShorthandClass:
+ To<CSSKeyframeShorthandValue>(this)->~CSSKeyframeShorthandValue();
+ return;
case kQuadClass:
To<CSSQuadValue>(this)->~CSSQuadValue();
return;
@@ -508,6 +530,9 @@ void CSSValue::FinalizeGarbageCollectedObject() {
case kCSSContentDistributionClass:
To<CSSContentDistributionValue>(this)->~CSSContentDistributionValue();
return;
+ case kPendingInterpolationClass:
+ To<CSSPendingInterpolationValue>(this)->~CSSPendingInterpolationValue();
+ return;
case kVariableReferenceClass:
To<CSSVariableReferenceValue>(this)->~CSSVariableReferenceValue();
return;
@@ -619,8 +644,11 @@ void CSSValue::Trace(blink::Visitor* visitor) {
case kPathClass:
To<CSSPathValue>(this)->TraceAfterDispatch(visitor);
return;
- case kPrimitiveClass:
- To<CSSPrimitiveValue>(this)->TraceAfterDispatch(visitor);
+ case kNumericLiteralClass:
+ To<CSSNumericLiteralValue>(this)->TraceAfterDispatch(visitor);
+ return;
+ case kMathFunctionClass:
+ To<CSSMathFunctionValue>(this)->TraceAfterDispatch(visitor);
return;
case kRayClass:
To<CSSRayValue>(this)->TraceAfterDispatch(visitor);
@@ -628,6 +656,9 @@ void CSSValue::Trace(blink::Visitor* visitor) {
case kIdentifierClass:
To<CSSIdentifierValue>(this)->TraceAfterDispatch(visitor);
return;
+ case kKeyframeShorthandClass:
+ To<CSSKeyframeShorthandValue>(this)->TraceAfterDispatch(visitor);
+ return;
case kQuadClass:
To<CSSQuadValue>(this)->TraceAfterDispatch(visitor);
return;
@@ -664,6 +695,9 @@ void CSSValue::Trace(blink::Visitor* visitor) {
case kCSSContentDistributionClass:
To<CSSContentDistributionValue>(this)->TraceAfterDispatch(visitor);
return;
+ case kPendingInterpolationClass:
+ To<CSSPendingInterpolationValue>(this)->TraceAfterDispatch(visitor);
+ return;
case kVariableReferenceClass:
To<CSSVariableReferenceValue>(this)->TraceAfterDispatch(visitor);
return;
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 aa399047640..447fc073f62 100644
--- a/chromium/third_party/blink/renderer/core/css/css_value.h
+++ b/chromium/third_party/blink/renderer/core/css/css_value.h
@@ -33,14 +33,12 @@ class Length;
class CORE_EXPORT CSSValue : public GarbageCollectedFinalized<CSSValue> {
public:
- static void* AllocateObject(size_t size, bool is_eager) {
+ static void* AllocateObject(size_t size) {
ThreadState* state =
ThreadStateFor<ThreadingTrait<CSSValue>::kAffinity>::GetState();
const char* type_name = "blink::CSSValue";
return state->Heap().AllocateOnArenaIndex(
- state, size,
- is_eager ? BlinkGC::kEagerSweepArenaIndex
- : BlinkGC::kCSSValueArenaIndex,
+ state, size, BlinkGC::kCSSValueArenaIndex,
GCInfoTrait<CSSValue>::Index(), type_name);
}
@@ -49,7 +47,13 @@ class CORE_EXPORT CSSValue : public GarbageCollectedFinalized<CSSValue> {
String CssText() const;
- bool IsPrimitiveValue() const { return class_type_ == kPrimitiveClass; }
+ bool IsNumericLiteralValue() const {
+ return class_type_ == kNumericLiteralClass;
+ }
+ bool IsMathFunctionValue() const { return class_type_ == kMathFunctionClass; }
+ bool IsPrimitiveValue() const {
+ return IsNumericLiteralValue() || IsMathFunctionValue();
+ }
bool IsIdentifierValue() const { return class_type_ == kIdentifierClass; }
bool IsValuePair() const { return class_type_ == kValuePairClass; }
bool IsValueList() const { return class_type_ >= kValueListClass; }
@@ -138,6 +142,9 @@ class CORE_EXPORT CSSValue : public GarbageCollectedFinalized<CSSValue> {
bool IsContentDistributionValue() const {
return class_type_ == kCSSContentDistributionClass;
}
+ bool IsPendingInterpolationValue() const {
+ return class_type_ == kPendingInterpolationClass;
+ }
bool IsUnicodeRangeValue() const { return class_type_ == kUnicodeRangeClass; }
bool IsGridLineNamesValue() const {
return class_type_ == kGridLineNamesClass;
@@ -161,6 +168,9 @@ class CORE_EXPORT CSSValue : public GarbageCollectedFinalized<CSSValue> {
return class_type_ == kInvalidVariableValueClass;
}
bool IsAxisValue() const { return class_type_ == kAxisClass; }
+ bool IsShorthandWrapperValue() const {
+ return class_type_ == kKeyframeShorthandClass;
+ }
bool HasFailedOrCanceledSubresources() const;
bool MayContainUrl() const;
@@ -181,7 +191,8 @@ class CORE_EXPORT CSSValue : public GarbageCollectedFinalized<CSSValue> {
protected:
static const size_t kClassTypeBits = 6;
enum ClassType {
- kPrimitiveClass,
+ kNumericLiteralClass,
+ kMathFunctionClass,
kIdentifierClass,
kColorClass,
kCounterClass,
@@ -239,6 +250,9 @@ class CORE_EXPORT CSSValue : public GarbageCollectedFinalized<CSSValue> {
kCSSContentDistributionClass,
+ kPendingInterpolationClass,
+ kKeyframeShorthandClass,
+
// List class types must appear after ValueListClass.
kValueListClass,
kFunctionClass,
@@ -256,8 +270,9 @@ class CORE_EXPORT CSSValue : public GarbageCollectedFinalized<CSSValue> {
ClassType GetClassType() const { return static_cast<ClassType>(class_type_); }
explicit CSSValue(ClassType class_type)
- : primitive_unit_type_(0),
+ : numeric_literal_unit_type_(0),
value_list_separator_(kSpaceSeparator),
+ is_non_negative_math_function_(false),
class_type_(class_type) {}
// NOTE: This class is non-virtual for memory and performance reasons.
@@ -267,11 +282,14 @@ class CORE_EXPORT CSSValue : public GarbageCollectedFinalized<CSSValue> {
// The bits in this section are only used by specific subclasses but kept here
// to maximize struct packing.
- // CSSPrimitiveValue bits:
- unsigned primitive_unit_type_ : 7; // CSSPrimitiveValue::UnitType
+ // CSSNumericLiteralValue bits:
+ unsigned numeric_literal_unit_type_ : 7; // CSSPrimitiveValue::UnitType
unsigned value_list_separator_ : kValueListSeparatorBits;
+ // CSSMathFunctionValue
+ unsigned is_non_negative_math_function_ : 1;
+
private:
unsigned class_type_ : kClassTypeBits; // ClassType
};
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 7327ea0361d..ac4693621d1 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
@@ -755,6 +755,10 @@
"ease-in",
"ease-out",
"ease-in-out",
+ "jump-both",
+ "jump-end",
+ "jump-none",
+ "jump-start",
"step-start",
"step-end",
"steps",
@@ -1103,8 +1107,13 @@
"ray",
"sides",
+ // math functions
+ // https://drafts.csswg.org/css-values-4/#math
"calc",
"-webkit-calc",
+ "min",
+ "max",
+ "clamp",
// scroll-snap-type
// none
@@ -1172,6 +1181,10 @@
// pan-down
// none
+ // @property
+ "true",
+ "false",
+
// (prefers-*:) media features
"no-preference",
@@ -1184,5 +1197,9 @@
// (prefers-reduced-motion:) media feature
"reduce",
+
+ // (forced-colors:) media feature
+ // none
+ "active",
],
}
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 bbcab26990a..8cfa8f785dc 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
@@ -46,12 +46,25 @@ CSSValuePool& CssValuePool() {
CSSValuePool::CSSValuePool()
: inherited_value_(MakeGarbageCollected<CSSInheritedValue>()),
initial_value_(MakeGarbageCollected<CSSInitialValue>()),
- unset_value_(MakeGarbageCollected<CSSUnsetValue>()),
+ unset_value_(MakeGarbageCollected<CSSUnsetValue>(PassKey())),
invalid_variable_value_(MakeGarbageCollected<CSSInvalidVariableValue>()),
color_transparent_(
MakeGarbageCollected<CSSColorValue>(Color::kTransparent)),
color_white_(MakeGarbageCollected<CSSColorValue>(Color::kWhite)),
color_black_(MakeGarbageCollected<CSSColorValue>(Color::kBlack)) {
+ {
+ using Value = CSSPendingInterpolationValue;
+ using Type = CSSPendingInterpolationValue::Type;
+ pending_interpolation_values_[0] =
+ MakeGarbageCollected<Value>(Type::kCSSProperty);
+ pending_interpolation_values_[1] =
+ MakeGarbageCollected<Value>(Type::kPresentationAttribute);
+ static_assert(static_cast<size_t>(Type::kCSSProperty) == 0u,
+ "kCSSProperty must be 0");
+ static_assert(static_cast<size_t>(Type::kPresentationAttribute) == 1u,
+ "kPresentationAttribute must be 1");
+ }
+
identifier_value_cache_.resize(numCSSValueKeywords);
pixel_value_cache_.resize(kMaximumCacheableIntegerValue + 1);
percent_value_cache_.resize(kMaximumCacheableIntegerValue + 1);
@@ -63,6 +76,8 @@ void CSSValuePool::Trace(blink::Visitor* visitor) {
visitor->Trace(initial_value_);
visitor->Trace(unset_value_);
visitor->Trace(invalid_variable_value_);
+ visitor->Trace(pending_interpolation_values_[0]);
+ visitor->Trace(pending_interpolation_values_[1]);
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 25a6c6ddb7a..ce42ae5e3b4 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
@@ -28,6 +28,7 @@
#include "base/macros.h"
#include "base/memory/scoped_refptr.h"
+#include "base/util/type_safety/pass_key.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/css/css_color_value.h"
#include "third_party/blink/renderer/core/css/css_custom_ident_value.h"
@@ -36,7 +37,8 @@
#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_numeric_literal_value.h"
+#include "third_party/blink/renderer/core/css/css_pending_interpolation_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"
@@ -50,10 +52,13 @@ class CORE_EXPORT CSSValuePool
: public GarbageCollectedFinalized<CSSValuePool> {
public:
+ using PassKey = util::PassKey<CSSValuePool>;
+
// TODO(sashab): Make all the value pools store const CSSValues.
static const int kMaximumCacheableIntegerValue = 255;
using CSSColorValue = cssvalue::CSSColorValue;
using CSSUnsetValue = cssvalue::CSSUnsetValue;
+ using CSSPendingInterpolationValue = cssvalue::CSSPendingInterpolationValue;
using ColorValueCache = HeapHashMap<unsigned, Member<CSSColorValue>>;
static const unsigned kMaximumColorCacheSize = 512;
using FontFaceValueCache =
@@ -73,6 +78,12 @@ class CORE_EXPORT CSSValuePool
CSSInvalidVariableValue* InvalidVariableValue() {
return invalid_variable_value_;
}
+ CSSPendingInterpolationValue* PendingInterpolationValue(
+ CSSPendingInterpolationValue::Type type) {
+ DCHECK_GE(static_cast<size_t>(type), 0u);
+ DCHECK_LE(static_cast<size_t>(type), 1u);
+ return pending_interpolation_values_[static_cast<size_t>(type)];
+ }
// Vector caches.
CSSIdentifierValue* IdentifierCacheValue(CSSValueID ident) {
@@ -82,25 +93,28 @@ class CORE_EXPORT CSSValuePool
CSSIdentifierValue* css_value) {
return identifier_value_cache_[static_cast<int>(ident)] = css_value;
}
- CSSPrimitiveValue* PixelCacheValue(int int_value) {
+ CSSNumericLiteralValue* PixelCacheValue(int int_value) {
return pixel_value_cache_[int_value];
}
- CSSPrimitiveValue* SetPixelCacheValue(int int_value,
- CSSPrimitiveValue* css_value) {
+ CSSNumericLiteralValue* SetPixelCacheValue(
+ int int_value,
+ CSSNumericLiteralValue* css_value) {
return pixel_value_cache_[int_value] = css_value;
}
- CSSPrimitiveValue* PercentCacheValue(int int_value) {
+ CSSNumericLiteralValue* PercentCacheValue(int int_value) {
return percent_value_cache_[int_value];
}
- CSSPrimitiveValue* SetPercentCacheValue(int int_value,
- CSSPrimitiveValue* css_value) {
+ CSSNumericLiteralValue* SetPercentCacheValue(
+ int int_value,
+ CSSNumericLiteralValue* css_value) {
return percent_value_cache_[int_value] = css_value;
}
- CSSPrimitiveValue* NumberCacheValue(int int_value) {
+ CSSNumericLiteralValue* NumberCacheValue(int int_value) {
return number_value_cache_[int_value];
}
- CSSPrimitiveValue* SetNumberCacheValue(int int_value,
- CSSPrimitiveValue* css_value) {
+ CSSNumericLiteralValue* SetNumberCacheValue(
+ int int_value,
+ CSSNumericLiteralValue* css_value) {
return number_value_cache_[int_value] = css_value;
}
@@ -131,6 +145,7 @@ class CORE_EXPORT CSSValuePool
Member<CSSInitialValue> initial_value_;
Member<CSSUnsetValue> unset_value_;
Member<CSSInvalidVariableValue> invalid_variable_value_;
+ Member<CSSPendingInterpolationValue> pending_interpolation_values_[2];
Member<CSSColorValue> color_transparent_;
Member<CSSColorValue> color_white_;
Member<CSSColorValue> color_black_;
@@ -138,11 +153,11 @@ class CORE_EXPORT CSSValuePool
// Vector caches.
HeapVector<Member<CSSIdentifierValue>, numCSSValueKeywords>
identifier_value_cache_;
- HeapVector<Member<CSSPrimitiveValue>, kMaximumCacheableIntegerValue + 1>
+ HeapVector<Member<CSSNumericLiteralValue>, kMaximumCacheableIntegerValue + 1>
pixel_value_cache_;
- HeapVector<Member<CSSPrimitiveValue>, kMaximumCacheableIntegerValue + 1>
+ HeapVector<Member<CSSNumericLiteralValue>, kMaximumCacheableIntegerValue + 1>
percent_value_cache_;
- HeapVector<Member<CSSPrimitiveValue>, kMaximumCacheableIntegerValue + 1>
+ HeapVector<Member<CSSNumericLiteralValue>, kMaximumCacheableIntegerValue + 1>
number_value_cache_;
// Hash map caches.
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 70cabac0d48..7ec8b2dcb26 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
@@ -28,7 +28,8 @@ class CSSVariableReferenceValue : public CSSValue {
CSSVariableData* VariableDataValue() const { return data_.get(); }
const CSSParserContext* ParserContext() const {
- DCHECK(parser_context_);
+ // TODO(crbug.com/985028): CSSVariableReferenceValue should always have
+ // a CSSParserContext.
return parser_context_.Get();
}
diff --git a/chromium/third_party/blink/renderer/core/css/css_viewport_rule.idl b/chromium/third_party/blink/renderer/core/css/css_viewport_rule.idl
index 4c1894b5e35..26d84823c3c 100644
--- a/chromium/third_party/blink/renderer/core/css/css_viewport_rule.idl
+++ b/chromium/third_party/blink/renderer/core/css/css_viewport_rule.idl
@@ -30,7 +30,8 @@
// https://drafts.csswg.org/css-device-adapt/#css-viewport-rule-interface
[
- RuntimeEnabled=CSSViewport
+ RuntimeEnabled=CSSViewport,
+ Exposed=Window
] interface CSSViewportRule : CSSRule {
readonly attribute CSSStyleDeclaration style;
};
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 5ab80542479..2d11b32549f 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
@@ -8,6 +8,7 @@
#include "third_party/blink/renderer/core/css/css_custom_property_declaration.h"
#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_numeric_literal_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"
@@ -36,12 +37,12 @@ const CSSValue* ComputedTransformComponent(const TransformOperation& operation,
CSSFunctionValue* result = MakeGarbageCollected<CSSFunctionValue>(
operation.Is3DOperation() ? CSSValueID::kScale3d
: CSSValueID::kScale);
- result->Append(*CSSPrimitiveValue::Create(
+ result->Append(*CSSNumericLiteralValue::Create(
scale.X(), CSSPrimitiveValue::UnitType::kNumber));
- result->Append(*CSSPrimitiveValue::Create(
+ result->Append(*CSSNumericLiteralValue::Create(
scale.Y(), CSSPrimitiveValue::UnitType::kNumber));
if (operation.Is3DOperation()) {
- result->Append(*CSSPrimitiveValue::Create(
+ result->Append(*CSSNumericLiteralValue::Create(
scale.Z(), CSSPrimitiveValue::UnitType::kNumber));
}
return result;
@@ -55,10 +56,10 @@ const CSSValue* ComputedTransformComponent(const TransformOperation& operation,
CSSFunctionValue* result = MakeGarbageCollected<CSSFunctionValue>(
operation.Is3DOperation() ? CSSValueID::kTranslate3d
: CSSValueID::kTranslate);
- result->Append(*CSSPrimitiveValue::Create(translate.X(), zoom));
- result->Append(*CSSPrimitiveValue::Create(translate.Y(), zoom));
+ result->Append(*CSSPrimitiveValue::CreateFromLength(translate.X(), zoom));
+ result->Append(*CSSPrimitiveValue::CreateFromLength(translate.Y(), zoom));
if (operation.Is3DOperation()) {
- result->Append(*CSSPrimitiveValue::Create(
+ result->Append(*CSSNumericLiteralValue::Create(
translate.Z(), CSSPrimitiveValue::UnitType::kPixels));
}
return result;
@@ -69,13 +70,13 @@ const CSSValue* ComputedTransformComponent(const TransformOperation& operation,
const auto& rotate = ToRotateTransformOperation(operation);
CSSFunctionValue* result =
MakeGarbageCollected<CSSFunctionValue>(CSSValueID::kRotate3d);
- result->Append(*CSSPrimitiveValue::Create(
+ result->Append(*CSSNumericLiteralValue::Create(
rotate.X(), CSSPrimitiveValue::UnitType::kNumber));
- result->Append(*CSSPrimitiveValue::Create(
+ result->Append(*CSSNumericLiteralValue::Create(
rotate.Y(), CSSPrimitiveValue::UnitType::kNumber));
- result->Append(*CSSPrimitiveValue::Create(
+ result->Append(*CSSNumericLiteralValue::Create(
rotate.Z(), CSSPrimitiveValue::UnitType::kNumber));
- result->Append(*CSSPrimitiveValue::Create(
+ result->Append(*CSSNumericLiteralValue::Create(
rotate.Angle(), CSSPrimitiveValue::UnitType::kDegrees));
return result;
}
@@ -83,30 +84,30 @@ const CSSValue* ComputedTransformComponent(const TransformOperation& operation,
const auto& rotate = ToRotateTransformOperation(operation);
auto* result =
MakeGarbageCollected<CSSFunctionValue>(CSSValueID::kRotate);
- result->Append(*CSSPrimitiveValue::Create(
+ result->Append(*CSSNumericLiteralValue::Create(
rotate.Angle(), CSSPrimitiveValue::UnitType::kDegrees));
return result;
}
case TransformOperation::kSkewX: {
const auto& skew = ToSkewTransformOperation(operation);
auto* result = MakeGarbageCollected<CSSFunctionValue>(CSSValueID::kSkewX);
- result->Append(*CSSPrimitiveValue::Create(
+ result->Append(*CSSNumericLiteralValue::Create(
skew.AngleX(), CSSPrimitiveValue::UnitType::kDegrees));
return result;
}
case TransformOperation::kSkewY: {
const auto& skew = ToSkewTransformOperation(operation);
auto* result = MakeGarbageCollected<CSSFunctionValue>(CSSValueID::kSkewY);
- result->Append(*CSSPrimitiveValue::Create(
+ result->Append(*CSSNumericLiteralValue::Create(
skew.AngleY(), CSSPrimitiveValue::UnitType::kDegrees));
return result;
}
case TransformOperation::kSkew: {
const auto& skew = ToSkewTransformOperation(operation);
auto* result = MakeGarbageCollected<CSSFunctionValue>(CSSValueID::kSkew);
- result->Append(*CSSPrimitiveValue::Create(
+ result->Append(*CSSNumericLiteralValue::Create(
skew.AngleX(), CSSPrimitiveValue::UnitType::kDegrees));
- result->Append(*CSSPrimitiveValue::Create(
+ result->Append(*CSSNumericLiteralValue::Create(
skew.AngleY(), CSSPrimitiveValue::UnitType::kDegrees));
return result;
}
@@ -114,7 +115,7 @@ const CSSValue* ComputedTransformComponent(const TransformOperation& operation,
const auto& perspective = ToPerspectiveTransformOperation(operation);
auto* result =
MakeGarbageCollected<CSSFunctionValue>(CSSValueID::kPerspective);
- result->Append(*CSSPrimitiveValue::Create(
+ result->Append(*CSSNumericLiteralValue::Create(
perspective.Perspective(), CSSPrimitiveValue::UnitType::kPixels));
return result;
}
@@ -125,7 +126,7 @@ const CSSValue* ComputedTransformComponent(const TransformOperation& operation,
double values[6] = {matrix.A(), matrix.B(), matrix.C(),
matrix.D(), matrix.E(), matrix.F()};
for (double value : values) {
- result->Append(*CSSPrimitiveValue::Create(
+ result->Append(*CSSNumericLiteralValue::Create(
value, CSSPrimitiveValue::UnitType::kNumber));
}
return result;
@@ -140,7 +141,7 @@ const CSSValue* ComputedTransformComponent(const TransformOperation& operation,
matrix.M31(), matrix.M32(), matrix.M33(), matrix.M34(),
matrix.M41(), matrix.M42(), matrix.M43(), matrix.M44()};
for (double value : values) {
- result->Append(*CSSPrimitiveValue::Create(
+ result->Append(*CSSNumericLiteralValue::Create(
value, CSSPrimitiveValue::UnitType::kNumber));
}
return result;
@@ -188,12 +189,12 @@ bool ComputedStylePropertyMap::ComparePropertyNames(
AtomicString a = name_a.ToAtomicString();
AtomicString b = name_b.ToAtomicString();
if (a.StartsWith("--"))
- return b.StartsWith("--") && WTF::CodePointCompareLessThan(a, b);
+ return b.StartsWith("--") && WTF::CodeUnitCompareLessThan(a, b);
if (a.StartsWith("-")) {
return b.StartsWith("--") ||
- (b.StartsWith("-") && WTF::CodePointCompareLessThan(a, b));
+ (b.StartsWith("-") && WTF::CodeUnitCompareLessThan(a, b));
}
- return b.StartsWith("-") || WTF::CodePointCompareLessThan(a, b);
+ return b.StartsWith("-") || WTF::CodeUnitCompareLessThan(a, b);
}
Node* ComputedStylePropertyMap::StyledNode() const {
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/cross_thread_keyword_value.cc b/chromium/third_party/blink/renderer/core/css/cssom/cross_thread_keyword_value.cc
index aa2676bb554..94d6a0ab283 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/cross_thread_keyword_value.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/cross_thread_keyword_value.cc
@@ -9,7 +9,7 @@
namespace blink {
CSSStyleValue* CrossThreadKeywordValue::ToCSSStyleValue() {
- return CSSKeywordValue::Create(keyword_value_);
+ return CSSKeywordValue::Create(std::move(keyword_value_.IsolatedCopy()));
}
bool CrossThreadKeywordValue::operator==(
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/cross_thread_style_value_test.cc b/chromium/third_party/blink/renderer/core/css/cssom/cross_thread_style_value_test.cc
index 5e82245e922..2dc5f10d77b 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/cross_thread_style_value_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/cross_thread_style_value_test.cc
@@ -14,9 +14,9 @@
#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/css_unit_value.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/web_thread_supporting_gc.h"
+#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
namespace blink {
@@ -24,7 +24,6 @@ class CrossThreadStyleValueTest : public testing::Test {
public:
void ShutDown(base::WaitableEvent* waitable_event) {
DCHECK(!IsMainThread());
- thread_->ShutdownOnThread();
waitable_event->Signal();
}
@@ -42,7 +41,6 @@ class CrossThreadStyleValueTest : public testing::Test {
base::WaitableEvent* waitable_event,
std::unique_ptr<CrossThreadUnsupportedValue> value) {
DCHECK(!IsMainThread());
- thread_->InitializeOnThread();
EXPECT_EQ(value->value_, "Unsupported");
waitable_event->Signal();
@@ -51,7 +49,6 @@ class CrossThreadStyleValueTest : public testing::Test {
void CheckKeywordValue(base::WaitableEvent* waitable_event,
std::unique_ptr<CrossThreadKeywordValue> value) {
DCHECK(!IsMainThread());
- thread_->InitializeOnThread();
EXPECT_EQ(value->keyword_value_, "Keyword");
waitable_event->Signal();
@@ -60,7 +57,6 @@ class CrossThreadStyleValueTest : public testing::Test {
void CheckUnitValue(base::WaitableEvent* waitable_event,
std::unique_ptr<CrossThreadUnitValue> value) {
DCHECK(!IsMainThread());
- thread_->InitializeOnThread();
EXPECT_EQ(value->value_, 1);
EXPECT_EQ(value->unit_, CSSPrimitiveValue::UnitType::kDegrees);
@@ -68,7 +64,7 @@ class CrossThreadStyleValueTest : public testing::Test {
}
protected:
- std::unique_ptr<WebThreadSupportingGC> thread_;
+ std::unique_ptr<blink::Thread> thread_;
};
// Ensure that a CrossThreadUnsupportedValue can be safely passed cross
@@ -78,9 +74,9 @@ TEST_F(CrossThreadStyleValueTest, PassUnsupportedValueCrossThread) {
std::make_unique<CrossThreadUnsupportedValue>("Unsupported");
DCHECK(value);
- // Use a WebThreadSupportingGC to emulate worklet thread.
- thread_ = std::make_unique<WebThreadSupportingGC>(
- ThreadCreationParams(WebThreadType::kTestThread));
+ // Use a Thread to emulate worklet thread.
+ thread_ = blink::Thread::CreateThread(
+ ThreadCreationParams(WebThreadType::kTestThread).SetSupportsGC(true));
base::WaitableEvent waitable_event;
PostCrossThreadTask(
*thread_->GetTaskRunner(), FROM_HERE,
@@ -109,9 +105,9 @@ TEST_F(CrossThreadStyleValueTest, PassKeywordValueCrossThread) {
std::make_unique<CrossThreadKeywordValue>("Keyword");
DCHECK(value);
- // Use a WebThreadSupportingGC to emulate worklet thread.
- thread_ = std::make_unique<WebThreadSupportingGC>(
- ThreadCreationParams(WebThreadType::kTestThread));
+ // Use a Thread to emulate worklet thread.
+ thread_ = blink::Thread::CreateThread(
+ ThreadCreationParams(WebThreadType::kTestThread).SetSupportsGC(true));
base::WaitableEvent waitable_event;
PostCrossThreadTask(
*thread_->GetTaskRunner(), FROM_HERE,
@@ -141,9 +137,9 @@ TEST_F(CrossThreadStyleValueTest, PassUnitValueCrossThread) {
1, CSSPrimitiveValue::UnitType::kDegrees);
DCHECK(value);
- // Use a WebThreadSupportingGC to emulate worklet thread.
- thread_ = std::make_unique<WebThreadSupportingGC>(
- ThreadCreationParams(WebThreadType::kTestThread));
+ // Use a Thread to emulate worklet thread.
+ thread_ = blink::Thread::CreateThread(
+ ThreadCreationParams(WebThreadType::kTestThread).SetSupportsGC(true));
base::WaitableEvent waitable_event;
PostCrossThreadTask(
*thread_->GetTaskRunner(), FROM_HERE,
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/cross_thread_unsupported_value.cc b/chromium/third_party/blink/renderer/core/css/cssom/cross_thread_unsupported_value.cc
index 6a258650711..657fc347847 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/cross_thread_unsupported_value.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/cross_thread_unsupported_value.cc
@@ -9,7 +9,7 @@
namespace blink {
CSSStyleValue* CrossThreadUnsupportedValue::ToCSSStyleValue() {
- return CSSUnsupportedStyleValue::Create(value_);
+ return CSSUnsupportedStyleValue::Create(std::move(value_.IsolatedCopy()));
}
bool CrossThreadUnsupportedValue::operator==(
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 134df106c0d..23816cd17c3 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
@@ -53,7 +53,7 @@ class CORE_EXPORT CSSMathInvert : public CSSMathValue {
return value_->Equals(*other_invert.value_);
}
- CSSCalcExpressionNode* ToCalcExpressionNode() const final {
+ CSSMathExpressionNode* ToCalcExpressionNode() const final {
// TODO(crbug.com/782103): Implement.
return nullptr;
}
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 c307520d1ee..3124a12d14b 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
@@ -30,7 +30,7 @@ class CORE_EXPORT CSSMathMax final : public CSSMathVariadic {
// From CSSStyleValue.
StyleValueType GetType() const final { return CSSStyleValue::kMaxType; }
- CSSCalcExpressionNode* ToCalcExpressionNode() const final {
+ CSSMathExpressionNode* ToCalcExpressionNode() const final {
// TODO(crbug.com/): Implement
return nullptr;
}
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 6f7dbdb6b6e..f5bdd4d3842 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
@@ -32,7 +32,7 @@ class CORE_EXPORT CSSMathMin final : public CSSMathVariadic {
// From CSSStyleValue.
StyleValueType GetType() const final { return CSSStyleValue::kMinType; }
- CSSCalcExpressionNode* ToCalcExpressionNode() const final {
+ CSSMathExpressionNode* ToCalcExpressionNode() const final {
// TODO(crbug.com/): Implement
return nullptr;
}
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 b80022290f5..977a7cd7b7d 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
@@ -52,7 +52,7 @@ class CORE_EXPORT CSSMathNegate : public CSSMathValue {
return value_->Equals(*other_negate.value_);
}
- CSSCalcExpressionNode* ToCalcExpressionNode() const final {
+ CSSMathExpressionNode* ToCalcExpressionNode() const final {
// TODO(crbug.com/xxx): Implement
return nullptr;
}
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 39f7bb92980..371dc2fed10 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
@@ -4,7 +4,7 @@
#include "third_party/blink/renderer/core/css/cssom/css_math_product.h"
-#include "third_party/blink/renderer/core/css/css_calculation_value.h"
+#include "third_party/blink/renderer/core/css/css_math_expression_node.h"
#include "third_party/blink/renderer/core/css/cssom/css_math_invert.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
@@ -81,18 +81,19 @@ base::Optional<CSSNumericSumValue> CSSMathProduct::SumValue() const {
return sum;
}
-CSSCalcExpressionNode* CSSMathProduct::ToCalcExpressionNode() const {
+CSSMathExpressionNode* CSSMathProduct::ToCalcExpressionNode() const {
// TODO(crbug.com/782103): Handle the single value case correctly.
if (NumericValues().size() == 1)
return NumericValues()[0]->ToCalcExpressionNode();
- CSSCalcExpressionNode* node = CSSCalcValue::CreateExpressionNode(
+ CSSMathExpressionNode* node = CSSMathExpressionBinaryOperation::Create(
NumericValues()[0]->ToCalcExpressionNode(),
- NumericValues()[1]->ToCalcExpressionNode(), kCalcMultiply);
+ NumericValues()[1]->ToCalcExpressionNode(), CSSMathOperator::kMultiply);
for (wtf_size_t i = 2; i < NumericValues().size(); i++) {
- node = CSSCalcValue::CreateExpressionNode(
- node, NumericValues()[i]->ToCalcExpressionNode(), kCalcMultiply);
+ node = CSSMathExpressionBinaryOperation::Create(
+ node, NumericValues()[i]->ToCalcExpressionNode(),
+ CSSMathOperator::kMultiply);
}
return node;
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 f0b32102198..e8f8f1932e6 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
@@ -30,7 +30,7 @@ class CORE_EXPORT CSSMathProduct final : public CSSMathVariadic {
// From CSSStyleValue.
StyleValueType GetType() const final { return CSSStyleValue::kProductType; }
- CSSCalcExpressionNode* ToCalcExpressionNode() const final;
+ CSSMathExpressionNode* ToCalcExpressionNode() const final;
private:
void BuildCSSText(Nested, ParenLess, StringBuilder&) 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 06327d17878..7ff6763053b 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
@@ -4,7 +4,7 @@
#include "third_party/blink/renderer/core/css/cssom/css_math_sum.h"
-#include "third_party/blink/renderer/core/css/css_calculation_value.h"
+#include "third_party/blink/renderer/core/css/css_math_expression_node.h"
#include "third_party/blink/renderer/core/css/cssom/css_math_negate.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
@@ -99,18 +99,19 @@ base::Optional<CSSNumericSumValue> CSSMathSum::SumValue() const {
return sum;
}
-CSSCalcExpressionNode* CSSMathSum::ToCalcExpressionNode() const {
+CSSMathExpressionNode* CSSMathSum::ToCalcExpressionNode() const {
// TODO(crbug.com/782103): Handle the single value case correctly.
if (NumericValues().size() == 1)
return NumericValues()[0]->ToCalcExpressionNode();
- CSSCalcExpressionNode* node = CSSCalcValue::CreateExpressionNode(
+ CSSMathExpressionNode* node = CSSMathExpressionBinaryOperation::Create(
NumericValues()[0]->ToCalcExpressionNode(),
- NumericValues()[1]->ToCalcExpressionNode(), kCalcAdd);
+ NumericValues()[1]->ToCalcExpressionNode(), CSSMathOperator::kAdd);
for (wtf_size_t i = 2; i < NumericValues().size(); i++) {
- node = CSSCalcValue::CreateExpressionNode(
- node, NumericValues()[i]->ToCalcExpressionNode(), kCalcAdd);
+ node = CSSMathExpressionBinaryOperation::Create(
+ node, NumericValues()[i]->ToCalcExpressionNode(),
+ CSSMathOperator::kAdd);
}
return node;
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 0ff1d04455b..8bdb4a3f5d9 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
@@ -30,7 +30,7 @@ class CORE_EXPORT CSSMathSum final : public CSSMathVariadic {
// From CSSStyleValue.
StyleValueType GetType() const final { return CSSStyleValue::kSumType; }
- CSSCalcExpressionNode* ToCalcExpressionNode() const final;
+ CSSMathExpressionNode* ToCalcExpressionNode() const final;
private:
void BuildCSSText(Nested, ParenLess, StringBuilder&) const final;
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_math_value.cc b/chromium/third_party/blink/renderer/core/css/cssom/css_math_value.cc
index 633fbbfa863..314c2c266dd 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_math_value.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_math_value.cc
@@ -4,15 +4,16 @@
#include "third_party/blink/renderer/core/css/cssom/css_math_value.h"
-#include "third_party/blink/renderer/core/css/css_calculation_value.h"
+#include "third_party/blink/renderer/core/css/css_math_expression_node.h"
+#include "third_party/blink/renderer/core/css/css_math_function_value.h"
namespace blink {
const CSSValue* CSSMathValue::ToCSSValue() const {
- CSSCalcExpressionNode* node = ToCalcExpressionNode();
+ CSSMathExpressionNode* node = ToCalcExpressionNode();
if (!node)
return nullptr;
- return CSSPrimitiveValue::Create(CSSCalcValue::Create(node));
+ return CSSMathFunctionValue::Create(node);
}
} // namespace blink
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 1137dafa0dd..d6545b6621c 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
@@ -4,6 +4,7 @@
#include "third_party/blink/renderer/core/css/cssom/css_matrix_component.h"
+#include "third_party/blink/renderer/core/css/css_numeric_literal_value.h"
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
#include "third_party/blink/renderer/core/css/cssom/css_matrix_component_options.h"
#include "third_party/blink/renderer/core/geometry/dom_matrix.h"
@@ -58,7 +59,7 @@ const CSSFunctionValue* CSSMatrixComponent::ToCSSValue() const {
double values[6] = {matrix_->a(), matrix_->b(), matrix_->c(),
matrix_->d(), matrix_->e(), matrix_->f()};
for (double value : values) {
- result->Append(*CSSPrimitiveValue::Create(
+ result->Append(*CSSNumericLiteralValue::Create(
value, CSSPrimitiveValue::UnitType::kNumber));
}
} else {
@@ -68,7 +69,7 @@ const CSSFunctionValue* CSSMatrixComponent::ToCSSValue() const {
matrix_->m31(), matrix_->m32(), matrix_->m33(), matrix_->m34(),
matrix_->m41(), matrix_->m42(), matrix_->m43(), matrix_->m44()};
for (double value : values) {
- result->Append(*CSSPrimitiveValue::Create(
+ result->Append(*CSSNumericLiteralValue::Create(
value, CSSPrimitiveValue::UnitType::kNumber));
}
}
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 a883fe0b67d..3b798630cc8 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
@@ -6,7 +6,8 @@
#include <numeric>
-#include "third_party/blink/renderer/core/css/css_calculation_value.h"
+#include "third_party/blink/renderer/core/css/css_math_expression_node.h"
+#include "third_party/blink/renderer/core/css/css_math_function_value.h"
#include "third_party/blink/renderer/core/css/css_primitive_value.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"
@@ -79,34 +80,38 @@ CSSUnitValue* MaybeMultiplyAsUnitValue(const CSSNumericValueVector& values) {
return CSSUnitValue::Create(final_value, unit_other_than_number);
}
-CalcOperator CanonicalOperator(CalcOperator op) {
- if (op == kCalcAdd || op == kCalcSubtract)
- return kCalcAdd;
- return kCalcMultiply;
+CSSMathOperator CanonicalOperator(CSSMathOperator op) {
+ if (op == CSSMathOperator::kAdd || op == CSSMathOperator::kSubtract)
+ return CSSMathOperator::kAdd;
+ return CSSMathOperator::kMultiply;
}
-bool CanCombineNodes(const CSSCalcExpressionNode& root,
- const CSSCalcExpressionNode& node) {
- DCHECK_EQ(root.GetType(), CSSCalcExpressionNode::kCssCalcBinaryOperation);
- if (node.GetType() == CSSCalcExpressionNode::kCssCalcPrimitiveValue)
+bool CanCombineNodes(const CSSMathExpressionNode& root,
+ const CSSMathExpressionNode& node) {
+ DCHECK(root.IsBinaryOperation());
+ if (!node.IsBinaryOperation())
return false;
- return !node.IsNestedCalc() && CanonicalOperator(root.OperatorType()) ==
- CanonicalOperator(node.OperatorType());
+ if (node.IsNestedCalc())
+ return false;
+ return CanonicalOperator(
+ To<CSSMathExpressionBinaryOperation>(root).OperatorType()) ==
+ CanonicalOperator(
+ To<CSSMathExpressionBinaryOperation>(node).OperatorType());
}
-CSSNumericValue* NegateOrInvertIfRequired(CalcOperator parent_op,
+CSSNumericValue* NegateOrInvertIfRequired(CSSMathOperator parent_op,
CSSNumericValue* value) {
DCHECK(value);
- if (parent_op == kCalcSubtract)
+ if (parent_op == CSSMathOperator::kSubtract)
return CSSMathNegate::Create(value);
- if (parent_op == kCalcDivide)
+ if (parent_op == CSSMathOperator::kDivide)
return CSSMathInvert::Create(value);
return value;
}
-CSSNumericValue* CalcToNumericValue(const CSSCalcExpressionNode& root) {
- if (root.GetType() == CSSCalcExpressionNode::kCssCalcPrimitiveValue) {
- const CSSPrimitiveValue::UnitType unit = root.TypeWithCalcResolved();
+CSSNumericValue* CalcToNumericValue(const CSSMathExpressionNode& root) {
+ if (root.IsNumericLiteral()) {
+ const CSSPrimitiveValue::UnitType unit = root.ResolvedUnitType();
auto* value = CSSUnitValue::Create(
root.DoubleValue(), unit == CSSPrimitiveValue::UnitType::kInteger
? CSSPrimitiveValue::UnitType::kNumber
@@ -124,7 +129,7 @@ CSSNumericValue* CalcToNumericValue(const CSSCalcExpressionNode& root) {
// When the node is a binary operator, we return either a CSSMathSum or a
// CSSMathProduct.
- DCHECK_EQ(root.GetType(), CSSCalcExpressionNode::kCssCalcBinaryOperation);
+ DCHECK(root.IsBinaryOperation());
CSSNumericValueVector values;
// For cases like calc(1 + 2 + 3), the calc expression tree looks like:
@@ -143,17 +148,21 @@ CSSNumericValue* CalcToNumericValue(const CSSCalcExpressionNode& root) {
// the two nodes. We keep moving down the left side of the tree as long as the
// current node and the root can be combined, collecting the right child of
// the nodes that we encounter.
- const CSSCalcExpressionNode* cur_node = &root;
+ const CSSMathExpressionNode* cur_node = &root;
do {
- DCHECK(cur_node->LeftExpressionNode());
- DCHECK(cur_node->RightExpressionNode());
+ DCHECK(cur_node->IsBinaryOperation());
+ const CSSMathExpressionBinaryOperation* binary_op =
+ To<CSSMathExpressionBinaryOperation>(cur_node);
+ DCHECK(binary_op->LeftExpressionNode());
+ DCHECK(binary_op->RightExpressionNode());
- auto* const value = CalcToNumericValue(*cur_node->RightExpressionNode());
+ auto* const value = CalcToNumericValue(*binary_op->RightExpressionNode());
// If the current node is a '-' or '/', it's really just a '+' or '*' with
// the right child negated or inverted, respectively.
- values.push_back(NegateOrInvertIfRequired(cur_node->OperatorType(), value));
- cur_node = cur_node->LeftExpressionNode();
+ values.push_back(
+ NegateOrInvertIfRequired(binary_op->OperatorType(), value));
+ cur_node = binary_op->LeftExpressionNode();
} while (CanCombineNodes(root, *cur_node));
DCHECK(cur_node);
@@ -162,7 +171,10 @@ CSSNumericValue* CalcToNumericValue(const CSSCalcExpressionNode& root) {
// Our algorithm collects the children in reverse order, so we have to reverse
// the values.
std::reverse(values.begin(), values.end());
- if (root.OperatorType() == kCalcAdd || root.OperatorType() == kCalcSubtract)
+ CSSMathOperator operator_type =
+ To<CSSMathExpressionBinaryOperation>(root).OperatorType();
+ if (operator_type == CSSMathOperator::kAdd ||
+ operator_type == CSSMathOperator::kSubtract)
return CSSMathSum::Create(std::move(values));
return CSSMathProduct::Create(std::move(values));
}
@@ -226,12 +238,11 @@ CSSNumericValue* CSSNumericValue::parse(const String& css_text,
case kFunctionToken:
if (range.Peek().FunctionId() == CSSValueID::kCalc ||
range.Peek().FunctionId() == CSSValueID::kWebkitCalc) {
- CSSCalcValue* calc_value = CSSCalcValue::Create(range, kValueRangeAll);
- if (!calc_value)
+ CSSMathExpressionNode* expression =
+ CSSMathExpressionNode::ParseCalc(range);
+ if (!expression)
break;
-
- DCHECK(calc_value->ExpressionNode());
- return CalcToNumericValue(*calc_value->ExpressionNode());
+ return CalcToNumericValue(*expression);
}
break;
default:
@@ -244,9 +255,11 @@ CSSNumericValue* CSSNumericValue::parse(const String& css_text,
}
CSSNumericValue* CSSNumericValue::FromCSSValue(const CSSPrimitiveValue& value) {
- if (value.IsCalculated())
- return CalcToNumericValue(*value.CssCalcValue()->ExpressionNode());
- return CSSUnitValue::FromCSSValue(value);
+ if (value.IsCalculated()) {
+ return CalcToNumericValue(
+ *To<CSSMathFunctionValue>(value).ExpressionNode());
+ }
+ return CSSUnitValue::FromCSSValue(To<CSSNumericLiteralValue>(value));
}
/* static */
@@ -315,8 +328,8 @@ CSSMathSum* CSSNumericValue::toSum(const Vector<String>& unit_strings,
if (unit_strings.size() == 0) {
std::sort(values.begin(), values.end(), [](const auto& a, const auto& b) {
- return WTF::CodePointCompareLessThan(To<CSSUnitValue>(a.Get())->unit(),
- To<CSSUnitValue>(b.Get())->unit());
+ return WTF::CodeUnitCompareLessThan(To<CSSUnitValue>(a.Get())->unit(),
+ To<CSSUnitValue>(b.Get())->unit());
});
// We got 'values' from a sum value, so it must be a valid CSSMathSum.
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 ecdd7bfd4e9..066261868cd 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
@@ -20,7 +20,7 @@ namespace blink {
class CSSUnitValue;
class ExceptionState;
-class CSSCalcExpressionNode;
+class CSSMathExpressionNode;
class CSSNumericValue;
class CSSMathSum;
@@ -67,7 +67,7 @@ class CORE_EXPORT CSSNumericValue : public CSSStyleValue {
virtual bool Equals(const CSSNumericValue&) const = 0;
const CSSNumericValueType& Type() const { return type_; }
- virtual CSSCalcExpressionNode* ToCalcExpressionNode() const = 0;
+ virtual CSSMathExpressionNode* ToCalcExpressionNode() const = 0;
enum class Nested : bool { kYes, kNo };
enum class ParenLess : bool { kYes, kNo };
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_numeric_value_type.cc b/chromium/third_party/blink/renderer/core/css/cssom/css_numeric_value_type.cc
index f41117d4fc5..288714653e4 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_numeric_value_type.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_numeric_value_type.cc
@@ -86,12 +86,14 @@ AtomicString CSSNumericValueType::BaseTypeToString(BaseType base_type) {
}
CSSNumericValueType::CSSNumericValueType(CSSPrimitiveValue::UnitType unit) {
+ exponents_.Fill(0, kNumBaseTypes);
if (unit != CSSPrimitiveValue::UnitType::kNumber)
SetExponent(UnitTypeToBaseType(unit), 1);
}
CSSNumericValueType::CSSNumericValueType(int exponent,
CSSPrimitiveValue::UnitType unit) {
+ exponents_.Fill(0, kNumBaseTypes);
if (unit != CSSPrimitiveValue::UnitType::kNumber)
SetExponent(UnitTypeToBaseType(unit), exponent);
}
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_numeric_value_type.h b/chromium/third_party/blink/renderer/core/css/cssom/css_numeric_value_type.h
index 886f1a916cb..42c0311baba 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_numeric_value_type.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_numeric_value_type.h
@@ -7,8 +7,6 @@
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
-#include <array>
-
namespace blink {
// Represents the type of a CSSNumericValue, which is a map of base types to
@@ -93,7 +91,7 @@ class CORE_EXPORT CSSNumericValueType {
return num_non_zero_entries_ == 1 && Exponent(base_type) == value;
}
- std::array<int, kNumBaseTypes> exponents_{}; // zero-initialize
+ Vector<int, kNumBaseTypes> exponents_;
BaseType percent_hint_ = BaseType::kPercent;
bool has_percent_hint_ = false;
unsigned num_non_zero_entries_ = 0;
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 3dacfe9d71a..019f9b84c8e 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
@@ -4,7 +4,8 @@
#include "third_party/blink/renderer/core/css/cssom/css_perspective.h"
-#include "third_party/blink/renderer/core/css/css_calculation_value.h"
+#include "third_party/blink/renderer/core/css/css_math_expression_node.h"
+#include "third_party/blink/renderer/core/css/css_math_function_value.h"
#include "third_party/blink/renderer/core/css/cssom/css_unit_value.h"
#include "third_party/blink/renderer/core/geometry/dom_matrix.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
@@ -67,9 +68,9 @@ const CSSFunctionValue* CSSPerspective::ToCSSValue() const {
const CSSValue* length = nullptr;
if (length_->IsUnitValue() && To<CSSUnitValue>(length_.Get())->value() < 0) {
// Wrap out of range length with a calc.
- CSSCalcExpressionNode* node = length_->ToCalcExpressionNode();
+ CSSMathExpressionNode* node = length_->ToCalcExpressionNode();
node->SetIsNestedCalc();
- length = CSSPrimitiveValue::Create(CSSCalcValue::Create(node));
+ length = CSSMathFunctionValue::Create(node);
} else {
length = length_->ToCSSValue();
}
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/css_style_value.cc b/chromium/third_party/blink/renderer/core/css/cssom/css_style_value.cc
index cdf051c7517..53dd6b1c279 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/css_style_value.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/css_style_value.cc
@@ -9,7 +9,6 @@
#include "third_party/blink/renderer/core/css/cssom/style_value_factory.h"
#include "third_party/blink/renderer/core/css/parser/css_parser_context.h"
#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/style_property_shorthand.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
@@ -35,14 +34,8 @@ CSSStyleValueVector ParseCSSStyleValue(
AtomicString custom_property_name = property_id == CSSPropertyID::kVariable
? AtomicString(property_name)
: g_null_atom;
-
- const PropertyRegistration* registration =
- (property_id == CSSPropertyID::kVariable)
- ? PropertyRegistration::From(execution_context, custom_property_name)
- : nullptr;
-
const auto style_values = StyleValueFactory::FromString(
- property_id, custom_property_name, registration, value,
+ property_id, custom_property_name, value,
MakeGarbageCollected<CSSParserContext>(*execution_context));
if (style_values.IsEmpty()) {
exception_state.ThrowTypeError("The value provided ('" + value +
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 6bba2d8fff5..e11cb7e100b 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
@@ -15,7 +15,6 @@
namespace blink {
-class CSSSyntaxComponent;
class ExceptionState;
class ExecutionContext;
enum class SecureContextMode;
@@ -66,9 +65,7 @@ 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 CSSSyntaxComponent*) const {
+ virtual const CSSValue* ToCSSValueWithProperty(CSSPropertyID) const {
return ToCSSValue();
}
virtual String toString() const;
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 608ecd94327..cc568a2a7ed 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
@@ -5,7 +5,9 @@
#include "third_party/blink/renderer/core/css/cssom/css_unit_value.h"
#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_math_expression_node.h"
+#include "third_party/blink/renderer/core/css/css_math_function_value.h"
+#include "third_party/blink/renderer/core/css/css_numeric_literal_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"
@@ -38,8 +40,7 @@ CSSPrimitiveValue::UnitType ToCanonicalUnitIfPossible(
bool IsValueOutOfRangeForProperty(CSSPropertyID property_id,
double value,
- CSSPrimitiveValue::UnitType unit,
- const CSSSyntaxComponent* match) {
+ CSSPrimitiveValue::UnitType unit) {
// 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)) ==
@@ -49,10 +50,6 @@ bool IsValueOutOfRangeForProperty(CSSPropertyID property_id,
// For non-length properties and special cases.
switch (property_id) {
- case CSSPropertyID::kVariable:
- if (match && match->IsInteger())
- return round(value) != value;
- return false;
case CSSPropertyID::kOrder:
case CSSPropertyID::kZIndex:
return round(value) != value;
@@ -106,8 +103,8 @@ CSSUnitValue* CSSUnitValue::Create(double value,
return MakeGarbageCollected<CSSUnitValue>(value, unit);
}
-CSSUnitValue* CSSUnitValue::FromCSSValue(const CSSPrimitiveValue& value) {
- CSSPrimitiveValue::UnitType unit = value.TypeWithCalcResolved();
+CSSUnitValue* CSSUnitValue::FromCSSValue(const CSSNumericLiteralValue& value) {
+ CSSPrimitiveValue::UnitType unit = value.GetType();
if (unit == CSSPrimitiveValue::UnitType::kInteger)
unit = CSSPrimitiveValue::UnitType::kNumber;
@@ -168,26 +165,25 @@ bool CSSUnitValue::Equals(const CSSNumericValue& other) const {
return value_ == other_unit_value->value_ && unit_ == other_unit_value->unit_;
}
-const CSSPrimitiveValue* CSSUnitValue::ToCSSValue() const {
- return CSSPrimitiveValue::Create(value_, unit_);
+const CSSNumericLiteralValue* CSSUnitValue::ToCSSValue() const {
+ return CSSNumericLiteralValue::Create(value_, unit_);
}
const CSSPrimitiveValue* CSSUnitValue::ToCSSValueWithProperty(
- CSSPropertyID property_id,
- const CSSSyntaxComponent* match) const {
- if (IsValueOutOfRangeForProperty(property_id, value_, unit_, match)) {
+ CSSPropertyID property_id) const {
+ if (IsValueOutOfRangeForProperty(property_id, value_, unit_)) {
// Wrap out of range values with a calc.
- CSSCalcExpressionNode* node = ToCalcExpressionNode();
+ CSSMathExpressionNode* node = ToCalcExpressionNode();
node->SetIsNestedCalc();
- return CSSPrimitiveValue::Create(CSSCalcValue::Create(node));
+ return CSSMathFunctionValue::Create(node);
}
- return CSSPrimitiveValue::Create(value_, unit_);
+ return CSSNumericLiteralValue::Create(value_, unit_);
}
-CSSCalcExpressionNode* CSSUnitValue::ToCalcExpressionNode() const {
- return CSSCalcValue::CreateExpressionNode(
- CSSPrimitiveValue::Create(value_, unit_));
+CSSMathExpressionNode* CSSUnitValue::ToCalcExpressionNode() const {
+ return CSSMathExpressionNumericLiteral::Create(
+ CSSNumericLiteralValue::Create(value_, unit_));
}
CSSNumericValue* CSSUnitValue::Negate() {
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 05b89506125..268f79d11fb 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
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSSOM_CSS_UNIT_VALUE_H_
#include "base/macros.h"
-#include "third_party/blink/renderer/core/css/css_primitive_value.h"
+#include "third_party/blink/renderer/core/css/css_numeric_literal_value.h"
#include "third_party/blink/renderer/core/css/cssom/css_numeric_value.h"
#include "third_party/blink/renderer/platform/wtf/casting.h"
@@ -27,7 +27,7 @@ class CORE_EXPORT CSSUnitValue final : public CSSNumericValue {
static CSSUnitValue* Create(
double value,
CSSPrimitiveValue::UnitType = CSSPrimitiveValue::UnitType::kNumber);
- static CSSUnitValue* FromCSSValue(const CSSPrimitiveValue&);
+ static CSSUnitValue* FromCSSValue(const CSSNumericLiteralValue&);
CSSUnitValue(double value, CSSPrimitiveValue::UnitType unit)
: CSSNumericValue(CSSNumericValueType(unit)),
@@ -51,11 +51,9 @@ class CORE_EXPORT CSSUnitValue final : public CSSNumericValue {
// From CSSStyleValue.
StyleValueType GetType() const final;
- const CSSPrimitiveValue* ToCSSValue() const final;
- const CSSPrimitiveValue* ToCSSValueWithProperty(
- CSSPropertyID,
- const CSSSyntaxComponent*) const final;
- CSSCalcExpressionNode* ToCalcExpressionNode() const final;
+ const CSSNumericLiteralValue* ToCSSValue() const final;
+ const CSSPrimitiveValue* ToCSSValueWithProperty(CSSPropertyID) const final;
+ CSSMathExpressionNode* ToCalcExpressionNode() const final;
private:
double ConvertFixedLength(CSSPrimitiveValue::UnitType) const;
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 97005aba840..922cd34ec61 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
@@ -5,34 +5,11 @@
#include "third_party/blink/renderer/core/css/cssom/css_url_image_value.h"
#include "third_party/blink/renderer/core/css/css_image_value.h"
-#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/loader/resource/image_resource_content.h"
#include "third_party/blink/renderer/core/style/style_image.h"
-#include "third_party/blink/renderer/platform/bindings/exception_state.h"
-#include "third_party/blink/renderer/platform/bindings/script_state.h"
namespace blink {
-CSSURLImageValue* CSSURLImageValue::Create(ScriptState* script_state,
- const AtomicString& url,
- ExceptionState& exception_state) {
- const auto* execution_context = ExecutionContext::From(script_state);
- DCHECK(execution_context);
- KURL parsed_url = execution_context->CompleteURL(url);
- if (!parsed_url.IsValid()) {
- exception_state.ThrowTypeError("Failed to parse URL from " + url);
- return nullptr;
- }
- // Use absolute URL for CSSImageValue but keep relative URL for
- // getter and serialization.
- return MakeGarbageCollected<CSSURLImageValue>(
- *CSSImageValue::Create(url, parsed_url, Referrer()));
-}
-
-CSSURLImageValue* CSSURLImageValue::FromCSSValue(const CSSImageValue& value) {
- return MakeGarbageCollected<CSSURLImageValue>(value);
-}
-
const String& CSSURLImageValue::url() const {
return value_->RelativeUrl();
}
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 9635cb30954..f8ca0aa20d8 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
@@ -10,17 +10,10 @@
namespace blink {
-class ScriptState;
class CSSImageValue;
class CORE_EXPORT CSSURLImageValue final : public CSSStyleImageValue {
public:
- static CSSURLImageValue* Create(ScriptState*,
- const AtomicString& url,
- ExceptionState&);
-
- static CSSURLImageValue* FromCSSValue(const CSSImageValue&);
-
explicit CSSURLImageValue(const CSSImageValue& value) : value_(value) {}
const String& url() const;
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 86bd5e28f91..067e42f75f6 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
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSSOM_CSSOM_KEYWORDS_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/allocator/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 d43ebea52f2..ba88a991556 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
@@ -7,12 +7,10 @@
#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/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
-class PropertyRegistration;
-
// This class provides utility functions for determining whether a property
// can accept a CSSStyleValue type or instance. Its implementation is generated
// using input from css_properties.json5 and the script
@@ -33,15 +31,9 @@ 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 CSSSyntaxComponent*& match);
+ const CSSStyleValue&);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/paint_worklet_input.cc b/chromium/third_party/blink/renderer/core/css/cssom/paint_worklet_input.cc
index 15cf35c5d1b..4c52ae986bf 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/paint_worklet_input.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/paint_worklet_input.cc
@@ -13,11 +13,13 @@ PaintWorkletInput::PaintWorkletInput(
const FloatSize& container_size,
float effective_zoom,
int worklet_id,
- PaintWorkletStylePropertyMap::CrossThreadData data)
+ PaintWorkletStylePropertyMap::CrossThreadData data,
+ Vector<std::unique_ptr<CrossThreadStyleValue>> parsed_input_arguments)
: name_(name.IsolatedCopy()),
container_size_(container_size),
effective_zoom_(effective_zoom),
worklet_id_(worklet_id),
- style_map_data_(std::move(data)) {}
+ style_map_data_(std::move(data)),
+ parsed_input_arguments_(std::move(parsed_input_arguments)) {}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/paint_worklet_input.h b/chromium/third_party/blink/renderer/core/css/cssom/paint_worklet_input.h
index 645f4d52637..5e2f9ab8d57 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/paint_worklet_input.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/paint_worklet_input.h
@@ -36,11 +36,13 @@ namespace blink {
// contains will die.
class CORE_EXPORT PaintWorkletInput : public cc::PaintWorkletInput {
public:
- PaintWorkletInput(const String& name,
- const FloatSize& container_size,
- float effective_zoom,
- int worklet_id,
- PaintWorkletStylePropertyMap::CrossThreadData values);
+ PaintWorkletInput(
+ const String& name,
+ const FloatSize& container_size,
+ float effective_zoom,
+ int worklet_id,
+ PaintWorkletStylePropertyMap::CrossThreadData values,
+ Vector<std::unique_ptr<CrossThreadStyleValue>> parsed_input_args);
~PaintWorkletInput() override = default;
@@ -53,10 +55,14 @@ class CORE_EXPORT PaintWorkletInput : public cc::PaintWorkletInput {
// These accessors are safe on any thread.
const FloatSize& ContainerSize() const { return container_size_; }
float EffectiveZoom() const { return effective_zoom_; }
+ const Vector<std::unique_ptr<CrossThreadStyleValue>>& ParsedInputArguments()
+ const {
+ return parsed_input_arguments_;
+ }
// These should only be accessed on the PaintWorklet thread.
String NameCopy() const { return name_.IsolatedCopy(); }
- PaintWorkletStylePropertyMap::CrossThreadData StyleMapData() {
+ PaintWorkletStylePropertyMap::CrossThreadData StyleMapData() const {
return PaintWorkletStylePropertyMap::CopyCrossThreadData(style_map_data_);
}
@@ -66,6 +72,7 @@ class CORE_EXPORT PaintWorkletInput : public cc::PaintWorkletInput {
const float effective_zoom_;
const int worklet_id_;
PaintWorkletStylePropertyMap::CrossThreadData style_map_data_;
+ Vector<std::unique_ptr<CrossThreadStyleValue>> parsed_input_arguments_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/paint_worklet_style_property_map.cc b/chromium/third_party/blink/renderer/core/css/cssom/paint_worklet_style_property_map.cc
index 34ac1b49ab6..a90eb46fa93 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/paint_worklet_style_property_map.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/paint_worklet_style_property_map.cc
@@ -54,7 +54,7 @@ class PaintWorkletStylePropertyMapIterationSource final
const HeapVector<PaintWorkletStylePropertyMap::StylePropertyMapEntry> values_;
};
-void BuildNativeValues(const ComputedStyle& style,
+bool BuildNativeValues(const ComputedStyle& style,
Node* styled_node,
const Vector<CSSPropertyID>& native_properties,
PaintWorkletStylePropertyMap::CrossThreadData& data) {
@@ -70,14 +70,17 @@ void BuildNativeValues(const ComputedStyle& style,
.CrossThreadStyleValueFromComputedStyle(
style, /* layout_object */ nullptr, styled_node,
/* allow_visited_style */ false);
+ if (value->GetType() == CrossThreadStyleValue::StyleValueType::kUnknownType)
+ return false;
String key = CSSProperty::Get(property_id).GetPropertyNameString();
if (!key.IsSafeToSendToAnotherThread())
key = key.IsolatedCopy();
data.Set(key, std::move(value));
}
+ return true;
}
-void BuildCustomValues(const Document& document,
+bool BuildCustomValues(const Document& document,
const ComputedStyle& style,
Node* styled_node,
const Vector<AtomicString>& custom_properties,
@@ -89,17 +92,21 @@ void BuildCustomValues(const Document& document,
ref.GetProperty().CrossThreadStyleValueFromComputedStyle(
style, /* layout_object */ nullptr, styled_node,
/* allow_visited_style */ false);
+ if (value->GetType() == CrossThreadStyleValue::StyleValueType::kUnknownType)
+ return false;
// Ensure that the String can be safely passed cross threads.
String key = property_name.GetString();
if (!key.IsSafeToSendToAnotherThread())
key = key.IsolatedCopy();
data.Set(key, std::move(value));
}
+ return true;
}
} // namespace
-PaintWorkletStylePropertyMap::CrossThreadData
+// static
+base::Optional<PaintWorkletStylePropertyMap::CrossThreadData>
PaintWorkletStylePropertyMap::BuildCrossThreadData(
const Document& document,
const ComputedStyle& style,
@@ -110,11 +117,14 @@ PaintWorkletStylePropertyMap::BuildCrossThreadData(
PaintWorkletStylePropertyMap::CrossThreadData data;
data.ReserveCapacityForSize(native_properties.size() +
custom_properties.size());
- BuildNativeValues(style, styled_node, native_properties, data);
- BuildCustomValues(document, style, styled_node, custom_properties, data);
+ if (!BuildNativeValues(style, styled_node, native_properties, data))
+ return base::nullopt;
+ if (!BuildCustomValues(document, style, styled_node, custom_properties, data))
+ return base::nullopt;
return data;
}
+// static
PaintWorkletStylePropertyMap::CrossThreadData
PaintWorkletStylePropertyMap::CopyCrossThreadData(const CrossThreadData& data) {
PaintWorkletStylePropertyMap::CrossThreadData copied_data;
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/paint_worklet_style_property_map.h b/chromium/third_party/blink/renderer/core/css/cssom/paint_worklet_style_property_map.h
index 7b59e24d354..f7695831639 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/paint_worklet_style_property_map.h
+++ b/chromium/third_party/blink/renderer/core/css/cssom/paint_worklet_style_property_map.h
@@ -31,7 +31,7 @@ class CORE_EXPORT PaintWorkletStylePropertyMap
HashMap<String, std::unique_ptr<CrossThreadStyleValue>>;
// Build the data that will be passed to the worklet thread to construct a
// style map. Should be called on the main thread only.
- static CrossThreadData BuildCrossThreadData(
+ static base::Optional<CrossThreadData> BuildCrossThreadData(
const Document&,
const ComputedStyle&,
Node* styled_node,
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/paint_worklet_style_property_map_test.cc b/chromium/third_party/blink/renderer/core/css/cssom/paint_worklet_style_property_map_test.cc
index 882287be9ac..e52f5a40a32 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/paint_worklet_style_property_map_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/paint_worklet_style_property_map_test.cc
@@ -16,10 +16,10 @@
#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/testing/page_test_base.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/scheduler/public/post_cross_thread_task.h"
-#include "third_party/blink/renderer/platform/web_thread_supporting_gc.h"
+#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
namespace blink {
@@ -33,7 +33,6 @@ class PaintWorkletStylePropertyMapTest : public PageTestBase {
void ShutDown(base::WaitableEvent* waitable_event) {
DCHECK(!IsMainThread());
- thread_->ShutdownOnThread();
waitable_event->Signal();
}
@@ -98,112 +97,109 @@ class PaintWorkletStylePropertyMapTest : public PageTestBase {
exception_state.ClearException();
}
- void CheckStyleMap(base::WaitableEvent* waitable_event,
- scoped_refptr<PaintWorkletInput> input) {
+ void CheckCrossThreadData(base::WaitableEvent* waitable_event,
+ scoped_refptr<PaintWorkletInput> input) {
DCHECK(!IsMainThread());
- thread_->InitializeOnThread();
PaintWorkletStylePropertyMap* map =
MakeGarbageCollected<PaintWorkletStylePropertyMap>(
input->StyleMapData());
DCHECK(map);
- DummyExceptionStateForTesting exception_state;
- CheckNativeProperties(map, exception_state);
- CheckCustomProperties(map, exception_state);
const PaintWorkletStylePropertyMap::CrossThreadData& data =
map->StyleMapDataForTest();
- EXPECT_EQ(data.size(), 8u);
- EXPECT_EQ(data.at("color")->ToCSSStyleValue()->CSSText(), "rgb(0, 255, 0)");
- EXPECT_EQ(data.at("color")->ToCSSStyleValue()->GetType(),
- CSSStyleValue::StyleValueType::kUnknownType);
- EXPECT_EQ(data.at("align-items")->ToCSSStyleValue()->CSSText(), "normal");
- EXPECT_EQ(data.at("align-items")->ToCSSStyleValue()->GetType(),
- CSSStyleValue::StyleValueType::kUnknownType);
- EXPECT_EQ(
- static_cast<CSSKeywordValue*>(data.at("display")->ToCSSStyleValue())
- ->value(),
- "block");
- EXPECT_EQ(data.at("display")->ToCSSStyleValue()->GetType(),
- CSSStyleValue::StyleValueType::kKeywordType);
- EXPECT_EQ(data.at("--foo")->ToCSSStyleValue()->CSSText(), "PaintWorklet");
+ EXPECT_EQ(data.size(), 4u);
EXPECT_EQ(data.at("--foo")->ToCSSStyleValue()->GetType(),
- CSSStyleValue::StyleValueType::kUnknownType);
- EXPECT_EQ(data.at("--bar")->ToCSSStyleValue()->CSSText(), "");
- EXPECT_EQ(data.at("--bar")->ToCSSStyleValue()->GetType(),
- CSSStyleValue::StyleValueType::kUnknownType);
- EXPECT_EQ(data.at("--keyword")->ToCSSStyleValue()->GetType(),
- CSSStyleValue::StyleValueType::kKeywordType);
- EXPECT_EQ(
- To<CSSKeywordValue>(data.at("--keyword")->ToCSSStyleValue())->value(),
- "test");
- EXPECT_EQ(data.at("--x")->ToCSSStyleValue()->GetType(),
CSSStyleValue::StyleValueType::kUnitType);
- EXPECT_EQ(To<CSSUnitValue>(data.at("--x")->ToCSSStyleValue())->value(), 10);
- EXPECT_EQ(To<CSSUnitValue>(data.at("--x")->ToCSSStyleValue())->unit(),
+ EXPECT_EQ(To<CSSUnitValue>(data.at("--foo")->ToCSSStyleValue())->value(),
+ 134);
+ EXPECT_EQ(To<CSSUnitValue>(data.at("--foo")->ToCSSStyleValue())->unit(),
"px");
- EXPECT_EQ(data.at("--y")->ToCSSStyleValue()->GetType(),
- CSSStyleValue::StyleValueType::kUnknownType);
- EXPECT_EQ(data.at("--y")->ToCSSStyleValue()->CSSText(), "rgb(0, 255, 0)");
-
+ EXPECT_EQ(data.at("--bar")->ToCSSStyleValue()->GetType(),
+ CSSStyleValue::StyleValueType::kUnitType);
+ EXPECT_EQ(To<CSSUnitValue>(data.at("--bar")->ToCSSStyleValue())->value(),
+ 42);
+ EXPECT_EQ(data.at("--loo")->ToCSSStyleValue()->GetType(),
+ CSSStyleValue::StyleValueType::kKeywordType);
+ EXPECT_EQ(To<CSSKeywordValue>(data.at("--loo")->ToCSSStyleValue())->value(),
+ "test");
+ EXPECT_EQ(data.at("display")->ToCSSStyleValue()->GetType(),
+ CSSStyleValue::StyleValueType::kKeywordType);
waitable_event->Signal();
}
protected:
- std::unique_ptr<WebThreadSupportingGC> thread_;
+ std::unique_ptr<blink::Thread> thread_;
};
-// This test ensures that Blink::PaintWorkletInput can be safely passed cross
-// threads and no information is lost.
-TEST_F(PaintWorkletStylePropertyMapTest, PassValuesCrossThread) {
- Vector<CSSPropertyID> native_properties({CSSPropertyID::kColor,
- CSSPropertyID::kAlignItems,
- CSSPropertyID::kDisplay});
- GetDocument().documentElement()->style()->setProperty(
- &GetDocument(), "color", "rgb(0, 255, 0)", "", ASSERT_NO_EXCEPTION);
- GetDocument().documentElement()->style()->setProperty(
- &GetDocument(), "display", "block", "", ASSERT_NO_EXCEPTION);
- Vector<AtomicString> custom_properties(
- {"--foo", "--bar", "--keyword", "--x", "--y"});
- css_test_helpers::RegisterProperty(GetDocument(), "--keyword", "test", "test",
+TEST_F(PaintWorkletStylePropertyMapTest, CreateSupportedCrossThreadData) {
+ Vector<CSSPropertyID> native_properties({CSSPropertyID::kDisplay});
+ Vector<AtomicString> custom_properties({"--foo", "--bar", "--loo"});
+ css_test_helpers::RegisterProperty(GetDocument(), "--foo", "<length>",
+ "134px", false);
+ css_test_helpers::RegisterProperty(GetDocument(), "--bar", "<number>", "42",
false);
- css_test_helpers::RegisterProperty(GetDocument(), "--x", "<length>", "42px",
+ css_test_helpers::RegisterProperty(GetDocument(), "--loo", "test", "test",
false);
- css_test_helpers::RegisterProperty(GetDocument(), "--y", "<color>",
- "rgb(0, 0, 0)", false);
- GetDocument().documentElement()->style()->setProperty(
- &GetDocument(), "--foo", "PaintWorklet", "", ASSERT_NO_EXCEPTION);
- GetDocument().documentElement()->style()->setProperty(
- &GetDocument(), "--keyword", "test", "", ASSERT_NO_EXCEPTION);
- GetDocument().documentElement()->style()->setProperty(
- &GetDocument(), "--x", "10px", "", ASSERT_NO_EXCEPTION);
- GetDocument().documentElement()->style()->setProperty(
- &GetDocument(), "--y", "rgb(0, 255, 0)", "", ASSERT_NO_EXCEPTION);
UpdateAllLifecyclePhasesForTest();
Node* node = PageNode();
- PaintWorkletStylePropertyMap::CrossThreadData data =
- PaintWorkletStylePropertyMap::BuildCrossThreadData(
- GetDocument(), node->ComputedStyleRef(), node, native_properties,
- custom_properties);
+ Vector<std::unique_ptr<CrossThreadStyleValue>> input_arguments;
+ auto data = PaintWorkletStylePropertyMap::BuildCrossThreadData(
+ GetDocument(), node->ComputedStyleRef(), node, native_properties,
+ custom_properties);
+
+ EXPECT_TRUE(data.has_value());
scoped_refptr<PaintWorkletInput> input =
base::MakeRefCounted<PaintWorkletInput>("test", FloatSize(100, 100), 1.0f,
- 1, std::move(data));
+ 1, std::move(data.value()),
+ std::move(input_arguments));
DCHECK(input);
- thread_ = std::make_unique<WebThreadSupportingGC>(
- ThreadCreationParams(WebThreadType::kTestThread));
+ thread_ = blink::Thread::CreateThread(
+ ThreadCreationParams(WebThreadType::kTestThread).SetSupportsGC(true));
base::WaitableEvent waitable_event;
PostCrossThreadTask(
*thread_->GetTaskRunner(), FROM_HERE,
- CrossThreadBindOnce(&PaintWorkletStylePropertyMapTest::CheckStyleMap,
- CrossThreadUnretained(this),
- CrossThreadUnretained(&waitable_event),
- std::move(input)));
+ CrossThreadBindOnce(
+ &PaintWorkletStylePropertyMapTest::CheckCrossThreadData,
+ CrossThreadUnretained(this), CrossThreadUnretained(&waitable_event),
+ std::move(input)));
waitable_event.Wait();
ShutDownThread();
}
+TEST_F(PaintWorkletStylePropertyMapTest, UnsupportedCrossThreadData) {
+ Vector<CSSPropertyID> native_properties1;
+ Vector<AtomicString> custom_properties1({"--foo", "--bar", "--loo"});
+ css_test_helpers::RegisterProperty(GetDocument(), "--foo", "<color>",
+ "rgb(0, 0, 0)", false);
+ css_test_helpers::RegisterProperty(GetDocument(), "--bar", "<number>", "42",
+ false);
+ css_test_helpers::RegisterProperty(GetDocument(), "--loo", "test", "test",
+ false);
+
+ UpdateAllLifecyclePhasesForTest();
+ Node* node = PageNode();
+
+ Vector<std::unique_ptr<CrossThreadStyleValue>> input_arguments;
+ auto data1 = PaintWorkletStylePropertyMap::BuildCrossThreadData(
+ GetDocument(), node->ComputedStyleRef(), node, native_properties1,
+ custom_properties1);
+
+ EXPECT_FALSE(data1.has_value());
+
+ Vector<CSSPropertyID> native_properties2(
+ {CSSPropertyID::kDisplay, CSSPropertyID::kColor});
+ Vector<AtomicString> custom_properties2;
+
+ auto data2 = PaintWorkletStylePropertyMap::BuildCrossThreadData(
+ GetDocument(), node->ComputedStyleRef(), node, native_properties2,
+ custom_properties2);
+
+ EXPECT_FALSE(data2.has_value());
+}
+
} // 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 aa9baf7ba61..c0f6f0fda64 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
@@ -18,7 +18,7 @@ namespace blink {
PrepopulatedComputedStylePropertyMap::PrepopulatedComputedStylePropertyMap(
const Document& document,
const ComputedStyle& style,
- Node* styled_node,
+ const Node* styled_node,
const Vector<CSSPropertyID>& native_properties,
const Vector<AtomicString>& custom_properties)
: StylePropertyMapReadOnlyMainThread(), styled_node_(styled_node) {
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 c4419a21740..1ff3f4d0791 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
@@ -31,7 +31,7 @@ class CORE_EXPORT PrepopulatedComputedStylePropertyMap
PrepopulatedComputedStylePropertyMap(
const Document&,
const ComputedStyle&,
- Node* styled_node,
+ const Node* styled_node,
const Vector<CSSPropertyID>& native_properties,
const Vector<AtomicString>& custom_properties);
@@ -54,7 +54,7 @@ class CORE_EXPORT PrepopulatedComputedStylePropertyMap
const ComputedStyle&,
const AtomicString& property_name);
- Member<Node> styled_node_;
+ Member<const Node> styled_node_;
HeapHashMap<CSSPropertyID, Member<const CSSValue>> native_values_;
HeapHashMap<AtomicString, Member<const CSSValue>> custom_values_;
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 45f6154d79a..8c174cab389 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
@@ -15,7 +15,6 @@
#include "third_party/blink/renderer/core/css/parser/css_parser_context.h"
#include "third_party/blink/renderer/core/css/parser/css_tokenizer.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/style_property_shorthand.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
@@ -24,21 +23,6 @@ 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(CSSPropertyID::kVariable) && 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();
@@ -55,79 +39,21 @@ 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 MakeGarbageCollected<CSSVariableReferenceValue>(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,
- const PropertyRegistration* registration,
const CSSStyleValue& style_value,
const ExecutionContext& execution_context) {
DCHECK_EQ(property.IDEquals(CSSPropertyID::kVariable),
!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,
- syntax_component)) {
+ style_value)) {
return nullptr;
}
- if (style_value.GetType() == CSSStyleValue::kUnknownType &&
- // Registered custom properties must enter the CSSPropertyID::kVariable
- // switch-case below, for proper parsing according to registered syntax.
- !(property_id == CSSPropertyID::kVariable && registration)) {
+ if (style_value.GetType() == CSSStyleValue::kUnknownType) {
return CSSParser::ParseSingleValue(
property.PropertyID(), style_value.toString(),
MakeGarbageCollected<CSSParserContext>(execution_context));
@@ -137,16 +63,6 @@ const CSSValue* StyleValueToCSSValue(
// TODO(https://crbug.com/545324): Move this into a method on
// CSSProperty when there are more of these cases.
switch (property_id) {
- case CSSPropertyID::kVariable:
- if (registration &&
- style_value.GetType() != CSSStyleValue::kUnparsedType) {
- auto* context =
- MakeGarbageCollected<CSSParserContext>(execution_context);
- String string =
- StyleValueToString(property, style_value, syntax_component);
- return CreateVariableReferenceValue(string, *context);
- }
- break;
case CSSPropertyID::kBorderBottomLeftRadius:
case CSSPropertyID::kBorderBottomRightRadius:
case CSSPropertyID::kBorderTopLeftRadius:
@@ -269,16 +185,15 @@ const CSSValue* StyleValueToCSSValue(
break;
}
- return style_value.ToCSSValueWithProperty(property_id, syntax_component);
+ return style_value.ToCSSValueWithProperty(property_id);
}
const CSSValue* CoerceStyleValueOrString(
const CSSProperty& property,
const AtomicString& custom_property_name,
- const PropertyRegistration* registration,
const CSSStyleValueOrString& value,
const ExecutionContext& execution_context) {
- DCHECK(!IsListValuedProperty(property, registration));
+ DCHECK(!property.IsRepeated());
DCHECK_EQ(property.IDEquals(CSSPropertyID::kVariable),
!custom_property_name.IsNull());
@@ -286,29 +201,27 @@ const CSSValue* CoerceStyleValueOrString(
if (!value.GetAsCSSStyleValue())
return nullptr;
- return StyleValueToCSSValue(property, custom_property_name, registration,
+ return StyleValueToCSSValue(property, custom_property_name,
*value.GetAsCSSStyleValue(), execution_context);
} else {
DCHECK(value.IsString());
const auto values = StyleValueFactory::FromString(
- property.PropertyID(), custom_property_name, registration,
- value.GetAsString(),
+ property.PropertyID(), custom_property_name, value.GetAsString(),
MakeGarbageCollected<CSSParserContext>(execution_context));
if (values.size() != 1U)
return nullptr;
- return StyleValueToCSSValue(property, custom_property_name, registration,
- *values[0], execution_context);
+ return StyleValueToCSSValue(property, custom_property_name, *values[0],
+ execution_context);
}
}
const CSSValue* CoerceStyleValuesOrStrings(
const CSSProperty& property,
const AtomicString& custom_property_name,
- const PropertyRegistration* registration,
const HeapVector<CSSStyleValueOrString>& values,
const ExecutionContext& execution_context) {
- DCHECK(IsListValuedProperty(property, registration));
+ DCHECK(property.IsRepeated());
DCHECK_EQ(property.IDEquals(CSSPropertyID::kVariable),
!custom_property_name.IsNull());
if (values.IsEmpty())
@@ -316,23 +229,15 @@ const CSSValue* CoerceStyleValuesOrStrings(
CSSStyleValueVector style_values =
StyleValueFactory::CoerceStyleValuesOrStrings(
- property, custom_property_name, registration, values,
- execution_context);
+ property, custom_property_name, values, execution_context);
if (style_values.IsEmpty())
return nullptr;
- if (property.IDEquals(CSSPropertyID::kVariable) && registration) {
- auto* context = MakeGarbageCollected<CSSParserContext>(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 =
- StyleValueToCSSValue(property, custom_property_name, nullptr,
- *style_value, execution_context);
+ const CSSValue* css_value = StyleValueToCSSValue(
+ property, custom_property_name, *style_value, execution_context);
if (!css_value)
return nullptr;
if (css_value->IsCSSWideKeyword() || css_value->IsVariableReferenceValue())
@@ -366,10 +271,8 @@ void StylePropertyMap::set(const ExecutionContext* execution_context,
String css_text;
if (values[0].IsCSSStyleValue()) {
CSSStyleValue* style_value = values[0].GetAsCSSStyleValue();
- const CSSSyntaxComponent* syntax_component = nullptr;
if (style_value &&
- CSSOMTypes::PropertyCanTake(property_id, g_null_atom, nullptr,
- *style_value, syntax_component)) {
+ CSSOMTypes::PropertyCanTake(property_id, g_null_atom, *style_value)) {
css_text = style_value->toString();
}
} else {
@@ -388,26 +291,13 @@ void StylePropertyMap::set(const ExecutionContext* execution_context,
? AtomicString(property_name)
: g_null_atom;
- const PropertyRegistration* registration = nullptr;
-
- if (property_id == CSSPropertyID::kVariable &&
- IsA<Document>(execution_context)) {
- const PropertyRegistry* registry =
- To<Document>(*execution_context).GetPropertyRegistry();
- if (registry) {
- registration = registry->Registration(custom_property_name);
- }
- }
-
const CSSValue* result = nullptr;
- if (IsListValuedProperty(property, registration)) {
- result =
- CoerceStyleValuesOrStrings(property, custom_property_name, registration,
- values, *execution_context);
+ if (property.IsRepeated()) {
+ result = CoerceStyleValuesOrStrings(property, custom_property_name, values,
+ *execution_context);
} else if (values.size() == 1U) {
- result =
- CoerceStyleValueOrString(property, custom_property_name, registration,
- values[0], *execution_context);
+ result = CoerceStyleValueOrString(property, custom_property_name, values[0],
+ *execution_context);
}
if (!result) {
@@ -438,47 +328,6 @@ void StylePropertyMap::append(const ExecutionContext* execution_context,
const CSSProperty& property = CSSProperty::Get(property_id);
if (property_id == CSSPropertyID::kVariable) {
- 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(
- CSSPropertyName(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);
- auto* context =
- MakeGarbageCollected<CSSParserContext>(*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;
@@ -497,7 +346,7 @@ void StylePropertyMap::append(const ExecutionContext* execution_context,
}
const CSSValue* result = CoerceStyleValuesOrStrings(
- property, g_null_atom, nullptr, values, *execution_context);
+ property, g_null_atom, values, *execution_context);
const auto* result_value_list = DynamicTo<CSSValueList>(result);
if (!result_value_list) {
exception_state.ThrowTypeError("Invalid type for property");
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/style_property_map_read_only_main_thread.cc b/chromium/third_party/blink/renderer/core/css/cssom/style_property_map_read_only_main_thread.cc
index f1fb21a34bb..3499347c498 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/style_property_map_read_only_main_thread.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/style_property_map_read_only_main_thread.cc
@@ -73,10 +73,9 @@ CSSStyleValue* StylePropertyMapReadOnlyMainThread::get(
if (property.IsShorthand())
return GetShorthandProperty(property);
- const CSSValue* value =
- (name->IsCustomProperty())
- ? GetCustomProperty(*execution_context, name->ToAtomicString())
- : GetProperty(name->Id());
+ const CSSValue* value = (name->IsCustomProperty())
+ ? GetCustomProperty(name->ToAtomicString())
+ : GetProperty(name->Id());
if (!value)
return nullptr;
@@ -110,10 +109,9 @@ CSSStyleValueVector StylePropertyMapReadOnlyMainThread::getAll(
return values;
}
- const CSSValue* value =
- (name->IsCustomProperty())
- ? GetCustomProperty(*execution_context, name->ToAtomicString())
- : GetProperty(name->Id());
+ const CSSValue* value = (name->IsCustomProperty())
+ ? GetCustomProperty(name->ToAtomicString())
+ : GetProperty(name->Id());
if (!value)
return CSSStyleValueVector();
@@ -127,41 +125,14 @@ bool StylePropertyMapReadOnlyMainThread::has(
return !getAll(execution_context, property_name, exception_state).IsEmpty();
}
-const CSSValue* StylePropertyMapReadOnlyMainThread::GetCustomProperty(
- const ExecutionContext& execution_context,
- const AtomicString& property_name) const {
- 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);
-
- ForEachProperty([&result, &execution_context](const CSSPropertyName& name,
- const CSSValue& css_value) {
- const CSSValue* value = &css_value;
-
- // TODO(andruud): Refactor this. ForEachProperty should yield the correct,
- // already-parsed value in the first place.
- if (name.IsCustomProperty()) {
- const auto* document = DynamicTo<Document>(execution_context);
- if (document) {
- value = PropertyRegistry::ParseIfRegistered(
- *document, name.ToAtomicString(), value);
- }
- }
-
- auto values = StyleValueFactory::CssValueToStyleValueVector(name, *value);
+ ForEachProperty([&result](const CSSPropertyName& name,
+ const CSSValue& value) {
+ auto values = StyleValueFactory::CssValueToStyleValueVector(name, value);
result.emplace_back(name.ToAtomicString(), std::move(values));
});
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
index c98f863450f..1c259a9ac02 100644
--- 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
@@ -43,9 +43,6 @@ class CORE_EXPORT StylePropertyMapReadOnlyMainThread
virtual String SerializationForShorthand(const CSSProperty&) const = 0;
- const CSSValue* GetCustomProperty(const ExecutionContext&,
- const AtomicString&) const;
-
private:
IterationSource* StartIteration(ScriptState*, ExceptionState&) override;
diff --git a/chromium/third_party/blink/renderer/core/css/cssom/style_value_factory.cc b/chromium/third_party/blink/renderer/core/css/cssom/style_value_factory.cc
index 7638247ec43..982f74626dd 100644
--- a/chromium/third_party/blink/renderer/core/css/cssom/style_value_factory.cc
+++ b/chromium/third_party/blink/renderer/core/css/cssom/style_value_factory.cc
@@ -26,7 +26,6 @@
#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/properties/css_property.h"
-#include "third_party/blink/renderer/core/css/property_registration.h"
#include "third_party/blink/renderer/core/style_property_shorthand.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
@@ -54,9 +53,8 @@ CSSStyleValue* CreateStyleValue(const CSSValue& value) {
return CSSKeywordValue::FromCSSValue(value);
if (auto* primitive_value = DynamicTo<CSSPrimitiveValue>(value))
return CSSNumericValue::FromCSSValue(*primitive_value);
- if (auto* image_value = DynamicTo<CSSImageValue>(value)) {
- return CSSURLImageValue::FromCSSValue(*image_value->Clone());
- }
+ if (auto* image_value = DynamicTo<CSSImageValue>(value))
+ return MakeGarbageCollected<CSSURLImageValue>(*image_value->Clone());
return nullptr;
}
@@ -245,7 +243,6 @@ CSSStyleValueVector UnsupportedCSSValue(const CSSPropertyName& name,
CSSStyleValueVector StyleValueFactory::FromString(
CSSPropertyID property_id,
const AtomicString& custom_property_name,
- const PropertyRegistration* registration,
const String& css_text,
const CSSParserContext* parser_context) {
DCHECK_NE(property_id, CSSPropertyID::kInvalid);
@@ -278,17 +275,6 @@ CSSStyleValueVector StyleValueFactory::FromString(
return result;
}
- if (property_id == CSSPropertyID::kVariable && registration) {
- const bool is_animation_tainted = false;
- const CSSValue* value = registration->Syntax().Parse(tokens, parser_context,
- is_animation_tainted);
- if (!value)
- return CSSStyleValueVector();
-
- return StyleValueFactory::CssValueToStyleValueVector(
- CSSPropertyName(custom_property_name), *value);
- }
-
if ((property_id == CSSPropertyID::kVariable && !tokens.IsEmpty()) ||
CSSVariableParser::ContainsValidVariableReferences(range)) {
const auto variable_data = CSSVariableData::Create(
@@ -317,7 +303,6 @@ CSSStyleValue* StyleValueFactory::CssValueToStyleValue(
CSSStyleValueVector StyleValueFactory::CoerceStyleValuesOrStrings(
const CSSProperty& property,
const AtomicString& custom_property_name,
- const PropertyRegistration* registration,
const HeapVector<CSSStyleValueOrString>& values,
const ExecutionContext& execution_context) {
const CSSParserContext* parser_context = nullptr;
@@ -336,8 +321,8 @@ CSSStyleValueVector StyleValueFactory::CoerceStyleValuesOrStrings(
}
const auto subvalues = StyleValueFactory::FromString(
- property.PropertyID(), custom_property_name, registration,
- value.GetAsString(), parser_context);
+ property.PropertyID(), custom_property_name, value.GetAsString(),
+ parser_context);
if (subvalues.IsEmpty())
return CSSStyleValueVector();
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 97e73500a10..4567fa836b3 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
@@ -8,7 +8,7 @@
#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/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -17,7 +17,6 @@ class CSSProperty;
class CSSPropertyName;
class CSSValue;
class ExecutionContext;
-class PropertyRegistration;
class CORE_EXPORT StyleValueFactory {
STATIC_ONLY(StyleValueFactory);
@@ -26,7 +25,6 @@ class CORE_EXPORT StyleValueFactory {
static CSSStyleValueVector FromString(
CSSPropertyID,
const AtomicString& custom_property_name,
- const PropertyRegistration*,
const String&,
const CSSParserContext*);
static CSSStyleValue* CssValueToStyleValue(const CSSPropertyName&,
@@ -37,7 +35,6 @@ class CORE_EXPORT StyleValueFactory {
static CSSStyleValueVector CoerceStyleValuesOrStrings(
const CSSProperty& property,
const AtomicString& custom_property_name,
- const PropertyRegistration*,
const HeapVector<CSSStyleValueOrString>& values,
const ExecutionContext&);
// Reify a CSSStyleValue without the context of a CSS property. For most
diff --git a/chromium/third_party/blink/renderer/core/css/document_style_environment_variables.cc b/chromium/third_party/blink/renderer/core/css/document_style_environment_variables.cc
index 09f38fddb07..d76e46260da 100644
--- a/chromium/third_party/blink/renderer/core/css/document_style_environment_variables.cc
+++ b/chromium/third_party/blink/renderer/core/css/document_style_environment_variables.cc
@@ -6,8 +6,8 @@
#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/frame/use_counter.h"
#include "third_party/blink/renderer/core/frame/web_feature.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/wtf/text/string_hasher.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/css/dom_window_css.cc b/chromium/third_party/blink/renderer/core/css/dom_window_css.cc
index c4684eb5509..1f83329c0b4 100644
--- a/chromium/third_party/blink/renderer/core/css/dom_window_css.cc
+++ b/chromium/third_party/blink/renderer/core/css/dom_window_css.cc
@@ -33,7 +33,6 @@
#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/properties/css_property.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/platform/heap/heap.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
@@ -51,18 +50,16 @@ bool DOMWindowCSS::supports(const ExecutionContext* execution_context,
auto* dummy_style =
MakeGarbageCollected<MutableCSSPropertyValueSet>(kHTMLStandardMode);
bool is_animation_tainted = false;
- const Document& document = To<Document>(*execution_context);
- const PropertyRegistry* registry = document.GetPropertyRegistry();
return CSSParser::ParseValueForCustomProperty(
- dummy_style, AtomicString(property), registry, value, false,
+ dummy_style, "--valid", value, false,
execution_context->GetSecureContextMode(), nullptr,
is_animation_tainted)
.did_parse;
}
#if DCHECK_IS_ON()
- DCHECK(
- CSSProperty::Get(resolveCSSPropertyID(unresolved_property)).IsEnabled());
+ DCHECK(CSSProperty::Get(resolveCSSPropertyID(unresolved_property))
+ .IsWebExposed());
#endif
// This will return false when !important is present
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 7e07c1def9b..f13672c7d7a 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
@@ -130,7 +130,7 @@ void ElementRuleCollector::CollectMatchingRulesForList(
init.part_names = part_names;
SelectorChecker checker(init);
SelectorChecker::SelectorCheckingContext context(
- context_.GetElement(), SelectorChecker::kVisitedMatchEnabled);
+ &context_.GetElement(), SelectorChecker::kVisitedMatchEnabled);
context.scope = match_request.scope;
context.pseudo_id = pseudo_style_request_.pseudo_id;
@@ -175,7 +175,7 @@ void ElementRuleCollector::CollectMatchingRulesForList(
}
StyleEngine& style_engine =
- context_.GetElement()->GetDocument().GetStyleEngine();
+ context_.GetElement().GetDocument().GetStyleEngine();
if (!style_engine.Stats())
return;
@@ -191,9 +191,8 @@ void ElementRuleCollector::CollectMatchingRules(
ShadowV0CascadeOrder cascade_order,
bool matching_tree_boundary_rules) {
DCHECK(match_request.rule_set);
- DCHECK(context_.GetElement());
- Element& element = *context_.GetElement();
+ Element& element = context_.GetElement();
const AtomicString& pseudo_id = element.ShadowPseudoId();
if (!pseudo_id.IsEmpty()) {
DCHECK(element.IsStyledElement());
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 2350a25fd61..bf483a2d434 100644
--- a/chromium/third_party/blink/renderer/core/css/font_face.cc
+++ b/chromium/third_party/blink/renderer/core/css/font_face.cc
@@ -56,7 +56,6 @@
#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/core/frame/settings.h"
-#include "third_party/blink/renderer/core/frame/use_counter.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/workers/worker_global_scope.h"
@@ -64,7 +63,8 @@
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/font_family_names.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/shared_buffer.h"
diff --git a/chromium/third_party/blink/renderer/core/css/font_face_cache_test.cc b/chromium/third_party/blink/renderer/core/css/font_face_cache_test.cc
index fe60820ba8e..56bbe080e10 100644
--- a/chromium/third_party/blink/renderer/core/css/font_face_cache_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/font_face_cache_test.cc
@@ -9,6 +9,7 @@
#include "third_party/blink/renderer/core/css/css_font_family_value.h"
#include "third_party/blink/renderer/core/css/css_font_style_range_value.h"
#include "third_party/blink/renderer/core/css/css_identifier_value.h"
+#include "third_party/blink/renderer/core/css/css_numeric_literal_value.h"
#include "third_party/blink/renderer/core/css/css_property_value_set.h"
#include "third_party/blink/renderer/core/css/css_segmented_font_face.h"
#include "third_party/blink/renderer/core/css/css_value_list.h"
@@ -65,7 +66,8 @@ void FontFaceCacheTest::AppendTestFaceForCapabilities(const CSSValue& stretch,
CSSFontFamilyValue* family_name =
CSSFontFamilyValue::Create(kFontNameForTesting);
CSSFontFaceSrcValue* src = CSSFontFaceSrcValue::CreateLocal(
- kFontNameForTesting, kDoNotCheckContentSecurityPolicy);
+ kFontNameForTesting, kDoNotCheckContentSecurityPolicy,
+ OriginClean::kTrue);
CSSValueList* src_value_list = CSSValueList::CreateCommaSeparated();
src_value_list->Append(*src);
CSSPropertyValue properties[] = {
@@ -115,7 +117,7 @@ TEST_F(FontFaceCacheTest, Instantiate) {
CSSIdentifierValue::Create(CSSValueID::kUltraExpanded);
CSSIdentifierValue* stretch_value_condensed =
CSSIdentifierValue::Create(CSSValueID::kCondensed);
- CSSPrimitiveValue* weight_value = CSSPrimitiveValue::Create(
+ CSSPrimitiveValue* weight_value = CSSNumericLiteralValue::Create(
BoldWeightValue(), CSSPrimitiveValue::UnitType::kNumber);
CSSIdentifierValue* style_value =
CSSIdentifierValue::Create(CSSValueID::kItalic);
@@ -132,7 +134,7 @@ TEST_F(FontFaceCacheTest, SimpleWidthMatch) {
CSSIdentifierValue::Create(CSSValueID::kUltraExpanded);
CSSIdentifierValue* stretch_value_condensed =
CSSIdentifierValue::Create(CSSValueID::kCondensed);
- CSSPrimitiveValue* weight_value = CSSPrimitiveValue::Create(
+ CSSPrimitiveValue* weight_value = CSSNumericLiteralValue::Create(
NormalWeightValue(), CSSPrimitiveValue::UnitType::kNumber);
CSSIdentifierValue* style_value =
CSSIdentifierValue::Create(CSSValueID::kNormal);
@@ -164,11 +166,11 @@ TEST_F(FontFaceCacheTest, SimpleWeightMatch) {
CSSIdentifierValue* style_value =
CSSIdentifierValue::Create(CSSValueID::kNormal);
CSSPrimitiveValue* weight_value_black =
- CSSPrimitiveValue::Create(900, CSSPrimitiveValue::UnitType::kNumber);
+ CSSNumericLiteralValue::Create(900, CSSPrimitiveValue::UnitType::kNumber);
AppendTestFaceForCapabilities(*stretch_value, *style_value,
*weight_value_black);
CSSPrimitiveValue* weight_value_thin =
- CSSPrimitiveValue::Create(100, CSSPrimitiveValue::UnitType::kNumber);
+ CSSNumericLiteralValue::Create(100, CSSPrimitiveValue::UnitType::kNumber);
AppendTestFaceForCapabilities(*stretch_value, *style_value,
*weight_value_thin);
ASSERT_EQ(cache_.GetNumSegmentedFacesForTesting(), 2ul);
@@ -234,8 +236,9 @@ TEST_F(FontFaceCacheTest, DISABLED_MatchCombinations) {
CSSValue* slopes[] = {CSSIdentifierValue::Create(CSSValueID::kNormal),
CSSIdentifierValue::Create(CSSValueID::kItalic)};
CSSValue* weights[] = {
- CSSPrimitiveValue::Create(100, CSSPrimitiveValue::UnitType::kNumber),
- CSSPrimitiveValue::Create(900, CSSPrimitiveValue::UnitType::kNumber)};
+ CSSNumericLiteralValue::Create(100, CSSPrimitiveValue::UnitType::kNumber),
+ CSSNumericLiteralValue::Create(900,
+ CSSPrimitiveValue::UnitType::kNumber)};
Vector<FontSelectionValue> width_choices = {CondensedWidthValue(),
ExpandedWidthValue()};
@@ -295,18 +298,18 @@ TEST_F(FontFaceCacheTest, WidthRangeMatching) {
CSSIdentifierValue* style_value =
CSSIdentifierValue::Create(CSSValueID::kNormal);
CSSPrimitiveValue* weight_value_from =
- CSSPrimitiveValue::Create(700, CSSPrimitiveValue::UnitType::kNumber);
+ CSSNumericLiteralValue::Create(700, CSSPrimitiveValue::UnitType::kNumber);
CSSPrimitiveValue* weight_value_to =
- CSSPrimitiveValue::Create(800, CSSPrimitiveValue::UnitType::kNumber);
+ CSSNumericLiteralValue::Create(800, CSSPrimitiveValue::UnitType::kNumber);
CSSValueList* weight_list = CSSValueList::CreateSpaceSeparated();
weight_list->Append(*weight_value_from);
weight_list->Append(*weight_value_to);
AppendTestFaceForCapabilities(*stretch_value, *style_value, *weight_list);
CSSPrimitiveValue* second_weight_value_from =
- CSSPrimitiveValue::Create(100, CSSPrimitiveValue::UnitType::kNumber);
+ CSSNumericLiteralValue::Create(100, CSSPrimitiveValue::UnitType::kNumber);
CSSPrimitiveValue* second_weight_value_to =
- CSSPrimitiveValue::Create(200, CSSPrimitiveValue::UnitType::kNumber);
+ CSSNumericLiteralValue::Create(200, CSSPrimitiveValue::UnitType::kNumber);
CSSValueList* second_weight_list = CSSValueList::CreateSpaceSeparated();
second_weight_list->Append(*second_weight_value_from);
second_weight_list->Append(*second_weight_value_to);
@@ -340,15 +343,15 @@ TEST_F(FontFaceCacheTest, WidthRangeMatchingBetween400500) {
CSSIdentifierValue::Create(CSSValueID::kNormal);
CSSPrimitiveValue* weight_values_lower[] = {
- CSSPrimitiveValue::Create(600, CSSPrimitiveValue::UnitType::kNumber),
- CSSPrimitiveValue::Create(415, CSSPrimitiveValue::UnitType::kNumber),
- CSSPrimitiveValue::Create(475, CSSPrimitiveValue::UnitType::kNumber),
+ CSSNumericLiteralValue::Create(600, CSSPrimitiveValue::UnitType::kNumber),
+ CSSNumericLiteralValue::Create(415, CSSPrimitiveValue::UnitType::kNumber),
+ CSSNumericLiteralValue::Create(475, CSSPrimitiveValue::UnitType::kNumber),
};
CSSPrimitiveValue* weight_values_upper[] = {
- CSSPrimitiveValue::Create(610, CSSPrimitiveValue::UnitType::kNumber),
- CSSPrimitiveValue::Create(425, CSSPrimitiveValue::UnitType::kNumber),
- CSSPrimitiveValue::Create(485, CSSPrimitiveValue::UnitType::kNumber),
+ CSSNumericLiteralValue::Create(610, CSSPrimitiveValue::UnitType::kNumber),
+ CSSNumericLiteralValue::Create(425, CSSPrimitiveValue::UnitType::kNumber),
+ CSSNumericLiteralValue::Create(485, CSSPrimitiveValue::UnitType::kNumber),
};
// From https://drafts.csswg.org/css-fonts-4/#font-style-matching: "If the
@@ -397,14 +400,14 @@ TEST_F(FontFaceCacheTest, WidthRangeMatchingBetween400500) {
}
TEST_F(FontFaceCacheTest, StretchRangeMatching) {
- CSSPrimitiveValue* stretch_value_from =
- CSSPrimitiveValue::Create(65, CSSPrimitiveValue::UnitType::kPercentage);
- CSSPrimitiveValue* stretch_value_to =
- CSSPrimitiveValue::Create(70, CSSPrimitiveValue::UnitType::kPercentage);
+ CSSPrimitiveValue* stretch_value_from = CSSNumericLiteralValue::Create(
+ 65, CSSPrimitiveValue::UnitType::kPercentage);
+ CSSPrimitiveValue* stretch_value_to = CSSNumericLiteralValue::Create(
+ 70, CSSPrimitiveValue::UnitType::kPercentage);
CSSIdentifierValue* style_value =
CSSIdentifierValue::Create(CSSValueID::kNormal);
CSSPrimitiveValue* weight_value =
- CSSPrimitiveValue::Create(400, CSSPrimitiveValue::UnitType::kNumber);
+ CSSNumericLiteralValue::Create(400, CSSPrimitiveValue::UnitType::kNumber);
CSSValueList* stretch_list = CSSValueList::CreateSpaceSeparated();
stretch_list->Append(*stretch_value_from);
stretch_list->Append(*stretch_value_to);
@@ -412,9 +415,9 @@ TEST_F(FontFaceCacheTest, StretchRangeMatching) {
const float kStretchFrom = 110;
const float kStretchTo = 120;
- CSSPrimitiveValue* second_stretch_value_from = CSSPrimitiveValue::Create(
+ CSSPrimitiveValue* second_stretch_value_from = CSSNumericLiteralValue::Create(
kStretchFrom, CSSPrimitiveValue::UnitType::kPercentage);
- CSSPrimitiveValue* second_stretch_value_to = CSSPrimitiveValue::Create(
+ CSSPrimitiveValue* second_stretch_value_to = CSSNumericLiteralValue::Create(
kStretchTo, CSSPrimitiveValue::UnitType::kPercentage);
CSSValueList* second_stretch_list = CSSValueList::CreateSpaceSeparated();
second_stretch_list->Append(*second_stretch_value_from);
@@ -444,16 +447,16 @@ TEST_F(FontFaceCacheTest, ObliqueRangeMatching) {
CSSIdentifierValue* stretch_value =
CSSIdentifierValue::Create(CSSValueID::kNormal);
CSSPrimitiveValue* weight_value =
- CSSPrimitiveValue::Create(400, CSSPrimitiveValue::UnitType::kNumber);
+ CSSNumericLiteralValue::Create(400, CSSPrimitiveValue::UnitType::kNumber);
CSSIdentifierValue* oblique_keyword_value =
CSSIdentifierValue::Create(CSSValueID::kOblique);
CSSValueList* oblique_range = CSSValueList::CreateCommaSeparated();
CSSPrimitiveValue* oblique_from =
- CSSPrimitiveValue::Create(30, CSSPrimitiveValue::UnitType::kNumber);
+ CSSNumericLiteralValue::Create(30, CSSPrimitiveValue::UnitType::kNumber);
CSSPrimitiveValue* oblique_to =
- CSSPrimitiveValue::Create(35, CSSPrimitiveValue::UnitType::kNumber);
+ CSSNumericLiteralValue::Create(35, CSSPrimitiveValue::UnitType::kNumber);
oblique_range->Append(*oblique_from);
oblique_range->Append(*oblique_to);
auto* oblique_value = MakeGarbageCollected<CSSFontStyleRangeValue>(
@@ -463,9 +466,9 @@ TEST_F(FontFaceCacheTest, ObliqueRangeMatching) {
CSSValueList* oblique_range_second = CSSValueList::CreateCommaSeparated();
CSSPrimitiveValue* oblique_from_second =
- CSSPrimitiveValue::Create(5, CSSPrimitiveValue::UnitType::kNumber);
+ CSSNumericLiteralValue::Create(5, CSSPrimitiveValue::UnitType::kNumber);
CSSPrimitiveValue* oblique_to_second =
- CSSPrimitiveValue::Create(10, CSSPrimitiveValue::UnitType::kNumber);
+ CSSNumericLiteralValue::Create(10, CSSPrimitiveValue::UnitType::kNumber);
oblique_range_second->Append(*oblique_from_second);
oblique_range_second->Append(*oblique_to_second);
auto* oblique_value_second = MakeGarbageCollected<CSSFontStyleRangeValue>(
diff --git a/chromium/third_party/blink/renderer/core/css/font_face_set_document.cc b/chromium/third_party/blink/renderer/core/css/font_face_set_document.cc
index 69a67ba4693..4abf570d9b1 100644
--- a/chromium/third_party/blink/renderer/core/css/font_face_set_document.cc
+++ b/chromium/third_party/blink/renderer/core/css/font_face_set_document.cc
@@ -32,6 +32,7 @@
#include "third_party/blink/renderer/core/css/font_face_cache.h"
#include "third_party/blink/renderer/core/css/font_face_set_load_event.h"
#include "third_party/blink/renderer/core/css/parser/css_parser.h"
+#include "third_party/blink/renderer/core/css/resolver/font_style_resolver.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/dom/document.h"
@@ -40,7 +41,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
namespace blink {
@@ -74,7 +75,6 @@ void FontFaceSetDocument::DidLayout() {
}
void FontFaceSetDocument::BeginFontLoading(FontFace* font_face) {
- histogram_.IncrementCount();
AddToLoadingFonts(font_face);
}
@@ -152,6 +152,15 @@ bool FontFaceSetDocument::ResolveFontStyle(const String& font_string,
if (font_value == "inherit" || font_value == "initial")
return false;
+ if (!GetDocument()->documentElement()) {
+ auto* font_selector = GetDocument()->GetStyleEngine().GetFontSelector();
+ FontDescription description =
+ FontStyleResolver::ComputeFont(*parsed_style, font_selector);
+ font = Font(description);
+ font.Update(font_selector);
+ return true;
+ }
+
scoped_refptr<ComputedStyle> style = ComputedStyle::Create();
FontFamily font_family;
@@ -167,7 +176,8 @@ bool FontFaceSetDocument::ResolveFontStyle(const String& font_string,
style->GetFont().Update(style->GetFont().GetFontSelector());
GetDocument()->UpdateActiveStyle();
- GetDocument()->EnsureStyleResolver().ComputeFont(style.get(), *parsed_style);
+ GetDocument()->EnsureStyleResolver().ComputeFont(
+ *GetDocument()->documentElement(), style.get(), *parsed_style);
font = style->GetFont();
font.Update(GetFontSelector());
@@ -213,12 +223,6 @@ void FontFaceSetDocument::FontLoadHistogram::UpdateStatus(FontFace* font_face) {
}
void FontFaceSetDocument::FontLoadHistogram::Record() {
- if (!recorded_) {
- recorded_ = true;
- DEFINE_STATIC_LOCAL(CustomCountHistogram, web_fonts_in_page_histogram,
- ("WebFont.WebFontsInPage", 1, 100, 50));
- web_fonts_in_page_histogram.Count(count_);
- }
if (status_ == kHadBlankText || status_ == kDidNotHaveBlankText) {
DEFINE_STATIC_LOCAL(EnumerationHistogram, had_blank_text_histogram,
("WebFont.HadBlankText", 2));
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 78e091d8cfc..e02777a5571 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
@@ -37,7 +37,7 @@
#include "third_party/blink/renderer/core/dom/events/event_listener.h"
#include "third_party/blink/renderer/core/dom/events/event_target.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -90,15 +90,12 @@ class CORE_EXPORT FontFaceSetDocument final : public FontFaceSet,
public:
enum Status { kNoWebFonts, kHadBlankText, kDidNotHaveBlankText, kReported };
- FontLoadHistogram() : status_(kNoWebFonts), count_(0), recorded_(false) {}
- void IncrementCount() { count_++; }
+ FontLoadHistogram() : status_(kNoWebFonts) {}
void UpdateStatus(FontFace*);
void Record();
private:
Status status_;
- int count_;
- bool recorded_;
};
FontLoadHistogram histogram_;
DISALLOW_COPY_AND_ASSIGN(FontFaceSetDocument);
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 eb605f198cc..87ce5492143 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
@@ -13,7 +13,7 @@
#include "third_party/blink/renderer/core/css/offscreen_font_selector.h"
#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/css/font_face_source.h b/chromium/third_party/blink/renderer/core/css/font_face_source.h
index 3ced8b262be..02a8d197b00 100644
--- a/chromium/third_party/blink/renderer/core/css/font_face_source.h
+++ b/chromium/third_party/blink/renderer/core/css/font_face_source.h
@@ -7,7 +7,7 @@
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/css/font_size_functions.h b/chromium/third_party/blink/renderer/core/css/font_size_functions.h
index 759721ad58e..7b54363fde0 100644
--- a/chromium/third_party/blink/renderer/core/css/font_size_functions.h
+++ b/chromium/third_party/blink/renderer/core/css/font_size_functions.h
@@ -24,7 +24,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_FONT_SIZE_FUNCTIONS_H_
#include "third_party/blink/renderer/core/css_value_keywords.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/css/hash_tools.h b/chromium/third_party/blink/renderer/core/css/hash_tools.h
index 3e0eed9edd5..868451d49ee 100644
--- a/chromium/third_party/blink/renderer/core/css/hash_tools.h
+++ b/chromium/third_party/blink/renderer/core/css/hash_tools.h
@@ -21,7 +21,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_HASH_TOOLS_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_HASH_TOOLS_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 bbb0eb61bd3..77cf6154914 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
@@ -53,11 +53,6 @@ CSSStyleSheet* InlineCSSStyleDeclaration::ParentStyleSheet() const {
: nullptr;
}
-PropertyRegistry* InlineCSSStyleDeclaration::GetPropertyRegistry() const {
- return parent_element_ ? parent_element_->GetDocument().GetPropertyRegistry()
- : nullptr;
-}
-
void InlineCSSStyleDeclaration::Trace(blink::Visitor* visitor) {
visitor->Trace(parent_element_);
AbstractPropertySetCSSStyleDeclaration::Trace(visitor);
diff --git a/chromium/third_party/blink/renderer/core/css/inline_css_style_declaration.h b/chromium/third_party/blink/renderer/core/css/inline_css_style_declaration.h
index 0d9ce294719..127c9d8944d 100644
--- a/chromium/third_party/blink/renderer/core/css/inline_css_style_declaration.h
+++ b/chromium/third_party/blink/renderer/core/css/inline_css_style_declaration.h
@@ -46,7 +46,6 @@ class InlineCSSStyleDeclaration final
Element* ParentElement() const override { return parent_element_; }
void DidMutate(MutationType) override;
- PropertyRegistry* GetPropertyRegistry() const final;
Member<Element> parent_element_;
};
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 483c6beffc5..5769a5df299 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
@@ -370,7 +370,7 @@ void InvalidationSet::Show() const {
value->BeginArray("InvalidationSet");
ToTracedValue(value.get());
value->EndArray();
- fprintf(stderr, "%s\n", value->ToString().Ascii().data());
+ fprintf(stderr, "%s\n", value->ToString().Ascii().c_str());
}
#endif // NDEBUG
diff --git a/chromium/third_party/blink/renderer/core/css/invalidation/invalidation_set.h b/chromium/third_party/blink/renderer/core/css/invalidation/invalidation_set.h
index 3470798988c..7de2e130b63 100644
--- a/chromium/third_party/blink/renderer/core/css/invalidation/invalidation_set.h
+++ b/chromium/third_party/blink/renderer/core/css/invalidation/invalidation_set.h
@@ -37,7 +37,7 @@
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/css/invalidation/invalidation_flags.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/casting.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
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 92d9c68af4d..d8090492d64 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
@@ -318,9 +318,10 @@ void StyleInvalidator::InvalidateSlotDistributedElements(
for (auto& distributed_node : slot.FlattenedAssignedNodes()) {
if (distributed_node->NeedsStyleRecalc())
continue;
- if (!distributed_node->IsElementNode())
+ auto* element = DynamicTo<Element>(distributed_node.Get());
+ if (!element)
continue;
- if (MatchesCurrentInvalidationSetsAsSlotted(ToElement(*distributed_node))) {
+ if (MatchesCurrentInvalidationSetsAsSlotted(*element)) {
distributed_node->SetNeedsStyleRecalc(
kLocalStyleChange, StyleChangeReasonForTracing::Create(
style_change_reason::kStyleInvalidator));
diff --git a/chromium/third_party/blink/renderer/core/css/layout_tree_rebuild_root.cc b/chromium/third_party/blink/renderer/core/css/layout_tree_rebuild_root.cc
index 8d1fd528a07..1d105534d06 100644
--- a/chromium/third_party/blink/renderer/core/css/layout_tree_rebuild_root.cc
+++ b/chromium/third_party/blink/renderer/core/css/layout_tree_rebuild_root.cc
@@ -27,7 +27,7 @@ Element& LayoutTreeRebuildRoot::RootElement() const {
}
if (!root_node || root_node->IsDocumentNode())
return *GetRootNode()->GetDocument().documentElement();
- return ToElement(*root_node);
+ return To<Element>(*root_node);
}
#if DCHECK_IS_ON()
diff --git a/chromium/third_party/blink/renderer/core/css/local_font_face_source.cc b/chromium/third_party/blink/renderer/core/css/local_font_face_source.cc
index df60a91fc0a..d9fe77b710e 100644
--- a/chromium/third_party/blink/renderer/core/css/local_font_face_source.cc
+++ b/chromium/third_party/blink/renderer/core/css/local_font_face_source.cc
@@ -13,7 +13,7 @@
#include "third_party/blink/renderer/platform/fonts/font_selector.h"
#include "third_party/blink/renderer/platform/fonts/font_unique_name_lookup.h"
#include "third_party/blink/renderer/platform/fonts/simple_font_data.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
@@ -33,10 +33,7 @@ LocalFontFaceSource::LocalFontFaceSource(CSSFontFace* css_font_face,
const String& font_name)
: face_(css_font_face),
font_selector_(font_selector),
- font_name_(font_name),
- weak_factory_(this) {
- was_resolved_ = IsLocalNonBlocking();
-}
+ font_name_(font_name) {}
LocalFontFaceSource::~LocalFontFaceSource() {}
@@ -80,7 +77,6 @@ scoped_refptr<SimpleFontData> LocalFontFaceSource::CreateFontData(
return CreateLoadingFallbackFontData(font_description);
}
- DCHECK(was_resolved_);
// FIXME(drott) crbug.com/627143: We still have the issue of matching
// family name instead of postscript name for local fonts. However, we
// should definitely not try to take into account the full requested
@@ -119,8 +115,6 @@ void LocalFontFaceSource::BeginLoadIfNeeded() {
}
void LocalFontFaceSource::NotifyFontUniqueNameLookupReady() {
- was_resolved_ = IsLocalFontAvailable(FontDescription());
-
PruneTable();
if (face_->FontLoaded(this)) {
@@ -141,7 +135,7 @@ bool LocalFontFaceSource::IsLoading() const {
}
bool LocalFontFaceSource::IsValid() const {
- return IsLoading() || was_resolved_;
+ return IsLoading() || IsLocalFontAvailable(FontDescription());
}
void LocalFontFaceSource::LocalFontHistograms::Record(bool load_success) {
diff --git a/chromium/third_party/blink/renderer/core/css/local_font_face_source.h b/chromium/third_party/blink/renderer/core/css/local_font_face_source.h
index 04ba160fee3..b96de2fc570 100644
--- a/chromium/third_party/blink/renderer/core/css/local_font_face_source.h
+++ b/chromium/third_party/blink/renderer/core/css/local_font_face_source.h
@@ -7,7 +7,7 @@
#include "base/memory/weak_ptr.h"
#include "third_party/blink/renderer/core/css/css_font_face_source.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
namespace blink {
@@ -73,10 +73,9 @@ class LocalFontFaceSource final : public CSSFontFaceSource,
Member<CSSFontFace> face_;
Member<FontSelector> font_selector_;
- bool was_resolved_ = false;
AtomicString font_name_;
LocalFontHistograms histograms_;
- base::WeakPtrFactory<LocalFontFaceSource> weak_factory_;
+ base::WeakPtrFactory<LocalFontFaceSource> weak_factory_{this};
};
} // namespace blink
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 976f70d400c..ad3352a2bc5 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
@@ -10,6 +10,7 @@
"color",
"color-index",
"color-gamut",
+ "forced-colors",
"grid",
"monochrome",
"height",
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 28b9ba20a4e..fcbc000c165 100644
--- a/chromium/third_party/blink/renderer/core/css/media_query.cc
+++ b/chromium/third_party/blink/renderer/core/css/media_query.cc
@@ -70,7 +70,7 @@ String MediaQuery::Serialize() const {
}
static bool ExpressionCompare(const MediaQueryExp& a, const MediaQueryExp& b) {
- return CodePointCompare(a.Serialize(), b.Serialize()) < 0;
+ return CodeUnitCompare(a.Serialize(), b.Serialize()) < 0;
}
std::unique_ptr<MediaQuery> MediaQuery::CreateNotAll() {
diff --git a/chromium/third_party/blink/renderer/core/css/media_query.h b/chromium/third_party/blink/renderer/core/css/media_query.h
index 8488b7171cc..95f350879e7 100644
--- a/chromium/third_party/blink/renderer/core/css/media_query.h
+++ b/chromium/third_party/blink/renderer/core/css/media_query.h
@@ -34,7 +34,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/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.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"
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 a5b29d9970c..b07a8ed5201 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
@@ -29,6 +29,7 @@
#include "third_party/blink/renderer/core/css/media_query_evaluator.h"
+#include "third_party/blink/public/common/css/forced_colors.h"
#include "third_party/blink/public/common/css/preferred_color_scheme.h"
#include "third_party/blink/public/common/manifest/web_display_mode.h"
#include "third_party/blink/public/platform/pointer_properties.h"
@@ -47,11 +48,11 @@
#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/settings.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#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/platform/geometry/float_rect.h"
#include "third_party/blink/renderer/platform/graphics/color_space_gamut.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
namespace blink {
@@ -847,6 +848,24 @@ static bool PrefersColorSchemeMediaFeatureEval(
value.id == CSSValueID::kLight);
}
+static bool ForcedColorsMediaFeatureEval(const MediaQueryExpValue& value,
+ MediaFeaturePrefix,
+ const MediaValues& media_values) {
+ ForcedColors forced_colors = media_values.GetForcedColors();
+
+ if (!value.IsValid())
+ return forced_colors != ForcedColors::kNone;
+
+ if (!value.is_id)
+ return false;
+
+ // Check the forced colors against value.id.
+ return (forced_colors == ForcedColors::kNone &&
+ value.id == CSSValueID::kNone) ||
+ (forced_colors != ForcedColors::kNone &&
+ value.id == CSSValueID::kActive);
+}
+
void MediaQueryEvaluator::Init() {
// Create the table.
g_function_map = new FunctionMap;
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 07ef2cb0a6f..1a00fa9667c 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
@@ -15,6 +15,7 @@
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/media_type_names.h"
#include "third_party/blink/renderer/core/testing/dummy_page_holder.h"
+#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
namespace blink {
@@ -173,6 +174,18 @@ MediaQueryEvaluatorTestCase g_non_ua_sheet_immersive_test_cases[] = {
{nullptr, 0} // Do not remove the terminator line.
};
+MediaQueryEvaluatorTestCase g_forcedcolors_active_cases[] = {
+ {"(forced-colors: active)", 1},
+ {"(forced-colors: none)", 0},
+ {nullptr, 0} // Do not remove the terminator line.
+};
+
+MediaQueryEvaluatorTestCase g_forcedcolors_none_cases[] = {
+ {"(forced-colors: active)", 0},
+ {"(forced-colors: none)", 1},
+ {nullptr, 0} // Do not remove the terminator line.
+};
+
void TestMQEvaluator(MediaQueryEvaluatorTestCase* test_cases,
const MediaQueryEvaluator& media_query_evaluator,
CSSParserMode mode) {
@@ -326,4 +339,24 @@ TEST(MediaQueryEvaluatorTest, DynamicImmersive) {
TestMQEvaluator(g_immersive_test_cases, media_query_evaluator, kUASheetMode);
}
+TEST(MediaQueryEvaluatorTest, CachedForcedColors) {
+ ScopedForcedColorsForTest scoped_feature(true);
+
+ MediaValuesCached::MediaValuesCachedData data;
+ data.forced_colors = ForcedColors::kNone;
+ MediaValues* media_values = MakeGarbageCollected<MediaValuesCached>(data);
+
+ // Forced colors - none.
+ MediaQueryEvaluator media_query_evaluator(*media_values);
+ TestMQEvaluator(g_forcedcolors_none_cases, media_query_evaluator);
+
+ // Forced colors - active.
+ {
+ data.forced_colors = ForcedColors::kActive;
+ MediaValues* media_values = MakeGarbageCollected<MediaValuesCached>(data);
+ MediaQueryEvaluator media_query_evaluator(*media_values);
+ TestMQEvaluator(g_forcedcolors_active_cases, media_query_evaluator);
+ }
+}
+
} // namespace blink
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 89f5eca7b62..07350e9b590 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
@@ -29,6 +29,9 @@
#include "third_party/blink/renderer/core/css/media_query_exp.h"
+#include "third_party/blink/renderer/core/css/css_math_expression_node.h"
+#include "third_party/blink/renderer/core/css/css_math_function_value.h"
+#include "third_party/blink/renderer/core/css/css_numeric_literal_value.h"
#include "third_party/blink/renderer/core/css/parser/css_parser_token_range.h"
#include "third_party/blink/renderer/core/css/parser/css_property_parser_helpers.h"
#include "third_party/blink/renderer/core/html/parser/html_parser_idioms.h"
@@ -85,6 +88,12 @@ static inline bool FeatureWithValidIdent(const String& media_feature,
if (media_feature == kPrefersReducedMotionMediaFeature)
return ident == CSSValueID::kNoPreference || ident == CSSValueID::kReduce;
+ if (RuntimeEnabledFeatures::ForcedColorsEnabled()) {
+ if (media_feature == kForcedColorsMediaFeature) {
+ return ident == CSSValueID::kNone || ident == CSSValueID::kActive;
+ }
+ }
+
return false;
}
@@ -111,13 +120,7 @@ static inline bool FeatureWithValidPositiveLength(
static inline bool FeatureWithValidDensity(const String& media_feature,
const CSSPrimitiveValue* value) {
- if ((value->TypeWithCalcResolved() !=
- CSSPrimitiveValue::UnitType::kDotsPerPixel &&
- value->TypeWithCalcResolved() !=
- CSSPrimitiveValue::UnitType::kDotsPerInch &&
- value->TypeWithCalcResolved() !=
- CSSPrimitiveValue::UnitType::kDotsPerCentimeter) ||
- value->GetDoubleValue() <= 0)
+ if (!value->IsResolution() || value->GetDoubleValue() <= 0)
return false;
return media_feature == kResolutionMediaFeature ||
@@ -141,7 +144,7 @@ static inline bool FeatureExpectingPositiveInteger(
static inline bool FeatureWithPositiveInteger(const String& media_feature,
const CSSPrimitiveValue* value) {
- if (value->TypeWithCalcResolved() != CSSPrimitiveValue::UnitType::kInteger)
+ if (!value->IsInteger())
return false;
return FeatureExpectingPositiveInteger(media_feature);
}
@@ -159,7 +162,7 @@ static inline bool FeatureWithPositiveNumber(const String& media_feature,
static inline bool FeatureWithZeroOrOne(const String& media_feature,
const CSSPrimitiveValue* value) {
- if (value->TypeWithCalcResolved() != CSSPrimitiveValue::UnitType::kInteger ||
+ if (!value->IsInteger() ||
!(value->GetDoubleValue() == 1 || !value->GetDoubleValue()))
return false;
@@ -201,7 +204,8 @@ static inline bool FeatureWithoutValue(const String& media_feature) {
media_feature == kColorGamutMediaFeature ||
media_feature == kImmersiveMediaFeature ||
media_feature == kPrefersColorSchemeMediaFeature ||
- media_feature == kPrefersReducedMotionMediaFeature;
+ media_feature == kPrefersReducedMotionMediaFeature ||
+ media_feature == kForcedColorsMediaFeature;
}
bool MediaQueryExp::IsViewportDependent() const {
@@ -262,51 +266,93 @@ MediaQueryExp MediaQueryExp::Create(const String& media_feature,
}
if (!value)
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)) {
- if (value->TypeWithCalcResolved() !=
- CSSPrimitiveValue::UnitType::kInteger ||
- value->GetDoubleValue() == 0)
- return Invalid();
- if (!css_property_parser_helpers::ConsumeSlashIncludingWhitespace(range))
- return Invalid();
- CSSPrimitiveValue* denominator =
- css_property_parser_helpers::ConsumePositiveInteger(range);
- if (!denominator)
+
+ if (!value) {
+ if (CSSIdentifierValue* ident =
+ css_property_parser_helpers::ConsumeIdent(range)) {
+ CSSValueID ident_id = ident->GetValueID();
+ if (!FeatureWithValidIdent(lower_media_feature, ident_id))
return Invalid();
+ exp_value.id = ident_id;
+ exp_value.is_id = true;
+ return MediaQueryExp(lower_media_feature, exp_value);
+ }
+ if (FeatureWithoutValue(lower_media_feature)) {
+ // Valid, creates a MediaQueryExp with an 'invalid' MediaQueryExpValue
+ return MediaQueryExp(lower_media_feature, exp_value);
+ }
+ return Invalid();
+ }
+
+ // Now we have |value| as a number, length or resolution
+ // Create value for media query expression that must have 1 or more values.
+ if (FeatureWithAspectRatio(lower_media_feature)) {
+ if (!value->IsInteger() || value->GetDoubleValue() == 0)
+ return Invalid();
+ if (!css_property_parser_helpers::ConsumeSlashIncludingWhitespace(range))
+ return Invalid();
+ CSSPrimitiveValue* denominator =
+ css_property_parser_helpers::ConsumePositiveInteger(range);
+ if (!denominator)
+ return Invalid();
+
+ exp_value.numerator = clampTo<unsigned>(value->GetDoubleValue());
+ exp_value.denominator = clampTo<unsigned>(denominator->GetDoubleValue());
+ exp_value.is_ratio = true;
+ return MediaQueryExp(lower_media_feature, exp_value);
+ }
+
+ if (FeatureWithValidDensity(lower_media_feature, value)) {
+ // TODO(crbug.com/983613): Support resolution in math functions.
+ DCHECK(value->IsNumericLiteralValue());
+ const auto* numeric_literal = To<CSSNumericLiteralValue>(value);
+ exp_value.value = numeric_literal->DoubleValue();
+ exp_value.unit = numeric_literal->GetType();
+ exp_value.is_value = true;
+ return MediaQueryExp(lower_media_feature, exp_value);
+ }
+
+ if (FeatureWithPositiveInteger(lower_media_feature, value) ||
+ FeatureWithPositiveNumber(lower_media_feature, value) ||
+ FeatureWithZeroOrOne(lower_media_feature, value)) {
+ exp_value.value = value->GetDoubleValue();
+ exp_value.unit = CSSPrimitiveValue::UnitType::kNumber;
+ exp_value.is_value = true;
+ return MediaQueryExp(lower_media_feature, exp_value);
+ }
- exp_value.numerator = clampTo<unsigned>(value->GetDoubleValue());
- exp_value.denominator = clampTo<unsigned>(denominator->GetDoubleValue());
- exp_value.is_ratio = true;
- } else if (FeatureWithValidDensity(lower_media_feature, value) ||
- FeatureWithValidPositiveLength(lower_media_feature, value) ||
- FeatureWithPositiveInteger(lower_media_feature, value) ||
- FeatureWithPositiveNumber(lower_media_feature, value) ||
- FeatureWithZeroOrOne(lower_media_feature, value)) {
+ if (FeatureWithValidPositiveLength(lower_media_feature, value)) {
+ if (value->IsNumber()) {
exp_value.value = value->GetDoubleValue();
- if (value->IsNumber())
- exp_value.unit = CSSPrimitiveValue::UnitType::kNumber;
- else
- exp_value.unit = value->TypeWithCalcResolved();
+ exp_value.unit = CSSPrimitiveValue::UnitType::kNumber;
exp_value.is_value = true;
- } else {
- return Invalid();
+ return MediaQueryExp(lower_media_feature, exp_value);
+ }
+
+ DCHECK(value->IsLength());
+ if (const auto* numeric_literal =
+ DynamicTo<CSSNumericLiteralValue>(value)) {
+ exp_value.value = numeric_literal->GetDoubleValue();
+ exp_value.unit = numeric_literal->GetType();
+ exp_value.is_value = true;
+ return MediaQueryExp(lower_media_feature, exp_value);
}
- } else if (CSSIdentifierValue* ident =
- css_property_parser_helpers::ConsumeIdent(range)) {
- CSSValueID ident_id = ident->GetValueID();
- if (!FeatureWithValidIdent(lower_media_feature, ident_id))
+
+ const auto* math_value = To<CSSMathFunctionValue>(value);
+ CSSPrimitiveValue::UnitType expression_unit =
+ math_value->ExpressionNode()->ResolvedUnitType();
+ if (expression_unit == CSSPrimitiveValue::UnitType::kUnknown) {
+ // TODO(crbug.com/982542): Support math expressions involving type
+ // conversions properly. For example, calc(10px + 1em).
return Invalid();
- exp_value.id = ident_id;
- exp_value.is_id = true;
- } else if (FeatureWithoutValue(lower_media_feature)) {
- // Valid, creates a MediaQueryExp with an 'invalid' MediaQueryExpValue
- } else {
- return Invalid();
+ }
+ exp_value.value = math_value->DoubleValue();
+ exp_value.unit = expression_unit;
+ exp_value.is_value = true;
+ return MediaQueryExp(lower_media_feature, exp_value);
}
- return MediaQueryExp(lower_media_feature, exp_value);
+ return Invalid();
}
MediaQueryExp::~MediaQueryExp() = default;
diff --git a/chromium/third_party/blink/renderer/core/css/media_query_exp.h b/chromium/third_party/blink/renderer/core/css/media_query_exp.h
index b25fd51f8e1..7650002aefa 100644
--- a/chromium/third_party/blink/renderer/core/css/media_query_exp.h
+++ b/chromium/third_party/blink/renderer/core/css/media_query_exp.h
@@ -34,7 +34,7 @@
#include "third_party/blink/renderer/core/css/css_value.h"
#include "third_party/blink/renderer/core/css/media_feature_names.h"
#include "third_party/blink/renderer/core/css_value_keywords.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/css/media_query_set_test.cc b/chromium/third_party/blink/renderer/core/css/media_query_set_test.cc
index abc7506b1ee..603ae1dec74 100644
--- a/chromium/third_party/blink/renderer/core/css/media_query_set_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/media_query_set_test.cc
@@ -28,9 +28,9 @@ static void TestMediaQuery(MediaQuerySetTestCase test,
output.Append(", ");
}
if (test.output)
- ASSERT_STREQ(test.output, output.ToString().Ascii().data());
+ ASSERT_EQ(test.output, output.ToString());
else
- ASSERT_STREQ(test.input, output.ToString().Ascii().data());
+ ASSERT_EQ(test.input, output.ToString());
}
TEST(MediaQuerySetTest, Basic) {
diff --git a/chromium/third_party/blink/renderer/core/css/media_values.cc b/chromium/third_party/blink/renderer/core/css/media_values.cc
index c1d76bfe7db..c31ccf36536 100644
--- a/chromium/third_party/blink/renderer/core/css/media_values.cc
+++ b/chromium/third_party/blink/renderer/core/css/media_values.cc
@@ -190,6 +190,13 @@ bool MediaValues::CalculatePrefersReducedMotion(LocalFrame* frame) {
return frame->GetSettings()->GetPrefersReducedMotion();
}
+ForcedColors MediaValues::CalculateForcedColors(LocalFrame* frame) {
+ DCHECK(frame);
+ DCHECK(frame->GetSettings());
+ DCHECK(frame->GetDocument());
+ return frame->GetDocument()->GetStyleEngine().GetForcedColors();
+}
+
bool MediaValues::ComputeLengthImpl(double value,
CSSPrimitiveValue::UnitType type,
unsigned default_font_size,
diff --git a/chromium/third_party/blink/renderer/core/css/media_values.h b/chromium/third_party/blink/renderer/core/css/media_values.h
index 6920db0e78a..445c19b47e0 100644
--- a/chromium/third_party/blink/renderer/core/css/media_values.h
+++ b/chromium/third_party/blink/renderer/core/css/media_values.h
@@ -19,6 +19,7 @@ class CSSPrimitiveValue;
class LocalFrame;
enum class ColorSpaceGamut;
enum class PreferredColorScheme;
+enum class ForcedColors;
class CORE_EXPORT MediaValues : public GarbageCollectedFinalized<MediaValues> {
public:
@@ -79,6 +80,7 @@ class CORE_EXPORT MediaValues : public GarbageCollectedFinalized<MediaValues> {
virtual ColorSpaceGamut ColorGamut() const = 0;
virtual PreferredColorScheme GetPreferredColorScheme() const = 0;
virtual bool PrefersReducedMotion() const = 0;
+ virtual ForcedColors GetForcedColors() const = 0;
protected:
static double CalculateViewportWidth(LocalFrame*);
@@ -102,6 +104,7 @@ class CORE_EXPORT MediaValues : public GarbageCollectedFinalized<MediaValues> {
static ColorSpaceGamut CalculateColorGamut(LocalFrame*);
static PreferredColorScheme CalculatePreferredColorScheme(LocalFrame*);
static bool CalculatePrefersReducedMotion(LocalFrame*);
+ static ForcedColors CalculateForcedColors(LocalFrame*);
};
} // namespace blink
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 58b9b3c43ff..7da0eaf41bf 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
@@ -4,6 +4,7 @@
#include "third_party/blink/renderer/core/css/media_values_cached.h"
+#include "third_party/blink/public/common/css/forced_colors.h"
#include "third_party/blink/public/common/css/preferred_color_scheme.h"
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
#include "third_party/blink/renderer/core/dom/document.h"
@@ -33,7 +34,8 @@ MediaValuesCached::MediaValuesCachedData::MediaValuesCachedData()
display_shape(kDisplayShapeRect),
color_gamut(ColorSpaceGamut::kUnknown),
preferred_color_scheme(PreferredColorScheme::kNoPreference),
- prefers_reduced_motion(false) {}
+ prefers_reduced_motion(false),
+ forced_colors(ForcedColors::kNone) {}
MediaValuesCached::MediaValuesCachedData::MediaValuesCachedData(
Document& document)
@@ -74,6 +76,7 @@ MediaValuesCached::MediaValuesCachedData::MediaValuesCachedData(
color_gamut = MediaValues::CalculateColorGamut(frame);
preferred_color_scheme = MediaValues::CalculatePreferredColorScheme(frame);
prefers_reduced_motion = MediaValues::CalculatePrefersReducedMotion(frame);
+ forced_colors = MediaValues::CalculateForcedColors(frame);
}
}
@@ -196,4 +199,8 @@ bool MediaValuesCached::PrefersReducedMotion() const {
return data_.prefers_reduced_motion;
}
+ForcedColors MediaValuesCached::GetForcedColors() const {
+ return data_.forced_colors;
+}
+
} // namespace blink
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 96df16f2799..3d123a79841 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
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/css/media_values.h"
-#include "third_party/blink/renderer/platform/cross_thread_copier.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_copier.h"
namespace blink {
@@ -38,6 +38,7 @@ class CORE_EXPORT MediaValuesCached final : public MediaValues {
ColorSpaceGamut color_gamut;
PreferredColorScheme preferred_color_scheme;
bool prefers_reduced_motion;
+ ForcedColors forced_colors;
MediaValuesCachedData();
explicit MediaValuesCachedData(Document&);
@@ -65,6 +66,7 @@ class CORE_EXPORT MediaValuesCached final : public MediaValues {
data.color_gamut = color_gamut;
data.preferred_color_scheme = preferred_color_scheme;
data.prefers_reduced_motion = prefers_reduced_motion;
+ data.forced_colors = forced_colors;
return data;
}
};
@@ -103,6 +105,7 @@ class CORE_EXPORT MediaValuesCached final : public MediaValues {
ColorSpaceGamut ColorGamut() const override;
PreferredColorScheme GetPreferredColorScheme() const override;
bool PrefersReducedMotion() const override;
+ ForcedColors GetForcedColors() const override;
void OverrideViewportDimensions(double width, double height) override;
@@ -110,14 +113,16 @@ class CORE_EXPORT MediaValuesCached final : public MediaValues {
MediaValuesCachedData data_;
};
+} // namespace blink
+
+namespace WTF {
+
template <>
-struct CrossThreadCopier<MediaValuesCached::MediaValuesCachedData> {
- typedef MediaValuesCached::MediaValuesCachedData Type;
- static Type Copy(const MediaValuesCached::MediaValuesCachedData& data) {
- return data.DeepCopy();
- }
+struct CrossThreadCopier<blink::MediaValuesCached::MediaValuesCachedData> {
+ typedef blink::MediaValuesCached::MediaValuesCachedData Type;
+ static Type Copy(const Type& data) { return data.DeepCopy(); }
};
-} // namespace blink
+} // namespace WTF
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_MEDIA_VALUES_CACHED_H_
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 54ef0444601..59488e77e1f 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
@@ -4,6 +4,7 @@
#include "third_party/blink/renderer/core/css/media_values_dynamic.h"
+#include "third_party/blink/public/common/css/forced_colors.h"
#include "third_party/blink/public/common/css/preferred_color_scheme.h"
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
#include "third_party/blink/renderer/core/css/css_resolution_units.h"
@@ -150,6 +151,10 @@ bool MediaValuesDynamic::PrefersReducedMotion() const {
return CalculatePrefersReducedMotion(frame_);
}
+ForcedColors MediaValuesDynamic::GetForcedColors() const {
+ return CalculateForcedColors(frame_);
+}
+
Document* MediaValuesDynamic::GetDocument() const {
return frame_->GetDocument();
}
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 5bdddf75b0a..95c454e1fac 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
@@ -50,6 +50,7 @@ class CORE_EXPORT MediaValuesDynamic : public MediaValues {
ColorSpaceGamut ColorGamut() const override;
PreferredColorScheme GetPreferredColorScheme() const override;
bool PrefersReducedMotion() const override;
+ ForcedColors GetForcedColors() const override;
Document* GetDocument() const override;
bool HasValues() const override;
void OverrideViewportDimensions(double width, double height) override;
diff --git a/chromium/third_party/blink/renderer/core/css/offscreen_font_selector.cc b/chromium/third_party/blink/renderer/core/css/offscreen_font_selector.cc
index f78ea572608..3534b670ca1 100644
--- a/chromium/third_party/blink/renderer/core/css/offscreen_font_selector.cc
+++ b/chromium/third_party/blink/renderer/core/css/offscreen_font_selector.cc
@@ -10,11 +10,11 @@
#include "third_party/blink/renderer/core/css/resolver/style_resolver.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"
#include "third_party/blink/renderer/core/loader/frame_loader.h"
#include "third_party/blink/renderer/platform/fonts/font_cache.h"
#include "third_party/blink/renderer/platform/fonts/font_selector_client.h"
#include "third_party/blink/renderer/platform/fonts/simple_font_data.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
namespace blink {
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 b0d61a78f1c..52a5b162b4b 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
@@ -4,13 +4,16 @@
#include "third_party/blink/renderer/core/css/parser/at_rule_descriptor_parser.h"
+#include "third_party/blink/renderer/core/css/css_custom_property_declaration.h"
#include "third_party/blink/renderer/core/css/css_font_face_src_value.h"
+#include "third_party/blink/renderer/core/css/css_string_value.h"
#include "third_party/blink/renderer/core/css/css_unicode_range_value.h"
#include "third_party/blink/renderer/core/css/css_value.h"
#include "third_party/blink/renderer/core/css/parser/css_parser_context.h"
#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/css/parser/css_tokenizer.h"
+#include "third_party/blink/renderer/core/css/parser/css_variable_parser.h"
#include "third_party/blink/renderer/core/css/properties/css_parsing_utils.h"
#include "third_party/blink/renderer/core/css/properties/css_property.h"
@@ -75,7 +78,8 @@ CSSValue* ConsumeFontFaceSrcURI(CSSParserTokenRange& range,
return nullptr;
CSSFontFaceSrcValue* uri_value(CSSFontFaceSrcValue::Create(
url, context.CompleteURL(url), context.GetReferrer(),
- context.ShouldCheckContentSecurityPolicy()));
+ context.ShouldCheckContentSecurityPolicy(),
+ context.IsOriginClean() ? OriginClean::kTrue : OriginClean::kFalse));
if (range.Peek().FunctionId() != CSSValueID::kFormat)
return uri_value;
@@ -103,14 +107,16 @@ CSSValue* ConsumeFontFaceSrcLocal(CSSParserTokenRange& range,
if (!args.AtEnd())
return nullptr;
return CSSFontFaceSrcValue::CreateLocal(
- arg.Value().ToString(), should_check_content_security_policy);
+ arg.Value().ToString(), should_check_content_security_policy,
+ context.IsOriginClean() ? OriginClean::kTrue : OriginClean::kFalse);
}
if (args.Peek().GetType() == kIdentToken) {
String family_name = css_parsing_utils::ConcatenateFamilyName(args);
if (!args.AtEnd())
return nullptr;
return CSSFontFaceSrcValue::CreateLocal(
- family_name, should_check_content_security_policy);
+ family_name, should_check_content_security_policy,
+ context.IsOriginClean() ? OriginClean::kTrue : OriginClean::kFalse);
}
return nullptr;
}
@@ -209,14 +215,53 @@ CSSValue* AtRuleDescriptorParser::ParseFontFaceDeclaration(
return ParseFontFaceDescriptor(id, range, context);
}
+CSSValue* AtRuleDescriptorParser::ParseAtPropertyDescriptor(
+ AtRuleDescriptorID id,
+ CSSParserTokenRange& range,
+ const CSSParserContext& context) {
+ CSSValue* parsed_value = nullptr;
+ switch (id) {
+ case AtRuleDescriptorID::Syntax:
+ range.ConsumeWhitespace();
+ parsed_value = css_property_parser_helpers::ConsumeString(range);
+ break;
+ case AtRuleDescriptorID::InitialValue: {
+ // Note that we must retain leading whitespace here.
+ return CSSVariableParser::ParseDeclarationValue(
+ g_null_atom, range, false /* is_animation_tainted */, context);
+ }
+ case AtRuleDescriptorID::Inherits:
+ range.ConsumeWhitespace();
+ parsed_value =
+ css_property_parser_helpers::ConsumeIdent<CSSValueID::kTrue,
+ CSSValueID::kFalse>(range);
+ break;
+ default:
+ break;
+ }
+
+ if (!parsed_value || !range.AtEnd())
+ return nullptr;
+
+ return parsed_value;
+}
+
bool AtRuleDescriptorParser::ParseAtRule(
AtRuleDescriptorID id,
CSSParserTokenRange& range,
const CSSParserContext& context,
HeapVector<CSSPropertyValue, 256>& parsed_descriptors) {
+ const CSSParserTokenRange original_range = range;
+
// TODO(meade): Handle other descriptor types here.
CSSValue* result =
AtRuleDescriptorParser::ParseFontFaceDescriptor(id, range, context);
+
+ if (!result) {
+ range = original_range;
+ result =
+ AtRuleDescriptorParser::ParseAtPropertyDescriptor(id, range, context);
+ }
if (!result)
return false;
// Convert to CSSPropertyID for legacy compatibility,
diff --git a/chromium/third_party/blink/renderer/core/css/parser/at_rule_descriptor_parser.h b/chromium/third_party/blink/renderer/core/css/parser/at_rule_descriptor_parser.h
index 51a30a7b651..9b275e7e0ad 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/at_rule_descriptor_parser.h
+++ b/chromium/third_party/blink/renderer/core/css/parser/at_rule_descriptor_parser.h
@@ -31,6 +31,9 @@ class AtRuleDescriptorParser {
const CSSParserContext&);
static CSSValue* ParseFontFaceDeclaration(CSSParserTokenRange&,
const CSSParserContext&);
+ static CSSValue* ParseAtPropertyDescriptor(AtRuleDescriptorID,
+ CSSParserTokenRange&,
+ const CSSParserContext&);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/parser/at_rule_names.json5 b/chromium/third_party/blink/renderer/core/css/parser/at_rule_names.json5
index ccd71f4b8f4..c5c1f0023d3 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/at_rule_names.json5
+++ b/chromium/third_party/blink/renderer/core/css/parser/at_rule_names.json5
@@ -40,6 +40,12 @@
name: "height",
},
{
+ name: "inherits"
+ },
+ {
+ name: "initial-value"
+ },
+ {
name: "max-height",
},
{
@@ -64,6 +70,9 @@
name: "src",
},
{
+ name: "syntax"
+ },
+ {
name: "unicode-range",
},
{
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 d9850ed87ce..c6414cf0ba0 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
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/css/parser/css_at_rule_id.h"
#include "third_party/blink/renderer/core/css/parser/css_parser_context.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
@@ -26,6 +26,8 @@ CSSAtRuleID CssAtRuleID(StringView name) {
return kCSSAtRuleNamespace;
if (EqualIgnoringASCIICase(name, "page"))
return kCSSAtRulePage;
+ if (EqualIgnoringASCIICase(name, "property"))
+ return kCSSAtRuleProperty;
if (EqualIgnoringASCIICase(name, "supports"))
return kCSSAtRuleSupports;
if (EqualIgnoringASCIICase(name, "viewport"))
@@ -63,6 +65,9 @@ void CountAtRule(const CSSParserContext* context, CSSAtRuleID rule_id) {
case kCSSAtRulePage:
feature = WebFeature::kCSSAtRulePage;
break;
+ case kCSSAtRuleProperty:
+ feature = WebFeature::kCSSAtRuleProperty;
+ return;
case kCSSAtRuleSupports:
feature = WebFeature::kCSSAtRuleSupports;
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 89404368c14..73fa0fdaaca 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
@@ -21,6 +21,7 @@ enum CSSAtRuleID {
kCSSAtRuleMedia,
kCSSAtRuleNamespace,
kCSSAtRulePage,
+ kCSSAtRuleProperty,
kCSSAtRuleSupports,
kCSSAtRuleViewport,
kCSSAtRuleWebkitKeyframes,
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 387d1f69112..2d4ad53c69c 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
@@ -6,8 +6,8 @@
#include "third_party/blink/renderer/core/css/parser/css_parser_token_stream.h"
#include "third_party/blink/renderer/core/dom/document.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
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 933342daa70..659c2139a0f 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
@@ -135,7 +135,6 @@ MutableCSSPropertyValueSet::SetResult CSSParser::ParseValue(
MutableCSSPropertyValueSet::SetResult CSSParser::ParseValueForCustomProperty(
MutableCSSPropertyValueSet* declaration,
const AtomicString& property_name,
- const PropertyRegistry* registry,
const String& value,
bool important,
SecureContextMode secure_context_mode,
@@ -157,8 +156,8 @@ MutableCSSPropertyValueSet::SetResult CSSParser::ParseValueForCustomProperty(
context = MakeGarbageCollected<CSSParserContext>(parser_mode,
secure_context_mode);
}
- return CSSParserImpl::ParseVariableValue(declaration, property_name, registry,
- value, important, context,
+ return CSSParserImpl::ParseVariableValue(declaration, property_name, value,
+ important, context,
is_animation_tainted);
}
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 e13bb6c4f01..d53b6f0a12b 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
@@ -69,7 +69,6 @@ class CORE_EXPORT CSSParser {
static MutableCSSPropertyValueSet::SetResult ParseValueForCustomProperty(
MutableCSSPropertyValueSet*,
const AtomicString& property_name,
- const PropertyRegistry*,
const String& value,
bool important,
SecureContextMode,
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 cf9555494f7..7740ac294b9 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
@@ -156,8 +156,8 @@ CSSParserContext::CSSParserContext(
ContentSecurityPolicyDisposition policy_disposition,
const Document* use_counter_document)
: base_url_(base_url),
+ should_check_content_security_policy_(policy_disposition),
origin_clean_(origin_clean),
- charset_(charset),
mode_(mode),
match_mode_(match_mode),
profile_(profile),
@@ -166,7 +166,7 @@ CSSParserContext::CSSParserContext(
use_legacy_background_size_shorthand_behavior_(
use_legacy_background_size_shorthand_behavior),
secure_context_mode_(secure_context_mode),
- should_check_content_security_policy_(policy_disposition),
+ charset_(charset),
document_(use_counter_document) {}
bool CSSParserContext::operator==(const CSSParserContext& other) const {
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 d6f870b45e0..c7435d8330f 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
@@ -27,7 +27,7 @@ class CORE_EXPORT CSSParserContext
: public GarbageCollectedFinalized<CSSParserContext> {
public:
// https://drafts.csswg.org/selectors/#profiles
- enum SelectorProfile { kLiveProfile, kSnapshotProfile };
+ enum SelectorProfile : uint8_t { kLiveProfile, kSnapshotProfile };
// All three of these constructors copy the context and override the current
// Document handle used for UseCounter.
@@ -131,11 +131,12 @@ class CORE_EXPORT CSSParserContext
private:
KURL base_url_;
+ ContentSecurityPolicyDisposition should_check_content_security_policy_;
+
// If true, allows reading and modifying of the CSS rules.
// https://drafts.csswg.org/cssom/#concept-css-style-sheet-origin-clean-flag
const bool origin_clean_;
- WTF::TextEncoding charset_;
CSSParserMode mode_;
CSSParserMode match_mode_;
SelectorProfile profile_ = kLiveProfile;
@@ -143,7 +144,8 @@ class CORE_EXPORT CSSParserContext
bool is_html_document_;
bool use_legacy_background_size_shorthand_behavior_;
SecureContextMode secure_context_mode_;
- ContentSecurityPolicyDisposition should_check_content_security_policy_;
+
+ WTF::TextEncoding charset_;
WeakMember<const Document> document_;
};
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 c9a14f8eeb5..5578a01ce92 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
@@ -10,6 +10,7 @@
#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_numeric_literal_value.h"
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
#include "third_party/blink/renderer/core/css/css_unset_value.h"
#include "third_party/blink/renderer/core/css/parser/css_parser_idioms.h"
@@ -41,14 +42,6 @@ static inline bool IsSimpleLengthPropertyID(CSSPropertyID property_id,
case CSSPropertyID::kPaddingLeft:
case CSSPropertyID::kPaddingRight:
case CSSPropertyID::kPaddingTop:
- case CSSPropertyID::kScrollMarginBlockEnd:
- case CSSPropertyID::kScrollMarginBlockStart:
- case CSSPropertyID::kScrollMarginBottom:
- case CSSPropertyID::kScrollMarginInlineEnd:
- case CSSPropertyID::kScrollMarginInlineStart:
- case CSSPropertyID::kScrollMarginLeft:
- case CSSPropertyID::kScrollMarginRight:
- case CSSPropertyID::kScrollMarginTop:
case CSSPropertyID::kScrollPaddingBlockEnd:
case CSSPropertyID::kScrollPaddingBlockStart:
case CSSPropertyID::kScrollPaddingBottom:
@@ -152,7 +145,7 @@ static CSSValue* ParseSimpleLengthValue(CSSPropertyID property_id,
if (number < 0 && !accepts_negative_numbers)
return nullptr;
- return CSSPrimitiveValue::Create(number, unit);
+ return CSSNumericLiteralValue::Create(number, unit);
}
static inline bool IsColorPropertyID(CSSPropertyID property_id) {
@@ -631,6 +624,8 @@ bool CSSParserFastPaths::IsValidKeywordPropertyAndValue(
(value_id == CSSValueID::kInlineStart ||
value_id == CSSValueID::kInlineEnd)) ||
value_id == CSSValueID::kNone;
+ case CSSPropertyID::kForcedColorAdjust:
+ return value_id == CSSValueID::kNone || value_id == CSSValueID::kAuto;
case CSSPropertyID::kImageRendering:
return value_id == CSSValueID::kAuto ||
value_id == CSSValueID::kWebkitOptimizeContrast ||
@@ -662,11 +657,9 @@ bool CSSParserFastPaths::IsValidKeywordPropertyAndValue(
case CSSPropertyID::kOverflowWrap:
return value_id == CSSValueID::kNormal ||
value_id == CSSValueID::kBreakWord;
+ case CSSPropertyID::kOverflowBlock:
+ case CSSPropertyID::kOverflowInline:
case CSSPropertyID::kOverflowX:
- return value_id == CSSValueID::kVisible ||
- value_id == CSSValueID::kHidden ||
- value_id == CSSValueID::kScroll || value_id == CSSValueID::kAuto ||
- value_id == CSSValueID::kOverlay;
case CSSPropertyID::kOverflowY:
return value_id == CSSValueID::kVisible ||
value_id == CSSValueID::kHidden ||
@@ -967,9 +960,9 @@ bool CSSParserFastPaths::IsValidKeywordPropertyAndValue(
value_id == CSSValueID::kBreakWord;
case CSSPropertyID::kScrollSnapStop:
return value_id == CSSValueID::kNormal || value_id == CSSValueID::kAlways;
+ case CSSPropertyID::kOverscrollBehaviorInline:
+ case CSSPropertyID::kOverscrollBehaviorBlock:
case CSSPropertyID::kOverscrollBehaviorX:
- return value_id == CSSValueID::kAuto ||
- value_id == CSSValueID::kContain || value_id == CSSValueID::kNone;
case CSSPropertyID::kOverscrollBehaviorY:
return value_id == CSSValueID::kAuto ||
value_id == CSSValueID::kContain || value_id == CSSValueID::kNone;
@@ -1006,6 +999,7 @@ bool CSSParserFastPaths::IsKeywordPropertyID(CSSPropertyID property_id) {
case CSSPropertyID::kEmptyCells:
case CSSPropertyID::kFillRule:
case CSSPropertyID::kFloat:
+ case CSSPropertyID::kForcedColorAdjust:
case CSSPropertyID::kHyphens:
case CSSPropertyID::kImageRendering:
case CSSPropertyID::kListStylePosition:
@@ -1014,6 +1008,8 @@ bool CSSParserFastPaths::IsKeywordPropertyID(CSSPropertyID property_id) {
case CSSPropertyID::kObjectFit:
case CSSPropertyID::kOutlineStyle:
case CSSPropertyID::kOverflowAnchor:
+ case CSSPropertyID::kOverflowBlock:
+ case CSSPropertyID::kOverflowInline:
case CSSPropertyID::kOverflowWrap:
case CSSPropertyID::kOverflowX:
case CSSPropertyID::kOverflowY:
@@ -1024,6 +1020,8 @@ bool CSSParserFastPaths::IsKeywordPropertyID(CSSPropertyID property_id) {
case CSSPropertyID::kPosition:
case CSSPropertyID::kResize:
case CSSPropertyID::kScrollBehavior:
+ case CSSPropertyID::kOverscrollBehaviorInline:
+ case CSSPropertyID::kOverscrollBehaviorBlock:
case CSSPropertyID::kOverscrollBehaviorX:
case CSSPropertyID::kOverscrollBehaviorY:
case CSSPropertyID::kShapeRendering:
@@ -1157,7 +1155,7 @@ static bool ParseTransformTranslateArguments(
if (unit != CSSPrimitiveValue::UnitType::kPixels &&
(number || unit != CSSPrimitiveValue::UnitType::kNumber))
return false;
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
number, CSSPrimitiveValue::UnitType::kPixels));
pos += argument_length + 1;
--expected_count;
@@ -1180,7 +1178,7 @@ static bool ParseTransformNumberArguments(CharType*& pos,
double number = CharactersToDouble(pos, argument_length, &ok);
if (!ok)
return false;
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
number, CSSPrimitiveValue::UnitType::kNumber));
pos += argument_length + 1;
--expected_count;
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 17109539d67..943767ecaa7 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
@@ -9,7 +9,7 @@
#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"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
namespace blink {
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 224e7bef7ea..dd681c46f74 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
@@ -34,9 +34,9 @@
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/frame/deprecation.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
@@ -95,7 +95,6 @@ MutableCSSPropertyValueSet::SetResult CSSParserImpl::ParseValue(
MutableCSSPropertyValueSet::SetResult CSSParserImpl::ParseVariableValue(
MutableCSSPropertyValueSet* declaration,
const AtomicString& property_name,
- const PropertyRegistry* registry,
const String& value,
bool important,
const CSSParserContext* context,
@@ -110,18 +109,6 @@ MutableCSSPropertyValueSet::SetResult CSSParserImpl::ParseVariableValue(
bool did_parse = false;
bool did_change = false;
if (!parser.parsed_properties_.IsEmpty()) {
- const auto* parsed_declaration =
- To<CSSCustomPropertyDeclaration>(parser.parsed_properties_[0].Value());
- if (parsed_declaration->Value() && registry) {
- const PropertyRegistration* registration =
- registry->Registration(property_name);
- // TODO(timloh): This is a bit wasteful, we parse the registered property
- // to validate but throw away the result.
- if (registration &&
- !registration->Syntax().Parse(range, context, is_animation_tainted)) {
- return MutableCSSPropertyValueSet::SetResult{did_parse, did_change};
- }
- }
did_parse = true;
did_change = declaration->AddParsedProperties(parser.parsed_properties_);
}
@@ -546,6 +533,8 @@ StyleRuleBase* CSSParserImpl::ConsumeAtRule(CSSParserTokenStream& stream,
return ConsumeKeyframesRule(false, prelude, prelude_offset, stream);
case kCSSAtRulePage:
return ConsumePageRule(prelude, prelude_offset, stream);
+ case kCSSAtRuleProperty:
+ return ConsumePropertyRule(prelude, prelude_offset, stream);
default:
return nullptr; // Parse error, unrecognised at-rule with block
}
@@ -645,7 +634,8 @@ StyleRuleImport* CSSParserImpl::ConsumeImportRule(
}
return MakeGarbageCollected<StyleRuleImport>(
- uri, MediaQueryParser::ParseMediaQuerySet(prelude));
+ uri, MediaQueryParser::ParseMediaQuerySet(prelude),
+ context_->IsOriginClean() ? OriginClean::kTrue : OriginClean::kFalse);
}
StyleRuleNamespace* CSSParserImpl::ConsumeNamespaceRule(
@@ -863,6 +853,30 @@ StyleRulePage* CSSParserImpl::ConsumePageRule(const CSSParserTokenRange prelude,
CreateCSSPropertyValueSet(parsed_properties_, context_->Mode()));
}
+StyleRuleProperty* CSSParserImpl::ConsumePropertyRule(
+ CSSParserTokenRange prelude,
+ const RangeOffset& prelude_offset,
+ CSSParserTokenStream& block) {
+ if (!RuntimeEnabledFeatures::CSSVariables2AtPropertyEnabled())
+ return nullptr;
+
+ const CSSParserToken& name_token = prelude.ConsumeIncludingWhitespace();
+ if (!prelude.AtEnd())
+ return nullptr;
+ if (!CSSVariableParser::IsValidVariableName(name_token))
+ return nullptr;
+ String name = name_token.Value().ToString();
+
+ if (observer_) {
+ observer_->StartRuleHeader(StyleRule::kProperty, prelude_offset.start);
+ observer_->EndRuleHeader(prelude_offset.end);
+ }
+
+ ConsumeDeclarationList(block, StyleRule::kProperty);
+ return StyleRuleProperty::Create(
+ name, CreateCSSPropertyValueSet(parsed_properties_, context_->Mode()));
+}
+
StyleRuleKeyframe* CSSParserImpl::ConsumeKeyframeStyleRule(
const CSSParserTokenRange prelude,
const RangeOffset& prelude_offset,
@@ -1019,14 +1033,14 @@ void CSSParserImpl::ConsumeDeclaration(CSSParserTokenRange range,
CSSPropertyID unresolved_property = CSSPropertyID::kInvalid;
AtRuleDescriptorID atrule_id = AtRuleDescriptorID::Invalid;
- if (rule_type == StyleRule::kFontFace) {
+ if (rule_type == StyleRule::kFontFace || rule_type == StyleRule::kProperty) {
if (important) // Invalid
return;
atrule_id = lhs.ParseAsAtRuleDescriptorID();
AtRuleDescriptorParser::ParseAtRule(atrule_id, range, *context_,
parsed_properties_);
} else {
- unresolved_property = lhs.ParseAsUnresolvedCSSPropertyID();
+ unresolved_property = lhs.ParseAsUnresolvedCSSPropertyID(context_->Mode());
}
// @rules other than FontFace still handled with legacy code.
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 58c53ab8ebf..7da6c307d80 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
@@ -34,6 +34,7 @@ class StyleRuleKeyframes;
class StyleRuleMedia;
class StyleRuleNamespace;
class StyleRulePage;
+class StyleRuleProperty;
class StyleRuleSupports;
class StyleRuleViewport;
class StyleSheetContents;
@@ -87,7 +88,6 @@ class CSSParserImpl {
static MutableCSSPropertyValueSet::SetResult ParseVariableValue(
MutableCSSPropertyValueSet*,
const AtomicString& property_name,
- const PropertyRegistry*,
const String&,
bool important,
const CSSParserContext*,
@@ -174,6 +174,9 @@ class CSSParserImpl {
StyleRulePage* ConsumePageRule(CSSParserTokenRange prelude,
const RangeOffset& prelude_offset,
CSSParserTokenStream& block);
+ StyleRuleProperty* ConsumePropertyRule(CSSParserTokenRange prelude,
+ const RangeOffset& prelude_offset,
+ CSSParserTokenStream& block);
StyleRuleKeyframe* ConsumeKeyframeStyleRule(CSSParserTokenRange prelude,
const RangeOffset& prelude_offset,
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 d5de80e82ed..95ca3af9681 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
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PARSER_CSS_PARSER_LOCAL_CONTEXT_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/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_parser_mode.h b/chromium/third_party/blink/renderer/core/css/parser/css_parser_mode.h
index f2d9bdead38..d50d3fa1e09 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_parser_mode.h
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_parser_mode.h
@@ -31,10 +31,12 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PARSER_CSS_PARSER_MODE_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PARSER_CSS_PARSER_MODE_H_
+#include <stdint.h>
+
namespace blink {
// Must not grow beyond 3 bits, due to packing in CSSPropertyValueSet.
-enum CSSParserMode {
+enum CSSParserMode : uint8_t {
kHTMLStandardMode,
kHTMLQuirksMode,
// SVG attributes are parsed in quirks mode but rules differ slightly.
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 75c472f2afa..6b564caba83 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
@@ -85,9 +85,10 @@ double CSSParserToken::NumericValue() const {
return numeric_value_;
}
-CSSPropertyID CSSParserToken::ParseAsUnresolvedCSSPropertyID() const {
+CSSPropertyID CSSParserToken::ParseAsUnresolvedCSSPropertyID(
+ CSSParserMode mode) const {
DCHECK_EQ(type_, static_cast<unsigned>(kIdentToken));
- return UnresolvedCSSPropertyID(Value());
+ return UnresolvedCSSPropertyID(Value(), mode);
}
AtRuleDescriptorID CSSParserToken::ParseAsAtRuleDescriptorID() const {
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 9feebcf15a5..3089edce720 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
@@ -8,7 +8,8 @@
#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/parser/at_rule_descriptors.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/core/css/parser/css_parser_mode.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/string_view.h"
namespace blink {
@@ -145,7 +146,8 @@ class CORE_EXPORT CSSParserToken {
bool HasStringBacking() const;
- CSSPropertyID ParseAsUnresolvedCSSPropertyID() const;
+ CSSPropertyID ParseAsUnresolvedCSSPropertyID(
+ CSSParserMode mode = kHTMLStandardMode) const;
AtRuleDescriptorID ParseAsAtRuleDescriptorID() const;
void Serialize(StringBuilder&) const;
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_parser_token_range.h b/chromium/third_party/blink/renderer/core/css/parser/css_parser_token_range.h
index 87a53423aec..61ae46c58e2 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_parser_token_range.h
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_parser_token_range.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/css/parser/css_parser_token.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_parser_token_stream.h b/chromium/third_party/blink/renderer/core/css/parser/css_parser_token_stream.h
index d348ad0d8aa..aad770ab0c6 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_parser_token_stream.h
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_parser_token_stream.h
@@ -8,7 +8,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/css/parser/css_parser_token_range.h"
#include "third_party/blink/renderer/core/css/parser/css_tokenizer.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 1da570e0fc8..db6b8898d6d 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
@@ -168,9 +168,16 @@ bool CSSPropertyParser::ParseValueStart(CSSPropertyID unresolved_property,
return false;
}
+static inline bool IsExposedInMode(const CSSProperty& property,
+ CSSParserMode mode) {
+ return mode == kUASheetMode ? property.IsUAExposed()
+ : property.IsWebExposed();
+}
+
template <typename CharacterType>
static CSSPropertyID UnresolvedCSSPropertyID(const CharacterType* property_name,
- unsigned length) {
+ unsigned length,
+ CSSParserMode mode) {
if (length == 0)
return CSSPropertyID::kInvalid;
if (length >= 2 && property_name[0] == '-' && property_name[1] == '-')
@@ -192,24 +199,26 @@ static CSSPropertyID UnresolvedCSSPropertyID(const CharacterType* property_name,
const Property* hash_table_entry = FindProperty(name, length);
if (!hash_table_entry)
return CSSPropertyID::kInvalid;
- CSSPropertyID property = static_cast<CSSPropertyID>(hash_table_entry->id);
- if (!CSSProperty::Get(resolveCSSPropertyID(property)).IsEnabled())
- return CSSPropertyID::kInvalid;
- return property;
+ CSSPropertyID property_id = static_cast<CSSPropertyID>(hash_table_entry->id);
+ const CSSProperty& property =
+ CSSProperty::Get(resolveCSSPropertyID(property_id));
+ bool exposed = IsExposedInMode(property, mode);
+ return exposed ? property_id : CSSPropertyID::kInvalid;
}
CSSPropertyID unresolvedCSSPropertyID(const String& string) {
unsigned length = string.length();
+ CSSParserMode mode = kHTMLStandardMode;
return string.Is8Bit()
- ? UnresolvedCSSPropertyID(string.Characters8(), length)
- : UnresolvedCSSPropertyID(string.Characters16(), length);
+ ? UnresolvedCSSPropertyID(string.Characters8(), length, mode)
+ : UnresolvedCSSPropertyID(string.Characters16(), length, mode);
}
-CSSPropertyID UnresolvedCSSPropertyID(StringView string) {
+CSSPropertyID UnresolvedCSSPropertyID(StringView string, CSSParserMode mode) {
unsigned length = string.length();
return string.Is8Bit()
- ? UnresolvedCSSPropertyID(string.Characters8(), length)
- : UnresolvedCSSPropertyID(string.Characters16(), length);
+ ? UnresolvedCSSPropertyID(string.Characters8(), length, mode)
+ : UnresolvedCSSPropertyID(string.Characters16(), length, mode);
}
template <typename CharacterType>
@@ -379,7 +388,8 @@ bool CSSPropertyParser::ParseFontFaceDescriptor(
// TODO(meade): This function should eventually take an AtRuleDescriptorID.
const AtRuleDescriptorID id =
CSSPropertyIDAsAtRuleDescriptor(resolved_property);
- DCHECK_NE(id, AtRuleDescriptorID::Invalid);
+ if (id == AtRuleDescriptorID::Invalid)
+ return false;
CSSValue* parsed_value =
AtRuleDescriptorParser::ParseFontFaceDescriptor(id, range_, *context_);
if (!parsed_value)
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_property_parser.h b/chromium/third_party/blink/renderer/core/css/parser/css_property_parser.h
index 4fd0b1f5811..d4989ede007 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_property_parser.h
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_property_parser.h
@@ -27,6 +27,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/css/parser/css_parser_context.h"
+#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/css/style_rule.h"
#include "third_party/blink/renderer/platform/wtf/text/string_view.h"
@@ -76,7 +77,8 @@ class CORE_EXPORT CSSPropertyParser {
DISALLOW_COPY_AND_ASSIGN(CSSPropertyParser);
};
-CSSPropertyID UnresolvedCSSPropertyID(StringView);
+CSSPropertyID UnresolvedCSSPropertyID(StringView,
+ CSSParserMode mode = kHTMLStandardMode);
CSSValueID CssValueKeywordID(StringView);
} // namespace blink
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 6eaf4c27837..af56e0621fd 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
@@ -5,13 +5,15 @@
#include "third_party/blink/renderer/core/css/parser/css_property_parser_helpers.h"
#include "third_party/blink/renderer/core/css/css_axis_value.h"
-#include "third_party/blink/renderer/core/css/css_calculation_value.h"
#include "third_party/blink/renderer/core/css/css_color_value.h"
#include "third_party/blink/renderer/core/css/css_crossfade_value.h"
#include "third_party/blink/renderer/core/css/css_gradient_value.h"
#include "third_party/blink/renderer/core/css/css_image_set_value.h"
#include "third_party/blink/renderer/core/css/css_image_value.h"
#include "third_party/blink/renderer/core/css/css_initial_value.h"
+#include "third_party/blink/renderer/core/css/css_math_expression_node.h"
+#include "third_party/blink/renderer/core/css/css_math_function_value.h"
+#include "third_party/blink/renderer/core/css/css_numeric_literal_value.h"
#include "third_party/blink/renderer/core/css/css_paint_value.h"
#include "third_party/blink/renderer/core/css/css_property_value.h"
#include "third_party/blink/renderer/core/css/css_shadow_value.h"
@@ -26,8 +28,8 @@
#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/style_color.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/style_property_shorthand.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
namespace blink {
@@ -130,7 +132,7 @@ CSSFunctionValue* ConsumeFilterFunction(CSSParserTokenRange& range,
double max_allowed = is_percentage ? 100.0 : 1.0;
if (To<CSSPrimitiveValue>(parsed_value)->GetDoubleValue() >
max_allowed) {
- parsed_value = CSSPrimitiveValue::Create(
+ parsed_value = CSSNumericLiteralValue::Create(
max_allowed, is_percentage
? CSSPrimitiveValue::UnitType::kPercentage
: CSSPrimitiveValue::UnitType::kNumber);
@@ -193,16 +195,18 @@ class CalcParser {
const CSSParserToken& token = range.Peek();
if (token.FunctionId() == CSSValueID::kCalc ||
token.FunctionId() == CSSValueID::kWebkitCalc) {
- calc_value_ = CSSCalcValue::Create(ConsumeFunction(range_), value_range);
+ calc_value_ = CSSMathFunctionValue::Create(
+ CSSMathExpressionNode::ParseCalc(ConsumeFunction(range_)),
+ value_range);
}
}
- const CSSCalcValue* Value() const { return calc_value_.Get(); }
- CSSPrimitiveValue* ConsumeValue() {
+ const CSSMathFunctionValue* Value() const { return calc_value_; }
+ CSSMathFunctionValue* ConsumeValue() {
if (!calc_value_)
return nullptr;
source_range_ = range_;
- return CSSPrimitiveValue::Create(calc_value_.Release());
+ return calc_value_.Release();
}
CSSPrimitiveValue* ConsumeRoundedInt() {
@@ -211,8 +215,8 @@ class CalcParser {
source_range_ = range_;
CSSPrimitiveValue::UnitType unit_type =
CSSPrimitiveValue::UnitType::kInteger;
- double rounded_value = floor(calc_value_->DoubleValue() + 0.5);
- return CSSPrimitiveValue::Create(rounded_value, unit_type);
+ double rounded_value = floor(calc_value_->GetDoubleValue() + 0.5);
+ return CSSNumericLiteralValue::Create(rounded_value, unit_type);
}
CSSPrimitiveValue* ConsumeNumber() {
@@ -222,21 +226,22 @@ class CalcParser {
CSSPrimitiveValue::UnitType unit_type =
calc_value_->IsInt() ? CSSPrimitiveValue::UnitType::kInteger
: CSSPrimitiveValue::UnitType::kNumber;
- return CSSPrimitiveValue::Create(calc_value_->DoubleValue(), unit_type);
+ return CSSNumericLiteralValue::Create(calc_value_->GetDoubleValue(),
+ unit_type);
}
bool ConsumeNumberRaw(double& result) {
if (!calc_value_ || calc_value_->Category() != kCalcNumber)
return false;
source_range_ = range_;
- result = calc_value_->DoubleValue();
+ result = calc_value_->GetDoubleValue();
return true;
}
private:
CSSParserTokenRange& source_range_;
CSSParserTokenRange range_;
- Member<CSSCalcValue> calc_value_;
+ Member<CSSMathFunctionValue> calc_value_;
};
CSSPrimitiveValue* ConsumeInteger(CSSParserTokenRange& range,
@@ -246,17 +251,17 @@ CSSPrimitiveValue* ConsumeInteger(CSSParserTokenRange& range,
if (token.GetNumericValueType() == kNumberValueType ||
token.NumericValue() < minimum_value)
return nullptr;
- return CSSPrimitiveValue::Create(
+ return CSSNumericLiteralValue::Create(
range.ConsumeIncludingWhitespace().NumericValue(),
CSSPrimitiveValue::UnitType::kInteger);
}
CalcParser calc_parser(range);
- if (const CSSCalcValue* calculation = calc_parser.Value()) {
+ if (const CSSMathFunctionValue* calculation = calc_parser.Value()) {
if (!RuntimeEnabledFeatures::CSSCalcAsIntEnabled() && !calculation->IsInt())
return nullptr;
if (calculation->Category() != kCalcNumber)
return nullptr;
- double value = calculation->DoubleValue();
+ double value = calculation->GetDoubleValue();
if (value < minimum_value)
return nullptr;
if (!RuntimeEnabledFeatures::CSSCalcAsIntEnabled())
@@ -284,7 +289,7 @@ CSSPrimitiveValue* ConsumeIntegerOrNumberCalc(CSSParserTokenRange& range) {
return value;
}
CalcParser calc_parser(range);
- if (const CSSCalcValue* calculation = calc_parser.Value()) {
+ if (const CSSMathFunctionValue* calculation = calc_parser.Value()) {
if (calculation->Category() != kCalcNumber)
return nullptr;
return calc_parser.ConsumeValue();
@@ -312,11 +317,11 @@ CSSPrimitiveValue* ConsumeNumber(CSSParserTokenRange& range,
if (token.GetType() == kNumberToken) {
if (value_range == kValueRangeNonNegative && token.NumericValue() < 0)
return nullptr;
- return CSSPrimitiveValue::Create(
+ return CSSNumericLiteralValue::Create(
range.ConsumeIncludingWhitespace().NumericValue(), token.GetUnitType());
}
CalcParser calc_parser(range, kValueRangeAll);
- if (const CSSCalcValue* calculation = calc_parser.Value()) {
+ if (const CSSMathFunctionValue* calculation = calc_parser.Value()) {
// TODO(rwlbuis) Calcs should not be subject to parse time range checks.
// spec: https://drafts.csswg.org/css-values-3/#calc-range
if (calculation->Category() != kCalcNumber ||
@@ -368,7 +373,7 @@ CSSPrimitiveValue* ConsumeLength(CSSParserTokenRange& range,
}
if (value_range == kValueRangeNonNegative && token.NumericValue() < 0)
return nullptr;
- return CSSPrimitiveValue::Create(
+ return CSSNumericLiteralValue::Create(
range.ConsumeIncludingWhitespace().NumericValue(), token.GetUnitType());
}
if (token.GetType() == kNumberToken) {
@@ -380,7 +385,7 @@ CSSPrimitiveValue* ConsumeLength(CSSParserTokenRange& range,
CSSPrimitiveValue::UnitType::kPixels;
if (css_parser_mode == kSVGAttributeMode)
unit_type = CSSPrimitiveValue::UnitType::kUserUnits;
- return CSSPrimitiveValue::Create(
+ return CSSNumericLiteralValue::Create(
range.ConsumeIncludingWhitespace().NumericValue(), unit_type);
}
if (css_parser_mode == kSVGAttributeMode)
@@ -397,12 +402,12 @@ CSSPrimitiveValue* ConsumePercent(CSSParserTokenRange& range,
if (token.GetType() == kPercentageToken) {
if (value_range == kValueRangeNonNegative && token.NumericValue() < 0)
return nullptr;
- return CSSPrimitiveValue::Create(
+ return CSSNumericLiteralValue::Create(
range.ConsumeIncludingWhitespace().NumericValue(),
CSSPrimitiveValue::UnitType::kPercentage);
}
CalcParser calc_parser(range, value_range);
- if (const CSSCalcValue* calculation = calc_parser.Value()) {
+ if (const CSSMathFunctionValue* calculation = calc_parser.Value()) {
if (calculation->Category() == kCalcPercent)
return calc_parser.ConsumeValue();
}
@@ -435,7 +440,7 @@ CSSPrimitiveValue* ConsumeLengthOrPercent(CSSParserTokenRange& range,
if (token.GetType() == kPercentageToken)
return ConsumePercent(range, value_range);
CalcParser calc_parser(range, value_range);
- if (const CSSCalcValue* calculation = calc_parser.Value()) {
+ if (const CSSMathFunctionValue* calculation = calc_parser.Value()) {
if (CanConsumeCalcValue(calculation->Category(), css_parser_mode))
return calc_parser.ConsumeValue();
}
@@ -445,8 +450,12 @@ CSSPrimitiveValue* ConsumeLengthOrPercent(CSSParserTokenRange& range,
namespace {
bool IsNonZeroUserUnitsValue(const CSSPrimitiveValue* value) {
- return value &&
- value->TypeWithCalcResolved() ==
+ // TODO(crbug.com/979895): This is the result of a refactoring, which might
+ // have revealed an existing bug in handling user units in math functions. Fix
+ // it if necessary.
+ const auto* numeric_literal = DynamicTo<CSSNumericLiteralValue>(value);
+ return numeric_literal &&
+ numeric_literal->GetType() ==
CSSPrimitiveValue::UnitType::kUserUnits &&
value->GetDoubleValue() != 0;
}
@@ -488,7 +497,7 @@ CSSPrimitiveValue* ConsumeAngle(
case CSSPrimitiveValue::UnitType::kRadians:
case CSSPrimitiveValue::UnitType::kGradians:
case CSSPrimitiveValue::UnitType::kTurns:
- return CSSPrimitiveValue::Create(
+ return CSSNumericLiteralValue::Create(
range.ConsumeIncludingWhitespace().NumericValue(),
token.GetUnitType());
default:
@@ -499,20 +508,21 @@ CSSPrimitiveValue* ConsumeAngle(
unitless_zero_feature) {
range.ConsumeIncludingWhitespace();
context->Count(*unitless_zero_feature);
- return CSSPrimitiveValue::Create(0, CSSPrimitiveValue::UnitType::kDegrees);
+ return CSSNumericLiteralValue::Create(
+ 0, CSSPrimitiveValue::UnitType::kDegrees);
}
CalcParser calc_parser(range, kValueRangeAll);
- if (const CSSCalcValue* calculation = calc_parser.Value()) {
+ if (const CSSMathFunctionValue* calculation = calc_parser.Value()) {
if (calculation->Category() != kCalcAngle)
return nullptr;
- if (CSSPrimitiveValue* result = calc_parser.ConsumeValue()) {
- if (result->GetDoubleValue() < minimum_value) {
- return CSSPrimitiveValue::Create(minimum_value,
- result->TypeWithCalcResolved());
+ if (CSSMathFunctionValue* result = calc_parser.ConsumeValue()) {
+ if (result->ComputeDegrees() < minimum_value) {
+ return CSSNumericLiteralValue::Create(
+ minimum_value, CSSPrimitiveValue::UnitType::kDegrees);
}
- if (result->GetDoubleValue() > maximum_value) {
- return CSSPrimitiveValue::Create(maximum_value,
- result->TypeWithCalcResolved());
+ if (result->ComputeDegrees() > maximum_value) {
+ return CSSNumericLiteralValue::Create(
+ maximum_value, CSSPrimitiveValue::UnitType::kDegrees);
}
return result;
}
@@ -538,13 +548,13 @@ CSSPrimitiveValue* ConsumeTime(CSSParserTokenRange& range,
CSSPrimitiveValue::UnitType unit = token.GetUnitType();
if (unit == CSSPrimitiveValue::UnitType::kMilliseconds ||
unit == CSSPrimitiveValue::UnitType::kSeconds)
- return CSSPrimitiveValue::Create(
+ return CSSNumericLiteralValue::Create(
range.ConsumeIncludingWhitespace().NumericValue(),
token.GetUnitType());
return nullptr;
}
CalcParser calc_parser(range, value_range);
- if (const CSSCalcValue* calculation = calc_parser.Value()) {
+ if (const CSSMathFunctionValue* calculation = calc_parser.Value()) {
if (calculation->Category() == kCalcTime)
return calc_parser.ConsumeValue();
}
@@ -560,7 +570,7 @@ CSSPrimitiveValue* ConsumeResolution(CSSParserTokenRange& range) {
if (unit == CSSPrimitiveValue::UnitType::kDotsPerPixel ||
unit == CSSPrimitiveValue::UnitType::kDotsPerInch ||
unit == CSSPrimitiveValue::UnitType::kDotsPerCentimeter) {
- return CSSPrimitiveValue::Create(
+ return CSSNumericLiteralValue::Create(
range.ConsumeIncludingWhitespace().NumericValue(), unit);
}
return nullptr;
@@ -1116,14 +1126,14 @@ static CSSPrimitiveValue* ConsumeDeprecatedGradientPoint(
if (args.Peek().GetType() == kIdentToken) {
if ((horizontal && ConsumeIdent<CSSValueID::kLeft>(args)) ||
(!horizontal && ConsumeIdent<CSSValueID::kTop>(args)))
- return CSSPrimitiveValue::Create(
+ return CSSNumericLiteralValue::Create(
0., CSSPrimitiveValue::UnitType::kPercentage);
if ((horizontal && ConsumeIdent<CSSValueID::kRight>(args)) ||
(!horizontal && ConsumeIdent<CSSValueID::kBottom>(args)))
- return CSSPrimitiveValue::Create(
+ return CSSNumericLiteralValue::Create(
100., CSSPrimitiveValue::UnitType::kPercentage);
if (ConsumeIdent<CSSValueID::kCenter>(args))
- return CSSPrimitiveValue::Create(
+ return CSSNumericLiteralValue::Create(
50., CSSPrimitiveValue::UnitType::kPercentage);
return nullptr;
}
@@ -1165,8 +1175,8 @@ static bool ConsumeDeprecatedGradientColorStop(CSSParserTokenRange& range,
return false;
}
- stop.offset_ =
- CSSPrimitiveValue::Create(position, CSSPrimitiveValue::UnitType::kNumber);
+ stop.offset_ = CSSNumericLiteralValue::Create(
+ position, CSSPrimitiveValue::UnitType::kNumber);
stop.color_ = ConsumeDeprecatedGradientStopColor(args, css_parser_mode);
return stop.color_ && args.AtEnd();
}
@@ -1248,7 +1258,7 @@ static CSSPrimitiveValue* ConsumeGradientAngleOrPercent(
if (token.GetType() == kPercentageToken)
return ConsumePercent(range, value_range);
CalcParser calc_parser(range, value_range);
- if (const CSSCalcValue* calculation = calc_parser.Value()) {
+ if (const CSSMathFunctionValue* calculation = calc_parser.Value()) {
CalculationCategory category = calculation->Category();
// TODO(fs): Add and support kCalcPercentAngle?
if (category == kCalcAngle || category == kCalcPercent)
@@ -1380,13 +1390,14 @@ static CSSValue* ConsumeRadialGradient(CSSParserTokenRange& args,
}
} else {
CSSPrimitiveValue* center =
- ConsumeLengthOrPercent(args, context.Mode(), kValueRangeAll);
+ ConsumeLengthOrPercent(args, context.Mode(), kValueRangeNonNegative);
if (!center)
break;
if (horizontal_size)
return nullptr;
horizontal_size = center;
- center = ConsumeLengthOrPercent(args, context.Mode(), kValueRangeAll);
+ center =
+ ConsumeLengthOrPercent(args, context.Mode(), kValueRangeNonNegative);
if (center) {
vertical_size = center;
++i;
@@ -1549,12 +1560,12 @@ static CSSValue* ConsumeCrossFade(CSSParserTokenRange& args,
CSSPrimitiveValue* percentage = nullptr;
if (CSSPrimitiveValue* percent_value = ConsumePercent(args, kValueRangeAll))
- percentage = CSSPrimitiveValue::Create(
+ percentage = CSSNumericLiteralValue::Create(
clampTo<double>(percent_value->GetDoubleValue() / 100.0, 0, 1),
CSSPrimitiveValue::UnitType::kNumber);
else if (CSSPrimitiveValue* number_value =
ConsumeNumber(args, kValueRangeAll))
- percentage = CSSPrimitiveValue::Create(
+ percentage = CSSNumericLiteralValue::Create(
clampTo<double>(number_value->GetDoubleValue(), 0, 1),
CSSPrimitiveValue::UnitType::kNumber);
@@ -1667,7 +1678,8 @@ static CSSValue* CreateCSSImageValueWithReferrer(
const AtomicString& raw_value,
const CSSParserContext* context) {
CSSValue* image_value = CSSImageValue::Create(
- raw_value, context->CompleteURL(raw_value), context->GetReferrer());
+ raw_value, context->CompleteURL(raw_value), context->GetReferrer(),
+ context->IsOriginClean() ? OriginClean::kTrue : OriginClean::kFalse);
return image_value;
}
@@ -1693,7 +1705,7 @@ static CSSValue* ConsumeImageSet(CSSParserTokenRange& range,
double image_scale_factor = token.NumericValue();
if (image_scale_factor <= 0)
return nullptr;
- image_set->Append(*CSSPrimitiveValue::Create(
+ image_set->Append(*CSSNumericLiteralValue::Create(
image_scale_factor, CSSPrimitiveValue::UnitType::kNumber));
} while (ConsumeCommaIncludingWhitespace(args));
if (!args.AtEnd())
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 985386091ab..75911c2de6e 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
@@ -328,7 +328,7 @@ TEST(CSSPropertyParserTest, ClipPathEllipse) {
}
TEST(CSSPropertyParserTest, ScrollCustomizationPropertySingleValue) {
- RuntimeEnabledFeatures::SetScrollCustomizationEnabled(true);
+ ScopedScrollCustomizationForTest scoped_feature(true);
const CSSValue* value = CSSParser::ParseSingleValue(
CSSPropertyID::kScrollCustomization, "pan-down",
StrictCSSParserContext(SecureContextMode::kSecureContext));
@@ -339,7 +339,7 @@ TEST(CSSPropertyParserTest, ScrollCustomizationPropertySingleValue) {
}
TEST(CSSPropertyParserTest, ScrollCustomizationPropertyTwoValuesCombined) {
- RuntimeEnabledFeatures::SetScrollCustomizationEnabled(true);
+ ScopedScrollCustomizationForTest scoped_feature(true);
const CSSValue* value = CSSParser::ParseSingleValue(
CSSPropertyID::kScrollCustomization, "pan-left pan-y",
StrictCSSParserContext(SecureContextMode::kSecureContext));
@@ -353,7 +353,7 @@ TEST(CSSPropertyParserTest, ScrollCustomizationPropertyTwoValuesCombined) {
TEST(CSSPropertyParserTest, ScrollCustomizationPropertyInvalidEntries) {
// We expect exactly one property value per coordinate.
- RuntimeEnabledFeatures::SetScrollCustomizationEnabled(true);
+ ScopedScrollCustomizationForTest scoped_feature(true);
const CSSValue* value = CSSParser::ParseSingleValue(
CSSPropertyID::kScrollCustomization, "pan-left pan-right",
StrictCSSParserContext(SecureContextMode::kSecureContext));
@@ -573,4 +573,16 @@ TEST_F(CSSPropertyUseCounterTest, CSSPropertyContainStyleUseCount) {
EXPECT_TRUE(IsCounted(feature));
}
+TEST_F(CSSPropertyUseCounterTest, CSSPropertyFontSizeWebkitXxxLargeUseCount) {
+ WebFeature feature = WebFeature::kFontSizeWebkitXxxLarge;
+ ParseProperty(CSSPropertyID::kFontSize, "xx-small");
+ ParseProperty(CSSPropertyID::kFontSize, "larger");
+ ParseProperty(CSSPropertyID::kFontSize, "smaller");
+ ParseProperty(CSSPropertyID::kFontSize, "10%");
+ ParseProperty(CSSPropertyID::kFontSize, "20px");
+ EXPECT_FALSE(IsCounted(feature));
+ ParseProperty(CSSPropertyID::kFontSize, "-webkit-xxx-large");
+ EXPECT_TRUE(IsCounted(feature));
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_proto_converter.cc b/chromium/third_party/blink/renderer/core/css/parser/css_proto_converter.cc
index 5c8a5062af7..6ebb3f9bbfe 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_proto_converter.cc
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_proto_converter.cc
@@ -1479,6 +1479,9 @@ const std::string Converter::kPropertyLookupTable[] = {
"inset-inline-end",
"inset-inline",
"inset",
+ "overflow-block",
+ "overflow-inline",
+ "forced-color-adjust",
"INVALID_PROPERTY",
};
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_proto_converter.h b/chromium/third_party/blink/renderer/core/css/parser/css_proto_converter.h
index c650b3c9d50..167e8170e3f 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_proto_converter.h
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_proto_converter.h
@@ -8,7 +8,7 @@
#include <string>
#include "third_party/blink/renderer/core/css/parser/css.pb.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace css_proto_converter {
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 3e72cb0fe53..4e068b03108 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
@@ -13,7 +13,7 @@
#include "third_party/blink/renderer/core/css/parser/css_parser_token_stream.h"
#include "third_party/blink/renderer/core/css/style_sheet_contents.h"
#include "third_party/blink/renderer/core/frame/deprecation.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
namespace blink {
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 8bc5292bde0..3bef478e561 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
@@ -9,9 +9,10 @@
#include "third_party/blink/renderer/core/css/parser/css_parser_context.h"
#include "third_party/blink/renderer/core/css/parser/css_tokenizer.h"
#include "third_party/blink/renderer/core/css/style_sheet_contents.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/testing/dummy_page_holder.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
+#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
@@ -724,7 +725,7 @@ TEST(CSSSelectorParserTest, UseCountShadowPseudo) {
TEST(CSSSelectorParserTest, ImplicitShadowCrossingCombinators) {
struct ShadowCombinatorTest {
const char* input;
- std::vector<std::pair<AtomicString, CSSSelector::RelationType>> expectation;
+ Vector<std::pair<AtomicString, CSSSelector::RelationType>> expectation;
};
const ShadowCombinatorTest test_cases[] = {
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_tokenizer.h b/chromium/third_party/blink/renderer/core/css/parser/css_tokenizer.h
index 04fa9974bbe..950ad5e4fa9 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_tokenizer.h
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_tokenizer.h
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/css/parser/css_parser_token.h"
#include "third_party/blink/renderer/core/css/parser/css_tokenizer_input_stream.h"
#include "third_party/blink/renderer/core/html/parser/input_stream_preprocessor.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/string_view.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
diff --git a/chromium/third_party/blink/renderer/core/css/parser/css_tokenizer_test.cc b/chromium/third_party/blink/renderer/core/css/parser/css_tokenizer_test.cc
index c70effc8408..740c8272c0b 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/css_tokenizer_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/parser/css_tokenizer_test.cc
@@ -15,7 +15,7 @@ namespace blink {
#define TEST_TOKENS(string, ...) \
{ \
String s = string; \
- SCOPED_TRACE(s.Ascii().data()); \
+ SCOPED_TRACE(s); \
TestTokens(string, __VA_ARGS__); \
}
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 ec8545b160b..519c321695c 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
@@ -15,13 +15,7 @@ class FontVariantNumericParser {
STACK_ALLOCATED();
public:
- FontVariantNumericParser()
- : saw_numeric_figure_value_(false),
- saw_numeric_spacing_value_(false),
- saw_numeric_fraction_value_(false),
- saw_ordinal_value_(false),
- saw_slashed_zero_value_(false),
- result_(CSSValueList::CreateSpaceSeparated()) {}
+ FontVariantNumericParser() {}
enum class ParseResult { kConsumedValue, kDisallowedValue, kUnknownValue };
@@ -30,52 +24,60 @@ class FontVariantNumericParser {
switch (value_id) {
case CSSValueID::kLiningNums:
case CSSValueID::kOldstyleNums:
- if (saw_numeric_figure_value_)
+ if (numeric_figure_)
return ParseResult::kDisallowedValue;
- saw_numeric_figure_value_ = true;
- break;
+ numeric_figure_ = css_property_parser_helpers::ConsumeIdent(range);
+ return ParseResult::kConsumedValue;
case CSSValueID::kProportionalNums:
case CSSValueID::kTabularNums:
- if (saw_numeric_spacing_value_)
+ if (numeric_spacing_)
return ParseResult::kDisallowedValue;
- saw_numeric_spacing_value_ = true;
- break;
+ numeric_spacing_ = css_property_parser_helpers::ConsumeIdent(range);
+ return ParseResult::kConsumedValue;
case CSSValueID::kDiagonalFractions:
case CSSValueID::kStackedFractions:
- if (saw_numeric_fraction_value_)
+ if (numeric_fraction_)
return ParseResult::kDisallowedValue;
- saw_numeric_fraction_value_ = true;
- break;
+ numeric_fraction_ = css_property_parser_helpers::ConsumeIdent(range);
+ return ParseResult::kConsumedValue;
case CSSValueID::kOrdinal:
- if (saw_ordinal_value_)
+ if (ordinal_)
return ParseResult::kDisallowedValue;
- saw_ordinal_value_ = true;
- break;
+ ordinal_ = css_property_parser_helpers::ConsumeIdent(range);
+ return ParseResult::kConsumedValue;
case CSSValueID::kSlashedZero:
- if (saw_slashed_zero_value_)
+ if (slashed_zero_)
return ParseResult::kDisallowedValue;
- saw_slashed_zero_value_ = true;
- break;
+ slashed_zero_ = css_property_parser_helpers::ConsumeIdent(range);
+ return ParseResult::kConsumedValue;
default:
return ParseResult::kUnknownValue;
}
- result_->Append(*css_property_parser_helpers::ConsumeIdent(range));
- return ParseResult::kConsumedValue;
}
CSSValue* FinalizeValue() {
- if (!result_->length())
- return CSSIdentifierValue::Create(CSSValueID::kNormal);
- return result_.Release();
+ CSSValueList* result = CSSValueList::CreateSpaceSeparated();
+ if (numeric_figure_)
+ result->Append(*numeric_figure_);
+ if (numeric_spacing_)
+ result->Append(*numeric_spacing_);
+ if (numeric_fraction_)
+ result->Append(*numeric_fraction_);
+ if (ordinal_)
+ result->Append(*ordinal_);
+ if (slashed_zero_)
+ result->Append(*slashed_zero_);
+ if (result->length() > 0)
+ return result;
+ return CSSIdentifierValue::Create(CSSValueID::kNormal);
}
private:
- bool saw_numeric_figure_value_;
- bool saw_numeric_spacing_value_;
- bool saw_numeric_fraction_value_;
- bool saw_ordinal_value_;
- bool saw_slashed_zero_value_;
- Member<CSSValueList> result_;
+ Member<CSSIdentifierValue> numeric_figure_;
+ Member<CSSIdentifierValue> numeric_spacing_;
+ Member<CSSIdentifierValue> numeric_fraction_;
+ Member<CSSIdentifierValue> ordinal_;
+ Member<CSSIdentifierValue> slashed_zero_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/parser/media_condition_test.cc b/chromium/third_party/blink/renderer/core/css/parser/media_condition_test.cc
index eba22256fae..cc8668d3c4b 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/media_condition_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/parser/media_condition_test.cc
@@ -43,7 +43,7 @@ TEST(MediaConditionParserTest, Basic) {
MediaQueryParser::ParseMediaCondition(CSSParserTokenRange(tokens));
ASSERT_EQ(media_condition_query_set->QueryVector().size(), (unsigned)1);
String query_text = media_condition_query_set->QueryVector()[0]->CssText();
- ASSERT_STREQ(test_cases[i].output, query_text.Ascii().data());
+ ASSERT_EQ(test_cases[i].output, query_text);
}
}
diff --git a/chromium/third_party/blink/renderer/core/css/parser/media_query_block_watcher.h b/chromium/third_party/blink/renderer/core/css/parser/media_query_block_watcher.h
index 4f7bdb714c0..a2739ae275d 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/media_query_block_watcher.h
+++ b/chromium/third_party/blink/renderer/core/css/parser/media_query_block_watcher.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PARSER_MEDIA_QUERY_BLOCK_WATCHER_H_
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/css/parser/sizes_calc_parser.cc b/chromium/third_party/blink/renderer/core/css/parser/sizes_calc_parser.cc
index 95b22c9065b..cfcc79611df 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/sizes_calc_parser.cc
+++ b/chromium/third_party/blink/renderer/core/css/parser/sizes_calc_parser.cc
@@ -20,10 +20,10 @@ float SizesCalcParser::Result() const {
return result_;
}
-static bool OperatorPriority(UChar cc, bool& high_priority) {
- if (cc == '+' || cc == '-')
+static bool OperatorPriority(CSSMathOperator cc, bool& high_priority) {
+ if (cc == CSSMathOperator::kAdd || cc == CSSMathOperator::kSubtract)
high_priority = false;
- else if (cc == '*' || cc == '/')
+ else if (cc == CSSMathOperator::kMultiply || cc == CSSMathOperator::kDivide)
high_priority = true;
else
return false;
@@ -35,7 +35,8 @@ bool SizesCalcParser::HandleOperator(Vector<CSSParserToken>& stack,
// If the token is not an operator, then return. Else determine the
// precedence of the new operator (op1).
bool incoming_operator_priority;
- if (!OperatorPriority(token.Delimiter(), incoming_operator_priority))
+ if (!OperatorPriority(ParseCSSArithmeticOperator(token),
+ incoming_operator_priority))
return false;
while (!stack.IsEmpty()) {
@@ -45,7 +46,8 @@ bool SizesCalcParser::HandleOperator(Vector<CSSParserToken>& stack,
if (top_of_stack.GetType() != kDelimiterToken)
break;
bool stack_operator_priority;
- if (!OperatorPriority(top_of_stack.Delimiter(), stack_operator_priority))
+ if (!OperatorPriority(ParseCSSArithmeticOperator(top_of_stack),
+ stack_operator_priority))
return false;
// ...if op1 is left-associative (all currently supported
// operators are) and its precedence is equal to that of op2, or
@@ -81,7 +83,7 @@ bool SizesCalcParser::AppendLength(const CSSParserToken& token) {
void SizesCalcParser::AppendOperator(const CSSParserToken& token) {
SizesCalcValue value;
- value.operation = token.Delimiter();
+ value.operation = ParseCSSArithmeticOperator(token);
value_list_.push_back(value);
}
@@ -107,7 +109,7 @@ bool SizesCalcParser::CalcToReversePolishNotation(CSSParserTokenRange range) {
return false;
break;
case kFunctionToken:
- if (!EqualIgnoringASCIICase(token.Value(), "calc"))
+ if (token.FunctionId() != CSSValueID::kCalc)
return false;
// "calc(" is the same as "("
FALLTHROUGH;
@@ -182,7 +184,8 @@ bool SizesCalcParser::CalcToReversePolishNotation(CSSParserTokenRange range) {
return true;
}
-static bool OperateOnStack(Vector<SizesCalcValue>& stack, UChar operation) {
+static bool OperateOnStack(Vector<SizesCalcValue>& stack,
+ CSSMathOperator operation) {
if (stack.size() < 2)
return false;
SizesCalcValue right_operand = stack.back();
@@ -191,28 +194,28 @@ static bool OperateOnStack(Vector<SizesCalcValue>& stack, UChar operation) {
stack.pop_back();
bool is_length;
switch (operation) {
- case '+':
+ case CSSMathOperator::kAdd:
if (right_operand.is_length != left_operand.is_length)
return false;
is_length = (right_operand.is_length && left_operand.is_length);
stack.push_back(
SizesCalcValue(left_operand.value + right_operand.value, is_length));
break;
- case '-':
+ case CSSMathOperator::kSubtract:
if (right_operand.is_length != left_operand.is_length)
return false;
is_length = (right_operand.is_length && left_operand.is_length);
stack.push_back(
SizesCalcValue(left_operand.value - right_operand.value, is_length));
break;
- case '*':
+ case CSSMathOperator::kMultiply:
if (right_operand.is_length && left_operand.is_length)
return false;
is_length = (right_operand.is_length || left_operand.is_length);
stack.push_back(
SizesCalcValue(left_operand.value * right_operand.value, is_length));
break;
- case '/':
+ case CSSMathOperator::kDivide:
if (right_operand.is_length || right_operand.value == 0)
return false;
stack.push_back(SizesCalcValue(left_operand.value / right_operand.value,
@@ -227,7 +230,7 @@ static bool OperateOnStack(Vector<SizesCalcValue>& stack, UChar operation) {
bool SizesCalcParser::Calculate() {
Vector<SizesCalcValue> stack;
for (const auto& value : value_list_) {
- if (value.operation == 0) {
+ if (value.operation == CSSMathOperator::kInvalid) {
stack.push_back(value);
} else {
if (!OperateOnStack(stack, value.operation))
diff --git a/chromium/third_party/blink/renderer/core/css/parser/sizes_calc_parser.h b/chromium/third_party/blink/renderer/core/css/parser/sizes_calc_parser.h
index b5605dc7e8f..fa3b96fcbee 100644
--- a/chromium/third_party/blink/renderer/core/css/parser/sizes_calc_parser.h
+++ b/chromium/third_party/blink/renderer/core/css/parser/sizes_calc_parser.h
@@ -6,6 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PARSER_SIZES_CALC_PARSER_H_
#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/css/css_math_operator.h"
#include "third_party/blink/renderer/core/css/media_values.h"
#include "third_party/blink/renderer/core/css/parser/css_parser_token.h"
#include "third_party/blink/renderer/core/css/parser/css_parser_token_range.h"
@@ -15,14 +16,14 @@ namespace blink {
struct SizesCalcValue {
DISALLOW_NEW();
- double value;
- bool is_length;
- UChar operation;
+ double value = 0;
+ bool is_length = false;
+ CSSMathOperator operation = CSSMathOperator::kInvalid;
- SizesCalcValue() : value(0), is_length(false), operation(0) {}
+ SizesCalcValue() = default;
SizesCalcValue(double numeric_value, bool length)
- : value(numeric_value), is_length(length), operation(0) {}
+ : value(numeric_value), is_length(length) {}
};
class CORE_EXPORT SizesCalcParser {
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 eb891668afd..90c3634d4db 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
@@ -15,6 +15,7 @@
#include "third_party/blink/renderer/core/css/css_function_value.h"
#include "third_party/blink/renderer/core/css/css_grid_line_names_value.h"
#include "third_party/blink/renderer/core/css/css_initial_value.h"
+#include "third_party/blink/renderer/core/css/css_numeric_literal_value.h"
#include "third_party/blink/renderer/core/css/css_primitive_value_mappings.h"
#include "third_party/blink/renderer/core/css/css_quad_value.h"
#include "third_party/blink/renderer/core/css/css_reflect_value.h"
@@ -25,6 +26,11 @@
#include "third_party/blink/renderer/core/css/css_value.h"
#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/cssom/cross_thread_keyword_value.h"
+#include "third_party/blink/renderer/core/css/cssom/cross_thread_unit_value.h"
+#include "third_party/blink/renderer/core/css/cssom/cross_thread_unsupported_value.h"
+#include "third_party/blink/renderer/core/css/cssom/css_keyword_value.h"
+#include "third_party/blink/renderer/core/css/cssom/css_unit_value.h"
#include "third_party/blink/renderer/core/css/style_color.h"
#include "third_party/blink/renderer/core/layout/layout_block.h"
#include "third_party/blink/renderer/core/layout/layout_box.h"
@@ -61,7 +67,7 @@ CSSValue* ComputedStyleUtils::ValueForPosition(const LengthPoint& position,
CSSValue* ComputedStyleUtils::ValueForOffset(const ComputedStyle& style,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) {
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
if (RuntimeEnabledFeatures::CSSOffsetPositionAnchorEnabled()) {
@@ -120,7 +126,7 @@ const blink::Color ComputedStyleUtils::BorderSideColor(
border_style == EBorderStyle::kRidge ||
border_style == EBorderStyle::kGroove))
return blink::Color(238, 238, 238);
- return visited_link ? style.VisitedLinkColor() : style.GetColor();
+ return visited_link ? style.InternalVisitedColor() : style.GetColor();
}
const CSSValue* ComputedStyleUtils::BackgroundImageOrWebkitMaskImage(
@@ -213,7 +219,7 @@ const CSSValue* ComputedStyleUtils::ValueForFillRepeat(EFillRepeat x_repeat,
const CSSValueList* ComputedStyleUtils::ValuesForBackgroundShorthand(
const ComputedStyle& style,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) {
CSSValueList* result = CSSValueList::CreateCommaSeparated();
const FillLayer* curr_layer = &style.BackgroundLayers();
@@ -300,11 +306,12 @@ CSSBorderImageSliceValue* ComputedStyleUtils::ValueForNinePieceImageSlice(
// TODO(alancutter): Make this code aware of calc lengths.
if (image.ImageSlices().Top().IsPercentOrCalc()) {
- top = CSSPrimitiveValue::Create(image.ImageSlices().Top().Value(),
- CSSPrimitiveValue::UnitType::kPercentage);
+ top = CSSNumericLiteralValue::Create(
+ image.ImageSlices().Top().Value(),
+ CSSPrimitiveValue::UnitType::kPercentage);
} else {
- top = CSSPrimitiveValue::Create(image.ImageSlices().Top().Value(),
- CSSPrimitiveValue::UnitType::kNumber);
+ top = CSSNumericLiteralValue::Create(image.ImageSlices().Top().Value(),
+ CSSPrimitiveValue::UnitType::kNumber);
}
if (image.ImageSlices().Right() == image.ImageSlices().Top() &&
@@ -315,12 +322,13 @@ CSSBorderImageSliceValue* ComputedStyleUtils::ValueForNinePieceImageSlice(
left = top;
} else {
if (image.ImageSlices().Right().IsPercentOrCalc()) {
- right =
- CSSPrimitiveValue::Create(image.ImageSlices().Right().Value(),
- CSSPrimitiveValue::UnitType::kPercentage);
+ right = CSSNumericLiteralValue::Create(
+ image.ImageSlices().Right().Value(),
+ CSSPrimitiveValue::UnitType::kPercentage);
} else {
- right = CSSPrimitiveValue::Create(image.ImageSlices().Right().Value(),
- CSSPrimitiveValue::UnitType::kNumber);
+ right =
+ CSSNumericLiteralValue::Create(image.ImageSlices().Right().Value(),
+ CSSPrimitiveValue::UnitType::kNumber);
}
if (image.ImageSlices().Bottom() == image.ImageSlices().Top() &&
@@ -329,26 +337,26 @@ CSSBorderImageSliceValue* ComputedStyleUtils::ValueForNinePieceImageSlice(
left = right;
} else {
if (image.ImageSlices().Bottom().IsPercentOrCalc()) {
- bottom =
- CSSPrimitiveValue::Create(image.ImageSlices().Bottom().Value(),
- CSSPrimitiveValue::UnitType::kPercentage);
+ bottom = CSSNumericLiteralValue::Create(
+ image.ImageSlices().Bottom().Value(),
+ CSSPrimitiveValue::UnitType::kPercentage);
} else {
- bottom =
- CSSPrimitiveValue::Create(image.ImageSlices().Bottom().Value(),
- CSSPrimitiveValue::UnitType::kNumber);
+ bottom = CSSNumericLiteralValue::Create(
+ image.ImageSlices().Bottom().Value(),
+ CSSPrimitiveValue::UnitType::kNumber);
}
if (image.ImageSlices().Left() == image.ImageSlices().Right()) {
left = right;
} else {
if (image.ImageSlices().Left().IsPercentOrCalc()) {
- left = CSSPrimitiveValue::Create(
+ left = CSSNumericLiteralValue::Create(
image.ImageSlices().Left().Value(),
CSSPrimitiveValue::UnitType::kPercentage);
} else {
- left =
- CSSPrimitiveValue::Create(image.ImageSlices().Left().Value(),
- CSSPrimitiveValue::UnitType::kNumber);
+ left = CSSNumericLiteralValue::Create(
+ image.ImageSlices().Left().Value(),
+ CSSPrimitiveValue::UnitType::kNumber);
}
}
}
@@ -364,8 +372,8 @@ CSSValue* ValueForBorderImageLength(
const BorderImageLength& border_image_length,
const ComputedStyle& style) {
if (border_image_length.IsNumber()) {
- return CSSPrimitiveValue::Create(border_image_length.Number(),
- CSSPrimitiveValue::UnitType::kNumber);
+ return CSSNumericLiteralValue::Create(border_image_length.Number(),
+ CSSPrimitiveValue::UnitType::kNumber);
}
return CSSValue::Create(border_image_length.length(), style.EffectiveZoom());
}
@@ -472,9 +480,9 @@ CSSValue* ComputedStyleUtils::ValueForReflection(
CSSPrimitiveValue* offset = nullptr;
// TODO(alancutter): Make this work correctly for calc lengths.
if (reflection->Offset().IsPercentOrCalc()) {
- offset =
- CSSPrimitiveValue::Create(reflection->Offset().Percent(),
- CSSPrimitiveValue::UnitType::kPercentage);
+ offset = CSSNumericLiteralValue::Create(
+ reflection->Offset().Percent(),
+ CSSPrimitiveValue::UnitType::kPercentage);
} else {
offset = ZoomAdjustedPixelValue(reflection->Offset().Value(), style);
}
@@ -500,7 +508,7 @@ CSSValue* ComputedStyleUtils::ValueForReflection(
}
CSSValue* ComputedStyleUtils::MinWidthOrMinHeightAuto(
- Node* styled_node,
+ const Node* styled_node,
const ComputedStyle& style) {
LayoutObject* layout_object =
styled_node ? styled_node->GetLayoutObject() : nullptr;
@@ -580,8 +588,8 @@ CSSValue* ComputedStyleUtils::ValueForPositionOffset(
// is negative right. So we get the opposite length unit and see if it is
// auto.
if (opposite.IsAuto()) {
- return CSSPrimitiveValue::Create(0,
- CSSPrimitiveValue::UnitType::kPixels);
+ return CSSNumericLiteralValue::Create(
+ 0, CSSPrimitiveValue::UnitType::kPixels);
}
if (opposite.IsPercentOrCalc()) {
@@ -764,8 +772,9 @@ CSSPrimitiveValue* ComputedStyleUtils::ValueForFontSize(
CSSPrimitiveValue* ComputedStyleUtils::ValueForFontStretch(
const ComputedStyle& style) {
- return CSSPrimitiveValue::Create(style.GetFontDescription().Stretch(),
- CSSPrimitiveValue::UnitType::kPercentage);
+ return CSSNumericLiteralValue::Create(
+ style.GetFontDescription().Stretch(),
+ CSSPrimitiveValue::UnitType::kPercentage);
}
CSSValue* ComputedStyleUtils::ValueForFontStyle(const ComputedStyle& style) {
@@ -782,16 +791,16 @@ CSSValue* ComputedStyleUtils::ValueForFontStyle(const ComputedStyle& style) {
// "20deg"', but since we compute that to 'italic' (handled above),
// we don't perform any special treatment of that value here.
CSSValueList* oblique_values = CSSValueList::CreateSpaceSeparated();
- oblique_values->Append(
- *CSSPrimitiveValue::Create(angle, CSSPrimitiveValue::UnitType::kDegrees));
+ oblique_values->Append(*CSSNumericLiteralValue::Create(
+ angle, CSSPrimitiveValue::UnitType::kDegrees));
return MakeGarbageCollected<CSSFontStyleRangeValue>(
*CSSIdentifierValue::Create(CSSValueID::kOblique), *oblique_values);
}
CSSPrimitiveValue* ComputedStyleUtils::ValueForFontWeight(
const ComputedStyle& style) {
- return CSSPrimitiveValue::Create(style.GetFontDescription().Weight(),
- CSSPrimitiveValue::UnitType::kNumber);
+ return CSSNumericLiteralValue::Create(style.GetFontDescription().Weight(),
+ CSSPrimitiveValue::UnitType::kNumber);
}
CSSIdentifierValue* ComputedStyleUtils::ValueForFontVariantCaps(
@@ -1036,8 +1045,8 @@ CSSValue* ComputedStyleUtils::ValueForFont(const ComputedStyle& style) {
CSSValue* SpecifiedValueForGridTrackBreadth(const GridLength& track_breadth,
const ComputedStyle& style) {
if (!track_breadth.IsLength()) {
- return CSSPrimitiveValue::Create(track_breadth.Flex(),
- CSSPrimitiveValue::UnitType::kFraction);
+ return CSSNumericLiteralValue::Create(
+ track_breadth.Flex(), CSSPrimitiveValue::UnitType::kFraction);
}
const Length& track_breadth_length = track_breadth.length();
@@ -1057,7 +1066,7 @@ CSSValue* ComputedStyleUtils::SpecifiedValueForGridTrackSize(
case kMinMaxTrackSizing: {
if (track_size.MinTrackBreadth().IsAuto() &&
track_size.MaxTrackBreadth().IsFlex()) {
- return CSSPrimitiveValue::Create(
+ return CSSNumericLiteralValue::Create(
track_size.MaxTrackBreadth().Flex(),
CSSPrimitiveValue::UnitType::kFraction);
}
@@ -1277,10 +1286,10 @@ CSSValue* ComputedStyleUtils::ValueForGridPosition(
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
if (position.IsSpan()) {
list->Append(*CSSIdentifierValue::Create(CSSValueID::kSpan));
- list->Append(*CSSPrimitiveValue::Create(
+ list->Append(*CSSNumericLiteralValue::Create(
position.SpanPosition(), CSSPrimitiveValue::UnitType::kNumber));
} else {
- list->Append(*CSSPrimitiveValue::Create(
+ list->Append(*CSSNumericLiteralValue::Create(
position.IntegerPosition(), CSSPrimitiveValue::UnitType::kNumber));
}
@@ -1414,11 +1423,11 @@ CSSValue* ComputedStyleUtils::ValueForAnimationDelay(
CSSValueList* list = CSSValueList::CreateCommaSeparated();
if (timing_data) {
for (wtf_size_t i = 0; i < timing_data->DelayList().size(); ++i) {
- list->Append(*CSSPrimitiveValue::Create(
+ list->Append(*CSSNumericLiteralValue::Create(
timing_data->DelayList()[i], CSSPrimitiveValue::UnitType::kSeconds));
}
} else {
- list->Append(*CSSPrimitiveValue::Create(
+ list->Append(*CSSNumericLiteralValue::Create(
CSSTimingData::InitialDelay(), CSSPrimitiveValue::UnitType::kSeconds));
}
return list;
@@ -1446,14 +1455,14 @@ CSSValue* ComputedStyleUtils::ValueForAnimationDuration(
CSSValueList* list = CSSValueList::CreateCommaSeparated();
if (timing_data) {
for (wtf_size_t i = 0; i < timing_data->DurationList().size(); ++i) {
- list->Append(
- *CSSPrimitiveValue::Create(timing_data->DurationList()[i],
- CSSPrimitiveValue::UnitType::kSeconds));
+ list->Append(*CSSNumericLiteralValue::Create(
+ timing_data->DurationList()[i],
+ CSSPrimitiveValue::UnitType::kSeconds));
}
} else {
list->Append(
- *CSSPrimitiveValue::Create(CSSTimingData::InitialDuration(),
- CSSPrimitiveValue::UnitType::kSeconds));
+ *CSSNumericLiteralValue::Create(CSSTimingData::InitialDuration(),
+ CSSPrimitiveValue::UnitType::kSeconds));
}
return list;
}
@@ -1479,8 +1488,8 @@ CSSValue* ComputedStyleUtils::ValueForAnimationIterationCount(
double iteration_count) {
if (iteration_count == std::numeric_limits<double>::infinity())
return CSSIdentifierValue::Create(CSSValueID::kInfinite);
- return CSSPrimitiveValue::Create(iteration_count,
- CSSPrimitiveValue::UnitType::kNumber);
+ return CSSNumericLiteralValue::Create(iteration_count,
+ CSSPrimitiveValue::UnitType::kNumber);
}
CSSValue* ComputedStyleUtils::ValueForAnimationPlayState(
@@ -1530,15 +1539,10 @@ CSSValue* ComputedStyleUtils::CreateTimingFunctionValue(
StepsTimingFunction::StepPosition position =
steps_timing_function->GetStepPosition();
int steps = steps_timing_function->NumberOfSteps();
- DCHECK(position == StepsTimingFunction::StepPosition::START ||
- position == StepsTimingFunction::StepPosition::END);
-
- if (steps > 1)
- return CSSStepsTimingFunctionValue::Create(steps, position);
- CSSValueID value_id = position == StepsTimingFunction::StepPosition::START
- ? CSSValueID::kStepStart
- : CSSValueID::kStepEnd;
- return CSSIdentifierValue::Create(value_id);
+
+ // Canonical form of step timing function is step(n, type) or step(n) even
+ // if initially parsed as step-start or step-end.
+ return CSSStepsTimingFunctionValue::Create(steps, position);
}
default:
@@ -1566,13 +1570,13 @@ CSSValueList* ComputedStyleUtils::ValuesForBorderRadiusCorner(
const ComputedStyle& style) {
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
if (radius.Width().IsPercent()) {
- list->Append(*CSSPrimitiveValue::Create(
+ list->Append(*CSSNumericLiteralValue::Create(
radius.Width().Percent(), CSSPrimitiveValue::UnitType::kPercentage));
} else {
list->Append(*ZoomAdjustedPixelValueForLength(radius.Width(), style));
}
if (radius.Height().IsPercent()) {
- list->Append(*CSSPrimitiveValue::Create(
+ list->Append(*CSSNumericLiteralValue::Create(
radius.Height().Percent(), CSSPrimitiveValue::UnitType::kPercentage));
} else {
list->Append(*ZoomAdjustedPixelValueForLength(radius.Height(), style));
@@ -1601,56 +1605,56 @@ CSSFunctionValue* ValueForMatrixTransform(
transform_value =
MakeGarbageCollected<CSSFunctionValue>(CSSValueID::kMatrix);
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.A(), CSSPrimitiveValue::UnitType::kNumber));
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.B(), CSSPrimitiveValue::UnitType::kNumber));
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.C(), CSSPrimitiveValue::UnitType::kNumber));
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.D(), CSSPrimitiveValue::UnitType::kNumber));
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.E(), CSSPrimitiveValue::UnitType::kNumber));
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.F(), CSSPrimitiveValue::UnitType::kNumber));
} else {
transform_value =
MakeGarbageCollected<CSSFunctionValue>(CSSValueID::kMatrix3d);
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.M11(), CSSPrimitiveValue::UnitType::kNumber));
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.M12(), CSSPrimitiveValue::UnitType::kNumber));
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.M13(), CSSPrimitiveValue::UnitType::kNumber));
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.M14(), CSSPrimitiveValue::UnitType::kNumber));
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.M21(), CSSPrimitiveValue::UnitType::kNumber));
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.M22(), CSSPrimitiveValue::UnitType::kNumber));
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.M23(), CSSPrimitiveValue::UnitType::kNumber));
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.M24(), CSSPrimitiveValue::UnitType::kNumber));
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.M31(), CSSPrimitiveValue::UnitType::kNumber));
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.M32(), CSSPrimitiveValue::UnitType::kNumber));
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.M33(), CSSPrimitiveValue::UnitType::kNumber));
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.M34(), CSSPrimitiveValue::UnitType::kNumber));
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.M41(), CSSPrimitiveValue::UnitType::kNumber));
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.M42(), CSSPrimitiveValue::UnitType::kNumber));
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.M43(), CSSPrimitiveValue::UnitType::kNumber));
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.M44(), CSSPrimitiveValue::UnitType::kNumber));
}
@@ -1810,7 +1814,7 @@ CSSValue* ComputedStyleUtils::ValueForCounterDirectives(
list->Append(*MakeGarbageCollected<CSSCustomIdentValue>(item.key));
int32_t number =
is_increment ? item.value.IncrementValue() : item.value.ResetValue();
- list->Append(*CSSPrimitiveValue::Create(
+ list->Append(*CSSNumericLiteralValue::Create(
(double)number, CSSPrimitiveValue::UnitType::kInteger));
}
@@ -1994,35 +1998,35 @@ CSSValue* ComputedStyleUtils::ValueForFilter(
case FilterOperation::GRAYSCALE:
filter_value =
MakeGarbageCollected<CSSFunctionValue>(CSSValueID::kGrayscale);
- filter_value->Append(*CSSPrimitiveValue::Create(
+ filter_value->Append(*CSSNumericLiteralValue::Create(
To<BasicColorMatrixFilterOperation>(filter_operation)->Amount(),
CSSPrimitiveValue::UnitType::kNumber));
break;
case FilterOperation::SEPIA:
filter_value =
MakeGarbageCollected<CSSFunctionValue>(CSSValueID::kSepia);
- filter_value->Append(*CSSPrimitiveValue::Create(
+ filter_value->Append(*CSSNumericLiteralValue::Create(
To<BasicColorMatrixFilterOperation>(filter_operation)->Amount(),
CSSPrimitiveValue::UnitType::kNumber));
break;
case FilterOperation::SATURATE:
filter_value =
MakeGarbageCollected<CSSFunctionValue>(CSSValueID::kSaturate);
- filter_value->Append(*CSSPrimitiveValue::Create(
+ filter_value->Append(*CSSNumericLiteralValue::Create(
To<BasicColorMatrixFilterOperation>(filter_operation)->Amount(),
CSSPrimitiveValue::UnitType::kNumber));
break;
case FilterOperation::HUE_ROTATE:
filter_value =
MakeGarbageCollected<CSSFunctionValue>(CSSValueID::kHueRotate);
- filter_value->Append(*CSSPrimitiveValue::Create(
+ filter_value->Append(*CSSNumericLiteralValue::Create(
To<BasicColorMatrixFilterOperation>(filter_operation)->Amount(),
CSSPrimitiveValue::UnitType::kDegrees));
break;
case FilterOperation::INVERT:
filter_value =
MakeGarbageCollected<CSSFunctionValue>(CSSValueID::kInvert);
- filter_value->Append(*CSSPrimitiveValue::Create(
+ filter_value->Append(*CSSNumericLiteralValue::Create(
To<BasicComponentTransferFilterOperation>(filter_operation)
->Amount(),
CSSPrimitiveValue::UnitType::kNumber));
@@ -2030,7 +2034,7 @@ CSSValue* ComputedStyleUtils::ValueForFilter(
case FilterOperation::OPACITY:
filter_value =
MakeGarbageCollected<CSSFunctionValue>(CSSValueID::kOpacity);
- filter_value->Append(*CSSPrimitiveValue::Create(
+ filter_value->Append(*CSSNumericLiteralValue::Create(
To<BasicComponentTransferFilterOperation>(filter_operation)
->Amount(),
CSSPrimitiveValue::UnitType::kNumber));
@@ -2038,7 +2042,7 @@ CSSValue* ComputedStyleUtils::ValueForFilter(
case FilterOperation::BRIGHTNESS:
filter_value =
MakeGarbageCollected<CSSFunctionValue>(CSSValueID::kBrightness);
- filter_value->Append(*CSSPrimitiveValue::Create(
+ filter_value->Append(*CSSNumericLiteralValue::Create(
To<BasicComponentTransferFilterOperation>(filter_operation)
->Amount(),
CSSPrimitiveValue::UnitType::kNumber));
@@ -2046,7 +2050,7 @@ CSSValue* ComputedStyleUtils::ValueForFilter(
case FilterOperation::CONTRAST:
filter_value =
MakeGarbageCollected<CSSFunctionValue>(CSSValueID::kContrast);
- filter_value->Append(*CSSPrimitiveValue::Create(
+ filter_value->Append(*CSSNumericLiteralValue::Create(
To<BasicComponentTransferFilterOperation>(filter_operation)
->Amount(),
CSSPrimitiveValue::UnitType::kNumber));
@@ -2200,7 +2204,7 @@ CSSValueList* ComputedStyleUtils::ValuesForShorthandProperty(
const StylePropertyShorthand& shorthand,
const ComputedStyle& style,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) {
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
for (unsigned i = 0; i < shorthand.length(); ++i) {
@@ -2217,7 +2221,7 @@ CSSValueList* ComputedStyleUtils::ValuesForGridShorthand(
const StylePropertyShorthand& shorthand,
const ComputedStyle& style,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) {
CSSValueList* list = CSSValueList::CreateSlashSeparated();
for (unsigned i = 0; i < shorthand.length(); ++i) {
@@ -2234,7 +2238,7 @@ CSSValueList* ComputedStyleUtils::ValuesForSidesShorthand(
const StylePropertyShorthand& shorthand,
const ComputedStyle& style,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) {
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
// Assume the properties are in the usual order top, right, bottom, left.
@@ -2274,7 +2278,7 @@ CSSValuePair* ComputedStyleUtils::ValuesForInlineBlockShorthand(
const StylePropertyShorthand& shorthand,
const ComputedStyle& style,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) {
const CSSValue* start_value =
shorthand.properties()[0]->CSSValueFromComputedStyle(
@@ -2291,6 +2295,23 @@ CSSValuePair* ComputedStyleUtils::ValuesForInlineBlockShorthand(
return pair;
}
+CSSValuePair* ComputedStyleUtils::ValuesForPlaceShorthand(
+ const StylePropertyShorthand& shorthand,
+ const ComputedStyle& style,
+ const LayoutObject* layout_object,
+ const Node* styled_node,
+ bool allow_visited_style) {
+ const CSSValue* align_value =
+ shorthand.properties()[0]->CSSValueFromComputedStyle(
+ style, layout_object, styled_node, allow_visited_style);
+ const CSSValue* justify_value =
+ shorthand.properties()[1]->CSSValueFromComputedStyle(
+ style, layout_object, styled_node, allow_visited_style);
+
+ return MakeGarbageCollected<CSSValuePair>(align_value, justify_value,
+ CSSValuePair::kDropIdenticalValues);
+}
+
static CSSValue* ExpandNoneLigaturesValue() {
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
list->Append(*CSSIdentifierValue::Create(CSSValueID::kNoCommonLigatures));
@@ -2304,7 +2325,7 @@ static CSSValue* ExpandNoneLigaturesValue() {
CSSValue* ComputedStyleUtils::ValuesForFontVariantProperty(
const ComputedStyle& style,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) {
enum VariantShorthandCases {
kAllNormal,
@@ -2401,4 +2422,22 @@ CSSValue* ComputedStyleUtils::ValueForGapLength(const GapLength& gap_length,
return ZoomAdjustedPixelValueForLength(gap_length.GetLength(), style);
}
+std::unique_ptr<CrossThreadStyleValue>
+ComputedStyleUtils::CrossThreadStyleValueFromCSSStyleValue(
+ CSSStyleValue* style_value) {
+ switch (style_value->GetType()) {
+ case CSSStyleValue::StyleValueType::kKeywordType:
+ return std::make_unique<CrossThreadKeywordValue>(
+ To<CSSKeywordValue>(style_value)->value().IsolatedCopy());
+ case CSSStyleValue::StyleValueType::kUnitType:
+ return std::make_unique<CrossThreadUnitValue>(
+ To<CSSUnitValue>(style_value)->value(),
+ To<CSSUnitValue>(style_value)->GetInternalUnit());
+ default:
+ // Make an isolated copy to ensure that it is safe to pass cross thread.
+ return std::make_unique<CrossThreadUnsupportedValue>(
+ style_value->toString().IsolatedCopy());
+ }
+}
+
} // namespace blink
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 909160cee0f..eac5b3cf22a 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
@@ -13,13 +13,14 @@
#include "third_party/blink/renderer/core/css/zoom_adjusted_pixel_value.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/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
using namespace cssvalue;
class ComputedStyle;
+class CSSStyleValue;
class CSSValue;
class StyleColor;
class StylePropertyShorthand;
@@ -57,7 +58,7 @@ class ComputedStyleUtils {
static const CSSValueList* ValuesForBackgroundShorthand(
const ComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style);
static const CSSValue* BackgroundRepeatOrWebkitMaskRepeat(const FillLayer*);
static const CSSValue* BackgroundPositionOrWebkitMaskPosition(
@@ -84,9 +85,9 @@ class ComputedStyleUtils {
static CSSValue* ValueForOffset(const ComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style);
- static CSSValue* MinWidthOrMinHeightAuto(Node*, const ComputedStyle&);
+ static CSSValue* MinWidthOrMinHeightAuto(const Node*, const ComputedStyle&);
static CSSValue* ValueForPositionOffset(const ComputedStyle&,
const CSSProperty&,
const LayoutObject*);
@@ -178,31 +179,38 @@ class ComputedStyleUtils {
static CSSValueList* ValuesForShorthandProperty(const StylePropertyShorthand&,
const ComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style);
static CSSValueList* ValuesForGridShorthand(const StylePropertyShorthand&,
const ComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style);
static CSSValueList* ValuesForSidesShorthand(const StylePropertyShorthand&,
const ComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style);
static CSSValuePair* ValuesForInlineBlockShorthand(
const StylePropertyShorthand&,
const ComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style);
+ static CSSValuePair* ValuesForPlaceShorthand(const StylePropertyShorthand&,
+ const ComputedStyle&,
+ const LayoutObject*,
+ const Node*,
+ bool allow_visited_style);
static CSSValue* ValuesForFontVariantProperty(const ComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style);
static CSSValue* ScrollCustomizationFlagsToCSSValue(
scroll_customization::ScrollDirection);
static CSSValue* ValueForGapLength(const GapLength&, const ComputedStyle&);
+ static std::unique_ptr<CrossThreadStyleValue>
+ CrossThreadStyleValueFromCSSStyleValue(CSSStyleValue* style_value);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/css_direction_aware_resolver.cc b/chromium/third_party/blink/renderer/core/css/properties/css_direction_aware_resolver.cc
index deb663efe1f..451c66bec37 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/css_direction_aware_resolver.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/css_direction_aware_resolver.cc
@@ -76,6 +76,14 @@ PhysicalGroup<2> CSSDirectionAwareResolver::MinSizeGroup() {
return PhysicalGroup<2>(kProperties);
}
+PhysicalGroup<2> CSSDirectionAwareResolver::OverflowGroup() {
+ return PhysicalGroup<2>(overflowShorthand());
+}
+
+PhysicalGroup<2> CSSDirectionAwareResolver::OverscrollBehaviorGroup() {
+ return PhysicalGroup<2>(overscrollBehaviorShorthand());
+}
+
PhysicalGroup<4> CSSDirectionAwareResolver::PaddingGroup() {
return PhysicalGroup<4>(paddingShorthand());
}
@@ -94,6 +102,15 @@ PhysicalGroup<2> CSSDirectionAwareResolver::SizeGroup() {
return PhysicalGroup<2>(kProperties);
}
+PhysicalGroup<4> CSSDirectionAwareResolver::VisitedBorderColorGroup() {
+ static const CSSProperty* kProperties[] = {
+ &GetCSSPropertyInternalVisitedBorderTopColor(),
+ &GetCSSPropertyInternalVisitedBorderRightColor(),
+ &GetCSSPropertyInternalVisitedBorderBottomColor(),
+ &GetCSSPropertyInternalVisitedBorderLeftColor()};
+ return PhysicalGroup<4>(kProperties);
+}
+
const CSSProperty& CSSDirectionAwareResolver::ResolveInlineStart(
TextDirection direction,
WritingMode writing_mode,
diff --git a/chromium/third_party/blink/renderer/core/css/properties/css_direction_aware_resolver.h b/chromium/third_party/blink/renderer/core/css/properties/css_direction_aware_resolver.h
index e189f7c18e8..4340a49a9c1 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/css_direction_aware_resolver.h
+++ b/chromium/third_party/blink/renderer/core/css/properties/css_direction_aware_resolver.h
@@ -7,7 +7,7 @@
#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/allocator/allocator.h"
namespace blink {
@@ -39,10 +39,13 @@ class CSSDirectionAwareResolver {
static PhysicalGroup<4> MarginGroup();
static PhysicalGroup<2> MaxSizeGroup();
static PhysicalGroup<2> MinSizeGroup();
+ static PhysicalGroup<2> OverflowGroup();
+ static PhysicalGroup<2> OverscrollBehaviorGroup();
static PhysicalGroup<4> PaddingGroup();
static PhysicalGroup<4> ScrollMarginGroup();
static PhysicalGroup<4> ScrollPaddingGroup();
static PhysicalGroup<2> SizeGroup();
+ static PhysicalGroup<4> VisitedBorderColorGroup();
// These resolvers expect a PhysicalGroup with box sides, in the following
// order: top, right, bottom, left.
diff --git a/chromium/third_party/blink/renderer/core/css/properties/css_exposure.h b/chromium/third_party/blink/renderer/core/css/properties/css_exposure.h
new file mode 100644
index 00000000000..ed1763722a0
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/properties/css_exposure.h
@@ -0,0 +1,32 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PROPERTIES_CSS_EXPOSURE_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PROPERTIES_CSS_EXPOSURE_H_
+
+namespace blink {
+
+// Describes whether a property is exposed to author/user style sheets,
+// UA style sheets, or not at all.
+enum class CSSExposure {
+ // The property can't be used anywhere, i.e. it's disabled.
+ kNone,
+ // The property may be used in UA stylesheets, but not in author and user
+ // stylesheets, and the property is otherwise not visible to the author.
+ kUA,
+ // The property is "web exposed", which means it's available everywhere.
+ kWeb
+};
+
+inline bool IsUAExposed(CSSExposure exposure) {
+ return exposure >= CSSExposure::kUA;
+}
+
+inline bool IsWebExposed(CSSExposure exposure) {
+ return exposure == CSSExposure::kWeb;
+}
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PROPERTIES_CSS_EXPOSURE_H_
diff --git a/chromium/third_party/blink/renderer/core/css/properties/css_exposure_test.cc b/chromium/third_party/blink/renderer/core/css/properties/css_exposure_test.cc
new file mode 100644
index 00000000000..6846ea9a016
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/properties/css_exposure_test.cc
@@ -0,0 +1,22 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/css/properties/css_exposure.h"
+#include "testing/gtest/include/gtest/gtest.h"
+
+namespace blink {
+
+TEST(CSSExposureTest, IsUAExposed) {
+ EXPECT_FALSE(IsUAExposed(CSSExposure::kNone));
+ EXPECT_TRUE(IsUAExposed(CSSExposure::kUA));
+ EXPECT_TRUE(IsUAExposed(CSSExposure::kWeb));
+}
+
+TEST(CSSExposureTest, IsWebExposed) {
+ EXPECT_FALSE(IsWebExposed(CSSExposure::kNone));
+ EXPECT_FALSE(IsWebExposed(CSSExposure::kUA));
+ EXPECT_TRUE(IsWebExposed(CSSExposure::kWeb));
+}
+
+} // namespace blink
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 c242a460739..ee870d8b463 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
@@ -21,6 +21,7 @@
#include "third_party/blink/renderer/core/css/css_grid_template_areas_value.h"
#include "third_party/blink/renderer/core/css/css_identifier_value.h"
#include "third_party/blink/renderer/core/css/css_initial_value.h"
+#include "third_party/blink/renderer/core/css/css_numeric_literal_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"
@@ -40,7 +41,6 @@
#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_value_keywords.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/frame/web_feature.h"
#include "third_party/blink/renderer/core/style_property_shorthand.h"
#include "third_party/blink/renderer/core/svg/svg_parsing_error.h"
@@ -49,6 +49,7 @@
#include "third_party/blink/renderer/platform/fonts/font_selection_types.h"
#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
@@ -90,11 +91,6 @@ CSSIdentifierValue* ConsumeOverflowPositionKeyword(CSSParserTokenRange& range) {
: nullptr;
}
-bool IsBaselineKeyword(CSSValueID id) {
- return css_property_parser_helpers::IdentMatches<
- CSSValueID::kFirst, CSSValueID::kLast, CSSValueID::kBaseline>(id);
-}
-
CSSValueID GetBaselineKeyword(CSSValue& value) {
auto* value_pair = DynamicTo<CSSValuePair>(value);
if (!value_pair) {
@@ -142,9 +138,27 @@ CSSValue* ConsumeSteps(CSSParserTokenRange& range) {
case CSSValueID::kStart:
position = StepsTimingFunction::StepPosition::START;
break;
+
case CSSValueID::kEnd:
position = StepsTimingFunction::StepPosition::END;
break;
+
+ case CSSValueID::kJumpBoth:
+ position = StepsTimingFunction::StepPosition::JUMP_BOTH;
+ break;
+
+ case CSSValueID::kJumpEnd:
+ position = StepsTimingFunction::StepPosition::JUMP_END;
+ break;
+
+ case CSSValueID::kJumpNone:
+ position = StepsTimingFunction::StepPosition::JUMP_NONE;
+ break;
+
+ case CSSValueID::kJumpStart:
+ position = StepsTimingFunction::StepPosition::JUMP_START;
+ break;
+
default:
return nullptr;
}
@@ -153,6 +167,12 @@ CSSValue* ConsumeSteps(CSSParserTokenRange& range) {
if (!args.AtEnd())
return nullptr;
+ // Steps(n, jump-none) requires n >= 2.
+ if (position == StepsTimingFunction::StepPosition::JUMP_NONE &&
+ steps->GetIntValue() < 2) {
+ return nullptr;
+ }
+
range = range_copy;
return CSSStepsTimingFunctionValue::Create(steps->GetIntValue(), position);
}
@@ -371,7 +391,7 @@ bool ConsumePerspective(CSSParserTokenRange& args,
return false;
}
context.Count(WebFeature::kUnitlessPerspectiveInTransformProperty);
- parsed_value = CSSPrimitiveValue::Create(
+ parsed_value = CSSNumericLiteralValue::Create(
perspective, CSSPrimitiveValue::UnitType::kPixels);
}
if (!parsed_value)
@@ -404,6 +424,11 @@ bool ConsumeTranslate3d(CSSParserTokenRange& args,
} // namespace
+bool IsBaselineKeyword(CSSValueID id) {
+ return css_property_parser_helpers::IdentMatches<
+ CSSValueID::kFirst, CSSValueID::kLast, CSSValueID::kBaseline>(id);
+}
+
bool IsSelfPositionKeyword(CSSValueID id) {
return css_property_parser_helpers::IdentMatches<
CSSValueID::kStart, CSSValueID::kEnd, CSSValueID::kCenter,
@@ -1181,12 +1206,9 @@ CSSShadowValue* ParseSingleShadow(CSSParserTokenRange& range,
return nullptr;
CSSPrimitiveValue* blur_radius = css_property_parser_helpers::ConsumeLength(
- range, css_parser_mode, kValueRangeAll);
+ range, css_parser_mode, kValueRangeNonNegative);
CSSPrimitiveValue* spread_distance = nullptr;
if (blur_radius) {
- // Blur radius must be non-negative.
- if (blur_radius->GetDoubleValue() < 0)
- return nullptr;
if (inset_and_spread == AllowInsetAndSpread::kAllow) {
spread_distance = css_property_parser_helpers::ConsumeLength(
range, css_parser_mode, kValueRangeAll);
@@ -1272,20 +1294,23 @@ CSSValue* ConsumeCounter(CSSParserTokenRange& range,
value = clampTo<int>(counter_value->GetDoubleValue());
list->Append(*MakeGarbageCollected<CSSValuePair>(
counter_name,
- CSSPrimitiveValue::Create(value, CSSPrimitiveValue::UnitType::kInteger),
+ CSSNumericLiteralValue::Create(value,
+ CSSPrimitiveValue::UnitType::kInteger),
CSSValuePair::kDropIdenticalValues));
} while (!range.AtEnd());
return list;
}
CSSValue* ConsumeFontSize(CSSParserTokenRange& range,
- CSSParserMode css_parser_mode,
+ const CSSParserContext& context,
css_property_parser_helpers::UnitlessQuirk unitless) {
+ if (range.Peek().Id() == CSSValueID::kWebkitXxxLarge)
+ context.Count(WebFeature::kFontSizeWebkitXxxLarge);
if (range.Peek().Id() >= CSSValueID::kXxSmall &&
range.Peek().Id() <= CSSValueID::kLarger)
return css_property_parser_helpers::ConsumeIdent(range);
return css_property_parser_helpers::ConsumeLengthOrPercent(
- range, css_parser_mode, kValueRangeNonNegative, unitless);
+ range, context.Mode(), kValueRangeNonNegative, unitless);
}
CSSValue* ConsumeLineHeight(CSSParserTokenRange& range,
@@ -1585,7 +1610,7 @@ CSSValue* ConsumeGridBreadth(CSSParserTokenRange& range,
token.GetUnitType() == CSSPrimitiveValue::UnitType::kFraction) {
if (range.Peek().NumericValue() < 0)
return nullptr;
- return CSSPrimitiveValue::Create(
+ return CSSNumericLiteralValue::Create(
range.ConsumeIncludingWhitespace().NumericValue(),
CSSPrimitiveValue::UnitType::kFraction);
}
@@ -1880,7 +1905,7 @@ CSSValue* ConsumeGridLine(CSSParserTokenRange& range,
// invalid.
if (numeric_value) {
- numeric_value = CSSPrimitiveValue::Create(
+ numeric_value = CSSNumericLiteralValue::Create(
clampTo(numeric_value->GetIntValue(), -kGridMaxTracks, kGridMaxTracks),
CSSPrimitiveValue::UnitType::kInteger);
}
@@ -2553,7 +2578,7 @@ CSSValue* ConsumeTransitionProperty(CSSParserTokenRange& range,
unresolved_property != CSSPropertyID::kVariable) {
#if DCHECK_IS_ON()
DCHECK(CSSProperty::Get(resolveCSSPropertyID(unresolved_property))
- .IsEnabled());
+ .IsWebExposed());
#endif
range.ConsumeIncludingWhitespace();
return MakeGarbageCollected<CSSCustomIdentValue>(unresolved_property);
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 bfe84e38bee..dbb113f5660 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
@@ -5,6 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PROPERTIES_CSS_PARSING_UTILS_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PROPERTIES_CSS_PARSING_UTILS_H_
+#include "third_party/blink/renderer/core/css/css_numeric_literal_value.h"
#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/css/parser/css_property_parser_helpers.h"
@@ -40,6 +41,7 @@ using IsPositionKeyword = bool (*)(CSSValueID);
constexpr size_t kMaxNumAnimationLonghands = 8;
+bool IsBaselineKeyword(CSSValueID id);
bool IsSelfPositionKeyword(CSSValueID);
bool IsSelfPositionOrLeftOrRightKeyword(CSSValueID);
bool IsContentPositionKeyword(CSSValueID);
@@ -141,7 +143,7 @@ CSSValue* ConsumeCounter(CSSParserTokenRange&, const CSSParserContext&, int);
CSSValue* ConsumeFontSize(
CSSParserTokenRange&,
- CSSParserMode,
+ const CSSParserContext&,
css_property_parser_helpers::UnitlessQuirk =
css_property_parser_helpers::UnitlessQuirk::kForbid);
@@ -255,8 +257,8 @@ CSSValue* ConsumePositionLonghand(CSSParserTokenRange& range,
else
return nullptr;
range.ConsumeIncludingWhitespace();
- return CSSPrimitiveValue::Create(percent,
- CSSPrimitiveValue::UnitType::kPercentage);
+ return CSSNumericLiteralValue::Create(
+ percent, CSSPrimitiveValue::UnitType::kPercentage);
}
return css_property_parser_helpers::ConsumeLengthOrPercent(
range, css_parser_mode, kValueRangeAll);
diff --git a/chromium/third_party/blink/renderer/core/css/properties/css_parsing_utils_test.cc b/chromium/third_party/blink/renderer/core/css/properties/css_parsing_utils_test.cc
index 9b2e8e52799..7b9aad46a4a 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/css_parsing_utils_test.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/css_parsing_utils_test.cc
@@ -2,11 +2,11 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/core/css/properties/css_parsing_utils.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
+#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/core/html/html_html_element.h"
#include "third_party/blink/renderer/core/testing/dummy_page_holder.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/css/properties/css_property.cc b/chromium/third_party/blink/renderer/core/css/properties/css_property.cc
index 7493852e3f0..53d8572a9ae 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/css_property.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/css_property.cc
@@ -5,13 +5,9 @@
#include "third_party/blink/renderer/core/css/properties/css_property.h"
#include "base/stl_util.h"
-#include "third_party/blink/renderer/core/css/cssom/cross_thread_keyword_value.h"
-#include "third_party/blink/renderer/core/css/cssom/cross_thread_style_value.h"
-#include "third_party/blink/renderer/core/css/cssom/cross_thread_unit_value.h"
#include "third_party/blink/renderer/core/css/cssom/cross_thread_unsupported_value.h"
-#include "third_party/blink/renderer/core/css/cssom/css_keyword_value.h"
-#include "third_party/blink/renderer/core/css/cssom/css_unit_value.h"
#include "third_party/blink/renderer/core/css/cssom/style_value_factory.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/core/style/svg_computed_style.h"
#include "third_party/blink/renderer/core/style_property_shorthand.h"
@@ -32,35 +28,24 @@ std::unique_ptr<CrossThreadStyleValue>
CSSProperty::CrossThreadStyleValueFromComputedStyle(
const ComputedStyle& computed_style,
const LayoutObject* layout_object,
- Node* node,
+ const Node* styled_node,
bool allow_visited_style) const {
const CSSValue* css_value = CSSValueFromComputedStyle(
- computed_style, layout_object, node, allow_visited_style);
+ computed_style, layout_object, styled_node, allow_visited_style);
if (!css_value)
return std::make_unique<CrossThreadUnsupportedValue>("");
CSSStyleValue* style_value =
StyleValueFactory::CssValueToStyleValue(GetCSSPropertyName(), *css_value);
if (!style_value)
return std::make_unique<CrossThreadUnsupportedValue>("");
- switch (style_value->GetType()) {
- case CSSStyleValue::StyleValueType::kKeywordType:
- return std::make_unique<CrossThreadKeywordValue>(
- To<CSSKeywordValue>(style_value)->value().IsolatedCopy());
- case CSSStyleValue::StyleValueType::kUnitType:
- return std::make_unique<CrossThreadUnitValue>(
- To<CSSUnitValue>(style_value)->value(),
- To<CSSUnitValue>(style_value)->GetInternalUnit());
- default:
- // Make an isolated copy to ensure that it is safe to pass cross thread.
- return std::make_unique<CrossThreadUnsupportedValue>(
- css_value->CssText().IsolatedCopy());
- }
+ return ComputedStyleUtils::CrossThreadStyleValueFromCSSStyleValue(
+ style_value);
}
const CSSValue* CSSProperty::CSSValueFromComputedStyle(
const ComputedStyle& style,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
const SVGComputedStyle& svg_style = style.SvgStyle();
const CSSProperty& resolved_property =
@@ -69,13 +54,13 @@ const CSSValue* CSSProperty::CSSValueFromComputedStyle(
style, svg_style, layout_object, styled_node, allow_visited_style);
}
-void CSSProperty::FilterEnabledCSSPropertiesIntoVector(
+void CSSProperty::FilterWebExposedCSSPropertiesIntoVector(
const CSSPropertyID* properties,
size_t propertyCount,
Vector<const CSSProperty*>& outVector) {
for (unsigned i = 0; i < propertyCount; i++) {
const CSSProperty& property = Get(properties[i]);
- if (property.IsEnabled())
+ if (property.IsWebExposed())
outVector.push_back(&property);
}
}
diff --git a/chromium/third_party/blink/renderer/core/css/properties/css_property.h b/chromium/third_party/blink/renderer/core/css/properties/css_property.h
index 2ca09d8351e..acc3dcdd278 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/css_property.h
+++ b/chromium/third_party/blink/renderer/core/css/properties/css_property.h
@@ -40,17 +40,22 @@ class CORE_EXPORT CSSProperty : public CSSUnresolvedProperty {
bool IsInterpolable() const { return flags_ & kInterpolable; }
bool IsCompositableProperty() const { return flags_ & kCompositableProperty; }
bool IsDescriptor() const { return flags_ & kDescriptor; }
- bool SupportsPercentage() const { return flags_ & kSupportsPercentage; }
bool IsProperty() const { return flags_ & kProperty; }
- bool IsValidForVisitedLink() const { return flags_ & kValidForVisitedLink; }
bool IsShorthand() const { return flags_ & kShorthand; }
bool IsLonghand() const { return flags_ & kLonghand; }
bool IsInherited() const { return flags_ & kInherited; }
+ bool IsVisited() const { return flags_ & kVisited; }
+ bool IsInternal() const { return flags_ & kInternal; }
+ bool IsAffectedByForcedColors() const {
+ return flags_ & kIsAffectedByForcedColors;
+ }
bool IsRepeated() const { return repetition_separator_ != '\0'; }
char RepetitionSeparator() const { return repetition_separator_; }
- virtual bool IsAffectedByAll() const { return IsEnabled() && IsProperty(); }
+ virtual bool IsAffectedByAll() const {
+ return IsWebExposed() && IsProperty();
+ }
virtual bool IsLayoutDependentProperty() const { return false; }
virtual bool IsLayoutDependent(const ComputedStyle* style,
LayoutObject* layout_object) const {
@@ -61,40 +66,48 @@ class CORE_EXPORT CSSProperty : public CSSUnresolvedProperty {
const ComputedStyle&,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return nullptr;
}
// TODO: Resolve computed auto alignment in applyProperty/ComputedStyle and
- // remove this non-const Node parameter.
+ // remove this const Node parameter.
const CSSValue* CSSValueFromComputedStyle(const ComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const;
virtual std::unique_ptr<CrossThreadStyleValue>
CrossThreadStyleValueFromComputedStyle(const ComputedStyle& computed_style,
const LayoutObject* layout_object,
- Node* node,
+ const Node* styled_node,
bool allow_visited_style) const;
virtual const CSSProperty& ResolveDirectionAwareProperty(TextDirection,
WritingMode) const {
return *this;
}
- static void FilterEnabledCSSPropertiesIntoVector(const CSSPropertyID*,
- size_t length,
- Vector<const CSSProperty*>&);
+ virtual const CSSProperty* GetVisitedProperty() const { return nullptr; }
+ virtual const CSSProperty* GetUnvisitedProperty() const { return nullptr; }
+ static void FilterWebExposedCSSPropertiesIntoVector(
+ const CSSPropertyID*,
+ size_t length,
+ Vector<const CSSProperty*>&);
protected:
enum Flag : uint16_t {
kInterpolable = 1 << 0,
kCompositableProperty = 1 << 1,
kDescriptor = 1 << 2,
- kSupportsPercentage = 1 << 3,
- kProperty = 1 << 4,
- kValidForVisitedLink = 1 << 5,
- kShorthand = 1 << 6,
- kLonghand = 1 << 7,
- kInherited = 1 << 8
+ kProperty = 1 << 3,
+ kShorthand = 1 << 4,
+ kLonghand = 1 << 5,
+ kInherited = 1 << 6,
+ // Visited properties are internal counterparts to properties that
+ // are permitted in :visited styles. They are used to handle and store the
+ // computed value as seen by painting (as opposed to the computed value
+ // seen by CSSOM, which is represented by the unvisited property).
+ kVisited = 1 << 7,
+ kInternal = 1 << 8,
+ kIsAffectedByForcedColors = 1 << 9
};
constexpr CSSProperty(CSSPropertyID property_id,
diff --git a/chromium/third_party/blink/renderer/core/css/properties/css_property_methods.json5 b/chromium/third_party/blink/renderer/core/css/properties/css_property_methods.json5
index 5fbb9e28d0f..b666b549b65 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/css_property_methods.json5
+++ b/chromium/third_party/blink/renderer/core/css/properties/css_property_methods.json5
@@ -32,7 +32,7 @@
{
name: "CSSValueFromComputedStyleInternal",
return_type: "const CSSValue*",
- parameters: "(const ComputedStyle&, const SVGComputedStyle&, const LayoutObject*, Node*, bool allow_visited_style)",
+ parameters: "(const ComputedStyle&, const SVGComputedStyle&, const LayoutObject*, const Node*, bool allow_visited_style)",
},
{
name: "ColorIncludingFallback",
diff --git a/chromium/third_party/blink/renderer/core/css/properties/css_property_test.cc b/chromium/third_party/blink/renderer/core/css/properties/css_property_test.cc
new file mode 100644
index 00000000000..80cbc05cee7
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/properties/css_property_test.cc
@@ -0,0 +1,90 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/css/properties/css_property.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_test_helpers.h"
+#include "third_party/blink/renderer/core/css/properties/css_property_instances.h"
+#include "third_party/blink/renderer/core/style/computed_style.h"
+#include "third_party/blink/renderer/core/style/data_equivalency.h"
+#include "third_party/blink/renderer/core/testing/page_test_base.h"
+
+namespace blink {
+
+class CSSPropertyTest : public PageTestBase {};
+
+TEST_F(CSSPropertyTest, VisitedPropertiesAreNotWebExposed) {
+ for (CSSPropertyID property_id : CSSPropertyIDList()) {
+ const CSSProperty& property = CSSProperty::Get(property_id);
+ EXPECT_TRUE(!property.IsVisited() || !property.IsWebExposed());
+ }
+}
+
+TEST_F(CSSPropertyTest, GetVisitedPropertyOnlyReturnsVisitedProperties) {
+ for (CSSPropertyID property_id : CSSPropertyIDList()) {
+ const CSSProperty& property = CSSProperty::Get(property_id);
+ const CSSProperty* visited = property.GetVisitedProperty();
+ EXPECT_TRUE(!visited || visited->IsVisited());
+ }
+}
+
+TEST_F(CSSPropertyTest, GetUnvisitedPropertyFromVisited) {
+ for (CSSPropertyID property_id : CSSPropertyIDList()) {
+ const CSSProperty& property = CSSProperty::Get(property_id);
+ EXPECT_EQ(property.IsVisited(),
+ static_cast<bool>(property.GetUnvisitedProperty()));
+ }
+}
+
+TEST_F(CSSPropertyTest, InternalEffectiveZoomNotWebExposed) {
+ const CSSProperty& property = GetCSSPropertyInternalEffectiveZoom();
+ EXPECT_FALSE(property.IsWebExposed());
+}
+
+TEST_F(CSSPropertyTest, InternalEffectiveZoomCanBeParsed) {
+ const CSSValue* value = css_test_helpers::ParseLonghand(
+ GetDocument(), GetCSSPropertyInternalEffectiveZoom(), "1.2");
+ ASSERT_TRUE(value);
+ EXPECT_EQ("1.2", value->CssText());
+}
+
+TEST_F(CSSPropertyTest, VisitedPropertiesCanParseValues) {
+ scoped_refptr<ComputedStyle> initial_style = ComputedStyle::Create();
+
+ // Count the number of 'visited' properties seen.
+ size_t num_visited = 0;
+
+ for (CSSPropertyID property_id : CSSPropertyIDList()) {
+ const CSSProperty& property = CSSProperty::Get(property_id);
+ const CSSProperty* visited = property.GetVisitedProperty();
+ if (!visited)
+ continue;
+
+ // Get any value compatible with 'property'. The initial value will do.
+ const CSSValue* initial_value = property.CSSValueFromComputedStyle(
+ *initial_style, nullptr /* layout_object */, nullptr /* node */,
+ false /* allow_visited_style */);
+ ASSERT_TRUE(initial_value);
+ String css_text = initial_value->CssText();
+
+ // Parse the initial value using both the regular property, and the
+ // accompanying 'visited' property.
+ const CSSValue* parsed_regular_value = css_test_helpers::ParseLonghand(
+ GetDocument(), property, initial_value->CssText());
+ const CSSValue* parsed_visited_value = css_test_helpers::ParseLonghand(
+ GetDocument(), *visited, initial_value->CssText());
+
+ // The properties should have identical parsing behavior.
+ EXPECT_TRUE(DataEquivalent(parsed_regular_value, parsed_visited_value));
+
+ num_visited++;
+ }
+
+ // Verify that we have seen at least one visited property. If we didn't (and
+ // there is no bug), it means this test can be removed.
+ EXPECT_GT(num_visited, 0u);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/properties/css_unresolved_property.h b/chromium/third_party/blink/renderer/core/css/properties/css_unresolved_property.h
index 3011c84fc54..9abed9fed82 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/css_unresolved_property.h
+++ b/chromium/third_party/blink/renderer/core/css/properties/css_unresolved_property.h
@@ -5,6 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PROPERTIES_CSS_UNRESOLVED_PROPERTY_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_PROPERTIES_CSS_UNRESOLVED_PROPERTY_H_
+#include "third_party/blink/renderer/core/css/properties/css_exposure.h"
#include "third_party/blink/renderer/core/css/properties/css_property_instances.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
@@ -18,7 +19,9 @@ class CORE_EXPORT CSSUnresolvedProperty {
static const CSSUnresolvedProperty& Get(CSSPropertyID);
static const CSSUnresolvedProperty* GetAliasProperty(CSSPropertyID);
- virtual bool IsEnabled() const { return true; }
+ bool IsWebExposed() const { return blink::IsWebExposed(Exposure()); }
+ bool IsUAExposed() const { return blink::IsUAExposed(Exposure()); }
+ virtual CSSExposure Exposure() const { return CSSExposure::kWeb; }
virtual bool IsResolvedProperty() const { return false; }
virtual const char* GetPropertyName() const {
NOTREACHED();
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
index c24e5e8adc6..554dcc56531 100644
--- 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
@@ -9,7 +9,9 @@
#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/css/resolver/style_builder_converter.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
+#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
namespace blink {
@@ -65,6 +67,14 @@ void CustomProperty::ApplyInherit(StyleResolverState& state) const {
void CustomProperty::ApplyValue(StyleResolverState& state,
const CSSValue& value) const {
+ if (value.IsInvalidVariableValue()) {
+ DCHECK(RuntimeEnabledFeatures::CSSCascadeEnabled());
+ state.Style()->SetVariableData(name_, nullptr, IsInherited());
+ if (registration_)
+ state.Style()->SetVariableValue(name_, nullptr, IsInherited());
+ return;
+ }
+
const auto& declaration = To<CSSCustomPropertyDeclaration>(value);
bool is_inherited_property = IsInherited();
@@ -79,10 +89,45 @@ void CustomProperty::ApplyValue(StyleResolverState& state,
} else if (inherit) {
ApplyInherit(state);
} else {
- state.Style()->SetVariableData(name_, declaration.Value(),
- is_inherited_property);
+ if (!RuntimeEnabledFeatures::CSSCascadeEnabled()) {
+ state.Style()->SetVariableData(name_, declaration.Value(),
+ is_inherited_property);
+ if (registration_)
+ state.Style()->SetVariableValue(name_, nullptr, is_inherited_property);
+ return;
+ }
+
+ scoped_refptr<CSSVariableData> data = declaration.Value();
+ DCHECK(!data->NeedsVariableResolution());
+
+ state.Style()->SetVariableData(name_, data, is_inherited_property);
+
if (registration_) {
- state.Style()->SetVariableValue(name_, nullptr, is_inherited_property);
+ // TODO(andruud): Store CSSParserContext on CSSCustomPropertyDeclaration
+ // and use that.
+ const CSSParserContext* context =
+ StrictCSSParserContext(state.GetDocument().GetSecureContextMode());
+ auto mode = CSSParserLocalContext::VariableMode::kTyped;
+ auto local_context = CSSParserLocalContext().WithVariableMode(mode);
+ CSSParserTokenRange range = data->TokenRange();
+ const CSSValue* registered_value =
+ ParseSingleValue(range, *context, local_context);
+ if (!registered_value) {
+ if (is_inherited_property)
+ ApplyInherit(state);
+ else
+ ApplyInitial(state);
+ return;
+ }
+
+ registered_value = &StyleBuilderConverter::ConvertRegisteredPropertyValue(
+ state, *registered_value, data->BaseURL(), data->Charset());
+ data = StyleBuilderConverter::ConvertRegisteredPropertyVariableData(
+ *registered_value, data->IsAnimationTainted());
+
+ state.Style()->SetVariableData(name_, data, is_inherited_property);
+ state.Style()->SetVariableValue(name_, registered_value,
+ is_inherited_property);
}
}
}
@@ -109,7 +154,7 @@ const CSSValue* CustomProperty::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
if (registration_) {
const CSSValue* value = style.GetVariableValue(name_, IsInherited());
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
index 30ab3652e91..a5f80df9b3c 100644
--- 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
@@ -45,9 +45,11 @@ class CORE_EXPORT CustomProperty : public Variable {
const ComputedStyle&,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const override;
+ bool IsRegistered() const { return registration_; }
+
void Trace(blink::Visitor* visitor) { visitor->Trace(registration_); }
private:
@@ -65,6 +67,14 @@ class CORE_EXPORT CustomProperty : public Variable {
Member<const PropertyRegistration> registration_;
};
+template <>
+struct DowncastTraits<CustomProperty> {
+ static bool AllowFrom(const CSSProperty& property) {
+ DCHECK(!Variable::IsStaticInstance(property));
+ return property.PropertyID() == CSSPropertyID::kVariable;
+ }
+};
+
} // 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/longhands_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/longhands/longhands_custom.cc
index 3b9bcc92c13..a5ae06605b7 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/longhands/longhands_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/longhands/longhands_custom.cc
@@ -14,6 +14,7 @@
#include "third_party/blink/renderer/core/css/css_grid_template_areas_value.h"
#include "third_party/blink/renderer/core/css/css_identifier_value.h"
#include "third_party/blink/renderer/core/css/css_layout_function_value.h"
+#include "third_party/blink/renderer/core/css/css_numeric_literal_value.h"
#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_quad_value.h"
@@ -35,369 +36,13 @@
#include "third_party/blink/renderer/core/css/parser/font_variant_numeric_parser.h"
#include "third_party/blink/renderer/core/css/properties/computed_style_utils.h"
#include "third_party/blink/renderer/core/css/properties/css_parsing_utils.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/align_content.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/align_items.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/align_self.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/alignment_baseline.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/animation_delay.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/animation_direction.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/animation_duration.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/animation_fill_mode.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/animation_iteration_count.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/animation_name.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/animation_play_state.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/animation_timing_function.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/backdrop_filter.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/backface_visibility.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/background_attachment.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/background_blend_mode.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/background_clip.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/background_color.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/background_image.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/background_origin.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/background_position_x.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/background_position_y.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/background_size.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/baseline_shift.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/block_size.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/border_block_end_color.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/border_block_end_width.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/border_block_start_color.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/border_block_start_width.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/border_bottom_color.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/border_bottom_left_radius.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/border_bottom_right_radius.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/border_bottom_style.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/border_bottom_width.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/border_collapse.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/border_image_outset.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/border_image_repeat.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/border_image_slice.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/border_image_source.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/border_image_width.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/border_inline_end_color.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/border_inline_end_width.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/border_inline_start_color.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/border_inline_start_width.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/border_left_color.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/border_left_style.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/border_left_width.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/border_right_color.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/border_right_style.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/border_right_width.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/border_top_color.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/border_top_left_radius.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/border_top_right_radius.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/border_top_style.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/border_top_width.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/bottom.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/box_shadow.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/box_sizing.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/break_after.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/break_before.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/break_inside.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/buffered_rendering.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/caption_side.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/caret_color.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/clear.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/clip.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/clip_path.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/clip_rule.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/color.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/color_interpolation.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/color_interpolation_filters.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/color_rendering.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/color_scheme.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/column_count.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/column_fill.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/column_gap.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/column_rule_color.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/column_rule_style.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/column_rule_width.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/column_span.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/column_width.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/contain.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/content.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/counter_increment.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/counter_reset.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/cursor.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/cx.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/cy.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/d.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/direction.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/display.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/dominant_baseline.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/empty_cells.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/fill.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/fill_opacity.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/fill_rule.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/filter.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/flex_basis.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/flex_direction.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/flex_grow.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/flex_shrink.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/flex_wrap.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/float.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/flood_color.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/flood_opacity.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/font_family.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/font_feature_settings.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/font_kerning.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/font_size.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/font_size_adjust.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/font_stretch.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/font_style.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/font_variant_caps.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/font_variant_east_asian.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/font_variant_ligatures.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/font_variant_numeric.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/font_variation_settings.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/font_weight.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/grid_auto_columns.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/grid_auto_flow.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/grid_auto_rows.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/grid_column_end.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/grid_column_start.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/grid_row_end.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/grid_row_start.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/grid_template_areas.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/grid_template_columns.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/grid_template_rows.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/height.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/hyphens.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/image_orientation.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/image_rendering.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/inline_size.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/inset_block_end.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/inset_block_start.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/inset_inline_end.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/inset_inline_start.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/isolation.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/justify_content.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/justify_items.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/justify_self.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/left.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/letter_spacing.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/lighting_color.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/line_break.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/line_height.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/line_height_step.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/list_style_image.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/list_style_position.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/list_style_type.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/margin_block_end.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/margin_block_start.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/margin_bottom.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/margin_inline_end.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/margin_inline_start.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/margin_left.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/margin_right.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/margin_top.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/marker_end.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/marker_mid.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/marker_start.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/mask.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/mask_source_type.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/mask_type.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/max_block_size.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/max_height.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/max_inline_size.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/max_width.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/min_block_size.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/min_height.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/min_inline_size.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/min_width.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/mix_blend_mode.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/object_fit.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/object_position.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/offset_anchor.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/offset_distance.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/offset_path.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/offset_position.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/offset_rotate.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/opacity.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/order.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/orphans.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/outline_color.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/outline_offset.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/outline_style.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/outline_width.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/overflow_anchor.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/overflow_wrap.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/overflow_x.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/overflow_y.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/overscroll_behavior_x.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/overscroll_behavior_y.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/padding_block_end.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/padding_block_start.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/padding_bottom.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/padding_inline_end.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/padding_inline_start.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/padding_left.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/padding_right.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/padding_top.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/page.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/paint_order.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/perspective.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/perspective_origin.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/pointer_events.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/position.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/quotes.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/r.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/resize.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/right.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/rotate.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/row_gap.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/rx.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/ry.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/scale.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/scroll_behavior.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/scroll_customization.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/scroll_margin_block_end.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/scroll_margin_block_start.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/scroll_margin_bottom.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/scroll_margin_inline_end.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/scroll_margin_inline_start.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/scroll_margin_left.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/scroll_margin_right.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/scroll_margin_top.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/scroll_padding_block_end.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/scroll_padding_block_start.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/scroll_padding_bottom.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/scroll_padding_inline_end.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/scroll_padding_inline_start.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/scroll_padding_left.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/scroll_padding_right.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/scroll_padding_top.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/scroll_snap_align.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/scroll_snap_stop.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/scroll_snap_type.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/shape_image_threshold.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/shape_margin.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/shape_outside.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/shape_rendering.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/size.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/speak.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/stop_color.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/stop_opacity.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/stroke.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/stroke_dasharray.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/stroke_dashoffset.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/stroke_linecap.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/stroke_linejoin.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/stroke_miterlimit.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/stroke_opacity.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/stroke_width.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/tab_size.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/table_layout.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/text_align.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/text_align_last.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/text_anchor.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/text_combine_upright.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/text_decoration_color.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/text_decoration_line.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/text_decoration_skip_ink.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/text_decoration_style.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/text_indent.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/text_justify.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/text_orientation.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/text_overflow.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/text_rendering.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/text_shadow.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/text_size_adjust.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/text_transform.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/text_underline_position.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/top.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/touch_action.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/transform.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/transform_box.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/transform_origin.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/transform_style.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/transition_delay.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/transition_duration.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/transition_property.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/transition_timing_function.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/translate.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/unicode_bidi.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/user_select.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/vector_effect.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/vertical_align.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/visibility.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_app_region.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_appearance.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_border_horizontal_spacing.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_border_image.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_border_vertical_spacing.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_box_align.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_box_decoration_break.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_box_direction.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_box_flex.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_box_ordinal_group.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_box_orient.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_box_pack.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_box_reflect.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_font_size_delta.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_font_smoothing.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_highlight.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_hyphenate_character.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_line_break.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_line_clamp.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_locale.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_margin_after_collapse.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_margin_before_collapse.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_margin_bottom_collapse.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_margin_top_collapse.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_mask_box_image_outset.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_mask_box_image_repeat.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_mask_box_image_slice.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_mask_box_image_source.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_mask_box_image_width.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_mask_clip.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_mask_composite.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_mask_image.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_mask_origin.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_mask_position_x.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_mask_position_y.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_mask_size.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_perspective_origin_x.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_perspective_origin_y.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_print_color_adjust.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_rtl_ordering.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_ruby_position.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_tap_highlight_color.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_text_combine.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_text_decorations_in_effect.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_text_emphasis_color.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_text_emphasis_position.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_text_emphasis_style.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_text_fill_color.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_text_orientation.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_text_security.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_text_stroke_color.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_text_stroke_width.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_transform_origin_x.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_transform_origin_y.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_transform_origin_z.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_user_drag.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_user_modify.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/webkit_writing_mode.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/white_space.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/widows.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/width.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/will_change.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/word_break.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/word_spacing.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/writing_mode.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/x.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/y.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/z_index.h"
-#include "third_party/blink/renderer/core/css/properties/longhands/zoom.h"
+#include "third_party/blink/renderer/core/css/properties/longhands.h"
#include "third_party/blink/renderer/core/css/resolver/style_builder_converter.h"
+#include "third_party/blink/renderer/core/css/resolver/style_resolver_state.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_value_keywords.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/frame/web_feature.h"
#include "third_party/blink/renderer/core/layout/layout_box.h"
#include "third_party/blink/renderer/core/layout/layout_object.h"
@@ -407,6 +52,7 @@
#include "third_party/blink/renderer/core/style/shape_clip_path_operation.h"
#include "third_party/blink/renderer/core/style_property_shorthand.h"
#include "third_party/blink/renderer/platform/geometry/length.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
// Implementations of methods in Longhand subclasses that aren't generated.
@@ -426,7 +72,7 @@ const CSSValue* AlignContent::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::
ValueForContentPositionAndDistributionWithOverflowAlignment(
@@ -449,7 +95,7 @@ const CSSValue* AlignItems::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForItemPositionWithOverflowAlignment(
style.AlignItems());
@@ -467,7 +113,7 @@ const CSSValue* AlignSelf::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForItemPositionWithOverflowAlignment(
style.AlignSelf());
@@ -476,7 +122,7 @@ const CSSValue* AlignmentBaseline::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(svg_style.AlignmentBaseline());
}
@@ -493,16 +139,16 @@ const CSSValue* AnimationDelay::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForAnimationDelay(style.Animations());
}
const CSSValue* AnimationDelay::InitialValue() const {
DEFINE_STATIC_LOCAL(
- Persistent<CSSValue>, value,
- (CSSPrimitiveValue::Create(CSSTimingData::InitialDelay(),
- CSSPrimitiveValue::UnitType::kSeconds)));
+ const Persistent<CSSValue>, value,
+ (CSSNumericLiteralValue::Create(CSSTimingData::InitialDelay(),
+ CSSPrimitiveValue::UnitType::kSeconds)));
return value;
}
@@ -521,7 +167,7 @@ const CSSValue* AnimationDirection::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
CSSValueList* list = CSSValueList::CreateCommaSeparated();
const CSSAnimationData* animation_data = style.Animations();
@@ -537,7 +183,7 @@ const CSSValue* AnimationDirection::CSSValueFromComputedStyleInternal(
}
const CSSValue* AnimationDirection::InitialValue() const {
- DEFINE_STATIC_LOCAL(Persistent<CSSValue>, value,
+ DEFINE_STATIC_LOCAL(const Persistent<CSSValue>, value,
(CSSIdentifierValue::Create(CSSValueID::kNormal)));
return value;
}
@@ -554,16 +200,16 @@ const CSSValue* AnimationDuration::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForAnimationDuration(style.Animations());
}
const CSSValue* AnimationDuration::InitialValue() const {
DEFINE_STATIC_LOCAL(
- Persistent<CSSValue>, value,
- (CSSPrimitiveValue::Create(CSSTimingData::InitialDuration(),
- CSSPrimitiveValue::UnitType::kSeconds)));
+ const Persistent<CSSValue>, value,
+ (CSSNumericLiteralValue::Create(CSSTimingData::InitialDuration(),
+ CSSPrimitiveValue::UnitType::kSeconds)));
return value;
}
@@ -582,7 +228,7 @@ const CSSValue* AnimationFillMode::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
CSSValueList* list = CSSValueList::CreateCommaSeparated();
const CSSAnimationData* animation_data = style.Animations();
@@ -598,7 +244,7 @@ const CSSValue* AnimationFillMode::CSSValueFromComputedStyleInternal(
}
const CSSValue* AnimationFillMode::InitialValue() const {
- DEFINE_STATIC_LOCAL(Persistent<CSSValue>, value,
+ DEFINE_STATIC_LOCAL(const Persistent<CSSValue>, value,
(CSSIdentifierValue::Create(CSSValueID::kNone)));
return value;
}
@@ -615,7 +261,7 @@ const CSSValue* AnimationIterationCount::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
CSSValueList* list = CSSValueList::CreateCommaSeparated();
const CSSAnimationData* animation_data = style.Animations();
@@ -633,9 +279,9 @@ const CSSValue* AnimationIterationCount::CSSValueFromComputedStyleInternal(
const CSSValue* AnimationIterationCount::InitialValue() const {
DEFINE_STATIC_LOCAL(
- Persistent<CSSValue>, value,
- (CSSPrimitiveValue::Create(CSSAnimationData::InitialIterationCount(),
- CSSPrimitiveValue::UnitType::kNumber)));
+ const Persistent<CSSValue>, value,
+ (CSSNumericLiteralValue::Create(CSSAnimationData::InitialIterationCount(),
+ CSSPrimitiveValue::UnitType::kNumber)));
return value;
}
@@ -653,7 +299,7 @@ const CSSValue* AnimationName::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
CSSValueList* list = CSSValueList::CreateCommaSeparated();
const CSSAnimationData* animation_data = style.Animations();
@@ -669,7 +315,7 @@ const CSSValue* AnimationName::CSSValueFromComputedStyleInternal(
}
const CSSValue* AnimationName::InitialValue() const {
- DEFINE_STATIC_LOCAL(Persistent<CSSValue>, value,
+ DEFINE_STATIC_LOCAL(const Persistent<CSSValue>, value,
(CSSIdentifierValue::Create(CSSValueID::kNone)));
return value;
}
@@ -688,7 +334,7 @@ const CSSValue* AnimationPlayState::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
CSSValueList* list = CSSValueList::CreateCommaSeparated();
const CSSAnimationData* animation_data = style.Animations();
@@ -704,7 +350,7 @@ const CSSValue* AnimationPlayState::CSSValueFromComputedStyleInternal(
}
const CSSValue* AnimationPlayState::InitialValue() const {
- DEFINE_STATIC_LOCAL(Persistent<CSSValue>, value,
+ DEFINE_STATIC_LOCAL(const Persistent<CSSValue>, value,
(CSSIdentifierValue::Create(CSSValueID::kRunning)));
return value;
}
@@ -721,14 +367,14 @@ const CSSValue* AnimationTimingFunction::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForAnimationTimingFunction(
style.Animations());
}
const CSSValue* AnimationTimingFunction::InitialValue() const {
- DEFINE_STATIC_LOCAL(Persistent<CSSValue>, value,
+ DEFINE_STATIC_LOCAL(const Persistent<CSSValue>, value,
(CSSIdentifierValue::Create(CSSValueID::kEase)));
return value;
}
@@ -744,7 +390,7 @@ const CSSValue* BackdropFilter::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForFilter(style, style.BackdropFilter());
}
@@ -752,7 +398,7 @@ const CSSValue* BackfaceVisibility::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(
(style.BackfaceVisibility() == EBackfaceVisibility::kHidden)
@@ -772,7 +418,7 @@ const CSSValue* BackgroundAttachment::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
CSSValueList* list = CSSValueList::CreateCommaSeparated();
for (const FillLayer* curr_layer = &style.BackgroundLayers(); curr_layer;
@@ -793,7 +439,7 @@ const CSSValue* BackgroundBlendMode::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
CSSValueList* list = CSSValueList::CreateCommaSeparated();
for (const FillLayer* curr_layer = &style.BackgroundLayers(); curr_layer;
@@ -814,7 +460,7 @@ const CSSValue* BackgroundClip::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
CSSValueList* list = CSSValueList::CreateCommaSeparated();
const FillLayer* curr_layer = &style.BackgroundLayers();
@@ -836,36 +482,23 @@ const CSSValue* BackgroundColor::ParseSingleValue(
const blink::Color BackgroundColor::ColorIncludingFallback(
bool visited_link,
const ComputedStyle& style) const {
- StyleColor style_color = visited_link ? style.VisitedLinkBackgroundColor()
- : style.BackgroundColor();
- blink::Color result =
- visited_link ? style.VisitedLinkColor() : style.GetColor();
- if (!style_color.IsCurrentColor())
- result = style_color.GetColor();
-
- // FIXME: Technically someone could explicitly specify the color transparent,
- // but for now we'll just assume that if the background color is transparent
- // that it wasn't set. Note that it's weird that we're returning unvisited
- // info for a visited link, but given our restriction that the alpha values
- // have to match, it makes more sense to return the unvisited background color
- // if specified than it does to return black. This behavior matches what
- // Firefox 4 does as well.
- if (visited_link && result == blink::Color::kTransparent)
- return ColorIncludingFallback(false, style);
-
- return result;
+ DCHECK(!visited_link);
+ return style.BackgroundColor().Resolve(style.GetColor());
}
const CSSValue* BackgroundColor::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
- return allow_visited_style ? cssvalue::CSSColorValue::Create(
- style.VisitedDependentColor(*this).Rgb())
- : ComputedStyleUtils::CurrentColorOrValidColor(
- style, style.BackgroundColor());
+ if (allow_visited_style) {
+ return cssvalue::CSSColorValue::Create(
+ style.VisitedDependentColor(*this).Rgb());
+ }
+
+ return ComputedStyleUtils::CurrentColorOrValidColor(style,
+ style.BackgroundColor());
}
const CSSValue* BackgroundImage::ParseSingleValue(
@@ -880,7 +513,7 @@ const CSSValue* BackgroundImage::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
const FillLayer& fill_layer = style.BackgroundLayers();
return ComputedStyleUtils::BackgroundImageOrWebkitMaskImage(fill_layer);
@@ -898,7 +531,7 @@ const CSSValue* BackgroundOrigin::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
CSSValueList* list = CSSValueList::CreateCommaSeparated();
const FillLayer* curr_layer = &style.BackgroundLayers();
@@ -923,7 +556,7 @@ const CSSValue* BackgroundPositionX::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
const FillLayer* curr_layer = &style.BackgroundLayers();
return ComputedStyleUtils::BackgroundPositionXOrWebkitMaskPositionX(
@@ -944,7 +577,7 @@ const CSSValue* BackgroundPositionY::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
const FillLayer* curr_layer = &style.BackgroundLayers();
return ComputedStyleUtils::BackgroundPositionYOrWebkitMaskPositionY(
@@ -963,7 +596,7 @@ const CSSValue* BackgroundSize::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
const FillLayer& fill_layer = style.BackgroundLayers();
return ComputedStyleUtils::BackgroundImageOrWebkitMaskSize(style, fill_layer);
@@ -985,7 +618,7 @@ const CSSValue* BaselineShift::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
switch (svg_style.BaselineShift()) {
case BS_SUPER:
@@ -1090,10 +723,9 @@ const CSSValue* BorderBottomColor::ParseSingleValue(
const blink::Color BorderBottomColor::ColorIncludingFallback(
bool visited_link,
const ComputedStyle& style) const {
- StyleColor result = visited_link ? style.VisitedLinkBorderBottomColor()
- : style.BorderBottomColor();
- EBorderStyle border_style = style.BorderBottomStyle();
- return ComputedStyleUtils::BorderSideColor(style, result, border_style,
+ DCHECK(!visited_link);
+ return ComputedStyleUtils::BorderSideColor(style, style.BorderBottomColor(),
+ style.BorderBottomStyle(),
visited_link);
}
@@ -1101,7 +733,7 @@ const CSSValue* BorderBottomColor::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return allow_visited_style ? cssvalue::CSSColorValue::Create(
style.VisitedDependentColor(*this).Rgb())
@@ -1120,7 +752,7 @@ const CSSValue* BorderBottomLeftRadius::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return &ComputedStyleUtils::ValueForBorderRadiusCorner(
style.BorderBottomLeftRadius(), style);
@@ -1137,7 +769,7 @@ const CSSValue* BorderBottomRightRadius::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return &ComputedStyleUtils::ValueForBorderRadiusCorner(
style.BorderBottomRightRadius(), style);
@@ -1146,7 +778,7 @@ const CSSValue* BorderBottomStyle::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.BorderBottomStyle());
}
@@ -1162,7 +794,7 @@ const CSSValue* BorderBottomWidth::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ZoomAdjustedPixelValue(style.BorderBottomWidth(), style);
}
@@ -1171,7 +803,7 @@ const CSSValue* BorderCollapse::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
if (style.BorderCollapse() == EBorderCollapse::kCollapse)
return CSSIdentifierValue::Create(CSSValueID::kCollapse);
@@ -1189,7 +821,7 @@ const CSSValue* BorderImageOutset::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForNinePieceImageQuad(
style.BorderImage().Outset(), style);
@@ -1197,10 +829,10 @@ const CSSValue* BorderImageOutset::CSSValueFromComputedStyleInternal(
const CSSValue* BorderImageOutset::InitialValue() const {
DEFINE_STATIC_LOCAL(
- Persistent<CSSQuadValue>, value,
- (CSSQuadValue::Create(
- CSSPrimitiveValue::Create(0, CSSPrimitiveValue::UnitType::kInteger),
- CSSQuadValue::kSerializeAsQuad)));
+ const Persistent<CSSQuadValue>, value,
+ (CSSQuadValue::Create(CSSNumericLiteralValue::Create(
+ 0, CSSPrimitiveValue::UnitType::kInteger),
+ CSSQuadValue::kSerializeAsQuad)));
return value;
}
@@ -1215,13 +847,13 @@ const CSSValue* BorderImageRepeat::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForNinePieceImageRepeat(style.BorderImage());
}
const CSSValue* BorderImageRepeat::InitialValue() const {
- DEFINE_STATIC_LOCAL(Persistent<CSSValue>, value,
+ DEFINE_STATIC_LOCAL(const Persistent<CSSValue>, value,
(CSSIdentifierValue::Create(CSSValueID::kStretch)));
return value;
}
@@ -1238,17 +870,17 @@ const CSSValue* BorderImageSlice::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForNinePieceImageSlice(style.BorderImage());
}
const CSSValue* BorderImageSlice::InitialValue() const {
DEFINE_STATIC_LOCAL(
- Persistent<CSSBorderImageSliceValue>, value,
+ const Persistent<CSSBorderImageSliceValue>, value,
(MakeGarbageCollected<CSSBorderImageSliceValue>(
CSSQuadValue::Create(
- CSSPrimitiveValue::Create(
+ CSSNumericLiteralValue::Create(
100, CSSPrimitiveValue::UnitType::kPercentage),
CSSQuadValue::kSerializeAsQuad),
/* fill */ false)));
@@ -1266,7 +898,7 @@ const CSSValue* BorderImageSource::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
if (style.BorderImageSource())
return style.BorderImageSource()->ComputedCSSValue();
@@ -1274,7 +906,7 @@ const CSSValue* BorderImageSource::CSSValueFromComputedStyleInternal(
}
const CSSValue* BorderImageSource::InitialValue() const {
- DEFINE_STATIC_LOCAL(Persistent<CSSValue>, value,
+ DEFINE_STATIC_LOCAL(const Persistent<CSSValue>, value,
(CSSIdentifierValue::Create(CSSValueID::kNone)));
return value;
}
@@ -1296,7 +928,7 @@ const CSSValue* BorderImageWidth::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForNinePieceImageQuad(
style.BorderImage().BorderSlices(), style);
@@ -1304,10 +936,10 @@ const CSSValue* BorderImageWidth::CSSValueFromComputedStyleInternal(
const CSSValue* BorderImageWidth::InitialValue() const {
DEFINE_STATIC_LOCAL(
- Persistent<CSSQuadValue>, value,
- (CSSQuadValue::Create(
- CSSPrimitiveValue::Create(1, CSSPrimitiveValue::UnitType::kInteger),
- CSSQuadValue::kSerializeAsQuad)));
+ const Persistent<CSSQuadValue>, value,
+ (CSSQuadValue::Create(CSSNumericLiteralValue::Create(
+ 1, CSSPrimitiveValue::UnitType::kInteger),
+ CSSQuadValue::kSerializeAsQuad)));
return value;
}
@@ -1354,18 +986,16 @@ const CSSValue* BorderLeftColor::ParseSingleValue(
const blink::Color BorderLeftColor::ColorIncludingFallback(
bool visited_link,
const ComputedStyle& style) const {
- StyleColor result = visited_link ? style.VisitedLinkBorderLeftColor()
- : style.BorderLeftColor();
- EBorderStyle border_style = style.BorderLeftStyle();
- return ComputedStyleUtils::BorderSideColor(style, result, border_style,
- visited_link);
+ DCHECK(!visited_link);
+ return ComputedStyleUtils::BorderSideColor(
+ style, style.BorderLeftColor(), style.BorderLeftStyle(), visited_link);
}
const CSSValue* BorderLeftColor::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return allow_visited_style ? cssvalue::CSSColorValue::Create(
style.VisitedDependentColor(*this).Rgb())
@@ -1377,7 +1007,7 @@ const CSSValue* BorderLeftStyle::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.BorderLeftStyle());
}
@@ -1393,7 +1023,7 @@ const CSSValue* BorderLeftWidth::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ZoomAdjustedPixelValue(style.BorderLeftWidth(), style);
}
@@ -1409,18 +1039,16 @@ const CSSValue* BorderRightColor::ParseSingleValue(
const blink::Color BorderRightColor::ColorIncludingFallback(
bool visited_link,
const ComputedStyle& style) const {
- StyleColor result = visited_link ? style.VisitedLinkBorderRightColor()
- : style.BorderRightColor();
- EBorderStyle border_style = style.BorderRightStyle();
- return ComputedStyleUtils::BorderSideColor(style, result, border_style,
- visited_link);
+ DCHECK(!visited_link);
+ return ComputedStyleUtils::BorderSideColor(
+ style, style.BorderRightColor(), style.BorderRightStyle(), visited_link);
}
const CSSValue* BorderRightColor::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return allow_visited_style ? cssvalue::CSSColorValue::Create(
style.VisitedDependentColor(*this).Rgb())
@@ -1432,7 +1060,7 @@ const CSSValue* BorderRightStyle::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.BorderRightStyle());
}
@@ -1448,7 +1076,7 @@ const CSSValue* BorderRightWidth::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ZoomAdjustedPixelValue(style.BorderRightWidth(), style);
}
@@ -1464,18 +1092,16 @@ const CSSValue* BorderTopColor::ParseSingleValue(
const blink::Color BorderTopColor::ColorIncludingFallback(
bool visited_link,
const ComputedStyle& style) const {
- StyleColor result =
- visited_link ? style.VisitedLinkBorderTopColor() : style.BorderTopColor();
- EBorderStyle border_style = style.BorderTopStyle();
- return ComputedStyleUtils::BorderSideColor(style, result, border_style,
- visited_link);
+ DCHECK(!visited_link);
+ return ComputedStyleUtils::BorderSideColor(
+ style, style.BorderTopColor(), style.BorderTopStyle(), visited_link);
}
const CSSValue* BorderTopColor::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return allow_visited_style
? cssvalue::CSSColorValue::Create(
@@ -1495,7 +1121,7 @@ const CSSValue* BorderTopLeftRadius::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return &ComputedStyleUtils::ValueForBorderRadiusCorner(
style.BorderTopLeftRadius(), style);
@@ -1512,7 +1138,7 @@ const CSSValue* BorderTopRightRadius::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return &ComputedStyleUtils::ValueForBorderRadiusCorner(
style.BorderTopRightRadius(), style);
@@ -1522,7 +1148,7 @@ const CSSValue* BorderTopStyle::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.BorderTopStyle());
}
@@ -1538,7 +1164,7 @@ const CSSValue* BorderTopWidth::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ZoomAdjustedPixelValue(style.BorderTopWidth(), style);
}
@@ -1561,7 +1187,7 @@ const CSSValue* Bottom::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForPositionOffset(style, *this,
layout_object);
@@ -1579,7 +1205,7 @@ const CSSValue* BoxShadow::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForShadowList(style.BoxShadow(), style, true);
}
@@ -1588,7 +1214,7 @@ const CSSValue* BoxSizing::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
if (style.BoxSizing() == EBoxSizing::kContentBox)
return CSSIdentifierValue::Create(CSSValueID::kContentBox);
@@ -1599,7 +1225,7 @@ const CSSValue* BreakAfter::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.BreakAfter());
}
@@ -1608,7 +1234,7 @@ const CSSValue* BreakBefore::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.BreakBefore());
}
@@ -1617,7 +1243,7 @@ const CSSValue* BreakInside::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.BreakInside());
}
@@ -1626,7 +1252,7 @@ const CSSValue* BufferedRendering::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(svg_style.BufferedRendering());
}
@@ -1635,7 +1261,7 @@ const CSSValue* CaptionSide::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.CaptionSide());
}
@@ -1652,22 +1278,20 @@ const CSSValue* CaretColor::ParseSingleValue(
const blink::Color CaretColor::ColorIncludingFallback(
bool visited_link,
const ComputedStyle& style) const {
- StyleAutoColor auto_color =
- visited_link ? style.VisitedLinkCaretColor() : style.CaretColor();
+ DCHECK(!visited_link);
+ StyleAutoColor auto_color = style.CaretColor();
// TODO(rego): We may want to adjust the caret color if it's the same as
// the background to ensure good visibility and contrast.
StyleColor result = auto_color.IsAutoColor() ? StyleColor::CurrentColor()
: auto_color.ToStyleColor();
- if (!result.IsCurrentColor())
- return result.GetColor();
- return visited_link ? style.VisitedLinkColor() : style.GetColor();
+ return result.Resolve(style.GetColor());
}
const CSSValue* CaretColor::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
blink::Color color;
if (allow_visited_style)
@@ -1680,38 +1304,24 @@ const CSSValue* CaretColor::CSSValueFromComputedStyleInternal(
}
void CaretColor::ApplyInitial(StyleResolverState& state) const {
- StyleAutoColor color = StyleAutoColor::AutoColor();
- if (state.ApplyPropertyToRegularStyle())
- state.Style()->SetCaretColor(color);
- if (state.ApplyPropertyToVisitedLinkStyle())
- state.Style()->SetVisitedLinkCaretColor(color);
+ state.Style()->SetCaretColor(StyleAutoColor::AutoColor());
}
void CaretColor::ApplyInherit(StyleResolverState& state) const {
- StyleAutoColor color = state.ParentStyle()->CaretColor();
- if (state.ApplyPropertyToRegularStyle())
- state.Style()->SetCaretColor(color);
- if (state.ApplyPropertyToVisitedLinkStyle())
- state.Style()->SetVisitedLinkCaretColor(color);
+ state.Style()->SetCaretColor(state.ParentStyle()->CaretColor());
}
void CaretColor::ApplyValue(StyleResolverState& state,
const CSSValue& value) const {
- if (state.ApplyPropertyToRegularStyle()) {
- state.Style()->SetCaretColor(
- StyleBuilderConverter::ConvertStyleAutoColor(state, value));
- }
- if (state.ApplyPropertyToVisitedLinkStyle()) {
- state.Style()->SetVisitedLinkCaretColor(
- StyleBuilderConverter::ConvertStyleAutoColor(state, value, true));
- }
+ state.Style()->SetCaretColor(
+ StyleBuilderConverter::ConvertStyleAutoColor(state, value));
}
const CSSValue* Clear::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.Clear());
}
@@ -1767,7 +1377,7 @@ const CSSValue* Clip::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
if (style.HasAutoClip())
return CSSIdentifierValue::Create(CSSValueID::kAuto);
@@ -1798,7 +1408,7 @@ const CSSValue* ClipPath::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
if (ClipPathOperation* operation = style.ClipPath()) {
if (operation->GetType() == ClipPathOperation::SHAPE) {
@@ -1817,7 +1427,7 @@ const CSSValue* ClipRule::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(svg_style.ClipRule());
}
@@ -1832,17 +1442,15 @@ const CSSValue* Color::ParseSingleValue(CSSParserTokenRange& range,
const blink::Color Color::ColorIncludingFallback(
bool visited_link,
const ComputedStyle& style) const {
- StyleColor result =
- visited_link ? style.VisitedLinkColor() : style.GetColor();
- ;
- return result.GetColor();
+ DCHECK(!visited_link);
+ return style.GetColor();
}
const CSSValue* Color::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return cssvalue::CSSColorValue::Create(
allow_visited_style ? style.VisitedDependentColor(*this).Rgb()
@@ -1851,22 +1459,15 @@ const CSSValue* Color::CSSValueFromComputedStyleInternal(
void Color::ApplyInitial(StyleResolverState& state) const {
blink::Color color = ComputedStyleInitialValues::InitialColor();
- if (state.ApplyPropertyToRegularStyle())
- state.Style()->SetColor(color);
- if (state.ApplyPropertyToVisitedLinkStyle())
- state.Style()->SetVisitedLinkColor(color);
+ state.Style()->SetColor(color);
}
void Color::ApplyInherit(StyleResolverState& state) const {
blink::Color color = state.ParentStyle()->GetColor();
- if (state.ApplyPropertyToRegularStyle()) {
- if (state.ParentStyle()->IsColorInternalText())
- state.Style()->SetIsColorInternalText(true);
- else
- state.Style()->SetColor(color);
- }
- if (state.ApplyPropertyToVisitedLinkStyle())
- state.Style()->SetVisitedLinkColor(color);
+ if (state.ParentStyle()->IsColorInternalText())
+ state.Style()->SetIsColorInternalText(true);
+ else
+ state.Style()->SetColor(color);
}
void Color::ApplyValue(StyleResolverState& state, const CSSValue& value) const {
@@ -1878,18 +1479,11 @@ void Color::ApplyValue(StyleResolverState& state, const CSSValue& value) const {
return;
}
- if (state.ApplyPropertyToRegularStyle()) {
- if (identifier_value &&
- identifier_value->GetValueID() == CSSValueID::kInternalRootColor) {
- state.Style()->SetIsColorInternalText(true);
- } else {
- state.Style()->SetColor(
- StyleBuilderConverter::ConvertColor(state, value));
- }
- }
- if (state.ApplyPropertyToVisitedLinkStyle()) {
- state.Style()->SetVisitedLinkColor(
- StyleBuilderConverter::ConvertColor(state, value, true));
+ if (identifier_value &&
+ identifier_value->GetValueID() == CSSValueID::kInternalRootColor) {
+ state.Style()->SetIsColorInternalText(true);
+ } else {
+ state.Style()->SetColor(StyleBuilderConverter::ConvertColor(state, value));
}
}
@@ -1897,7 +1491,7 @@ const CSSValue* ColorInterpolation::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(svg_style.ColorInterpolation());
}
@@ -1906,7 +1500,7 @@ const CSSValue* ColorInterpolationFilters::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(svg_style.ColorInterpolationFilters());
}
@@ -1915,7 +1509,7 @@ const CSSValue* ColorRendering::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(svg_style.ColorRendering());
}
@@ -1924,7 +1518,7 @@ const CSSValue* ColorScheme::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
- if (range.Peek().Id() == CSSValueID::kAuto)
+ if (range.Peek().Id() == CSSValueID::kNormal)
return css_property_parser_helpers::ConsumeIdent(range);
if (range.Peek().Id() == CSSValueID::kOnly) {
// Handle 'only light'
@@ -1939,10 +1533,10 @@ const CSSValue* ColorScheme::ParseSingleValue(
CSSValueList* values = CSSValueList::CreateSpaceSeparated();
do {
CSSValueID id = range.Peek().Id();
- // 'auto' is handled above, and 'none' is reserved for future use. 'revert'
- // is not yet implemented as a keyword, but still skip it for compat and
- // interop.
- if (id == CSSValueID::kAuto || id == CSSValueID::kNone ||
+ // 'normal' is handled above, and 'none' is reserved for future use.
+ // 'revert' is not yet implemented as a keyword, but still skip it for
+ // compat and interop.
+ if (id == CSSValueID::kNormal || id == CSSValueID::kNone ||
id == CSSValueID::kRevert || id == CSSValueID::kDefault) {
return nullptr;
}
@@ -1972,10 +1566,10 @@ const CSSValue* ColorScheme::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
if (style.ColorScheme().IsEmpty())
- return CSSIdentifierValue::Create(CSSValueID::kAuto);
+ return CSSIdentifierValue::Create(CSSValueID::kNormal);
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
for (auto ident : style.ColorScheme()) {
list->Append(*MakeGarbageCollected<CSSCustomIdentValue>(ident));
@@ -1984,7 +1578,7 @@ const CSSValue* ColorScheme::CSSValueFromComputedStyleInternal(
}
const CSSValue* ColorScheme::InitialValue() const {
- return CSSIdentifierValue::Create(CSSValueID::kAuto);
+ return CSSIdentifierValue::Create(CSSValueID::kNormal);
}
void ColorScheme::ApplyInitial(StyleResolverState& state) const {
@@ -2000,7 +1594,7 @@ void ColorScheme::ApplyInherit(StyleResolverState& state) const {
void ColorScheme::ApplyValue(StyleResolverState& state,
const CSSValue& value) const {
if (const auto* identifier_value = DynamicTo<CSSIdentifierValue>(value)) {
- DCHECK(identifier_value->GetValueID() == CSSValueID::kAuto);
+ DCHECK(identifier_value->GetValueID() == CSSValueID::kNormal);
state.Style()->SetColorScheme(Vector<AtomicString>());
state.Style()->SetDarkColorScheme(false);
} else if (const auto* scheme_list = DynamicTo<CSSValueList>(value)) {
@@ -2038,19 +1632,19 @@ const CSSValue* ColumnCount::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
if (style.HasAutoColumnCount())
return CSSIdentifierValue::Create(CSSValueID::kAuto);
- return CSSPrimitiveValue::Create(style.ColumnCount(),
- CSSPrimitiveValue::UnitType::kNumber);
+ return CSSNumericLiteralValue::Create(style.ColumnCount(),
+ CSSPrimitiveValue::UnitType::kNumber);
}
const CSSValue* ColumnFill::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.GetColumnFill());
}
@@ -2066,7 +1660,7 @@ const CSSValue* ColumnGap::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool) const {
return ComputedStyleUtils::ValueForGapLength(style.ColumnGap(), style);
}
@@ -2081,18 +1675,15 @@ const CSSValue* ColumnRuleColor::ParseSingleValue(
const blink::Color ColumnRuleColor::ColorIncludingFallback(
bool visited_link,
const ComputedStyle& style) const {
- StyleColor result = visited_link ? style.VisitedLinkColumnRuleColor()
- : style.ColumnRuleColor();
- if (!result.IsCurrentColor())
- return result.GetColor();
- return visited_link ? style.VisitedLinkColor() : style.GetColor();
+ DCHECK(!visited_link);
+ return style.ColumnRuleColor().Resolve(style.GetColor());
}
const CSSValue* ColumnRuleColor::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return allow_visited_style ? cssvalue::CSSColorValue::Create(
style.VisitedDependentColor(*this).Rgb())
@@ -2104,7 +1695,7 @@ const CSSValue* ColumnRuleStyle::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.ColumnRuleStyle());
}
@@ -2122,7 +1713,7 @@ const CSSValue* ColumnRuleWidth::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ZoomAdjustedPixelValue(style.ColumnRuleWidth(), style);
}
@@ -2139,7 +1730,7 @@ const CSSValue* ColumnSpan::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(static_cast<unsigned>(style.GetColumnSpan())
? CSSValueID::kAll
@@ -2157,7 +1748,7 @@ const CSSValue* ColumnWidth::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
if (style.HasAutoColumnWidth())
return CSSIdentifierValue::Create(CSSValueID::kAuto);
@@ -2214,7 +1805,7 @@ const CSSValue* Contain::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
if (!style.Contain())
return CSSIdentifierValue::Create(CSSValueID::kNone);
@@ -2355,7 +1946,7 @@ const CSSValue* Content::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForContentData(style);
}
@@ -2427,7 +2018,7 @@ void Content::ApplyValue(StyleResolverState& state,
g_null_atom,
To<CSSCustomIdentValue>(function_value->Item(0)).Value(),
g_null_atom);
- const AtomicString& attr_value = state.GetElement()->getAttribute(attr);
+ const AtomicString& attr_value = state.GetElement().getAttribute(attr);
string = attr_value.IsNull() ? g_empty_string : attr_value.GetString();
} else {
string = To<CSSStringValue>(*item).Value();
@@ -2472,7 +2063,7 @@ const CSSValue* CounterIncrement::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForCounterDirectives(style, true);
}
@@ -2491,7 +2082,7 @@ const CSSValue* CounterReset::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForCounterDirectives(style, false);
}
@@ -2559,7 +2150,7 @@ const CSSValue* Cursor::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
CSSValueList* list = nullptr;
CursorList* cursors = style.Cursors();
@@ -2625,7 +2216,7 @@ const CSSValue* Cx::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ZoomAdjustedPixelValueForLength(svg_style.Cx(),
style);
@@ -2642,7 +2233,7 @@ const CSSValue* Cy::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ZoomAdjustedPixelValueForLength(svg_style.Cy(),
style);
@@ -2658,7 +2249,7 @@ const CSSValue* D::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
if (const StylePath* style_path = svg_style.D())
return style_path->ComputedCSSValue();
@@ -2669,7 +2260,7 @@ const CSSValue* Direction::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.Direction());
}
@@ -2715,7 +2306,7 @@ const CSSValue* Display::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
if (style.IsDisplayLayoutCustomBox()) {
return MakeGarbageCollected<cssvalue::CSSLayoutFunctionValue>(
@@ -2762,7 +2353,7 @@ const CSSValue* DominantBaseline::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(svg_style.DominantBaseline());
}
@@ -2771,7 +2362,7 @@ const CSSValue* EmptyCells::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.EmptyCells());
}
@@ -2786,7 +2377,7 @@ const CSSValue* Fill::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::AdjustSVGPaintForCurrentColor(
svg_style.FillPaint(), style.GetColor());
@@ -2803,17 +2394,17 @@ const CSSValue* FillOpacity::CSSValueFromComputedStyleInternal(
const ComputedStyle&,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
- return CSSPrimitiveValue::Create(svg_style.FillOpacity(),
- CSSPrimitiveValue::UnitType::kNumber);
+ return CSSNumericLiteralValue::Create(svg_style.FillOpacity(),
+ CSSPrimitiveValue::UnitType::kNumber);
}
const CSSValue* FillRule::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(svg_style.FillRule());
}
@@ -2828,7 +2419,7 @@ const CSSValue* Filter::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForFilter(style, style.Filter());
}
@@ -2848,7 +2439,7 @@ const CSSValue* FlexBasis::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ZoomAdjustedPixelValueForLength(style.FlexBasis(),
style);
@@ -2858,7 +2449,7 @@ const CSSValue* FlexDirection::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.FlexDirection());
}
@@ -2874,10 +2465,10 @@ const CSSValue* FlexGrow::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
- return CSSPrimitiveValue::Create(style.FlexGrow(),
- CSSPrimitiveValue::UnitType::kNumber);
+ return CSSNumericLiteralValue::Create(style.FlexGrow(),
+ CSSPrimitiveValue::UnitType::kNumber);
}
const CSSValue* FlexShrink::ParseSingleValue(
@@ -2892,17 +2483,17 @@ const CSSValue* FlexShrink::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
- return CSSPrimitiveValue::Create(style.FlexShrink(),
- CSSPrimitiveValue::UnitType::kNumber);
+ return CSSNumericLiteralValue::Create(style.FlexShrink(),
+ CSSPrimitiveValue::UnitType::kNumber);
}
const CSSValue* FlexWrap::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.FlexWrap());
}
@@ -2911,7 +2502,7 @@ const CSSValue* Float::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
if (style.HasOutOfFlowPosition())
return CSSIdentifierValue::Create(CSSValueID::kNone);
@@ -2931,14 +2522,14 @@ const blink::Color FloodColor::ColorIncludingFallback(
StyleColor result = style.FloodColor();
if (!result.IsCurrentColor())
return result.GetColor();
- return visited_link ? style.VisitedLinkColor() : style.GetColor();
+ return visited_link ? style.InternalVisitedColor() : style.GetColor();
}
const CSSValue* FloodColor::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::CurrentColorOrValidColor(style,
style.FloodColor());
@@ -2955,10 +2546,10 @@ const CSSValue* FloodOpacity::CSSValueFromComputedStyleInternal(
const ComputedStyle&,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
- return CSSPrimitiveValue::Create(svg_style.FloodOpacity(),
- CSSPrimitiveValue::UnitType::kNumber);
+ return CSSNumericLiteralValue::Create(svg_style.FloodOpacity(),
+ CSSPrimitiveValue::UnitType::kNumber);
}
const CSSValue* FontFamily::ParseSingleValue(
@@ -2972,7 +2563,7 @@ const CSSValue* FontFamily::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForFontFamily(style);
}
@@ -2988,7 +2579,7 @@ const CSSValue* FontFeatureSettings::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
const blink::FontFeatureSettings* feature_settings =
style.GetFontDescription().FeatureSettings();
@@ -3008,7 +2599,7 @@ const CSSValue* FontKerning::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.GetFontDescription().GetKerning());
}
@@ -3028,11 +2619,11 @@ const CSSValue* FontSizeAdjust::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
if (style.HasFontSizeAdjust()) {
- return CSSPrimitiveValue::Create(style.FontSizeAdjust(),
- CSSPrimitiveValue::UnitType::kNumber);
+ return CSSNumericLiteralValue::Create(style.FontSizeAdjust(),
+ CSSPrimitiveValue::UnitType::kNumber);
}
return CSSIdentifierValue::Create(CSSValueID::kNone);
}
@@ -3041,15 +2632,14 @@ const CSSValue* FontSize::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
return css_parsing_utils::ConsumeFontSize(
- range, context.Mode(),
- css_property_parser_helpers::UnitlessQuirk::kAllow);
+ range, context, css_property_parser_helpers::UnitlessQuirk::kAllow);
}
const CSSValue* FontSize::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForFontSize(style);
}
@@ -3065,7 +2655,7 @@ const CSSValue* FontStretch::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForFontStretch(style);
}
@@ -3081,7 +2671,7 @@ const CSSValue* FontStyle::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForFontStyle(style);
}
@@ -3100,7 +2690,7 @@ const CSSValue* FontVariantCaps::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForFontVariantCaps(style);
}
@@ -3126,7 +2716,7 @@ const CSSValue* FontVariantEastAsian::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForFontVariantEastAsian(style);
}
@@ -3153,7 +2743,7 @@ const CSSValue* FontVariantLigatures::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForFontVariantLigatures(style);
}
@@ -3179,7 +2769,7 @@ const CSSValue* FontVariantNumeric::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForFontVariantNumeric(style);
}
@@ -3236,7 +2826,7 @@ const CSSValue* FontVariationSettings::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
const blink::FontVariationSettings* variation_settings =
style.GetFontDescription().VariationSettings();
@@ -3264,11 +2854,69 @@ const CSSValue* FontWeight::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForFontWeight(style);
}
+const CSSValue* ForcedColorAdjust::CSSValueFromComputedStyleInternal(
+ const ComputedStyle& style,
+ const SVGComputedStyle&,
+ const LayoutObject*,
+ const Node*,
+ bool allow_visited_style) const {
+ return CSSIdentifierValue::Create(style.ForcedColorAdjust());
+}
+
+void InternalEffectiveZoom::ApplyInitial(StyleResolverState& state) const {
+ auto initial = ComputedStyleInitialValues::InitialInternalEffectiveZoom();
+ state.SetEffectiveZoom(initial);
+}
+
+void InternalEffectiveZoom::ApplyInherit(StyleResolverState& state) const {
+ state.SetEffectiveZoom(state.ParentStyle()->EffectiveZoom());
+}
+
+void InternalEffectiveZoom::ApplyValue(StyleResolverState& state,
+ const CSSValue& value) const {
+ state.SetEffectiveZoom(StyleBuilderConverter::ConvertZoom(state, value));
+}
+
+const CSSValue* InternalEffectiveZoom::ParseSingleValue(
+ CSSParserTokenRange& range,
+ const CSSParserContext& context,
+ const CSSParserLocalContext& local_context) const {
+ ValueRange value_range = kValueRangeNonNegative;
+ return css_property_parser_helpers::ConsumeNumber(range, value_range);
+}
+
+void InternalVisitedColor::ApplyValue(StyleResolverState& state,
+ const CSSValue& value) const {
+ auto* identifier_value = DynamicTo<CSSIdentifierValue>(value);
+ if (identifier_value &&
+ identifier_value->GetValueID() == CSSValueID::kCurrentcolor) {
+ ApplyInherit(state);
+ return;
+ }
+ state.Style()->SetInternalVisitedColor(
+ StyleBuilderConverter::ConvertColor(state, value, true));
+}
+
+const blink::Color InternalVisitedColor::ColorIncludingFallback(
+ bool visited_link,
+ const ComputedStyle& style) const {
+ DCHECK(visited_link);
+ return style.InternalVisitedColor();
+}
+
+const CSSValue* InternalVisitedColor::ParseSingleValue(
+ CSSParserTokenRange& range,
+ const CSSParserContext& context,
+ const CSSParserLocalContext& local_context) const {
+ return css_property_parser_helpers::ConsumeColor(
+ range, context.Mode(), IsQuirksModeBehavior(context.Mode()));
+}
+
const CSSValue* GridAutoColumns::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
@@ -3289,7 +2937,7 @@ const CSSValue* GridAutoColumns::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForGridTrackSizeList(kForColumns, style);
}
@@ -3322,7 +2970,7 @@ const CSSValue* GridAutoFlow::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
switch (style.GetGridAutoFlow()) {
@@ -3364,7 +3012,7 @@ const CSSValue* GridAutoRows::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForGridTrackSizeList(kForRows, style);
}
@@ -3380,7 +3028,7 @@ const CSSValue* GridColumnEnd::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForGridPosition(style.GridColumnEnd());
}
@@ -3396,7 +3044,7 @@ const CSSValue* GridColumnStart::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForGridPosition(style.GridColumnStart());
}
@@ -3412,7 +3060,7 @@ const CSSValue* GridRowEnd::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForGridPosition(style.GridRowEnd());
}
@@ -3428,7 +3076,7 @@ const CSSValue* GridRowStart::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForGridPosition(style.GridRowStart());
}
@@ -3463,7 +3111,7 @@ const CSSValue* GridTemplateAreas::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
if (!style.NamedGridAreaRowCount()) {
DCHECK(!style.NamedGridAreaColumnCount());
@@ -3541,7 +3189,7 @@ const CSSValue* GridTemplateColumns::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForGridTrackList(kForColumns, layout_object,
style);
@@ -3564,7 +3212,7 @@ const CSSValue* GridTemplateRows::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForGridTrackList(kForRows, layout_object,
style);
@@ -3586,7 +3234,7 @@ const CSSValue* Height::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
if (ComputedStyleUtils::WidthOrHeightShouldReturnUsedValue(layout_object)) {
return ZoomAdjustedPixelValue(
@@ -3600,7 +3248,7 @@ const CSSValue* Hyphens::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.GetHyphens());
}
@@ -3625,18 +3273,19 @@ const CSSValue* ImageOrientation::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
if (style.RespectImageOrientation() == kRespectImageOrientation)
return CSSIdentifierValue::Create(CSSValueID::kFromImage);
- return CSSPrimitiveValue::Create(0, CSSPrimitiveValue::UnitType::kDegrees);
+ return CSSNumericLiteralValue::Create(0,
+ CSSPrimitiveValue::UnitType::kDegrees);
}
const CSSValue* ImageRendering::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.ImageRendering());
}
@@ -3689,11 +3338,259 @@ const CSSValue* InsetInlineStart::ParseSingleValue(
css_property_parser_helpers::UnitlessQuirk::kForbid);
}
+const blink::Color InternalVisitedBackgroundColor::ColorIncludingFallback(
+ bool visited_link,
+ const ComputedStyle& style) const {
+ DCHECK(visited_link);
+
+ blink::Color color = style.InternalVisitedBackgroundColor().Resolve(
+ style.InternalVisitedColor());
+
+ // TODO: Technically someone could explicitly specify the color
+ // transparent, but for now we'll just assume that if the background color
+ // is transparent that it wasn't set. Note that it's weird that we're
+ // returning unvisited info for a visited link, but given our restriction
+ // that the alpha values have to match, it makes more sense to return the
+ // unvisited background color if specified than it does to return black.
+ // This behavior matches what Firefox 4 does as well.
+ if (color == blink::Color::kTransparent)
+ return style.BackgroundColor().Resolve(style.GetColor());
+
+ return color;
+}
+
+const CSSValue* InternalVisitedBackgroundColor::ParseSingleValue(
+ CSSParserTokenRange& range,
+ const CSSParserContext& context,
+ const CSSParserLocalContext& local_context) const {
+ return css_property_parser_helpers::ConsumeColor(
+ range, context.Mode(), IsQuirksModeBehavior(context.Mode()));
+}
+
+const blink::Color InternalVisitedBorderLeftColor::ColorIncludingFallback(
+ bool visited_link,
+ const ComputedStyle& style) const {
+ DCHECK(visited_link);
+ return style.InternalVisitedBorderLeftColor().Resolve(
+ style.InternalVisitedColor());
+}
+
+const CSSValue* InternalVisitedBorderLeftColor::ParseSingleValue(
+ CSSParserTokenRange& range,
+ const CSSParserContext& context,
+ const CSSParserLocalContext& local_context) const {
+ return css_parsing_utils::ConsumeBorderColorSide(range, context,
+ local_context);
+}
+
+const blink::Color InternalVisitedBorderTopColor::ColorIncludingFallback(
+ bool visited_link,
+ const ComputedStyle& style) const {
+ DCHECK(visited_link);
+ return style.InternalVisitedBorderTopColor().Resolve(
+ style.InternalVisitedColor());
+}
+
+const CSSValue* InternalVisitedBorderTopColor::ParseSingleValue(
+ CSSParserTokenRange& range,
+ const CSSParserContext& context,
+ const CSSParserLocalContext& local_context) const {
+ return css_parsing_utils::ConsumeBorderColorSide(range, context,
+ local_context);
+}
+
+const blink::Color InternalVisitedCaretColor::ColorIncludingFallback(
+ bool visited_link,
+ const ComputedStyle& style) const {
+ DCHECK(visited_link);
+ StyleAutoColor auto_color = style.InternalVisitedCaretColor();
+ StyleColor result = auto_color.IsAutoColor() ? StyleColor::CurrentColor()
+ : auto_color.ToStyleColor();
+ return result.Resolve(style.InternalVisitedColor());
+}
+
+const CSSValue* InternalVisitedCaretColor::ParseSingleValue(
+ CSSParserTokenRange& range,
+ const CSSParserContext& context,
+ const CSSParserLocalContext& local_context) const {
+ return To<Longhand>(GetCSSPropertyCaretColor())
+ .ParseSingleValue(range, context, local_context);
+}
+
+const blink::Color InternalVisitedBorderRightColor::ColorIncludingFallback(
+ bool visited_link,
+ const ComputedStyle& style) const {
+ DCHECK(visited_link);
+ return style.InternalVisitedBorderRightColor().Resolve(
+ style.InternalVisitedColor());
+}
+
+const CSSValue* InternalVisitedBorderRightColor::ParseSingleValue(
+ CSSParserTokenRange& range,
+ const CSSParserContext& context,
+ const CSSParserLocalContext& local_context) const {
+ return css_parsing_utils::ConsumeBorderColorSide(range, context,
+ local_context);
+}
+
+const blink::Color InternalVisitedBorderBottomColor::ColorIncludingFallback(
+ bool visited_link,
+ const ComputedStyle& style) const {
+ DCHECK(visited_link);
+ return style.InternalVisitedBorderBottomColor().Resolve(
+ style.InternalVisitedColor());
+}
+
+const CSSValue* InternalVisitedBorderBottomColor::ParseSingleValue(
+ CSSParserTokenRange& range,
+ const CSSParserContext& context,
+ const CSSParserLocalContext& local_context) const {
+ return css_parsing_utils::ConsumeBorderColorSide(range, context,
+ local_context);
+}
+
+const CSSValue* InternalVisitedBorderInlineStartColor::ParseSingleValue(
+ CSSParserTokenRange& range,
+ const CSSParserContext& context,
+ const CSSParserLocalContext& local_context) const {
+ return css_parsing_utils::ConsumeBorderColorSide(range, context,
+ local_context);
+}
+
+const CSSValue* InternalVisitedBorderInlineEndColor::ParseSingleValue(
+ CSSParserTokenRange& range,
+ const CSSParserContext& context,
+ const CSSParserLocalContext& local_context) const {
+ return css_parsing_utils::ConsumeBorderColorSide(range, context,
+ local_context);
+}
+
+const CSSValue* InternalVisitedBorderBlockStartColor::ParseSingleValue(
+ CSSParserTokenRange& range,
+ const CSSParserContext& context,
+ const CSSParserLocalContext& local_context) const {
+ return css_parsing_utils::ConsumeBorderColorSide(range, context,
+ local_context);
+}
+
+const CSSValue* InternalVisitedBorderBlockEndColor::ParseSingleValue(
+ CSSParserTokenRange& range,
+ const CSSParserContext& context,
+ const CSSParserLocalContext& local_context) const {
+ return css_parsing_utils::ConsumeBorderColorSide(range, context,
+ local_context);
+}
+
+const CSSValue* InternalVisitedFill::ParseSingleValue(
+ CSSParserTokenRange& range,
+ const CSSParserContext& context,
+ const CSSParserLocalContext& local_context) const {
+ return css_parsing_utils::ParsePaintStroke(range, context);
+}
+
+const blink::Color InternalVisitedColumnRuleColor::ColorIncludingFallback(
+ bool visited_link,
+ const ComputedStyle& style) const {
+ DCHECK(visited_link);
+ return style.InternalVisitedColumnRuleColor().Resolve(
+ style.InternalVisitedColor());
+}
+
+const CSSValue* InternalVisitedColumnRuleColor::ParseSingleValue(
+ CSSParserTokenRange& range,
+ const CSSParserContext& context,
+ const CSSParserLocalContext& local_context) const {
+ return css_property_parser_helpers::ConsumeColor(range, context.Mode());
+}
+
+const blink::Color InternalVisitedOutlineColor::ColorIncludingFallback(
+ bool visited_link,
+ const ComputedStyle& style) const {
+ DCHECK(visited_link);
+ return style.InternalVisitedOutlineColor().Resolve(
+ style.InternalVisitedColor());
+}
+
+const CSSValue* InternalVisitedOutlineColor::ParseSingleValue(
+ CSSParserTokenRange& range,
+ const CSSParserContext& context,
+ const CSSParserLocalContext& local_context) const {
+ return To<Longhand>(GetCSSPropertyOutlineColor())
+ .ParseSingleValue(range, context, local_context);
+}
+
+const CSSValue* InternalVisitedStroke::ParseSingleValue(
+ CSSParserTokenRange& range,
+ const CSSParserContext& context,
+ const CSSParserLocalContext& local_context) const {
+ return css_parsing_utils::ParsePaintStroke(range, context);
+}
+
+const blink::Color InternalVisitedTextDecorationColor::ColorIncludingFallback(
+ bool visited_link,
+ const ComputedStyle& style) const {
+ DCHECK(visited_link);
+ return style.DecorationColorIncludingFallback(visited_link)
+ .Resolve(style.InternalVisitedColor());
+}
+
+const CSSValue* InternalVisitedTextDecorationColor::ParseSingleValue(
+ CSSParserTokenRange& range,
+ const CSSParserContext& context,
+ const CSSParserLocalContext& local_context) const {
+ return css_property_parser_helpers::ConsumeColor(range, context.Mode());
+}
+
+const blink::Color InternalVisitedTextEmphasisColor::ColorIncludingFallback(
+ bool visited_link,
+ const ComputedStyle& style) const {
+ DCHECK(visited_link);
+ return style.InternalVisitedTextEmphasisColor().Resolve(
+ style.InternalVisitedColor());
+}
+
+const CSSValue* InternalVisitedTextEmphasisColor::ParseSingleValue(
+ CSSParserTokenRange& range,
+ const CSSParserContext& context,
+ const CSSParserLocalContext& local_context) const {
+ return css_property_parser_helpers::ConsumeColor(range, context.Mode());
+}
+
+const blink::Color InternalVisitedTextFillColor::ColorIncludingFallback(
+ bool visited_link,
+ const ComputedStyle& style) const {
+ DCHECK(visited_link);
+ return style.InternalVisitedTextFillColor().Resolve(
+ style.InternalVisitedColor());
+}
+
+const CSSValue* InternalVisitedTextFillColor::ParseSingleValue(
+ CSSParserTokenRange& range,
+ const CSSParserContext& context,
+ const CSSParserLocalContext& local_context) const {
+ return css_property_parser_helpers::ConsumeColor(range, context.Mode());
+}
+
+const blink::Color InternalVisitedTextStrokeColor::ColorIncludingFallback(
+ bool visited_link,
+ const ComputedStyle& style) const {
+ DCHECK(visited_link);
+ return style.InternalVisitedTextStrokeColor().Resolve(
+ style.InternalVisitedColor());
+}
+
+const CSSValue* InternalVisitedTextStrokeColor::ParseSingleValue(
+ CSSParserTokenRange& range,
+ const CSSParserContext& context,
+ const CSSParserLocalContext& local_context) const {
+ return css_property_parser_helpers::ConsumeColor(range, context.Mode());
+}
+
const CSSValue* Isolation::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.Isolation());
}
@@ -3715,7 +3612,7 @@ const CSSValue* JustifyContent::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::
ValueForContentPositionAndDistributionWithOverflowAlignment(
@@ -3760,7 +3657,7 @@ const CSSValue* JustifyItems::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForItemPositionWithOverflowAlignment(
style.JustifyItems().GetPosition() == ItemPosition::kAuto
@@ -3780,7 +3677,7 @@ const CSSValue* JustifySelf::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForItemPositionWithOverflowAlignment(
style.JustifySelf());
@@ -3804,7 +3701,7 @@ const CSSValue* Left::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForPositionOffset(style, *this,
layout_object);
@@ -3821,7 +3718,7 @@ const CSSValue* LetterSpacing::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
if (!style.LetterSpacing())
return CSSIdentifierValue::Create(CSSValueID::kNormal);
@@ -3841,14 +3738,14 @@ const blink::Color LightingColor::ColorIncludingFallback(
StyleColor result = style.LightingColor();
if (!result.IsCurrentColor())
return result.GetColor();
- return visited_link ? style.VisitedLinkColor() : style.GetColor();
+ return visited_link ? style.InternalVisitedColor() : style.GetColor();
}
const CSSValue* LightingColor::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::CurrentColorOrValidColor(style,
style.LightingColor());
@@ -3858,7 +3755,7 @@ const CSSValue* LineBreak::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.GetLineBreak());
}
@@ -3874,7 +3771,7 @@ const CSSValue* LineHeight::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForLineHeight(style);
}
@@ -3891,7 +3788,7 @@ const CSSValue* LineHeightStep::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ZoomAdjustedPixelValue(style.LineHeightStep(), style);
}
@@ -3907,7 +3804,7 @@ const CSSValue* ListStyleImage::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
if (style.ListStyleImage())
return style.ListStyleImage()->ComputedCSSValue();
@@ -3924,7 +3821,7 @@ const CSSValue* ListStylePosition::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.ListStylePosition());
}
@@ -3933,7 +3830,7 @@ const CSSValue* ListStyleType::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.ListStyleType());
}
@@ -3975,7 +3872,7 @@ const CSSValue* MarginBottom::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
const Length& margin_bottom = style.MarginBottom();
if (margin_bottom.IsFixed() || !layout_object || !layout_object->IsBox()) {
@@ -4023,7 +3920,7 @@ const CSSValue* MarginLeft::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
const Length& margin_left = style.MarginLeft();
if (margin_left.IsFixed() || !layout_object || !layout_object->IsBox()) {
@@ -4053,7 +3950,7 @@ const CSSValue* MarginRight::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
const Length& margin_right = style.MarginRight();
if (margin_right.IsFixed() || !layout_object || !layout_object->IsBox()) {
@@ -4097,7 +3994,7 @@ const CSSValue* MarginTop::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
const Length& margin_top = style.MarginTop();
if (margin_top.IsFixed() || !layout_object || !layout_object->IsBox()) {
@@ -4120,7 +4017,7 @@ const CSSValue* MarkerEnd::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForSVGResource(svg_style.MarkerEndResource());
}
@@ -4138,7 +4035,7 @@ const CSSValue* MarkerMid::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForSVGResource(svg_style.MarkerMidResource());
}
@@ -4156,7 +4053,7 @@ const CSSValue* MarkerStart::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForSVGResource(
svg_style.MarkerStartResource());
@@ -4174,7 +4071,7 @@ const CSSValue* Mask::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForSVGResource(svg_style.MaskerResource());
}
@@ -4202,7 +4099,7 @@ const CSSValue* MaskSourceType::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
CSSValueList* list = CSSValueList::CreateCommaSeparated();
for (const FillLayer* curr_layer = &style.MaskLayers(); curr_layer;
@@ -4215,7 +4112,7 @@ const CSSValue* MaskType::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(svg_style.MaskType());
}
@@ -4239,7 +4136,7 @@ const CSSValue* MaxHeight::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
const Length& max_height = style.MaxHeight();
if (max_height.IsMaxSizeNone())
@@ -4265,7 +4162,7 @@ const CSSValue* MaxWidth::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
const Length& max_width = style.MaxWidth();
if (max_width.IsMaxSizeNone())
@@ -4292,7 +4189,7 @@ const CSSValue* MinHeight::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
if (style.MinHeight().IsAuto())
return ComputedStyleUtils::MinWidthOrMinHeightAuto(styled_node, style);
@@ -4318,7 +4215,7 @@ const CSSValue* MinWidth::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
if (style.MinWidth().IsAuto())
return ComputedStyleUtils::MinWidthOrMinHeightAuto(styled_node, style);
@@ -4330,7 +4227,7 @@ const CSSValue* MixBlendMode::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.GetBlendMode());
}
@@ -4339,7 +4236,7 @@ const CSSValue* ObjectFit::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.GetObjectFit());
}
@@ -4357,7 +4254,7 @@ const CSSValue* ObjectPosition::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return MakeGarbageCollected<CSSValuePair>(
ComputedStyleUtils::ZoomAdjustedPixelValueForLength(
@@ -4383,7 +4280,7 @@ const CSSValue* OffsetAnchor::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForPosition(style.OffsetAnchor(), style);
}
@@ -4400,7 +4297,7 @@ const CSSValue* OffsetDistance::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ZoomAdjustedPixelValueForLength(
style.OffsetDistance(), style);
@@ -4417,7 +4314,7 @@ const CSSValue* OffsetPath::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
if (const BasicShape* style_motion_path = style.OffsetPath())
return ValueForBasicShape(style, style_motion_path);
@@ -4445,7 +4342,7 @@ const CSSValue* OffsetPosition::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForPosition(style.OffsetPosition(), style);
}
@@ -4460,12 +4357,12 @@ const CSSValue* OffsetRotate::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
if (style.OffsetRotate().type == OffsetRotationType::kAuto)
list->Append(*CSSIdentifierValue::Create(CSSValueID::kAuto));
- list->Append(*CSSPrimitiveValue::Create(
+ list->Append(*CSSNumericLiteralValue::Create(
style.OffsetRotate().angle, CSSPrimitiveValue::UnitType::kDegrees));
return list;
}
@@ -4480,10 +4377,10 @@ const CSSValue* Opacity::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
- return CSSPrimitiveValue::Create(style.Opacity(),
- CSSPrimitiveValue::UnitType::kNumber);
+ return CSSNumericLiteralValue::Create(style.Opacity(),
+ CSSPrimitiveValue::UnitType::kNumber);
}
const CSSValue* Order::ParseSingleValue(CSSParserTokenRange& range,
@@ -4496,10 +4393,10 @@ const CSSValue* Order::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
- return CSSPrimitiveValue::Create(style.Order(),
- CSSPrimitiveValue::UnitType::kNumber);
+ return CSSNumericLiteralValue::Create(style.Order(),
+ CSSPrimitiveValue::UnitType::kNumber);
}
const CSSValue* Orphans::ParseSingleValue(CSSParserTokenRange& range,
@@ -4512,10 +4409,10 @@ const CSSValue* Orphans::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
- return CSSPrimitiveValue::Create(style.Orphans(),
- CSSPrimitiveValue::UnitType::kNumber);
+ return CSSNumericLiteralValue::Create(style.Orphans(),
+ CSSPrimitiveValue::UnitType::kNumber);
}
const CSSValue* OutlineColor::ParseSingleValue(
@@ -4531,18 +4428,15 @@ const CSSValue* OutlineColor::ParseSingleValue(
const blink::Color OutlineColor::ColorIncludingFallback(
bool visited_link,
const ComputedStyle& style) const {
- StyleColor result =
- visited_link ? style.VisitedLinkOutlineColor() : style.OutlineColor();
- if (!result.IsCurrentColor())
- return result.GetColor();
- return visited_link ? style.VisitedLinkColor() : style.GetColor();
+ DCHECK(!visited_link);
+ return style.OutlineColor().Resolve(style.GetColor());
}
const CSSValue* OutlineColor::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return allow_visited_style ? cssvalue::CSSColorValue::Create(
style.VisitedDependentColor(*this).Rgb())
@@ -4562,7 +4456,7 @@ const CSSValue* OutlineOffset::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ZoomAdjustedPixelValue(style.OutlineOffset(), style);
}
@@ -4571,7 +4465,7 @@ const CSSValue* OutlineStyle::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
if (style.OutlineStyleIsAuto())
return CSSIdentifierValue::Create(CSSValueID::kAuto);
@@ -4611,7 +4505,7 @@ const CSSValue* OutlineWidth::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ZoomAdjustedPixelValue(style.OutlineWidth(), style);
}
@@ -4620,7 +4514,7 @@ const CSSValue* OverflowAnchor::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.OverflowAnchor());
}
@@ -4629,7 +4523,7 @@ const CSSValue* OverflowWrap::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.OverflowWrap());
}
@@ -4638,7 +4532,7 @@ const CSSValue* OverflowX::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.OverflowX());
}
@@ -4647,7 +4541,7 @@ const CSSValue* OverflowY::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.OverflowY());
}
@@ -4656,7 +4550,7 @@ const CSSValue* OverscrollBehaviorX::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.OverscrollBehaviorX());
}
@@ -4665,7 +4559,7 @@ const CSSValue* OverscrollBehaviorY::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.OverscrollBehaviorY());
}
@@ -4707,7 +4601,7 @@ const CSSValue* PaddingBottom::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
const Length& padding_bottom = style.PaddingBottom();
if (padding_bottom.IsFixed() || !layout_object || !layout_object->IsBox()) {
@@ -4755,7 +4649,7 @@ const CSSValue* PaddingLeft::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
const Length& padding_left = style.PaddingLeft();
if (padding_left.IsFixed() || !layout_object || !layout_object->IsBox()) {
@@ -4785,7 +4679,7 @@ const CSSValue* PaddingRight::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
const Length& padding_right = style.PaddingRight();
if (padding_right.IsFixed() || !layout_object || !layout_object->IsBox()) {
@@ -4815,7 +4709,7 @@ const CSSValue* PaddingTop::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
const Length& padding_top = style.PaddingTop();
if (padding_top.IsFixed() || !layout_object || !layout_object->IsBox()) {
@@ -4891,7 +4785,7 @@ const CSSValue* PaintOrder::CSSValueFromComputedStyleInternal(
const ComputedStyle&,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
const EPaintOrder paint_order = svg_style.PaintOrder();
if (paint_order == kPaintOrderNormal)
@@ -4939,7 +4833,7 @@ const CSSValue* Perspective::ParseSingleValue(
if (!css_property_parser_helpers::ConsumeNumberRaw(range, perspective))
return nullptr;
context.Count(WebFeature::kUnitlessPerspectiveInPerspectiveProperty);
- parsed_value = CSSPrimitiveValue::Create(
+ parsed_value = CSSNumericLiteralValue::Create(
perspective, CSSPrimitiveValue::UnitType::kPixels);
}
if (parsed_value &&
@@ -4952,7 +4846,7 @@ const CSSValue* Perspective::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
if (!style.HasPerspective())
return CSSIdentifierValue::Create(CSSValueID::kNone);
@@ -4977,7 +4871,7 @@ const CSSValue* PerspectiveOrigin::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
if (layout_object) {
LayoutRect box;
@@ -5006,7 +4900,7 @@ const CSSValue* PointerEvents::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.PointerEvents());
}
@@ -5015,7 +4909,7 @@ const CSSValue* Position::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.GetPosition());
}
@@ -5047,7 +4941,7 @@ const CSSValue* Quotes::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
if (!style.Quotes()) {
// TODO(ramya.v): We should return the quote values that we're actually
@@ -5078,7 +4972,7 @@ const CSSValue* R::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ZoomAdjustedPixelValueForLength(svg_style.R(),
style);
@@ -5088,7 +4982,7 @@ const CSSValue* Resize::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.Resize());
}
@@ -5128,7 +5022,7 @@ const CSSValue* Right::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForPositionOffset(style, *this,
layout_object);
@@ -5169,7 +5063,7 @@ const CSSValue* Rotate::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
if (!style.Rotate())
return CSSIdentifierValue::Create(CSSValueID::kNone);
@@ -5177,14 +5071,14 @@ const CSSValue* Rotate::CSSValueFromComputedStyleInternal(
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
if (style.Rotate()->X() != 0 || style.Rotate()->Y() != 0 ||
style.Rotate()->Z() != 1) {
- list->Append(*CSSPrimitiveValue::Create(
+ list->Append(*CSSNumericLiteralValue::Create(
style.Rotate()->X(), CSSPrimitiveValue::UnitType::kNumber));
- list->Append(*CSSPrimitiveValue::Create(
+ list->Append(*CSSNumericLiteralValue::Create(
style.Rotate()->Y(), CSSPrimitiveValue::UnitType::kNumber));
- list->Append(*CSSPrimitiveValue::Create(
+ list->Append(*CSSNumericLiteralValue::Create(
style.Rotate()->Z(), CSSPrimitiveValue::UnitType::kNumber));
}
- list->Append(*CSSPrimitiveValue::Create(
+ list->Append(*CSSNumericLiteralValue::Create(
style.Rotate()->Angle(), CSSPrimitiveValue::UnitType::kDegrees));
return list;
}
@@ -5199,7 +5093,7 @@ const CSSValue* RowGap::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool) const {
return ComputedStyleUtils::ValueForGapLength(style.RowGap(), style);
}
@@ -5217,7 +5111,7 @@ const CSSValue* Rx::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ZoomAdjustedPixelValueForLength(svg_style.Rx(),
style);
@@ -5236,7 +5130,7 @@ const CSSValue* Ry::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ZoomAdjustedPixelValueForLength(svg_style.Ry(),
style);
@@ -5251,18 +5145,26 @@ const CSSValue* Scale::ParseSingleValue(CSSParserTokenRange& range,
if (id == CSSValueID::kNone)
return css_property_parser_helpers::ConsumeIdent(range);
- CSSValue* scale =
+ CSSValue* x_scale =
css_property_parser_helpers::ConsumeNumber(range, kValueRangeAll);
- if (!scale)
+ if (!x_scale)
return nullptr;
+
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
- list->Append(*scale);
- scale = css_property_parser_helpers::ConsumeNumber(range, kValueRangeAll);
- if (scale) {
- list->Append(*scale);
- scale = css_property_parser_helpers::ConsumeNumber(range, kValueRangeAll);
- if (scale)
- list->Append(*scale);
+ list->Append(*x_scale);
+
+ CSSValue* y_scale =
+ css_property_parser_helpers::ConsumeNumber(range, kValueRangeAll);
+ if (y_scale) {
+ CSSValue* z_scale =
+ css_property_parser_helpers::ConsumeNumber(range, kValueRangeAll);
+ if (z_scale) {
+ list->Append(*y_scale);
+ list->Append(*z_scale);
+ } else if (To<CSSPrimitiveValue>(x_scale)->GetDoubleValue() !=
+ To<CSSPrimitiveValue>(y_scale)->GetDoubleValue()) {
+ list->Append(*y_scale);
+ }
}
return list;
@@ -5272,18 +5174,26 @@ const CSSValue* Scale::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
- if (!style.Scale())
+ ScaleTransformOperation* scale = style.Scale();
+ if (!scale)
return CSSIdentifierValue::Create(CSSValueID::kNone);
+
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
- list->Append(*CSSPrimitiveValue::Create(
- style.Scale()->X(), CSSPrimitiveValue::UnitType::kNumber));
- list->Append(*CSSPrimitiveValue::Create(
- style.Scale()->Y(), CSSPrimitiveValue::UnitType::kNumber));
- if (style.Scale()->Z() != 1) {
- list->Append(*CSSPrimitiveValue::Create(
- style.Scale()->Z(), CSSPrimitiveValue::UnitType::kNumber));
+ list->Append(*CSSNumericLiteralValue::Create(
+ scale->X(), CSSPrimitiveValue::UnitType::kNumber));
+
+ if (scale->Z() == 1) {
+ if (scale->X() != scale->Y()) {
+ list->Append(*CSSNumericLiteralValue::Create(
+ scale->Y(), CSSPrimitiveValue::UnitType::kNumber));
+ }
+ } else {
+ list->Append(*CSSNumericLiteralValue::Create(
+ scale->Y(), CSSPrimitiveValue::UnitType::kNumber));
+ list->Append(*CSSNumericLiteralValue::Create(
+ scale->Z(), CSSNumericLiteralValue::UnitType::kNumber));
}
return list;
}
@@ -5292,7 +5202,7 @@ const CSSValue* ScrollBehavior::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.GetScrollBehavior());
}
@@ -5348,7 +5258,7 @@ const CSSValue* ScrollCustomization::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ScrollCustomizationFlagsToCSSValue(
style.ScrollCustomization());
@@ -5382,7 +5292,7 @@ const CSSValue* ScrollMarginBottom::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ZoomAdjustedPixelValue(style.ScrollMarginBottom(), style);
}
@@ -5415,7 +5325,7 @@ const CSSValue* ScrollMarginLeft::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ZoomAdjustedPixelValue(style.ScrollMarginLeft(), style);
}
@@ -5432,7 +5342,7 @@ const CSSValue* ScrollMarginRight::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ZoomAdjustedPixelValue(style.ScrollMarginRight(), style);
}
@@ -5449,7 +5359,7 @@ const CSSValue* ScrollMarginTop::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ZoomAdjustedPixelValue(style.ScrollMarginTop(), style);
}
@@ -5485,7 +5395,7 @@ const CSSValue* ScrollPaddingBottom::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ZoomAdjustedPixelValueForLength(
style.ScrollPaddingBottom(), style);
@@ -5522,7 +5432,7 @@ const CSSValue* ScrollPaddingLeft::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ZoomAdjustedPixelValueForLength(
style.ScrollPaddingLeft(), style);
@@ -5541,7 +5451,7 @@ const CSSValue* ScrollPaddingRight::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ZoomAdjustedPixelValueForLength(
style.ScrollPaddingRight(), style);
@@ -5560,7 +5470,7 @@ const CSSValue* ScrollPaddingTop::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ZoomAdjustedPixelValueForLength(
style.ScrollPaddingTop(), style);
@@ -5592,7 +5502,7 @@ const CSSValue* ScrollSnapAlign::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForScrollSnapAlign(style.GetScrollSnapAlign(),
style);
@@ -5602,7 +5512,7 @@ const CSSValue* ScrollSnapStop::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.ScrollSnapStop());
}
@@ -5636,7 +5546,7 @@ const CSSValue* ScrollSnapType::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForScrollSnapType(style.GetScrollSnapType(),
style);
@@ -5653,10 +5563,10 @@ const CSSValue* ShapeImageThreshold::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
- return CSSPrimitiveValue::Create(style.ShapeImageThreshold(),
- CSSPrimitiveValue::UnitType::kNumber);
+ return CSSNumericLiteralValue::Create(style.ShapeImageThreshold(),
+ CSSPrimitiveValue::UnitType::kNumber);
}
const CSSValue* ShapeMargin::ParseSingleValue(
@@ -5671,7 +5581,7 @@ const CSSValue* ShapeMargin::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return CSSValue::Create(style.ShapeMargin(), style.EffectiveZoom());
}
@@ -5703,7 +5613,7 @@ const CSSValue* ShapeOutside::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForShape(style, style.ShapeOutside());
}
@@ -5712,7 +5622,7 @@ const CSSValue* ShapeRendering::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(svg_style.ShapeRendering());
}
@@ -5861,7 +5771,7 @@ const CSSValue* Speak::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.Speak());
}
@@ -5879,14 +5789,14 @@ const blink::Color StopColor::ColorIncludingFallback(
StyleColor result = style.StopColor();
if (!result.IsCurrentColor())
return result.GetColor();
- return visited_link ? style.VisitedLinkColor() : style.GetColor();
+ return visited_link ? style.InternalVisitedColor() : style.GetColor();
}
const CSSValue* StopColor::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::CurrentColorOrValidColor(style, style.StopColor());
}
@@ -5902,10 +5812,10 @@ const CSSValue* StopOpacity::CSSValueFromComputedStyleInternal(
const ComputedStyle&,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
- return CSSPrimitiveValue::Create(svg_style.StopOpacity(),
- CSSPrimitiveValue::UnitType::kNumber);
+ return CSSNumericLiteralValue::Create(svg_style.StopOpacity(),
+ CSSPrimitiveValue::UnitType::kNumber);
}
const CSSValue* Stroke::ParseSingleValue(CSSParserTokenRange& range,
@@ -5918,7 +5828,7 @@ const CSSValue* Stroke::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::AdjustSVGPaintForCurrentColor(
svg_style.StrokePaint(), style.GetColor());
@@ -5950,7 +5860,7 @@ const CSSValue* StrokeDasharray::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::StrokeDashArrayToCSSValueList(
*svg_style.StrokeDashArray(), style);
@@ -5969,7 +5879,7 @@ const CSSValue* StrokeDashoffset::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ZoomAdjustedPixelValueForLength(
style.StrokeDashOffset(), style);
@@ -5979,7 +5889,7 @@ const CSSValue* StrokeLinecap::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(svg_style.CapStyle());
}
@@ -5988,7 +5898,7 @@ const CSSValue* StrokeLinejoin::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(svg_style.JoinStyle());
}
@@ -6005,10 +5915,10 @@ const CSSValue* StrokeMiterlimit::CSSValueFromComputedStyleInternal(
const ComputedStyle&,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
- return CSSPrimitiveValue::Create(svg_style.StrokeMiterLimit(),
- CSSPrimitiveValue::UnitType::kNumber);
+ return CSSNumericLiteralValue::Create(svg_style.StrokeMiterLimit(),
+ CSSPrimitiveValue::UnitType::kNumber);
}
const CSSValue* StrokeOpacity::ParseSingleValue(
@@ -6022,10 +5932,10 @@ const CSSValue* StrokeOpacity::CSSValueFromComputedStyleInternal(
const ComputedStyle&,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
- return CSSPrimitiveValue::Create(svg_style.StrokeOpacity(),
- CSSPrimitiveValue::UnitType::kNumber);
+ return CSSNumericLiteralValue::Create(svg_style.StrokeOpacity(),
+ CSSPrimitiveValue::UnitType::kNumber);
}
const CSSValue* StrokeWidth::ParseSingleValue(
@@ -6041,12 +5951,12 @@ const CSSValue* StrokeWidth::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
const Length& length = svg_style.StrokeWidth().length();
if (length.IsFixed()) {
- return CSSPrimitiveValue::Create(length.Value(),
- CSSPrimitiveValue::UnitType::kPixels);
+ return CSSNumericLiteralValue::Create(length.Value(),
+ CSSPrimitiveValue::UnitType::kPixels);
}
return CSSValue::Create(length, style.EffectiveZoom());
}
@@ -6055,7 +5965,7 @@ const CSSValue* TabSize::ParseSingleValue(CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
CSSPrimitiveValue* parsed_value =
- css_property_parser_helpers::ConsumeInteger(range, 0);
+ css_property_parser_helpers::ConsumeNumber(range, kValueRangeNonNegative);
if (parsed_value)
return parsed_value;
return css_property_parser_helpers::ConsumeLength(range, context.Mode(),
@@ -6066,19 +5976,19 @@ const CSSValue* TabSize::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
- return CSSPrimitiveValue::Create(style.GetTabSize().GetPixelSize(1.0),
- style.GetTabSize().IsSpaces()
- ? CSSPrimitiveValue::UnitType::kNumber
- : CSSPrimitiveValue::UnitType::kPixels);
+ return CSSNumericLiteralValue::Create(
+ style.GetTabSize().GetPixelSize(1.0),
+ style.GetTabSize().IsSpaces() ? CSSPrimitiveValue::UnitType::kNumber
+ : CSSPrimitiveValue::UnitType::kPixels);
}
const CSSValue* TableLayout::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.TableLayout());
}
@@ -6087,7 +5997,7 @@ const CSSValue* TextAlign::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.GetTextAlign());
}
@@ -6123,7 +6033,7 @@ const CSSValue* TextAlignLast::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.TextAlignLast());
}
@@ -6132,7 +6042,7 @@ const CSSValue* TextAnchor::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(svg_style.TextAnchor());
}
@@ -6141,7 +6051,7 @@ const CSSValue* TextCombineUpright::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.TextCombine());
}
@@ -6156,17 +6066,16 @@ const CSSValue* TextDecorationColor::ParseSingleValue(
const blink::Color TextDecorationColor::ColorIncludingFallback(
bool visited_link,
const ComputedStyle& style) const {
- StyleColor result = style.DecorationColorIncludingFallback(visited_link);
- if (!result.IsCurrentColor())
- return result.GetColor();
- return visited_link ? style.VisitedLinkColor() : style.GetColor();
+ DCHECK(!visited_link);
+ return style.DecorationColorIncludingFallback(visited_link)
+ .Resolve(style.GetColor());
}
const CSSValue* TextDecorationColor::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::CurrentColorOrValidColor(
style, style.TextDecorationColor());
@@ -6183,7 +6092,7 @@ const CSSValue* TextDecorationLine::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::RenderTextDecorationFlagsToCSSValue(
style.GetTextDecoration());
@@ -6193,7 +6102,7 @@ const CSSValue* TextDecorationSkipInk::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForTextDecorationSkipInk(
style.TextDecorationSkipInk());
@@ -6203,7 +6112,7 @@ const CSSValue* TextDecorationStyle::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForTextDecorationStyle(
style.TextDecorationStyle());
@@ -6260,7 +6169,7 @@ const CSSValue* TextIndent::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
list->Append(*ComputedStyleUtils::ZoomAdjustedPixelValueForLength(
@@ -6321,7 +6230,7 @@ const CSSValue* TextJustify::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.GetTextJustify());
}
@@ -6330,7 +6239,7 @@ const CSSValue* TextOrientation::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.GetTextOrientation());
}
@@ -6345,7 +6254,7 @@ const CSSValue* TextOverflow::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
if (style.TextOverflow() != ETextOverflow::kClip)
return CSSIdentifierValue::Create(CSSValueID::kEllipsis);
@@ -6356,7 +6265,7 @@ const CSSValue* TextRendering::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.GetFontDescription().TextRendering());
}
@@ -6373,7 +6282,7 @@ const CSSValue* TextShadow::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForShadowList(style.TextShadow(), style,
false);
@@ -6395,19 +6304,20 @@ const CSSValue* TextSizeAdjust::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
if (style.GetTextSizeAdjust().IsAuto())
return CSSIdentifierValue::Create(CSSValueID::kAuto);
- return CSSPrimitiveValue::Create(style.GetTextSizeAdjust().Multiplier() * 100,
- CSSPrimitiveValue::UnitType::kPercentage);
+ return CSSNumericLiteralValue::Create(
+ style.GetTextSizeAdjust().Multiplier() * 100,
+ CSSPrimitiveValue::UnitType::kPercentage);
}
const CSSValue* TextTransform::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.TextTransform());
}
@@ -6444,7 +6354,7 @@ const CSSValue* TextUnderlinePosition::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
auto text_underline_position = style.TextUnderlinePosition();
if (text_underline_position == kTextUnderlinePositionAuto)
@@ -6485,7 +6395,7 @@ const CSSValue* Top::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForPositionOffset(style, *this,
layout_object);
@@ -6551,7 +6461,7 @@ const CSSValue* TouchAction::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::TouchActionFlagsToCSSValue(style.GetTouchAction());
}
@@ -6560,7 +6470,7 @@ const CSSValue* TransformBox::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.TransformBox());
}
@@ -6582,7 +6492,7 @@ const CSSValue* Transform::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ComputedTransform(layout_object, style);
}
@@ -6619,7 +6529,7 @@ const CSSValue* TransformOrigin::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
if (layout_object) {
@@ -6645,7 +6555,7 @@ const CSSValue* TransformStyle::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(
(style.TransformStyle3D() == ETransformStyle3D::kPreserve3d)
@@ -6665,16 +6575,16 @@ const CSSValue* TransitionDelay::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForAnimationDelay(style.Transitions());
}
const CSSValue* TransitionDelay::InitialValue() const {
DEFINE_STATIC_LOCAL(
- Persistent<CSSValue>, value,
- (CSSPrimitiveValue::Create(CSSTimingData::InitialDelay(),
- CSSPrimitiveValue::UnitType::kSeconds)));
+ const Persistent<CSSValue>, value,
+ (CSSNumericLiteralValue::Create(CSSTimingData::InitialDelay(),
+ CSSPrimitiveValue::UnitType::kSeconds)));
return value;
}
@@ -6690,16 +6600,16 @@ const CSSValue* TransitionDuration::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForAnimationDuration(style.Transitions());
}
const CSSValue* TransitionDuration::InitialValue() const {
DEFINE_STATIC_LOCAL(
- Persistent<CSSValue>, value,
- (CSSPrimitiveValue::Create(CSSTimingData::InitialDuration(),
- CSSPrimitiveValue::UnitType::kSeconds)));
+ const Persistent<CSSValue>, value,
+ (CSSNumericLiteralValue::Create(CSSTimingData::InitialDuration(),
+ CSSPrimitiveValue::UnitType::kSeconds)));
return value;
}
@@ -6718,13 +6628,13 @@ const CSSValue* TransitionProperty::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForTransitionProperty(style.Transitions());
}
const CSSValue* TransitionProperty::InitialValue() const {
- DEFINE_STATIC_LOCAL(Persistent<CSSValue>, value,
+ DEFINE_STATIC_LOCAL(const Persistent<CSSValue>, value,
(CSSIdentifierValue::Create(CSSValueID::kAll)));
return value;
}
@@ -6741,14 +6651,14 @@ const CSSValue* TransitionTimingFunction::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForAnimationTimingFunction(
style.Transitions());
}
const CSSValue* TransitionTimingFunction::InitialValue() const {
- DEFINE_STATIC_LOCAL(Persistent<CSSValue>, value,
+ DEFINE_STATIC_LOCAL(const Persistent<CSSValue>, value,
(CSSIdentifierValue::Create(CSSValueID::kEase)));
return value;
}
@@ -6774,7 +6684,7 @@ const CSSValue* Translate::ParseSingleValue(
if (translate_y) {
CSSValue* translate_z = css_property_parser_helpers::ConsumeLength(
range, context.Mode(), kValueRangeAll);
- if (translate_y->GetIntValue() == 0 && !translate_z)
+ if (translate_y->IsZero() && !translate_z)
return list;
list->Append(*translate_y);
@@ -6795,7 +6705,7 @@ const CSSValue* Translate::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
if (!style.Translate())
return CSSIdentifierValue::Create(CSSValueID::kNone);
@@ -6819,7 +6729,7 @@ const CSSValue* UnicodeBidi::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.GetUnicodeBidi());
}
@@ -6828,7 +6738,7 @@ const CSSValue* UserSelect::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.UserSelect());
}
@@ -6837,7 +6747,7 @@ const CSSValue* VectorEffect::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(svg_style.VectorEffect());
}
@@ -6860,7 +6770,7 @@ const CSSValue* VerticalAlign::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
switch (style.VerticalAlign()) {
case EVerticalAlign::kBaseline:
@@ -6914,7 +6824,7 @@ const CSSValue* Visibility::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.Visibility());
}
@@ -6923,7 +6833,7 @@ const CSSValue* WebkitAppRegion::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
if (style.DraggableRegionMode() == EDraggableRegionMode::kNone)
return CSSIdentifierValue::Create(CSSValueID::kNone);
@@ -6951,7 +6861,7 @@ const CSSValue* WebkitAppearance::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.Appearance());
}
@@ -6969,7 +6879,7 @@ WebkitBorderHorizontalSpacing::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ZoomAdjustedPixelValue(style.HorizontalBorderSpacing(), style);
}
@@ -6985,7 +6895,7 @@ const CSSValue* WebkitBorderImage::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForNinePieceImage(style.BorderImage(), style);
}
@@ -7010,7 +6920,7 @@ const CSSValue* WebkitBorderVerticalSpacing::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ZoomAdjustedPixelValue(style.VerticalBorderSpacing(), style);
}
@@ -7019,7 +6929,7 @@ const CSSValue* WebkitBoxAlign::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.BoxAlign());
}
@@ -7028,7 +6938,7 @@ const CSSValue* WebkitBoxDecorationBreak::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
if (style.BoxDecorationBreak() == EBoxDecorationBreak::kSlice)
return CSSIdentifierValue::Create(CSSValueID::kSlice);
@@ -7039,7 +6949,7 @@ const CSSValue* WebkitBoxDirection::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.BoxDirection());
}
@@ -7055,10 +6965,10 @@ const CSSValue* WebkitBoxFlex::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
- return CSSPrimitiveValue::Create(style.BoxFlex(),
- CSSPrimitiveValue::UnitType::kNumber);
+ return CSSNumericLiteralValue::Create(style.BoxFlex(),
+ CSSPrimitiveValue::UnitType::kNumber);
}
const CSSValue* WebkitBoxOrdinalGroup::ParseSingleValue(
@@ -7072,17 +6982,17 @@ const CSSValue* WebkitBoxOrdinalGroup::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
- return CSSPrimitiveValue::Create(style.BoxOrdinalGroup(),
- CSSPrimitiveValue::UnitType::kNumber);
+ return CSSNumericLiteralValue::Create(style.BoxOrdinalGroup(),
+ CSSPrimitiveValue::UnitType::kNumber);
}
const CSSValue* WebkitBoxOrient::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.BoxOrient());
}
@@ -7091,7 +7001,7 @@ const CSSValue* WebkitBoxPack::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.BoxPack());
}
@@ -7108,7 +7018,8 @@ CSSValue* ConsumeReflect(CSSParserTokenRange& range,
CSSPrimitiveValue* offset = nullptr;
if (range.AtEnd()) {
- offset = CSSPrimitiveValue::Create(0, CSSPrimitiveValue::UnitType::kPixels);
+ offset =
+ CSSNumericLiteralValue::Create(0, CSSPrimitiveValue::UnitType::kPixels);
} else {
offset = ConsumeLengthOrPercent(
range, context.Mode(), kValueRangeAll,
@@ -7140,7 +7051,7 @@ const CSSValue* WebkitBoxReflect::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForReflection(style.BoxReflect(), style);
}
@@ -7158,7 +7069,7 @@ const CSSValue* WebkitFontSmoothing::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.GetFontDescription().FontSmoothing());
}
@@ -7176,7 +7087,7 @@ const CSSValue* WebkitHighlight::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
if (style.Highlight() == g_null_atom)
return CSSIdentifierValue::Create(CSSValueID::kNone);
@@ -7196,7 +7107,7 @@ const CSSValue* WebkitHyphenateCharacter::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
if (style.HyphenationString().IsNull())
return CSSIdentifierValue::Create(CSSValueID::kAuto);
@@ -7207,7 +7118,7 @@ const CSSValue* WebkitLineBreak::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.GetLineBreak());
}
@@ -7224,12 +7135,12 @@ const CSSValue* WebkitLineClamp::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
if (!style.HasLineClamp())
return CSSIdentifierValue::Create(CSSValueID::kNone);
- return CSSPrimitiveValue::Create(style.LineClamp(),
- CSSPrimitiveValue::UnitType::kNumber);
+ return CSSNumericLiteralValue::Create(style.LineClamp(),
+ CSSPrimitiveValue::UnitType::kNumber);
}
const CSSValue* WebkitLocale::ParseSingleValue(
@@ -7245,7 +7156,7 @@ const CSSValue* WebkitLocale::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
if (style.Locale().IsNull())
return CSSIdentifierValue::Create(CSSValueID::kAuto);
@@ -7267,7 +7178,7 @@ const CSSValue* WebkitMarginAfterCollapse::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.MarginAfterCollapse());
}
@@ -7276,7 +7187,7 @@ const CSSValue* WebkitMarginBeforeCollapse::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.MarginBeforeCollapse());
}
@@ -7285,7 +7196,7 @@ const CSSValue* WebkitMarginBottomCollapse::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.MarginAfterCollapse());
}
@@ -7294,7 +7205,7 @@ const CSSValue* WebkitMarginTopCollapse::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.MarginBeforeCollapse());
}
@@ -7310,7 +7221,7 @@ const CSSValue* WebkitMaskBoxImageOutset::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForNinePieceImageQuad(
style.MaskBoxImage().Outset(), style);
@@ -7327,7 +7238,7 @@ const CSSValue* WebkitMaskBoxImageRepeat::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForNinePieceImageRepeat(style.MaskBoxImage());
}
@@ -7344,7 +7255,7 @@ const CSSValue* WebkitMaskBoxImageSlice::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForNinePieceImageSlice(style.MaskBoxImage());
}
@@ -7360,7 +7271,7 @@ const CSSValue* WebkitMaskBoxImageSource::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
if (style.MaskBoxImageSource())
return style.MaskBoxImageSource()->ComputedCSSValue();
@@ -7384,7 +7295,7 @@ const CSSValue* WebkitMaskBoxImageWidth::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForNinePieceImageQuad(
style.MaskBoxImage().BorderSlices(), style);
@@ -7403,7 +7314,7 @@ const CSSValue* WebkitMaskClip::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
CSSValueList* list = CSSValueList::CreateCommaSeparated();
const FillLayer* curr_layer = &style.MaskLayers();
@@ -7426,7 +7337,7 @@ const CSSValue* WebkitMaskComposite::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
CSSValueList* list = CSSValueList::CreateCommaSeparated();
const FillLayer* curr_layer = &style.MaskLayers();
@@ -7447,7 +7358,7 @@ const CSSValue* WebkitMaskImage::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
const FillLayer& fill_layer = style.MaskLayers();
return ComputedStyleUtils::BackgroundImageOrWebkitMaskImage(fill_layer);
@@ -7466,7 +7377,7 @@ const CSSValue* WebkitMaskOrigin::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
CSSValueList* list = CSSValueList::CreateCommaSeparated();
const FillLayer* curr_layer = &style.MaskLayers();
@@ -7491,7 +7402,7 @@ const CSSValue* WebkitMaskPositionX::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
const FillLayer* curr_layer = &style.MaskLayers();
return ComputedStyleUtils::BackgroundPositionXOrWebkitMaskPositionX(
@@ -7512,7 +7423,7 @@ const CSSValue* WebkitMaskPositionY::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
const FillLayer* curr_layer = &style.MaskLayers();
return ComputedStyleUtils::BackgroundPositionYOrWebkitMaskPositionY(
@@ -7531,7 +7442,7 @@ const CSSValue* WebkitMaskSize::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
const FillLayer& fill_layer = style.MaskLayers();
return ComputedStyleUtils::BackgroundImageOrWebkitMaskSize(style, fill_layer);
@@ -7559,7 +7470,7 @@ const CSSValue* WebkitPrintColorAdjust::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.PrintColorAdjust());
}
@@ -7568,7 +7479,7 @@ const CSSValue* WebkitRtlOrdering::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.RtlOrdering() == EOrder::kVisual
? CSSValueID::kVisual
@@ -7579,7 +7490,7 @@ const CSSValue* WebkitRubyPosition::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.GetRubyPosition());
}
@@ -7597,14 +7508,14 @@ const blink::Color WebkitTapHighlightColor::ColorIncludingFallback(
StyleColor result = style.TapHighlightColor();
if (!result.IsCurrentColor())
return result.GetColor();
- return visited_link ? style.VisitedLinkColor() : style.GetColor();
+ return visited_link ? style.InternalVisitedColor() : style.GetColor();
}
const CSSValue* WebkitTapHighlightColor::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::CurrentColorOrValidColor(
style, style.TapHighlightColor());
@@ -7614,7 +7525,7 @@ const CSSValue* WebkitTextCombine::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
if (style.TextCombine() == ETextCombine::kAll)
return CSSIdentifierValue::Create(CSSValueID::kHorizontal);
@@ -7633,7 +7544,7 @@ WebkitTextDecorationsInEffect::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::RenderTextDecorationFlagsToCSSValue(
style.TextDecorationsInEffect());
@@ -7649,18 +7560,15 @@ const CSSValue* WebkitTextEmphasisColor::ParseSingleValue(
const blink::Color WebkitTextEmphasisColor::ColorIncludingFallback(
bool visited_link,
const ComputedStyle& style) const {
- StyleColor result = visited_link ? style.VisitedLinkTextEmphasisColor()
- : style.TextEmphasisColor();
- if (!result.IsCurrentColor())
- return result.GetColor();
- return visited_link ? style.VisitedLinkColor() : style.GetColor();
+ DCHECK(!visited_link);
+ return style.TextEmphasisColor().Resolve(style.GetColor());
}
const CSSValue* WebkitTextEmphasisColor::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::CurrentColorOrValidColor(
style, style.TextEmphasisColor());
@@ -7720,7 +7628,7 @@ const CSSValue* WebkitTextEmphasisPosition::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
switch (style.GetTextEmphasisPosition()) {
@@ -7783,7 +7691,7 @@ const CSSValue* WebkitTextEmphasisStyle::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
switch (style.GetTextEmphasisMark()) {
case TextEmphasisMark::kNone:
@@ -7880,18 +7788,15 @@ const CSSValue* WebkitTextFillColor::ParseSingleValue(
const blink::Color WebkitTextFillColor::ColorIncludingFallback(
bool visited_link,
const ComputedStyle& style) const {
- StyleColor result =
- visited_link ? style.VisitedLinkTextFillColor() : style.TextFillColor();
- if (!result.IsCurrentColor())
- return result.GetColor();
- return visited_link ? style.VisitedLinkColor() : style.GetColor();
+ DCHECK(!visited_link);
+ return style.TextFillColor().Resolve(style.GetColor());
}
const CSSValue* WebkitTextFillColor::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::CurrentColorOrValidColor(style,
style.TextFillColor());
@@ -7901,7 +7806,7 @@ const CSSValue* WebkitTextOrientation::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
if (style.GetTextOrientation() == ETextOrientation::kMixed)
return CSSIdentifierValue::Create(CSSValueID::kVerticalRight);
@@ -7918,7 +7823,7 @@ const CSSValue* WebkitTextSecurity::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.TextSecurity());
}
@@ -7933,18 +7838,15 @@ const CSSValue* WebkitTextStrokeColor::ParseSingleValue(
const blink::Color WebkitTextStrokeColor::ColorIncludingFallback(
bool visited_link,
const ComputedStyle& style) const {
- StyleColor result = visited_link ? style.VisitedLinkTextStrokeColor()
- : style.TextStrokeColor();
- if (!result.IsCurrentColor())
- return result.GetColor();
- return visited_link ? style.VisitedLinkColor() : style.GetColor();
+ DCHECK(!visited_link);
+ return style.TextStrokeColor().Resolve(style.GetColor());
}
const CSSValue* WebkitTextStrokeColor::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::CurrentColorOrValidColor(style,
style.TextStrokeColor());
@@ -7963,7 +7865,7 @@ const CSSValue* WebkitTextStrokeWidth::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ZoomAdjustedPixelValue(style.TextStrokeWidth(), style);
}
@@ -7998,7 +7900,7 @@ const CSSValue* WebkitUserDrag::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.UserDrag());
}
@@ -8007,7 +7909,7 @@ const CSSValue* WebkitUserModify::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.UserModify());
}
@@ -8016,7 +7918,7 @@ const CSSValue* WebkitWritingMode::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.GetWritingMode());
}
@@ -8031,7 +7933,7 @@ const CSSValue* WhiteSpace::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.WhiteSpace());
}
@@ -8046,10 +7948,10 @@ const CSSValue* Widows::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
- return CSSPrimitiveValue::Create(style.Widows(),
- CSSPrimitiveValue::UnitType::kNumber);
+ return CSSNumericLiteralValue::Create(style.Widows(),
+ CSSPrimitiveValue::UnitType::kNumber);
}
const CSSValue* Width::ParseSingleValue(CSSParserTokenRange& range,
@@ -8068,7 +7970,7 @@ const CSSValue* Width::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
if (ComputedStyleUtils::WidthOrHeightShouldReturnUsedValue(layout_object)) {
return ZoomAdjustedPixelValue(
@@ -8097,7 +7999,7 @@ const CSSValue* WillChange::ParseSingleValue(
unresolved_property != CSSPropertyID::kVariable) {
#if DCHECK_IS_ON()
DCHECK(CSSProperty::Get(resolveCSSPropertyID(unresolved_property))
- .IsEnabled());
+ .IsWebExposed());
#endif
// Now "all" is used by both CSSValue and CSSPropertyValue.
// Need to return nullptr when currentValue is CSSPropertyID::kAll.
@@ -8139,7 +8041,7 @@ const CSSValue* WillChange::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForWillChange(
style.WillChangeProperties(), style.WillChangeContents(),
@@ -8200,7 +8102,7 @@ const CSSValue* WordBreak::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.WordBreak());
}
@@ -8216,7 +8118,7 @@ const CSSValue* WordSpacing::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ZoomAdjustedPixelValue(style.WordSpacing(), style);
}
@@ -8225,7 +8127,7 @@ const CSSValue* WritingMode::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return CSSIdentifierValue::Create(style.GetWritingMode());
}
@@ -8247,7 +8149,7 @@ const CSSValue* X::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ZoomAdjustedPixelValueForLength(svg_style.X(),
style);
@@ -8264,7 +8166,7 @@ const CSSValue* Y::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle& svg_style,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ZoomAdjustedPixelValueForLength(svg_style.Y(),
style);
@@ -8282,12 +8184,12 @@ const CSSValue* ZIndex::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
if (style.HasAutoZIndex() || !style.IsStackingContext())
return CSSIdentifierValue::Create(CSSValueID::kAuto);
- return CSSPrimitiveValue::Create(style.ZIndex(),
- CSSPrimitiveValue::UnitType::kInteger);
+ return CSSNumericLiteralValue::Create(style.ZIndex(),
+ CSSPrimitiveValue::UnitType::kInteger);
}
const CSSValue* Zoom::ParseSingleValue(CSSParserTokenRange& range,
@@ -8321,10 +8223,10 @@ const CSSValue* Zoom::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
- return CSSPrimitiveValue::Create(style.Zoom(),
- CSSPrimitiveValue::UnitType::kNumber);
+ return CSSNumericLiteralValue::Create(style.Zoom(),
+ CSSPrimitiveValue::UnitType::kNumber);
}
void Zoom::ApplyInitial(StyleResolverState& state) const {
@@ -8336,26 +8238,7 @@ void Zoom::ApplyInherit(StyleResolverState& state) const {
}
void Zoom::ApplyValue(StyleResolverState& state, const CSSValue& value) const {
- SECURITY_DCHECK(value.IsPrimitiveValue() || value.IsIdentifierValue());
-
- if (const auto* identifier_value = DynamicTo<CSSIdentifierValue>(value)) {
- if (identifier_value->GetValueID() == CSSValueID::kNormal) {
- state.SetZoom(ComputedStyleInitialValues::InitialZoom());
- }
- } else if (const auto* primitive_value =
- DynamicTo<CSSPrimitiveValue>(value)) {
- if (primitive_value->IsPercentage()) {
- if (float percent = primitive_value->GetFloatValue())
- state.SetZoom(percent / 100.0f);
- else
- state.SetZoom(1.0f);
- } else if (primitive_value->IsNumber()) {
- if (float number = primitive_value->GetFloatValue())
- state.SetZoom(number);
- else
- state.SetZoom(1.0f);
- }
- }
+ state.SetZoom(StyleBuilderConverter::ConvertZoom(state, value));
}
} // namespace css_longhand
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 2f415738f82..fd5cd2ec39b 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,8 +13,8 @@
namespace blink {
-// TODO(andruud): Remove this class when the static Variable instance
-// (as returned by GetCSSPropertyVariable()) has been removed.
+// TODO(https://crbug.com/980160): Remove this class when the static Variable
+// instance (as returned by GetCSSPropertyVariable()) has been removed.
class CORE_EXPORT Variable : public Longhand {
public:
constexpr Variable() : Variable(true) {}
diff --git a/chromium/third_party/blink/renderer/core/css/properties/shorthands/shorthands_custom.cc b/chromium/third_party/blink/renderer/core/css/properties/shorthands/shorthands_custom.cc
index aed51214ff4..e60f650a03a 100644
--- a/chromium/third_party/blink/renderer/core/css/properties/shorthands/shorthands_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/properties/shorthands/shorthands_custom.cc
@@ -3,9 +3,11 @@
// found in the LICENSE file.
#include "base/stl_util.h"
+#include "third_party/blink/renderer/core/css/css_content_distribution_value.h"
#include "third_party/blink/renderer/core/css/css_font_family_value.h"
#include "third_party/blink/renderer/core/css/css_identifier_value.h"
#include "third_party/blink/renderer/core/css/css_initial_value.h"
+#include "third_party/blink/renderer/core/css/css_numeric_literal_value.h"
#include "third_party/blink/renderer/core/css/css_primitive_value_mappings.h"
#include "third_party/blink/renderer/core/css/css_property_value.h"
#include "third_party/blink/renderer/core/css/css_value_pair.h"
@@ -19,87 +21,7 @@
#include "third_party/blink/renderer/core/css/properties/computed_style_utils.h"
#include "third_party/blink/renderer/core/css/properties/css_parsing_utils.h"
#include "third_party/blink/renderer/core/css/properties/longhand.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/animation.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/background.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/background_position.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/background_repeat.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/border.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/border_block.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/border_block_color.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/border_block_end.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/border_block_start.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/border_block_style.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/border_block_width.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/border_bottom.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/border_color.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/border_image.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/border_inline.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/border_inline_color.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/border_inline_end.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/border_inline_start.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/border_inline_style.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/border_inline_width.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/border_left.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/border_radius.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/border_right.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/border_spacing.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/border_style.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/border_top.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/border_width.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/column_rule.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/columns.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/flex.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/flex_flow.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/font.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/font_variant.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/gap.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/grid.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/grid_area.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/grid_column.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/grid_column_gap.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/grid_gap.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/grid_row.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/grid_row_gap.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/grid_template.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/inset.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/inset_block.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/inset_inline.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/list_style.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/margin.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/margin_block.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/margin_inline.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/marker.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/offset.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/outline.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/overflow.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/overscroll_behavior.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/padding.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/padding_block.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/padding_inline.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/page_break_after.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/page_break_before.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/page_break_inside.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/place_content.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/place_items.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/place_self.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/scroll_margin.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/scroll_margin_block.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/scroll_margin_inline.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/scroll_padding.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/scroll_padding_block.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/scroll_padding_inline.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/text_decoration.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/transition.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/webkit_column_break_after.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/webkit_column_break_before.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/webkit_column_break_inside.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/webkit_margin_collapse.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/webkit_mask.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/webkit_mask_box_image.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/webkit_mask_position.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/webkit_mask_repeat.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/webkit_text_emphasis.h"
-#include "third_party/blink/renderer/core/css/properties/shorthands/webkit_text_stroke.h"
+#include "third_party/blink/renderer/core/css/properties/shorthands.h"
#include "third_party/blink/renderer/core/css/zoom_adjusted_pixel_value.h"
#include "third_party/blink/renderer/core/layout/layout_object.h"
#include "third_party/blink/renderer/core/layout/layout_theme.h"
@@ -183,20 +105,20 @@ const CSSValue* Animation::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
const CSSAnimationData* animation_data = style.Animations();
if (animation_data) {
CSSValueList* animations_list = CSSValueList::CreateCommaSeparated();
for (wtf_size_t i = 0; i < animation_data->NameList().size(); ++i) {
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
- list->Append(*CSSPrimitiveValue::Create(
+ list->Append(*CSSNumericLiteralValue::Create(
CSSTimingData::GetRepeated(animation_data->DurationList(), i),
CSSPrimitiveValue::UnitType::kSeconds));
list->Append(*ComputedStyleUtils::CreateTimingFunctionValue(
CSSTimingData::GetRepeated(animation_data->TimingFunctionList(), i)
.get()));
- list->Append(*CSSPrimitiveValue::Create(
+ list->Append(*CSSNumericLiteralValue::Create(
CSSTimingData::GetRepeated(animation_data->DelayList(), i),
CSSPrimitiveValue::UnitType::kSeconds));
list->Append(*ComputedStyleUtils::ValueForAnimationIterationCount(
@@ -218,15 +140,15 @@ const CSSValue* Animation::CSSValueFromComputedStyleInternal(
// animation-name default value.
list->Append(*CSSIdentifierValue::Create(CSSValueID::kNone));
list->Append(
- *CSSPrimitiveValue::Create(CSSAnimationData::InitialDuration(),
- CSSPrimitiveValue::UnitType::kSeconds));
+ *CSSNumericLiteralValue::Create(CSSAnimationData::InitialDuration(),
+ CSSPrimitiveValue::UnitType::kSeconds));
list->Append(*ComputedStyleUtils::CreateTimingFunctionValue(
CSSAnimationData::InitialTimingFunction().get()));
- list->Append(*CSSPrimitiveValue::Create(
+ list->Append(*CSSNumericLiteralValue::Create(
CSSAnimationData::InitialDelay(), CSSPrimitiveValue::UnitType::kSeconds));
list->Append(
- *CSSPrimitiveValue::Create(CSSAnimationData::InitialIterationCount(),
- CSSPrimitiveValue::UnitType::kNumber));
+ *CSSNumericLiteralValue::Create(CSSAnimationData::InitialIterationCount(),
+ CSSPrimitiveValue::UnitType::kNumber));
list->Append(*ComputedStyleUtils::ValueForAnimationDirection(
CSSAnimationData::InitialDirection()));
list->Append(*ComputedStyleUtils::ValueForAnimationFillMode(
@@ -250,7 +172,7 @@ const CSSValue* Background::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForBackgroundShorthand(
style, layout_object, styled_node, allow_visited_style);
@@ -289,7 +211,7 @@ const CSSValue* BackgroundPosition::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::BackgroundPositionOrWebkitMaskPosition(
*this, style, &style.BackgroundLayers());
@@ -329,7 +251,7 @@ const CSSValue* BackgroundRepeat::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::BackgroundRepeatOrWebkitMaskRepeat(
&style.BackgroundLayers());
@@ -349,7 +271,7 @@ const CSSValue* BorderBlockColor::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForInlineBlockShorthand(
borderBlockColorShorthand(), style, layout_object, styled_node,
@@ -385,7 +307,7 @@ const CSSValue* BorderBlock::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
const CSSValue* value_start =
GetCSSPropertyBorderBlockStart().CSSValueFromComputedStyle(
@@ -433,7 +355,7 @@ const CSSValue* BorderBlockStyle::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForInlineBlockShorthand(
borderBlockStyleShorthand(), style, layout_object, styled_node,
@@ -454,7 +376,7 @@ const CSSValue* BorderBlockWidth::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForInlineBlockShorthand(
borderBlockWidthShorthand(), style, layout_object, styled_node,
@@ -475,7 +397,7 @@ const CSSValue* BorderBottom::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForShorthandProperty(
borderBottomShorthand(), style, layout_object, styled_node,
@@ -496,7 +418,7 @@ const CSSValue* BorderColor::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForSidesShorthand(
borderColorShorthand(), style, layout_object, styled_node,
@@ -535,7 +457,7 @@ const CSSValue* Border::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
const CSSValue* value = GetCSSPropertyBorderTop().CSSValueFromComputedStyle(
style, layout_object, styled_node, allow_visited_style);
@@ -611,7 +533,7 @@ const CSSValue* BorderImage::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForNinePieceImage(style.BorderImage(), style);
}
@@ -630,7 +552,7 @@ const CSSValue* BorderInlineColor::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForInlineBlockShorthand(
borderInlineColorShorthand(), style, layout_object, styled_node,
@@ -666,7 +588,7 @@ const CSSValue* BorderInline::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
const CSSValue* value_start =
GetCSSPropertyBorderInlineStart().CSSValueFromComputedStyle(
@@ -714,7 +636,7 @@ const CSSValue* BorderInlineStyle::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForInlineBlockShorthand(
borderInlineStyleShorthand(), style, layout_object, styled_node,
@@ -735,7 +657,7 @@ const CSSValue* BorderInlineWidth::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForInlineBlockShorthand(
borderInlineWidthShorthand(), style, layout_object, styled_node,
@@ -756,7 +678,7 @@ const CSSValue* BorderLeft::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForShorthandProperty(
borderLeftShorthand(), style, layout_object, styled_node,
@@ -812,7 +734,7 @@ const CSSValue* BorderRadius::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForBorderRadiusShorthand(style);
}
@@ -831,7 +753,7 @@ const CSSValue* BorderRight::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForShorthandProperty(
borderRightShorthand(), style, layout_object, styled_node,
@@ -874,7 +796,7 @@ const CSSValue* BorderSpacing::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
list->Append(*ZoomAdjustedPixelValue(style.HorizontalBorderSpacing(), style));
@@ -896,7 +818,7 @@ const CSSValue* BorderStyle::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForSidesShorthand(
borderStyleShorthand(), style, layout_object, styled_node,
@@ -917,7 +839,7 @@ const CSSValue* BorderTop::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForShorthandProperty(
borderTopShorthand(), style, layout_object, styled_node,
@@ -938,7 +860,7 @@ const CSSValue* BorderWidth::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForSidesShorthand(
borderWidthShorthand(), style, layout_object, styled_node,
@@ -959,7 +881,7 @@ const CSSValue* ColumnRule::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForShorthandProperty(
columnRuleShorthand(), style, layout_object, styled_node,
@@ -1000,7 +922,7 @@ const CSSValue* Columns::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForShorthandProperty(
columnsShorthand(), style, layout_object, styled_node,
@@ -1037,7 +959,7 @@ bool Flex::ParseShorthand(bool important,
// flex only allows a basis of 0 (sans units) if
// flex-grow and flex-shrink values have already been
// set.
- flex_basis = CSSPrimitiveValue::Create(
+ flex_basis = CSSNumericLiteralValue::Create(
0, CSSPrimitiveValue::UnitType::kPixels);
} else {
return false;
@@ -1060,7 +982,7 @@ bool Flex::ParseShorthand(bool important,
if (flex_shrink == kUnsetValue)
flex_shrink = 1;
if (!flex_basis) {
- flex_basis = CSSPrimitiveValue::Create(
+ flex_basis = CSSNumericLiteralValue::Create(
0, CSSPrimitiveValue::UnitType::kPercentage);
}
}
@@ -1069,14 +991,14 @@ bool Flex::ParseShorthand(bool important,
return false;
css_property_parser_helpers::AddProperty(
CSSPropertyID::kFlexGrow, CSSPropertyID::kFlex,
- *CSSPrimitiveValue::Create(clampTo<float>(flex_grow),
- CSSPrimitiveValue::UnitType::kNumber),
+ *CSSNumericLiteralValue::Create(clampTo<float>(flex_grow),
+ CSSPrimitiveValue::UnitType::kNumber),
important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
css_property_parser_helpers::AddProperty(
CSSPropertyID::kFlexShrink, CSSPropertyID::kFlex,
- *CSSPrimitiveValue::Create(clampTo<float>(flex_shrink),
- CSSPrimitiveValue::UnitType::kNumber),
+ *CSSNumericLiteralValue::Create(clampTo<float>(flex_shrink),
+ CSSPrimitiveValue::UnitType::kNumber),
important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
@@ -1092,7 +1014,7 @@ const CSSValue* Flex::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForShorthandProperty(
flexShorthand(), style, layout_object, styled_node, allow_visited_style);
@@ -1112,7 +1034,7 @@ const CSSValue* FlexFlow::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForShorthandProperty(
flexFlowShorthand(), style, layout_object, styled_node,
@@ -1145,14 +1067,14 @@ bool ConsumeSystemFont(bool important,
properties);
css_property_parser_helpers::AddProperty(
CSSPropertyID::kFontWeight, CSSPropertyID::kFont,
- *CSSPrimitiveValue::Create(font_weight,
- CSSPrimitiveValue::UnitType::kNumber),
+ *CSSNumericLiteralValue::Create(font_weight,
+ CSSPrimitiveValue::UnitType::kNumber),
important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
css_property_parser_helpers::AddProperty(
CSSPropertyID::kFontSize, CSSPropertyID::kFont,
- *CSSPrimitiveValue::Create(font_size,
- CSSPrimitiveValue::UnitType::kPixels),
+ *CSSNumericLiteralValue::Create(font_size,
+ CSSPrimitiveValue::UnitType::kPixels),
important, css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
properties);
@@ -1201,22 +1123,26 @@ bool ConsumeFont(bool important,
const CSSParserContext& context,
HeapVector<CSSPropertyValue, 256>& properties) {
// Optional font-style, font-variant, font-stretch and font-weight.
+ // Each may be normal.
CSSValue* font_style = nullptr;
CSSIdentifierValue* font_variant_caps = nullptr;
CSSValue* font_weight = nullptr;
CSSValue* font_stretch = nullptr;
- while (!range.AtEnd()) {
+ const int kNumReorderableFontProperties = 4;
+ for (int i = 0; i < kNumReorderableFontProperties && !range.AtEnd(); ++i) {
CSSValueID id = range.Peek().Id();
+ if (id == CSSValueID::kNormal) {
+ css_property_parser_helpers::ConsumeIdent(range);
+ continue;
+ }
if (!font_style &&
- (id == CSSValueID::kNormal || id == CSSValueID::kItalic ||
- id == CSSValueID::kOblique)) {
+ (id == CSSValueID::kItalic || id == CSSValueID::kOblique)) {
font_style = css_parsing_utils::ConsumeFontStyle(range, context.Mode());
if (!font_style)
return false;
continue;
}
- if (!font_variant_caps &&
- (id == CSSValueID::kNormal || id == CSSValueID::kSmallCaps)) {
+ if (!font_variant_caps && id == CSSValueID::kSmallCaps) {
// Font variant in the shorthand is particular, it only accepts normal or
// small-caps.
// See https://drafts.csswg.org/css-fonts/#propdef-font
@@ -1287,8 +1213,7 @@ bool ConsumeFont(bool important,
properties);
// Now a font size _must_ come.
- CSSValue* font_size =
- css_parsing_utils::ConsumeFontSize(range, context.Mode());
+ CSSValue* font_size = css_parsing_utils::ConsumeFontSize(range, context);
if (!font_size || range.AtEnd())
return false;
@@ -1350,7 +1275,7 @@ const CSSValue* Font::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForFont(style);
}
@@ -1460,7 +1385,7 @@ const CSSValue* FontVariant::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForFontVariantProperty(
style, layout_object, styled_node, allow_visited_style);
@@ -1493,7 +1418,7 @@ const CSSValue* Gap::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForShorthandProperty(
gapShorthand(), style, layout_object, styled_node, allow_visited_style);
@@ -1572,7 +1497,7 @@ const CSSValue* GridArea::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForGridShorthand(gridAreaShorthand(), style,
layout_object, styled_node,
@@ -1614,7 +1539,7 @@ const CSSValue* GridColumn::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForGridShorthand(
gridColumnShorthand(), style, layout_object, styled_node,
@@ -1642,7 +1567,7 @@ const CSSValue* GridColumnGap::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForShorthandProperty(
gridColumnGapShorthand(), style, layout_object, styled_node,
@@ -1837,7 +1762,7 @@ const CSSValue* Grid::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForGridShorthand(
gridShorthand(), style, layout_object, styled_node, allow_visited_style);
@@ -1871,7 +1796,7 @@ const CSSValue* GridGap::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForShorthandProperty(
gridGapShorthand(), style, layout_object, styled_node,
@@ -1913,7 +1838,7 @@ const CSSValue* GridRow::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForGridShorthand(gridRowShorthand(), style,
layout_object, styled_node,
@@ -1941,7 +1866,7 @@ const CSSValue* GridRowGap::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForShorthandProperty(
gridRowGapShorthand(), style, layout_object, styled_node,
@@ -1994,7 +1919,7 @@ const CSSValue* GridTemplate::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForGridShorthand(
gridTemplateShorthand(), style, layout_object, styled_node,
@@ -2015,7 +1940,7 @@ const CSSValue* InsetBlock::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForInlineBlockShorthand(
insetBlockShorthand(), style, layout_object, styled_node,
@@ -2036,7 +1961,7 @@ const CSSValue* Inset::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForSidesShorthand(
insetShorthand(), style, layout_object, styled_node, allow_visited_style);
@@ -2056,7 +1981,7 @@ const CSSValue* InsetInline::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForInlineBlockShorthand(
insetInlineShorthand(), style, layout_object, styled_node,
@@ -2069,15 +1994,93 @@ bool ListStyle::ParseShorthand(
const CSSParserContext& context,
const CSSParserLocalContext&,
HeapVector<CSSPropertyValue, 256>& properties) const {
- return css_property_parser_helpers::ConsumeShorthandGreedilyViaLonghands(
- listStyleShorthand(), important, context, range, properties);
+ const CSSValue* none = nullptr;
+ const CSSValue* list_style_position = nullptr;
+ const CSSValue* list_style_image = nullptr;
+ const CSSValue* list_style_type = nullptr;
+ do {
+ if (!none) {
+ none =
+ css_property_parser_helpers::ConsumeIdent<CSSValueID::kNone>(range);
+ if (none)
+ continue;
+ }
+ if (!list_style_position) {
+ list_style_position = css_property_parser_helpers::ParseLonghand(
+ CSSPropertyID::kListStylePosition, CSSPropertyID::kListStyle, context,
+ range);
+ if (list_style_position)
+ continue;
+ }
+ if (!list_style_image) {
+ list_style_image = css_property_parser_helpers::ParseLonghand(
+ CSSPropertyID::kListStyleImage, CSSPropertyID::kListStyle, context,
+ range);
+ if (list_style_image)
+ continue;
+ }
+ if (!list_style_type) {
+ list_style_type = css_property_parser_helpers::ParseLonghand(
+ CSSPropertyID::kListStyleType, CSSPropertyID::kListStyle, context,
+ range);
+ if (list_style_type)
+ continue;
+ }
+ return false;
+ } while (!range.AtEnd());
+ if (none) {
+ if (!list_style_type)
+ list_style_type = none;
+ else if (!list_style_image)
+ list_style_image = none;
+ else
+ return false;
+ }
+
+ if (list_style_position) {
+ AddProperty(CSSPropertyID::kListStylePosition, CSSPropertyID::kListStyle,
+ *list_style_position, important,
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ } else {
+ AddProperty(CSSPropertyID::kListStylePosition, CSSPropertyID::kListStyle,
+ *CSSInitialValue::Create(), important,
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ }
+
+ if (list_style_image) {
+ AddProperty(CSSPropertyID::kListStyleImage, CSSPropertyID::kListStyle,
+ *list_style_image, important,
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ } else {
+ AddProperty(CSSPropertyID::kListStyleImage, CSSPropertyID::kListStyle,
+ *CSSInitialValue::Create(), important,
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ }
+
+ if (list_style_type) {
+ AddProperty(CSSPropertyID::kListStyleType, CSSPropertyID::kListStyle,
+ *list_style_type, important,
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ } else {
+ AddProperty(CSSPropertyID::kListStyleType, CSSPropertyID::kListStyle,
+ *CSSInitialValue::Create(), important,
+ css_property_parser_helpers::IsImplicitProperty::kNotImplicit,
+ properties);
+ }
+
+ return true;
}
const CSSValue* ListStyle::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForShorthandProperty(
listStyleShorthand(), style, layout_object, styled_node,
@@ -2098,7 +2101,7 @@ const CSSValue* MarginBlock::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForInlineBlockShorthand(
marginBlockShorthand(), style, layout_object, styled_node,
@@ -2127,7 +2130,7 @@ const CSSValue* Margin::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForSidesShorthand(marginShorthand(), style,
layout_object, styled_node,
@@ -2148,7 +2151,7 @@ const CSSValue* MarginInline::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForInlineBlockShorthand(
marginInlineShorthand(), style, layout_object, styled_node,
@@ -2299,7 +2302,7 @@ const CSSValue* Offset::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForOffset(style, layout_object, styled_node,
allow_visited_style);
@@ -2319,7 +2322,7 @@ const CSSValue* Outline::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForShorthandProperty(
outlineShorthand(), style, layout_object, styled_node,
@@ -2340,7 +2343,7 @@ const CSSValue* Overflow::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
list->Append(*CSSIdentifierValue::Create(style.OverflowX()));
@@ -2364,7 +2367,7 @@ const CSSValue* OverscrollBehavior::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
list->Append(*CSSIdentifierValue::Create(style.OverscrollBehaviorX()));
@@ -2388,7 +2391,7 @@ const CSSValue* PaddingBlock::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForInlineBlockShorthand(
paddingBlockShorthand(), style, layout_object, styled_node,
@@ -2417,7 +2420,7 @@ const CSSValue* Padding::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForSidesShorthand(paddingShorthand(), style,
layout_object, styled_node,
@@ -2438,7 +2441,7 @@ const CSSValue* PaddingInline::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForInlineBlockShorthand(
paddingInlineShorthand(), style, layout_object, styled_node,
@@ -2469,7 +2472,7 @@ const CSSValue* PageBreakAfter::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForPageBreakBetween(style.BreakAfter());
}
@@ -2498,7 +2501,7 @@ const CSSValue* PageBreakBefore::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForPageBreakBetween(style.BreakBefore());
}
@@ -2526,7 +2529,7 @@ const CSSValue* PageBreakInside::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForPageBreakInside(style.BreakInside());
}
@@ -2540,18 +2543,28 @@ bool PlaceContent::ParseShorthand(
DCHECK_EQ(shorthandForProperty(CSSPropertyID::kPlaceContent).length(), 2u);
CSSParserTokenRange range_copy = range;
+ bool is_baseline = css_parsing_utils::IsBaselineKeyword(range.Peek().Id());
const CSSValue* align_content_value =
To<Longhand>(GetCSSPropertyAlignContent())
.ParseSingleValue(range, context, local_context);
if (!align_content_value)
return false;
- if (range.AtEnd())
- range = range_copy;
+ const CSSValue* justify_content_value = nullptr;
+ if (range.AtEnd()) {
+ if (is_baseline) {
+ justify_content_value = MakeGarbageCollected<CSSContentDistributionValue>(
+ CSSValueID::kInvalid, CSSValueID::kStart, CSSValueID::kInvalid);
+ } else {
+ range = range_copy;
+ }
+ }
+ if (!justify_content_value) {
+ justify_content_value =
+ To<Longhand>(GetCSSPropertyJustifyContent())
+ .ParseSingleValue(range, context, local_context);
+ }
- const CSSValue* justify_content_value =
- To<Longhand>(GetCSSPropertyJustifyContent())
- .ParseSingleValue(range, context, local_context);
if (!justify_content_value || !range.AtEnd())
return false;
@@ -2576,11 +2589,9 @@ const CSSValue* PlaceContent::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
- // TODO (jfernandez): The spec states that we should return the specified
- // value.
- return ComputedStyleUtils::ValuesForShorthandProperty(
+ return ComputedStyleUtils::ValuesForPlaceShorthand(
placeContentShorthand(), style, layout_object, styled_node,
allow_visited_style);
}
@@ -2630,11 +2641,9 @@ const CSSValue* PlaceItems::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
- // TODO (jfernandez): The spec states that we should return the specified
- // value.
- return ComputedStyleUtils::ValuesForShorthandProperty(
+ return ComputedStyleUtils::ValuesForPlaceShorthand(
placeItemsShorthand(), style, layout_object, styled_node,
allow_visited_style);
}
@@ -2683,11 +2692,9 @@ const CSSValue* PlaceSelf::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
- // TODO (jfernandez): The spec states that we should return the specified
- // value.
- return ComputedStyleUtils::ValuesForShorthandProperty(
+ return ComputedStyleUtils::ValuesForPlaceShorthand(
placeSelfShorthand(), style, layout_object, styled_node,
allow_visited_style);
}
@@ -2706,7 +2713,7 @@ const CSSValue* ScrollMarginBlock::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForInlineBlockShorthand(
scrollMarginBlockShorthand(), style, layout_object, styled_node,
@@ -2727,7 +2734,7 @@ const CSSValue* ScrollMargin::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForSidesShorthand(
scrollMarginShorthand(), style, layout_object, styled_node,
@@ -2748,7 +2755,7 @@ const CSSValue* ScrollMarginInline::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForInlineBlockShorthand(
scrollMarginInlineShorthand(), style, layout_object, styled_node,
@@ -2769,7 +2776,7 @@ const CSSValue* ScrollPaddingBlock::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForInlineBlockShorthand(
scrollPaddingBlockShorthand(), style, layout_object, styled_node,
@@ -2790,7 +2797,7 @@ const CSSValue* ScrollPadding::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForSidesShorthand(
scrollPaddingShorthand(), style, layout_object, styled_node,
@@ -2811,7 +2818,7 @@ const CSSValue* ScrollPaddingInline::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForInlineBlockShorthand(
scrollPaddingInlineShorthand(), style, layout_object, styled_node,
@@ -2832,7 +2839,7 @@ const CSSValue* TextDecoration::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject* layout_object,
- Node* styled_node,
+ const Node* styled_node,
bool allow_visited_style) const {
return ComputedStyleUtils::ValuesForShorthandProperty(
textDecorationShorthand(), style, layout_object, styled_node,
@@ -2902,7 +2909,7 @@ const CSSValue* Transition::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
const CSSTransitionData* transition_data = style.Transitions();
if (transition_data) {
@@ -2911,13 +2918,13 @@ const CSSValue* Transition::CSSValueFromComputedStyleInternal(
CSSValueList* list = CSSValueList::CreateSpaceSeparated();
list->Append(*ComputedStyleUtils::CreateTransitionPropertyValue(
transition_data->PropertyList()[i]));
- list->Append(*CSSPrimitiveValue::Create(
+ list->Append(*CSSNumericLiteralValue::Create(
CSSTimingData::GetRepeated(transition_data->DurationList(), i),
CSSPrimitiveValue::UnitType::kSeconds));
list->Append(*ComputedStyleUtils::CreateTimingFunctionValue(
CSSTimingData::GetRepeated(transition_data->TimingFunctionList(), i)
.get()));
- list->Append(*CSSPrimitiveValue::Create(
+ list->Append(*CSSNumericLiteralValue::Create(
CSSTimingData::GetRepeated(transition_data->DelayList(), i),
CSSPrimitiveValue::UnitType::kSeconds));
transitions_list->Append(*list);
@@ -2929,13 +2936,13 @@ const CSSValue* Transition::CSSValueFromComputedStyleInternal(
// transition-property default value.
list->Append(*CSSIdentifierValue::Create(CSSValueID::kAll));
list->Append(
- *CSSPrimitiveValue::Create(CSSTransitionData::InitialDuration(),
- CSSPrimitiveValue::UnitType::kSeconds));
+ *CSSNumericLiteralValue::Create(CSSTransitionData::InitialDuration(),
+ CSSPrimitiveValue::UnitType::kSeconds));
list->Append(*ComputedStyleUtils::CreateTimingFunctionValue(
CSSTransitionData::InitialTimingFunction().get()));
list->Append(
- *CSSPrimitiveValue::Create(CSSTransitionData::InitialDelay(),
- CSSPrimitiveValue::UnitType::kSeconds));
+ *CSSNumericLiteralValue::Create(CSSTransitionData::InitialDelay(),
+ CSSPrimitiveValue::UnitType::kSeconds));
return list;
}
@@ -2962,7 +2969,7 @@ const CSSValue* WebkitColumnBreakAfter::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForWebkitColumnBreakBetween(
style.BreakAfter());
@@ -2991,7 +2998,7 @@ const CSSValue* WebkitColumnBreakBefore::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForWebkitColumnBreakBetween(
style.BreakBefore());
@@ -3020,7 +3027,7 @@ const CSSValue* WebkitColumnBreakInside::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node* styled_node,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForWebkitColumnBreakInside(
style.BreakInside());
@@ -3121,7 +3128,7 @@ const CSSValue* WebkitMaskBoxImage::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::ValueForNinePieceImage(style.MaskBoxImage(),
style);
@@ -3170,7 +3177,7 @@ const CSSValue* WebkitMaskPosition::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::BackgroundPositionOrWebkitMaskPosition(
*this, style, &style.MaskLayers());
@@ -3210,7 +3217,7 @@ const CSSValue* WebkitMaskRepeat::CSSValueFromComputedStyleInternal(
const ComputedStyle& style,
const SVGComputedStyle&,
const LayoutObject*,
- Node*,
+ const Node*,
bool allow_visited_style) const {
return ComputedStyleUtils::BackgroundRepeatOrWebkitMaskRepeat(
&style.MaskLayers());
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 040300dddfa..662e95c88e0 100644
--- a/chromium/third_party/blink/renderer/core/css/property_registration.cc
+++ b/chromium/third_party/blink/renderer/core/css/property_registration.cc
@@ -5,6 +5,9 @@
#include "third_party/blink/renderer/core/css/property_registration.h"
#include "third_party/blink/renderer/core/animation/css_interpolation_types_map.h"
+#include "third_party/blink/renderer/core/css/css_custom_property_declaration.h"
+#include "third_party/blink/renderer/core/css/css_identifier_value.h"
+#include "third_party/blink/renderer/core/css/css_string_value.h"
#include "third_party/blink/renderer/core/css/css_style_sheet.h"
#include "third_party/blink/renderer/core/css/css_syntax_descriptor.h"
#include "third_party/blink/renderer/core/css/css_syntax_string_parser.h"
@@ -18,6 +21,7 @@
#include "third_party/blink/renderer/core/css/resolver/style_builder_converter.h"
#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/css/style_rule.h"
#include "third_party/blink/renderer/core/css/style_sheet_contents.h"
#include "third_party/blink/renderer/core/dom/document.h"
@@ -69,27 +73,83 @@ static bool ComputationallyIndependent(const CSSValue& value) {
return true;
}
- if (const auto* primitive_value = DynamicTo<CSSPrimitiveValue>(value)) {
- if (!primitive_value->IsLength() &&
- !primitive_value->IsCalculatedPercentageWithLength())
- return true;
-
- CSSPrimitiveValue::CSSLengthArray length_array;
- primitive_value->AccumulateLengthArray(length_array);
- for (size_t i = 0; i < length_array.values.size(); i++) {
- if (length_array.type_flags[i] &&
- i != CSSPrimitiveValue::kUnitTypePixels &&
- i != CSSPrimitiveValue::kUnitTypePercentage)
- return false;
- }
- return true;
- }
+ if (const auto* primitive_value = DynamicTo<CSSPrimitiveValue>(value))
+ return primitive_value->IsComputationallyIndependent();
// TODO(timloh): Images values can also contain lengths.
return true;
}
+static base::Optional<CSSSyntaxDescriptor> ConvertSyntax(
+ const CSSValue& value) {
+ return CSSSyntaxStringParser(To<CSSStringValue>(value).Value()).Parse();
+}
+
+static bool ConvertInherts(const CSSValue& value) {
+ CSSValueID inherits_id = To<CSSIdentifierValue>(value).GetValueID();
+ DCHECK(inherits_id == CSSValueID::kTrue || inherits_id == CSSValueID::kFalse);
+ return inherits_id == CSSValueID::kTrue;
+}
+
+static scoped_refptr<CSSVariableData> ConvertInitialVariableData(
+ const CSSValue* value) {
+ if (!value)
+ return nullptr;
+ return To<CSSCustomPropertyDeclaration>(*value).Value();
+}
+
+PropertyRegistration* PropertyRegistration::MaybeCreate(
+ Document& document,
+ const AtomicString& name,
+ StyleRuleProperty& rule) {
+ const auto& properties = rule.Properties();
+
+ // syntax
+ const CSSValue* syntax_value =
+ properties.GetPropertyCSSValue(CSSPropertyID::kSyntax);
+ if (!syntax_value)
+ return nullptr;
+ base::Optional<CSSSyntaxDescriptor> syntax = ConvertSyntax(*syntax_value);
+ if (!syntax)
+ return nullptr;
+
+ // inherits
+ const CSSValue* inherits_value =
+ properties.GetPropertyCSSValue(CSSPropertyID::kInherits);
+ if (!inherits_value)
+ return nullptr;
+ bool inherits = ConvertInherts(*inherits_value);
+
+ // initial-value (optional)
+ const CSSValue* initial_value =
+ properties.GetPropertyCSSValue(CSSPropertyID::kInitialValue);
+ scoped_refptr<CSSVariableData> initial_variable_data =
+ ConvertInitialVariableData(initial_value);
+
+ // Parse initial value, if we have it.
+ const CSSValue* initial = nullptr;
+ if (initial_variable_data) {
+ const CSSParserContext* parser_context =
+ document.ElementSheet().Contents()->ParserContext();
+ const bool is_animation_tainted = false;
+ initial = syntax->Parse(initial_variable_data->TokenRange(), parser_context,
+ is_animation_tainted);
+ if (!initial)
+ return nullptr;
+ if (!ComputationallyIndependent(*initial))
+ return nullptr;
+ initial = &StyleBuilderConverter::ConvertRegisteredPropertyInitialValue(
+ document, *initial);
+ initial_variable_data =
+ StyleBuilderConverter::ConvertRegisteredPropertyVariableData(
+ *initial, is_animation_tainted);
+ }
+
+ return MakeGarbageCollected<PropertyRegistration>(
+ name, *syntax, inherits, initial, initial_variable_data);
+}
+
void PropertyRegistration::registerProperty(
ExecutionContext* execution_context,
const PropertyDescriptor* descriptor,
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 2986ee03c42..4f0ed65fa61 100644
--- a/chromium/third_party/blink/renderer/core/css/property_registration.h
+++ b/chromium/third_party/blink/renderer/core/css/property_registration.h
@@ -11,7 +11,7 @@
#include "third_party/blink/renderer/core/css/css_syntax_descriptor.h"
#include "third_party/blink/renderer/core/css/css_value.h"
#include "third_party/blink/renderer/core/css/css_variable_data.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
@@ -19,12 +19,17 @@ namespace blink {
class ExceptionState;
class ExecutionContext;
class PropertyDescriptor;
+class StyleRuleProperty;
using CSSInterpolationTypes = Vector<std::unique_ptr<CSSInterpolationType>>;
class CORE_EXPORT PropertyRegistration
: public GarbageCollectedFinalized<PropertyRegistration> {
public:
+ static PropertyRegistration* MaybeCreate(Document&,
+ const AtomicString& name,
+ StyleRuleProperty&);
+
static void registerProperty(ExecutionContext*,
const PropertyDescriptor*,
ExceptionState&);
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 d74c6c264ff..cfd893a84b3 100644
--- a/chromium/third_party/blink/renderer/core/css/property_registry.cc
+++ b/chromium/third_party/blink/renderer/core/css/property_registry.cc
@@ -3,7 +3,6 @@
// found in the LICENSE file.
#include "third_party/blink/renderer/core/css/property_registry.h"
-#include "third_party/blink/renderer/core/css/css_custom_property_declaration.h"
namespace blink {
@@ -28,37 +27,6 @@ PropertyRegistry::RegistrationMap::const_iterator PropertyRegistry::end()
return registrations_.end();
}
-const CSSValue* PropertyRegistry::ParseIfRegistered(
- const Document& document,
- const AtomicString& property_name,
- const CSSValue* value) {
- auto* custom_property_declaration =
- DynamicTo<CSSCustomPropertyDeclaration>(value);
- if (!custom_property_declaration)
- return value;
-
- const PropertyRegistry* registry = document.GetPropertyRegistry();
-
- if (!registry)
- return value;
-
- const PropertyRegistration* registration =
- registry->Registration(property_name);
-
- if (!registration)
- return value;
-
- CSSVariableData* tokens = custom_property_declaration->Value();
-
- if (!tokens || tokens->NeedsVariableResolution())
- return value;
-
- const CSSValue* parsed_value = tokens->ParseForSyntax(
- registration->Syntax(), document.GetSecureContextMode());
-
- return parsed_value ? parsed_value : value;
-}
-
void PropertyRegistry::MarkReferenced(const AtomicString& property_name) const {
const PropertyRegistration* registration = Registration(property_name);
if (registration) {
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 730f5784624..53bea429eec 100644
--- a/chromium/third_party/blink/renderer/core/css/property_registry.h
+++ b/chromium/third_party/blink/renderer/core/css/property_registry.h
@@ -25,15 +25,6 @@ class CORE_EXPORT PropertyRegistry : public GarbageCollected<PropertyRegistry> {
void Trace(blink::Visitor* visitor) { visitor->Trace(registrations_); }
- // Parse the incoming value and return the parsed result, if:
- // 1. A registration with the specified name exists, and
- // 2. The incoming value is a CSSCustomPropertyDeclaration, has no
- // unresolved var-references and matches the registered syntax.
- // Otherwise the incoming value is returned.
- static const CSSValue* ParseIfRegistered(const Document& document,
- const AtomicString& property_name,
- const CSSValue*);
-
void MarkReferenced(const AtomicString&) const;
bool WasReferenced(const AtomicString&) const;
diff --git a/chromium/third_party/blink/renderer/core/css/property_set_css_style_declaration.h b/chromium/third_party/blink/renderer/core/css/property_set_css_style_declaration.h
index c0eef99c1c5..0c1e52f2ceb 100644
--- a/chromium/third_party/blink/renderer/core/css/property_set_css_style_declaration.h
+++ b/chromium/third_party/blink/renderer/core/css/property_set_css_style_declaration.h
@@ -32,7 +32,6 @@
namespace blink {
class MutableCSSPropertyValueSet;
-class PropertyRegistry;
class PropertySetCSSStyleDeclaration
: public AbstractPropertySetCSSStyleDeclaration {
@@ -48,8 +47,6 @@ class PropertySetCSSStyleDeclaration
return *property_set_;
}
- PropertyRegistry* GetPropertyRegistry() const override { return nullptr; }
-
Member<MutableCSSPropertyValueSet> property_set_; // Cannot be null
};
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 9ddc9131449..cdedb7b597f 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
@@ -18,7 +18,7 @@
#include "third_party/blink/renderer/platform/fonts/font_description.h"
#include "third_party/blink/renderer/platform/fonts/font_selector.h"
#include "third_party/blink/renderer/platform/fonts/simple_font_data.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_load_priority.h"
#include "third_party/blink/renderer/platform/network/network_state_notifier.h"
@@ -321,14 +321,16 @@ void RemoteFontFaceSource::Trace(blink::Visitor* visitor) {
}
void RemoteFontFaceSource::FontLoadHistograms::LoadStarted() {
- if (!load_start_time_)
- load_start_time_ = CurrentTimeMS();
+ if (load_start_time_.is_null())
+ load_start_time_ = base::TimeTicks::Now();
}
void RemoteFontFaceSource::FontLoadHistograms::FallbackFontPainted(
DisplayPeriod period) {
- if (period == kBlockPeriod && !blank_paint_time_)
- blank_paint_time_ = CurrentTimeMS();
+ if (period == kBlockPeriod && blank_paint_time_.is_null()) {
+ blank_paint_time_ = base::TimeTicks::Now();
+ blank_paint_time_recorded_ = false;
+ }
}
void RemoteFontFaceSource::FontLoadHistograms::LongLimitExceeded() {
@@ -337,14 +339,16 @@ void RemoteFontFaceSource::FontLoadHistograms::LongLimitExceeded() {
}
void RemoteFontFaceSource::FontLoadHistograms::RecordFallbackTime() {
- if (blank_paint_time_ <= 0)
+ if (blank_paint_time_.is_null() || blank_paint_time_recorded_)
return;
- int duration = static_cast<int>(CurrentTimeMS() - blank_paint_time_);
+ base::TimeDelta duration = base::TimeTicks::Now() - blank_paint_time_;
DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram,
blank_text_shown_time_histogram,
("WebFont.BlankTextShownTime", 0, 10000, 50));
- blank_text_shown_time_histogram.Count(duration);
- blank_paint_time_ = -1;
+ blank_text_shown_time_histogram.Count(
+ base::saturated_cast<base::HistogramBase::Sample>(
+ duration.InMilliseconds()));
+ blank_paint_time_recorded_ = true;
}
void RemoteFontFaceSource::FontLoadHistograms::RecordRemoteFont(
@@ -356,16 +360,8 @@ void RemoteFontFaceSource::FontLoadHistograms::RecordRemoteFont(
cache_hit_histogram.Count(DataSourceMetricsValue());
if (data_source_ == kFromDiskCache || data_source_ == kFromNetwork) {
- DCHECK_NE(load_start_time_, 0);
- int duration = static_cast<int>(CurrentTimeMS() - load_start_time_);
- RecordLoadTimeHistogram(font, duration);
-
- enum { kCorsFail, kCorsSuccess, kCorsEnumMax };
- int cors_value =
- font->GetResponse().IsCorsSameOrigin() ? kCorsSuccess : kCorsFail;
- DEFINE_THREAD_SAFE_STATIC_LOCAL(EnumerationHistogram, cors_histogram,
- ("WebFont.CORSSuccess", kCorsEnumMax));
- cors_histogram.Count(cors_value);
+ DCHECK(!load_start_time_.is_null());
+ RecordLoadTimeHistogram(font, base::TimeTicks::Now() - load_start_time_);
}
}
@@ -376,7 +372,7 @@ void RemoteFontFaceSource::FontLoadHistograms::MaySetDataSource(
// Classify as memory cache hit if |load_start_time_| is not set, i.e.
// this RemoteFontFaceSource instance didn't trigger FontResource
// loading.
- if (load_start_time_ == 0)
+ if (load_start_time_.is_null())
data_source_ = kFromMemoryCache;
else
data_source_ = data_source;
@@ -384,9 +380,11 @@ void RemoteFontFaceSource::FontLoadHistograms::MaySetDataSource(
void RemoteFontFaceSource::FontLoadHistograms::RecordLoadTimeHistogram(
const FontResource* font,
- int duration) {
+ base::TimeDelta delta) {
CHECK_NE(kFromUnknown, data_source_);
+ int duration =
+ base::saturated_cast<base::HistogramBase::Sample>(delta.InMilliseconds());
if (font->ErrorOccurred()) {
DEFINE_THREAD_SAFE_STATIC_LOCAL(
CustomCountHistogram, load_error_histogram,
diff --git a/chromium/third_party/blink/renderer/core/css/remote_font_face_source.h b/chromium/third_party/blink/renderer/core/css/remote_font_face_source.h
index 3d7eafe93a3..fa6a90489e8 100644
--- a/chromium/third_party/blink/renderer/core/css/remote_font_face_source.h
+++ b/chromium/third_party/blink/renderer/core/css/remote_font_face_source.h
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/css/css_font_face_source.h"
#include "third_party/blink/renderer/core/execution_context/security_context.h"
#include "third_party/blink/renderer/core/loader/resource/font_resource.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -82,8 +82,7 @@ class RemoteFontFaceSource final : public CSSFontFaceSource,
};
FontLoadHistograms()
- : load_start_time_(0),
- blank_paint_time_(0),
+ : blank_paint_time_recorded_(false),
is_long_limit_exceeded_(false),
data_source_(kFromUnknown) {}
void LoadStarted();
@@ -91,7 +90,7 @@ class RemoteFontFaceSource final : public CSSFontFaceSource,
void LongLimitExceeded();
void RecordFallbackTime();
void RecordRemoteFont(const FontResource*);
- bool HadBlankText() { return blank_paint_time_; }
+ bool HadBlankText() { return !blank_paint_time_.is_null(); }
DataSource GetDataSource() { return data_source_; }
void MaySetDataSource(DataSource);
@@ -102,10 +101,14 @@ class RemoteFontFaceSource final : public CSSFontFaceSource,
}
private:
- void RecordLoadTimeHistogram(const FontResource*, int duration);
+ void RecordLoadTimeHistogram(const FontResource*, base::TimeDelta duration);
CacheHitMetrics DataSourceMetricsValue();
- double load_start_time_;
- double blank_paint_time_;
+ base::TimeTicks load_start_time_;
+ base::TimeTicks blank_paint_time_;
+ // |blank_paint_time_recorded_| is used to prevent
+ // WebFont.BlankTextShownTime to be reported incorrectly when the web font
+ // fallbacks immediately. See https://crbug.com/591304
+ bool blank_paint_time_recorded_;
bool is_long_limit_exceeded_;
DataSource data_source_;
};
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 6b57d119ead..9842a19f4a2 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
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_RESOLVER_CSS_PROPERTY_PRIORITY_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/allocator/allocator.h"
namespace blink {
@@ -87,7 +87,7 @@ inline CSSPropertyID CSSPropertyPriorityData<kHighPropertyPriority>::First() {
template <>
inline CSSPropertyID CSSPropertyPriorityData<kHighPropertyPriority>::Last() {
static_assert(static_cast<int>(CSSPropertyID::kZoom) ==
- static_cast<int>(CSSPropertyID::kColor) + 22,
+ static_cast<int>(CSSPropertyID::kColor) + 25,
"CSSPropertyID::kZoom should be the end of the high priority "
"property range");
static_assert(static_cast<int>(CSSPropertyID::kWritingMode) ==
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 bd46b249d8f..9781979c133 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
@@ -28,7 +28,7 @@
#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"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 a99c4f0aadb..210bc41cd1b 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
@@ -61,7 +61,8 @@ CSSVariableResolver::Fallback CSSVariableResolver::ResolveFallback(
scoped_refptr<CSSVariableData> CSSVariableResolver::ValueForCustomProperty(
AtomicString name,
- const Options& options) {
+ const Options& options,
+ bool& unit_cycle) {
if (variables_seen_.Contains(name)) {
cycle_start_points_.insert(name);
return nullptr;
@@ -87,7 +88,12 @@ scoped_refptr<CSSVariableData> CSSVariableResolver::ValueForCustomProperty(
}
if (resolved_data) {
- if (IsVariableDisallowed(*resolved_data, options, registration))
+ if (IsDisallowedByFontUnitFlags(*resolved_data, options, registration)) {
+ unit_cycle = true;
+ SetInvalidVariable(name, registration);
+ return nullptr;
+ }
+ if (IsDisallowedByAnimationTaintedFlag(*resolved_data, options))
return nullptr;
}
@@ -198,18 +204,23 @@ CSSVariableResolver::ResolveCustomPropertyIfNeeded(
return ResolveCustomProperty(name, *variable_data, options, cycle_detected);
}
-bool CSSVariableResolver::IsVariableDisallowed(
+bool CSSVariableResolver::IsDisallowedByFontUnitFlags(
const CSSVariableData& variable_data,
const Options& options,
const PropertyRegistration* registration) {
- return (options.disallow_animation_tainted &&
- variable_data.IsAnimationTainted()) ||
- (registration && options.disallow_registered_font_units &&
+ return (registration && options.disallow_registered_font_units &&
variable_data.HasFontUnits()) ||
(registration && options.disallow_registered_root_font_units &&
variable_data.HasRootFontUnits());
}
+bool CSSVariableResolver::IsDisallowedByAnimationTaintedFlag(
+ const CSSVariableData& variable_data,
+ const Options& options) {
+ return options.disallow_animation_tainted &&
+ variable_data.IsAnimationTainted();
+}
+
CSSVariableData* CSSVariableResolver::GetVariableData(
const AtomicString& name,
const PropertyRegistration* registration) {
@@ -257,6 +268,15 @@ void CSSVariableResolver::SetInvalidVariable(
SetVariableValue(name, *registration, nullptr);
}
+const CSSParserContext* CSSVariableResolver::GetParserContext(
+ const CSSVariableReferenceValue& value) const {
+ // TODO(crbug.com/985028): CSSVariableReferenceValue should always have
+ // a CSSParserContext.
+ if (value.ParserContext())
+ return value.ParserContext();
+ return StrictCSSParserContext(state_.GetDocument().GetSecureContextMode());
+}
+
bool CSSVariableResolver::ResolveVariableReference(CSSParserTokenRange range,
const Options& options,
bool is_env_variable,
@@ -282,9 +302,14 @@ bool CSSVariableResolver::ResolveVariableReference(CSSParserTokenRange range,
registry_->MarkReferenced(variable_name);
}
+ bool unit_cycle = false;
scoped_refptr<CSSVariableData> variable_data =
- is_env_variable ? ValueForEnvironmentVariable(variable_name)
- : ValueForCustomProperty(variable_name, options);
+ is_env_variable
+ ? ValueForEnvironmentVariable(variable_name)
+ : ValueForCustomProperty(variable_name, options, unit_cycle);
+
+ if (unit_cycle)
+ return false;
if (!variable_data) {
// TODO(alancutter): Append the registered initial custom property value if
@@ -357,8 +382,7 @@ const CSSValue* CSSVariableResolver::ResolveVariableReferences(
if (id == CSSPropertyID::kFontSize) {
bool is_root =
- state_.GetElement() &&
- state_.GetElement() == state_.GetDocument().documentElement();
+ &state_.GetElement() == state_.GetDocument().documentElement();
options.disallow_registered_font_units = true;
options.disallow_registered_root_font_units = is_root;
}
@@ -388,7 +412,7 @@ const CSSValue* CSSVariableResolver::ResolveVariableReferences(
return cssvalue::CSSUnsetValue::Create();
}
const CSSValue* resolved_value = CSSPropertyParser::ParseSingleValue(
- id, result.tokens, value.ParserContext());
+ id, result.tokens, GetParserContext(value));
if (!resolved_value)
return cssvalue::CSSUnsetValue::Create();
return resolved_value;
@@ -398,11 +422,22 @@ const CSSValue* CSSVariableResolver::ResolvePendingSubstitutions(
CSSPropertyID id,
const cssvalue::CSSPendingSubstitutionValue& pending_value,
const Options& options) {
+ DCHECK_NE(CSSPropertyID::kVariable, id);
+
+ // For -internal-visited-* properties, we pretend that we're resolving the
+ // unvisited counterpart. This is because the CSSPendingSubstitutionValue
+ // held by the -internal-visited-* property contains a shorthand that expands
+ // to unvisited properties.
+ const CSSProperty& property = CSSProperty::Get(id);
+ CSSPropertyID cache_id = id;
+ if (property.IsVisited())
+ cache_id = property.GetUnvisitedProperty()->PropertyID();
+
// Longhands from shorthand references follow this path.
HeapHashMap<CSSPropertyID, Member<const CSSValue>>& property_cache =
state_.ParsedPropertiesForPendingSubstitutionCache(pending_value);
- const CSSValue* value = property_cache.at(id);
+ const CSSValue* value = property_cache.at(cache_id);
if (!value) {
// TODO(timloh): We shouldn't retry this for all longhands if the shorthand
// ends up invalid.
@@ -425,7 +460,7 @@ const CSSValue* CSSVariableResolver::ResolvePendingSubstitutions(
}
}
}
- value = property_cache.at(id);
+ value = property_cache.at(cache_id);
}
if (value)
@@ -461,14 +496,18 @@ void CSSVariableResolver::ResolveVariableDefinitions() {
int variable_count = 0;
if (inherited_variables_ && inherited_variables_->NeedsResolution()) {
- for (auto& variable : inherited_variables_->Data())
- ValueForCustomProperty(variable.key, options);
+ for (auto& variable : inherited_variables_->Data()) {
+ bool cycle_detected = false;
+ ValueForCustomProperty(variable.key, options, cycle_detected);
+ }
inherited_variables_->ClearNeedsResolution();
variable_count += inherited_variables_->Data().size();
}
if (non_inherited_variables_ && non_inherited_variables_->NeedsResolution()) {
- for (auto& variable : non_inherited_variables_->Data())
- ValueForCustomProperty(variable.key, options);
+ for (auto& variable : non_inherited_variables_->Data()) {
+ bool cycle_detected = false;
+ ValueForCustomProperty(variable.key, options, cycle_detected);
+ }
non_inherited_variables_->ClearNeedsResolution();
variable_count += non_inherited_variables_->Data().size();
}
@@ -480,12 +519,16 @@ void CSSVariableResolver::ComputeRegisteredVariables() {
Options options;
if (inherited_variables_) {
- for (auto& variable : inherited_variables_->Values())
- ValueForCustomProperty(variable.key, options);
+ for (auto& variable : inherited_variables_->Values()) {
+ bool cycle_detected = false;
+ ValueForCustomProperty(variable.key, options, cycle_detected);
+ }
}
if (non_inherited_variables_) {
- for (auto& variable : non_inherited_variables_->Values())
- ValueForCustomProperty(variable.key, options);
+ for (auto& variable : non_inherited_variables_->Values()) {
+ bool cycle_detected = false;
+ ValueForCustomProperty(variable.key, options, cycle_detected);
+ }
}
}
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 4b61055e282..1df731c3b04 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
@@ -17,6 +17,7 @@ class CSSCustomPropertyDeclaration;
class CSSParserTokenRange;
class CSSVariableData;
class CSSVariableReferenceValue;
+class CSSParserContext;
class PropertyRegistration;
class PropertyRegistry;
class StyleInheritedVariables;
@@ -172,9 +173,13 @@ class CORE_EXPORT CSSVariableResolver {
scoped_refptr<CSSVariableData> ValueForEnvironmentVariable(
const AtomicString& name);
// Returns the CSSVariableData for a custom property, resolving and storing it
- // if necessary.
+ // if necessary. If a cycle via font-relative units was discovered, the
+ // unit_cycle flag is set to true.
+ //
+ // https://drafts.css-houdini.org/css-properties-values-api-1/#dependency-cycles
scoped_refptr<CSSVariableData> ValueForCustomProperty(AtomicString name,
- const Options&);
+ const Options&,
+ bool& unit_cycle);
// Resolves the CSSVariableData from a custom property declaration.
scoped_refptr<CSSVariableData> ResolveCustomProperty(AtomicString name,
const CSSVariableData&,
@@ -188,9 +193,12 @@ class CORE_EXPORT CSSVariableResolver {
const Options&,
bool& cycle_detected);
- bool IsVariableDisallowed(const CSSVariableData&,
- const Options&,
- const PropertyRegistration*);
+ bool IsDisallowedByFontUnitFlags(const CSSVariableData&,
+ const Options&,
+ const PropertyRegistration*);
+
+ bool IsDisallowedByAnimationTaintedFlag(const CSSVariableData&,
+ const Options&);
// The following utilities get/set variables on either StyleInheritedVariables
// or StyleNonInheritedVariables, according to their PropertyRegistration.
@@ -207,6 +215,10 @@ class CORE_EXPORT CSSVariableResolver {
const CSSValue*);
void SetInvalidVariable(const AtomicString& name,
const PropertyRegistration*);
+
+ const CSSParserContext* GetParserContext(
+ const CSSVariableReferenceValue&) const;
+
const StyleResolverState& state_;
StyleInheritedVariables* inherited_variables_;
StyleNonInheritedVariables* non_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 eb6ff4edc28..a7d942a8082 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
@@ -6,6 +6,7 @@
#include "third_party/blink/renderer/core/css/css_custom_property_declaration.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_numeric_literal_value.h"
#include "third_party/blink/renderer/core/css/css_syntax_string_parser.h"
#include "third_party/blink/renderer/core/css/css_unset_value.h"
#include "third_party/blink/renderer/core/css/css_variable_reference_value.h"
@@ -108,7 +109,8 @@ class CSSVariableResolverTest : public PageTestBase {
}
const CSSValue* CreatePxValue(double px) {
- return CSSPrimitiveValue::Create(px, CSSPrimitiveValue::UnitType::kPixels);
+ return CSSNumericLiteralValue::Create(px,
+ CSSPrimitiveValue::UnitType::kPixels);
}
size_t MaxSubstitutionTokens() const {
@@ -274,8 +276,13 @@ TEST_F(CSSVariableResolverTest, CopiedVariablesRetainNeedsResolution) {
}
TEST_F(CSSVariableResolverTest, NeedsResolutionClearedByResolver) {
+ // This test is not relevant when CSSCascade is enabled, as we won't store
+ // unresolved CSSVariableData on the ComputedStyle in that case.
+ if (RuntimeEnabledFeatures::CSSCascadeEnabled())
+ return;
+
const ComputedStyle* initial = &ComputedStyle::InitialStyle();
- StyleResolverState state(GetDocument(), nullptr /* element */,
+ StyleResolverState state(GetDocument(), *GetDocument().documentElement(),
nullptr /* pseudo_element */, initial, initial);
scoped_refptr<ComputedStyle> style = ComputedStyle::Create();
@@ -463,7 +470,7 @@ TEST_F(CSSVariableResolverTest, CSSWideKeywords) {
using CSSUnsetValue = cssvalue::CSSUnsetValue;
const ComputedStyle* initial = &ComputedStyle::InitialStyle();
- StyleResolverState state(GetDocument(), nullptr /* element */,
+ StyleResolverState state(GetDocument(), *GetDocument().documentElement(),
nullptr /* pseudo_element */, initial, initial);
scoped_refptr<ComputedStyle> style = ComputedStyle::Create();
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/element_resolve_context.cc b/chromium/third_party/blink/renderer/core/css/resolver/element_resolve_context.cc
index b33131b958b..3e755ed6cd8 100644
--- a/chromium/third_party/blink/renderer/core/css/resolver/element_resolve_context.cc
+++ b/chromium/third_party/blink/renderer/core/css/resolver/element_resolve_context.cc
@@ -30,32 +30,23 @@
namespace blink {
-ElementResolveContext::ElementResolveContext(const Document& document)
- : element_(nullptr),
- parent_node_(nullptr),
- layout_parent_(nullptr),
- root_element_style_(document.documentElement()
- ? document.documentElement()->GetComputedStyle()
- : document.GetComputedStyle()),
- element_link_state_(EInsideLink::kNotInsideLink),
- distributed_to_insertion_point_(false) {}
-
ElementResolveContext::ElementResolveContext(Element& element)
: element_(&element),
element_link_state_(
element.GetDocument().GetVisitedLinkState().DetermineLinkState(
element)),
distributed_to_insertion_point_(false) {
- LayoutTreeBuilderTraversal::ParentDetails parent_details;
- if (element.CanParticipateInFlatTree()) {
+ if (!element.NeedsDistributionRecalc() &&
+ element.CanParticipateInFlatTree()) {
+ LayoutTreeBuilderTraversal::ParentDetails parent_details;
parent_node_ = LayoutTreeBuilderTraversal::Parent(element);
layout_parent_ =
LayoutTreeBuilderTraversal::LayoutParent(element, &parent_details);
+ distributed_to_insertion_point_ = parent_details.GetInsertionPoint();
} else {
parent_node_ = nullptr;
layout_parent_ = nullptr;
}
- distributed_to_insertion_point_ = parent_details.GetInsertionPoint();
const Document& document = element.GetDocument();
Node* document_element = document.documentElement();
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 b7b00858af9..d1984700d80 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
@@ -29,7 +29,6 @@
namespace blink {
class ContainerNode;
-class Document;
class Element;
class ComputedStyle;
@@ -39,11 +38,9 @@ class CORE_EXPORT ElementResolveContext {
STACK_ALLOCATED();
public:
- explicit ElementResolveContext(const Document&);
-
explicit ElementResolveContext(Element&);
- Element* GetElement() const { return element_; }
+ Element& GetElement() const { return *element_; }
const ContainerNode* ParentNode() const { return parent_node_; }
const ContainerNode* LayoutParent() const { return layout_parent_; }
const ComputedStyle* RootElementStyle() const {
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 9278785b242..173a46cf1f8 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
@@ -211,8 +211,8 @@ void ElementStyleResources::LoadPendingImages(ComputedStyle* style) {
if (!BackgroundLayerMayBeSprite(*background_layer)) {
if (element_->GetDocument()
.GetFrame()
- ->GetLazyLoadImageEnabledState() ==
- LocalFrame::LazyLoadImageEnabledState::kEnabledAutomatic) {
+ ->GetLazyLoadImageSetting() ==
+ LocalFrame::LazyLoadImageSetting::kEnabledAutomatic) {
image_request_optimization = FetchParameters::kDeferImageLoad;
} else {
image_request_optimization = FetchParameters::kAllowPlaceholder;
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 df8257de706..157bf28c827 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
@@ -35,8 +35,8 @@
#include "third_party/blink/renderer/core/css/css_uri_value.h"
#include "third_party/blink/renderer/core/css/resolver/style_builder_converter.h"
#include "third_party/blink/renderer/core/css/resolver/style_resolver_state.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
@@ -120,8 +120,8 @@ static void CountFilterUse(FilterOperation::OperationType operation_type,
document.CountUse(feature);
}
-static double ResolveFirstArgumentForFunction(const CSSFunctionValue& filter,
- const CSSPrimitiveValue* value) {
+double FilterOperationResolver::ResolveNumericArgumentForFunction(
+ const CSSFunctionValue& filter) {
switch (filter.FunctionType()) {
case CSSValueID::kGrayscale:
case CSSValueID::kSepia:
@@ -130,21 +130,21 @@ static double ResolveFirstArgumentForFunction(const CSSFunctionValue& filter,
case CSSValueID::kBrightness:
case CSSValueID::kContrast:
case CSSValueID::kOpacity: {
- double amount = (filter.FunctionType() == CSSValueID::kBrightness ||
- filter.FunctionType() == CSSValueID::kInvert)
- ? 0
- : 1;
+ double amount = 1;
if (filter.length() == 1) {
- amount = value->GetDoubleValue();
- if (value->IsPercentage())
+ const CSSPrimitiveValue& value = To<CSSPrimitiveValue>(filter.Item(0));
+ amount = value.GetDoubleValue();
+ if (value.IsPercentage())
amount /= 100;
}
return amount;
}
case CSSValueID::kHueRotate: {
double angle = 0;
- if (filter.length() == 1)
- angle = value->ComputeDegrees();
+ if (filter.length() == 1) {
+ const CSSPrimitiveValue& value = To<CSSPrimitiveValue>(filter.Item(0));
+ angle = value.ComputeDegrees();
+ }
return angle;
}
default:
@@ -185,14 +185,6 @@ FilterOperations FilterOperationResolver::CreateFilterOperations(
FilterOperationForType(filter_value->FunctionType());
CountFilterUse(operation_type, state.GetDocument());
DCHECK_LE(filter_value->length(), 1u);
-
- const CSSPrimitiveValue* first_value = nullptr;
- if (filter_value->length())
- first_value = DynamicTo<CSSPrimitiveValue>(filter_value->Item(0));
-
- double first_number =
- ResolveFirstArgumentForFunction(*filter_value, first_value);
-
switch (filter_value->FunctionType()) {
case CSSValueID::kGrayscale:
case CSSValueID::kSepia:
@@ -200,7 +192,8 @@ FilterOperations FilterOperationResolver::CreateFilterOperations(
case CSSValueID::kHueRotate: {
operations.Operations().push_back(
MakeGarbageCollected<BasicColorMatrixFilterOperation>(
- first_number, operation_type));
+ ResolveNumericArgumentForFunction(*filter_value),
+ operation_type));
break;
}
case CSSValueID::kInvert:
@@ -209,12 +202,15 @@ FilterOperations FilterOperationResolver::CreateFilterOperations(
case CSSValueID::kOpacity: {
operations.Operations().push_back(
MakeGarbageCollected<BasicComponentTransferFilterOperation>(
- first_number, operation_type));
+ ResolveNumericArgumentForFunction(*filter_value),
+ operation_type));
break;
}
case CSSValueID::kBlur: {
Length std_deviation = Length::Fixed(0);
if (filter_value->length() >= 1) {
+ const CSSPrimitiveValue* first_value =
+ DynamicTo<CSSPrimitiveValue>(filter_value->Item(0));
std_deviation = first_value->ConvertToLength(conversion_data);
}
operations.Operations().push_back(
@@ -269,14 +265,6 @@ FilterOperations FilterOperationResolver::CreateOffscreenFilterOperations(
// so we can have workers using UseCounter as well.
// countFilterUse(operationType, state.document());
DCHECK_LE(filter_value->length(), 1u);
-
- const CSSPrimitiveValue* first_value = nullptr;
- if (filter_value->length())
- first_value = DynamicTo<CSSPrimitiveValue>(filter_value->Item(0));
-
- double first_number =
- ResolveFirstArgumentForFunction(*filter_value, first_value);
-
switch (filter_value->FunctionType()) {
case CSSValueID::kGrayscale:
case CSSValueID::kSepia:
@@ -284,7 +272,8 @@ FilterOperations FilterOperationResolver::CreateOffscreenFilterOperations(
case CSSValueID::kHueRotate: {
operations.Operations().push_back(
MakeGarbageCollected<BasicColorMatrixFilterOperation>(
- first_number, operation_type));
+ ResolveNumericArgumentForFunction(*filter_value),
+ operation_type));
break;
}
case CSSValueID::kInvert:
@@ -293,12 +282,15 @@ FilterOperations FilterOperationResolver::CreateOffscreenFilterOperations(
case CSSValueID::kOpacity: {
operations.Operations().push_back(
MakeGarbageCollected<BasicComponentTransferFilterOperation>(
- first_number, operation_type));
+ ResolveNumericArgumentForFunction(*filter_value),
+ operation_type));
break;
}
case CSSValueID::kBlur: {
Length std_deviation = Length::Fixed(0);
if (filter_value->length() >= 1) {
+ const CSSPrimitiveValue* first_value =
+ DynamicTo<CSSPrimitiveValue>(filter_value->Item(0));
std_deviation = first_value->ConvertToLength(conversion_data);
}
operations.Operations().push_back(
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/filter_operation_resolver.h b/chromium/third_party/blink/renderer/core/css/resolver/filter_operation_resolver.h
index 39920cbb894..dc9a930311f 100644
--- a/chromium/third_party/blink/renderer/core/css/resolver/filter_operation_resolver.h
+++ b/chromium/third_party/blink/renderer/core/css/resolver/filter_operation_resolver.h
@@ -30,6 +30,7 @@
namespace blink {
+class CSSFunctionValue;
class CSSValue;
class StyleResolverState;
@@ -42,6 +43,8 @@ class CORE_EXPORT FilterOperationResolver {
const CSSValue&);
static FilterOperations CreateOffscreenFilterOperations(const CSSValue&,
const Font&);
+ static double ResolveNumericArgumentForFunction(
+ const CSSFunctionValue& filter);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/match_result.cc b/chromium/third_party/blink/renderer/core/css/resolver/match_result.cc
index b6265ac41d9..4391044d6b1 100644
--- a/chromium/third_party/blink/renderer/core/css/resolver/match_result.cc
+++ b/chromium/third_party/blink/renderer/core/css/resolver/match_result.cc
@@ -30,14 +30,18 @@
#include "third_party/blink/renderer/core/css/resolver/match_result.h"
+#include <memory>
#include <type_traits>
#include "third_party/blink/renderer/core/css/css_property_value_set.h"
#include "third_party/blink/renderer/core/css/style_rule.h"
+#include "third_party/blink/renderer/platform/wtf/math_extras.h"
namespace blink {
-MatchedProperties::MatchedProperties() : possibly_padded_member(nullptr) {}
+MatchedProperties::MatchedProperties() {
+ memset(&types_, 0, sizeof(types_));
+}
MatchedProperties::~MatchedProperties() = default;
@@ -56,6 +60,10 @@ void MatchResult::AddMatchedProperties(
new_properties.types_.valid_property_filter =
static_cast<std::underlying_type_t<ValidPropertyFilter>>(
valid_property_filter);
+ // TODO(andruud): MatchedProperties are stored here in reverse order.
+ // Reevaluate this when cascade has shipped.
+ new_properties.types_.tree_order =
+ std::numeric_limits<uint16_t>::max() - current_tree_order_;
}
void MatchResult::FinishAddingUARules() {
@@ -71,6 +79,7 @@ void MatchResult::FinishAddingUserRules() {
user_range_ends_.back() == matched_properties_.size())
return;
user_range_ends_.push_back(matched_properties_.size());
+ current_tree_order_ = clampTo<uint16_t>(user_range_ends_.size());
}
void MatchResult::FinishAddingAuthorRulesForTreeScope() {
@@ -85,6 +94,7 @@ void MatchResult::FinishAddingAuthorRulesForTreeScope() {
author_range_ends_.back() == matched_properties_.size())
return;
author_range_ends_.push_back(matched_properties_.size());
+ current_tree_order_ = clampTo<uint16_t>(author_range_ends_.size());
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/match_result.h b/chromium/third_party/blink/renderer/core/css/resolver/match_result.h
index ac45f89ccab..e555f7995f2 100644
--- a/chromium/third_party/blink/renderer/core/css/resolver/match_result.h
+++ b/chromium/third_party/blink/renderer/core/css/resolver/match_result.h
@@ -46,15 +46,22 @@ struct CORE_EXPORT MatchedProperties {
Member<CSSPropertyValueSet> properties;
- union {
- struct {
- unsigned link_match_type : 2;
- unsigned valid_property_filter : 2;
- } types_;
- // Used to make sure all memory is zero-initialized since we compute the
- // hash over the bytes of this object.
- void* possibly_padded_member;
- };
+ struct {
+ unsigned link_match_type : 2;
+ unsigned valid_property_filter : 2;
+ // This is approximately equivalent to the 'shadow-including tree order'.
+ // It can be used to evaluate the 'Shadow Tree' criteria. Note that the
+ // number stored here is 'local' to each origin (user, author), and is
+ // not used at all for the UA origin. Hence, it is not possible to compare
+ // tree_orders from two different origins.
+ //
+ // Note also that the tree_order will start at ~0u and then decrease.
+ // This is because we currently store the matched properties in reverse
+ // order.
+ //
+ // https://drafts.csswg.org/css-scoping/#shadow-cascading
+ uint16_t tree_order;
+ } types_;
};
} // namespace blink
@@ -149,6 +156,7 @@ class CORE_EXPORT MatchResult {
Vector<unsigned, 16> author_range_ends_;
unsigned ua_range_end_ = 0;
bool is_cacheable_ = true;
+ uint16_t current_tree_order_ = 0;
DISALLOW_COPY_AND_ASSIGN(MatchResult);
};
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 143554abac6..deb17120a0f 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
@@ -47,9 +47,8 @@ class StyleSheetContents;
// and provides methods to collect the rules that apply to a given element,
// broken down by what kind of scope they apply to (e.g. shadow host,
// tree-boundary-crossing, etc).
-class ScopedStyleResolver final
+class CORE_EXPORT ScopedStyleResolver final
: public GarbageCollectedFinalized<ScopedStyleResolver> {
-
public:
explicit ScopedStyleResolver(TreeScope& scope) : scope_(scope) {}
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 0b29a4b537b..ae73c27522e 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
@@ -41,7 +41,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/frame/settings.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/forms/html_input_element.h"
#include "third_party/blink/renderer/core/html/forms/html_text_area_element.h"
#include "third_party/blink/renderer/core/html/html_iframe_element.h"
@@ -58,6 +57,7 @@
#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/geometry/length.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.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"
@@ -353,6 +353,13 @@ static void AdjustOverflow(ComputedStyle& style) {
static void AdjustStyleForDisplay(ComputedStyle& style,
const ComputedStyle& layout_parent_style,
Document* document) {
+ // Blockify the children of flex, grid or LayoutCustom containers.
+ if (layout_parent_style.BlockifiesChildren()) {
+ style.SetIsInBlockifyingDisplay();
+ if (style.Display() != EDisplay::kContents)
+ style.SetDisplay(EquivalentBlockDisplay(style.Display()));
+ }
+
if (style.Display() == EDisplay::kBlock && !style.IsFloating())
return;
@@ -413,7 +420,6 @@ static void AdjustStyleForDisplay(ComputedStyle& style,
if (layout_parent_style.IsDisplayFlexibleOrGridBox()) {
style.SetFloating(EFloat::kNone);
- style.SetDisplay(EquivalentBlockDisplay(style.Display()));
// We want to count vertical percentage paddings/margins on flex items
// because our current behavior is different from the spec and we want to
@@ -427,9 +433,6 @@ static void AdjustStyleForDisplay(ComputedStyle& style,
style.MarginAfter().IsPercentOrCalc()) {
UseCounter::Count(document, WebFeature::kFlexboxPercentageMarginVertical);
}
- } else if (layout_parent_style.IsDisplayLayoutCustomBox()) {
- // Blockify the children of a LayoutCustom.
- style.SetDisplay(EquivalentBlockDisplay(style.Display()));
}
}
@@ -672,5 +675,17 @@ void StyleAdjuster::AdjustComputedStyle(StyleResolverState& state,
style.SetTextOverflow(text_control->ValueForTextOverflow());
}
}
+
+ if (RuntimeEnabledFeatures::LayoutNGBlockFragmentationEnabled()) {
+ // When establishing a block fragmentation context for LayoutNG, we require
+ // that everything fragmentable inside can be laid out by NG natively, since
+ // NG and legacy layout cannot cooperate within the same fragmentation
+ // context. Set a flag, so that we can quickly determine whether we need to
+ // check that an element is compatible with the NG block fragmentation
+ // machinery.
+ if (style.SpecifiesColumns() ||
+ (element && element->GetDocument().Printing()))
+ style.SetInsideNGFragmentationContext(true);
+ }
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/style_adjuster.h b/chromium/third_party/blink/renderer/core/css/resolver/style_adjuster.h
index 247461f2e65..28782fe1963 100644
--- a/chromium/third_party/blink/renderer/core/css/resolver/style_adjuster.h
+++ b/chromium/third_party/blink/renderer/core/css/resolver/style_adjuster.h
@@ -23,7 +23,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_RESOLVER_STYLE_ADJUSTER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_RESOLVER_STYLE_ADJUSTER_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/style_animator.cc b/chromium/third_party/blink/renderer/core/css/resolver/style_animator.cc
new file mode 100644
index 00000000000..c9ebb4db1c5
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/resolver/style_animator.cc
@@ -0,0 +1,78 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/css/resolver/style_animator.h"
+
+#include "third_party/blink/renderer/core/animation/css_interpolation_environment.h"
+#include "third_party/blink/renderer/core/animation/css_interpolation_types_map.h"
+#include "third_party/blink/renderer/core/animation/invalidatable_interpolation.h"
+#include "third_party/blink/renderer/core/animation/transition_interpolation.h"
+#include "third_party/blink/renderer/core/css/css_pending_interpolation_value.h"
+#include "third_party/blink/renderer/core/css/properties/longhands/custom_property.h"
+
+namespace blink {
+
+namespace {
+
+PropertyHandle ToPropertyHandle(
+ const CSSProperty& property,
+ const cssvalue::CSSPendingInterpolationValue& value) {
+ if (IsA<CustomProperty>(property))
+ return PropertyHandle(property.GetPropertyNameAtomicString());
+ return PropertyHandle(property, value.IsPresentationAttribute());
+}
+
+const ActiveInterpolations& GetActiveInterpolations(
+ const ActiveInterpolationsMap& animations_map,
+ const ActiveInterpolationsMap& transitions_map,
+ const PropertyHandle& property) {
+ // Interpolations will never be found in both animations_map and
+ // transitions_map. This condition is ensured by
+ // CSSAnimations::CalculateTransitionUpdateForProperty().
+ const auto& animation = animations_map.find(property);
+ if (animation != animations_map.end()) {
+ DCHECK_EQ(transitions_map.find(property), transitions_map.end());
+ return animation->value;
+ }
+ const auto& transition = transitions_map.find(property);
+ DCHECK_NE(transition, transitions_map.end());
+ return transition->value;
+}
+
+const ActiveInterpolations& GetActiveInterpolations(
+ const CSSAnimationUpdate& update,
+ const PropertyHandle& property) {
+ if (property.IsCSSCustomProperty()) {
+ return GetActiveInterpolations(
+ update.ActiveInterpolationsForCustomAnimations(),
+ update.ActiveInterpolationsForCustomTransitions(), property);
+ }
+ return GetActiveInterpolations(
+ update.ActiveInterpolationsForStandardAnimations(),
+ update.ActiveInterpolationsForStandardTransitions(), property);
+}
+
+} // namespace
+
+StyleAnimator::StyleAnimator(StyleResolverState& state, StyleCascade& cascade)
+ : state_(state), cascade_(cascade) {}
+
+void StyleAnimator::Apply(const CSSProperty& property,
+ const cssvalue::CSSPendingInterpolationValue& value,
+ StyleCascade::Resolver& resolver) {
+ PropertyHandle property_handle = ToPropertyHandle(property, value);
+ const ActiveInterpolations& interpolations =
+ GetActiveInterpolations(state_.AnimationUpdate(), property_handle);
+ const Interpolation& interpolation = *interpolations.front();
+ if (interpolation.IsInvalidatableInterpolation()) {
+ CSSInterpolationTypesMap map(state_.GetDocument().GetPropertyRegistry(),
+ state_.GetDocument());
+ CSSInterpolationEnvironment environment(map, state_, &cascade_, &resolver);
+ InvalidatableInterpolation::ApplyStack(interpolations, environment);
+ } else {
+ ToTransitionInterpolation(interpolation).Apply(state_);
+ }
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/style_animator.h b/chromium/third_party/blink/renderer/core/css/resolver/style_animator.h
new file mode 100644
index 00000000000..5bcbc7f2c41
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/resolver/style_animator.h
@@ -0,0 +1,53 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_RESOLVER_STYLE_ANIMATOR_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_RESOLVER_STYLE_ANIMATOR_H_
+
+#include "third_party/blink/renderer/core/animation/interpolation.h"
+#include "third_party/blink/renderer/core/animation/property_handle.h"
+#include "third_party/blink/renderer/core/css/resolver/style_cascade.h"
+
+namespace blink {
+
+class StyleResolverState;
+class StyleCascade;
+
+namespace cssvalue {
+
+class CSSPendingInterpolationValue;
+
+} // namespace cssvalue
+
+// StyleAnimator is a class which knows how to apply active interpolations
+// for given a CSSProperty.
+//
+// When the set of currently animating properties has been determined,
+// a CSSPendingInterpolationValues is added to the cascade for each animating
+// property (see StyleResolver::CascadeInterpolations). Later, when the
+// cascade is applied, an Animator may be provided. That Animator is then
+// responsible for applying the actual interpolated values represented by
+// any CSSPendingInterpolationValues that may (or may not) remain in the
+// cascade. See StyleCascade::Animator for more information.
+//
+// TODO(crbug.com/985051) Evaluate if there's a performance issue here, and
+// if so possibly store active interpolations directly in the cascade.
+class CORE_EXPORT StyleAnimator : public StyleCascade::Animator {
+ STACK_ALLOCATED();
+
+ public:
+ explicit StyleAnimator(StyleResolverState&, StyleCascade&);
+
+ void Apply(const CSSProperty&,
+ const cssvalue::CSSPendingInterpolationValue&,
+ StyleCascade::Resolver&) override;
+
+ private:
+ StyleResolverState& state_;
+ StyleCascade& cascade_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_RESOLVER_STYLE_ANIMATOR_H_
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 3e174b035aa..744995d74cd 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
@@ -98,14 +98,6 @@ void StyleBuilder::ApplyProperty(const CSSProperty& property,
// isInherit => (state.parentNode() && state.parentStyle())
DCHECK(!is_inherit || (state.ParentNode() && state.ParentStyle()));
- if (!state.ApplyPropertyToRegularStyle() &&
- (!state.ApplyPropertyToVisitedLinkStyle() ||
- !property.IsValidForVisitedLink())) {
- // Limit the properties that can be applied to only the ones honored by
- // :visited.
- return;
- }
-
if (is_inherit && !state.ParentStyle()->HasExplicitlyInheritedProperties() &&
!is_inherited) {
state.ParentStyle()->SetHasExplicitlyInheritedProperties();
@@ -117,11 +109,6 @@ void StyleBuilder::ApplyProperty(const CSSProperty& property,
is_initial = true;
}
- // CSSPropertyID::kVariable currently handles initial/inherit inside
- // ApplyValue.
- DCHECK(id != CSSPropertyID::kVariable || !is_initial);
- DCHECK(id != CSSPropertyID::kVariable || !is_inherit);
-
if (is_initial)
To<Longhand>(property).ApplyInitial(state);
else if (is_inherit)
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 d0cd0e1afa8..630ecc7bcf5 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
@@ -41,6 +41,9 @@
#include "third_party/blink/renderer/core/css/css_font_variation_value.h"
#include "third_party/blink/renderer/core/css/css_grid_auto_repeat_value.h"
#include "third_party/blink/renderer/core/css/css_grid_integer_repeat_value.h"
+#include "third_party/blink/renderer/core/css/css_math_expression_node.h"
+#include "third_party/blink/renderer/core/css/css_math_function_value.h"
+#include "third_party/blink/renderer/core/css/css_numeric_literal_value.h"
#include "third_party/blink/renderer/core/css/css_path_value.h"
#include "third_party/blink/renderer/core/css/css_primitive_value_mappings.h"
#include "third_party/blink/renderer/core/css/css_quad_value.h"
@@ -53,11 +56,11 @@
#include "third_party/blink/renderer/core/css/resolver/transform_builder.h"
#include "third_party/blink/renderer/core/css/style_engine.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/style/computed_style.h"
#include "third_party/blink/renderer/core/style/reference_clip_path_operation.h"
#include "third_party/blink/renderer/core/style/shape_clip_path_operation.h"
#include "third_party/blink/renderer/core/style/style_svg_resource.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
@@ -299,10 +302,11 @@ static float ComputeFontSize(const CSSToLengthConversionData& conversion_data,
const FontDescription::Size& parent_size) {
if (primitive_value.IsLength())
return primitive_value.ComputeLength<float>(conversion_data);
- if (primitive_value.IsCalculatedPercentageWithLength())
- return primitive_value.CssCalcValue()
- ->ToCalcValue(conversion_data)
+ if (primitive_value.IsCalculatedPercentageWithLength()) {
+ return To<CSSMathFunctionValue>(primitive_value)
+ .ToCalcValue(conversion_data)
->Evaluate(parent_size.value);
+ }
NOTREACHED();
return 0;
@@ -1007,6 +1011,28 @@ UnzoomedLength StyleBuilderConverter::ConvertUnzoomedLength(
state.UnzoomedLengthConversionData()));
}
+float StyleBuilderConverter::ConvertZoom(const StyleResolverState& state,
+ const CSSValue& value) {
+ SECURITY_DCHECK(value.IsPrimitiveValue() || value.IsIdentifierValue());
+
+ if (const auto* identifier_value = DynamicTo<CSSIdentifierValue>(value)) {
+ if (identifier_value->GetValueID() == CSSValueID::kNormal)
+ return ComputedStyleInitialValues::InitialZoom();
+ } else if (const auto* primitive_value =
+ DynamicTo<CSSPrimitiveValue>(value)) {
+ if (primitive_value->IsPercentage()) {
+ float percent = primitive_value->GetFloatValue();
+ return percent ? (percent / 100.0f) : 1.0f;
+ } else if (primitive_value->IsNumber()) {
+ float number = primitive_value->GetFloatValue();
+ return number ? number : 1.0f;
+ }
+ }
+
+ NOTREACHED();
+ return 1.0f;
+}
+
Length StyleBuilderConverter::ConvertLengthOrAuto(
const StyleResolverState& state,
const CSSValue& value) {
@@ -1056,9 +1082,10 @@ TabSize StyleBuilderConverter::ConvertLengthOrTabSpaces(
const CSSValue& value) {
const auto& primitive_value = To<CSSPrimitiveValue>(value);
if (primitive_value.IsNumber())
- return TabSize(primitive_value.GetIntValue());
+ return TabSize(primitive_value.GetFloatValue(), TabSizeValueType::kSpace);
return TabSize(
- primitive_value.ComputeLength<float>(state.CssToLengthConversionData()));
+ primitive_value.ComputeLength<float>(state.CssToLengthConversionData()),
+ TabSizeValueType::kLength);
}
static CSSToLengthConversionData LineHeightToLengthConversionData(
@@ -1087,8 +1114,8 @@ Length StyleBuilderConverter::ConvertLineHeight(StyleResolverState& state,
}
if (primitive_value->IsCalculated()) {
Length zoomed_length =
- Length(primitive_value->CssCalcValue()->ToCalcValue(
- LineHeightToLengthConversionData(state)));
+ Length(To<CSSMathFunctionValue>(primitive_value)
+ ->ToCalcValue(LineHeightToLengthConversionData(state)));
return Length::Fixed(ValueForLength(
zoomed_length, LayoutUnit(state.Style()->ComputedFontSize())));
}
@@ -1206,8 +1233,8 @@ Length StyleBuilderConverter::ConvertQuirkyLength(StyleResolverState& state,
const CSSValue& value) {
Length length = ConvertLengthOrAuto(state, value);
// This is only for margins which use __qem
- auto* primitive_value = DynamicTo<CSSPrimitiveValue>(value);
- length.SetQuirk(primitive_value && primitive_value->IsQuirkyEms());
+ auto* numeric_literal = DynamicTo<CSSNumericLiteralValue>(value);
+ length.SetQuirk(numeric_literal && numeric_literal->IsQuirkyEms());
return length;
}
@@ -1442,8 +1469,8 @@ float StyleBuilderConverter::ConvertTextStrokeWidth(StyleResolverState& state,
auto* identifier_value = DynamicTo<CSSIdentifierValue>(value);
if (identifier_value && IsValidCSSValueID(identifier_value->GetValueID())) {
float multiplier = ConvertLineWidth<float>(state, value);
- return CSSPrimitiveValue::Create(multiplier / 48,
- CSSPrimitiveValue::UnitType::kEms)
+ return CSSNumericLiteralValue::Create(multiplier / 48,
+ CSSPrimitiveValue::UnitType::kEms)
->ComputeLength<float>(state.CssToLengthConversionData());
}
return To<CSSPrimitiveValue>(value).ComputeLength<float>(
@@ -1703,7 +1730,7 @@ static const CSSValue& ComputeRegisteredPropertyValue(
// Instead of the actual zoom, use 1 to avoid potential rounding errors
Length length = primitive_value->ConvertToLength(
css_to_length_conversion_data.CopyWithAdjustedZoom(1));
- return *CSSPrimitiveValue::Create(length, 1);
+ return *CSSPrimitiveValue::CreateFromLength(length, 1);
}
// If we encounter a calculated number that was not resolved during
@@ -1711,26 +1738,31 @@ static const CSSValue& ComputeRegisteredPropertyValue(
// 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->IsCalculated()) {
+ const CSSMathFunctionValue& math_value =
+ To<CSSMathFunctionValue>(*primitive_value);
+ if (math_value.IsNumber()) {
+ double double_value = math_value.GetDoubleValue();
+ auto unit_type = CSSPrimitiveValue::UnitType::kInteger;
+ return *CSSNumericLiteralValue::Create(std::round(double_value),
+ unit_type);
+ }
}
if (primitive_value->IsAngle()) {
- return *CSSPrimitiveValue::Create(primitive_value->ComputeDegrees(),
- CSSPrimitiveValue::UnitType::kDegrees);
+ return *CSSNumericLiteralValue::Create(
+ primitive_value->ComputeDegrees(),
+ CSSPrimitiveValue::UnitType::kDegrees);
}
if (primitive_value->IsTime()) {
- return *CSSPrimitiveValue::Create(primitive_value->ComputeSeconds(),
- CSSPrimitiveValue::UnitType::kSeconds);
+ return *CSSNumericLiteralValue::Create(
+ primitive_value->ComputeSeconds(),
+ CSSPrimitiveValue::UnitType::kSeconds);
}
if (primitive_value->IsResolution()) {
- return *CSSPrimitiveValue::Create(
+ return *CSSNumericLiteralValue::Create(
primitive_value->ComputeDotsPerPixel(),
CSSPrimitiveValue::UnitType::kDotsPerPixel);
}
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 1a6fe32c9f5..d1fe1b50cee 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
@@ -51,7 +51,7 @@
#include "third_party/blink/renderer/platform/graphics/image_orientation.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"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/text_encoding.h"
namespace blink {
@@ -164,6 +164,7 @@ class StyleBuilderConverter {
static Length ConvertLength(const StyleResolverState&, const CSSValue&);
static UnzoomedLength ConvertUnzoomedLength(const StyleResolverState&,
const CSSValue&);
+ static float ConvertZoom(const StyleResolverState&, const CSSValue&);
static Length ConvertLengthOrAuto(const StyleResolverState&, const CSSValue&);
static Length ConvertLengthSizing(StyleResolverState&, const CSSValue&);
static Length ConvertLengthMaxSizing(StyleResolverState&, const CSSValue&);
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/style_cascade.cc b/chromium/third_party/blink/renderer/core/css/resolver/style_cascade.cc
new file mode 100644
index 00000000000..e3810cc1a42
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/resolver/style_cascade.cc
@@ -0,0 +1,648 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/css/resolver/style_cascade.h"
+
+#include "third_party/blink/renderer/core/animation/css/css_animations.h"
+#include "third_party/blink/renderer/core/animation/css_interpolation_environment.h"
+#include "third_party/blink/renderer/core/animation/css_interpolation_types_map.h"
+#include "third_party/blink/renderer/core/animation/invalidatable_interpolation.h"
+#include "third_party/blink/renderer/core/animation/property_handle.h"
+#include "third_party/blink/renderer/core/animation/transition_interpolation.h"
+#include "third_party/blink/renderer/core/css/css_custom_property_declaration.h"
+#include "third_party/blink/renderer/core/css/css_font_selector.h"
+#include "third_party/blink/renderer/core/css/css_invalid_variable_value.h"
+#include "third_party/blink/renderer/core/css/css_pending_interpolation_value.h"
+#include "third_party/blink/renderer/core/css/css_pending_substitution_value.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"
+#include "third_party/blink/renderer/core/css/document_style_environment_variables.h"
+#include "third_party/blink/renderer/core/css/parser/css_parser_local_context.h"
+#include "third_party/blink/renderer/core/css/parser/css_property_parser.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/property_registry.h"
+#include "third_party/blink/renderer/core/css/resolver/css_property_priority.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/style_engine.h"
+#include "third_party/blink/renderer/core/dom/shadow_root.h"
+#include "third_party/blink/renderer/core/style/computed_style.h"
+
+namespace blink {
+
+using namespace cssvalue;
+
+namespace {
+
+class NullAnimator : public StyleCascade::Animator {
+ STACK_ALLOCATED();
+
+ public:
+ void Apply(const CSSProperty&,
+ const cssvalue::CSSPendingInterpolationValue&,
+ StyleCascade::Resolver&) override {}
+};
+
+AtomicString ConsumeVariableName(CSSParserTokenRange& range) {
+ range.ConsumeWhitespace();
+ CSSParserToken ident_token = range.ConsumeIncludingWhitespace();
+ DCHECK_EQ(ident_token.GetType(), kIdentToken);
+ return ident_token.Value().ToAtomicString();
+}
+
+bool ConsumeComma(CSSParserTokenRange& range) {
+ if (range.Peek().GetType() == kCommaToken) {
+ range.Consume();
+ return true;
+ }
+ return false;
+}
+
+const CSSValue* Parse(const CSSProperty& property,
+ CSSParserTokenRange range,
+ const CSSParserContext* context) {
+ return CSSPropertyParser::ParseSingleValue(property.PropertyID(), range,
+ context);
+}
+
+constexpr bool IsImportant(StyleCascade::Origin origin) {
+ return static_cast<uint8_t>(origin) & StyleCascade::kImportantBit;
+}
+
+static_assert(!IsImportant(StyleCascade::Origin::kNone),
+ "Origin::kNone is not important");
+static_assert(!IsImportant(StyleCascade::Origin::kUserAgent),
+ "Origin::kUserAgent is not important");
+static_assert(!IsImportant(StyleCascade::Origin::kUser),
+ "Origin::kUser is not important");
+static_assert(!IsImportant(StyleCascade::Origin::kAnimation),
+ "Origin::kAnimation is not important");
+static_assert(IsImportant(StyleCascade::Origin::kImportantAuthor),
+ "Origin::kImportantAuthor is important");
+static_assert(IsImportant(StyleCascade::Origin::kImportantUser),
+ "Origin::kImportantUser is important");
+static_assert(IsImportant(StyleCascade::Origin::kImportantUserAgent),
+ "Origin::kImportantUserAgent is important");
+static_assert(!IsImportant(StyleCascade::Origin::kTransition),
+ "Origin::kTransition is not important");
+
+} // namespace
+
+StyleCascade::Priority::Priority(Origin origin, uint16_t tree_order)
+ : priority_((static_cast<uint64_t>(origin) << 32) |
+ (static_cast<uint64_t>(tree_order) << 16) |
+ StyleCascade::kMaxCascadeOrder) {}
+
+StyleCascade::Origin StyleCascade::Priority::GetOrigin() const {
+ return static_cast<StyleCascade::Origin>((priority_ >> 32) & 0xFF);
+}
+
+bool StyleCascade::Priority::operator>=(const Priority& other) const {
+ uint64_t important_xor = IsImportant(GetOrigin()) ? 0 : (0xFF << 16);
+ return (priority_ ^ important_xor) >= (other.priority_ ^ important_xor);
+}
+
+void StyleCascade::Add(const CSSPropertyName& name,
+ const CSSValue* value,
+ Priority priority) {
+ auto result = cascade_.insert(name, Value());
+ if (priority >= result.stored_value->value.GetPriority()) {
+ result.stored_value->value =
+ Value(value, priority.WithCascadeOrder(++order_));
+ }
+}
+
+void StyleCascade::Apply() {
+ NullAnimator animator;
+ Apply(animator);
+}
+
+void StyleCascade::Apply(Animator& animator) {
+ Resolver resolver(animator);
+
+ // TODO(crbug.com/985031): Set bits ::Add-time to know if we need to do this.
+ ApplyHighPriority(resolver);
+
+ // TODO(crbug.com/985010): Improve with non-destructive Apply.
+ while (!cascade_.IsEmpty()) {
+ auto iter = cascade_.begin();
+ const CSSPropertyName& name = iter->key;
+ Apply(name, resolver);
+ }
+}
+
+void StyleCascade::RemoveAnimationPriority() {
+ using AnimPrio = CSSPropertyPriorityData<kAnimationPropertyPriority>;
+ int first = static_cast<int>(AnimPrio::First());
+ int last = static_cast<int>(AnimPrio::Last());
+ for (int i = first; i <= last; ++i) {
+ CSSPropertyName name(convertToCSSPropertyID(i));
+ cascade_.erase(name);
+ }
+}
+
+const CSSValue* StyleCascade::Resolve(const CSSPropertyName& name,
+ const CSSValue& value,
+ Resolver& resolver) {
+ CSSPropertyRef ref(name, state_.GetDocument());
+
+ const CSSValue* resolved = Resolve(ref.GetProperty(), value, resolver);
+
+ DCHECK(resolved);
+
+ if (resolved->IsInvalidVariableValue())
+ return nullptr;
+
+ return resolved;
+}
+
+void StyleCascade::ApplyHighPriority(Resolver& resolver) {
+ using HighPriority = CSSPropertyPriorityData<kHighPropertyPriority>;
+ int first = static_cast<int>(HighPriority::First());
+ int last = static_cast<int>(HighPriority::Last());
+ for (int i = first; i <= last; ++i)
+ Apply(CSSProperty::Get(convertToCSSPropertyID(i)), resolver);
+
+ state_.GetFontBuilder().CreateFont(
+ state_.GetDocument().GetStyleEngine().GetFontSelector(),
+ state_.StyleRef());
+ state_.SetConversionFontSizes(CSSToLengthConversionData::FontSizes(
+ state_.Style(), state_.RootElementStyle()));
+ state_.SetConversionZoom(state_.Style()->EffectiveZoom());
+}
+
+void StyleCascade::Apply(const CSSPropertyName& name) {
+ NullAnimator animator;
+ Resolver resolver(animator);
+ Apply(name, resolver);
+}
+
+void StyleCascade::Apply(const CSSPropertyName& name, Resolver& resolver) {
+ CSSPropertyRef ref(name, state_.GetDocument());
+ DCHECK(ref.IsValid());
+ Apply(ref.GetProperty(), resolver);
+}
+
+void StyleCascade::Apply(const CSSProperty& property, Resolver& resolver) {
+ CSSPropertyName name = property.GetCSSPropertyName();
+
+ DCHECK(!resolver.IsLocked(name));
+
+ Value cascaded = cascade_.Take(property.GetCSSPropertyName());
+ if (cascaded.IsEmpty())
+ return;
+
+ const CSSValue* value = cascaded.GetValue();
+
+ if (const auto* v = DynamicTo<CSSPendingInterpolationValue>(value)) {
+ resolver.animator_.Apply(property, *v, resolver);
+ return;
+ }
+
+ value = Resolve(property, *value, resolver);
+
+ DCHECK(!value->IsVariableReferenceValue());
+ DCHECK(!value->IsPendingSubstitutionValue());
+ DCHECK(!value->IsPendingInterpolationValue());
+
+ if (!resolver.filter_.Add(property, cascaded))
+ return;
+
+ StyleBuilder::ApplyProperty(property, state_, *value);
+}
+
+bool StyleCascade::HasValue(const CSSPropertyName& name,
+ const CSSValue* value) const {
+ auto iter = cascade_.find(name);
+ return (iter != cascade_.end()) && (iter->value.GetValue() == value);
+}
+
+const CSSValue* StyleCascade::GetValue(const CSSPropertyName& name) const {
+ auto iter = cascade_.find(name);
+ return (iter != cascade_.end()) ? iter->value.GetValue() : nullptr;
+}
+
+void StyleCascade::ReplaceValue(const CSSPropertyName& name,
+ const CSSValue* value) {
+ auto iter = cascade_.find(name);
+ if (iter != cascade_.end())
+ iter->value = Value(value, iter->value.GetPriority());
+}
+
+bool StyleCascade::IsRootElement() const {
+ return &state_.GetElement() == state_.GetDocument().documentElement();
+}
+
+StyleCascade::TokenSequence::TokenSequence(const CSSVariableData* data)
+ : backing_strings_(data->BackingStrings()),
+ is_animation_tainted_(data->IsAnimationTainted()),
+ has_font_units_(data->HasFontUnits()),
+ has_root_font_units_(data->HasRootFontUnits()),
+ base_url_(data->BaseURL()),
+ charset_(data->Charset()) {}
+
+void StyleCascade::TokenSequence::Append(const TokenSequence& sequence) {
+ tokens_.AppendVector(sequence.tokens_);
+ backing_strings_.AppendVector(sequence.backing_strings_);
+ is_animation_tainted_ |= sequence.is_animation_tainted_;
+ has_font_units_ |= sequence.has_font_units_;
+ has_root_font_units_ |= sequence.has_root_font_units_;
+}
+
+void StyleCascade::TokenSequence::Append(const CSSVariableData* data) {
+ tokens_.AppendVector(data->Tokens());
+ backing_strings_.AppendVector(data->BackingStrings());
+ is_animation_tainted_ |= data->IsAnimationTainted();
+ has_font_units_ |= data->HasFontUnits();
+ has_root_font_units_ |= data->HasRootFontUnits();
+}
+
+void StyleCascade::TokenSequence::Append(const CSSParserToken& token) {
+ tokens_.push_back(token);
+}
+
+scoped_refptr<CSSVariableData>
+StyleCascade::TokenSequence::BuildVariableData() {
+ // TODO(andruud): Why not also std::move tokens?
+ const bool absolutized = true;
+ return CSSVariableData::CreateResolved(
+ tokens_, std::move(backing_strings_), is_animation_tainted_,
+ has_font_units_, has_root_font_units_, absolutized, base_url_, charset_);
+}
+
+const CSSValue* StyleCascade::Resolve(const CSSProperty& property,
+ const CSSValue& value,
+ Resolver& resolver) {
+ if (const auto* v = DynamicTo<CSSCustomPropertyDeclaration>(value))
+ return ResolveCustomProperty(property, *v, resolver);
+ if (const auto* v = DynamicTo<CSSVariableReferenceValue>(value))
+ return ResolveVariableReference(property, *v, resolver);
+ if (const auto* v = DynamicTo<CSSPendingSubstitutionValue>(value))
+ return ResolvePendingSubstitution(property, *v, resolver);
+ return &value;
+}
+
+const CSSValue* StyleCascade::ResolveCustomProperty(
+ const CSSProperty& property,
+ const CSSCustomPropertyDeclaration& decl,
+ Resolver& resolver) {
+ DCHECK(!resolver.IsLocked(property));
+ AutoLock lock(property, resolver);
+
+ // TODO(andruud): Don't transport css-wide keywords in this value.
+ if (!decl.Value())
+ return &decl;
+
+ scoped_refptr<CSSVariableData> data = decl.Value();
+
+ if (data->NeedsVariableResolution())
+ data = ResolveVariableData(data.get(), resolver);
+
+ if (HasFontSizeDependency(To<CustomProperty>(property), data.get()))
+ resolver.DetectCycle(GetCSSPropertyFontSize());
+
+ if (resolver.InCycle())
+ return CSSInvalidVariableValue::Create();
+
+ if (!data) {
+ // TODO(crbug.com/980930): Treat custom properties as unset here,
+ // not invalid. This behavior is enforced by WPT, but violates the spec.
+ if (const auto* custom_property = DynamicTo<CustomProperty>(property)) {
+ if (!custom_property->IsRegistered())
+ return CSSInvalidVariableValue::Create();
+ }
+ return CSSUnsetValue::Create();
+ }
+
+ if (data == decl.Value())
+ return &decl;
+
+ return MakeGarbageCollected<CSSCustomPropertyDeclaration>(decl.GetName(),
+ data);
+}
+
+const CSSValue* StyleCascade::ResolveVariableReference(
+ const CSSProperty& property,
+ const CSSVariableReferenceValue& value,
+ Resolver& resolver) {
+ DCHECK(!resolver.IsLocked(property));
+ AutoLock lock(property, resolver);
+
+ const CSSVariableData* data = value.VariableDataValue();
+ const CSSParserContext* context = GetParserContext(value);
+
+ DCHECK(data);
+ DCHECK(context);
+
+ TokenSequence sequence;
+
+ if (ResolveTokensInto(data->Tokens(), resolver, sequence)) {
+ if (const auto* parsed = Parse(property, sequence.TokenRange(), context))
+ return parsed;
+ }
+
+ return CSSUnsetValue::Create();
+}
+
+const CSSValue* StyleCascade::ResolvePendingSubstitution(
+ const CSSProperty& property,
+ const CSSPendingSubstitutionValue& value,
+ Resolver& resolver) {
+ DCHECK(!resolver.IsLocked(property));
+ AutoLock lock(property, resolver);
+
+ DCHECK_NE(property.PropertyID(), CSSPropertyID::kVariable);
+
+ CSSVariableReferenceValue* shorthand_value = value.ShorthandValue();
+ const auto* shorthand_data = shorthand_value->VariableDataValue();
+ CSSPropertyID shorthand_property_id = value.ShorthandPropertyId();
+
+ TokenSequence sequence;
+
+ if (!ResolveTokensInto(shorthand_data->Tokens(), resolver, sequence))
+ return CSSUnsetValue::Create();
+
+ HeapVector<CSSPropertyValue, 256> parsed_properties;
+ const bool important = false;
+
+ if (!CSSPropertyParser::ParseValue(
+ shorthand_property_id, important, sequence.TokenRange(),
+ shorthand_value->ParserContext(), parsed_properties,
+ StyleRule::RuleType::kStyle)) {
+ return CSSUnsetValue::Create();
+ }
+
+ // For -internal-visited-properties with CSSPendingSubstitutionValues,
+ // the inner 'shorthand_property_id' will expand to a set of longhands
+ // containing the unvisited equivalent. Hence, when parsing the
+ // CSSPendingSubstitutionValue, we look for the unvisited property in
+ // parsed_properties.
+ const CSSProperty* unvisited_property =
+ property.IsVisited() ? property.GetUnvisitedProperty() : &property;
+
+ const CSSValue* result = nullptr;
+
+ unsigned parsed_properties_count = parsed_properties.size();
+ for (unsigned i = 0; i < parsed_properties_count; ++i) {
+ const CSSProperty& longhand = CSSProperty::Get(parsed_properties[i].Id());
+ const CSSPropertyName& name = longhand.GetCSSPropertyName();
+ const CSSValue* parsed = parsed_properties[i].Value();
+
+ if (unvisited_property == &longhand)
+ result = parsed;
+ else if (HasValue(name, &value))
+ ReplaceValue(name, parsed);
+ }
+
+ DCHECK(result);
+ return result;
+}
+
+scoped_refptr<CSSVariableData> StyleCascade::ResolveVariableData(
+ CSSVariableData* data,
+ Resolver& resolver) {
+ DCHECK(data && data->NeedsVariableResolution());
+
+ TokenSequence sequence(data);
+
+ if (!ResolveTokensInto(data->Tokens(), resolver, sequence))
+ return nullptr;
+
+ return sequence.BuildVariableData();
+}
+
+bool StyleCascade::ResolveTokensInto(CSSParserTokenRange range,
+ Resolver& resolver,
+ TokenSequence& out) {
+ bool success = true;
+ while (!range.AtEnd()) {
+ const CSSParserToken& token = range.Peek();
+ if (token.FunctionId() == CSSValueID::kVar)
+ success &= ResolveVarInto(range.ConsumeBlock(), resolver, out);
+ else if (token.FunctionId() == CSSValueID::kEnv)
+ success &= ResolveEnvInto(range.ConsumeBlock(), resolver, out);
+ else
+ out.Append(range.Consume());
+ }
+ return success;
+}
+
+bool StyleCascade::ResolveVarInto(CSSParserTokenRange range,
+ Resolver& resolver,
+ TokenSequence& out) {
+ AtomicString variable_name = ConsumeVariableName(range);
+ DCHECK(range.AtEnd() || (range.Peek().GetType() == kCommaToken));
+
+ CustomProperty property(variable_name, state_.GetDocument());
+
+ // Any custom property referenced (by anything, even just once) in the
+ // document can currently not be animated on the compositor. Hence we mark
+ // properties that have been referenced.
+ MarkReferenced(property);
+
+ if (!resolver.DetectCycle(property)) {
+ // We are about to substitute var(property). In order to do that, we must
+ // know the computed value of 'property', hence we Apply it.
+ //
+ // We can however not do this if we're in a cycle. If a cycle is detected
+ // here, it means we are already resolving 'property', and have discovered
+ // a reference to 'property' during that resolution.
+ Apply(property, resolver);
+ }
+
+ // Note that even if we are in a cycle, we must proceed in order to discover
+ // secondary cycles via the var() fallback.
+
+ scoped_refptr<CSSVariableData> data = GetVariableData(property);
+
+ // If substitution is not allowed, treat the value as
+ // invalid-at-computed-value-time.
+ //
+ // https://drafts.csswg.org/css-variables/#animation-tainted
+ if (!resolver.AllowSubstitution(data.get()))
+ data = nullptr;
+
+ // If we have a fallback, we must process it to look for cycles,
+ // even if we aren't going to use the fallback.
+ //
+ // https://drafts.csswg.org/css-variables/#cycles
+ if (ConsumeComma(range)) {
+ TokenSequence fallback;
+ bool success = ResolveTokensInto(range, resolver, fallback);
+ // The fallback must match the syntax of the referenced custom property.
+ // https://drafts.css-houdini.org/css-properties-values-api-1/#fallbacks-in-var-references
+ if (!ValidateFallback(property, fallback.TokenRange()))
+ return false;
+ if (!data && success)
+ data = fallback.BuildVariableData();
+ }
+
+ if (!data || resolver.InCycle())
+ return false;
+
+ // https://drafts.csswg.org/css-variables/#long-variables
+ if (data->Tokens().size() > kMaxSubstitutionTokens)
+ return false;
+
+ out.Append(data.get());
+
+ return true;
+}
+
+bool StyleCascade::ResolveEnvInto(CSSParserTokenRange range,
+ Resolver& resolver,
+ TokenSequence& out) {
+ AtomicString variable_name = ConsumeVariableName(range);
+ DCHECK(range.AtEnd() || (range.Peek().GetType() == kCommaToken));
+
+ CSSVariableData* data = GetEnvironmentVariable(variable_name);
+
+ if (!data) {
+ if (ConsumeComma(range))
+ return ResolveTokensInto(range, resolver, out);
+ return false;
+ }
+
+ out.Append(data);
+
+ return true;
+}
+
+CSSVariableData* StyleCascade::GetVariableData(
+ const CustomProperty& property) const {
+ const AtomicString& name = property.GetPropertyNameAtomicString();
+ const bool is_inherited = property.IsInherited();
+ return state_.StyleRef().GetVariableData(name, is_inherited);
+}
+
+CSSVariableData* StyleCascade::GetEnvironmentVariable(
+ const AtomicString& name) const {
+ // If we are in a User Agent Shadow DOM then we should not record metrics.
+ ContainerNode& scope_root = state_.GetTreeScope().RootNode();
+ auto* shadow_root = DynamicTo<ShadowRoot>(&scope_root);
+ bool is_ua_scope = shadow_root && shadow_root->IsUserAgent();
+
+ return state_.GetDocument()
+ .GetStyleEngine()
+ .EnsureEnvironmentVariables()
+ .ResolveVariable(name, !is_ua_scope);
+}
+
+const CSSParserContext* StyleCascade::GetParserContext(
+ const CSSVariableReferenceValue& value) {
+ // TODO(crbug.com/985028): CSSVariableReferenceValue should always have a
+ // CSSParserContext. (CSSUnparsedValue violates this).
+ if (value.ParserContext())
+ return value.ParserContext();
+ return StrictCSSParserContext(state_.GetDocument().GetSecureContextMode());
+}
+
+bool StyleCascade::HasFontSizeDependency(const CustomProperty& property,
+ CSSVariableData* data) const {
+ if (!property.IsRegistered() || !data)
+ return false;
+ if (data->HasFontUnits())
+ return true;
+ if (data->HasRootFontUnits() && IsRootElement())
+ return true;
+ return false;
+}
+
+bool StyleCascade::ValidateFallback(const CustomProperty& property,
+ CSSParserTokenRange range) const {
+ if (!property.IsRegistered())
+ return true;
+ auto context_mode = state_.GetDocument().GetSecureContextMode();
+ auto var_mode = CSSParserLocalContext::VariableMode::kTyped;
+ auto* context = StrictCSSParserContext(context_mode);
+ auto local_context = CSSParserLocalContext().WithVariableMode(var_mode);
+ return property.ParseSingleValue(range, *context, local_context);
+}
+
+void StyleCascade::MarkReferenced(const CustomProperty& property) {
+ if (!property.IsInherited())
+ state_.Style()->SetHasVariableReferenceFromNonInheritedProperty();
+ if (!property.IsRegistered())
+ return;
+ const AtomicString& name = property.GetPropertyNameAtomicString();
+ state_.GetDocument().GetPropertyRegistry()->MarkReferenced(name);
+}
+
+bool StyleCascade::Filter::Add(const CSSProperty& property,
+ const Value& value) {
+ Priority& slot = GetSlot(property);
+ if (value.GetPriority() >= slot) {
+ slot = value.GetPriority();
+ return true;
+ }
+ return false;
+}
+
+StyleCascade::Priority& StyleCascade::Filter::GetSlot(
+ const CSSProperty& property) {
+ // TODO(crbug.com/985043): Ribbonize?
+ switch (property.PropertyID()) {
+ case CSSPropertyID::kWritingMode:
+ case CSSPropertyID::kWebkitWritingMode:
+ return writing_mode_;
+ case CSSPropertyID::kZoom:
+ case CSSPropertyID::kInternalEffectiveZoom:
+ return zoom_;
+ default:
+ none_ = Priority();
+ return none_;
+ }
+}
+
+bool StyleCascade::Resolver::IsLocked(const CSSProperty& property) const {
+ return IsLocked(property.GetCSSPropertyName());
+}
+
+bool StyleCascade::Resolver::IsLocked(const CSSPropertyName& name) const {
+ return stack_.Contains(name);
+}
+
+bool StyleCascade::Resolver::AllowSubstitution(CSSVariableData* data) const {
+ if (data && data->IsAnimationTainted() && stack_.size()) {
+ const CSSPropertyName& name = stack_.back();
+ if (name.IsCustomProperty())
+ return true;
+ const CSSProperty& property = CSSProperty::Get(name.Id());
+ return !CSSAnimations::IsAnimationAffectingProperty(property);
+ }
+ return true;
+}
+
+bool StyleCascade::Resolver::DetectCycle(const CSSProperty& property) {
+ wtf_size_t index = stack_.Find(property.GetCSSPropertyName());
+ if (index == kNotFound)
+ return false;
+ cycle_depth_ = std::min(cycle_depth_, index);
+ return true;
+}
+
+bool StyleCascade::Resolver::InCycle() const {
+ return cycle_depth_ != kNotFound;
+}
+
+StyleCascade::AutoLock::AutoLock(const CSSProperty& property,
+ Resolver& resolver)
+ : AutoLock(property.GetCSSPropertyName(), resolver) {}
+
+StyleCascade::AutoLock::AutoLock(const CSSPropertyName& name,
+ Resolver& resolver)
+ : resolver_(resolver) {
+ DCHECK(!resolver.IsLocked(name));
+ resolver_.stack_.push_back(name);
+}
+
+StyleCascade::AutoLock::~AutoLock() {
+ resolver_.stack_.pop_back();
+ if (resolver_.stack_.size() <= resolver_.cycle_depth_)
+ resolver_.cycle_depth_ = kNotFound;
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/style_cascade.h b/chromium/third_party/blink/renderer/core/css/resolver/style_cascade.h
new file mode 100644
index 00000000000..d6cbce28d14
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/resolver/style_cascade.h
@@ -0,0 +1,508 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_RESOLVER_STYLE_CASCADE_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_RESOLVER_STYLE_CASCADE_H_
+
+#include "third_party/blink/renderer/core/css/css_property_name.h"
+#include "third_party/blink/renderer/core/css/parser/css_parser_token.h"
+#include "third_party/blink/renderer/core/css/parser/css_parser_token_range.h"
+#include "third_party/blink/renderer/platform/heap/handle.h"
+#include "third_party/blink/renderer/platform/wtf/text/text_encoding.h"
+#include "third_party/blink/renderer/platform/wtf/vector.h"
+
+namespace blink {
+
+class CSSCustomPropertyDeclaration;
+class CSSParserContext;
+class CSSProperty;
+class CSSValue;
+class CSSVariableData;
+class CSSVariableReferenceValue;
+class CustomProperty;
+class StyleResolverState;
+
+namespace cssvalue {
+
+class CSSPendingSubstitutionValue;
+class CSSPendingInterpolationValue;
+
+} // namespace cssvalue
+
+// The StyleCascade is responsible for managing cascaded values [1], resolving
+// dependencies between them, and applying the values to the ComputedStyle.
+//
+// Its usage pattern is:
+//
+// const CSSPropertyName& name = ...;
+// const CSSValue* value1 = ...;
+// const CSSValue* value2 = ...;
+//
+// StyleCascade cascade(state);
+// cascade.Add(name, value1, Priority(Origin::kAuthor));
+// cascade.Add(name, value2, Priority(Origin::kUA));
+// cascade.Apply(); // value1 is applied, value2 is ignored.
+//
+// [1] https://drafts.csswg.org/css-cascade/#cascade
+class CORE_EXPORT StyleCascade {
+ STACK_ALLOCATED();
+
+ using CSSPendingSubstitutionValue = cssvalue::CSSPendingSubstitutionValue;
+ using CSSPendingInterpolationValue = cssvalue::CSSPendingInterpolationValue;
+
+ public:
+ class Animator;
+ class Resolver;
+ class AutoLock;
+
+ StyleCascade(StyleResolverState& state) : state_(state) {}
+
+ static constexpr uint16_t kMaxCascadeOrder = ~static_cast<uint16_t>(0);
+
+ // Represents the origin and importance criteria described by css-cascade [1].
+ //
+ // Higher values are more significant than lower values. The values are
+ // chosen such that an important origin can be produced by inverting the bits
+ // of the corresponding non-important origin.
+ //
+ // [1] https://www.w3.org/TR/css-cascade-3/#cascade-origin
+ enum class Origin : uint8_t {
+ kNone = 0,
+ kUserAgent = 0b0001,
+ kUser = 0b0010,
+ kAuthor = 0b0011,
+ kAnimation = 0b0100,
+ kImportantAuthor = 0b1100,
+ kImportantUser = 0b1101,
+ kImportantUserAgent = 0b1110,
+ kTransition = 0b10000,
+ };
+
+ // All important Origins (and only those) must have this bit set. This
+ // provides a fast way to check if an Origin is important.
+ static constexpr uint8_t kImportantBit = 0b1000;
+
+ // The Priority class encapsulates a subset of the cascading criteria
+ // described by css-cascade [1], and provides a way to compare priorities.
+ //
+ // It encompasses, from most significant to least significant: Origin (which
+ // includes importance); tree order, which is a number representing the
+ // shadow-including tree order [2]; and finally cascade order, which is
+ // a monotonically increasing number increased by one every time something
+ // is added to the cascade.
+ //
+ // The cascade order is initially kMaxCascadeOrder for an instance of
+ // Priority; an actual value will be assigned by StyleCascade::Add.
+ //
+ // [1] https://drafts.csswg.org/css-cascade/#cascading
+ // [2] https://drafts.csswg.org/css-scoping/#shadow-cascading
+ class CORE_EXPORT Priority {
+ DISALLOW_NEW();
+
+ public:
+ Priority() : Priority(Origin::kNone) {}
+ // Deliberately implicit.
+ Priority(Origin origin) : Priority(origin, 0) {}
+ // For an explanation of 'tree_order', see css-scoping [1].
+ // [1] https://drafts.csswg.org/css-scoping/#shadow-cascading
+ Priority(Origin, uint16_t tree_order);
+
+ Origin GetOrigin() const;
+ bool HasOrigin() const { return GetOrigin() != Origin::kNone; }
+
+ // This function is used to determine if an incoming Value should win
+ // over the Value which already exists in the cascade.
+ bool operator>=(const Priority&) const;
+
+ // Returns a copy of this Priority, except that the non-important origin
+ // has been converted to its important counterpart.
+ //
+ // Must be used with kUserAgent, kAuthor, and kAuthor only, as importance
+ // does not apply to the other origins.
+ //
+ // https://drafts.csswg.org/css-cascade/#important
+ inline Priority AddImportance() const {
+ DCHECK_GE(GetOrigin(), Origin::kUserAgent);
+ DCHECK_LE(GetOrigin(), Origin::kAuthor);
+ // Flip Origin bits, converting non-important to important. We only
+ // xor four bits here, because only those bits are in use by
+ // k[Important,][User,UserAgent,Author].
+ return Priority(priority_ ^ (static_cast<uint64_t>(0b1111) << 32));
+ }
+
+ private:
+ friend class StyleCascade;
+ friend class StyleCascadeTest;
+
+ Priority(uint64_t priority) : priority_(priority) {}
+
+ // Returns a copy of this Priority, with the cascade order set to the
+ // specified value.
+ //
+ // For the purposes of StyleCascade::Add alone, we don't need to store the
+ // cascade order at all, since the cascade order is implicit in the order
+ // of the calls to ::Add. However, some properties unfortunately require
+ // that we store the cascade order and act upon it Apply-time. This is
+ // because we have multiple properties that mutate the same field on
+ // ComputedStyle, hence the relative ordering must be preserved between
+ // them to know which should be applied. (See class Filter).
+ inline Priority WithCascadeOrder(uint16_t cascade_order) const {
+ return Priority((priority_ & ~0xFFFF) | cascade_order);
+ }
+
+ // To make Priority comparisons fast, the origin, tree_order and
+ // cascade_order are stored in a single uint64_t, as follows:
+ //
+ // Bit 0-15: cascade_order
+ // Bit 16-31: tree_order
+ // Bit 32-39: Origin
+ //
+ // This way, the numeric value of priority_ can be compared directly
+ // for all criteria simultaneously.
+ uint64_t priority_;
+ };
+
+ // The Value class simply represents the data we store for each property
+ // in the cascade. See StyleCascade::cascade_ field.
+ class CORE_EXPORT Value {
+ DISALLOW_NEW();
+
+ public:
+ // The empty Value is needed because we store it in a HashMap.
+ Value() = default;
+ Value(const CSSValue* value, Priority priority)
+ : value_(value), priority_(priority) {}
+ bool IsEmpty() const { return !priority_.HasOrigin(); }
+ const CSSValue* GetValue() const { return value_; }
+ const Priority& GetPriority() const { return priority_; }
+ void Trace(blink::Visitor* visitor) { visitor->Trace(value_); }
+
+ private:
+ Member<const CSSValue> value_;
+ Priority priority_;
+ };
+
+ // Add a Value to the cascade. The Value will either become the cascaded
+ // value, or be discarded, depending on the Priority of the incoming value
+ // vs. the Priority of the existing value.
+ void Add(const CSSPropertyName&, const CSSValue*, Priority);
+
+ // Applies all values currently in the cascade to the ComputedStyle.
+ // Any CSSPendingInterpolationValues present in the cascade will be ignored.
+ void Apply();
+ // Applies all values currently in the cascade to the ComputedStyle,
+ // dispatching any CSSPendingInterpolationValues to the given Animator.
+ void Apply(Animator&);
+
+ // Removes all kAnimationPropertyPriority properties from the cascade,
+ // without applying the properties. This is used when pre-emptively copying
+ // the cascade in case there are animations.
+ //
+ // TODO(crbug.com/985010): Improve with non-destructive Apply.
+ void RemoveAnimationPriority();
+
+ // The Filter class is responsible for resolving situations where
+ // we have multiple (non-alias) properties in the cascade that mutates the
+ // same fields on ComputedStyle.
+ //
+ // An example of this is writing-mode and -webkit-writing-mode, which
+ // both result in ComputedStyle::SetWritingMode calls.
+ //
+ // When applying the cascade (applying each property/value pair to the
+ // ComputedStyle), the order of the application is in the general case
+ // not defined. (It is determined by the iteration order of the HashMap).
+ // This means that if both writing-mode and -webkit-writing-mode exist in
+ // the cascade, we would get non-deterministic behavior: the application order
+ // would not be defined. To fix this, all Values pass through this Filter
+ // before being applied.
+
+ // The Filter stores the Priority of the Value that was previously applied
+ // for a certain 'group' of properties (writing_mode_ is one such group).
+ // When we're about to apply a Value, we only actually do so if the call to
+ // Filter::Add succeeds. If the call to Filter::Add does not succeed, it means
+ // that we have previously added a Value with higher Priority, and that the
+ // current Value must be ignored.
+
+ // A key difference between discarding Values in the Filter, vs. discarding
+ // them cascade-time (StyleCascade::Add), is that we are taking the cascade
+ // order into account. This means that, if everything else is equal (origin,
+ // tree order), the Value that entered the cascade last wins. This is crucial
+ // to resolve situations like writing-mode and -webkit-writing-mode.
+
+ // The Filter is also expected to resolve similar difficulties with
+ // direction-aware properties in the future, although this is not yet
+ // implemented.
+ class CORE_EXPORT Filter {
+ STACK_ALLOCATED();
+
+ public:
+ // Attempts to add a given property/value to the Filter. If this returns
+ // true, the Value may be applied to the ComputedStyle. If not, it means
+ // that we have previously applied a Value with higher Priority, and the
+ // current Value must be discarded.
+ bool Add(const CSSProperty& property, const Value&);
+
+ private:
+ Priority& GetSlot(const CSSProperty&);
+
+ Priority none_;
+ Priority writing_mode_;
+ Priority zoom_;
+ };
+
+ // Resolver is an object passed on a stack during Apply. Its most important
+ // job is to detect cycles during Apply (in general, keep track of which
+ // properties we're currently applying).
+ class CORE_EXPORT Resolver {
+ STACK_ALLOCATED();
+
+ public:
+ // TODO(crbug.com/985047): Probably use a HashMap for this.
+ using NameStack = Vector<CSSPropertyName, 8>;
+
+ // A 'locked' property is a property we are in the process of applying.
+ // In other words, once a property is locked, locking it again would form
+ // a cycle, and is therefore an error.
+ bool IsLocked(const CSSProperty&) const;
+ bool IsLocked(const CSSPropertyName&) const;
+
+ // We do not allow substitution of animation-tainted values into
+ // an animation-affecting property.
+ //
+ // https://drafts.csswg.org/css-variables/#animation-tainted
+ bool AllowSubstitution(CSSVariableData*) const;
+
+ private:
+ friend class AutoLock;
+ friend class StyleCascade;
+ friend class TestCascadeResolver;
+
+ Resolver(Animator& animator) : animator_(animator) {}
+ // If the given property is already being applied, returns true.
+ // The return value is the same value you would get from InCycle(), and
+ // is just returned for convenience.
+ //
+ // When a cycle has been detected, the Resolver will *persist the cycle
+ // state* (i.e. InCycle() will continue to return true) until we reach
+ // the start of the cycle.
+ //
+ // The cycle state is cleared by ~AutoLock, once we have moved far enough
+ // up the stack.
+ bool DetectCycle(const CSSProperty&);
+ // Returns true whenever the Resolver is in a cycle state.
+ // This DOES NOT detect cycles; the caller must call DetectCycle first.
+ bool InCycle() const;
+
+ NameStack stack_;
+ Animator& animator_;
+ wtf_size_t cycle_depth_ = kNotFound;
+ Filter filter_;
+ };
+
+ // Automatically locks and unlocks the given property. (See
+ // Resolver::IsLocked).
+ class CORE_EXPORT AutoLock {
+ STACK_ALLOCATED();
+
+ public:
+ AutoLock(const CSSProperty&, Resolver&);
+ AutoLock(const CSSPropertyName&, Resolver&);
+ ~AutoLock();
+
+ private:
+ Resolver& resolver_;
+ };
+
+ // Animator & CSSPendingInterpolationValue
+ //
+ // Blink's way of applying animations poses some difficulty for StyleCascade,
+ // as much of the code that applies the animation effects completely bypasses
+ // StyleBuilder; it sets the values on ComputedStyle directly. This prevents
+ // those values from participating properly in the cascade.
+ //
+ // At the same time, we don't want to actually create CSSValues for the
+ // animation effects, as this is (yet another?) unnecessary conversion, and
+ // it produces unwanted GC pressure. To solve this problem, the cascading
+ // and application aspects of interpolations are handled *separately*.
+ //
+ // CSSPendingInterpolationValue represents the cascading aspect of an
+ // interpolation: this means that, once we know that an interpolation is
+ // active for a given property, we add a CSSPendingInterpolationValue to the
+ // cascade (with the appropriate Priority). Apply-time, we then ask the
+ // Animator (see StyleAnimator) to actually apply the interpolated value
+ // using the interpolation infrastructure.
+ class CORE_EXPORT Animator {
+ public:
+ virtual void Apply(const CSSProperty&,
+ const CSSPendingInterpolationValue&,
+ Resolver&) = 0;
+ };
+
+ // Applying a CSSPendingInterpolationValue may involve resolving values,
+ // since we may be applying a keyframe from e.g. "color: var(--x)" to
+ // "color: var(--y)". Hence that code needs an entry point to the resolving
+ // process.
+ //
+ // TODO(crbug.com/985023): This function has an associated const
+ // violation, which isn't great. (This vilation was not introduced with
+ // StyleCascade, however).
+ //
+ // See documentation the other Resolve* functions for what resolve means.
+ const CSSValue* Resolve(const CSSPropertyName&, const CSSValue&, Resolver&);
+
+ private:
+ friend class TestCascade;
+
+ // The maximum number of tokens that may be produced by a var()
+ // reference.
+ //
+ // https://drafts.csswg.org/css-variables/#long-variables
+ static const size_t kMaxSubstitutionTokens = 16384;
+
+ // Applies kHighPropertyPriority properties.
+ //
+ // In theory, it would be possible for each property/value that contains
+ // em/ch/etc to dynamically apply font-size (and related properties), but
+ // in practice, it is very inconvenient to detect these dependencies. Hence,
+ // we apply font-affecting properties (among others) before all the others.
+ void ApplyHighPriority(Resolver&);
+
+ // Apply a single property (including any dependencies).
+ void Apply(const CSSPropertyName&);
+ void Apply(const CSSPropertyName&, Resolver&);
+ void Apply(const CSSProperty&, Resolver&);
+
+ // True if the cascade currently holds the provided value for a given
+ // property. Note that the value is compared by address.
+ bool HasValue(const CSSPropertyName&, const CSSValue*) const;
+
+ // Get current cascaded value for the specified property.
+ const CSSValue* GetValue(const CSSPropertyName&) const;
+
+ // If there is a cascaded value for the specified property, replace it
+ // with the incoming value, maintaining the current cascade origin.
+ // Has no effect if there is no cascaded value for the property.
+ void ReplaceValue(const CSSPropertyName&, const CSSValue*);
+
+ // Whether or not we are calculating the style for the root element.
+ // We need to know this to detect cycles with 'rem' units.
+ // https://drafts.css-houdini.org/css-properties-values-api-1/#dependency-cycles
+ bool IsRootElement() const;
+
+ // The TokenSequence class acts as a builder for CSSVariableData.
+ //
+ // However, actually building a CSSVariableData is optional; you can also
+ // get a CSSParserTokenRange directly, which is useful when resolving a
+ // CSSVariableData which won't ultimately end up in a CSSVariableData
+ // (i.e. CSSVariableReferenceValue or CSSPendingSubstitutionValue).
+ class TokenSequence {
+ STACK_ALLOCATED();
+
+ public:
+ TokenSequence() = default;
+ // Initialize a TokenSequence from a CSSVariableData, preparing the
+ // TokenSequence for var() resolution.
+ //
+ // This copies everything except the tokens.
+ explicit TokenSequence(const CSSVariableData*);
+
+ bool IsAnimationTainted() const { return is_animation_tainted_; }
+ CSSParserTokenRange TokenRange() const { return tokens_; }
+
+ void Append(const TokenSequence&);
+ void Append(const CSSVariableData*);
+ void Append(const CSSParserToken&);
+
+ scoped_refptr<CSSVariableData> BuildVariableData();
+
+ private:
+ Vector<CSSParserToken> tokens_;
+ Vector<String> backing_strings_;
+ // https://drafts.csswg.org/css-variables/#animation-tainted
+ bool is_animation_tainted_ = false;
+ // https://drafts.css-houdini.org/css-properties-values-api-1/#dependency-cycles
+ bool has_font_units_ = false;
+ bool has_root_font_units_ = false;
+
+ // The base URL and charset are currently needed to calculate the computed
+ // value of <url>-registered custom properties correctly.
+ //
+ // TODO(crbug.com/985013): Store CSSParserContext on
+ // CSSCustomPropertyDeclaration and avoid this.
+ //
+ // https://drafts.css-houdini.org/css-properties-values-api-1/#relative-urls
+ String base_url_;
+ WTF::TextEncoding charset_;
+ };
+
+ // Resolving Values
+ //
+ // *Resolving* a value, means looking at the dependencies for a given
+ // CSSValue, and ensuring that these dependencies are satisfied. The result
+ // of a Resolve call is either the same CSSValue (e.g. if there were no
+ // dependencies), or a new CSSValue with the dependencies resolved.
+ //
+ // For example, consider the following properties:
+ //
+ // --x: 10px;
+ // --y: var(--x);
+ // width: var(--y);
+ //
+ // Here, to resolve 'width', the computed value of --y must be known. In
+ // other words, we must first Apply '--y'. Hence, resolving 'width' will
+ // Apply '--y' as a side-effect. (This process would then continue to '--x').
+
+ const CSSValue* Resolve(const CSSProperty&, const CSSValue&, Resolver&);
+ const CSSValue* ResolveCustomProperty(const CSSProperty&,
+ const CSSCustomPropertyDeclaration&,
+ Resolver&);
+ const CSSValue* ResolveVariableReference(const CSSProperty&,
+ const CSSVariableReferenceValue&,
+ Resolver&);
+ const CSSValue* ResolvePendingSubstitution(const CSSProperty&,
+ const CSSPendingSubstitutionValue&,
+ Resolver&);
+
+ scoped_refptr<CSSVariableData> ResolveVariableData(CSSVariableData*,
+ Resolver&);
+
+ // The Resolve*Into functions either resolve dependencies, append to the
+ // TokenSequence accordingly, and return true; or it returns false when
+ // the TokenSequence is "invalid at computed-value time" [1]. This happens
+ // when there was a reference to an invalid/missing custom property, or when a
+ // cycle was detected.
+ //
+ // [1] https://drafts.csswg.org/css-variables/#invalid-at-computed-value-time
+
+ bool ResolveTokensInto(CSSParserTokenRange, Resolver&, TokenSequence&);
+ bool ResolveVarInto(CSSParserTokenRange, Resolver&, TokenSequence&);
+ bool ResolveEnvInto(CSSParserTokenRange, Resolver&, TokenSequence&);
+
+ CSSVariableData* GetVariableData(const CustomProperty&) const;
+ CSSVariableData* GetEnvironmentVariable(const AtomicString&) const;
+ const CSSParserContext* GetParserContext(const CSSVariableReferenceValue&);
+
+ // Detects if the given property/data depends on the font-size property
+ // of the Element we're calculating the style for.
+ //
+ // https://drafts.css-houdini.org/css-properties-values-api-1/#dependency-cycles
+ bool HasFontSizeDependency(const CustomProperty&, CSSVariableData*) const;
+ // The fallback must match the syntax of the custom property, otherwise the
+ // the declaration is "invalid at computed-value time".'
+ //
+ // https://drafts.css-houdini.org/css-properties-values-api-1/#fallbacks-in-var-references
+ bool ValidateFallback(const CustomProperty&, CSSParserTokenRange) const;
+ // Marks the CustomProperty as referenced by something. Needed to avoid
+ // animating these custom properties on the compositor, and to disable the
+ // matched properties cache in some cases.
+ void MarkReferenced(const CustomProperty&);
+
+ StyleResolverState& state_;
+ HeapHashMap<CSSPropertyName, Value> cascade_;
+ uint16_t order_ = 0;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_RESOLVER_STYLE_CASCADE_H_
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/style_cascade_test.cc b/chromium/third_party/blink/renderer/core/css/resolver/style_cascade_test.cc
new file mode 100644
index 00000000000..af7d9d2449a
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/resolver/style_cascade_test.cc
@@ -0,0 +1,1976 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/css/resolver/style_cascade.h"
+
+#include <vector>
+
+#include "third_party/blink/renderer/core/animation/css/css_animations.h"
+#include "third_party/blink/renderer/core/css/active_style_sheets.h"
+#include "third_party/blink/renderer/core/css/css_custom_property_declaration.h"
+#include "third_party/blink/renderer/core/css/css_pending_interpolation_value.h"
+#include "third_party/blink/renderer/core/css/css_pending_substitution_value.h"
+#include "third_party/blink/renderer/core/css/css_primitive_value.h"
+#include "third_party/blink/renderer/core/css/css_style_sheet_init.h"
+#include "third_party/blink/renderer/core/css/css_test_helpers.h"
+#include "third_party/blink/renderer/core/css/css_variable_reference_value.h"
+#include "third_party/blink/renderer/core/css/document_style_environment_variables.h"
+#include "third_party/blink/renderer/core/css/media_query_evaluator.h"
+#include "third_party/blink/renderer/core/css/parser/css_parser_context.h"
+#include "third_party/blink/renderer/core/css/parser/css_parser_local_context.h"
+#include "third_party/blink/renderer/core/css/parser/css_parser_token_range.h"
+#include "third_party/blink/renderer/core/css/parser/css_property_parser.h"
+#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/properties/css_property_instances.h"
+#include "third_party/blink/renderer/core/css/properties/css_property_ref.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/css/resolver/scoped_style_resolver.h"
+#include "third_party/blink/renderer/core/css/resolver/style_animator.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/style_sheet_contents.h"
+#include "third_party/blink/renderer/core/html/html_element.h"
+#include "third_party/blink/renderer/core/style/computed_style.h"
+#include "third_party/blink/renderer/core/style_property_shorthand.h"
+#include "third_party/blink/renderer/core/testing/page_test_base.h"
+#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
+
+namespace blink {
+
+using namespace css_test_helpers;
+using namespace cssvalue;
+using Origin = StyleCascade::Origin;
+using Priority = StyleCascade::Priority;
+using UnitType = CSSPrimitiveValue::UnitType;
+
+enum class AnimationTainted { kYes, kNo };
+
+class TestCascade {
+ STACK_ALLOCATED();
+
+ public:
+ TestCascade(Document& document, Element* target = nullptr)
+ : state_(document, target ? *target : *document.body(), nullptr),
+ cascade_(InitState(state_)) {}
+
+ scoped_refptr<ComputedStyle> TakeStyle() { return state_.TakeStyle(); }
+
+ StyleResolverState& State() { return state_; }
+ StyleCascade& InnerCascade() { return cascade_; }
+
+ void InheritFrom(scoped_refptr<ComputedStyle> parent) {
+ state_.SetParentStyle(parent);
+ state_.StyleRef().InheritFrom(*parent);
+ }
+
+ void Add(String name,
+ String value,
+ Priority priority = Origin::kAuthor,
+ AnimationTainted animation_tainted = AnimationTainted::kNo) {
+ return Add(*CSSPropertyName::From(name), value, priority,
+ animation_tainted);
+ }
+
+ void Add(const CSSPropertyName& name,
+ String value,
+ Priority priority = Origin::kAuthor,
+ AnimationTainted animation_tainted = AnimationTainted::kNo) {
+ HeapVector<CSSPropertyValue, 256> values =
+ ParseValues(name, value, animation_tainted);
+
+ for (const CSSPropertyValue& v : values)
+ Add(v.Name(), v.Value(), priority);
+ }
+
+ void Add(String name,
+ const CSSValue* value,
+ Priority priority = Origin::kAuthor) {
+ Add(*CSSPropertyName::From(name), value, priority);
+ }
+
+ void Add(const CSSPropertyName& name,
+ const CSSValue* value,
+ Priority priority = Origin::kAuthor) {
+ DCHECK(CSSPropertyRef(name, GetDocument()).GetProperty().IsLonghand());
+ cascade_.Add(name, value, priority);
+ }
+
+ void Apply(const CSSPropertyName& name) { cascade_.Apply(name); }
+ void Apply(String name) { Apply(*CSSPropertyName::From(name)); }
+ void Apply() { cascade_.Apply(); }
+ void Apply(StyleCascade::Animator& animator) { cascade_.Apply(animator); }
+
+ HeapVector<CSSPropertyValue, 256> ParseValues(
+ const CSSPropertyName& name,
+ String value,
+ AnimationTainted animation_tainted) {
+ CSSTokenizer tokenizer(value);
+ auto tokens = tokenizer.TokenizeToEOF();
+ auto* context = MakeGarbageCollected<CSSParserContext>(GetDocument());
+ context->SetMode(kUASheetMode); // Allows -internal variables.
+
+ HeapVector<CSSPropertyValue, 256> parsed_properties;
+
+ bool is_animation_tainted = animation_tainted == AnimationTainted::kYes;
+ if (name.Id() == CSSPropertyID::kVariable) {
+ // TODO(andruud): Make CSSPropertyParser::ParseValue handle custom props.
+ const CSSValue* decl = CSSVariableParser::ParseDeclarationValue(
+ name.ToAtomicString(), tokens, is_animation_tainted, *context);
+ DCHECK(decl);
+ parsed_properties.emplace_back(GetCSSPropertyVariable(), *decl);
+ return parsed_properties;
+ }
+
+ const bool important = false;
+
+ bool ok = CSSPropertyParser::ParseValue(name.Id(), important, tokens,
+ context, parsed_properties,
+ StyleRule::RuleType::kStyle);
+ DCHECK(ok);
+
+ return parsed_properties;
+ }
+
+ String ComputedValue(String name) const {
+ CSSPropertyRef ref(name, GetDocument());
+ DCHECK(ref.IsValid());
+ const LayoutObject* layout_object = nullptr;
+ bool allow_visited_style = false;
+ const CSSValue* value = ref.GetProperty().CSSValueFromComputedStyle(
+ *state_.Style(), layout_object, Body(), allow_visited_style);
+ return value ? value->CssText() : g_null_atom;
+ }
+
+ bool HasValue(String name, const CSSValue* value) {
+ return cascade_.HasValue(*CSSPropertyName::From(name), value);
+ }
+
+ const CSSValue* GetCSSValue(String name) {
+ return cascade_.GetValue(*CSSPropertyName::From(name));
+ }
+
+ const String GetValue(String name) {
+ const CSSValue* value = GetCSSValue(name);
+ // Per spec, CSSPendingSubstitutionValue serializes as an empty string,
+ // but for testing purposes it's nice to see the actual value.
+ if (const auto* v = DynamicTo<CSSPendingSubstitutionValue>(value))
+ return v->ShorthandValue()->CssText();
+ if (DynamicTo<CSSPendingInterpolationValue>(value))
+ return "<interpolation>";
+ return value ? value->CssText() : g_null_atom;
+ }
+
+ CSSAnimationUpdate& CalculateTransitionUpdate() {
+ CSSAnimations::CalculateTransitionUpdate(
+ state_.AnimationUpdate(), CSSAnimations::PropertyPass::kCustom,
+ &state_.GetElement(), *state_.Style());
+ CSSAnimations::CalculateTransitionUpdate(
+ state_.AnimationUpdate(), CSSAnimations::PropertyPass::kStandard,
+ &state_.GetElement(), *state_.Style());
+ return state_.AnimationUpdate();
+ }
+
+ CSSAnimationUpdate& CalculateAnimationUpdate() {
+ CSSAnimations::CalculateAnimationUpdate(
+ state_.AnimationUpdate(), &state_.GetElement(), state_.GetElement(),
+ *state_.Style(), state_.ParentStyle(),
+ &GetDocument().EnsureStyleResolver());
+ return state_.AnimationUpdate();
+ }
+
+ void AddAnimations() {
+ auto& update = CalculateAnimationUpdate();
+ using Type = CSSPendingInterpolationValue::Type;
+
+ for (const auto& entry : update.ActiveInterpolationsForCustomAnimations()) {
+ auto name = entry.key.GetCSSPropertyName();
+ auto* v = CSSPendingInterpolationValue::Create(Type::kCSSProperty);
+ Add(name.ToAtomicString(), v);
+ }
+ for (const auto& entry :
+ update.ActiveInterpolationsForStandardAnimations()) {
+ auto name = entry.key.GetCSSPropertyName();
+ auto* v = CSSPendingInterpolationValue::Create(Type::kCSSProperty);
+ Add(name.ToAtomicString(), v);
+ }
+ }
+
+ void AddTransitions() {
+ auto& update = CalculateTransitionUpdate();
+ using Type = CSSPendingInterpolationValue::Type;
+
+ for (const auto& entry :
+ update.ActiveInterpolationsForCustomTransitions()) {
+ auto name = entry.key.GetCSSPropertyName();
+ auto* v = CSSPendingInterpolationValue::Create(Type::kCSSProperty);
+ Add(name.ToAtomicString(), v);
+ }
+ for (const auto& entry :
+ update.ActiveInterpolationsForStandardTransitions()) {
+ auto name = entry.key.GetCSSPropertyName();
+ auto* v = CSSPendingInterpolationValue::Create(Type::kCSSProperty);
+ Add(name.ToAtomicString(), v);
+ }
+ }
+
+ private:
+ Document& GetDocument() const { return state_.GetDocument(); }
+ Element* Body() const { return GetDocument().body(); }
+
+ static StyleResolverState& InitState(StyleResolverState& state) {
+ state.SetStyle(InitialStyle(state.GetDocument()));
+ state.SetParentStyle(InitialStyle(state.GetDocument()));
+ return state;
+ }
+
+ static scoped_refptr<ComputedStyle> InitialStyle(Document& document) {
+ return StyleResolver::InitialStyleForElement(document);
+ }
+
+ StyleResolverState state_;
+ StyleCascade cascade_;
+};
+
+class TestCascadeResolver {
+ STACK_ALLOCATED();
+
+ public:
+ TestCascadeResolver(Document& document, StyleAnimator& animator)
+ : document_(&document), resolver_(animator) {}
+ bool InCycle() const { return resolver_.InCycle(); }
+ bool DetectCycle(String name) {
+ CSSPropertyRef ref(name, *document_);
+ DCHECK(ref.IsValid());
+ const CSSProperty& property = ref.GetProperty();
+ return resolver_.DetectCycle(property);
+ }
+ wtf_size_t CycleDepth() const { return resolver_.cycle_depth_; }
+
+ private:
+ friend class TestCascadeAutoLock;
+
+ Member<Document> document_;
+ StyleCascade::Resolver resolver_;
+};
+
+class TestCascadeAutoLock {
+ STACK_ALLOCATED();
+
+ public:
+ TestCascadeAutoLock(const CSSPropertyName& name,
+ TestCascadeResolver& resolver)
+ : lock_(name, resolver.resolver_) {}
+
+ private:
+ StyleCascade::AutoLock lock_;
+};
+
+class StyleCascadeTest : public PageTestBase {
+ public:
+ void SetUp() override {
+ RuntimeEnabledFeatures::SetCSSCascadeEnabled(true);
+ PageTestBase::SetUp();
+ }
+
+ void TearDown() override {
+ PageTestBase::TearDown();
+ RuntimeEnabledFeatures::SetCSSCascadeEnabled(false);
+ }
+
+ CSSStyleSheet* CreateSheet(const String& css_text) {
+ auto* init = MakeGarbageCollected<CSSStyleSheetInit>();
+ DummyExceptionStateForTesting exception_state;
+ CSSStyleSheet* sheet =
+ CSSStyleSheet::Create(GetDocument(), init, exception_state);
+ sheet->replaceSync(css_text, exception_state);
+ sheet->Contents()->EnsureRuleSet(MediaQueryEvaluator(),
+ kRuleHasNoSpecialState);
+ return sheet;
+ }
+
+ void AppendSheet(const String& css_text) {
+ CSSStyleSheet* sheet = CreateSheet(css_text);
+ ASSERT_TRUE(sheet);
+
+ Element* body = GetDocument().body();
+ ASSERT_TRUE(body->IsInTreeScope());
+ TreeScope& tree_scope = body->GetTreeScope();
+ ScopedStyleResolver& scoped_resolver =
+ tree_scope.EnsureScopedStyleResolver();
+ ActiveStyleSheetVector active_sheets;
+ active_sheets.push_back(
+ std::make_pair(sheet, &sheet->Contents()->GetRuleSet()));
+ scoped_resolver.AppendActiveStyleSheets(0, active_sheets);
+ }
+
+ Element* DocumentElement() const { return GetDocument().documentElement(); }
+
+ void SetRootFont(String value) {
+ DocumentElement()->SetInlineStyleProperty(CSSPropertyID::kFontSize, value);
+ UpdateAllLifecyclePhasesForTest();
+ }
+
+ Priority AuthorPriority(uint16_t tree_order, uint16_t cascade_order) {
+ return Priority(Origin::kAuthor, tree_order)
+ .WithCascadeOrder(cascade_order);
+ }
+
+ Priority ImportantAuthorPriority(uint16_t tree_order,
+ uint16_t cascade_order) {
+ return Priority(Origin::kImportantAuthor, tree_order)
+ .WithCascadeOrder(cascade_order);
+ }
+
+ // Temporarily create a CSS Environment Variable.
+ // https://drafts.csswg.org/css-env-1/
+ class AutoEnv {
+ STACK_ALLOCATED();
+
+ public:
+ AutoEnv(PageTestBase& test, AtomicString name, String value)
+ : document_(&test.GetDocument()), name_(name) {
+ EnsureEnvironmentVariables().SetVariable(name, value);
+ }
+ ~AutoEnv() { EnsureEnvironmentVariables().RemoveVariable(name_); }
+
+ private:
+ DocumentStyleEnvironmentVariables& EnsureEnvironmentVariables() {
+ return document_->GetStyleEngine().EnsureEnvironmentVariables();
+ }
+
+ Member<Document> document_;
+ AtomicString name_;
+ };
+};
+
+TEST_F(StyleCascadeTest, OriginImportance) {
+ EXPECT_EQ(Origin::kImportantUserAgent,
+ Priority(Origin::kUserAgent).AddImportance().GetOrigin());
+ EXPECT_EQ(Origin::kImportantUser,
+ Priority(Origin::kUser).AddImportance().GetOrigin());
+ EXPECT_EQ(Origin::kImportantAuthor,
+ Priority(Origin::kAuthor).AddImportance().GetOrigin());
+}
+
+TEST_F(StyleCascadeTest, PriorityOrigin) {
+ std::vector<Priority> priorities = {
+ Origin::kTransition, Origin::kImportantUserAgent,
+ Origin::kImportantUser, Origin::kImportantAuthor,
+ Origin::kAnimation, Origin::kAuthor,
+ Origin::kUser, Origin::kUserAgent,
+ Origin::kNone};
+
+ for (size_t i = 0; i < priorities.size(); ++i) {
+ for (size_t j = i; j < priorities.size(); ++j)
+ EXPECT_GE(priorities[i], priorities[j]);
+ }
+
+ EXPECT_FALSE(Priority(Origin::kUser) >= Priority(Origin::kAuthor));
+}
+
+TEST_F(StyleCascadeTest, PriorityHasOrigin) {
+ EXPECT_TRUE(Priority(Origin::kTransition).HasOrigin());
+ EXPECT_TRUE(Priority(Origin::kAuthor).HasOrigin());
+ EXPECT_FALSE(Priority(Origin::kNone).HasOrigin());
+}
+
+TEST_F(StyleCascadeTest, PriorityTreeOrder) {
+ Origin origin = Origin::kAuthor;
+ EXPECT_GE(Priority(origin, 0), Priority(origin, 1));
+ EXPECT_GE(Priority(origin, 6), Priority(origin, 7));
+ EXPECT_GE(Priority(origin, 42), Priority(origin, 42));
+ EXPECT_FALSE(Priority(origin, 8) >= Priority(origin, 1));
+}
+
+TEST_F(StyleCascadeTest, PriorityTreeOrderImportant) {
+ Origin origin = Origin::kImportantAuthor;
+ EXPECT_GE(Priority(origin, 1), Priority(origin, 0));
+ EXPECT_GE(Priority(origin, 7), Priority(origin, 6));
+ EXPECT_GE(Priority(origin, 42), Priority(origin, 42));
+ EXPECT_FALSE(Priority(origin, 1) >= Priority(origin, 8));
+}
+
+TEST_F(StyleCascadeTest, PriorityTreeOrderDifferentOrigin) {
+ // Tree order does not matter if the origin is different.
+ Origin author = Origin::kAuthor;
+ Origin transition = Origin::kTransition;
+ EXPECT_GE(Priority(transition, 42), Priority(author, 1));
+ EXPECT_GE(Priority(transition, 1), Priority(author, 1));
+}
+
+TEST_F(StyleCascadeTest, PriorityCascadeOrder) {
+ // AuthorPriority(tree_order, cascade_order)
+ EXPECT_GE(AuthorPriority(0, 0), AuthorPriority(0, 0));
+ EXPECT_GE(AuthorPriority(0, 1), AuthorPriority(0, 1));
+ EXPECT_GE(AuthorPriority(0, 1), AuthorPriority(0, 0));
+ EXPECT_GE(AuthorPriority(0, 2), AuthorPriority(0, 1));
+ EXPECT_GE(AuthorPriority(0, 0xFFFF), AuthorPriority(0, 0xFFFE));
+ EXPECT_FALSE(AuthorPriority(0, 2) >= AuthorPriority(0, 3));
+}
+
+TEST_F(StyleCascadeTest, PriorityCascadeOrderAndTreeOrder) {
+ // AuthorPriority(tree_order, cascade_order)
+ EXPECT_GE(AuthorPriority(0, 0), AuthorPriority(1, 0));
+ EXPECT_GE(AuthorPriority(0, 1), AuthorPriority(1, 1));
+ EXPECT_GE(AuthorPriority(0, 1), AuthorPriority(1, 3));
+ EXPECT_GE(AuthorPriority(0, 2), AuthorPriority(1, 0xFFFE));
+}
+
+TEST_F(StyleCascadeTest, PriorityCascadeOrderAndOrigin) {
+ // [Important]AuthorPriority(tree_order, cascade_order)
+ EXPECT_GE(ImportantAuthorPriority(0, 0), AuthorPriority(0, 0));
+ EXPECT_GE(ImportantAuthorPriority(0, 1), AuthorPriority(0, 1));
+ EXPECT_GE(ImportantAuthorPriority(0, 1), AuthorPriority(0, 3));
+ EXPECT_GE(ImportantAuthorPriority(0, 2), AuthorPriority(0, 0xFFFE));
+}
+
+TEST_F(StyleCascadeTest, ApplySingle) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("width", "2px", Origin::kAuthor);
+ cascade.Add("width", "1px", Origin::kUser);
+ cascade.Apply("width");
+
+ EXPECT_EQ("2px", cascade.ComputedValue("width"));
+}
+
+TEST_F(StyleCascadeTest, ApplyCustomProperty) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("--x", " 10px ");
+ cascade.Add("--y", "nope");
+ cascade.Apply("--x");
+ cascade.Apply("--y");
+
+ EXPECT_EQ(" 10px ", cascade.ComputedValue("--x"));
+ EXPECT_EQ("nope", cascade.ComputedValue("--y"));
+}
+
+TEST_F(StyleCascadeTest, Copy) {
+ StyleResolverState state(GetDocument(), *GetDocument().body(), nullptr);
+
+ TestCascade cascade(GetDocument());
+ cascade.Add("--x", "10px");
+ cascade.Add("width", "20px");
+
+ // Take snapshot of the cascade, pointing to the same StyleResolverState.
+ StyleCascade snapshot(cascade.InnerCascade());
+
+ cascade.Add("--x", "0px");
+ cascade.Add("width", "1px");
+ cascade.Apply();
+
+ EXPECT_EQ("0px", cascade.ComputedValue("--x"));
+ EXPECT_EQ("1px", cascade.ComputedValue("width"));
+
+ snapshot.Apply();
+ EXPECT_EQ("10px", cascade.ComputedValue("--x"));
+ EXPECT_EQ("20px", cascade.ComputedValue("width"));
+}
+
+TEST_F(StyleCascadeTest, ApplyCustomPropertyVar) {
+ // Apply --x first.
+ {
+ TestCascade cascade(GetDocument());
+ cascade.Add("--x", "yes and var(--y)");
+ cascade.Add("--y", "no");
+ cascade.Apply("--x");
+ cascade.Apply("--y");
+
+ EXPECT_EQ("yes and no", cascade.ComputedValue("--x"));
+ EXPECT_EQ("no", cascade.ComputedValue("--y"));
+ }
+
+ // Apply --y first.
+ {
+ TestCascade cascade(GetDocument());
+ cascade.Add("--x", "yes and var(--y)");
+ cascade.Add("--y", "no");
+ cascade.Apply("--y");
+ cascade.Apply("--x");
+
+ EXPECT_EQ("yes and no", cascade.ComputedValue("--x"));
+ EXPECT_EQ("no", cascade.ComputedValue("--y"));
+ }
+}
+
+TEST_F(StyleCascadeTest, InvalidVarReferenceCauseInvalidVariable) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("--x", "nope var(--y)");
+ cascade.Apply("--x");
+
+ EXPECT_EQ(g_null_atom, cascade.ComputedValue("--x"));
+}
+
+TEST_F(StyleCascadeTest, ApplyCustomPropertyFallback) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("--x", "yes and var(--y,no)");
+ cascade.Apply("--x");
+
+ EXPECT_EQ("yes and no", cascade.ComputedValue("--x"));
+}
+
+TEST_F(StyleCascadeTest, RegisteredPropertyFallback) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "0px", false);
+
+ TestCascade cascade(GetDocument());
+ cascade.Add("--x", "var(--y,10px)");
+ cascade.Apply();
+
+ EXPECT_EQ("10px", cascade.ComputedValue("--x"));
+}
+
+TEST_F(StyleCascadeTest, RegisteredPropertyFallbackValidation) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "0px", false);
+
+ TestCascade cascade(GetDocument());
+ cascade.Add("--x", "10px");
+ cascade.Add("--y", "var(--x,red)"); // Fallback must be valid <length>.
+ cascade.Add("--z", "var(--y,pass)");
+ cascade.Apply();
+
+ EXPECT_EQ("pass", cascade.ComputedValue("--z"));
+}
+
+TEST_F(StyleCascadeTest, VarInFallback) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("--x", "one var(--z,two var(--y))");
+ cascade.Add("--y", "three");
+ cascade.Apply("--x");
+
+ EXPECT_EQ("one two three", cascade.ComputedValue("--x"));
+}
+
+TEST_F(StyleCascadeTest, VarReferenceInNormalProperty) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("--x", "10px");
+ cascade.Add("width", "var(--x)");
+ cascade.Apply("width");
+
+ EXPECT_EQ("10px", cascade.ComputedValue("width"));
+}
+
+TEST_F(StyleCascadeTest, MultipleVarRefs) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("--x", "var(--y) bar var(--y)");
+ cascade.Add("--y", "foo");
+ cascade.Apply("--x");
+
+ EXPECT_EQ("foo bar foo", cascade.ComputedValue("--x"));
+}
+
+TEST_F(StyleCascadeTest, RegisteredPropertyComputedValue) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "0px", false);
+
+ TestCascade cascade(GetDocument());
+ cascade.Add("--x", "1in");
+ cascade.Apply("--x");
+
+ EXPECT_EQ("96px", cascade.ComputedValue("--x"));
+}
+
+TEST_F(StyleCascadeTest, RegisteredPropertySyntaxErrorCausesInitial) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "10px", false);
+
+ TestCascade cascade(GetDocument());
+ cascade.Add("--x", "#fefefe");
+ cascade.Add("--y", "var(--x)");
+ cascade.Apply("--x");
+ cascade.Apply("--y");
+
+ EXPECT_EQ("10px", cascade.ComputedValue("--x"));
+ EXPECT_EQ("10px", cascade.ComputedValue("--y"));
+}
+
+TEST_F(StyleCascadeTest, RegisteredPropertySubstitution) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "0px", false);
+
+ TestCascade cascade(GetDocument());
+ cascade.Add("--x", "1in");
+ cascade.Add("--y", "var(--x)");
+ cascade.Apply("--y");
+
+ EXPECT_EQ("96px", cascade.ComputedValue("--y"));
+}
+
+TEST_F(StyleCascadeTest, RegisteredPropertyChain) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "0px", false);
+ RegisterProperty(GetDocument(), "--z", "<length>", "0px", false);
+
+ TestCascade cascade(GetDocument());
+ cascade.Add("--x", "1in");
+ cascade.Add("--y", "var(--x)");
+ cascade.Add("--z", "calc(var(--y) + 1in)");
+ cascade.Apply();
+
+ EXPECT_EQ("96px", cascade.ComputedValue("--x"));
+ EXPECT_EQ("96px", cascade.ComputedValue("--y"));
+ EXPECT_EQ("192px", cascade.ComputedValue("--z"));
+}
+
+TEST_F(StyleCascadeTest, BasicShorthand) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("margin", "1px 2px 3px 4px");
+ cascade.Apply();
+
+ EXPECT_EQ("1px", cascade.ComputedValue("margin-top"));
+ EXPECT_EQ("2px", cascade.ComputedValue("margin-right"));
+ EXPECT_EQ("3px", cascade.ComputedValue("margin-bottom"));
+ EXPECT_EQ("4px", cascade.ComputedValue("margin-left"));
+}
+
+TEST_F(StyleCascadeTest, BasicVarShorthand) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("margin", "1px var(--x) 3px 4px");
+ cascade.Add("--x", "2px");
+ cascade.Apply();
+
+ EXPECT_EQ("1px", cascade.ComputedValue("margin-top"));
+ EXPECT_EQ("2px", cascade.ComputedValue("margin-right"));
+ EXPECT_EQ("3px", cascade.ComputedValue("margin-bottom"));
+ EXPECT_EQ("4px", cascade.ComputedValue("margin-left"));
+}
+
+TEST_F(StyleCascadeTest, ApplyingPendingSubstitutionFirst) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("margin", "1px var(--x) 3px 4px");
+ cascade.Add("--x", "2px");
+ cascade.Add("margin-right", "5px");
+
+ // Apply one of the pending substitution values first. This should not
+ // overwrite margin-right's 5px.
+ cascade.Apply("margin-left");
+ cascade.Apply();
+
+ EXPECT_EQ("1px", cascade.ComputedValue("margin-top"));
+ EXPECT_EQ("5px", cascade.ComputedValue("margin-right"));
+ EXPECT_EQ("3px", cascade.ComputedValue("margin-bottom"));
+ EXPECT_EQ("4px", cascade.ComputedValue("margin-left"));
+}
+
+TEST_F(StyleCascadeTest, ApplyingPendingSubstitutionLast) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("margin", "1px var(--x) 3px 4px");
+ cascade.Add("--x", "2px");
+ cascade.Add("margin-right", "5px");
+
+ // Apply margin-right before the others. Applying the pending substitution
+ // afterwards should not overwrite margin-right's 5px.
+ cascade.Apply("margin-right");
+ cascade.Apply();
+
+ EXPECT_EQ("1px", cascade.ComputedValue("margin-top"));
+ EXPECT_EQ("5px", cascade.ComputedValue("margin-right"));
+ EXPECT_EQ("3px", cascade.ComputedValue("margin-bottom"));
+ EXPECT_EQ("4px", cascade.ComputedValue("margin-left"));
+}
+
+TEST_F(StyleCascadeTest, ApplyingPendingSubstitutionModifiesCascade) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("margin", "1px var(--x) 3px 4px");
+ cascade.Add("--x", "2px");
+ cascade.Add("margin-right", "5px");
+
+ // We expect the pending substitution value for all the shorthands,
+ // except margin-right.
+ EXPECT_EQ("1px var(--x) 3px 4px", cascade.GetValue("margin-top"));
+ EXPECT_EQ("5px", cascade.GetValue("margin-right"));
+ EXPECT_EQ("1px var(--x) 3px 4px", cascade.GetValue("margin-bottom"));
+ EXPECT_EQ("1px var(--x) 3px 4px", cascade.GetValue("margin-left"));
+
+ // Apply a pending substitution value should modify the cascade for other
+ // longhands with the same pending substitution value.
+ cascade.Apply("margin-left");
+
+ EXPECT_EQ("1px", cascade.GetValue("margin-top"));
+ EXPECT_EQ("5px", cascade.GetValue("margin-right"));
+ EXPECT_EQ("3px", cascade.GetValue("margin-bottom"));
+ EXPECT_FALSE(cascade.GetValue("margin-left"));
+}
+
+TEST_F(StyleCascadeTest, ResolverDetectCycle) {
+ TestCascade cascade(GetDocument());
+ StyleAnimator animator(cascade.State(), cascade.InnerCascade());
+ TestCascadeResolver resolver(GetDocument(), animator);
+
+ {
+ TestCascadeAutoLock lock(CSSPropertyName("--a"), resolver);
+ EXPECT_FALSE(resolver.InCycle());
+ {
+ TestCascadeAutoLock lock(CSSPropertyName("--b"), resolver);
+ EXPECT_FALSE(resolver.InCycle());
+ {
+ TestCascadeAutoLock lock(CSSPropertyName("--c"), resolver);
+ EXPECT_FALSE(resolver.InCycle());
+
+ EXPECT_TRUE(resolver.DetectCycle("--a"));
+ EXPECT_TRUE(resolver.InCycle());
+ }
+ EXPECT_TRUE(resolver.InCycle());
+ }
+ EXPECT_TRUE(resolver.InCycle());
+ }
+ EXPECT_FALSE(resolver.InCycle());
+}
+
+TEST_F(StyleCascadeTest, ResolverDetectNoCycle) {
+ TestCascade cascade(GetDocument());
+ StyleAnimator animator(cascade.State(), cascade.InnerCascade());
+ TestCascadeResolver resolver(GetDocument(), animator);
+
+ {
+ TestCascadeAutoLock lock(CSSPropertyName("--a"), resolver);
+ EXPECT_FALSE(resolver.InCycle());
+ {
+ TestCascadeAutoLock lock(CSSPropertyName("--b"), resolver);
+ EXPECT_FALSE(resolver.InCycle());
+ {
+ TestCascadeAutoLock lock(CSSPropertyName("--c"), resolver);
+ EXPECT_FALSE(resolver.InCycle());
+
+ EXPECT_FALSE(resolver.DetectCycle("--x"));
+ EXPECT_FALSE(resolver.InCycle());
+ }
+ EXPECT_FALSE(resolver.InCycle());
+ }
+ EXPECT_FALSE(resolver.InCycle());
+ }
+ EXPECT_FALSE(resolver.InCycle());
+}
+
+TEST_F(StyleCascadeTest, ResolverDetectCycleSelf) {
+ TestCascade cascade(GetDocument());
+ StyleAnimator animator(cascade.State(), cascade.InnerCascade());
+ TestCascadeResolver resolver(GetDocument(), animator);
+
+ {
+ TestCascadeAutoLock lock(CSSPropertyName("--a"), resolver);
+ EXPECT_FALSE(resolver.InCycle());
+
+ EXPECT_TRUE(resolver.DetectCycle("--a"));
+ EXPECT_TRUE(resolver.InCycle());
+ }
+ EXPECT_FALSE(resolver.InCycle());
+}
+
+TEST_F(StyleCascadeTest, ResolverDetectMultiCycle) {
+ using AutoLock = TestCascadeAutoLock;
+
+ TestCascade cascade(GetDocument());
+ StyleAnimator animator(cascade.State(), cascade.InnerCascade());
+ TestCascadeResolver resolver(GetDocument(), animator);
+
+ {
+ AutoLock lock(CSSPropertyName("--a"), resolver);
+ EXPECT_FALSE(resolver.InCycle());
+ {
+ AutoLock lock(CSSPropertyName("--b"), resolver);
+ EXPECT_FALSE(resolver.InCycle());
+ {
+ AutoLock lock(CSSPropertyName("--c"), resolver);
+ EXPECT_FALSE(resolver.InCycle());
+ {
+ AutoLock lock(CSSPropertyName("--d"), resolver);
+ EXPECT_FALSE(resolver.InCycle());
+
+ // Cycle 1 (big cycle):
+ EXPECT_TRUE(resolver.DetectCycle("--b"));
+ EXPECT_TRUE(resolver.InCycle());
+ EXPECT_EQ(1u, resolver.CycleDepth());
+
+ // Cycle 2 (small cycle):
+ EXPECT_TRUE(resolver.DetectCycle("--c"));
+ EXPECT_TRUE(resolver.InCycle());
+ EXPECT_EQ(1u, resolver.CycleDepth());
+ }
+ }
+ EXPECT_TRUE(resolver.InCycle());
+ }
+ EXPECT_FALSE(resolver.InCycle());
+ }
+ EXPECT_FALSE(resolver.InCycle());
+}
+
+TEST_F(StyleCascadeTest, ResolverDetectMultiCycleReverse) {
+ using AutoLock = TestCascadeAutoLock;
+
+ TestCascade cascade(GetDocument());
+ StyleAnimator animator(cascade.State(), cascade.InnerCascade());
+ TestCascadeResolver resolver(GetDocument(), animator);
+
+ {
+ AutoLock lock(CSSPropertyName("--a"), resolver);
+ EXPECT_FALSE(resolver.InCycle());
+ {
+ AutoLock lock(CSSPropertyName("--b"), resolver);
+ EXPECT_FALSE(resolver.InCycle());
+ {
+ AutoLock lock(CSSPropertyName("--c"), resolver);
+ EXPECT_FALSE(resolver.InCycle());
+ {
+ AutoLock lock(CSSPropertyName("--d"), resolver);
+ EXPECT_FALSE(resolver.InCycle());
+
+ // Cycle 1 (small cycle):
+ EXPECT_TRUE(resolver.DetectCycle("--c"));
+ EXPECT_TRUE(resolver.InCycle());
+ EXPECT_EQ(2u, resolver.CycleDepth());
+
+ // Cycle 2 (big cycle):
+ EXPECT_TRUE(resolver.DetectCycle("--b"));
+ EXPECT_TRUE(resolver.InCycle());
+ EXPECT_EQ(1u, resolver.CycleDepth());
+ }
+ }
+ EXPECT_TRUE(resolver.InCycle());
+ }
+ EXPECT_FALSE(resolver.InCycle());
+ }
+ EXPECT_FALSE(resolver.InCycle());
+}
+
+TEST_F(StyleCascadeTest, BasicCycle) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("--a", "foo");
+ cascade.Add("--b", "bar");
+ cascade.Apply();
+
+ EXPECT_EQ("foo", cascade.ComputedValue("--a"));
+ EXPECT_EQ("bar", cascade.ComputedValue("--b"));
+
+ cascade.Add("--a", "var(--b)");
+ cascade.Add("--b", "var(--a)");
+ cascade.Apply();
+
+ EXPECT_FALSE(cascade.ComputedValue("--a"));
+ EXPECT_FALSE(cascade.ComputedValue("--b"));
+}
+
+TEST_F(StyleCascadeTest, SelfCycle) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("--a", "foo");
+ cascade.Apply();
+
+ EXPECT_EQ("foo", cascade.ComputedValue("--a"));
+
+ cascade.Add("--a", "var(--a)");
+ cascade.Apply();
+
+ EXPECT_FALSE(cascade.ComputedValue("--a"));
+}
+
+TEST_F(StyleCascadeTest, SelfCycleInFallback) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("--a", "var(--x, var(--a))");
+ cascade.Apply();
+
+ EXPECT_FALSE(cascade.ComputedValue("--a"));
+}
+
+TEST_F(StyleCascadeTest, SelfCycleInUnusedFallback) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("--a", "var(--b, var(--a))");
+ cascade.Add("--b", "10px");
+ cascade.Apply();
+
+ EXPECT_FALSE(cascade.ComputedValue("--a"));
+ EXPECT_EQ("10px", cascade.ComputedValue("--b"));
+}
+
+TEST_F(StyleCascadeTest, LongCycle) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("--a", "var(--b)");
+ cascade.Add("--b", "var(--c)");
+ cascade.Add("--c", "var(--d)");
+ cascade.Add("--d", "var(--e)");
+ cascade.Add("--e", "var(--a)");
+ cascade.Apply();
+
+ EXPECT_FALSE(cascade.ComputedValue("--a"));
+ EXPECT_FALSE(cascade.ComputedValue("--b"));
+ EXPECT_FALSE(cascade.ComputedValue("--c"));
+ EXPECT_FALSE(cascade.ComputedValue("--d"));
+ EXPECT_FALSE(cascade.ComputedValue("--e"));
+}
+
+TEST_F(StyleCascadeTest, PartialCycle) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("--a", "var(--b)");
+ cascade.Add("--b", "var(--a)");
+ cascade.Add("--c", "bar var(--d) var(--a)");
+ cascade.Add("--d", "foo");
+ cascade.Apply();
+
+ EXPECT_FALSE(cascade.ComputedValue("--a"));
+ EXPECT_FALSE(cascade.ComputedValue("--b"));
+ EXPECT_FALSE(cascade.ComputedValue("--c"));
+ EXPECT_EQ("foo", cascade.ComputedValue("--d"));
+}
+
+TEST_F(StyleCascadeTest, VarCycleViaFallback) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("--a", "var(--b)");
+ cascade.Add("--b", "var(--x, var(--a))");
+ cascade.Add("--c", "var(--a)");
+ cascade.Apply();
+
+ EXPECT_FALSE(cascade.ComputedValue("--a"));
+ EXPECT_FALSE(cascade.ComputedValue("--b"));
+ EXPECT_FALSE(cascade.ComputedValue("--c"));
+}
+
+TEST_F(StyleCascadeTest, FallbackTriggeredByCycle) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("--a", "var(--b)");
+ cascade.Add("--b", "var(--a)");
+ cascade.Add("--c", "var(--a,foo)");
+ cascade.Apply();
+
+ EXPECT_FALSE(cascade.ComputedValue("--a"));
+ EXPECT_FALSE(cascade.ComputedValue("--b"));
+ EXPECT_EQ("foo", cascade.ComputedValue("--c"));
+}
+
+TEST_F(StyleCascadeTest, RegisteredCycle) {
+ RegisterProperty(GetDocument(), "--a", "<length>", "0px", false);
+ RegisterProperty(GetDocument(), "--b", "<length>", "0px", false);
+
+ TestCascade cascade(GetDocument());
+ cascade.Add("--a", "var(--b)");
+ cascade.Add("--b", "var(--a)");
+ cascade.Apply();
+
+ EXPECT_FALSE(cascade.ComputedValue("--a"));
+ EXPECT_FALSE(cascade.ComputedValue("--b"));
+}
+
+TEST_F(StyleCascadeTest, PartiallyRegisteredCycle) {
+ RegisterProperty(GetDocument(), "--a", "<length>", "0px", false);
+
+ TestCascade cascade(GetDocument());
+ cascade.Add("--a", "var(--b)");
+ cascade.Add("--b", "var(--a)");
+ cascade.Apply();
+
+ EXPECT_FALSE(cascade.ComputedValue("--a"));
+ EXPECT_FALSE(cascade.ComputedValue("--b"));
+}
+
+TEST_F(StyleCascadeTest, FallbackTriggeredByRegisteredCycle) {
+ RegisterProperty(GetDocument(), "--a", "<length>", "0px", false);
+ RegisterProperty(GetDocument(), "--b", "<length>", "0px", false);
+
+ TestCascade cascade(GetDocument());
+ // Cycle:
+ cascade.Add("--a", "var(--b)");
+ cascade.Add("--b", "var(--a)");
+ // References to cycle:
+ cascade.Add("--c", "var(--a,1px)");
+ cascade.Add("--d", "var(--b,2px)");
+ cascade.Apply();
+
+ EXPECT_FALSE(cascade.ComputedValue("--a"));
+ EXPECT_FALSE(cascade.ComputedValue("--b"));
+ EXPECT_EQ("1px", cascade.ComputedValue("--c"));
+ EXPECT_EQ("2px", cascade.ComputedValue("--d"));
+}
+
+TEST_F(StyleCascadeTest, CycleStillInvalidWithFallback) {
+ TestCascade cascade(GetDocument());
+ // Cycle:
+ cascade.Add("--a", "var(--b,red)");
+ cascade.Add("--b", "var(--a,red)");
+ // References to cycle:
+ cascade.Add("--c", "var(--a,green)");
+ cascade.Add("--d", "var(--b,green)");
+ cascade.Apply();
+
+ EXPECT_FALSE(cascade.ComputedValue("--a"));
+ EXPECT_FALSE(cascade.ComputedValue("--b"));
+ EXPECT_EQ("green", cascade.ComputedValue("--c"));
+ EXPECT_EQ("green", cascade.ComputedValue("--d"));
+}
+
+TEST_F(StyleCascadeTest, CycleInFallbackStillInvalid) {
+ TestCascade cascade(GetDocument());
+ // Cycle:
+ cascade.Add("--a", "var(--b,red)");
+ cascade.Add("--b", "var(--x,var(--a))");
+ // References to cycle:
+ cascade.Add("--c", "var(--a,green)");
+ cascade.Add("--d", "var(--b,green)");
+ cascade.Apply();
+
+ EXPECT_FALSE(cascade.ComputedValue("--a"));
+ EXPECT_FALSE(cascade.ComputedValue("--b"));
+ EXPECT_EQ("green", cascade.ComputedValue("--c"));
+ EXPECT_EQ("green", cascade.ComputedValue("--d"));
+}
+
+TEST_F(StyleCascadeTest, CycleMultiple) {
+ TestCascade cascade(GetDocument());
+ // Cycle:
+ cascade.Add("--a", "var(--c, red)");
+ cascade.Add("--b", "var(--c, red)");
+ cascade.Add("--c", "var(--a, blue) var(--b, blue)");
+ // References to cycle:
+ cascade.Add("--d", "var(--a,green)");
+ cascade.Add("--e", "var(--b,green)");
+ cascade.Add("--f", "var(--c,green)");
+ cascade.Apply();
+
+ EXPECT_FALSE(cascade.ComputedValue("--a"));
+ EXPECT_FALSE(cascade.ComputedValue("--b"));
+ EXPECT_FALSE(cascade.ComputedValue("--c"));
+ EXPECT_EQ("green", cascade.ComputedValue("--d"));
+ EXPECT_EQ("green", cascade.ComputedValue("--e"));
+ EXPECT_EQ("green", cascade.ComputedValue("--f"));
+}
+
+TEST_F(StyleCascadeTest, CycleMultipleFallback) {
+ TestCascade cascade(GetDocument());
+ // Cycle:
+ cascade.Add("--a", "var(--b, red)");
+ cascade.Add("--b", "var(--a, var(--c, red))");
+ cascade.Add("--c", "var(--b, red)");
+ // References to cycle:
+ cascade.Add("--d", "var(--a,green)");
+ cascade.Add("--e", "var(--b,green)");
+ cascade.Add("--f", "var(--c,green)");
+ cascade.Apply();
+
+ EXPECT_FALSE(cascade.ComputedValue("--a"));
+ EXPECT_FALSE(cascade.ComputedValue("--b"));
+ EXPECT_FALSE(cascade.ComputedValue("--c"));
+ EXPECT_EQ("green", cascade.ComputedValue("--d"));
+ EXPECT_EQ("green", cascade.ComputedValue("--e"));
+ EXPECT_EQ("green", cascade.ComputedValue("--f"));
+}
+
+TEST_F(StyleCascadeTest, CycleMultipleUnusedFallback) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("--a", "red");
+ // Cycle:
+ cascade.Add("--b", "var(--c, red)");
+ cascade.Add("--c", "var(--a, var(--b, red) var(--d, red))");
+ cascade.Add("--d", "var(--c, red)");
+ // References to cycle:
+ cascade.Add("--e", "var(--b,green)");
+ cascade.Add("--f", "var(--c,green)");
+ cascade.Add("--g", "var(--d,green)");
+ cascade.Apply();
+
+ EXPECT_FALSE(cascade.ComputedValue("--b"));
+ EXPECT_FALSE(cascade.ComputedValue("--c"));
+ EXPECT_FALSE(cascade.ComputedValue("--d"));
+ EXPECT_EQ("green", cascade.ComputedValue("--e"));
+ EXPECT_EQ("green", cascade.ComputedValue("--f"));
+ EXPECT_EQ("green", cascade.ComputedValue("--g"));
+}
+
+TEST_F(StyleCascadeTest, CycleReferencedFromStandardProperty) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("--a", "var(--b)");
+ cascade.Add("--b", "var(--a)");
+ cascade.Add("color", "var(--a,green)");
+ cascade.Apply();
+
+ EXPECT_FALSE(cascade.ComputedValue("--a"));
+ EXPECT_FALSE(cascade.ComputedValue("--b"));
+ EXPECT_EQ("rgb(0, 128, 0)", cascade.ComputedValue("color"));
+}
+
+TEST_F(StyleCascadeTest, CycleReferencedFromShorthand) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("--a", "var(--b)");
+ cascade.Add("--b", "var(--a)");
+ cascade.Add("background", "var(--a,green)");
+ cascade.Apply();
+
+ EXPECT_FALSE(cascade.ComputedValue("--a"));
+ EXPECT_FALSE(cascade.ComputedValue("--b"));
+ EXPECT_EQ("rgb(0, 128, 0)", cascade.ComputedValue("background-color"));
+}
+
+TEST_F(StyleCascadeTest, EmUnit) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("font-size", "10px");
+ cascade.Add("width", "10em");
+ cascade.Apply();
+
+ EXPECT_EQ("100px", cascade.ComputedValue("width"));
+}
+
+TEST_F(StyleCascadeTest, EmUnitCustomProperty) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "0px", false);
+
+ TestCascade cascade(GetDocument());
+ cascade.Add("font-size", "10px");
+ cascade.Add("--x", "10em");
+ cascade.Apply();
+
+ EXPECT_EQ("100px", cascade.ComputedValue("--x"));
+}
+
+TEST_F(StyleCascadeTest, EmUnitNonCycle) {
+ TestCascade parent(GetDocument());
+ parent.Add("font-size", "10px");
+ parent.Apply();
+
+ TestCascade cascade(GetDocument());
+ cascade.InheritFrom(parent.TakeStyle());
+ cascade.Add("font-size", "var(--x)");
+ cascade.Add("--x", "10em");
+ cascade.Apply();
+
+ // Note: Only registered properties can have cycles with font-size.
+ EXPECT_EQ("100px", cascade.ComputedValue("font-size"));
+}
+
+TEST_F(StyleCascadeTest, EmUnitCycle) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "0px", false);
+
+ TestCascade cascade(GetDocument());
+ cascade.Add("font-size", "var(--x)");
+ cascade.Add("--x", "10em");
+ cascade.Apply();
+
+ EXPECT_FALSE(cascade.ComputedValue("--x"));
+}
+
+TEST_F(StyleCascadeTest, SubstitutingEmCycles) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "0px", false);
+
+ TestCascade cascade(GetDocument());
+ cascade.Add("font-size", "var(--x)");
+ cascade.Add("--x", "10em");
+ cascade.Add("--y", "var(--x)");
+ cascade.Add("--z", "var(--x,1px)");
+ cascade.Apply();
+
+ EXPECT_FALSE(cascade.ComputedValue("--y"));
+ EXPECT_EQ("1px", cascade.ComputedValue("--z"));
+}
+
+TEST_F(StyleCascadeTest, RemUnit) {
+ SetRootFont("10px");
+ UpdateAllLifecyclePhasesForTest();
+
+ TestCascade cascade(GetDocument());
+ cascade.Add("width", "10rem");
+ cascade.Apply();
+
+ EXPECT_EQ("100px", cascade.ComputedValue("width"));
+}
+
+TEST_F(StyleCascadeTest, RemUnitCustomProperty) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "0px", false);
+
+ SetRootFont("10px");
+ UpdateAllLifecyclePhasesForTest();
+
+ TestCascade cascade(GetDocument());
+ cascade.Add("--x", "10rem");
+ cascade.Apply();
+
+ EXPECT_EQ("100px", cascade.ComputedValue("--x"));
+}
+
+TEST_F(StyleCascadeTest, RemUnitInFontSize) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "0px", false);
+
+ SetRootFont("10px");
+ UpdateAllLifecyclePhasesForTest();
+
+ TestCascade cascade(GetDocument());
+ cascade.Add("font-size", "1rem");
+ cascade.Add("--x", "10rem");
+ cascade.Apply();
+
+ EXPECT_EQ("100px", cascade.ComputedValue("--x"));
+}
+
+TEST_F(StyleCascadeTest, RemUnitInRootFontSizeCycle) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "0px", false);
+
+ TestCascade cascade(GetDocument(), DocumentElement());
+ cascade.Add("font-size", "var(--x)");
+ cascade.Add("--x", "1rem");
+ cascade.Apply();
+
+ EXPECT_FALSE(cascade.ComputedValue("--x"));
+}
+
+TEST_F(StyleCascadeTest, RemUnitInRootFontSizeNonCycle) {
+ TestCascade cascade(GetDocument(), DocumentElement());
+ cascade.Add("font-size", "initial");
+ cascade.Apply();
+
+ String expected = cascade.ComputedValue("font-size");
+
+ cascade.Add("font-size", "var(--x)");
+ cascade.Add("--x", "1rem");
+ cascade.Apply();
+
+ // Note: Only registered properties can have cycles with font-size.
+ EXPECT_EQ("1rem", cascade.ComputedValue("--x"));
+ EXPECT_EQ(expected, cascade.ComputedValue("font-size"));
+}
+
+TEST_F(StyleCascadeTest, Initial) {
+ TestCascade parent(GetDocument());
+ parent.Add("--x", "foo");
+ parent.Apply();
+
+ TestCascade cascade(GetDocument());
+ cascade.InheritFrom(parent.TakeStyle());
+ cascade.Add("--y", "foo");
+ cascade.Apply();
+
+ EXPECT_EQ("foo", cascade.ComputedValue("--x"));
+ EXPECT_EQ("foo", cascade.ComputedValue("--y"));
+
+ cascade.Add("--x", "initial");
+ cascade.Add("--y", "initial");
+ cascade.Apply();
+
+ EXPECT_FALSE(cascade.ComputedValue("--x"));
+ EXPECT_FALSE(cascade.ComputedValue("--y"));
+}
+
+TEST_F(StyleCascadeTest, Inherit) {
+ TestCascade parent(GetDocument());
+ parent.Add("--x", "foo");
+ parent.Apply();
+
+ TestCascade cascade(GetDocument());
+ cascade.InheritFrom(parent.TakeStyle());
+
+ EXPECT_EQ("foo", cascade.ComputedValue("--x"));
+
+ cascade.Add("--x", "bar");
+ cascade.Apply();
+ EXPECT_EQ("bar", cascade.ComputedValue("--x"));
+
+ cascade.Add("--x", "inherit");
+ cascade.Apply();
+ EXPECT_EQ("foo", cascade.ComputedValue("--x"));
+}
+
+TEST_F(StyleCascadeTest, Unset) {
+ TestCascade parent(GetDocument());
+ parent.Add("--x", "foo");
+ parent.Apply();
+
+ TestCascade cascade(GetDocument());
+ cascade.InheritFrom(parent.TakeStyle());
+ EXPECT_EQ("foo", cascade.ComputedValue("--x"));
+
+ cascade.Add("--x", "bar");
+ cascade.Apply();
+ EXPECT_EQ("bar", cascade.ComputedValue("--x"));
+
+ cascade.Add("--x", "unset");
+ cascade.Apply();
+ EXPECT_EQ("foo", cascade.ComputedValue("--x"));
+}
+
+TEST_F(StyleCascadeTest, RegisteredInitial) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "0px", false);
+
+ TestCascade cascade(GetDocument());
+ cascade.Apply();
+ EXPECT_EQ("0px", cascade.ComputedValue("--x"));
+}
+
+TEST_F(StyleCascadeTest, SubstituteRegisteredImplicitInitialValue) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "13px", false);
+
+ TestCascade cascade(GetDocument());
+ cascade.Add("--y", " var(--x) ");
+ cascade.Apply();
+ EXPECT_EQ("13px", cascade.ComputedValue("--x"));
+ EXPECT_EQ(" 13px ", cascade.ComputedValue("--y"));
+}
+
+TEST_F(StyleCascadeTest, SubstituteRegisteredUniversal) {
+ RegisterProperty(GetDocument(), "--x", "*", "foo", false);
+
+ TestCascade cascade(GetDocument());
+ cascade.Add("--x", "bar");
+ cascade.Add("--y", "var(--x)");
+ cascade.Apply();
+ EXPECT_EQ("bar", cascade.ComputedValue("--x"));
+ EXPECT_EQ("bar", cascade.ComputedValue("--y"));
+}
+
+TEST_F(StyleCascadeTest, SubstituteRegisteredUniversalInvalid) {
+ RegisterProperty(GetDocument(), "--x", "*", g_null_atom, false);
+
+ TestCascade cascade(GetDocument());
+ cascade.Add("--y", " var(--x) ");
+ cascade.Apply();
+ EXPECT_FALSE(cascade.ComputedValue("--x"));
+ EXPECT_FALSE(cascade.ComputedValue("--y"));
+}
+
+TEST_F(StyleCascadeTest, SubstituteRegisteredUniversalInitial) {
+ RegisterProperty(GetDocument(), "--x", "*", "foo", false);
+
+ TestCascade cascade(GetDocument());
+ cascade.Add("--y", " var(--x) ");
+ cascade.Apply();
+ EXPECT_EQ("foo", cascade.ComputedValue("--x"));
+ EXPECT_EQ(" foo ", cascade.ComputedValue("--y"));
+}
+
+TEST_F(StyleCascadeTest, RegisteredExplicitInitial) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "0px", false);
+
+ TestCascade cascade(GetDocument());
+ cascade.Add("--x", "10px");
+ cascade.Apply();
+ EXPECT_EQ("10px", cascade.ComputedValue("--x"));
+
+ cascade.Add("--x", "initial");
+ cascade.Add("--y", "var(--x)");
+ cascade.Apply();
+ EXPECT_EQ("0px", cascade.ComputedValue("--x"));
+ EXPECT_EQ("0px", cascade.ComputedValue("--y"));
+}
+
+TEST_F(StyleCascadeTest, RegisteredExplicitInherit) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "0px", false);
+
+ TestCascade parent(GetDocument());
+ parent.Add("--x", "15px");
+ parent.Apply();
+ EXPECT_EQ("15px", parent.ComputedValue("--x"));
+
+ TestCascade cascade(GetDocument());
+ cascade.InheritFrom(parent.TakeStyle());
+ cascade.Apply();
+ EXPECT_EQ("0px", cascade.ComputedValue("--x")); // Note: inherit==false
+
+ cascade.Add("--x", "inherit");
+ cascade.Add("--y", "var(--x)");
+ cascade.Apply();
+ EXPECT_EQ("15px", cascade.ComputedValue("--x"));
+ EXPECT_EQ("15px", cascade.ComputedValue("--y"));
+}
+
+TEST_F(StyleCascadeTest, RegisteredExplicitUnset) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "0px", false);
+ RegisterProperty(GetDocument(), "--y", "<length>", "0px", true);
+
+ TestCascade parent(GetDocument());
+ parent.Add("--x", "15px");
+ parent.Add("--y", "15px");
+ parent.Apply();
+ EXPECT_EQ("15px", parent.ComputedValue("--x"));
+ EXPECT_EQ("15px", parent.ComputedValue("--y"));
+
+ TestCascade cascade(GetDocument());
+ cascade.InheritFrom(parent.TakeStyle());
+ cascade.Add("--x", "2px");
+ cascade.Add("--y", "2px");
+ cascade.Apply();
+ EXPECT_EQ("2px", cascade.ComputedValue("--x"));
+ EXPECT_EQ("2px", cascade.ComputedValue("--y"));
+
+ cascade.Add("--x", "unset");
+ cascade.Add("--y", "unset");
+ cascade.Add("--z", "var(--x) var(--y)");
+ cascade.Apply();
+ EXPECT_EQ("0px", cascade.ComputedValue("--x"));
+ EXPECT_EQ("15px", cascade.ComputedValue("--y"));
+ EXPECT_EQ("0px 15px", cascade.ComputedValue("--z"));
+}
+
+TEST_F(StyleCascadeTest, SubstituteAnimationTaintedInCustomProperty) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("--x", "15px", Origin::kAuthor, AnimationTainted::kYes);
+ cascade.Add("--y", "var(--x)");
+ cascade.Apply();
+ EXPECT_EQ("15px", cascade.ComputedValue("--x"));
+ EXPECT_EQ("15px", cascade.ComputedValue("--y"));
+}
+
+TEST_F(StyleCascadeTest, SubstituteAnimationTaintedInStandardProperty) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("--x", "15px", Origin::kAuthor, AnimationTainted::kYes);
+ cascade.Add("width", "var(--x)");
+ cascade.Apply();
+ EXPECT_EQ("15px", cascade.ComputedValue("--x"));
+ EXPECT_EQ("15px", cascade.ComputedValue("width"));
+}
+
+TEST_F(StyleCascadeTest, SubstituteAnimationTaintedInAnimationProperty) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("--x", "20s");
+ cascade.Add("animation-duration", "var(--x)");
+ cascade.Apply();
+
+ EXPECT_EQ("20s", cascade.ComputedValue("--x"));
+ EXPECT_EQ("20s", cascade.ComputedValue("animation-duration"));
+
+ cascade.Add("--y", "20s", Origin::kAuthor, AnimationTainted::kYes);
+ cascade.Add("animation-duration", "var(--y)");
+ cascade.Apply();
+
+ EXPECT_EQ("20s", cascade.ComputedValue("--y"));
+ EXPECT_EQ("0s", cascade.ComputedValue("animation-duration"));
+}
+
+TEST_F(StyleCascadeTest, IndirectlyAnimationTainted) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("--x", "20s", Origin::kAuthor, AnimationTainted::kYes);
+ cascade.Add("--y", "var(--x)");
+ cascade.Add("animation-duration", "var(--y)");
+ cascade.Apply();
+
+ EXPECT_EQ("20s", cascade.ComputedValue("--x"));
+ EXPECT_EQ("20s", cascade.ComputedValue("--y"));
+ EXPECT_EQ("0s", cascade.ComputedValue("animation-duration"));
+}
+
+TEST_F(StyleCascadeTest, AnimationTaintedFallback) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("--x", "20s", Origin::kAuthor, AnimationTainted::kYes);
+ cascade.Add("animation-duration", "var(--x,1s)");
+ cascade.Apply();
+
+ EXPECT_EQ("20s", cascade.ComputedValue("--x"));
+ EXPECT_EQ("1s", cascade.ComputedValue("animation-duration"));
+}
+
+TEST_F(StyleCascadeTest, EnvMissingNestedVar) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("--x", "rgb(0, 0, 0)");
+ cascade.Add("background-color", "env(missing, var(--x))");
+ cascade.Apply();
+
+ EXPECT_EQ("rgb(0, 0, 0)", cascade.ComputedValue("--x"));
+ EXPECT_EQ("rgb(0, 0, 0)", cascade.ComputedValue("background-color"));
+}
+
+TEST_F(StyleCascadeTest, EnvMissingNestedVarFallback) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("background-color", "env(missing, var(--missing, blue))");
+ cascade.Apply();
+
+ EXPECT_EQ("rgb(0, 0, 255)", cascade.ComputedValue("background-color"));
+}
+
+TEST_F(StyleCascadeTest, EnvMissingFallback) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("background-color", "env(missing, blue)");
+ cascade.Apply();
+
+ EXPECT_EQ("rgb(0, 0, 255)", cascade.ComputedValue("background-color"));
+}
+
+TEST_F(StyleCascadeTest, ValidEnv) {
+ AutoEnv env(*this, "test", "red");
+
+ TestCascade cascade(GetDocument());
+ cascade.Add("background-color", "env(test, blue)");
+ cascade.Apply();
+
+ EXPECT_EQ("rgb(255, 0, 0)", cascade.ComputedValue("background-color"));
+}
+
+TEST_F(StyleCascadeTest, ValidEnvFallback) {
+ AutoEnv env(*this, "test", "red");
+
+ TestCascade cascade(GetDocument());
+ cascade.Add("background-color", "env(test, blue)");
+ cascade.Apply();
+
+ EXPECT_EQ("rgb(255, 0, 0)", cascade.ComputedValue("background-color"));
+}
+
+TEST_F(StyleCascadeTest, ValidEnvInUnusedFallback) {
+ AutoEnv env(*this, "test", "red");
+
+ TestCascade cascade(GetDocument());
+ cascade.Add("--x", "rgb(0, 0, 0)");
+ cascade.Add("background-color", "var(--x, env(test))");
+ cascade.Apply();
+
+ EXPECT_EQ("rgb(0, 0, 0)", cascade.ComputedValue("--x"));
+ EXPECT_EQ("rgb(0, 0, 0)", cascade.ComputedValue("background-color"));
+}
+
+TEST_F(StyleCascadeTest, ValidEnvInUsedFallback) {
+ AutoEnv env(*this, "test", "red");
+
+ TestCascade cascade(GetDocument());
+ cascade.Add("background-color", "var(--missing, env(test))");
+ cascade.Apply();
+
+ EXPECT_EQ("rgb(255, 0, 0)", cascade.ComputedValue("background-color"));
+}
+
+// An Animator that just records the name of all the properties
+// applied.
+class RecordingAnimator : public StyleCascade::Animator {
+ public:
+ void Apply(const CSSProperty& property,
+ const cssvalue::CSSPendingInterpolationValue&,
+ StyleCascade::Resolver& resolver) override {
+ record.push_back(property.GetCSSPropertyName());
+ }
+
+ Vector<CSSPropertyName> record;
+};
+
+TEST_F(StyleCascadeTest, AnimatorCalledByPendingInterpolationValue) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "0px", false);
+
+ RecordingAnimator animator;
+
+ using Type = CSSPendingInterpolationValue::Type;
+ TestCascade cascade(GetDocument());
+ cascade.Add("--x", CSSPendingInterpolationValue::Create(Type::kCSSProperty));
+ cascade.Add("--y", CSSPendingInterpolationValue::Create(Type::kCSSProperty));
+
+ cascade.Apply(animator);
+
+ EXPECT_TRUE(animator.record.Contains(*CSSPropertyName::From("--x")));
+ EXPECT_TRUE(animator.record.Contains(*CSSPropertyName::From("--y")));
+}
+
+TEST_F(StyleCascadeTest, PendingKeyframeAnimation) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "0px", false);
+
+ AppendSheet(R"HTML(
+ @keyframes test {
+ from { --x: 10px; }
+ to { --x: 20px; }
+ }
+ )HTML");
+
+ TestCascade cascade(GetDocument());
+
+ cascade.Add("animation-name", "test");
+ cascade.Add("animation-duration", "1s");
+ cascade.Apply();
+
+ cascade.AddAnimations();
+
+ EXPECT_EQ("<interpolation>", cascade.GetValue("--x"));
+}
+
+TEST_F(StyleCascadeTest, PendingKeyframeAnimationApply) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "0px", false);
+
+ AppendSheet(R"HTML(
+ @keyframes test {
+ from { --x: 10px; }
+ to { --x: 20px; }
+ }
+ )HTML");
+
+ TestCascade cascade(GetDocument());
+
+ cascade.Add("animation-name", "test");
+ cascade.Add("animation-duration", "10s");
+ cascade.Add("animation-timing-function", "linear");
+ cascade.Add("animation-delay", "-5s");
+ cascade.Apply();
+
+ cascade.AddAnimations();
+
+ EXPECT_EQ("<interpolation>", cascade.GetValue("--x"));
+ StyleAnimator animator(cascade.State(), cascade.InnerCascade());
+ cascade.Apply(animator);
+ EXPECT_EQ("15px", cascade.ComputedValue("--x"));
+}
+
+TEST_F(StyleCascadeTest, TransitionCausesInterpolationValue) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "0px", false);
+
+ // First, simulate an "old style".
+ TestCascade cascade1(GetDocument());
+ cascade1.Add("--x", "10px");
+ cascade1.Add("transition", "--x 1s");
+ cascade1.Apply();
+
+ // Set the old style on the element, so that the animation
+ // update detects it.
+ GetDocument().body()->SetComputedStyle(cascade1.TakeStyle());
+
+ // Now simulate a new style, with a new value for --x.
+ TestCascade cascade2(GetDocument());
+ cascade2.Add("--x", "20px");
+ cascade2.Add("transition", "--x 1s");
+ cascade2.Apply();
+
+ // Detects transitions, and adds CSSPendingInterpolationValues
+ // to the cascade, as appropriate.
+ cascade2.AddTransitions();
+
+ EXPECT_EQ("<interpolation>", cascade2.GetValue("--x"));
+}
+
+TEST_F(StyleCascadeTest, TransitionDetectedForChangedFontSize) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "0px", false);
+
+ TestCascade cascade1(GetDocument());
+ cascade1.Add("font-size", "10px");
+ cascade1.Add("--x", "10em");
+ cascade1.Add("width", "10em");
+ cascade1.Add("height", "10px");
+ cascade1.Add("transition", "--x 1s, width 1s");
+ cascade1.Apply();
+
+ GetDocument().body()->SetComputedStyle(cascade1.TakeStyle());
+
+ TestCascade cascade2(GetDocument());
+ cascade2.Add("font-size", "20px");
+ cascade2.Add("--x", "10em");
+ cascade2.Add("width", "10em");
+ cascade2.Add("height", "10px");
+ cascade2.Add("transition", "--x 1s, width 1s");
+ cascade2.Apply();
+
+ cascade2.AddTransitions();
+
+ EXPECT_EQ("<interpolation>", cascade2.GetValue("--x"));
+ EXPECT_EQ("<interpolation>", cascade2.GetValue("width"));
+ EXPECT_EQ("10px", cascade2.ComputedValue("height"));
+}
+
+TEST_F(StyleCascadeTest, AnimatingVarReferences) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "0px", false);
+
+ AppendSheet(R"HTML(
+ @keyframes test {
+ from { --x: var(--from); }
+ to { --x: var(--to); }
+ }
+ )HTML");
+
+ TestCascade cascade(GetDocument());
+
+ cascade.Add("animation-name", "test");
+ cascade.Add("animation-duration", "10s");
+ cascade.Add("animation-timing-function", "linear");
+ cascade.Add("animation-delay", "-5s");
+ cascade.Apply();
+
+ StyleAnimator animator(cascade.State(), cascade.InnerCascade());
+
+ cascade.AddAnimations();
+ cascade.Add("--from", "10px");
+ cascade.Add("--to", "20px");
+ cascade.Add("--y", "var(--x)");
+ cascade.Apply(animator);
+
+ EXPECT_EQ("15px", cascade.ComputedValue("--x"));
+ EXPECT_EQ("15px", cascade.ComputedValue("--y"));
+}
+
+TEST_F(StyleCascadeTest, AnimateStandardProperty) {
+ AppendSheet(R"HTML(
+ @keyframes test {
+ from { width: 10px; }
+ to { width: 20px; }
+ }
+ )HTML");
+
+ TestCascade cascade(GetDocument());
+
+ cascade.Add("animation-name", "test");
+ cascade.Add("animation-duration", "10s");
+ cascade.Add("animation-timing-function", "linear");
+ cascade.Add("animation-delay", "-5s");
+ cascade.Apply();
+
+ StyleAnimator animator(cascade.State(), cascade.InnerCascade());
+
+ cascade.AddAnimations();
+ EXPECT_EQ("<interpolation>", cascade.GetValue("width"));
+
+ cascade.Apply(animator);
+ EXPECT_EQ("15px", cascade.ComputedValue("width"));
+}
+
+TEST_F(StyleCascadeTest, EmRespondsToAnimatedFontSize) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "0px", false);
+
+ AppendSheet(R"HTML(
+ @keyframes test {
+ from { font-size: 10px; }
+ to { font-size: 20px; }
+ }
+ )HTML");
+
+ TestCascade cascade(GetDocument());
+
+ cascade.Add("animation-name", "test");
+ cascade.Add("animation-duration", "10s");
+ cascade.Add("animation-timing-function", "linear");
+ cascade.Add("animation-delay", "-5s");
+ cascade.Apply();
+
+ StyleAnimator animator(cascade.State(), cascade.InnerCascade());
+
+ cascade.AddAnimations();
+ cascade.Add("--x", "2em");
+ cascade.Add("width", "10em");
+
+ cascade.Apply(animator);
+ EXPECT_EQ("30px", cascade.ComputedValue("--x"));
+ EXPECT_EQ("150px", cascade.ComputedValue("width"));
+}
+
+TEST_F(StyleCascadeTest, AnimateStandardPropertyWithVar) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "0px", false);
+
+ AppendSheet(R"HTML(
+ @keyframes test {
+ from { width: var(--from); }
+ to { width: var(--to); }
+ }
+ )HTML");
+
+ TestCascade cascade(GetDocument());
+
+ cascade.Add("animation-name", "test");
+ cascade.Add("animation-duration", "10s");
+ cascade.Add("animation-timing-function", "linear");
+ cascade.Add("animation-delay", "-5s");
+ cascade.Apply();
+
+ StyleAnimator animator(cascade.State(), cascade.InnerCascade());
+
+ cascade.AddAnimations();
+ cascade.Add("--from", "10px");
+ cascade.Add("--to", "20px");
+
+ cascade.Apply(animator);
+ EXPECT_EQ("15px", cascade.ComputedValue("width"));
+}
+
+TEST_F(StyleCascadeTest, AnimateStandardShorthand) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "0px", false);
+
+ AppendSheet(R"HTML(
+ @keyframes test {
+ from { margin: 10px; }
+ to { margin: 20px; }
+ }
+ )HTML");
+
+ TestCascade cascade(GetDocument());
+
+ cascade.Add("animation-name", "test");
+ cascade.Add("animation-duration", "10s");
+ cascade.Add("animation-timing-function", "linear");
+ cascade.Add("animation-delay", "-5s");
+ cascade.Apply();
+
+ StyleAnimator animator(cascade.State(), cascade.InnerCascade());
+
+ cascade.AddAnimations();
+ EXPECT_EQ("<interpolation>", cascade.GetValue("margin-top"));
+ EXPECT_EQ("<interpolation>", cascade.GetValue("margin-right"));
+ EXPECT_EQ("<interpolation>", cascade.GetValue("margin-bottom"));
+ EXPECT_EQ("<interpolation>", cascade.GetValue("margin-left"));
+
+ cascade.Apply(animator);
+ EXPECT_EQ("15px", cascade.ComputedValue("margin-top"));
+ EXPECT_EQ("15px", cascade.ComputedValue("margin-right"));
+ EXPECT_EQ("15px", cascade.ComputedValue("margin-bottom"));
+ EXPECT_EQ("15px", cascade.ComputedValue("margin-left"));
+}
+
+TEST_F(StyleCascadeTest, AnimatePendingSubstitutionValue) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "0px", false);
+
+ AppendSheet(R"HTML(
+ @keyframes test {
+ from { margin: var(--from); }
+ to { margin: var(--to); }
+ }
+ )HTML");
+
+ TestCascade cascade(GetDocument());
+
+ cascade.Add("animation-name", "test");
+ cascade.Add("animation-duration", "10s");
+ cascade.Add("animation-timing-function", "linear");
+ cascade.Add("animation-delay", "-5s");
+ cascade.Apply();
+
+ StyleAnimator animator(cascade.State(), cascade.InnerCascade());
+
+ cascade.AddAnimations();
+ cascade.Add("--from", "10px");
+ cascade.Add("--to", "20px");
+ EXPECT_EQ("<interpolation>", cascade.GetValue("margin-top"));
+ EXPECT_EQ("<interpolation>", cascade.GetValue("margin-right"));
+ EXPECT_EQ("<interpolation>", cascade.GetValue("margin-bottom"));
+ EXPECT_EQ("<interpolation>", cascade.GetValue("margin-left"));
+
+ cascade.Apply(animator);
+ EXPECT_EQ("15px", cascade.ComputedValue("margin-top"));
+ EXPECT_EQ("15px", cascade.ComputedValue("margin-right"));
+ EXPECT_EQ("15px", cascade.ComputedValue("margin-bottom"));
+ EXPECT_EQ("15px", cascade.ComputedValue("margin-left"));
+}
+
+TEST_F(StyleCascadeTest, ForeignObjectZoomVsEffectiveZoom) {
+ GetDocument().body()->SetInnerHTMLFromString(R"HTML(
+ <svg>
+ <foreignObject id='foreign'></foreignObject>
+ </svg>
+ )HTML");
+ UpdateAllLifecyclePhasesForTest();
+
+ Element* foreign_object = GetDocument().getElementById("foreign");
+ ASSERT_TRUE(foreign_object);
+
+ TestCascade cascade(GetDocument(), foreign_object);
+
+ cascade.Add("zoom", "200%");
+ // TODO(andruud): Can't use CSSPropertyName to get -internal properties
+ // yet.
+ cascade.Add(CSSPropertyName(CSSPropertyID::kInternalEffectiveZoom),
+ "initial");
+ cascade.Apply();
+
+ // If both zoom and -internal-zoom exists in the cascade,
+ // -internal-effective-zoom should win.
+ EXPECT_EQ(1.0f, cascade.TakeStyle()->EffectiveZoom());
+}
+
+TEST_F(StyleCascadeTest, ZoomCascadeOrder) {
+ CSSPropertyName effective_zoom(CSSPropertyID::kInternalEffectiveZoom);
+ TestCascade cascade(GetDocument());
+ cascade.Add("zoom", "200%");
+ cascade.Add(effective_zoom, "initial");
+ cascade.Apply();
+
+ EXPECT_EQ(1.0f, cascade.TakeStyle()->EffectiveZoom());
+}
+
+TEST_F(StyleCascadeTest, ZoomReversedCascadeOrder) {
+ CSSPropertyName effective_zoom(CSSPropertyID::kInternalEffectiveZoom);
+ TestCascade cascade(GetDocument());
+ cascade.Add(effective_zoom, "initial");
+ cascade.Add("zoom", "200%");
+ cascade.Apply();
+
+ EXPECT_EQ(2.0f, cascade.TakeStyle()->EffectiveZoom());
+}
+
+TEST_F(StyleCascadeTest, ZoomPriority) {
+ CSSPropertyName effective_zoom(CSSPropertyID::kInternalEffectiveZoom);
+ TestCascade cascade(GetDocument());
+ cascade.Add("zoom", "200%", Origin::kImportantAuthor);
+ cascade.Add(effective_zoom, "initial");
+ cascade.Apply();
+
+ EXPECT_EQ(2.0f, cascade.TakeStyle()->EffectiveZoom());
+}
+
+TEST_F(StyleCascadeTest, WritingModeCascadeOrder) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("writing-mode", "vertical-lr");
+ cascade.Add("-webkit-writing-mode", "vertical-rl");
+ cascade.Apply();
+
+ EXPECT_EQ("vertical-rl", cascade.ComputedValue("writing-mode"));
+ EXPECT_EQ("vertical-rl", cascade.ComputedValue("-webkit-writing-mode"));
+}
+
+TEST_F(StyleCascadeTest, WritingModeReversedCascadeOrder) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("-webkit-writing-mode", "vertical-rl");
+ cascade.Add("writing-mode", "vertical-lr");
+ cascade.Apply();
+
+ EXPECT_EQ("vertical-lr", cascade.ComputedValue("writing-mode"));
+ EXPECT_EQ("vertical-lr", cascade.ComputedValue("-webkit-writing-mode"));
+}
+
+TEST_F(StyleCascadeTest, WritingModePriority) {
+ TestCascade cascade(GetDocument());
+ cascade.Add("writing-mode", "vertical-lr", Origin::kImportantAuthor);
+ cascade.Add("-webkit-writing-mode", "vertical-rl", Origin::kAuthor);
+ cascade.Apply();
+
+ EXPECT_EQ("vertical-lr", cascade.ComputedValue("writing-mode"));
+ EXPECT_EQ("vertical-lr", cascade.ComputedValue("-webkit-writing-mode"));
+}
+
+TEST_F(StyleCascadeTest, MarkReferenced) {
+ RegisterProperty(GetDocument(), "--x", "<length>", "0px", false);
+ RegisterProperty(GetDocument(), "--y", "<length>", "0px", false);
+
+ TestCascade cascade(GetDocument());
+ cascade.Add("width", "var(--x)");
+ cascade.Apply();
+
+ const auto* registry = GetDocument().GetPropertyRegistry();
+ ASSERT_TRUE(registry);
+
+ EXPECT_TRUE(registry->WasReferenced("--x"));
+ EXPECT_FALSE(registry->WasReferenced("--y"));
+}
+
+TEST_F(StyleCascadeTest, InternalVisitedColorLonghand) {
+ CSSPropertyName visited_color(CSSPropertyID::kInternalVisitedColor);
+
+ TestCascade cascade(GetDocument());
+ cascade.Add(visited_color, "red");
+ cascade.Add("color", "green");
+ cascade.Apply();
+
+ cascade.State().Style()->SetInsideLink(EInsideLink::kInsideVisitedLink);
+
+ EXPECT_EQ("rgb(0, 128, 0)", cascade.ComputedValue("color"));
+
+ Color red(255, 0, 0);
+ const CSSProperty& color = GetCSSPropertyColor();
+ EXPECT_EQ(red, cascade.TakeStyle()->VisitedDependentColor(color));
+}
+
+TEST_F(StyleCascadeTest, VarInInternalVisitedShorthand) {
+ CSSPropertyName visited_outline_color(
+ CSSPropertyID::kInternalVisitedOutlineColor);
+
+ TestCascade cascade(GetDocument());
+ cascade.Add("--x", "green");
+ cascade.Add("outline", "medium solid var(--x)");
+
+ // Copy pending substitution value from outline-color to
+ // -internal-visited-outline-color, approximating StyleResolver's behavior
+ // for :visited declarations.
+ const CSSValue* pending_substitution = cascade.GetCSSValue("outline-color");
+ ASSERT_TRUE(pending_substitution);
+ cascade.Add(visited_outline_color, pending_substitution);
+ cascade.Add("outline-color", "red");
+
+ // Apply "outline-color" manually first, to ensure that
+ // -internal-visited-outline-color is applied afterwards.
+ cascade.Apply("outline-color");
+
+ // When applying -internal-visited-outline-color, it should not modify
+ // outline-color.
+ cascade.Apply();
+
+ cascade.State().Style()->SetInsideLink(EInsideLink::kInsideVisitedLink);
+
+ EXPECT_EQ("rgb(255, 0, 0)", cascade.ComputedValue("outline-color"));
+
+ Color green(0, 128, 0);
+ const CSSProperty& outline_color = GetCSSPropertyOutlineColor();
+ EXPECT_EQ(green, cascade.TakeStyle()->VisitedDependentColor(outline_color));
+}
+
+} // namespace blink
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 6a77809f067..6ec8f2f90c2 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
@@ -38,13 +38,13 @@
#include "third_party/blink/renderer/core/animation/invalidatable_interpolation.h"
#include "third_party/blink/renderer/core/animation/keyframe_effect.h"
#include "third_party/blink/renderer/core/animation/transition_interpolation.h"
-#include "third_party/blink/renderer/core/css/css_calculation_value.h"
#include "third_party/blink/renderer/core/css/css_custom_ident_value.h"
#include "third_party/blink/renderer/core/css/css_default_style_sheets.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_keyframe_rule.h"
#include "third_party/blink/renderer/core/css/css_keyframes_rule.h"
+#include "third_party/blink/renderer/core/css/css_pending_interpolation_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/css_reflect_value.h"
@@ -68,6 +68,7 @@
#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_adjuster.h"
+#include "third_party/blink/renderer/core/css/resolver/style_animator.h"
#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/resolver/style_rule_usage_tracker.h"
@@ -82,7 +83,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/frame/settings.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/custom/custom_element_definition.h"
#include "third_party/blink/renderer/core/html/html_iframe_element.h"
#include "third_party/blink/renderer/core/html/html_slot_element.h"
@@ -94,6 +94,7 @@
#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/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
@@ -536,6 +537,12 @@ void StyleResolver::MatchUARules(ElementRuleCollector& collector) {
if (GetDocument().IsViewSource())
MatchRuleSet(collector, default_style_sheets.DefaultViewSourceStyle());
+ // If the system is in forced colors mode, match rules from the forced colors
+ // style sheet.
+ if (blink::RuntimeEnabledFeatures::ForcedColorsEnabled() &&
+ GetDocument().GetSettings()->GetForcedColors() != ForcedColors::kNone)
+ MatchRuleSet(collector, default_style_sheets.DefaultForcedColorStyle());
+
collector.FinishAddingUARules();
collector.SetMatchingUARules(false);
}
@@ -556,16 +563,16 @@ void StyleResolver::MatchAllRules(StyleResolverState& state,
// Now check author rules, beginning first with presentational attributes
// mapped from HTML.
- if (state.GetElement()->IsStyledElement()) {
+ if (state.GetElement().IsStyledElement()) {
collector.AddElementStyleProperties(
- state.GetElement()->PresentationAttributeStyle());
+ state.GetElement().PresentationAttributeStyle());
// Now we check additional mapped declarations.
// Tables and table cells share an additional mapped rule that must be
// applied after all attributes, since their mapped style depends on the
// values of multiple attributes.
collector.AddElementStyleProperties(
- state.GetElement()->AdditionalPresentationAttributeStyle());
+ state.GetElement().AdditionalPresentationAttributeStyle());
if (auto* html_element = DynamicTo<HTMLElement>(state.GetElement())) {
bool is_auto;
@@ -580,18 +587,18 @@ void StyleResolver::MatchAllRules(StyleResolverState& state,
}
}
- MatchAuthorRules(*state.GetElement(), collector);
+ MatchAuthorRules(state.GetElement(), collector);
- if (state.GetElement()->IsStyledElement()) {
+ if (state.GetElement().IsStyledElement()) {
// For Shadow DOM V1, inline style is already collected in
// matchScopedRules().
if (GetDocument().GetShadowCascadeOrder() ==
ShadowCascadeOrder::kShadowCascadeV0 &&
- state.GetElement()->InlineStyle()) {
+ state.GetElement().InlineStyle()) {
// Inline style is immutable as long as there is no CSSOM wrapper.
bool is_inline_style_cacheable =
- !state.GetElement()->InlineStyle()->IsMutable();
- collector.AddElementStyleProperties(state.GetElement()->InlineStyle(),
+ !state.GetElement().InlineStyle()->IsMutable();
+ collector.AddElementStyleProperties(state.GetElement().InlineStyle(),
is_inline_style_cacheable);
}
@@ -861,16 +868,23 @@ CompositorKeyframeValue* StyleResolver::CreateCompositorKeyframeValueSnapshot(
const CSSValue* value) {
// TODO(alancutter): Avoid creating a StyleResolverState just to apply a
// single value on a ComputedStyle.
- StyleResolverState state(element.GetDocument(), &element,
+ StyleResolverState state(element.GetDocument(), element,
nullptr /* pseudo_element */, parent_style,
parent_style);
state.SetStyle(ComputedStyle::Clone(base_style));
if (value) {
- StyleBuilder::ApplyProperty(property.GetCSSPropertyName(), state, *value);
- state.GetFontBuilder().CreateFont(
- state.GetDocument().GetStyleEngine().GetFontSelector(),
- state.StyleRef());
- CSSVariableResolver(state).ResolveVariableDefinitions();
+ if (RuntimeEnabledFeatures::CSSCascadeEnabled()) {
+ StyleCascade cascade(state);
+ auto name = property.GetCSSPropertyName();
+ cascade.Add(name, value, StyleCascade::Origin::kAuthor);
+ cascade.Apply();
+ } else {
+ StyleBuilder::ApplyProperty(property.GetCSSPropertyName(), state, *value);
+ state.GetFontBuilder().CreateFont(
+ state.GetDocument().GetStyleEngine().GetFontSelector(),
+ state.StyleRef());
+ CSSVariableResolver(state).ResolveVariableDefinitions();
+ }
}
return CompositorKeyframeValueFactory::Create(property, *state.Style());
}
@@ -916,7 +930,7 @@ bool StyleResolver::PseudoStyleForElementInternal(
MatchUARules(collector);
MatchUserRules(collector);
- MatchAuthorRules(*state.GetElement(), collector);
+ MatchAuthorRules(state.GetElement(), collector);
collector.FinishAddingAuthorRulesForTreeScope();
if (tracker_)
@@ -965,7 +979,7 @@ scoped_refptr<ComputedStyle> StyleResolver::PseudoStyleForElement(
return nullptr;
StyleResolverState state(
- GetDocument(), element,
+ GetDocument(), *element,
element->GetPseudoElement(pseudo_style_request.pseudo_id), parent_style,
parent_layout_object_style);
if (!PseudoStyleForElementInternal(*element, pseudo_style_request, state)) {
@@ -982,10 +996,13 @@ scoped_refptr<ComputedStyle> StyleResolver::PseudoStyleForElement(
return state.TakeStyle();
}
-scoped_refptr<ComputedStyle> StyleResolver::StyleForPage(int page_index) {
- scoped_refptr<ComputedStyle> initial_style =
+scoped_refptr<const ComputedStyle> StyleResolver::StyleForPage(int page_index) {
+ scoped_refptr<const ComputedStyle> initial_style =
InitialStyleForElement(GetDocument());
- StyleResolverState state(GetDocument(), GetDocument().documentElement(),
+ if (!GetDocument().documentElement())
+ return initial_style;
+
+ StyleResolverState state(GetDocument(), *GetDocument().documentElement(),
nullptr /* pseudo_element */, initial_style.get(),
initial_style.get());
@@ -1058,10 +1075,14 @@ scoped_refptr<ComputedStyle> StyleResolver::InitialStyleForElement(
return initial_style;
}
-scoped_refptr<ComputedStyle> StyleResolver::StyleForText(Text* text_node) {
+scoped_refptr<const ComputedStyle> StyleResolver::StyleForText(
+ Text* text_node) {
DCHECK(text_node);
- if (Node* parent_node = LayoutTreeBuilderTraversal::Parent(*text_node))
- return parent_node->MutableComputedStyle();
+ if (Node* parent_node = LayoutTreeBuilderTraversal::Parent(*text_node)) {
+ const ComputedStyle* style = parent_node->GetComputedStyle();
+ if (style && !style->IsEnsuredInDisplayNone())
+ return style;
+ }
return nullptr;
}
@@ -1081,7 +1102,7 @@ void StyleResolver::AddMatchedRulesToTracker(
StyleRuleList* StyleResolver::StyleRulesForElement(Element* element,
unsigned rules_to_include) {
DCHECK(element);
- StyleResolverState state(GetDocument(), element,
+ StyleResolverState state(GetDocument(), *element,
nullptr /* pseudo_element */);
ElementRuleCollector collector(state.ElementContext(), selector_filter_,
state.Style());
@@ -1096,7 +1117,7 @@ CSSRuleList* StyleResolver::PseudoCSSRulesForElement(
PseudoId pseudo_id,
unsigned rules_to_include) {
DCHECK(element);
- StyleResolverState state(GetDocument(), element,
+ StyleResolverState state(GetDocument(), *element,
nullptr /* pseudo_element */);
ElementRuleCollector collector(state.ElementContext(), selector_filter_,
state.Style());
@@ -1136,13 +1157,13 @@ void StyleResolver::CollectPseudoRulesForElement(
bool StyleResolver::ApplyAnimatedStandardProperties(
StyleResolverState& state,
const Element* animating_element) {
- Element* element = state.GetElement();
- DCHECK(element);
+ Element& element = state.GetElement();
- // The animating element may be this element, or its pseudo element. It is
- // null when calculating the style for a potential pseudo element that has
- // yet to be created.
- DCHECK(animating_element == element || !animating_element ||
+ // The animating element may be this element, the pseudo element we are
+ // resolving style for, or null if we are resolving style for a pseudo
+ // element which is not represented by a PseudoElement like scrollbar pseudo
+ // elements.
+ DCHECK(animating_element == &element || !animating_element ||
animating_element->ParentOrShadowHostElement() == element);
if (state.Style()->Animations() ||
@@ -1154,43 +1175,55 @@ bool StyleResolver::ApplyAnimatedStandardProperties(
}
CSSAnimations::CalculateCompositorAnimationUpdate(
- state.AnimationUpdate(), animating_element, *element, *state.Style(),
+ state.AnimationUpdate(), animating_element, element, *state.Style(),
state.ParentStyle(), WasViewportResized());
CSSAnimations::CalculateTransitionUpdate(
state.AnimationUpdate(), CSSAnimations::PropertyPass::kStandard,
animating_element, *state.Style());
CSSAnimations::SnapshotCompositorKeyframes(
- *element, state.AnimationUpdate(), *state.Style(), state.ParentStyle());
+ element, state.AnimationUpdate(), *state.Style(), state.ParentStyle());
if (state.AnimationUpdate().IsEmpty())
return false;
- if (state.Style()->InsideLink() != EInsideLink::kNotInsideLink) {
- DCHECK(state.ApplyPropertyToRegularStyle());
- state.SetApplyPropertyToVisitedLinkStyle(true);
- }
-
const ActiveInterpolationsMap& animations_map =
state.AnimationUpdate().ActiveInterpolationsForStandardAnimations();
const ActiveInterpolationsMap& transitions_map =
state.AnimationUpdate().ActiveInterpolationsForStandardTransitions();
- ApplyAnimatedStandardProperties<kHighPropertyPriority>(state, animations_map);
- ApplyAnimatedStandardProperties<kHighPropertyPriority>(state,
- transitions_map);
- UpdateFont(state);
+ if (RuntimeEnabledFeatures::CSSCascadeEnabled()) {
+ // TODO(crbug.com/985049): Use main cascade.
+ //
+ // For now, we use a dedicated cascade for animation of standard properties.
+ // A StyleCascade is required, because otherwise we can't resolve any var()
+ // references that may appear in keyframes. Ultimately, we should use ONE
+ // cascade for everything, but this is not yet possible.
+ using Origin = StyleCascade::Origin;
+ StyleCascade cascade(state);
+ StyleAnimator animator(state, cascade);
+ CascadeInterpolations(cascade, animations_map, Origin::kAnimation);
+ CascadeInterpolations(cascade, transitions_map, Origin::kTransition);
+ cascade.Apply(animator);
+ } else {
+ ApplyAnimatedStandardProperties<kHighPropertyPriority>(state,
+ animations_map);
+ ApplyAnimatedStandardProperties<kHighPropertyPriority>(state,
+ transitions_map);
+
+ UpdateFont(state);
- ApplyAnimatedStandardProperties<kLowPropertyPriority>(state, animations_map);
- ApplyAnimatedStandardProperties<kLowPropertyPriority>(state, transitions_map);
+ ApplyAnimatedStandardProperties<kLowPropertyPriority>(state,
+ animations_map);
+ ApplyAnimatedStandardProperties<kLowPropertyPriority>(state,
+ transitions_map);
+ }
// Start loading resources used by animations.
LoadPendingResources(state);
DCHECK(!state.GetFontBuilder().FontDirty());
- state.SetApplyPropertyToVisitedLinkStyle(false);
-
return true;
}
@@ -1450,14 +1483,26 @@ static bool PassesPropertyFilter(ValidPropertyFilter valid_property_filter,
return true;
}
+static inline void ApplyProperty(const CSSProperty& property,
+ StyleResolverState& state,
+ const CSSValue& value,
+ unsigned apply_mask) {
+ if (apply_mask & kApplyMaskRegular)
+ StyleBuilder::ApplyProperty(property, state, value);
+ if (apply_mask & kApplyMaskVisited) {
+ if (const CSSProperty* visited = property.GetVisitedProperty())
+ StyleBuilder::ApplyProperty(*visited, state, value);
+ }
+}
+
// This method expands the 'all' shorthand property to longhand properties
// and applies the expanded longhand properties.
template <CSSPropertyPriority priority>
-void StyleResolver::ApplyAllProperty(
- StyleResolverState& state,
- const CSSValue& all_value,
- bool inherited_only,
- ValidPropertyFilter valid_property_filter) {
+void StyleResolver::ApplyAllProperty(StyleResolverState& state,
+ const CSSValue& all_value,
+ bool inherited_only,
+ ValidPropertyFilter valid_property_filter,
+ unsigned apply_mask) {
// The 'all' property doesn't apply to variables:
// https://drafts.csswg.org/css-variables/#defining-variables
if (priority == kResolveVariables)
@@ -1495,27 +1540,29 @@ void StyleResolver::ApplyAllProperty(
if (inherited_only && !property_class.IsInherited())
continue;
- StyleBuilder::ApplyProperty(property_class, state, all_value);
+ ApplyProperty(property_class, state, all_value, apply_mask);
}
}
template <CSSPropertyPriority priority>
static inline void ApplyProperty(
const CSSPropertyValueSet::PropertyReference& reference,
- StyleResolverState& state) {
+ StyleResolverState& state,
+ unsigned apply_mask) {
static_assert(
priority != kResolveVariables,
"Application of custom properties must use specialized template");
DCHECK_NE(reference.Id(), CSSPropertyID::kVariable);
- StyleBuilder::ApplyProperty(reference.Property(), state, reference.Value());
+ ApplyProperty(reference.Property(), state, reference.Value(), apply_mask);
}
template <>
inline void ApplyProperty<kResolveVariables>(
const CSSPropertyValueSet::PropertyReference& reference,
- StyleResolverState& state) {
+ StyleResolverState& state,
+ unsigned apply_mask) {
CSSPropertyRef ref(reference.Name(), state.GetDocument());
- StyleBuilder::ApplyProperty(ref.GetProperty(), state, reference.Value());
+ ApplyProperty(ref.GetProperty(), state, reference.Value(), apply_mask);
}
template <CSSPropertyPriority priority,
@@ -1525,7 +1572,8 @@ void StyleResolver::ApplyProperties(StyleResolverState& state,
bool is_important,
bool inherited_only,
NeedsApplyPass& needs_apply_pass,
- ValidPropertyFilter valid_property_filter) {
+ ValidPropertyFilter valid_property_filter,
+ unsigned apply_mask) {
unsigned property_count = properties->PropertyCount();
for (unsigned i = 0; i < property_count; ++i) {
CSSPropertyValueSet::PropertyReference current = properties->PropertyAt(i);
@@ -1539,7 +1587,7 @@ void StyleResolver::ApplyProperties(StyleResolverState& state,
needs_apply_pass.Set(kLowPropertyPriority, is_important);
}
ApplyAllProperty<priority>(state, current.Value(), inherited_only,
- valid_property_filter);
+ valid_property_filter, apply_mask);
continue;
}
@@ -1560,19 +1608,33 @@ void StyleResolver::ApplyProperties(StyleResolverState& state,
// here. For this reason we don't allow declarations with explicitly
// inherited properties to be cached.
DCHECK(!current.Value().IsInheritedValue() ||
- (!state.ApplyPropertyToRegularStyle() &&
- (!state.ApplyPropertyToVisitedLinkStyle() ||
- !current.Property().IsValidForVisitedLink())));
+ (!(apply_mask & kApplyMaskRegular) &&
+ (!(apply_mask & kApplyMaskVisited) ||
+ !current.Property().GetVisitedProperty())));
continue;
}
if (!CSSPropertyPriorityData<priority>::PropertyHasPriority(property_id))
continue;
- ApplyProperty<priority>(current, state);
+ ApplyProperty<priority>(current, state, apply_mask);
}
}
+static inline unsigned ComputeApplyMask(
+ StyleResolverState& state,
+ const MatchedProperties& matched_properties) {
+ if (state.Style()->InsideLink() == EInsideLink::kNotInsideLink)
+ return kApplyMaskRegular;
+ static_assert(static_cast<int>(kApplyMaskRegular) ==
+ static_cast<int>(CSSSelector::kMatchLink),
+ "kApplyMaskRegular and kMatchLink must match");
+ static_assert(static_cast<int>(kApplyMaskVisited) ==
+ static_cast<int>(CSSSelector::kMatchVisited),
+ "kApplyMaskVisited and kMatchVisited must match");
+ return matched_properties.types_.link_match_type;
+}
+
template <CSSPropertyPriority priority,
StyleResolver::ShouldUpdateNeedsApplyPass shouldUpdateNeedsApplyPass>
void StyleResolver::ApplyMatchedProperties(StyleResolverState& state,
@@ -1587,32 +1649,14 @@ void StyleResolver::ApplyMatchedProperties(StyleResolverState& state,
!needs_apply_pass.Get(priority, is_important))
return;
- if (state.Style()->InsideLink() != EInsideLink::kNotInsideLink) {
- for (const auto& matched_properties : range) {
- unsigned link_match_type = matched_properties.types_.link_match_type;
- // FIXME: It would be nicer to pass these as arguments but that requires
- // changes in many places.
- state.SetApplyPropertyToRegularStyle(link_match_type &
- CSSSelector::kMatchLink);
- state.SetApplyPropertyToVisitedLinkStyle(link_match_type &
- CSSSelector::kMatchVisited);
-
- ApplyProperties<priority, shouldUpdateNeedsApplyPass>(
- state, matched_properties.properties.Get(), is_important,
- inherited_only, needs_apply_pass,
- static_cast<ValidPropertyFilter>(
- matched_properties.types_.valid_property_filter));
- }
- state.SetApplyPropertyToRegularStyle(true);
- state.SetApplyPropertyToVisitedLinkStyle(false);
- return;
- }
for (const auto& matched_properties : range) {
+ const unsigned apply_mask = ComputeApplyMask(state, matched_properties);
ApplyProperties<priority, shouldUpdateNeedsApplyPass>(
state, matched_properties.properties.Get(), is_important,
inherited_only, needs_apply_pass,
static_cast<ValidPropertyFilter>(
- matched_properties.types_.valid_property_filter));
+ matched_properties.types_.valid_property_filter),
+ apply_mask);
}
}
@@ -1640,8 +1684,7 @@ void StyleResolver::ClearResizedForViewportUnits() {
StyleResolver::CacheSuccess StyleResolver::ApplyMatchedCache(
StyleResolverState& state,
const MatchResult& match_result) {
- const Element* element = state.GetElement();
- DCHECK(element);
+ const Element& element = state.GetElement();
unsigned cache_hash = match_result.IsCacheable()
? ComputeMatchedPropertiesHash(
@@ -1667,8 +1710,8 @@ StyleResolver::CacheSuccess StyleResolver::ApplyMatchedCache(
*cached_matched_properties->computed_style);
if (state.ParentStyle()->InheritedDataShared(
*cached_matched_properties->parent_computed_style) &&
- !IsAtShadowBoundary(element) &&
- (!state.DistributedToV0InsertionPoint() || element->AssignedSlot() ||
+ !IsAtShadowBoundary(&element) &&
+ (!state.DistributedToV0InsertionPoint() || element.AssignedSlot() ||
state.Style()->UserModify() == EUserModify::kReadOnly)) {
INCREMENT_STYLE_STATS_COUNTER(GetDocument().GetStyleEngine(),
matched_property_cache_inherited_hit, 1);
@@ -1740,7 +1783,7 @@ void StyleResolver::CalculateAnimationUpdate(StyleResolverState& state,
DCHECK(!state.IsAnimationInterpolationMapReady());
CSSAnimations::CalculateAnimationUpdate(
- state.AnimationUpdate(), animating_element, *state.GetElement(),
+ state.AnimationUpdate(), animating_element, state.GetElement(),
*state.Style(), state.ParentStyle(), this);
CSSAnimations::CalculateTransitionUpdate(state.AnimationUpdate(),
CSSAnimations::PropertyPass::kCustom,
@@ -1787,20 +1830,6 @@ void StyleResolver::ApplyMatchedHighPriorityProperties(
state, match_result.UaRules(), true, apply_inherited_only,
needs_apply_pass);
- if (UNLIKELY(IsSVGForeignObjectElement(state.GetElement()))) {
- // LayoutSVGRoot handles zooming for the whole SVG subtree, so foreignObject
- // content should not be scaled again.
- //
- // FIXME: The following hijacks the zoom property for foreignObject so that
- // children of foreignObject get the correct font-size in case of zooming.
- // 'zoom' has HighPropertyPriority, along with other font-related properties
- // used as input to the FontBuilder, so resetting it here may cause the
- // FontBuilder to recompute the font used as inheritable font for
- // foreignObject content. If we want to support zoom on foreignObject we'll
- // need to find another way of handling the SVG zoom model.
- state.SetEffectiveZoom(ComputedStyleInitialValues::InitialZoom());
- }
-
if (cache_success.cached_matched_properties &&
cache_success.cached_matched_properties->computed_style
->EffectiveZoom() != state.Style()->EffectiveZoom()) {
@@ -1819,12 +1848,77 @@ void StyleResolver::ApplyMatchedHighPriorityProperties(
apply_inherited_only = false;
}
+void StyleResolver::ApplyMatchedLowPriorityProperties(
+ StyleResolverState& state,
+ const MatchResult& match_result,
+ const CacheSuccess& cache_success,
+ bool& apply_inherited_only,
+ NeedsApplyPass& needs_apply_pass) {
+ // Now do the normal priority UA properties.
+ ApplyMatchedProperties<kLowPropertyPriority, kCheckNeedsApplyPass>(
+ state, match_result.UaRules(), false, apply_inherited_only,
+ needs_apply_pass);
+
+ // Cache the UA properties to pass them to LayoutTheme in
+ // StyleAdjuster::AdjustComputedStyle.
+ state.CacheUserAgentBorderAndBackground();
+
+ // Now do the author and user normal priority properties and all the
+ // !important properties.
+ ApplyMatchedProperties<kLowPropertyPriority, kCheckNeedsApplyPass>(
+ state, match_result.UserRules(), false, apply_inherited_only,
+ needs_apply_pass);
+ ApplyMatchedProperties<kLowPropertyPriority, kCheckNeedsApplyPass>(
+ state, match_result.AuthorRules(), false, apply_inherited_only,
+ needs_apply_pass);
+ for (auto range : ImportantAuthorRanges(match_result)) {
+ ApplyMatchedProperties<kLowPropertyPriority, kCheckNeedsApplyPass>(
+ state, range, true, apply_inherited_only, needs_apply_pass);
+ }
+ for (auto range : ImportantUserRanges(match_result)) {
+ ApplyMatchedProperties<kLowPropertyPriority, kCheckNeedsApplyPass>(
+ state, range, true, apply_inherited_only, needs_apply_pass);
+ }
+ ApplyMatchedProperties<kLowPropertyPriority, kCheckNeedsApplyPass>(
+ state, match_result.UaRules(), true, apply_inherited_only,
+ needs_apply_pass);
+
+ if (state.Style()->HasAppearance() && !apply_inherited_only) {
+ // Check whether the final border and background differs from the cached UA
+ // ones. When there is a partial match in the MatchedPropertiesCache, these
+ // flags will already be set correctly and the value stored in
+ // cacheUserAgentBorderAndBackground is incorrect, so doing this check again
+ // would give the wrong answer.
+ state.Style()->SetHasAuthorBackground(HasAuthorBackground(state));
+ state.Style()->SetHasAuthorBorder(HasAuthorBorder(state));
+ }
+
+ LoadPendingResources(state);
+
+ if (!state.IsAnimatingCustomProperties() &&
+ !cache_success.cached_matched_properties && cache_success.cache_hash &&
+ MatchedPropertiesCache::IsCacheable(state)) {
+ INCREMENT_STYLE_STATS_COUNTER(GetDocument().GetStyleEngine(),
+ matched_property_cache_added, 1);
+ matched_properties_cache_.Add(*state.Style(), *state.ParentStyle(),
+ cache_success.cache_hash,
+ match_result.GetMatchedProperties());
+ }
+
+ DCHECK(!state.GetFontBuilder().FontDirty());
+}
+
void StyleResolver::ApplyMatchedProperties(StyleResolverState& state,
const MatchResult& match_result,
const Element* animating_element) {
INCREMENT_STYLE_STATS_COUNTER(GetDocument().GetStyleEngine(),
matched_property_apply, 1);
+ if (RuntimeEnabledFeatures::CSSCascadeEnabled()) {
+ CascadeAndApplyMatchedProperties(state, match_result, animating_element);
+ return;
+ }
+
CacheSuccess cache_success = ApplyMatchedCache(state, match_result);
bool apply_inherited_only = cache_success.ShouldApplyInheritedOnly();
NeedsApplyPass needs_apply_pass;
@@ -1866,58 +1960,189 @@ void StyleResolver::ApplyMatchedProperties(StyleResolverState& state,
CSSVariableResolver(state).ResolveVariableDefinitions();
- // Now do the normal priority UA properties.
- ApplyMatchedProperties<kLowPropertyPriority, kCheckNeedsApplyPass>(
- state, match_result.UaRules(), false, apply_inherited_only,
- needs_apply_pass);
+ ApplyMatchedLowPriorityProperties(state, match_result, cache_success,
+ apply_inherited_only, needs_apply_pass);
+}
- // Cache the UA properties to pass them to LayoutTheme in
- // StyleAdjuster::AdjustComputedStyle.
- state.CacheUserAgentBorderAndBackground();
+void StyleResolver::CascadeAndApplyMatchedProperties(
+ StyleResolverState& state,
+ const MatchResult& match_result,
+ const Element* animating_element) {
+ DCHECK(RuntimeEnabledFeatures::CSSCascadeEnabled());
- // Now do the author and user normal priority properties and all the
- // !important properties.
- ApplyMatchedProperties<kLowPropertyPriority, kCheckNeedsApplyPass>(
- state, match_result.UserRules(), false, apply_inherited_only,
- needs_apply_pass);
- ApplyMatchedProperties<kLowPropertyPriority, kCheckNeedsApplyPass>(
- state, match_result.AuthorRules(), false, apply_inherited_only,
- needs_apply_pass);
- for (auto range : ImportantAuthorRanges(match_result)) {
- ApplyMatchedProperties<kLowPropertyPriority, kCheckNeedsApplyPass>(
- state, range, true, apply_inherited_only, needs_apply_pass);
+ CacheSuccess cache_success = ApplyMatchedCache(state, match_result);
+
+ StyleCascade cascade(state);
+ CascadeMatchResult(state, cascade, match_result);
+
+ // We need to copy the entire cascade before applying, in case there are
+ // animations.
+ //
+ // TODO(crbug.com/985010): Avoid this copy with non-destructive Apply.
+ StyleCascade cascade_copy(cascade);
+ cascade_copy.RemoveAnimationPriority();
+
+ if (!cache_success.IsFullCacheHit())
+ cascade.Apply();
+
+ if (HasAnimationsOrTransitions(state, animating_element)) {
+ CalculateAnimationUpdate(state, animating_element);
+
+ // Add animation effects for custom properties to the cascade.
+ if (state.IsAnimatingCustomProperties()) {
+ cache_success.SetFailed();
+ CascadeAnimations(state, cascade_copy);
+ CascadeTransitions(state, cascade_copy);
+ StyleAnimator animator(state, cascade_copy);
+ cascade_copy.Apply(animator);
+ }
}
- for (auto range : ImportantUserRanges(match_result)) {
- ApplyMatchedProperties<kLowPropertyPriority, kCheckNeedsApplyPass>(
- state, range, true, apply_inherited_only, needs_apply_pass);
+
+ if (cache_success.IsFullCacheHit())
+ return;
+
+ // TODO(crbug.com/985025): We only support full cache hits for now.
+ bool apply_inherited_only = false;
+
+ // TODO(crbug.com/985027): Cascade kLowPropertyPriority.
+ //
+ // Ultimately NeedsApplyPass will be removed, so we don't bother fixing
+ // that for this codepath. For now, just always go through the low-priority
+ // properties.
+ const bool important = true;
+ NeedsApplyPass needs_apply_pass;
+ needs_apply_pass.Set(kLowPropertyPriority, important);
+ needs_apply_pass.Set(kLowPropertyPriority, !important);
+ ApplyMatchedLowPriorityProperties(state, match_result, cache_success,
+ apply_inherited_only, needs_apply_pass);
+}
+
+static void CascadeDeclaration(StyleCascade& cascade,
+ const CSSPropertyName& name,
+ const CSSValue& value,
+ StyleCascade::Priority priority,
+ unsigned apply_mask) {
+ if (apply_mask & kApplyMaskRegular)
+ cascade.Add(name, &value, priority);
+ if (apply_mask & kApplyMaskVisited) {
+ const CSSProperty* visited =
+ CSSProperty::Get(name.Id()).GetVisitedProperty();
+ if (visited)
+ cascade.Add(visited->GetCSSPropertyName(), &value, priority);
}
- ApplyMatchedProperties<kLowPropertyPriority, kCheckNeedsApplyPass>(
- state, match_result.UaRules(), true, apply_inherited_only,
- needs_apply_pass);
+}
- if (state.Style()->HasAppearance() && !apply_inherited_only) {
- // Check whether the final border and background differs from the cached UA
- // ones. When there is a partial match in the MatchedPropertiesCache, these
- // flags will already be set correctly and the value stored in
- // cacheUserAgentBorderAndBackground is incorrect, so doing this check again
- // would give the wrong answer.
- state.Style()->SetHasAuthorBackground(HasAuthorBackground(state));
- state.Style()->SetHasAuthorBorder(HasAuthorBorder(state));
+// https://drafts.csswg.org/css-cascade/#all-shorthand
+static void CascadeAll(StyleResolverState& state,
+ StyleCascade& cascade,
+ StyleCascade::Priority priority,
+ unsigned apply_mask,
+ ValidPropertyFilter filter,
+ const CSSValue& value) {
+ for (CSSPropertyID property_id : CSSPropertyIDList()) {
+ using LowPrioData = CSSPropertyPriorityData<kLowPropertyPriority>;
+ if (LowPrioData::PropertyHasPriority(property_id))
+ continue;
+
+ const CSSProperty& property = CSSProperty::Get(property_id);
+
+ if (property.IsShorthand())
+ continue;
+ if (!property.IsAffectedByAll())
+ continue;
+ if (!PassesPropertyFilter(filter, property_id, state.GetDocument()))
+ continue;
+
+ CascadeDeclaration(cascade, CSSPropertyName(property_id), value, priority,
+ apply_mask);
}
+}
- LoadPendingResources(state);
+void StyleResolver::CascadeMatchResult(StyleResolverState& state,
+ StyleCascade& cascade,
+ const MatchResult& result) {
+ DCHECK(RuntimeEnabledFeatures::CSSCascadeEnabled());
- if (!state.IsAnimatingCustomProperties() &&
- !cache_success.cached_matched_properties && cache_success.cache_hash &&
- MatchedPropertiesCache::IsCacheable(state)) {
- INCREMENT_STYLE_STATS_COUNTER(GetDocument().GetStyleEngine(),
- matched_property_cache_added, 1);
- matched_properties_cache_.Add(*state.Style(), *state.ParentStyle(),
- cache_success.cache_hash,
- match_result.GetMatchedProperties());
+ using Origin = StyleCascade::Origin;
+ CascadeRange(state, cascade, result.UaRules(), Origin::kUserAgent);
+ CascadeRange(state, cascade, result.AuthorRules(), Origin::kAuthor);
+ CascadeRange(state, cascade, result.UserRules(), Origin::kUser);
+}
+
+void StyleResolver::CascadeRange(StyleResolverState& state,
+ StyleCascade& cascade,
+ const MatchedPropertiesRange& range,
+ StyleCascade::Origin origin) {
+ DCHECK(RuntimeEnabledFeatures::CSSCascadeEnabled());
+
+ if (range.IsEmpty())
+ return;
+
+ for (const auto& matched_properties : range) {
+ auto filter = static_cast<ValidPropertyFilter>(
+ matched_properties.types_.valid_property_filter);
+ uint16_t tree_order = matched_properties.types_.tree_order;
+ unsigned apply_mask = ComputeApplyMask(state, matched_properties);
+ const CSSPropertyValueSet* properties = matched_properties.properties.Get();
+ unsigned property_count = properties->PropertyCount();
+
+ for (unsigned i = 0; i < property_count; ++i) {
+ CSSPropertyValueSet::PropertyReference current =
+ properties->PropertyAt(i);
+ CSSPropertyID property_id = current.Id();
+
+ StyleCascade::Priority priority(origin, tree_order);
+
+ if (current.IsImportant())
+ priority = priority.AddImportance();
+
+ if (property_id == CSSPropertyID::kAll) {
+ CascadeAll(state, cascade, priority, apply_mask, filter,
+ current.Value());
+ continue;
+ }
+
+ using LowPrioData = CSSPropertyPriorityData<kLowPropertyPriority>;
+ if (LowPrioData::PropertyHasPriority(property_id))
+ continue;
+
+ if (!PassesPropertyFilter(filter, property_id, state.GetDocument()))
+ continue;
+
+ CascadeDeclaration(cascade, current.Name(), current.Value(), priority,
+ apply_mask);
+ }
}
+}
- DCHECK(!state.GetFontBuilder().FontDirty());
+void StyleResolver::CascadeTransitions(StyleResolverState& state,
+ StyleCascade& cascade) {
+ const auto& update = state.AnimationUpdate();
+ const auto& map = update.ActiveInterpolationsForCustomTransitions();
+ const auto origin = StyleCascade::Origin::kTransition;
+ CascadeInterpolations(cascade, map, origin);
+}
+
+void StyleResolver::CascadeAnimations(StyleResolverState& state,
+ StyleCascade& cascade) {
+ const auto& update = state.AnimationUpdate();
+ const auto& map = update.ActiveInterpolationsForCustomAnimations();
+ const auto origin = StyleCascade::Origin::kAnimation;
+ CascadeInterpolations(cascade, map, origin);
+}
+
+void StyleResolver::CascadeInterpolations(StyleCascade& cascade,
+ const ActiveInterpolationsMap& map,
+ StyleCascade::Origin origin) {
+ using Type = cssvalue::CSSPendingInterpolationValue::Type;
+ for (const auto& entry : map) {
+ auto name = entry.key.GetCSSPropertyName();
+ Type type = entry.key.IsPresentationAttribute()
+ ? Type::kPresentationAttribute
+ : Type::kCSSProperty;
+ auto* v = cssvalue::CSSPendingInterpolationValue::Create(type);
+ cascade.Add(name, v, origin);
+ }
}
bool StyleResolver::HasAuthorBackground(const StyleResolverState& state) {
@@ -1975,7 +2200,8 @@ void StyleResolver::ApplyCallbackSelectors(StyleResolverState& state) {
// Font properties are also handled by FontStyleResolver outside the main
// thread. If you add/remove properties here, make sure they are also properly
// handled by FontStyleResolver.
-void StyleResolver::ComputeFont(ComputedStyle* style,
+void StyleResolver::ComputeFont(Element& element,
+ ComputedStyle* style,
const CSSPropertyValueSet& property_set) {
static const CSSProperty* properties[7] = {
&GetCSSPropertyFontSize(), &GetCSSPropertyFontFamily(),
@@ -1985,8 +2211,8 @@ void StyleResolver::ComputeFont(ComputedStyle* style,
};
// TODO(timloh): This is weird, the style is being used as its own parent
- StyleResolverState state(GetDocument(), nullptr /* element */,
- nullptr /* pseudo_element */, style, style);
+ StyleResolverState state(GetDocument(), element, nullptr /* pseudo_element */,
+ style, style);
state.SetStyle(style);
for (const CSSProperty* property : properties) {
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 4deba97b21f..c136fb1049a 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
@@ -33,6 +33,7 @@
#include "third_party/blink/renderer/core/css/resolver/css_property_priority.h"
#include "third_party/blink/renderer/core/css/resolver/matched_properties_cache.h"
#include "third_party/blink/renderer/core/css/resolver/style_builder.h"
+#include "third_party/blink/renderer/core/css/resolver/style_cascade.h"
#include "third_party/blink/renderer/core/css/selector_checker.h"
#include "third_party/blink/renderer/core/css/selector_filter.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
@@ -55,6 +56,7 @@ class StyleRuleUsageTracker;
class PropertyHandle;
enum RuleMatchingBehavior { kMatchAllRules, kMatchAllRulesExcludingSMIL };
+enum ApplyMask { kApplyMaskRegular = 1 << 0, kApplyMaskVisited = 1 << 1 };
// This class selects a ComputedStyle for a given element in a document based on
// the document's collection of stylesheets (user styles, author styles, UA
@@ -88,8 +90,8 @@ class CORE_EXPORT StyleResolver final
const ComputedStyle* parent_style,
const ComputedStyle* layout_parent_style);
- scoped_refptr<ComputedStyle> StyleForPage(int page_index);
- scoped_refptr<ComputedStyle> StyleForText(Text*);
+ scoped_refptr<const ComputedStyle> StyleForPage(int page_index);
+ scoped_refptr<const ComputedStyle> StyleForText(Text*);
static scoped_refptr<ComputedStyle> StyleForViewport(Document&);
@@ -120,7 +122,7 @@ class CORE_EXPORT StyleResolver final
unsigned rules_to_include = kAllButEmptyCSSRules);
StyleRuleList* StyleRulesForElement(Element*, unsigned rules_to_include);
- void ComputeFont(ComputedStyle*, const CSSPropertyValueSet&);
+ void ComputeFont(Element&, ComputedStyle*, const CSSPropertyValueSet&);
// FIXME: Rename to reflect the purpose, like didChangeFontSize or something.
void InvalidateMatchedPropertiesCache();
@@ -233,10 +235,31 @@ class CORE_EXPORT StyleResolver final
const CacheSuccess&,
bool& apply_inherited_only,
NeedsApplyPass&);
+ void ApplyMatchedLowPriorityProperties(StyleResolverState&,
+ const MatchResult&,
+ const CacheSuccess&,
+ bool& apply_inherited_only,
+ NeedsApplyPass&);
void ApplyMatchedProperties(StyleResolverState&,
const MatchResult&,
const Element* animating_element);
+ void CascadeAndApplyMatchedProperties(StyleResolverState&,
+ const MatchResult&,
+ const Element* animating_element);
+ void CascadeMatchResult(StyleResolverState&,
+ StyleCascade&,
+ const MatchResult&);
+ void CascadeRange(StyleResolverState&,
+ StyleCascade&,
+ const MatchedPropertiesRange&,
+ StyleCascade::Origin);
+ void CascadeTransitions(StyleResolverState&, StyleCascade&);
+ void CascadeAnimations(StyleResolverState&, StyleCascade&);
+ void CascadeInterpolations(StyleCascade&,
+ const ActiveInterpolationsMap&,
+ StyleCascade::Origin);
+
void CalculateAnimationUpdate(StyleResolverState&,
const Element* animating_element);
@@ -256,7 +279,8 @@ class CORE_EXPORT StyleResolver final
bool is_important,
bool inherited_only,
NeedsApplyPass&,
- ValidPropertyFilter = ValidPropertyFilter::kNoFilter);
+ ValidPropertyFilter,
+ unsigned apply_mask);
template <CSSPropertyPriority priority>
void ApplyAnimatedStandardProperties(StyleResolverState&,
const ActiveInterpolationsMap&);
@@ -264,7 +288,8 @@ class CORE_EXPORT StyleResolver final
void ApplyAllProperty(StyleResolverState&,
const CSSValue&,
bool inherited_only,
- ValidPropertyFilter);
+ ValidPropertyFilter,
+ unsigned apply_mask);
bool PseudoStyleForElementInternal(Element&,
const PseudoStyleRequest&,
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 9726e5e812a..947fbbdbb8d 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
@@ -43,11 +43,9 @@ StyleResolverState::StyleResolverState(
layout_parent_style_(layout_parent_style),
is_animation_interpolation_map_ready_(false),
is_animating_custom_properties_(false),
- apply_property_to_regular_style_(true),
- apply_property_to_visited_link_style_(false),
has_dir_auto_attribute_(false),
font_builder_(&document),
- element_style_resources_(*GetElement(),
+ element_style_resources_(GetElement(),
document.DevicePixelRatio(),
pseudo_element) {
DCHECK(!!parent_style_ == !!layout_parent_style_);
@@ -66,13 +64,12 @@ StyleResolverState::StyleResolverState(
}
StyleResolverState::StyleResolverState(Document& document,
- Element* element,
+ Element& element,
PseudoElement* pseudo_element,
const ComputedStyle* parent_style,
const ComputedStyle* layout_parent_style)
: StyleResolverState(document,
- element ? ElementResolveContext(*element)
- : ElementResolveContext(document),
+ ElementResolveContext(element),
pseudo_element,
parent_style,
layout_parent_style) {}
@@ -84,7 +81,7 @@ StyleResolverState::~StyleResolverState() {
}
TreeScope& StyleResolverState::GetTreeScope() const {
- return GetElement() ? GetElement()->GetTreeScope() : GetDocument();
+ return GetElement().GetTreeScope();
}
void StyleResolverState::SetStyle(scoped_refptr<ComputedStyle> style) {
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 e56cdd31306..06a7533d878 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
@@ -57,7 +57,7 @@ class CORE_EXPORT StyleResolverState {
const ComputedStyle* parent_style,
const ComputedStyle* layout_parent_style);
StyleResolverState(Document&,
- Element*,
+ Element&,
PseudoElement* pseudo_element,
const ComputedStyle* parent_style = nullptr,
const ComputedStyle* layout_parent_style = nullptr);
@@ -68,7 +68,7 @@ class CORE_EXPORT StyleResolverState {
// separately.
Document& GetDocument() const { return *document_; }
// These are all just pass-through methods to ElementResolveContext.
- Element* GetElement() const { return element_context_.GetElement(); }
+ Element& GetElement() const { return element_context_.GetElement(); }
TreeScope& GetTreeScope() const;
const ContainerNode* ParentNode() const {
return element_context_.ParentNode();
@@ -137,25 +137,6 @@ class CORE_EXPORT StyleResolverState {
return layout_parent_style_.get();
}
- // FIXME: These are effectively side-channel "out parameters" for the various
- // map functions. When we map from CSS to style objects we use this state
- // object to track various meta-data about that mapping (e.g. if it's
- // cache-able). We need to move this data off of StyleResolverState and
- // closer to the objects it applies to. Possibly separating (immutable) inputs
- // from (mutable) outputs.
- void SetApplyPropertyToRegularStyle(bool is_apply) {
- apply_property_to_regular_style_ = is_apply;
- }
- void SetApplyPropertyToVisitedLinkStyle(bool is_apply) {
- apply_property_to_visited_link_style_ = is_apply;
- }
- bool ApplyPropertyToRegularStyle() const {
- return apply_property_to_regular_style_;
- }
- bool ApplyPropertyToVisitedLinkStyle() const {
- return apply_property_to_visited_link_style_;
- }
-
void CacheUserAgentBorderAndBackground();
const CachedUAStyle* GetCachedUAStyle() const {
@@ -220,8 +201,6 @@ class CORE_EXPORT StyleResolverState {
bool is_animation_interpolation_map_ready_;
bool is_animating_custom_properties_;
- bool apply_property_to_regular_style_;
- bool apply_property_to_visited_link_style_;
bool has_dir_auto_attribute_;
FontBuilder font_builder_;
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/style_resolver_test.cc b/chromium/third_party/blink/renderer/core/css/resolver/style_resolver_test.cc
new file mode 100644
index 00000000000..0dddc49547a
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/css/resolver/style_resolver_test.cc
@@ -0,0 +1,36 @@
+// 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/css/resolver/style_resolver.h"
+
+#include "testing/gtest/include/gtest/gtest.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/node_computed_style.h"
+#include "third_party/blink/renderer/core/dom/text.h"
+#include "third_party/blink/renderer/core/testing/page_test_base.h"
+
+namespace blink {
+
+class StyleResolverTest : public PageTestBase {
+ protected:
+};
+
+TEST_F(StyleResolverTest, StyleForTextInDisplayNone) {
+ GetDocument().documentElement()->SetInnerHTMLFromString(R"HTML(
+ <body style="display:none">Text</body>
+ )HTML");
+
+ UpdateAllLifecyclePhasesForTest();
+
+ GetDocument().body()->EnsureComputedStyle();
+
+ ASSERT_TRUE(GetDocument().body()->GetComputedStyle());
+ EXPECT_TRUE(
+ GetDocument().body()->GetComputedStyle()->IsEnsuredInDisplayNone());
+ EXPECT_FALSE(GetStyleEngine().Resolver()->StyleForText(
+ To<Text>(GetDocument().body()->firstChild())));
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/css/resolver/transform_builder.cc b/chromium/third_party/blink/renderer/core/css/resolver/transform_builder.cc
index c3e1ba7177b..d2bfb9520c4 100644
--- a/chromium/third_party/blink/renderer/core/css/resolver/transform_builder.cc
+++ b/chromium/third_party/blink/renderer/core/css/resolver/transform_builder.cc
@@ -31,6 +31,9 @@
#include "third_party/blink/renderer/core/css/resolver/transform_builder.h"
#include "third_party/blink/renderer/core/css/css_function_value.h"
+#include "third_party/blink/renderer/core/css/css_math_expression_node.h"
+#include "third_party/blink/renderer/core/css/css_math_function_value.h"
+#include "third_party/blink/renderer/core/css/css_numeric_literal_value.h"
#include "third_party/blink/renderer/core/css/css_primitive_value_mappings.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/transforms/matrix_3d_transform_operation.h"
@@ -107,20 +110,14 @@ bool TransformBuilder::HasRelativeLengths(const CSSValueList& value_list) {
for (const CSSValue* item : *transform_value) {
const auto& primitive_value = To<CSSPrimitiveValue>(*item);
-
if (primitive_value.IsCalculated()) {
- CSSCalcValue* css_calc_value = primitive_value.CssCalcValue();
- CSSPrimitiveValue::UnitType resolved_type =
- css_calc_value->ExpressionNode()->TypeWithCalcResolved();
- if (CSSPrimitiveValue::IsRelativeUnit(resolved_type) ||
- resolved_type == CSSPrimitiveValue::UnitType::kUnknown) {
+ if (To<CSSMathFunctionValue>(primitive_value).MayHaveRelativeUnit())
+ return true;
+ } else {
+ CSSPrimitiveValue::UnitType unit_type =
+ To<CSSNumericLiteralValue>(primitive_value).GetType();
+ if (CSSPrimitiveValue::IsRelativeUnit(unit_type))
return true;
- }
- }
-
- if (CSSPrimitiveValue::IsRelativeUnit(
- primitive_value.TypeWithCalcResolved())) {
- return true;
}
}
}
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 6ab24edfe84..d90be37ebcc 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
@@ -17,6 +17,7 @@
#include "third_party/blink/renderer/core/html/html_element.h"
#include "third_party/blink/renderer/core/html/html_html_element.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
@@ -39,7 +40,7 @@ class RuleFeatureSetTest : public testing::Test {
StrictCSSParserContext(SecureContextMode::kInsecureContext), nullptr,
selector_text);
- std::vector<wtf_size_t> indices;
+ Vector<wtf_size_t> indices;
for (const CSSSelector* s = selector_list.First(); s;
s = selector_list.Next(*s)) {
indices.push_back(selector_list.SelectorIndex(*s));
@@ -1418,7 +1419,7 @@ TEST_F(RuleFeatureSetTest, CopyOnWrite) {
TEST_F(RuleFeatureSetTest, CopyOnWrite_SiblingDescendantPairs) {
// Test data:
- std::vector<const char*> data;
+ Vector<const char*> data;
// Descendant.
data.push_back(".a .b0");
data.push_back(".a .b1");
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 966820579d9..8227f2de5e1 100644
--- a/chromium/third_party/blink/renderer/core/css/rule_set.cc
+++ b/chromium/third_party/blink/renderer/core/css/rule_set.cc
@@ -287,6 +287,11 @@ void RuleSet::AddKeyframesRule(StyleRuleKeyframes* rule) {
keyframes_rules_.push_back(rule);
}
+void RuleSet::AddPropertyRule(StyleRuleProperty* rule) {
+ EnsurePendingRules(); // So that property_rules_.ShrinkToFit() gets called.
+ property_rules_.push_back(rule);
+}
+
void RuleSet::AddChildRules(const HeapVector<Member<StyleRuleBase>>& rules,
const MediaQueryEvaluator& medium,
AddRuleFlags add_rule_flags) {
@@ -326,6 +331,8 @@ void RuleSet::AddChildRules(const HeapVector<Member<StyleRuleBase>>& rules,
AddFontFeatureValuesRule(font_feature_values_rule);
} else if (auto* keyframes_rule = DynamicTo<StyleRuleKeyframes>(rule)) {
AddKeyframesRule(keyframes_rule);
+ } else if (auto* property_rule = DynamicTo<StyleRuleProperty>(rule)) {
+ AddPropertyRule(property_rule);
} else if (auto* supports_rule = DynamicTo<StyleRuleSupports>(rule)) {
if (supports_rule->ConditionIsSupported())
AddChildRules(supports_rule->ChildRules(), medium, add_rule_flags);
@@ -402,6 +409,7 @@ void RuleSet::CompactRules() {
font_face_rules_.ShrinkToFit();
font_feature_values_rules_.ShrinkToFit();
keyframes_rules_.ShrinkToFit();
+ property_rules_.ShrinkToFit();
deep_combinator_or_shadow_pseudo_rules_.ShrinkToFit();
part_pseudo_rules_.ShrinkToFit();
content_pseudo_element_rules_.ShrinkToFit();
@@ -438,6 +446,7 @@ void RuleSet::Trace(blink::Visitor* visitor) {
visitor->Trace(font_face_rules_);
visitor->Trace(font_feature_values_rules_);
visitor->Trace(keyframes_rules_);
+ visitor->Trace(property_rules_);
visitor->Trace(deep_combinator_or_shadow_pseudo_rules_);
visitor->Trace(part_pseudo_rules_);
visitor->Trace(content_pseudo_element_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 bf13377c581..6776c98aca8 100644
--- a/chromium/third_party/blink/renderer/core/css/rule_set.h
+++ b/chromium/third_party/blink/renderer/core/css/rule_set.h
@@ -250,6 +250,9 @@ class CORE_EXPORT RuleSet : public GarbageCollectedFinalized<RuleSet> {
const HeapVector<Member<StyleRuleKeyframes>>& KeyframesRules() const {
return keyframes_rules_;
}
+ const HeapVector<Member<StyleRuleProperty>>& PropertyRules() const {
+ return property_rules_;
+ }
const HeapVector<MinimalRuleData>& DeepCombinatorOrShadowPseudoRules() const {
return deep_combinator_or_shadow_pseudo_rules_;
}
@@ -301,6 +304,7 @@ class CORE_EXPORT RuleSet : public GarbageCollectedFinalized<RuleSet> {
void AddFontFaceRule(StyleRuleFontFace*);
void AddFontFeatureValuesRule(StyleRuleFontFeatureValues*);
void AddKeyframesRule(StyleRuleKeyframes*);
+ void AddPropertyRule(StyleRuleProperty*);
void AddChildRules(const HeapVector<Member<StyleRuleBase>>&,
const MediaQueryEvaluator& medium,
@@ -344,6 +348,7 @@ class CORE_EXPORT RuleSet : public GarbageCollectedFinalized<RuleSet> {
HeapVector<Member<StyleRuleFontFace>> font_face_rules_;
HeapVector<Member<StyleRuleFontFeatureValues>> font_feature_values_rules_;
HeapVector<Member<StyleRuleKeyframes>> keyframes_rules_;
+ HeapVector<Member<StyleRuleProperty>> property_rules_;
HeapVector<MinimalRuleData> deep_combinator_or_shadow_pseudo_rules_;
HeapVector<MinimalRuleData> content_pseudo_element_rules_;
HeapVector<MinimalRuleData> slotted_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 474ae9a0b28..5959b5427f3 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
@@ -361,7 +361,7 @@ TEST(RuleSetTest, SelectorIndexLimit) {
builder.Append("b,span {}");
TestStyleSheet sheet;
- sheet.AddCSSRules(builder.ToString().Ascii().data());
+ sheet.AddCSSRules(builder.ToString());
const RuleSet& rule_set = sheet.GetRuleSet();
const HeapVector<Member<const RuleData>>* rules = rule_set.TagRules("b");
ASSERT_EQ(1u, rules->size());
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 af1ce205684..027612ad824 100644
--- a/chromium/third_party/blink/renderer/core/css/selector_checker.cc
+++ b/chromium/third_party/blink/renderer/core/css/selector_checker.cc
@@ -901,17 +901,20 @@ bool SelectorChecker::CheckPseudoClass(const SelectorCheckingContext& context,
return true;
}
} break;
- case CSSSelector::kPseudoAutofill:
- return element.IsFormControlElement() &&
- ToHTMLFormControlElement(element).IsAutofilled();
- case CSSSelector::kPseudoAutofillPreviewed:
- return element.IsFormControlElement() &&
- ToHTMLFormControlElement(element).GetAutofillState() ==
- WebAutofillState::kPreviewed;
- case CSSSelector::kPseudoAutofillSelected:
- return element.IsFormControlElement() &&
- ToHTMLFormControlElement(element).GetAutofillState() ==
- WebAutofillState::kAutofilled;
+ case CSSSelector::kPseudoAutofill: {
+ auto* html_form_element = DynamicTo<HTMLFormControlElement>(&element);
+ return html_form_element && html_form_element->IsAutofilled();
+ }
+ case CSSSelector::kPseudoAutofillPreviewed: {
+ auto* html_form_element = DynamicTo<HTMLFormControlElement>(&element);
+ return html_form_element && html_form_element->GetAutofillState() ==
+ WebAutofillState::kPreviewed;
+ }
+ case CSSSelector::kPseudoAutofillSelected: {
+ auto* html_form_element = DynamicTo<HTMLFormControlElement>(&element);
+ return html_form_element && html_form_element->GetAutofillState() ==
+ WebAutofillState::kAutofilled;
+ }
case CSSSelector::kPseudoAnyLink:
case CSSSelector::kPseudoWebkitAnyLink:
case CSSSelector::kPseudoLink:
diff --git a/chromium/third_party/blink/renderer/core/css/style_attribute_mutation_scope.h b/chromium/third_party/blink/renderer/core/css/style_attribute_mutation_scope.h
index efbc88114d3..34fd5076832 100644
--- a/chromium/third_party/blink/renderer/core/css/style_attribute_mutation_scope.h
+++ b/chromium/third_party/blink/renderer/core/css/style_attribute_mutation_scope.h
@@ -24,7 +24,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_STYLE_ATTRIBUTE_MUTATION_SCOPE_H_
#include "third_party/blink/renderer/platform/heap/member.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/css/style_auto_color.h b/chromium/third_party/blink/renderer/core/css/style_auto_color.h
index 6d29ca1bddc..9e26166df10 100644
--- a/chromium/third_party/blink/renderer/core/css/style_auto_color.h
+++ b/chromium/third_party/blink/renderer/core/css/style_auto_color.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/css/style_color.h"
#include "third_party/blink/renderer/platform/graphics/color.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 b43684bf76f..8e96f863dbb 100644
--- a/chromium/third_party/blink/renderer/core/css/style_color.h
+++ b/chromium/third_party/blink/renderer/core/css/style_color.h
@@ -33,7 +33,7 @@
#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/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 f33e2f624cd..5f88201679f 100644
--- a/chromium/third_party/blink/renderer/core/css/style_engine.cc
+++ b/chromium/third_party/blink/renderer/core/css/style_engine.cc
@@ -39,6 +39,7 @@
#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_registration.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"
@@ -94,8 +95,10 @@ StyleEngine::StyleEngine(Document& document)
global_rule_set_ = MakeGarbageCollected<CSSGlobalRuleSet>();
// Document is initially style dirty.
style_recalc_root_.Update(nullptr, &document);
- if (auto* settings = GetDocument().GetSettings())
+ if (auto* settings = GetDocument().GetSettings()) {
preferred_color_scheme_ = settings->GetPreferredColorScheme();
+ forced_colors_ = settings->GetForcedColors();
+ }
}
StyleEngine::~StyleEngine() = default;
@@ -214,11 +217,13 @@ void StyleEngine::AddPendingSheet(StyleEngineContext& context) {
pending_script_blocking_stylesheets_++;
context.AddingPendingSheet(GetDocument());
- if (context.AddedPendingSheetBeforeBody()) {
+
+ if (context.AddedPendingSheetBeforeBody() &&
+ !RuntimeEnabledFeatures::BlockHTMLParserOnStyleSheetsEnabled()) {
pending_render_blocking_stylesheets_++;
} else {
- pending_body_stylesheets_++;
- GetDocument().DidAddPendingStylesheetInBody();
+ pending_parser_blocking_stylesheets_++;
+ GetDocument().DidAddPendingParserBlockingStylesheet();
}
}
@@ -228,14 +233,15 @@ void StyleEngine::RemovePendingSheet(Node& style_sheet_candidate_node,
if (style_sheet_candidate_node.isConnected())
SetNeedsActiveStyleUpdate(style_sheet_candidate_node.GetTreeScope());
- if (context.AddedPendingSheetBeforeBody()) {
+ if (context.AddedPendingSheetBeforeBody() &&
+ !RuntimeEnabledFeatures::BlockHTMLParserOnStyleSheetsEnabled()) {
DCHECK_GT(pending_render_blocking_stylesheets_, 0);
pending_render_blocking_stylesheets_--;
} else {
- DCHECK_GT(pending_body_stylesheets_, 0);
- pending_body_stylesheets_--;
- if (!pending_body_stylesheets_)
- GetDocument().DidRemoveAllPendingBodyStylesheets();
+ DCHECK_GT(pending_parser_blocking_stylesheets_, 0);
+ pending_parser_blocking_stylesheets_--;
+ if (!pending_parser_blocking_stylesheets_)
+ GetDocument().DidLoadAllPendingParserBlockingStylesheets();
}
// Make sure we knew this sheet was pending, and that our count isn't out of
@@ -246,7 +252,7 @@ void StyleEngine::RemovePendingSheet(Node& style_sheet_candidate_node,
if (pending_script_blocking_stylesheets_)
return;
- GetDocument().DidRemoveAllPendingStylesheet();
+ GetDocument().DidRemoveAllPendingStylesheets();
}
void StyleEngine::SetNeedsActiveStyleUpdate(TreeScope& tree_scope) {
@@ -1340,6 +1346,7 @@ enum RuleSetFlags {
kFullRecalcRules = 1 << 2,
kFontFeatureValuesRules = 1 << 3,
kFontRules = kFontFaceRules | kFontFeatureValuesRules,
+ kPropertyRules = 1 << 4
};
unsigned GetRuleSetFlags(const HeapHashSet<Member<RuleSet>> rule_sets) {
@@ -1354,6 +1361,8 @@ unsigned GetRuleSetFlags(const HeapHashSet<Member<RuleSet>> rule_sets) {
flags |= kFullRecalcRules;
if (!rule_set->FontFeatureValuesRules().IsEmpty())
flags |= kFontFeatureValuesRules;
+ if (!rule_set->PropertyRules().IsEmpty())
+ flags |= kPropertyRules;
}
return flags;
}
@@ -1480,6 +1489,20 @@ void StyleEngine::ApplyRuleSetChanges(
if (changed_rule_flags & kKeyframesRules)
ScopedStyleResolver::KeyframesRulesAdded(tree_scope);
+ if (changed_rule_flags & kPropertyRules) {
+ // TODO(https://crbug.com/978786): Don't ignore TreeScope.
+
+ // TODO(https://crbug.com/978781): Support unregistration.
+ // At this point we could have unregistered properties for
+ // change==kActiveSheetsChanged, but we don't yet support that.
+
+ for (auto* it = new_style_sheets.begin(); it != new_style_sheets.end();
+ it++) {
+ DCHECK(it->second);
+ AddPropertyRules(*it->second);
+ }
+ }
+
if (rebuild_font_cache)
ClearFontCacheAndAddUserFonts();
@@ -1691,6 +1714,33 @@ void StyleEngine::AddUserKeyframeStyle(StyleRuleKeyframes* rule) {
}
}
+void StyleEngine::AddPropertyRules(const RuleSet& rule_set) {
+ PropertyRegistry* registry = GetDocument().GetPropertyRegistry();
+ if (!registry)
+ return;
+ const HeapVector<Member<StyleRuleProperty>> property_rules =
+ rule_set.PropertyRules();
+ for (unsigned i = 0; i < property_rules.size(); ++i) {
+ StyleRuleProperty* rule = property_rules[i];
+
+ AtomicString name(rule->GetName());
+
+ // For now, ignore silently if registration already exists.
+ // TODO(https://crbug.com/978781): Support unregistration.
+ if (registry->Registration(name))
+ continue;
+
+ PropertyRegistration* registration =
+ PropertyRegistration::MaybeCreate(GetDocument(), name, *rule);
+
+ if (!registration)
+ continue;
+
+ registry->RegisterProperty(name, *registration);
+ CustomPropertyRegistered();
+ }
+}
+
StyleRuleKeyframes* StyleEngine::KeyframeStylesForAnimation(
const AtomicString& animation_name) {
if (keyframes_rule_map_.IsEmpty())
@@ -1815,6 +1865,10 @@ bool StyleEngine::SupportsDarkColorScheme() {
void StyleEngine::UpdateColorScheme() {
auto* settings = GetDocument().GetSettings();
DCHECK(settings);
+
+ ForcedColors old_forced_colors = forced_colors_;
+ forced_colors_ = settings->GetForcedColors();
+
PreferredColorScheme old_preferred_color_scheme = preferred_color_scheme_;
preferred_color_scheme_ = settings->GetPreferredColorScheme();
bool use_dark_scheme =
@@ -1825,7 +1879,9 @@ void StyleEngine::UpdateColorScheme() {
// darkening is enabled.
preferred_color_scheme_ = PreferredColorScheme::kNoPreference;
}
- if (preferred_color_scheme_ != old_preferred_color_scheme)
+
+ if (forced_colors_ != old_forced_colors ||
+ preferred_color_scheme_ != old_preferred_color_scheme)
PlatformColorsChanged();
UpdateColorSchemeBackground();
}
@@ -1850,7 +1906,8 @@ void StyleEngine::UpdateColorSchemeBackground() {
bool use_dark_background = false;
- if (preferred_color_scheme_ == PreferredColorScheme::kDark) {
+ if (preferred_color_scheme_ == PreferredColorScheme::kDark &&
+ forced_colors_ != ForcedColors::kActive) {
const ComputedStyle* style = nullptr;
if (auto* root_element = GetDocument().documentElement())
style = root_element->GetComputedStyle();
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 164c603e843..9f1410d2a4d 100644
--- a/chromium/third_party/blink/renderer/core/css/style_engine.h
+++ b/chromium/third_party/blink/renderer/core/css/style_engine.h
@@ -33,6 +33,7 @@
#include <memory>
#include <utility>
#include "base/auto_reset.h"
+#include "third_party/blink/public/common/css/forced_colors.h"
#include "third_party/blink/public/common/css/preferred_color_scheme.h"
#include "third_party/blink/public/web/web_document.h"
#include "third_party/blink/renderer/core/core_export.h"
@@ -53,7 +54,7 @@
#include "third_party/blink/renderer/platform/bindings/name_client.h"
#include "third_party/blink/renderer/platform/fonts/font_selector_client.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
@@ -347,6 +348,7 @@ class CORE_EXPORT StyleEngine final
PreferredColorScheme GetPreferredColorScheme() const {
return preferred_color_scheme_;
}
+ ForcedColors GetForcedColors() const { return forced_colors_; }
void UpdateColorSchemeBackground();
void Trace(blink::Visitor*) override;
@@ -436,10 +438,12 @@ class CORE_EXPORT StyleEngine final
void ClearFontCacheAndAddUserFonts();
void ClearKeyframeRules() { keyframes_rule_map_.clear(); }
+ void ClearPropertyRules();
void AddUserFontFaceRules(const RuleSet&);
void AddUserKeyframeRules(const RuleSet&);
void AddUserKeyframeStyle(StyleRuleKeyframes*);
+ void AddPropertyRules(const RuleSet&);
void UpdateColorScheme();
bool SupportsDarkColorScheme();
@@ -447,13 +451,29 @@ class CORE_EXPORT StyleEngine final
Member<Document> document_;
bool is_master_;
- // Track the number of currently loading top-level stylesheets needed for
- // layout. Sheets loaded using the @import directive are not included in this
- // count. We use this count of pending sheets to detect when we can begin
- // attaching elements and when it is safe to execute scripts.
+ // Tracks the number of currently loading top-level stylesheets. Sheets loaded
+ // using the @import directive are not included in this count. We use this
+ // count of pending sheets to detect when it is safe to execute scripts
+ // (parser-inserted scripts may not run until all pending stylesheets have
+ // loaded). See:
+ // https://html.spec.whatwg.org/multipage/semantics.html#interactions-of-styling-and-scripting
+ // Once the BlockHTMLParserOnStyleSheets flag has shipped, this is the same
+ // as pending_parser_blocking_stylesheets_.
int pending_script_blocking_stylesheets_ = 0;
+
+ // Tracks the number of currently loading top-level stylesheets which block
+ // rendering (the "Update the rendering" step of the event loop processing
+ // model) from starting. Sheets loaded using the @import directive are not
+ // included in this count. See:
+ // https://html.spec.whatwg.org/multipage/webappapis.html#event-loop-processing-model
+ // Once all of these sheets have loaded, rendering begins.
int pending_render_blocking_stylesheets_ = 0;
- int pending_body_stylesheets_ = 0;
+
+ // Tracks the number of currently loading top-level stylesheets which block
+ // the HTML parser. Sheets loaded using the @import directive are not included
+ // in this count. Once all of these sheets have loaded, the parser may
+ // continue.
+ int pending_parser_blocking_stylesheets_ = 0;
Member<CSSStyleSheet> inspector_style_sheet_;
@@ -533,11 +553,14 @@ class CORE_EXPORT StyleEngine final
Member<const CSSValue> meta_color_scheme_;
// The preferred color scheme is set in settings, but may be overridden by the
- // ForceDarkMode setting where the preferred_color_scheme_ will be set no
+ // ForceDarkMode setting where the preferred_color_scheme_ will be set to
// kNoPreference to avoid dark styling to be applied before auto darkening.
PreferredColorScheme preferred_color_scheme_ =
PreferredColorScheme::kNoPreference;
+ // Forced colors is set in settings.
+ ForcedColors forced_colors_ = ForcedColors::kNone;
+
friend class NodeTest;
friend class StyleEngineTest;
friend class WhitespaceAttacherTest;
diff --git a/chromium/third_party/blink/renderer/core/css/style_engine_context.cc b/chromium/third_party/blink/renderer/core/css/style_engine_context.cc
index 88e2c9cc083..8638358e1db 100644
--- a/chromium/third_party/blink/renderer/core/css/style_engine_context.cc
+++ b/chromium/third_party/blink/renderer/core/css/style_engine_context.cc
@@ -25,7 +25,7 @@
#include "third_party/blink/renderer/core/css/style_engine_context.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
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 f09c6ceb2d7..d43d42ee052 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
@@ -7,6 +7,7 @@
#include <memory>
#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/public/common/css/forced_colors.h"
#include "third_party/blink/public/common/css/preferred_color_scheme.h"
#include "third_party/blink/public/platform/web_float_rect.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
@@ -35,6 +36,7 @@
#include "third_party/blink/renderer/core/testing/dummy_page_holder.h"
#include "third_party/blink/renderer/platform/geometry/float_size.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
namespace blink {
@@ -43,7 +45,6 @@ using namespace css_test_helpers;
class StyleEngineTest : public testing::Test {
protected:
void SetUp() override;
- void TearDown() override;
Document& GetDocument() { return dummy_page_holder_->GetDocument(); }
StyleEngine& GetStyleEngine() { return GetDocument().GetStyleEngine(); }
@@ -67,17 +68,12 @@ class StyleEngineTest : public testing::Test {
private:
std::unique_ptr<DummyPageHolder> dummy_page_holder_;
- RuntimeEnabledFeatures::Backup features_backup_;
};
void StyleEngineTest::SetUp() {
dummy_page_holder_ = std::make_unique<DummyPageHolder>(IntSize(800, 600));
}
-void StyleEngineTest::TearDown() {
- features_backup_.Restore();
-}
-
StyleEngineTest::RuleSetInvalidation
StyleEngineTest::ScheduleInvalidationsForRules(TreeScope& tree_scope,
const String& css_text) {
@@ -1490,7 +1486,7 @@ TEST_F(StyleEngineTest, MediaQueriesChangeDefaultFontSize) {
}
TEST_F(StyleEngineTest, MediaQueriesChangeColorScheme) {
- RuntimeEnabledFeatures::SetMediaQueryPrefersColorSchemeEnabled(true);
+ ScopedMediaQueryPrefersColorSchemeForTest feature_scope(true);
GetDocument().body()->SetInnerHTMLFromString(R"HTML(
<style>
@@ -1516,7 +1512,7 @@ TEST_F(StyleEngineTest, MediaQueriesChangeColorScheme) {
}
TEST_F(StyleEngineTest, MediaQueriesChangeColorSchemeForcedDarkMode) {
- RuntimeEnabledFeatures::SetMediaQueryPrefersColorSchemeEnabled(true);
+ ScopedMediaQueryPrefersColorSchemeForTest feature_scope(true);
GetDocument().GetSettings()->SetForceDarkModeEnabled(true);
GetDocument().GetSettings()->SetPreferredColorScheme(
@@ -1563,6 +1559,96 @@ TEST_F(StyleEngineTest, MediaQueriesChangePrefersReducedMotion) {
GetCSSPropertyColor()));
}
+TEST_F(StyleEngineTest, MediaQueriesChangeForcedColors) {
+ ScopedForcedColorsForTest scoped_feature(true);
+ GetDocument().body()->SetInnerHTMLFromString(R"HTML(
+ <style>
+ @media (forced-colors: none) {
+ body { color: red }
+ }
+ @media (forced-colors: active) {
+ body { color: green }
+ }
+ </style>
+ <body></body>
+ )HTML");
+
+ UpdateAllLifecyclePhases();
+ EXPECT_EQ(MakeRGB(255, 0, 0),
+ GetDocument().body()->GetComputedStyle()->VisitedDependentColor(
+ GetCSSPropertyColor()));
+
+ GetDocument().GetSettings()->SetForcedColors(ForcedColors::kActive);
+ UpdateAllLifecyclePhases();
+ EXPECT_EQ(MakeRGB(0, 128, 0),
+ GetDocument().body()->GetComputedStyle()->VisitedDependentColor(
+ GetCSSPropertyColor()));
+}
+
+TEST_F(StyleEngineTest, MediaQueriesChangeForcedColorsAndPreferredColorScheme) {
+ ScopedForcedColorsForTest scoped_feature(true);
+ GetDocument().body()->SetInnerHTMLFromString(R"HTML(
+ <style>
+ @media (forced-colors: none) and (prefers-color-scheme: light) {
+ body { color: red }
+ }
+ @media (forced-colors: none) and (prefers-color-scheme: dark) {
+ body { color: green }
+ }
+ @media (forced-colors: active) and (prefers-color-scheme: no-preference) {
+ body { color: yellow }
+ }
+ @media (forced-colors: active) and (prefers-color-scheme: dark) {
+ body { color: orange }
+ }
+ @media (forced-colors: active) and (prefers-color-scheme: light) {
+ body { color: blue }
+ }
+ </style>
+ <body></body>
+ )HTML");
+
+ // ForcedColors = kNone, PreferredColorScheme = kLight
+ GetDocument().GetSettings()->SetForcedColors(ForcedColors::kNone);
+ GetDocument().GetSettings()->SetPreferredColorScheme(
+ PreferredColorScheme::kLight);
+ UpdateAllLifecyclePhases();
+ EXPECT_EQ(MakeRGB(255, 0, 0),
+ GetDocument().body()->GetComputedStyle()->VisitedDependentColor(
+ GetCSSPropertyColor()));
+
+ // ForcedColors = kNone, PreferredColorScheme = kDark
+ GetDocument().GetSettings()->SetPreferredColorScheme(
+ PreferredColorScheme::kDark);
+ UpdateAllLifecyclePhases();
+ EXPECT_EQ(MakeRGB(0, 128, 0),
+ GetDocument().body()->GetComputedStyle()->VisitedDependentColor(
+ GetCSSPropertyColor()));
+
+ // ForcedColors = kActive, PreferredColorScheme = kDark
+ GetDocument().GetSettings()->SetForcedColors(ForcedColors::kActive);
+ UpdateAllLifecyclePhases();
+ EXPECT_EQ(MakeRGB(255, 165, 0),
+ GetDocument().body()->GetComputedStyle()->VisitedDependentColor(
+ GetCSSPropertyColor()));
+
+ // ForcedColors = kActive, PreferredColorScheme = kNoPreference
+ GetDocument().GetSettings()->SetPreferredColorScheme(
+ PreferredColorScheme::kNoPreference);
+ UpdateAllLifecyclePhases();
+ EXPECT_EQ(MakeRGB(255, 255, 0),
+ GetDocument().body()->GetComputedStyle()->VisitedDependentColor(
+ GetCSSPropertyColor()));
+
+ // ForcedColors = kActive, PreferredColorScheme = kLight
+ GetDocument().GetSettings()->SetPreferredColorScheme(
+ PreferredColorScheme::kLight);
+ UpdateAllLifecyclePhases();
+ EXPECT_EQ(MakeRGB(0, 0, 255),
+ GetDocument().body()->GetComputedStyle()->VisitedDependentColor(
+ GetCSSPropertyColor()));
+}
+
TEST_F(StyleEngineTest, ShadowRootStyleRecalcCrash) {
GetDocument().body()->SetInnerHTMLFromString("<div id=host></div>");
auto* host = To<HTMLElement>(GetDocument().getElementById("host"));
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 d999a12e19e..0299110e218 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
@@ -7,11 +7,11 @@
#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/node_computed_style.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/frame/web_feature.h"
#include "third_party/blink/renderer/core/html/html_element.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/core/testing/page_test_base.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/shared_buffer.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
diff --git a/chromium/third_party/blink/renderer/core/css/style_property_serializer.cc b/chromium/third_party/blink/renderer/core/css/style_property_serializer.cc
index f2a88bb9994..d338cbd7e11 100644
--- a/chromium/third_party/blink/renderer/core/css/style_property_serializer.cc
+++ b/chromium/third_party/blink/renderer/core/css/style_property_serializer.cc
@@ -228,8 +228,8 @@ String StylePropertySerializer::AsText() const {
const CSSProperty& property_class = property.Property();
CSSPropertyID property_id = property_class.PropertyID();
- // Only enabled properties should be part of the style.
- DCHECK(property_class.IsEnabled());
+ // Only web exposed properties should be part of the style.
+ DCHECK(property_class.IsWebExposed());
// All shorthand properties should have been expanded at parse time.
DCHECK(property_set_.IsDescriptorContext() ||
(property_class.IsProperty() && !property_class.IsShorthand()));
@@ -1094,7 +1094,8 @@ static void AppendBackgroundRepeatValue(StringBuilder& builder,
const CSSValue& repeat_xcss_value,
const CSSValue& repeat_ycss_value) {
// FIXME: Ensure initial values do not appear in CSS_VALUE_LISTS.
- DEFINE_STATIC_LOCAL(Persistent<CSSIdentifierValue>, initial_repeat_value,
+ DEFINE_STATIC_LOCAL(const Persistent<CSSIdentifierValue>,
+ initial_repeat_value,
(CSSIdentifierValue::Create(CSSValueID::kRepeat)));
const CSSIdentifierValue& repeat_x =
repeat_xcss_value.IsInitialValue()
diff --git a/chromium/third_party/blink/renderer/core/css/style_property_shorthand_custom.cc b/chromium/third_party/blink/renderer/core/css/style_property_shorthand_custom.cc
index e6a15cb1b0f..a3b9cdd729e 100644
--- a/chromium/third_party/blink/renderer/core/css/style_property_shorthand_custom.cc
+++ b/chromium/third_party/blink/renderer/core/css/style_property_shorthand_custom.cc
@@ -44,9 +44,10 @@ const StylePropertyShorthand& animationShorthandForParsing() {
&GetCSSPropertyAnimationFillMode(),
&GetCSSPropertyAnimationPlayState(),
&GetCSSPropertyAnimationName()};
- static StylePropertyShorthand webkit_animation_longhands_for_parsing(
- CSSPropertyID::kAnimation, kAnimationPropertiesForParsing,
- base::size(kAnimationPropertiesForParsing));
+ static constexpr StylePropertyShorthand
+ webkit_animation_longhands_for_parsing(
+ CSSPropertyID::kAnimation, kAnimationPropertiesForParsing,
+ base::size(kAnimationPropertiesForParsing));
return webkit_animation_longhands_for_parsing;
}
diff --git a/chromium/third_party/blink/renderer/core/css/style_recalc_root.cc b/chromium/third_party/blink/renderer/core/css/style_recalc_root.cc
index 8c887718413..0a251fbd4f0 100644
--- a/chromium/third_party/blink/renderer/core/css/style_recalc_root.cc
+++ b/chromium/third_party/blink/renderer/core/css/style_recalc_root.cc
@@ -31,7 +31,7 @@ Element& StyleRecalcRoot::RootElement() const {
}
if (root_node->IsTextNode())
return *root_node->parentElement();
- return ToElement(*root_node);
+ return To<Element>(*root_node);
}
#if DCHECK_IS_ON()
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 466a6f3a1d5..fc4f7801d15 100644
--- a/chromium/third_party/blink/renderer/core/css/style_rule.cc
+++ b/chromium/third_party/blink/renderer/core/css/style_rule.cc
@@ -29,6 +29,7 @@
#include "third_party/blink/renderer/core/css/css_media_rule.h"
#include "third_party/blink/renderer/core/css/css_namespace_rule.h"
#include "third_party/blink/renderer/core/css/css_page_rule.h"
+#include "third_party/blink/renderer/core/css/css_property_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"
@@ -66,6 +67,9 @@ void StyleRuleBase::Trace(blink::Visitor* visitor) {
case kPage:
To<StyleRulePage>(this)->TraceAfterDispatch(visitor);
return;
+ case kProperty:
+ To<StyleRuleProperty>(this)->TraceAfterDispatch(visitor);
+ return;
case kFontFace:
To<StyleRuleFontFace>(this)->TraceAfterDispatch(visitor);
return;
@@ -108,6 +112,9 @@ void StyleRuleBase::FinalizeGarbageCollectedObject() {
case kPage:
To<StyleRulePage>(this)->~StyleRulePage();
return;
+ case kProperty:
+ To<StyleRuleProperty>(this)->~StyleRuleProperty();
+ return;
case kFontFace:
To<StyleRuleFontFace>(this)->~StyleRuleFontFace();
return;
@@ -145,6 +152,8 @@ StyleRuleBase* StyleRuleBase::Copy() const {
return To<StyleRule>(this)->Copy();
case kPage:
return To<StyleRulePage>(this)->Copy();
+ case kProperty:
+ return To<StyleRuleProperty>(this)->Copy();
case kFontFace:
return To<StyleRuleFontFace>(this)->Copy();
case kMedia:
@@ -185,6 +194,10 @@ CSSRule* StyleRuleBase::CreateCSSOMWrapper(CSSStyleSheet* parent_sheet,
rule = MakeGarbageCollected<CSSPageRule>(To<StyleRulePage>(self),
parent_sheet);
break;
+ case kProperty:
+ rule = MakeGarbageCollected<CSSPropertyRule>(To<StyleRuleProperty>(self),
+ parent_sheet);
+ break;
case kFontFace:
rule = MakeGarbageCollected<CSSFontFaceRule>(To<StyleRuleFontFace>(self),
parent_sheet);
@@ -317,6 +330,27 @@ void StyleRulePage::TraceAfterDispatch(blink::Visitor* visitor) {
StyleRuleBase::TraceAfterDispatch(visitor);
}
+StyleRuleProperty::StyleRuleProperty(const String& name,
+ CSSPropertyValueSet* properties)
+ : StyleRuleBase(kProperty), name_(name), properties_(properties) {}
+
+StyleRuleProperty::StyleRuleProperty(const StyleRuleProperty& property_rule)
+ : StyleRuleBase(property_rule),
+ properties_(property_rule.properties_->MutableCopy()) {}
+
+StyleRuleProperty::~StyleRuleProperty() = default;
+
+MutableCSSPropertyValueSet& StyleRuleProperty::MutableProperties() {
+ if (!properties_->IsMutable())
+ properties_ = properties_->MutableCopy();
+ return *To<MutableCSSPropertyValueSet>(properties_.Get());
+}
+
+void StyleRuleProperty::TraceAfterDispatch(blink::Visitor* visitor) {
+ visitor->Trace(properties_);
+ StyleRuleBase::TraceAfterDispatch(visitor);
+}
+
StyleRuleFontFace::StyleRuleFontFace(CSSPropertyValueSet* properties)
: StyleRuleBase(kFontFace), properties_(properties) {}
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 774bb0bf94f..d465b100cda 100644
--- a/chromium/third_party/blink/renderer/core/css/style_rule.h
+++ b/chromium/third_party/blink/renderer/core/css/style_rule.h
@@ -47,6 +47,7 @@ class CORE_EXPORT StyleRuleBase
kMedia,
kFontFace,
kPage,
+ kProperty,
kKeyframes,
kKeyframe,
kNamespace,
@@ -64,6 +65,7 @@ class CORE_EXPORT StyleRuleBase
bool IsNamespaceRule() const { return GetType() == kNamespace; }
bool IsMediaRule() const { return GetType() == kMedia; }
bool IsPageRule() const { return GetType() == kPage; }
+ bool IsPropertyRule() const { return GetType() == kProperty; }
bool IsStyleRule() const { return GetType() == kStyle; }
bool IsSupportsRule() const { return GetType() == kSupports; }
bool IsViewportRule() const { return GetType() == kViewport; }
@@ -192,6 +194,32 @@ class StyleRulePage : public StyleRuleBase {
CSSSelectorList selector_list_;
};
+class StyleRuleProperty : public StyleRuleBase {
+ public:
+ static StyleRuleProperty* Create(const String& name,
+ CSSPropertyValueSet* properties) {
+ return MakeGarbageCollected<StyleRuleProperty>(name, properties);
+ }
+
+ StyleRuleProperty(const String& name, CSSPropertyValueSet*);
+ StyleRuleProperty(const StyleRuleProperty&);
+ ~StyleRuleProperty();
+
+ const CSSPropertyValueSet& Properties() const { return *properties_; }
+ MutableCSSPropertyValueSet& MutableProperties();
+ const String& GetName() const { return name_; }
+
+ StyleRuleProperty* Copy() const {
+ return MakeGarbageCollected<StyleRuleProperty>(*this);
+ }
+
+ void TraceAfterDispatch(blink::Visitor*);
+
+ private:
+ String name_;
+ Member<CSSPropertyValueSet> properties_;
+};
+
class CORE_EXPORT StyleRuleGroup : public StyleRuleBase {
public:
const HeapVector<Member<StyleRuleBase>>& ChildRules() const {
@@ -340,6 +368,13 @@ struct DowncastTraits<StyleRulePage> {
};
template <>
+struct DowncastTraits<StyleRuleProperty> {
+ static bool AllowFrom(const StyleRuleBase& rule) {
+ return rule.IsPropertyRule();
+ }
+};
+
+template <>
struct DowncastTraits<StyleRuleMedia> {
static bool AllowFrom(const StyleRuleBase& rule) {
return rule.IsMediaRule();
diff --git a/chromium/third_party/blink/renderer/core/css/style_rule_css_style_declaration.cc b/chromium/third_party/blink/renderer/core/css/style_rule_css_style_declaration.cc
index 0b02d74c462..4b45ec7238c 100644
--- a/chromium/third_party/blink/renderer/core/css/style_rule_css_style_declaration.cc
+++ b/chromium/third_party/blink/renderer/core/css/style_rule_css_style_declaration.cc
@@ -57,16 +57,6 @@ void StyleRuleCSSStyleDeclaration::Reattach(
property_set_ = &property_set;
}
-PropertyRegistry* StyleRuleCSSStyleDeclaration::GetPropertyRegistry() const {
- CSSStyleSheet* sheet = parent_rule_->parentStyleSheet();
- if (!sheet)
- return nullptr;
- Node* node = sheet->ownerNode();
- if (!node)
- return nullptr;
- return node->GetDocument().GetPropertyRegistry();
-}
-
void StyleRuleCSSStyleDeclaration::Trace(blink::Visitor* visitor) {
visitor->Trace(parent_rule_);
PropertySetCSSStyleDeclaration::Trace(visitor);
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 00f0d29a231..e3bc6fb5ddf 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
@@ -49,7 +49,6 @@ class StyleRuleCSSStyleDeclaration : public PropertySetCSSStyleDeclaration {
void WillMutate() override;
void DidMutate(MutationType) override;
- PropertyRegistry* GetPropertyRegistry() const final;
Member<CSSRule> 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 8c8944a0c14..9be8d3cde82 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,13 +34,15 @@
namespace blink {
StyleRuleImport::StyleRuleImport(const String& href,
- scoped_refptr<MediaQuerySet> media)
+ scoped_refptr<MediaQuerySet> media,
+ OriginClean origin_clean)
: StyleRuleBase(kImport),
parent_style_sheet_(nullptr),
style_sheet_client_(MakeGarbageCollected<ImportedStyleSheetClient>(this)),
str_href_(href),
media_queries_(media),
- loading_(false) {
+ loading_(false),
+ origin_clean_(origin_clean) {
if (!media_queries_)
media_queries_ = MediaQuerySet::Create(String());
}
@@ -133,6 +135,7 @@ void StyleRuleImport::RequestStyleSheet() {
options.initiator_info.name = fetch_initiator_type_names::kCSS;
FetchParameters params(ResourceRequest(abs_url), options);
params.SetCharset(parent_style_sheet_->Charset());
+ params.SetFromOriginDirtyStyleSheet(origin_clean_ != OriginClean::kTrue);
loading_ = true;
DCHECK(!style_sheet_client_->GetResource());
CSSStyleSheetResource::Fetch(params, fetcher, style_sheet_client_);
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 2e86fa5b7f7..cdfd0ef7bba 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
@@ -22,6 +22,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_STYLE_RULE_IMPORT_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_STYLE_RULE_IMPORT_H_
+#include "third_party/blink/renderer/core/css/css_origin_clean.h"
#include "third_party/blink/renderer/core/css/style_rule.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_client.h"
@@ -36,7 +37,9 @@ class StyleRuleImport : public StyleRuleBase {
USING_PRE_FINALIZER(StyleRuleImport, Dispose);
public:
- StyleRuleImport(const String& href, scoped_refptr<MediaQuerySet>);
+ StyleRuleImport(const String& href,
+ scoped_refptr<MediaQuerySet>,
+ OriginClean origin_clean);
~StyleRuleImport();
StyleSheetContents* ParentStyleSheet() const { return parent_style_sheet_; }
@@ -97,6 +100,9 @@ class StyleRuleImport : public StyleRuleBase {
scoped_refptr<MediaQuerySet> media_queries_;
Member<StyleSheetContents> style_sheet_;
bool loading_;
+ // Whether the style sheet that has this import rule is origin-clean:
+ // https://drafts.csswg.org/cssom-1/#concept-css-style-sheet-origin-clean-flag
+ const OriginClean origin_clean_;
};
template <>
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 801a537a62e..f6acf062758 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
@@ -35,7 +35,7 @@
#include "third_party/blink/renderer/core/css/active_style_sheets.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/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
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 ad58dcf77e5..31140d7094a 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
@@ -29,11 +29,11 @@
#include "third_party/blink/renderer/core/css/style_rule_namespace.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/node.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/inspector/inspector_trace_events.h"
#include "third_party/blink/renderer/core/loader/resource/css_style_sheet_resource.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
namespace blink {
@@ -510,6 +510,7 @@ static bool ChildRulesHaveFailedOrCanceledSubresources(
NOTREACHED();
break;
case StyleRuleBase::kPage:
+ case StyleRuleBase::kProperty:
case StyleRuleBase::kKeyframes:
case StyleRuleBase::kKeyframe:
case StyleRuleBase::kSupports:
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 afca618f8dd..2b9eb876a8f 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
@@ -22,9 +22,9 @@
#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/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/html_style_element.h"
#include "third_party/blink/renderer/core/html_names.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/css/svg.css b/chromium/third_party/blink/renderer/core/css/svg.css
index 091b6fec913..ce01fef0c1f 100644
--- a/chromium/third_party/blink/renderer/core/css/svg.css
+++ b/chromium/third_party/blink/renderer/core/css/svg.css
@@ -84,3 +84,8 @@ tspan, textPath {
*:not(svg), *:not(foreignObject) > svg {
transform-origin: 0 0;
}
+
+/* TODO(crbug.com/976224): Support zoom on foreignObject */
+foreignObject {
+ -internal-effective-zoom: initial !important;
+}
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 afa544e0650..6f1fd9ad972 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
@@ -5,6 +5,7 @@
#include "third_party/blink/renderer/core/css/css_to_length_conversion_data.h"
#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/renderer/core/css/css_numeric_literal_value.h"
#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"
@@ -32,8 +33,8 @@ TSAN_TEST(CSSToLengthConversionDataThreadedTest, ConversionEm) {
CSSToLengthConversionData conversionData(nullptr, fontSizes, viewportSize,
1);
- CSSPrimitiveValue& value =
- *CSSPrimitiveValue::Create(3.14, CSSPrimitiveValue::UnitType::kEms);
+ CSSPrimitiveValue& value = *CSSNumericLiteralValue::Create(
+ 3.14, CSSPrimitiveValue::UnitType::kEms);
Length length = value.ConvertToLength(conversionData);
EXPECT_EQ(length.Value(), 50.24f);
@@ -49,8 +50,8 @@ TSAN_TEST(CSSToLengthConversionDataThreadedTest, ConversionPixel) {
CSSToLengthConversionData conversionData(nullptr, fontSizes, viewportSize,
1);
- CSSPrimitiveValue& value =
- *CSSPrimitiveValue::Create(44, CSSPrimitiveValue::UnitType::kPixels);
+ CSSPrimitiveValue& value = *CSSNumericLiteralValue::Create(
+ 44, CSSPrimitiveValue::UnitType::kPixels);
Length length = value.ConvertToLength(conversionData);
EXPECT_EQ(length.Value(), 44);
@@ -66,7 +67,7 @@ TSAN_TEST(CSSToLengthConversionDataThreadedTest, ConversionViewport) {
CSSToLengthConversionData conversionData(nullptr, fontSizes, viewportSize,
1);
- CSSPrimitiveValue& value = *CSSPrimitiveValue::Create(
+ CSSPrimitiveValue& value = *CSSNumericLiteralValue::Create(
1, CSSPrimitiveValue::UnitType::kViewportWidth);
Length length = value.ConvertToLength(conversionData);
@@ -84,7 +85,7 @@ TSAN_TEST(CSSToLengthConversionDataThreadedTest, ConversionRem) {
1);
CSSPrimitiveValue& value =
- *CSSPrimitiveValue::Create(1, CSSPrimitiveValue::UnitType::kRems);
+ *CSSNumericLiteralValue::Create(1, CSSPrimitiveValue::UnitType::kRems);
Length length = value.ConvertToLength(conversionData);
EXPECT_EQ(length.Value(), 16);
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 9f788456606..3871a5e12fe 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,11 +12,10 @@
#include "base/single_thread_task_runner.h"
#include "base/synchronization/waitable_event.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/web_thread_supporting_gc.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
@@ -54,25 +53,19 @@ class MultiThreadedTest : public testing::Test {
// The default for this is 10*100 = 1000 times.
template <typename FunctionType, typename... Ps>
void RunOnThreads(FunctionType function, Ps&&... parameters) {
- Vector<std::unique_ptr<WebThreadSupportingGC>> threads;
+ Vector<std::unique_ptr<blink::Thread>> threads;
Vector<std::unique_ptr<base::WaitableEvent>> waits;
for (int i = 0; i < num_threads_; ++i) {
- threads.push_back(std::make_unique<WebThreadSupportingGC>(
- ThreadCreationParams(WebThreadType::kTestThread)));
+ threads.push_back(blink::Thread::CreateThread(
+ ThreadCreationParams(WebThreadType::kTestThread)
+ .SetSupportsGC(true)));
waits.push_back(std::make_unique<base::WaitableEvent>());
}
for (int i = 0; i < num_threads_; ++i) {
base::SingleThreadTaskRunner* task_runner =
- threads[i]->PlatformThread().GetTaskRunner().get();
-
- PostCrossThreadTask(*task_runner, FROM_HERE,
- CrossThreadBindOnce(
- [](WebThreadSupportingGC* thread) {
- thread->InitializeOnThread();
- },
- CrossThreadUnretained(threads[i].get())));
+ threads[i]->GetTaskRunner().get();
for (int j = 0; j < callbacks_per_thread_; ++j) {
PostCrossThreadTask(*task_runner, FROM_HERE,
@@ -81,13 +74,10 @@ class MultiThreadedTest : public testing::Test {
PostCrossThreadTask(
*task_runner, FROM_HERE,
- CrossThreadBindOnce(
- [](WebThreadSupportingGC* thread, base::WaitableEvent* w) {
- thread->ShutdownOnThread();
- w->Signal();
- },
- CrossThreadUnretained(threads[i].get()),
- CrossThreadUnretained(waits[i].get())));
+ CrossThreadBindOnce([](blink::Thread* thread,
+ base::WaitableEvent* w) { w->Signal(); },
+ CrossThreadUnretained(threads[i].get()),
+ CrossThreadUnretained(waits[i].get())));
}
for (int i = 0; i < num_threads_; ++i) {
diff --git a/chromium/third_party/blink/renderer/core/css/zoom_adjusted_pixel_value.h b/chromium/third_party/blink/renderer/core/css/zoom_adjusted_pixel_value.h
index 05cb1f9626e..81bf92f6b5d 100644
--- a/chromium/third_party/blink/renderer/core/css/zoom_adjusted_pixel_value.h
+++ b/chromium/third_party/blink/renderer/core/css/zoom_adjusted_pixel_value.h
@@ -5,6 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_ZOOM_ADJUSTED_PIXEL_VALUE_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_ZOOM_ADJUSTED_PIXEL_VALUE_H_
+#include "third_party/blink/renderer/core/css/css_numeric_literal_value.h"
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
#include "third_party/blink/renderer/core/layout/adjust_for_absolute_zoom.h"
@@ -14,7 +15,7 @@ class ComputedStyle;
inline CSSPrimitiveValue* ZoomAdjustedPixelValue(double value,
const ComputedStyle& style) {
- return CSSPrimitiveValue::Create(
+ return CSSNumericLiteralValue::Create(
AdjustForAbsoluteZoom::AdjustFloat(value, style),
CSSPrimitiveValue::UnitType::kPixels);
}
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 db3d6ed0151..9d286cff02a 100644
--- a/chromium/third_party/blink/renderer/core/display_lock/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/display_lock/BUILD.gn
@@ -2,6 +2,7 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
+import("//testing/libfuzzer/fuzzer_test.gni")
import("//third_party/blink/renderer/core/core.gni")
blink_core_sources("display_lock") {
@@ -26,3 +27,15 @@ blink_core_sources("display_lock") {
"//third_party/blink/renderer/bindings/core/v8:bindings_core_v8_generated",
]
}
+
+fuzzer_test("display_lock_fuzzer") {
+ sources = [
+ "display_lock_fuzzer.cc",
+ ]
+ deps = [
+ "//content/test/fuzzer:fuzzer_support",
+ ]
+
+ seed_corpus = "//third_party/blink/web_tests/wpt_internal/display-lock"
+ dict = "display_lock.dict"
+}
diff --git a/chromium/third_party/blink/renderer/core/display_lock/DEPS b/chromium/third_party/blink/renderer/core/display_lock/DEPS
new file mode 100644
index 00000000000..df774afac1e
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/display_lock/DEPS
@@ -0,0 +1,3 @@
+specific_include_rules = {
+ "display_lock_fuzzer.cc" : [ "+content/test/fuzzer/fuzzer_support.h" ],
+}
diff --git a/chromium/third_party/blink/renderer/core/display_lock/display_lock.dict b/chromium/third_party/blink/renderer/core/display_lock/display_lock.dict
new file mode 100644
index 00000000000..e8d53579c69
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/display_lock/display_lock.dict
@@ -0,0 +1,11 @@
+"displayLock.acquire"
+"displayLock.commit()"
+"displayLock.update()"
+"displayLock.updateAndCommit()"
+"activatable: true"
+"activatable: false"
+"timeout: Infinity"
+"timeout: 0"
+"timeout: 17"
+"size: [100, 100]"
+"contain: style layout"
diff --git a/chromium/third_party/blink/renderer/core/display_lock/display_lock_budget.cc b/chromium/third_party/blink/renderer/core/display_lock/display_lock_budget.cc
index 9cdd3da9f37..35a62be4289 100644
--- a/chromium/third_party/blink/renderer/core/display_lock/display_lock_budget.cc
+++ b/chromium/third_party/blink/renderer/core/display_lock/display_lock_budget.cc
@@ -12,12 +12,12 @@ namespace blink {
DisplayLockBudget::DisplayLockBudget(DisplayLockContext* context)
: clock_(base::DefaultTickClock::GetInstance()), context_(context) {}
-bool DisplayLockBudget::MarkAncestorsDirtyForPhaseIfNeeded(Phase phase) {
+bool DisplayLockBudget::MarkDirtyForPhaseIfNeeded(Phase phase) {
switch (phase) {
case Phase::kStyle:
return context_->MarkForStyleRecalcIfNeeded();
case Phase::kLayout:
- return context_->MarkAncestorsForLayoutIfNeeded();
+ return context_->MarkForLayoutIfNeeded();
case Phase::kPrePaint:
return context_->MarkAncestorsForPrePaintIfNeeded();
}
@@ -38,4 +38,13 @@ bool DisplayLockBudget::IsElementDirtyForPhase(Phase phase) const {
return false;
}
+void DisplayLockBudget::MarkPhaseAsDirty(Phase marking_phase) {
+ // Mark the next phase we're scheduled to run.
+ for (auto phase = static_cast<unsigned>(marking_phase);
+ phase <= static_cast<unsigned>(Phase::kLast); ++phase) {
+ if (MarkDirtyForPhaseIfNeeded(static_cast<Phase>(phase)))
+ break;
+ }
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/display_lock/display_lock_budget.h b/chromium/third_party/blink/renderer/core/display_lock/display_lock_budget.h
index f715ab24a63..aeea5fa3dbe 100644
--- a/chromium/third_party/blink/renderer/core/display_lock/display_lock_budget.h
+++ b/chromium/third_party/blink/renderer/core/display_lock/display_lock_budget.h
@@ -15,6 +15,8 @@ class TickClock;
namespace blink {
class DisplayLockContext;
+struct LifecycleData;
+
class CORE_EXPORT DisplayLockBudget {
public:
enum class Phase : unsigned {
@@ -30,14 +32,14 @@ class CORE_EXPORT DisplayLockBudget {
// Returns true if the given phase is allowed to proceed under the current
// budget.
- virtual bool ShouldPerformPhase(Phase) const = 0;
+ virtual bool ShouldPerformPhase(Phase, const LifecycleData&) = 0;
+
+ // Called just before any calls to ShouldPerformPhase for a new lifecycle.
+ virtual void OnLifecycleChange(const LifecycleData&) = 0;
// Notifies the budget that the given phase was completed.
virtual void DidPerformPhase(Phase) = 0;
- // Notifies the budget that a new lifecycle update phase is going to start.
- virtual void WillStartLifecycleUpdate() = 0;
-
// Returns true if according to this budget, we still need a lifecycle update.
// For example, if a budget blocked a needed phase, then it this will return
// true indicating that another frame is needed.
@@ -48,13 +50,16 @@ class CORE_EXPORT DisplayLockBudget {
void SetTickClockForTesting(const base::TickClock* clock) { clock_ = clock; }
protected:
- // Marks the ancestor chain dirty for the given phase if it's needed. Returns
- // true if the ancestors were marked dirty and false otherwise.
- bool MarkAncestorsDirtyForPhaseIfNeeded(Phase);
-
// Returns true if there is likely to be work for the given phase.
bool IsElementDirtyForPhase(Phase) const;
+ void MarkPhaseAsDirty(Phase marking_phase);
+
+ // Marks the element and ancestor chain dirty for the given phase if it's
+ // needed. Returns true if the ancestors were marked dirty and false
+ // otherwise.
+ bool MarkDirtyForPhaseIfNeeded(Phase);
+
const base::TickClock* clock_;
private:
diff --git a/chromium/third_party/blink/renderer/core/display_lock/display_lock_budget_test.cc b/chromium/third_party/blink/renderer/core/display_lock/display_lock_budget_test.cc
index 729587763a6..15f0f14001f 100644
--- a/chromium/third_party/blink/renderer/core/display_lock/display_lock_budget_test.cc
+++ b/chromium/third_party/blink/renderer/core/display_lock/display_lock_budget_test.cc
@@ -18,29 +18,24 @@
namespace blink {
-class DisplayLockBudgetTest : public RenderingTest {
+class DisplayLockBudgetTest : public RenderingTest,
+ private ScopedDisplayLockingForTest {
public:
+ DisplayLockBudgetTest() : ScopedDisplayLockingForTest(true) {}
void SetUp() override {
RenderingTest::SetUp();
- features_backup_.emplace();
- RuntimeEnabledFeatures::SetDisplayLockingEnabled(true);
test_task_runner_ = base::MakeRefCounted<base::TestMockTimeTaskRunner>();
}
- void TearDown() override {
- if (features_backup_) {
- features_backup_->Restore();
- features_backup_.reset();
- }
+ base::TimeDelta GetBudget(const YieldingDisplayLockBudget& budget,
+ const LifecycleData& lifecycle_data) const {
+ return budget.GetCurrentBudget(lifecycle_data);
}
- double GetBudgetMs(const YieldingDisplayLockBudget& budget) const {
- return budget.GetCurrentBudgetMs();
- }
-
- void ResetDeadlineForTesting(YieldingDisplayLockBudget& budget) {
- budget.deadline_ = CurrentTimeTicks() + TimeDelta::FromMillisecondsD(
- budget.GetCurrentBudgetMs());
+ void ResetDeadlineForTesting(YieldingDisplayLockBudget& budget,
+ const LifecycleData& lifecycle_data) {
+ budget.deadline_ =
+ base::TimeTicks::Now() + budget.GetCurrentBudget(lifecycle_data);
}
void ResetBudget(std::unique_ptr<DisplayLockBudget> budget,
@@ -83,16 +78,20 @@ TEST_F(DisplayLockBudgetTest, UnyieldingBudget) {
// need an update.
EXPECT_TRUE(budget.NeedsLifecycleUpdates());
+ LifecycleData lifecycle_data;
+
// Check everything twice since it shouldn't matter how many times we ask the
// unyielding budget, the results should always be the same.
for (int i = 0; i < 2; ++i) {
- budget.WillStartLifecycleUpdate();
// Note that although we only dirtied layout, all phases "should" complete,
// since the budget should never be responsible for blocking phases for any
// reason other than we're out of budget.
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint,
+ lifecycle_data));
budget.DidPerformPhase(DisplayLockBudget::Phase::kStyle);
budget.DidPerformPhase(DisplayLockBudget::Phase::kLayout);
budget.DidPerformPhase(DisplayLockBudget::Phase::kPrePaint);
@@ -126,79 +125,105 @@ TEST_F(DisplayLockBudgetTest, StrictYieldingBudget) {
// need an update.
EXPECT_TRUE(budget.NeedsLifecycleUpdates());
+ LifecycleData lifecycle_data;
+
{
- budget.WillStartLifecycleUpdate();
// Initially all of the phase checks should return true, since we don't know
// which phase the system wants to process next.
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint,
+ lifecycle_data));
// Not doing anything should ensure that we schedule another animation by
// returning true here.
EXPECT_TRUE(budget.NeedsLifecycleUpdates());
}
{
- budget.WillStartLifecycleUpdate();
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint));
+ lifecycle_data.count++;
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint,
+ lifecycle_data));
// Once we perform a phase, its check should remain true, but the rest
// will be false for this cycle.
budget.DidPerformPhase(DisplayLockBudget::Phase::kStyle);
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle));
- EXPECT_FALSE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout));
- EXPECT_FALSE(
- budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle,
+ lifecycle_data));
+ EXPECT_FALSE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout,
+ lifecycle_data));
+ EXPECT_FALSE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint,
+ lifecycle_data));
+ if (true)
+ return;
// We would need at least one more run to finish everything.
EXPECT_TRUE(budget.NeedsLifecycleUpdates());
}
{
- budget.WillStartLifecycleUpdate();
+ lifecycle_data.count++;
// Run the previous block again, now everything will always return true
// since the phase we complete here (style) has already been completed
// before, and we are open to complete a new phase.
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint,
+ lifecycle_data));
// Since we already befored style before, no new phase has been processed
// and all phases are allowed to finish.
budget.DidPerformPhase(DisplayLockBudget::Phase::kStyle);
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint,
+ lifecycle_data));
// We would need at least one more run to finish everything.
EXPECT_TRUE(budget.NeedsLifecycleUpdates());
}
{
- budget.WillStartLifecycleUpdate();
+ lifecycle_data.count++;
// On the next run, the checks for phases completed before should always
// return true, and as before since we haven't completed a new phase, the
// remainder of the phases should return true for now.
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint,
+ lifecycle_data));
// This check is the same as in the previous block, but is here to verify
// that going through NeedsLifecycleUpdates() and then
// WillStartLifecycleUpdate() again doesn't change the fact that we should
// still perform all of the phases at this point.
budget.DidPerformPhase(DisplayLockBudget::Phase::kStyle);
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint,
+ lifecycle_data));
// Let's say layout was clean and we jumped and did prepaint instead, now
// every phase before and including prepaint should be true, the rest are
// locked from completing.
budget.DidPerformPhase(DisplayLockBudget::Phase::kPrePaint);
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint,
+ lifecycle_data));
// Note that since we processed everything, we no longer need lifecycle
// updates.
@@ -206,28 +231,40 @@ TEST_F(DisplayLockBudgetTest, StrictYieldingBudget) {
}
{
// Do one more run to ensure everything is still returning true.
- budget.WillStartLifecycleUpdate();
+ lifecycle_data.count++;
// On the last run, we'll complete all phases. Since there is only one
// remaining phase we haven't done, all of the checks should always return
// true (it's either an old phase or a first uncompleted phase).
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint,
+ lifecycle_data));
budget.DidPerformPhase(DisplayLockBudget::Phase::kStyle);
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint,
+ lifecycle_data));
budget.DidPerformPhase(DisplayLockBudget::Phase::kLayout);
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint,
+ lifecycle_data));
budget.DidPerformPhase(DisplayLockBudget::Phase::kPrePaint);
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint,
+ lifecycle_data));
// Since we completed everything, we should now be returning false here (no
// more updates needed).
@@ -262,14 +299,18 @@ TEST_F(DisplayLockBudgetTest,
// When acquiring, we need to update the layout with the locked size, so we
// need an update.
EXPECT_TRUE(budget.NeedsLifecycleUpdates());
- budget.WillStartLifecycleUpdate();
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout));
+ LifecycleData lifecycle_data;
+ budget.OnLifecycleChange(lifecycle_data);
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout,
+ lifecycle_data));
budget.DidPerformPhase(DisplayLockBudget::Phase::kLayout);
EXPECT_TRUE(budget.NeedsLifecycleUpdates());
- budget.WillStartLifecycleUpdate();
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint));
+ lifecycle_data.count++;
+ budget.OnLifecycleChange(lifecycle_data);
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint,
+ lifecycle_data));
budget.DidPerformPhase(DisplayLockBudget::Phase::kPrePaint);
// Note that since the layout was indicated as done (from the budget
@@ -306,79 +347,110 @@ TEST_F(DisplayLockBudgetTest, YieldingBudget) {
// When acquiring, we need to update the layout with the locked size, so we
// need an update.
EXPECT_TRUE(budget.NeedsLifecycleUpdates());
+ LifecycleData lifecycle_data;
+ budget.OnLifecycleChange(lifecycle_data);
- budget.WillStartLifecycleUpdate();
// Initially all of the phase checks should return true, since we don't know
// which phase the system wants to process next.
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint,
+ lifecycle_data));
// Not doing anything should ensure that we schedule another animation by
// returning true here.
EXPECT_TRUE(budget.NeedsLifecycleUpdates());
// Advancing the clock a bit will make us still want to the phases.
- test_task_runner_->FastForwardBy(
- TimeDelta::FromMillisecondsD(GetBudgetMs(budget) / 2));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint));
+ test_task_runner_->FastForwardBy(GetBudget(budget, lifecycle_data) / 2);
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint,
+ lifecycle_data));
// However, once we're out of budget, we will only do the next phase.
- test_task_runner_->FastForwardBy(
- TimeDelta::FromMillisecondsD(GetBudgetMs(budget)));
+ test_task_runner_->FastForwardBy(GetBudget(budget, lifecycle_data));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle));
- EXPECT_FALSE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout));
- EXPECT_FALSE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle,
+ lifecycle_data));
+ EXPECT_FALSE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout,
+ lifecycle_data));
+ EXPECT_FALSE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint,
+ lifecycle_data));
// Starting a new lifecycle will reset the budget.
- budget.WillStartLifecycleUpdate();
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint));
+ lifecycle_data.count++;
+ lifecycle_data.start_time = test_task_runner_->NowTicks();
+ budget.OnLifecycleChange(lifecycle_data);
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout,
+ lifecycle_data));
+
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint,
+ lifecycle_data));
// Performing a phase still keeps the rest of the phases available for work
// since we haven't advanced the clock.
budget.DidPerformPhase(DisplayLockBudget::Phase::kStyle);
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint,
+ lifecycle_data));
// Now that we're out of budget, phases performed previously should remain
// true.
- test_task_runner_->FastForwardBy(
- TimeDelta::FromMillisecondsD(GetBudgetMs(budget) * 2));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle));
- EXPECT_FALSE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout));
- EXPECT_FALSE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint));
+ test_task_runner_->FastForwardBy(GetBudget(budget, lifecycle_data) * 2);
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle,
+ lifecycle_data));
+ EXPECT_FALSE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout,
+ lifecycle_data));
+ EXPECT_FALSE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint,
+ lifecycle_data));
// Sanity check here: the element still needs layout.
EXPECT_TRUE(budget.NeedsLifecycleUpdates());
// Resetting the budget, and advancing again should yield the same results as
// before, except that we will process at least one more phase.
- budget.WillStartLifecycleUpdate();
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint));
- test_task_runner_->FastForwardBy(
- TimeDelta::FromMillisecondsD(GetBudgetMs(budget) * 2));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout));
- EXPECT_FALSE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint));
+ lifecycle_data.count++;
+ lifecycle_data.start_time = test_task_runner_->NowTicks();
+ budget.OnLifecycleChange(lifecycle_data);
+
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint,
+ lifecycle_data));
+ test_task_runner_->FastForwardBy(GetBudget(budget, lifecycle_data) * 2);
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout,
+ lifecycle_data));
+ EXPECT_FALSE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint,
+ lifecycle_data));
// Eventually the budget becomes essentially infinite.
- for (int i = 0; i < 60; ++i)
- budget.WillStartLifecycleUpdate();
+ lifecycle_data.count += 60;
+ budget.OnLifecycleChange(lifecycle_data);
- EXPECT_GT(GetBudgetMs(budget), 1e6);
+ EXPECT_GT(GetBudget(budget, lifecycle_data),
+ base::TimeDelta::FromMilliseconds(1e6));
for (int i = 0; i < 60; ++i) {
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout));
- EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint));
- test_task_runner_->FastForwardBy(TimeDelta::FromMillisecondsD(10000));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kStyle,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kLayout,
+ lifecycle_data));
+ EXPECT_TRUE(budget.ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint,
+ lifecycle_data));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromMillisecondsD(10000));
}
}
@@ -408,7 +480,6 @@ TEST_F(DisplayLockBudgetTest, YieldingBudgetMarksNextPhase) {
auto budget_owned = base::WrapUnique(
new YieldingDisplayLockBudget(element->GetDisplayLockContext()));
- ;
auto* budget = budget_owned.get();
budget->SetTickClockForTesting(test_task_runner_->GetMockTickClock());
{
@@ -428,39 +499,54 @@ TEST_F(DisplayLockBudgetTest, YieldingBudgetMarksNextPhase) {
auto* parent = GetDocument().getElementById("parent");
EXPECT_TRUE(budget->NeedsLifecycleUpdates());
- element->GetDisplayLockContext()->WillStartLifecycleUpdate(
- *GetDocument().GetFrame()->View());
+ LifecycleData lifecycle_data;
+ budget->OnLifecycleChange(lifecycle_data);
+
+ GetDocument().View()->SetInLifecycleUpdateForTest(true);
+ GetDocument().View()->SetLifecycleDataForTesting(lifecycle_data);
// Initially all of the phase checks should return true, since we don't know
// which phase the system wants to process next.
- EXPECT_TRUE(budget->ShouldPerformPhase(DisplayLockBudget::Phase::kStyle));
- EXPECT_TRUE(budget->ShouldPerformPhase(DisplayLockBudget::Phase::kLayout));
- EXPECT_TRUE(budget->ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint));
+ EXPECT_TRUE(
+ budget->ShouldPerformPhase(DisplayLockBudget::Phase::kStyle,
+ GetDocument().View()->CurrentLifecycleData()));
+ EXPECT_TRUE(
+ budget->ShouldPerformPhase(DisplayLockBudget::Phase::kLayout,
+ GetDocument().View()->CurrentLifecycleData()));
+ EXPECT_TRUE(
+ budget->ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint,
+ GetDocument().View()->CurrentLifecycleData()));
EXPECT_TRUE(parent->NeedsStyleRecalc() || parent->ChildNeedsStyleRecalc());
EXPECT_TRUE(element->NeedsStyleRecalc() || element->ChildNeedsStyleRecalc());
test_task_runner_->FastForwardBy(
- TimeDelta::FromMillisecondsD(GetBudgetMs(*budget) * 2));
- EXPECT_TRUE(budget->ShouldPerformPhase(DisplayLockBudget::Phase::kStyle));
- EXPECT_FALSE(budget->ShouldPerformPhase(DisplayLockBudget::Phase::kLayout));
+ GetBudget(*budget, GetDocument().View()->CurrentLifecycleData()) * 2);
+ EXPECT_TRUE(
+ budget->ShouldPerformPhase(DisplayLockBudget::Phase::kStyle,
+ GetDocument().View()->CurrentLifecycleData()));
+ EXPECT_FALSE(
+ budget->ShouldPerformPhase(DisplayLockBudget::Phase::kLayout,
+ GetDocument().View()->CurrentLifecycleData()));
GetDocument().UpdateStyleAndLayoutTree();
-
- EXPECT_FALSE(budget->ShouldPerformPhase(DisplayLockBudget::Phase::kLayout));
+ EXPECT_FALSE(
+ budget->ShouldPerformPhase(DisplayLockBudget::Phase::kLayout,
+ GetDocument().View()->CurrentLifecycleData()));
EXPECT_FALSE(parent->NeedsStyleRecalc() || parent->ChildNeedsStyleRecalc());
EXPECT_FALSE(element->NeedsStyleRecalc() || element->ChildNeedsStyleRecalc());
- EXPECT_FALSE(parent->GetLayoutObject()->NeedsLayout());
+ EXPECT_TRUE(parent->GetLayoutObject()->NeedsLayout());
EXPECT_TRUE(element->GetLayoutObject()->NeedsLayout());
- ResetDeadlineForTesting(*budget);
- budget->DidPerformPhase(DisplayLockBudget::Phase::kStyle);
- EXPECT_TRUE(budget->ShouldPerformPhase(DisplayLockBudget::Phase::kLayout));
+ ResetDeadlineForTesting(*budget,
+ GetDocument().View()->CurrentLifecycleData());
+ EXPECT_TRUE(
+ budget->ShouldPerformPhase(DisplayLockBudget::Phase::kLayout,
+ GetDocument().View()->CurrentLifecycleData()));
- EXPECT_TRUE(parent->GetLayoutObject()->NeedsLayout());
- EXPECT_TRUE(element->GetLayoutObject()->NeedsLayout());
+ GetDocument().View()->SetInLifecycleUpdateForTest(false);
}
TEST_F(DisplayLockBudgetTest, UpdateHappensInLifecycleOnly) {
@@ -501,28 +587,34 @@ TEST_F(DisplayLockBudgetTest, UpdateHappensInLifecycleOnly) {
// need an update.
EXPECT_TRUE(budget->NeedsLifecycleUpdates());
+ LifecycleData lifecycle_data;
+ budget->OnLifecycleChange(lifecycle_data);
+
auto* context = element->GetDisplayLockContext();
- EXPECT_TRUE(budget->ShouldPerformPhase(DisplayLockBudget::Phase::kStyle));
- EXPECT_TRUE(budget->ShouldPerformPhase(DisplayLockBudget::Phase::kLayout));
- EXPECT_TRUE(budget->ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint));
+ EXPECT_TRUE(budget->ShouldPerformPhase(DisplayLockBudget::Phase::kStyle,
+ lifecycle_data));
+ EXPECT_TRUE(budget->ShouldPerformPhase(DisplayLockBudget::Phase::kLayout,
+ lifecycle_data));
+ EXPECT_TRUE(budget->ShouldPerformPhase(DisplayLockBudget::Phase::kPrePaint,
+ lifecycle_data));
// Since we're not in a lifecycle, the budget itself should not want to do any
// phases, even though the budget allows it.
EXPECT_FALSE(context->ShouldStyle(DisplayLockContext::kChildren));
EXPECT_FALSE(context->ShouldLayout(DisplayLockContext::kChildren));
- EXPECT_FALSE(context->ShouldPrePaint());
+ EXPECT_FALSE(context->ShouldPrePaint(DisplayLockContext::kChildren));
- context->WillStartLifecycleUpdate(*GetDocument().GetFrame()->View());
+ GetDocument().GetFrame()->View()->SetInLifecycleUpdateForTest(true);
EXPECT_TRUE(context->ShouldStyle(DisplayLockContext::kChildren));
EXPECT_TRUE(context->ShouldLayout(DisplayLockContext::kChildren));
- EXPECT_TRUE(context->ShouldPrePaint());
+ EXPECT_TRUE(context->ShouldPrePaint(DisplayLockContext::kChildren));
- context->DidFinishLifecycleUpdate(*GetDocument().GetFrame()->View());
+ GetDocument().GetFrame()->View()->SetInLifecycleUpdateForTest(false);
EXPECT_FALSE(context->ShouldStyle(DisplayLockContext::kChildren));
EXPECT_FALSE(context->ShouldLayout(DisplayLockContext::kChildren));
- EXPECT_FALSE(context->ShouldPrePaint());
+ EXPECT_FALSE(context->ShouldPrePaint(DisplayLockContext::kChildren));
// Ensure to flush any tasks scheduled by context calls.
test::RunPendingTasks();
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 3b09b764578..3b3435a6a6a 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
@@ -9,6 +9,7 @@
#include "base/memory/ptr_util.h"
#include "third_party/blink/renderer/core/css/style_change_reason.h"
#include "third_party/blink/renderer/core/display_lock/display_lock_options.h"
+#include "third_party/blink/renderer/core/display_lock/display_lock_utilities.h"
#include "third_party/blink/renderer/core/display_lock/strict_yielding_display_lock_budget.h"
#include "third_party/blink/renderer/core/display_lock/unyielding_display_lock_budget.h"
#include "third_party/blink/renderer/core/display_lock/yielding_display_lock_budget.h"
@@ -43,6 +44,7 @@ const char* kUnsupportedDisplay =
const char* kElementIsDisconnected = "Element is disconnected.";
const char* kLockCommitted = "Lock commit was requested.";
const char* kInvalidOptions = "Invalid options.";
+const char* kElementIsNested = "Element is nested under a locked element.";
} // namespace rejection_names
// Helper function to convert a display locking state to a string. Used in
@@ -92,10 +94,7 @@ DisplayLockContext::DisplayLockContext(Element* element,
: ContextLifecycleObserver(context),
element_(element),
document_(&element_->GetDocument()),
- state_(this) {
- if (document_->View())
- document_->View()->RegisterForLifecycleNotifications(this);
-}
+ state_(this) {}
DisplayLockContext::~DisplayLockContext() {
DCHECK_EQ(state_, kUnlocked);
@@ -125,9 +124,6 @@ void DisplayLockContext::Dispose() {
FinishAcquireResolver(kDetach);
CancelTimeoutTask();
state_ = kUnlocked;
-
- if (document_ && document_->View())
- document_->View()->UnregisterFromLifecycleNotifications(this);
}
void DisplayLockContext::ContextDestroyed(ExecutionContext*) {
@@ -149,6 +145,11 @@ bool DisplayLockContext::HasPendingActivity() const {
ScriptPromise DisplayLockContext::acquire(ScriptState* script_state,
DisplayLockOptions* options) {
TRACE_EVENT0("blink", "DisplayLockContext::acquire()");
+ if (!GetExecutionContext()) {
+ return GetRejectedPromise(script_state,
+ rejection_names::kExecutionContextDestroyed);
+ }
+
double timeout_ms = (options && options->hasTimeout())
? options->timeout()
: kDefaultLockTimeoutMs;
@@ -162,13 +163,21 @@ ScriptPromise DisplayLockContext::acquire(ScriptState* script_state,
}
activatable_ = options && options->activatable();
+ // If we're acquiring something that isn't currently locked, we need to recalc
+ // the layout size. Otherwise if we're re-acquiring, we only need to recalc if
+ // the locked size has changed.
+ bool should_recalc_layout_size = !IsLocked();
if (options && options->hasSize()) {
auto parsed_size = ParseAndVerifySize(options->size());
- if (!parsed_size) {
+ if (!parsed_size)
return GetRejectedPromise(script_state, rejection_names::kInvalidOptions);
- }
+ if (locked_content_logical_size_ != *parsed_size)
+ should_recalc_layout_size = true;
locked_content_logical_size_ = *parsed_size;
+
} else {
+ if (locked_content_logical_size_ != LayoutSize())
+ should_recalc_layout_size = true;
locked_content_logical_size_ = LayoutSize();
}
@@ -177,6 +186,14 @@ ScriptPromise DisplayLockContext::acquire(ScriptState* script_state,
// interval. Note that the following call cancels any existing timeout tasks.
RescheduleTimeoutTask(timeout_ms);
+ if (should_recalc_layout_size && ConnectedToView()) {
+ if (auto* layout_object = element_->GetLayoutObject()) {
+ layout_object->SetNeedsLayoutAndPrefWidthsRecalc(
+ layout_invalidation_reason::kDisplayLock);
+ }
+ ScheduleAnimation();
+ }
+
if (acquire_resolver_)
return acquire_resolver_->Promise();
@@ -193,31 +210,28 @@ ScriptPromise DisplayLockContext::acquire(ScriptState* script_state,
FinishCommitResolver(kResolve);
update_budget_.reset();
+ state_ = kLocked;
- // If we're already connected then we need to ensure that we update our layout
- // size based on the options and we have cleared the painted output.
+ // If we're already connected then we need to ensure that we update our style
+ // to check for containment later, layout size based on the options, and
+ // also clear the painted output.
if (ConnectedToView()) {
- if (auto* reason = ShouldForceUnlock()) {
- // The element has up-to-date style and doesn't satisfy the containment
- // or display type requirement, so we unlock and reject now.
- // If the style needs recalc we would instead check the requirements after
- // style recalc for this element.
- DCHECK(!element_->NeedsStyleRecalc());
- CancelTimeoutTask();
- state_ = kUnlocked;
- return GetRejectedPromise(script_state, reason);
- }
-
- acquire_resolver_ =
- MakeGarbageCollected<ScriptPromiseResolver>(script_state);
+ element_->SetNeedsStyleRecalc(
+ kLocalStyleChange,
+ StyleChangeReasonForTracing::Create(style_change_reason::kDisplayLock));
+ MakeResolver(script_state, &acquire_resolver_);
is_horizontal_writing_mode_ = true;
if (auto* layout_object = element_->GetLayoutObject()) {
- layout_object->SetNeedsLayoutAndPrefWidthsRecalc(
- layout_invalidation_reason::kDisplayLock);
is_horizontal_writing_mode_ = layout_object->IsHorizontalWritingMode();
+ // GraphicsLayer collection would normally skip layers if paint is blocked
+ // by display-locking (see: CollectDrawableLayersForLayerListRecursively
+ // in LocalFrameView). However, if we don't trigger this collection, then
+ // we might use the cached result instead. In order to ensure we skip the
+ // newly locked layers, we need to set |need_graphics_layer_collection_|
+ // before marking the layer for repaint.
+ needs_graphics_layer_collection_ = true;
+ MarkPaintLayerNeedsRepaint();
}
- MarkPaintLayerNeedsRepaint();
- ScheduleAnimation();
// TODO(vmpstr): This needs to be set after invalidation above, since we
// want the object to layout once. After the changes to separate self and
// child layout, this would no longer be required and we can set the
@@ -226,7 +240,6 @@ ScriptPromise DisplayLockContext::acquire(ScriptState* script_state,
return acquire_resolver_->Promise();
}
- state_ = kLocked;
// Otherwise (if we're not connected), resolve immediately.
return GetResolvedPromise(script_state);
}
@@ -246,11 +259,29 @@ ScriptPromise DisplayLockContext::update(ScriptState* script_state) {
return update_resolver_->Promise();
}
- update_resolver_ = MakeGarbageCollected<ScriptPromiseResolver>(script_state);
+ if (DisplayLockUtilities::NearestLockedExclusiveAncestor(*element_)) {
+ return GetRejectedPromise(script_state, rejection_names::kElementIsNested);
+ }
+
+ MakeResolver(script_state, &update_resolver_);
StartUpdateIfNeeded();
return update_resolver_->Promise();
}
+bool DisplayLockContext::CleanupAndRejectCommitIfNotConnected() {
+ // If we're not connected, then the process of committing is the same as just
+ // unlocking the element. Early out if this conditions *doesn't* hold.
+ if (ConnectedToView())
+ return false;
+
+ state_ = kUnlocked;
+ update_budget_.reset();
+ // Note that we reject the update, but resolve the commit.
+ FinishUpdateResolver(kReject, rejection_names::kElementIsDisconnected);
+ FinishCommitResolver(kResolve);
+ return true;
+}
+
ScriptPromise DisplayLockContext::commit(ScriptState* script_state) {
TRACE_EVENT0("blink", "DisplayLockContext::commit()");
// Resolve if we're already unlocked.
@@ -268,12 +299,15 @@ ScriptPromise DisplayLockContext::commit(ScriptState* script_state) {
return commit_resolver_->Promise();
}
+ if (CleanupAndRejectCommitIfNotConnected())
+ return GetResolvedPromise(script_state);
+
// Note that we don't resolve the update promise here, since it should still
// finish updating before resolution. That is, calling update() and commit()
// together will still wait until the lifecycle is clean before resolving any
// of the promises.
- commit_resolver_ = MakeGarbageCollected<ScriptPromiseResolver>(script_state);
+ MakeResolver(script_state, &commit_resolver_);
auto promise = commit_resolver_->Promise();
// It's possible we are already committing due to activation. If not, we
// should start the commit.
@@ -282,6 +316,17 @@ ScriptPromise DisplayLockContext::commit(ScriptState* script_state) {
return promise;
}
+void DisplayLockContext::MakeResolver(ScriptState* script_state,
+ Member<ScriptPromiseResolver>* resolver) {
+ DCHECK(ConnectedToView());
+ document_->View()->RegisterForLifecycleNotifications(this);
+ *resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state);
+}
+
+bool DisplayLockContext::HasResolver() {
+ return acquire_resolver_ || update_resolver_ || commit_resolver_;
+}
+
ScriptPromise DisplayLockContext::updateAndCommit(ScriptState* script_state) {
TRACE_EVENT0("blink", "DisplayLockContext::updateAndCommit()");
@@ -290,10 +335,12 @@ ScriptPromise DisplayLockContext::updateAndCommit(ScriptState* script_state) {
return GetResolvedPromise(script_state);
// If we're in a state where a co-operative update doesn't make sense (e.g. we
- // haven't acquired the lock, or we're already sync committing), then do
- // whatever commit() would do.
- if (state_ == kCommitting || !ConnectedToView())
+ // haven't acquired the lock, or we're already sync committing, or we're under
+ // a nested lock), then do whatever commit() would do.
+ if (state_ == kCommitting || !ConnectedToView() ||
+ DisplayLockUtilities::NearestLockedExclusiveAncestor(*element_)) {
return commit(script_state);
+ }
// If we have a commit resolver already, return it.
if (commit_resolver_) {
@@ -304,7 +351,7 @@ ScriptPromise DisplayLockContext::updateAndCommit(ScriptState* script_state) {
}
CancelTimeoutTask();
- commit_resolver_ = MakeGarbageCollected<ScriptPromiseResolver>(script_state);
+ MakeResolver(script_state, &commit_resolver_);
StartUpdateIfNeeded();
return commit_resolver_->Promise();
}
@@ -348,19 +395,39 @@ void DisplayLockContext::FinishResolver(Member<ScriptPromiseResolver>* resolver,
break;
case kDetach:
(*resolver)->Detach();
+ break;
}
*resolver = nullptr;
+ if (!HasResolver() && ConnectedToView())
+ document_->View()->UnregisterFromLifecycleNotifications(this);
+}
+
+bool DisplayLockContext::ShouldPerformUpdatePhase(
+ DisplayLockBudget::Phase phase) const {
+ DCHECK(document_);
+ if (state_ != kUpdating)
+ return false;
+ auto* view = document_->View();
+ return view && view->InLifecycleUpdate() &&
+ update_budget_->ShouldPerformPhase(phase,
+ view->CurrentLifecycleData());
}
bool DisplayLockContext::ShouldStyle(LifecycleTarget target) const {
return target == kSelf || update_forced_ || state_ > kUpdating ||
- (state_ == kUpdating && in_lifecycle_update_ &&
- update_budget_->ShouldPerformPhase(DisplayLockBudget::Phase::kStyle));
+ ShouldPerformUpdatePhase(DisplayLockBudget::Phase::kStyle);
}
void DisplayLockContext::DidStyle(LifecycleTarget target) {
- if (state_ == kUnlocked)
+ if (state_ == kUnlocked) {
+ // If we're committing without finishing the acquire() first, it's possible
+ // for the state to be kUnlocked instead of kCommitting. We should still
+ // mark child reattachment & whitespace reattachment in that case.
+ MarkElementsForWhitespaceReattachment();
+ if (element_->ChildNeedsReattachLayoutTree())
+ element_->MarkAncestorsWithChildNeedsReattachLayoutTree();
return;
+ }
if (target == kSelf) {
if (ForceUnlockIfNeeded())
@@ -377,6 +444,9 @@ void DisplayLockContext::DidStyle(LifecycleTarget target) {
if (state_ != kCommitting && state_ != kUpdating && !update_forced_)
return;
+ if (element_->ChildNeedsReattachLayoutTree())
+ element_->MarkAncestorsWithChildNeedsReattachLayoutTree();
+
blocked_style_traversal_type_ = kStyleUpdateNotRequired;
MarkElementsForWhitespaceReattachment();
@@ -387,27 +457,28 @@ void DisplayLockContext::DidStyle(LifecycleTarget target) {
bool DisplayLockContext::ShouldLayout(LifecycleTarget target) const {
return target == kSelf || update_forced_ || state_ > kUpdating ||
- (state_ == kUpdating && in_lifecycle_update_ &&
- update_budget_->ShouldPerformPhase(
- DisplayLockBudget::Phase::kLayout));
+ ShouldPerformUpdatePhase(DisplayLockBudget::Phase::kLayout);
}
void DisplayLockContext::DidLayout(LifecycleTarget target) {
if (target == kSelf)
return;
+ // Since we did layout on children already, we'll clear this.
+ child_layout_was_blocked_ = false;
if (state_ == kUpdating)
update_budget_->DidPerformPhase(DisplayLockBudget::Phase::kLayout);
}
-bool DisplayLockContext::ShouldPrePaint() const {
- return update_forced_ || state_ > kUpdating ||
- (state_ == kUpdating && in_lifecycle_update_ &&
- update_budget_->ShouldPerformPhase(
- DisplayLockBudget::Phase::kPrePaint));
+bool DisplayLockContext::ShouldPrePaint(LifecycleTarget target) const {
+ return target == kSelf || update_forced_ || state_ > kUpdating ||
+ ShouldPerformUpdatePhase(DisplayLockBudget::Phase::kPrePaint);
}
-void DisplayLockContext::DidPrePaint() {
+void DisplayLockContext::DidPrePaint(LifecycleTarget target) {
+ if (target == kSelf)
+ return;
+
if (state_ == kUpdating)
update_budget_->DidPerformPhase(DisplayLockBudget::Phase::kPrePaint);
@@ -420,15 +491,15 @@ void DisplayLockContext::DidPrePaint() {
#endif
}
-bool DisplayLockContext::ShouldPaint() const {
+bool DisplayLockContext::ShouldPaint(LifecycleTarget target) const {
// Note that forced updates should never require us to paint, so we don't
// check |update_forced_| here. In other words, although |update_forced_|
// could be true here, we still should not paint. This also holds for
// kUpdating state, since updates should not paint.
- return state_ == kCommitting || state_ == kUnlocked;
+ return target == kSelf || state_ == kCommitting || state_ == kUnlocked;
}
-void DisplayLockContext::DidPaint() {
+void DisplayLockContext::DidPaint(LifecycleTarget) {
// This is here for symmetry, but could be removed if necessary.
}
@@ -450,8 +521,6 @@ bool DisplayLockContext::ShouldCommitForActivation() const {
void DisplayLockContext::DidAttachLayoutTree() {
if (state_ >= kUnlocked)
return;
- if (ForceUnlockIfNeeded())
- return;
if (auto* layout_object = element_->GetLayoutObject())
is_horizontal_writing_mode_ = layout_object->IsHorizontalWritingMode();
@@ -470,7 +539,7 @@ DisplayLockContext::GetScopedForcedUpdate() {
// this, since |update_forced_| doesn't force paint to happen. See
// ShouldPaint().
MarkForStyleRecalcIfNeeded();
- MarkAncestorsForLayoutIfNeeded();
+ MarkForLayoutIfNeeded();
MarkAncestorsForPrePaintIfNeeded();
return ScopedForcedUpdate(this);
}
@@ -483,16 +552,8 @@ void DisplayLockContext::NotifyForcedUpdateScopeEnded() {
void DisplayLockContext::StartCommit() {
// Since we are starting a commit, cancel the timeout task.
CancelTimeoutTask();
- // If we don't have an element or we're not connected, then the process of
- // committing is the same as just unlocking the element.
- if (!element_ || !ConnectedToView()) {
- state_ = kUnlocked;
- update_budget_.reset();
- // Note that we reject the update, but resolve the commit.
- FinishUpdateResolver(kReject, rejection_names::kElementIsDisconnected);
- FinishCommitResolver(kResolve);
+ if (CleanupAndRejectCommitIfNotConnected())
return;
- }
// If we have an acquire resolver, it means that we haven't had a chance to
// run the lifecycle yet to clear the painted output. However, we're being
@@ -523,7 +584,7 @@ void DisplayLockContext::StartCommit() {
// Now that we know we have a layout object, we should ensure that we can
// reach the rest of the phases as well.
- MarkAncestorsForLayoutIfNeeded();
+ MarkForLayoutIfNeeded();
MarkAncestorsForPrePaintIfNeeded();
MarkPaintLayerNeedsRepaint();
@@ -577,6 +638,12 @@ void DisplayLockContext::MarkElementsForWhitespaceReattachment() {
}
bool DisplayLockContext::MarkForStyleRecalcIfNeeded() {
+ if (reattach_layout_tree_was_blocked_) {
+ // We previously blocked a layout tree reattachment on |element_|'s
+ // descendants, so we should mark it for layout tree reattachment now.
+ element_->SetForceReattachLayoutTree();
+ reattach_layout_tree_was_blocked_ = false;
+ }
if (IsElementDirtyForStyleRecalc()) {
if (blocked_style_traversal_type_ > kStyleUpdateNotRequired) {
// We blocked a traversal going to the element previously.
@@ -591,6 +658,12 @@ bool DisplayLockContext::MarkForStyleRecalcIfNeeded() {
if (blocked_style_traversal_type_ == kStyleUpdateChildren)
element_->SetChildNeedsStyleRecalc();
blocked_style_traversal_type_ = kStyleUpdateNotRequired;
+ } else if (element_->ChildNeedsReattachLayoutTree()) {
+ // Mark |element_| as style dirty, as we can't mark for child reattachment
+ // before style.
+ element_->SetNeedsStyleRecalc(kLocalStyleChange,
+ StyleChangeReasonForTracing::Create(
+ style_change_reason::kDisplayLock));
}
// Propagate to the ancestors, since the dirty bit in a locked subtree is
// stopped at the locked ancestor.
@@ -601,9 +674,26 @@ bool DisplayLockContext::MarkForStyleRecalcIfNeeded() {
return false;
}
-bool DisplayLockContext::MarkAncestorsForLayoutIfNeeded() {
+bool DisplayLockContext::MarkForLayoutIfNeeded() {
if (IsElementDirtyForLayout()) {
- element_->GetLayoutObject()->MarkContainerChainForLayout();
+ // Forces the marking of ancestors to happen, even if
+ // |DisplayLockContext::ShouldLayout()| returns false.
+ base::AutoReset<bool> scoped_force(&update_forced_, true);
+ if (child_layout_was_blocked_) {
+ // We've previously blocked a child traversal when doing self-layout for
+ // the locked element, so we're marking it with child-needs-layout so that
+ // it will traverse to the locked element and do the child traversal
+ // again. We don't need to mark it for self-layout (by calling
+ // |LayoutObject::SetNeedsLayout()|) because the locked element itself
+ // doesn't need to relayout.
+ element_->GetLayoutObject()->SetChildNeedsLayout();
+ child_layout_was_blocked_ = false;
+ } else {
+ // Since the dirty layout propagation stops at the locked element, we need
+ // to mark its ancestors as dirty here so that it will be traversed to on
+ // the next layout.
+ element_->GetLayoutObject()->MarkContainerChainForLayout();
+ }
return true;
}
return false;
@@ -622,6 +712,9 @@ bool DisplayLockContext::MarkAncestorsForPrePaintIfNeeded() {
if (needs_effective_allowed_touch_action_update_ ||
layout_object->EffectiveAllowedTouchActionChanged() ||
layout_object->DescendantEffectiveAllowedTouchActionChanged()) {
+ // Note that although the object itself should have up to date value, in
+ // order to force recalc of the whole subtree, we mark it as needing an
+ // update.
layout_object->MarkEffectiveAllowedTouchActionChanged();
}
return true;
@@ -630,8 +723,13 @@ bool DisplayLockContext::MarkAncestorsForPrePaintIfNeeded() {
}
bool DisplayLockContext::MarkPaintLayerNeedsRepaint() {
+ DCHECK(ConnectedToView());
if (auto* layout_object = element_->GetLayoutObject()) {
layout_object->PaintingLayer()->SetNeedsRepaint();
+ if (needs_graphics_layer_collection_) {
+ document_->View()->GraphicsLayersDidChange();
+ needs_graphics_layer_collection_ = false;
+ }
return true;
}
return false;
@@ -646,12 +744,13 @@ bool DisplayLockContext::IsElementDirtyForStyleRecalc() const {
// blocked, meaning we never blocked style during a walk. Instead we might
// have not propagated the dirty bits up the tree.
return element_->NeedsStyleRecalc() || element_->ChildNeedsStyleRecalc() ||
+ element_->ChildNeedsReattachLayoutTree() ||
blocked_style_traversal_type_ > kStyleUpdateNotRequired;
}
bool DisplayLockContext::IsElementDirtyForLayout() const {
if (auto* layout_object = element_->GetLayoutObject())
- return layout_object->NeedsLayout();
+ return layout_object->NeedsLayout() || child_layout_was_blocked_;
return false;
}
@@ -671,10 +770,12 @@ void DisplayLockContext::DidMoveToNewDocument(Document& old_document) {
// Since we're observing the lifecycle updates, ensure that we listen to the
// right document's view.
- if (old_document.View())
- old_document.View()->UnregisterFromLifecycleNotifications(this);
- if (document_->View())
- document_->View()->RegisterForLifecycleNotifications(this);
+ if (HasResolver()) {
+ if (old_document.View())
+ old_document.View()->UnregisterFromLifecycleNotifications(this);
+ if (document_->View())
+ document_->View()->RegisterForLifecycleNotifications(this);
+ }
if (!IsActivatable()) {
old_document.RemoveActivationBlockingDisplayLock();
@@ -687,20 +788,15 @@ void DisplayLockContext::DidMoveToNewDocument(Document& old_document) {
}
void DisplayLockContext::WillStartLifecycleUpdate(const LocalFrameView& view) {
- in_lifecycle_update_ = true;
- if (state_ == kUpdating)
- update_budget_->WillStartLifecycleUpdate();
+ if (update_budget_)
+ update_budget_->OnLifecycleChange(view.CurrentLifecycleData());
}
void DisplayLockContext::DidFinishLifecycleUpdate(const LocalFrameView& view) {
- in_lifecycle_update_ = false;
if (acquire_resolver_) {
- if (ForceUnlockIfNeeded())
- return;
FinishAcquireResolver(kResolve);
// TODO(vmpstr): When size: auto is supported, we need to get the size from
// the layout object here.
- DCHECK(locked_content_logical_size_);
// Fallthrough here in case we're already updating.
}
@@ -717,7 +813,7 @@ void DisplayLockContext::DidFinishLifecycleUpdate(const LocalFrameView& view) {
// If we became disconnected for any reason, then we should reject the
// update promise and go back to the locked state.
- if (!element_ || !ConnectedToView()) {
+ if (!ConnectedToView()) {
FinishUpdateResolver(kReject, rejection_names::kElementIsDisconnected);
update_budget_.reset();
@@ -772,7 +868,16 @@ void DisplayLockContext::NotifyWillDisconnect() {
void DisplayLockContext::ScheduleAnimation() {
DCHECK(element_);
- DCHECK(ConnectedToView());
+ // We could have posted a task to run ScheduleAnimation if we're updating.
+ // However, before that task runs, we could have disconnected the element
+ // already. If that's the case and we don't need to finalize update, then we
+ // can skip scheduling animation. If we do need to finalize update (ie reset
+ // update_budget_), then we should still schedule an animation just in case
+ // one was not scheduled.
+ if ((!ConnectedToView() && !update_budget_) || !document_ ||
+ !document_->GetPage()) {
+ return;
+ }
// Schedule an animation to perform the lifecycle phases.
document_->GetPage()->Animator().ScheduleVisualUpdate(document_->GetFrame());
@@ -790,7 +895,7 @@ void DisplayLockContext::RescheduleTimeoutTask(double delay) {
*GetExecutionContext()->GetTaskRunner(TaskType::kMiscPlatformAPI),
FROM_HERE,
WTF::Bind(&DisplayLockContext::TriggerTimeout, WrapWeakPersistent(this)),
- TimeDelta::FromMillisecondsD(delay));
+ base::TimeDelta::FromMillisecondsD(delay));
}
void DisplayLockContext::CancelTimeoutTask() {
@@ -800,43 +905,62 @@ void DisplayLockContext::CancelTimeoutTask() {
void DisplayLockContext::TriggerTimeout() {
// We might have started destroyed the element or started to shut down while
// we're triggering a timeout. In that case, do nothing.
- if (!element_ || !document_->Lifecycle().IsActive())
+ if (!element_ || !document_ || !document_->Lifecycle().IsActive())
return;
StartCommit();
}
const char* DisplayLockContext::ShouldForceUnlock() const {
DCHECK(element_);
- // The style can be dirty if we're in a nested lock.
+ // This function is only called after style, layout tree, or lifecycle
+ // updates, so the style should be up-to-date, except in the case of nested
+ // locks, where the style recalc will never actually get to |element_|.
// TODO(vmpstr): We need to figure out what to do here, since we don't know
// what the style is and whether this element has proper containment. However,
// forcing an update from the ancestor locks seems inefficient. For now, we
// just optimistically assume that we have all of the right containment in
// place. See crbug.com/926276 for more information.
- if (element_->NeedsStyleRecalc())
+ if (element_->NeedsStyleRecalc()) {
+ DCHECK(DisplayLockUtilities::NearestLockedExclusiveAncestor(*element_));
return nullptr;
+ }
if (element_->HasDisplayContentsStyle())
return rejection_names::kUnsupportedDisplay;
- // If we have a layout object, check that since it's a more authoritative
- // source of containment information.
- if (auto* layout_object = element_->GetLayoutObject()) {
- if (layout_object->ShouldApplyStyleContainment() &&
- layout_object->ShouldApplyLayoutContainment())
- return nullptr;
- return rejection_names::kContainmentNotSatisfied;
- }
-
- // Otherwise, fallback on just checking style.
auto* style = element_->GetComputedStyle();
// Note that if for whatever reason we don't have computed style, then
// optimistically assume that we have containment.
- // TODO(vmpstr): Perhaps we need to add render=lockable which will ensure
- // containment.
- if (!style || (style->ContainsStyle() && style->ContainsLayout()))
+ if (!style)
return nullptr;
- return rejection_names::kContainmentNotSatisfied;
+ if (!style->ContainsStyle() || !style->ContainsLayout())
+ return rejection_names::kContainmentNotSatisfied;
+
+ // We allow replaced elements to be locked. This check is similar to the check
+ // in DefinitelyNewFormattingContext() in element.cc, but in this case we
+ // allow object element to get locked.
+ if (IsHTMLObjectElement(element_) || IsHTMLImageElement(element_) ||
+ element_->IsFormControlElement() || element_->IsMediaElement() ||
+ element_->IsFrameOwnerElement() || element_->IsSVGElement()) {
+ return nullptr;
+ }
+
+ // From https://www.w3.org/TR/css-contain-1/#containment-layout
+ // If the element does not generate a principal box (as is the case with
+ // display: contents or display: none), or if the element is an internal
+ // table element other than display: table-cell, if the element is an
+ // internal ruby element, or if the element’s principal box is a
+ // non-atomic inline-level box, layout containment has no effect.
+ // (Note we're allowing display:none for display locked elements, and a bit
+ // more restrictive on ruby - banning <ruby> elements entirely).
+ auto* html_element = DynamicTo<HTMLElement>(element_.Get());
+ if ((style->IsDisplayTableType() &&
+ style->Display() != EDisplay::kTableCell) ||
+ (!html_element || IsHTMLRubyElement(html_element)) ||
+ (style->IsDisplayInlineType() && !style->IsDisplayReplacedType())) {
+ return rejection_names::kContainmentNotSatisfied;
+ }
+ return nullptr;
}
bool DisplayLockContext::ForceUnlockIfNeeded() {
@@ -860,8 +984,7 @@ bool DisplayLockContext::ForceUnlockIfNeeded() {
}
bool DisplayLockContext::ConnectedToView() const {
- DCHECK(element_);
- return element_->isConnected() && document_->View();
+ return element_ && document_ && element_->isConnected() && document_->View();
}
// Scoped objects implementation
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 feaab81f46e..2617a0743d7 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
@@ -12,7 +12,7 @@
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -110,10 +110,10 @@ class CORE_EXPORT DisplayLockContext final
void DidStyle(LifecycleTarget);
bool ShouldLayout(LifecycleTarget) const;
void DidLayout(LifecycleTarget);
- bool ShouldPrePaint() const;
- void DidPrePaint();
- bool ShouldPaint() const;
- void DidPaint();
+ bool ShouldPrePaint(LifecycleTarget) const;
+ void DidPrePaint(LifecycleTarget);
+ bool ShouldPaint(LifecycleTarget) const;
+ void DidPaint(LifecycleTarget);
// Returns true if the last style recalc traversal was blocked at this
// element, either for itself, its children or its descendants.
@@ -164,6 +164,18 @@ class CORE_EXPORT DisplayLockContext final
std::max(blocked_style_traversal_type_, type);
}
+ void NotifyReattachLayoutTreeWasBlocked() {
+ reattach_layout_tree_was_blocked_ = true;
+ }
+
+ void NotifyChildLayoutWasBlocked() { child_layout_was_blocked_ = true; }
+
+ // Inform the display lock that it needs a graphics layer collection when it
+ // needs to paint.
+ void NotifyNeedsGraphicsLayerCollection() {
+ needs_graphics_layer_collection_ = true;
+ }
+
// Notify this element will be disconnected.
void NotifyWillDisconnect();
@@ -175,12 +187,12 @@ class CORE_EXPORT DisplayLockContext final
}
LayoutUnit GetLockedContentLogicalWidth() const {
- return is_horizontal_writing_mode_ ? locked_content_logical_size_->Width()
- : locked_content_logical_size_->Height();
+ return is_horizontal_writing_mode_ ? locked_content_logical_size_.Width()
+ : locked_content_logical_size_.Height();
}
LayoutUnit GetLockedContentLogicalHeight() const {
- return is_horizontal_writing_mode_ ? locked_content_logical_size_->Height()
- : locked_content_logical_size_->Width();
+ return is_horizontal_writing_mode_ ? locked_content_logical_size_.Height()
+ : locked_content_logical_size_.Width();
}
private:
@@ -219,7 +231,7 @@ class CORE_EXPORT DisplayLockContext final
// as well if needed. They return true if the element or its subtree were
// dirty, and false otherwise.
bool MarkForStyleRecalcIfNeeded();
- bool MarkAncestorsForLayoutIfNeeded();
+ bool MarkForLayoutIfNeeded();
bool MarkAncestorsForPrePaintIfNeeded();
bool MarkPaintLayerNeedsRepaint();
@@ -252,6 +264,8 @@ class CORE_EXPORT DisplayLockContext final
// Helper functions to resolve the update/commit promises.
enum ResolverState { kResolve, kReject, kDetach };
+ void MakeResolver(ScriptState*, Member<ScriptPromiseResolver>*);
+ bool HasResolver();
void FinishUpdateResolver(ResolverState, const char* reject_reason = nullptr);
void FinishCommitResolver(ResolverState, const char* reject_reason = nullptr);
void FinishAcquireResolver(ResolverState,
@@ -277,6 +291,12 @@ class CORE_EXPORT DisplayLockContext final
// when acquiring this lock should immediately resolve the acquire promise.
bool ConnectedToView() const;
+ bool ShouldPerformUpdatePhase(DisplayLockBudget::Phase phase) const;
+
+ // During an attempt to commit, clean up state and reject pending resolver
+ // promises if the lock is not connected to the tree.
+ bool CleanupAndRejectCommitIfNotConnected();
+
std::unique_ptr<DisplayLockBudget> update_budget_;
Member<ScriptPromiseResolver> commit_resolver_;
@@ -295,18 +315,27 @@ class CORE_EXPORT DisplayLockContext final
HeapHashSet<Member<Element>> whitespace_reattach_set_;
StateChangeHelper state_;
- base::Optional<LayoutSize> locked_content_logical_size_;
+ LayoutSize locked_content_logical_size_;
bool update_forced_ = false;
- bool in_lifecycle_update_ = false;
bool activatable_ = false;
bool is_locked_after_connect_ = false;
StyleType blocked_style_traversal_type_ = kStyleUpdateNotRequired;
+ // Signifies whether we've blocked a layout tree reattachment on |element_|'s
+ // descendants or not, so that we can mark |element_| for reattachment when
+ // needed.
+ bool reattach_layout_tree_was_blocked_ = false;
bool needs_effective_allowed_touch_action_update_ = false;
bool needs_prepaint_subtree_walk_ = false;
bool is_horizontal_writing_mode_ = true;
+ bool needs_graphics_layer_collection_ = false;
+ // Will be true if child traversal was blocked on a previous layout run on the
+ // locked element. We need to keep track of this to ensure that on the next
+ // layout run where the descendants of the locked element are allowed to be
+ // traversed into, we will traverse to the children of the locked element.
+ bool child_layout_was_blocked_ = false;
TaskHandle timeout_task_handle_;
};
diff --git a/chromium/third_party/blink/renderer/core/display_lock/display_lock_context_test.cc b/chromium/third_party/blink/renderer/core/display_lock/display_lock_context_test.cc
index 373a8b746ba..7c054b1026c 100644
--- a/chromium/third_party/blink/renderer/core/display_lock/display_lock_context_test.cc
+++ b/chromium/third_party/blink/renderer/core/display_lock/display_lock_context_test.cc
@@ -3,9 +3,16 @@
// found in the LICENSE file.
#include "third_party/blink/renderer/core/display_lock/display_lock_context.h"
+
+#include <memory>
+#include <utility>
+
+#include "mojo/public/cpp/bindings/pending_remote.h"
+#include "mojo/public/cpp/bindings/receiver.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
#include "third_party/blink/renderer/core/css/style_change_reason.h"
#include "third_party/blink/renderer/core/display_lock/display_lock_options.h"
+#include "third_party/blink/renderer/core/display_lock/strict_yielding_display_lock_budget.h"
#include "third_party/blink/renderer/core/dom/events/native_event_listener.h"
#include "third_party/blink/renderer/core/dom/node_computed_style.h"
#include "third_party/blink/renderer/core/editing/ephemeral_range.h"
@@ -17,7 +24,7 @@
#include "third_party/blink/renderer/core/html/html_template_element.h"
#include "third_party/blink/renderer/core/style/computed_style.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"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
namespace blink {
@@ -25,17 +32,12 @@ namespace {
class DisplayLockTestFindInPageClient : public mojom::blink::FindInPageClient {
public:
DisplayLockTestFindInPageClient()
- : find_results_are_ready_(false),
- active_index_(-1),
- count_(-1),
- binding_(this) {}
+ : find_results_are_ready_(false), active_index_(-1), count_(-1) {}
~DisplayLockTestFindInPageClient() override = default;
void SetFrame(WebLocalFrameImpl* frame) {
- mojom::blink::FindInPageClientPtr client;
- binding_.Bind(MakeRequest(&client));
- frame->GetFindInPage()->SetClient(std::move(client));
+ frame->GetFindInPage()->SetClient(receiver_.BindNewPipeAndPassRemote());
}
void SetNumberOfMatches(
@@ -75,7 +77,7 @@ class DisplayLockTestFindInPageClient : public mojom::blink::FindInPageClient {
int active_index_;
int count_;
- mojo::Binding<mojom::blink::FindInPageClient> binding_;
+ mojo::Receiver<mojom::blink::FindInPageClient> receiver_{this};
};
class DisplayLockEmptyEventListener final : public NativeEventListener {
@@ -84,19 +86,16 @@ class DisplayLockEmptyEventListener final : public NativeEventListener {
};
} // namespace
-class DisplayLockContextTest : public testing::Test {
+class DisplayLockContextTest : public testing::Test,
+ private ScopedDisplayLockingForTest {
public:
+ DisplayLockContextTest() : ScopedDisplayLockingForTest(true) {}
+
void SetUp() override {
- features_backup_.emplace();
- RuntimeEnabledFeatures::SetDisplayLockingEnabled(true);
web_view_helper_.Initialize();
}
void TearDown() override {
- if (features_backup_) {
- features_backup_->Restore();
- features_backup_.reset();
- }
web_view_helper_.Reset();
}
@@ -144,6 +143,10 @@ class DisplayLockContextTest : public testing::Test {
UpdateAllLifecyclePhasesForTest();
}
+ bool GraphicsLayerNeedsCollection(DisplayLockContext* context) const {
+ return context->needs_graphics_layer_collection_;
+ }
+
mojom::blink::FindOptionsPtr FindOptions(bool find_next = false) {
auto find_options = mojom::blink::FindOptions::New();
find_options->run_synchronously_for_testing = true;
@@ -160,10 +163,15 @@ class DisplayLockContextTest : public testing::Test {
test::RunPendingTasks();
}
+ void ResetBudget(std::unique_ptr<DisplayLockBudget> budget,
+ DisplayLockContext* context) {
+ ASSERT_TRUE(context->update_budget_);
+ context->update_budget_ = std::move(budget);
+ }
+
const int FAKE_FIND_ID = 1;
private:
- base::Optional<RuntimeEnabledFeatures::Backup> features_backup_;
frame_test_helpers::WebViewHelper web_view_helper_;
};
@@ -195,7 +203,8 @@ TEST_F(DisplayLockContextTest, LockAfterAppendStyleDirtyBits) {
DisplayLockContext::kChildren));
EXPECT_FALSE(element->GetDisplayLockContext()->ShouldLayout(
DisplayLockContext::kChildren));
- EXPECT_FALSE(element->GetDisplayLockContext()->ShouldPaint());
+ EXPECT_FALSE(element->GetDisplayLockContext()->ShouldPaint(
+ DisplayLockContext::kChildren));
EXPECT_EQ(GetDocument().LockedDisplayLockCount(), 1);
// If the element is dirty, style recalc would handle it in the next recalc.
@@ -336,6 +345,8 @@ TEST_F(DisplayLockContextTest,
}
TEST_F(DisplayLockContextTest, FindInPageWithChangedContent) {
+ if (!RuntimeEnabledFeatures::LayoutNGEnabled())
+ return;
ResizeAndFocus();
SetHtmlInnerHTML(R"HTML(
<style>
@@ -564,7 +575,8 @@ TEST_F(DisplayLockContextTest, CallUpdateStyleAndLayoutAfterChange) {
DisplayLockContext::kChildren));
EXPECT_FALSE(element->GetDisplayLockContext()->ShouldLayout(
DisplayLockContext::kChildren));
- EXPECT_FALSE(element->GetDisplayLockContext()->ShouldPaint());
+ EXPECT_FALSE(element->GetDisplayLockContext()->ShouldPaint(
+ DisplayLockContext::kChildren));
EXPECT_EQ(GetDocument().LockedDisplayLockCount(), 1);
EXPECT_EQ(GetDocument().ActivationBlockingDisplayLockCount(), 1);
@@ -662,7 +674,8 @@ TEST_F(DisplayLockContextTest, LockedElementAndDescendantsAreNotFocusable) {
DisplayLockContext::kChildren));
EXPECT_FALSE(element->GetDisplayLockContext()->ShouldLayout(
DisplayLockContext::kChildren));
- EXPECT_FALSE(element->GetDisplayLockContext()->ShouldPaint());
+ EXPECT_FALSE(element->GetDisplayLockContext()->ShouldPaint(
+ DisplayLockContext::kChildren));
EXPECT_EQ(GetDocument().LockedDisplayLockCount(), 1);
EXPECT_EQ(GetDocument().ActivationBlockingDisplayLockCount(), 1);
@@ -687,7 +700,8 @@ TEST_F(DisplayLockContextTest, LockedElementAndDescendantsAreNotFocusable) {
DisplayLockContext::kChildren));
EXPECT_TRUE(element->GetDisplayLockContext()->ShouldLayout(
DisplayLockContext::kChildren));
- EXPECT_TRUE(element->GetDisplayLockContext()->ShouldPaint());
+ EXPECT_TRUE(element->GetDisplayLockContext()->ShouldPaint(
+ DisplayLockContext::kChildren));
UpdateAllLifecyclePhasesForTest();
@@ -805,7 +819,8 @@ TEST_F(DisplayLockContextTest,
DisplayLockContext::kChildren));
EXPECT_FALSE(element->GetDisplayLockContext()->ShouldLayout(
DisplayLockContext::kChildren));
- EXPECT_FALSE(element->GetDisplayLockContext()->ShouldPaint());
+ EXPECT_FALSE(element->GetDisplayLockContext()->ShouldPaint(
+ DisplayLockContext::kChildren));
EXPECT_EQ(GetDocument().LockedDisplayLockCount(), 1);
EXPECT_EQ(GetDocument().ActivationBlockingDisplayLockCount(), 1);
@@ -1201,7 +1216,7 @@ TEST_F(DisplayLockContextTest, AncestorAllowedTouchAction) {
EXPECT_FALSE(ancestor_object->InsideBlockingTouchEventHandler());
EXPECT_TRUE(handler_object->InsideBlockingTouchEventHandler());
EXPECT_TRUE(descendant_object->InsideBlockingTouchEventHandler());
- EXPECT_FALSE(locked_object->InsideBlockingTouchEventHandler());
+ EXPECT_TRUE(locked_object->InsideBlockingTouchEventHandler());
EXPECT_FALSE(lockedchild_object->InsideBlockingTouchEventHandler());
{
@@ -1226,7 +1241,7 @@ TEST_F(DisplayLockContextTest, AncestorAllowedTouchAction) {
EXPECT_FALSE(ancestor_object->InsideBlockingTouchEventHandler());
EXPECT_TRUE(handler_object->InsideBlockingTouchEventHandler());
EXPECT_TRUE(descendant_object->InsideBlockingTouchEventHandler());
- EXPECT_FALSE(locked_object->InsideBlockingTouchEventHandler());
+ EXPECT_TRUE(locked_object->InsideBlockingTouchEventHandler());
EXPECT_FALSE(lockedchild_object->InsideBlockingTouchEventHandler());
UpdateAllLifecyclePhasesForTest();
@@ -1393,4 +1408,244 @@ TEST_F(DisplayLockContextTest, DescendantAllowedTouchAction) {
EXPECT_TRUE(handler_object->InsideBlockingTouchEventHandler());
}
+TEST_F(DisplayLockContextTest,
+ CompositedLayerLockCausesGraphicsLayersCollection) {
+ // This test only tests the BGPT path.
+ if (!RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled() ||
+ RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) {
+ return;
+ }
+
+ ResizeAndFocus();
+ GetDocument().GetSettings()->SetPreferCompositingToLCDTextEnabled(true);
+
+ SetHtmlInnerHTML(R"HTML(
+ <style>
+ #container {
+ width: 100px;
+ height: 100px;
+ contain: style layout;
+ }
+ #composited {
+ will-change: transform;
+ }
+ </style>
+ <body>
+ <div id="container"><div id="composited">testing</div></div></body>
+ </body>
+ )HTML");
+
+ // Check if the result is correct if we update the contents.
+ auto* container = GetDocument().getElementById("container");
+
+ // Ensure that we will gather graphics layer on the next update (after lock).
+ GetDocument().View()->GraphicsLayersDidChange();
+
+ LockElement(*container, false /* activatable */);
+ EXPECT_TRUE(container->GetDisplayLockContext()->IsLocked());
+ EXPECT_TRUE(GraphicsLayerNeedsCollection(container->GetDisplayLockContext()));
+
+ CommitElement(*container);
+ EXPECT_FALSE(
+ GraphicsLayerNeedsCollection(container->GetDisplayLockContext()));
+}
+
+TEST_F(DisplayLockContextTest, DescendantNeedsPaintPropertyUpdateBlocked) {
+ SetHtmlInnerHTML(R"HTML(
+ <style>
+ #locked {
+ width: 100px;
+ height: 100px;
+ contain: style layout paint;
+ }
+ </style>
+ <div id="ancestor">
+ <div id="descendant">
+ <div id="locked">
+ <div id="handler"></div>
+ </div>
+ </div>
+ </div>
+ )HTML");
+
+ auto* ancestor_element = GetDocument().getElementById("ancestor");
+ auto* descendant_element = GetDocument().getElementById("descendant");
+ auto* locked_element = GetDocument().getElementById("locked");
+ auto* handler_element = GetDocument().getElementById("handler");
+
+ auto* script_state = ToScriptStateForMainWorld(GetDocument().GetFrame());
+ {
+ ScriptState::Scope scope(script_state);
+ locked_element->getDisplayLockForBindings()->acquire(script_state, nullptr);
+ }
+
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_TRUE(locked_element->GetDisplayLockContext()->IsLocked());
+
+ auto* ancestor_object = ancestor_element->GetLayoutObject();
+ auto* descendant_object = descendant_element->GetLayoutObject();
+ auto* locked_object = locked_element->GetLayoutObject();
+ auto* handler_object = handler_element->GetLayoutObject();
+
+ EXPECT_FALSE(ancestor_object->NeedsPaintPropertyUpdate());
+ EXPECT_FALSE(descendant_object->NeedsPaintPropertyUpdate());
+ EXPECT_FALSE(locked_object->NeedsPaintPropertyUpdate());
+ EXPECT_FALSE(handler_object->NeedsPaintPropertyUpdate());
+
+ EXPECT_FALSE(ancestor_object->DescendantNeedsPaintPropertyUpdate());
+ EXPECT_FALSE(descendant_object->DescendantNeedsPaintPropertyUpdate());
+ EXPECT_FALSE(locked_object->DescendantNeedsPaintPropertyUpdate());
+ EXPECT_FALSE(handler_object->DescendantNeedsPaintPropertyUpdate());
+
+ handler_object->SetNeedsPaintPropertyUpdate();
+
+ EXPECT_FALSE(ancestor_object->NeedsPaintPropertyUpdate());
+ EXPECT_FALSE(descendant_object->NeedsPaintPropertyUpdate());
+ EXPECT_FALSE(locked_object->NeedsPaintPropertyUpdate());
+ EXPECT_TRUE(handler_object->NeedsPaintPropertyUpdate());
+
+ EXPECT_TRUE(ancestor_object->DescendantNeedsPaintPropertyUpdate());
+ EXPECT_TRUE(descendant_object->DescendantNeedsPaintPropertyUpdate());
+ EXPECT_TRUE(locked_object->DescendantNeedsPaintPropertyUpdate());
+ EXPECT_FALSE(handler_object->DescendantNeedsPaintPropertyUpdate());
+
+ UpdateAllLifecyclePhasesForTest();
+
+ EXPECT_FALSE(ancestor_object->NeedsPaintPropertyUpdate());
+ EXPECT_FALSE(descendant_object->NeedsPaintPropertyUpdate());
+ EXPECT_FALSE(locked_object->NeedsPaintPropertyUpdate());
+ EXPECT_TRUE(handler_object->NeedsPaintPropertyUpdate());
+
+ EXPECT_FALSE(ancestor_object->DescendantNeedsPaintPropertyUpdate());
+ EXPECT_FALSE(descendant_object->DescendantNeedsPaintPropertyUpdate());
+ EXPECT_TRUE(locked_object->DescendantNeedsPaintPropertyUpdate());
+ EXPECT_FALSE(handler_object->DescendantNeedsPaintPropertyUpdate());
+
+ locked_object->SetShouldCheckForPaintInvalidationWithoutGeometryChange();
+ UpdateAllLifecyclePhasesForTest();
+
+ EXPECT_FALSE(ancestor_object->NeedsPaintPropertyUpdate());
+ EXPECT_FALSE(descendant_object->NeedsPaintPropertyUpdate());
+ EXPECT_FALSE(locked_object->NeedsPaintPropertyUpdate());
+ EXPECT_TRUE(handler_object->NeedsPaintPropertyUpdate());
+
+ EXPECT_FALSE(ancestor_object->DescendantNeedsPaintPropertyUpdate());
+ EXPECT_FALSE(descendant_object->DescendantNeedsPaintPropertyUpdate());
+ EXPECT_TRUE(locked_object->DescendantNeedsPaintPropertyUpdate());
+ EXPECT_FALSE(handler_object->DescendantNeedsPaintPropertyUpdate());
+
+ {
+ ScriptState::Scope scope(script_state);
+ locked_element->GetDisplayLockContext()->commit(script_state);
+ }
+
+ EXPECT_FALSE(ancestor_object->NeedsPaintPropertyUpdate());
+ EXPECT_FALSE(descendant_object->NeedsPaintPropertyUpdate());
+ EXPECT_TRUE(locked_object->NeedsPaintPropertyUpdate());
+ EXPECT_TRUE(handler_object->NeedsPaintPropertyUpdate());
+
+ EXPECT_TRUE(ancestor_object->DescendantNeedsPaintPropertyUpdate());
+ EXPECT_TRUE(descendant_object->DescendantNeedsPaintPropertyUpdate());
+ EXPECT_TRUE(locked_object->DescendantNeedsPaintPropertyUpdate());
+ EXPECT_FALSE(handler_object->DescendantNeedsPaintPropertyUpdate());
+
+ UpdateAllLifecyclePhasesForTest();
+
+ EXPECT_FALSE(ancestor_object->NeedsPaintPropertyUpdate());
+ EXPECT_FALSE(descendant_object->NeedsPaintPropertyUpdate());
+ EXPECT_FALSE(locked_object->NeedsPaintPropertyUpdate());
+ EXPECT_FALSE(handler_object->NeedsPaintPropertyUpdate());
+
+ EXPECT_FALSE(ancestor_object->DescendantNeedsPaintPropertyUpdate());
+ EXPECT_FALSE(descendant_object->DescendantNeedsPaintPropertyUpdate());
+ EXPECT_FALSE(locked_object->DescendantNeedsPaintPropertyUpdate());
+ EXPECT_FALSE(handler_object->DescendantNeedsPaintPropertyUpdate());
+}
+
+TEST_F(DisplayLockContextTest, DisconnectedWhileUpdating) {
+ SetHtmlInnerHTML(R"HTML(
+ <style>
+ #container {
+ contain: style layout;
+ }
+ </style>
+ <div id="container"></div>
+ )HTML");
+
+ auto* container = GetDocument().getElementById("container");
+ LockElement(*container, false);
+
+ EXPECT_TRUE(container->GetDisplayLockContext()->IsLocked());
+ EXPECT_FALSE(container->GetDisplayLockContext()->ShouldStyle(
+ DisplayLockContext::kChildren));
+ EXPECT_FALSE(container->GetDisplayLockContext()->ShouldLayout(
+ DisplayLockContext::kChildren));
+ EXPECT_FALSE(container->GetDisplayLockContext()->ShouldPrePaint(
+ DisplayLockContext::kChildren));
+
+ auto* script_state = ToScriptStateForMainWorld(GetDocument().GetFrame());
+ {
+ ScriptState::Scope scope(script_state);
+ container->GetDisplayLockContext()->update(script_state);
+ }
+ auto budget = base::WrapUnique(
+ new StrictYieldingDisplayLockBudget(container->GetDisplayLockContext()));
+ ResetBudget(std::move(budget), container->GetDisplayLockContext());
+
+ // This should style and allow layout, but not actually do layout (thus
+ // pre-paint would be blocked). Furthermore, this should schedule a task to
+ // run DisplayLockContext::ScheduleAnimation (since we can't directly schedule
+ // it from within a lifecycle).
+ UpdateAllLifecyclePhasesForTest();
+
+ ASSERT_FALSE(GetDocument().View()->InLifecycleUpdate());
+ GetDocument().View()->SetInLifecycleUpdateForTest(true);
+ EXPECT_TRUE(container->GetDisplayLockContext()->IsLocked());
+ EXPECT_TRUE(container->GetDisplayLockContext()->ShouldStyle(
+ DisplayLockContext::kChildren));
+ EXPECT_TRUE(container->GetDisplayLockContext()->ShouldLayout(
+ DisplayLockContext::kChildren));
+ EXPECT_FALSE(container->GetDisplayLockContext()->ShouldPrePaint(
+ DisplayLockContext::kChildren));
+ GetDocument().View()->SetInLifecycleUpdateForTest(false);
+
+ // Now disconnect the element.
+ container->remove();
+
+ // Flushing the pending tasks would call ScheduleAnimation, but since we're no
+ // longer connected and can't schedule from within the element, we should
+ // gracefully exit (and not crash).
+ test::RunPendingTasks();
+}
+
+class DisplayLockContextRenderingTest : public RenderingTest,
+ private ScopedDisplayLockingForTest {
+ public:
+ DisplayLockContextRenderingTest()
+ : RenderingTest(MakeGarbageCollected<SingleChildLocalFrameClient>()),
+ ScopedDisplayLockingForTest(true) {}
+};
+
+TEST_F(DisplayLockContextRenderingTest, FrameDocumentRemovedWhileAcquire) {
+ SetHtmlInnerHTML(R"HTML(
+ <iframe id="frame"></iframe>
+ )HTML");
+ SetChildFrameHTML(R"HTML(
+ <style>
+ div {
+ contain: style layout;
+ }
+ </style>
+ <div id="target"></target>
+ )HTML");
+
+ auto* target = ChildDocument().getElementById("target");
+ GetDocument().getElementById("frame")->remove();
+
+ auto* script_state = ToScriptStateForMainWorld(GetDocument().GetFrame());
+ ScriptState::Scope scope(script_state);
+ DisplayLockOptions options;
+ target->getDisplayLockForBindings()->acquire(script_state, &options);
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/display_lock/display_lock_fuzzer.cc b/chromium/third_party/blink/renderer/core/display_lock/display_lock_fuzzer.cc
new file mode 100644
index 00000000000..03ab9065171
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/display_lock/display_lock_fuzzer.cc
@@ -0,0 +1,50 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "content/test/fuzzer/fuzzer_support.h"
+#include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h"
+#include "third_party/blink/public/platform/web_runtime_features.h"
+#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_view.h"
+#include "third_party/blink/public/web/web_widget.h"
+
+static content::Env* env;
+
+bool Initialize() {
+ blink::WebRuntimeFeatures::EnableDisplayLocking(true);
+ env = new content::Env();
+ return true;
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+ static bool initialized = Initialize();
+ // Suppress unused variable warning.
+ (void)initialized;
+
+ // Only handle reasonable size inputs.
+ if (size < 1 || size > 10000)
+ return 0;
+
+ std::string data_as_string(reinterpret_cast<const char*>(data), size);
+ int num_rafs = std::hash<std::string>()(data_as_string) % 10;
+ env->adapter->LoadHTML(data_as_string, "");
+
+ // Delay each frame 17ms which is roughly the length of a frame when running
+ // at 60fps.
+ auto frame_delay = base::TimeDelta::FromMillisecondsD(17);
+
+ for (int i = 0; i < num_rafs; ++i) {
+ base::RunLoop run_loop;
+ blink::scheduler::GetSingleThreadTaskRunnerForTesting()->PostDelayedTask(
+ FROM_HERE, run_loop.QuitClosure(), frame_delay);
+ run_loop.Run();
+
+ env->adapter->GetMainFrame()
+ ->View()
+ ->MainFrameWidget()
+ ->UpdateAllLifecyclePhases(
+ blink::WebWidget::LifecycleUpdateReason::kTest);
+ }
+ return 0;
+}
diff --git a/chromium/third_party/blink/renderer/core/display_lock/display_lock_utilities.cc b/chromium/third_party/blink/renderer/core/display_lock/display_lock_utilities.cc
index ad63a673a46..310355953bf 100644
--- a/chromium/third_party/blink/renderer/core/display_lock/display_lock_utilities.cc
+++ b/chromium/third_party/blink/renderer/core/display_lock/display_lock_utilities.cc
@@ -15,6 +15,19 @@
#include "third_party/blink/renderer/core/layout/layout_view.h"
namespace blink {
+namespace {
+
+// Returns the frame owner node for the frame that contains the given child, if
+// one exists. Returns nullptr otherwise.
+const Node* GetFrameOwnerNode(const Node* child) {
+ if (!child || !child->GetDocument().GetFrame() ||
+ !child->GetDocument().GetFrame()->OwnerLayoutObject()) {
+ return nullptr;
+ }
+ return child->GetDocument().GetFrame()->OwnerLayoutObject()->GetNode();
+}
+
+} // namespace
bool DisplayLockUtilities::ActivateFindInPageMatchRangeIfNeeded(
const EphemeralRangeInFlatTree& range) {
@@ -64,22 +77,28 @@ DisplayLockUtilities::ActivatableLockedInclusiveAncestors(Element& element) {
}
DisplayLockUtilities::ScopedChainForcedUpdate::ScopedChainForcedUpdate(
- const Node* node) {
- if (!RuntimeEnabledFeatures::DisplayLockingEnabled() ||
- node->GetDocument().LockedDisplayLockCount() == 0) {
+ const Node* node,
+ bool include_self) {
+ if (!RuntimeEnabledFeatures::DisplayLockingEnabled())
+ return;
+
+ CreateParentFrameScopeIfNeeded(node);
+
+ if (node->GetDocument().LockedDisplayLockCount() == 0)
return;
- }
const_cast<Node*>(node)->UpdateDistributionForFlatTreeTraversal();
// Get the right ancestor view. Only use inclusive ancestors if the node
// itself is locked and it prevents self layout. If self layout is not
// prevented, we don't need to force the subtree layout, so use exclusive
// ancestors in that case.
- auto ancestor_view = [node] {
- if (node->IsElementNode()) {
- auto* context = ToElement(node)->GetDisplayLockContext();
- if (context && !context->ShouldLayout(DisplayLockContext::kSelf))
+ auto ancestor_view = [node, include_self] {
+ if (auto* element = DynamicTo<Element>(node)) {
+ auto* context = element->GetDisplayLockContext();
+ if (context &&
+ (include_self || !context->ShouldLayout(DisplayLockContext::kSelf))) {
return FlatTreeTraversal::InclusiveAncestorsOf(*node);
+ }
}
return FlatTreeTraversal::AncestorsOf(*node);
}();
@@ -98,18 +117,28 @@ DisplayLockUtilities::ScopedChainForcedUpdate::ScopedChainForcedUpdate(
}
}
+void DisplayLockUtilities::ScopedChainForcedUpdate::
+ CreateParentFrameScopeIfNeeded(const Node* node) {
+ auto* owner_node = GetFrameOwnerNode(node);
+ if (owner_node) {
+ parent_frame_scope_ =
+ std::make_unique<ScopedChainForcedUpdate>(owner_node, true);
+ }
+}
+
const Element* DisplayLockUtilities::NearestLockedInclusiveAncestor(
const Node& node) {
- if (!node.IsElementNode())
+ auto* element = DynamicTo<Element>(node);
+ if (!element)
return NearestLockedExclusiveAncestor(node);
if (!RuntimeEnabledFeatures::DisplayLockingEnabled() || !node.isConnected() ||
node.GetDocument().LockedDisplayLockCount() == 0 ||
!node.CanParticipateInFlatTree()) {
return nullptr;
}
- if (auto* context = ToElement(node).GetDisplayLockContext()) {
+ if (auto* context = element->GetDisplayLockContext()) {
if (context->IsLocked())
- return &ToElement(node);
+ return element;
}
return NearestLockedExclusiveAncestor(node);
}
@@ -179,32 +208,25 @@ bool DisplayLockUtilities::IsInLockedSubtreeCrossingFrames(
const Node* node = &source_node;
// Special case self-node checking.
- if (node->GetDocument().LockedDisplayLockCount() && node->IsElementNode()) {
- auto* context = ToElement(node)->GetDisplayLockContext();
+ auto* element = DynamicTo<Element>(node);
+ if (element && node->GetDocument().LockedDisplayLockCount()) {
+ auto* context = element->GetDisplayLockContext();
if (context && !context->ShouldLayout(DisplayLockContext::kSelf))
return true;
}
- auto get_frame_owner_node = [](const Node* child) -> const Node* {
- if (!child || !child->GetDocument().GetFrame() ||
- !child->GetDocument().GetFrame()->OwnerLayoutObject()) {
- return nullptr;
- }
- return child->GetDocument().GetFrame()->OwnerLayoutObject()->GetNode();
- };
-
// Since we handled the self-check above, we need to do inclusive checks
// starting from the parent.
node = FlatTreeTraversal::Parent(*node);
// If we don't have a flat-tree parent, get the |source_node|'s owner node
// instead.
if (!node)
- node = get_frame_owner_node(&source_node);
+ node = GetFrameOwnerNode(&source_node);
while (node) {
if (NearestLockedInclusiveAncestor(*node))
return true;
- node = get_frame_owner_node(node);
+ node = GetFrameOwnerNode(node);
}
return false;
}
diff --git a/chromium/third_party/blink/renderer/core/display_lock/display_lock_utilities.h b/chromium/third_party/blink/renderer/core/display_lock/display_lock_utilities.h
index 855309e5bf8..94474471d70 100644
--- a/chromium/third_party/blink/renderer/core/display_lock/display_lock_utilities.h
+++ b/chromium/third_party/blink/renderer/core/display_lock/display_lock_utilities.h
@@ -8,7 +8,7 @@
#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/editing/ephemeral_range.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -18,17 +18,20 @@ class CORE_EXPORT DisplayLockUtilities {
public:
// This class forces updates on display locks from the given node up the
- // ancestor chain until the root.
+ // ancestor chain until the local frame root.
class ScopedChainForcedUpdate {
- STACK_ALLOCATED();
DISALLOW_COPY_AND_ASSIGN(ScopedChainForcedUpdate);
public:
- explicit ScopedChainForcedUpdate(const Node* node);
+ explicit ScopedChainForcedUpdate(const Node* node,
+ bool include_self = false);
~ScopedChainForcedUpdate() = default;
+ void CreateParentFrameScopeIfNeeded(const Node* node);
+
private:
Vector<DisplayLockContext::ScopedForcedUpdate> scoped_update_forced_list_;
+ std::unique_ptr<ScopedChainForcedUpdate> parent_frame_scope_;
};
// Activates all the nodes within a find-in-page match |range|.
// Returns true if at least one node gets activated.
diff --git a/chromium/third_party/blink/renderer/core/display_lock/display_lock_utilities_test.cc b/chromium/third_party/blink/renderer/core/display_lock/display_lock_utilities_test.cc
index 69e1164abf8..e34792f2787 100644
--- a/chromium/third_party/blink/renderer/core/display_lock/display_lock_utilities_test.cc
+++ b/chromium/third_party/blink/renderer/core/display_lock/display_lock_utilities_test.cc
@@ -10,23 +10,16 @@
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/testing/core_unit_test_helper.h"
#include "third_party/blink/renderer/core/testing/page_test_base.h"
+#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
namespace blink {
-class DisplayLockUtilitiesTest : public RenderingTest {
+class DisplayLockUtilitiesTest : public RenderingTest,
+ private ScopedDisplayLockingForTest {
public:
DisplayLockUtilitiesTest()
- : RenderingTest(MakeGarbageCollected<SingleChildLocalFrameClient>()) {}
-
- void SetUp() override {
- RenderingTest::SetUp();
- RuntimeEnabledFeatures::SetDisplayLockingEnabled(true);
- }
-
- void TearDown() override {
- RenderingTest::TearDown();
- RuntimeEnabledFeatures::SetDisplayLockingEnabled(false);
- }
+ : RenderingTest(MakeGarbageCollected<SingleChildLocalFrameClient>()),
+ ScopedDisplayLockingForTest(true) {}
};
TEST_F(DisplayLockUtilitiesTest, ActivatableLockedInclusiveAncestors) {
diff --git a/chromium/third_party/blink/renderer/core/display_lock/strict_yielding_display_lock_budget.cc b/chromium/third_party/blink/renderer/core/display_lock/strict_yielding_display_lock_budget.cc
index aca76e246aa..3f319b97ae1 100644
--- a/chromium/third_party/blink/renderer/core/display_lock/strict_yielding_display_lock_budget.cc
+++ b/chromium/third_party/blink/renderer/core/display_lock/strict_yielding_display_lock_budget.cc
@@ -5,6 +5,7 @@
#include "third_party/blink/renderer/core/display_lock/strict_yielding_display_lock_budget.h"
#include <algorithm>
+#include "third_party/blink/renderer/core/frame/local_frame_view.h"
namespace blink {
@@ -12,7 +13,9 @@ StrictYieldingDisplayLockBudget::StrictYieldingDisplayLockBudget(
DisplayLockContext* context)
: DisplayLockBudget(context) {}
-bool StrictYieldingDisplayLockBudget::ShouldPerformPhase(Phase phase) const {
+bool StrictYieldingDisplayLockBudget::ShouldPerformPhase(
+ Phase phase,
+ const LifecycleData& lifecycle_data) {
// We should perform any phase earlier than the one we already completed.
// Also, we should complete a new phase once per cycle.
return (last_completed_phase_ && phase <= *last_completed_phase_) ||
@@ -36,7 +39,8 @@ void StrictYieldingDisplayLockBudget::DidPerformPhase(Phase phase) {
#endif
}
-void StrictYieldingDisplayLockBudget::WillStartLifecycleUpdate() {
+void StrictYieldingDisplayLockBudget::OnLifecycleChange(
+ const LifecycleData& lifecycle_data) {
// Figure out the next phase we would run. If we had completed a phase before,
// then we should try to complete the next one, otherwise we'll start with the
// first phase.
@@ -48,12 +52,7 @@ void StrictYieldingDisplayLockBudget::WillStartLifecycleUpdate() {
: Phase::kFirst;
// Mark the next phase we're scheduled to run.
- for (auto phase = static_cast<unsigned>(next_phase);
- phase <= static_cast<unsigned>(Phase::kLast); ++phase) {
- if (MarkAncestorsDirtyForPhaseIfNeeded(static_cast<Phase>(phase)))
- break;
- }
-
+ MarkPhaseAsDirty(next_phase);
completed_new_phase_this_cycle_ = false;
}
diff --git a/chromium/third_party/blink/renderer/core/display_lock/strict_yielding_display_lock_budget.h b/chromium/third_party/blink/renderer/core/display_lock/strict_yielding_display_lock_budget.h
index 77c6ca1fc3b..c0b9cbac611 100644
--- a/chromium/third_party/blink/renderer/core/display_lock/strict_yielding_display_lock_budget.h
+++ b/chromium/third_party/blink/renderer/core/display_lock/strict_yielding_display_lock_budget.h
@@ -21,9 +21,9 @@ class CORE_EXPORT StrictYieldingDisplayLockBudget final
StrictYieldingDisplayLockBudget(DisplayLockContext*);
~StrictYieldingDisplayLockBudget() override = default;
- bool ShouldPerformPhase(Phase) const override;
+ bool ShouldPerformPhase(Phase, const LifecycleData&) override;
void DidPerformPhase(Phase) override;
- void WillStartLifecycleUpdate() override;
+ void OnLifecycleChange(const LifecycleData&) override;
// Returns true if any of the lifecycles that have been previously blocked by
// this budget need updates. Note that this does not check lifecycle phases
// that have already completed by this budget even if they are now dirty
diff --git a/chromium/third_party/blink/renderer/core/display_lock/unyielding_display_lock_budget.cc b/chromium/third_party/blink/renderer/core/display_lock/unyielding_display_lock_budget.cc
index bf0d00f3a16..8ed458bdc75 100644
--- a/chromium/third_party/blink/renderer/core/display_lock/unyielding_display_lock_budget.cc
+++ b/chromium/third_party/blink/renderer/core/display_lock/unyielding_display_lock_budget.cc
@@ -4,23 +4,28 @@
#include "third_party/blink/renderer/core/display_lock/unyielding_display_lock_budget.h"
+#include "third_party/blink/renderer/core/frame/local_frame_view.h"
+
namespace blink {
UnyieldingDisplayLockBudget::UnyieldingDisplayLockBudget(
DisplayLockContext* context)
: DisplayLockBudget(context) {}
-bool UnyieldingDisplayLockBudget::ShouldPerformPhase(Phase) const {
+bool UnyieldingDisplayLockBudget::ShouldPerformPhase(
+ Phase,
+ const LifecycleData& lifecycle_data) {
return true;
}
void UnyieldingDisplayLockBudget::DidPerformPhase(Phase) {}
-void UnyieldingDisplayLockBudget::WillStartLifecycleUpdate() {
+void UnyieldingDisplayLockBudget::OnLifecycleChange(
+ const LifecycleData& lifecycle_data) {
// Mark all the phases dirty since we have no intention of yielding.
for (auto phase = static_cast<unsigned>(Phase::kFirst);
phase <= static_cast<unsigned>(Phase::kLast); ++phase) {
- MarkAncestorsDirtyForPhaseIfNeeded(static_cast<Phase>(phase));
+ MarkDirtyForPhaseIfNeeded(static_cast<Phase>(phase));
}
}
diff --git a/chromium/third_party/blink/renderer/core/display_lock/unyielding_display_lock_budget.h b/chromium/third_party/blink/renderer/core/display_lock/unyielding_display_lock_budget.h
index aed8c3a964b..7b3351aaae2 100644
--- a/chromium/third_party/blink/renderer/core/display_lock/unyielding_display_lock_budget.h
+++ b/chromium/third_party/blink/renderer/core/display_lock/unyielding_display_lock_budget.h
@@ -18,9 +18,9 @@ class CORE_EXPORT UnyieldingDisplayLockBudget final : public DisplayLockBudget {
UnyieldingDisplayLockBudget(DisplayLockContext*);
~UnyieldingDisplayLockBudget() override = default;
- bool ShouldPerformPhase(Phase) const override;
+ bool ShouldPerformPhase(Phase, const LifecycleData&) override;
void DidPerformPhase(Phase) override;
- void WillStartLifecycleUpdate() override;
+ void OnLifecycleChange(const LifecycleData&) override;
bool NeedsLifecycleUpdates() const override;
};
diff --git a/chromium/third_party/blink/renderer/core/display_lock/yielding_display_lock_budget.cc b/chromium/third_party/blink/renderer/core/display_lock/yielding_display_lock_budget.cc
index 7ffac6e6b97..ec51cdef647 100644
--- a/chromium/third_party/blink/renderer/core/display_lock/yielding_display_lock_budget.cc
+++ b/chromium/third_party/blink/renderer/core/display_lock/yielding_display_lock_budget.cc
@@ -5,6 +5,7 @@
#include "third_party/blink/renderer/core/display_lock/yielding_display_lock_budget.h"
#include "base/time/tick_clock.h"
+#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
#include <algorithm>
@@ -15,7 +16,9 @@ YieldingDisplayLockBudget::YieldingDisplayLockBudget(
DisplayLockContext* context)
: DisplayLockBudget(context) {}
-bool YieldingDisplayLockBudget::ShouldPerformPhase(Phase phase) const {
+bool YieldingDisplayLockBudget::ShouldPerformPhase(
+ Phase phase,
+ const LifecycleData& lifecycle_data) {
// Always perform at least one more phase.
if (phase <= next_phase_from_start_of_lifecycle_)
return true;
@@ -33,17 +36,15 @@ void YieldingDisplayLockBudget::DidPerformPhase(Phase phase) {
last_completed_phase_ = phase;
// Mark the next phase as dirty so that we can reach it if we need to.
- for (auto phase = static_cast<unsigned>(*last_completed_phase_) + 1;
- phase <= static_cast<unsigned>(Phase::kLast); ++phase) {
- if (MarkAncestorsDirtyForPhaseIfNeeded(static_cast<Phase>(phase)))
- break;
- }
+ MarkPhaseAsDirty(
+ static_cast<Phase>(static_cast<unsigned>(*last_completed_phase_) + 1));
}
-void YieldingDisplayLockBudget::WillStartLifecycleUpdate() {
- ++lifecycle_count_;
- deadline_ =
- clock_->NowTicks() + TimeDelta::FromMillisecondsD(GetCurrentBudgetMs());
+void YieldingDisplayLockBudget::OnLifecycleChange(
+ const LifecycleData& lifecycle_data) {
+ if (first_lifecycle_count_ == 0)
+ first_lifecycle_count_ = lifecycle_data.count;
+ deadline_ = lifecycle_data.start_time + GetCurrentBudget(lifecycle_data);
// Figure out the next phase we would run. If we had completed a phase before,
// then we should try to complete the next one, otherwise we'll start with the
@@ -54,13 +55,7 @@ void YieldingDisplayLockBudget::WillStartLifecycleUpdate() {
std::min(static_cast<unsigned>(*last_completed_phase_) + 1,
static_cast<unsigned>(Phase::kLast)))
: Phase::kFirst;
-
- // Mark the next phase we're scheduled to run.
- for (auto phase = static_cast<unsigned>(next_phase_from_start_of_lifecycle_);
- phase <= static_cast<unsigned>(Phase::kLast); ++phase) {
- if (MarkAncestorsDirtyForPhaseIfNeeded(static_cast<Phase>(phase)))
- break;
- }
+ MarkPhaseAsDirty(next_phase_from_start_of_lifecycle_);
}
bool YieldingDisplayLockBudget::NeedsLifecycleUpdates() const {
@@ -80,22 +75,24 @@ bool YieldingDisplayLockBudget::NeedsLifecycleUpdates() const {
return false;
}
-double YieldingDisplayLockBudget::GetCurrentBudgetMs() const {
- if (TimeTicks::IsHighResolution()) {
- if (lifecycle_count_ < 3)
- return 4.;
- if (lifecycle_count_ < 10)
- return 8.;
- if (lifecycle_count_ < 60)
- return 16.;
+base::TimeDelta YieldingDisplayLockBudget::GetCurrentBudget(
+ const LifecycleData& lifecycle_data) const {
+ int lifecycle_count = lifecycle_data.count - first_lifecycle_count_ + 1;
+ if (base::TimeTicks::IsHighResolution()) {
+ if (lifecycle_count < 3)
+ return base::TimeDelta::FromMilliseconds(4);
+ if (lifecycle_count < 10)
+ return base::TimeDelta::FromMilliseconds(8);
+ if (lifecycle_count < 60)
+ return base::TimeDelta::FromMilliseconds(16);
} else {
// Without a high resolution clock, the resolution can be as bad as 15ms, so
// increase the budgets accordingly to ensure we don't abort before doing
// any phases.
- if (lifecycle_count_ < 60)
- return 16.;
+ if (lifecycle_count < 60)
+ return base::TimeDelta::FromMilliseconds(16);
}
- return 1e9;
+ return base::TimeDelta::FromMilliseconds(1e9);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/display_lock/yielding_display_lock_budget.h b/chromium/third_party/blink/renderer/core/display_lock/yielding_display_lock_budget.h
index 17ee1a72d30..4edf28edf95 100644
--- a/chromium/third_party/blink/renderer/core/display_lock/yielding_display_lock_budget.h
+++ b/chromium/third_party/blink/renderer/core/display_lock/yielding_display_lock_budget.h
@@ -21,9 +21,9 @@ class CORE_EXPORT YieldingDisplayLockBudget final : public DisplayLockBudget {
YieldingDisplayLockBudget(DisplayLockContext*);
~YieldingDisplayLockBudget() override = default;
- bool ShouldPerformPhase(Phase) const override;
+ bool ShouldPerformPhase(Phase, const LifecycleData& lifecycle_data) override;
void DidPerformPhase(Phase) override;
- void WillStartLifecycleUpdate() override;
+ void OnLifecycleChange(const LifecycleData& lifecycle_data) override;
// Returns true if any of the lifecycles that have been previously blocked by
// this budget need updates. Note that this does not check lifecycle phases
// that have already completed by this budget even if they are now dirty
@@ -35,10 +35,11 @@ class CORE_EXPORT YieldingDisplayLockBudget final : public DisplayLockBudget {
protected:
friend class DisplayLockBudgetTest;
- double GetCurrentBudgetMs() const;
+ base::TimeDelta GetCurrentBudget(const LifecycleData& lifecycle_data) const;
- int lifecycle_count_ = 0;
- TimeTicks deadline_;
+ private:
+ unsigned first_lifecycle_count_ = 0;
+ base::TimeTicks deadline_;
base::Optional<Phase> last_completed_phase_;
Phase next_phase_from_start_of_lifecycle_ = Phase::kFirst;
};
diff --git a/chromium/third_party/blink/renderer/core/dom/BUILD.gn b/chromium/third_party/blink/renderer/core/dom/BUILD.gn
index 9557a946f0d..394115bfa0f 100644
--- a/chromium/third_party/blink/renderer/core/dom/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/dom/BUILD.gn
@@ -170,6 +170,8 @@ blink_core_sources("dom") {
"mutation_observer.h",
"mutation_observer_interest_group.cc",
"mutation_observer_interest_group.h",
+ "mutation_observer_notifier.cc",
+ "mutation_observer_notifier.h",
"mutation_observer_registration.cc",
"mutation_observer_registration.h",
"mutation_record.cc",
@@ -224,10 +226,6 @@ blink_core_sources("dom") {
"scripted_animation_controller.h",
"scripted_idle_task_controller.cc",
"scripted_idle_task_controller.h",
- "scripted_task_queue.cc",
- "scripted_task_queue.h",
- "scripted_task_queue_controller.cc",
- "scripted_task_queue_controller.h",
"shadow_root.cc",
"shadow_root.h",
"shadow_root_v0.cc",
diff --git a/chromium/third_party/blink/renderer/core/dom/OWNERS b/chromium/third_party/blink/renderer/core/dom/OWNERS
index 1828548f566..0c86b535391 100644
--- a/chromium/third_party/blink/renderer/core/dom/OWNERS
+++ b/chromium/third_party/blink/renderer/core/dom/OWNERS
@@ -1,4 +1,4 @@
-hayato@chromium.org
+masonfreed@chromium.org
per-file *_struct_traits*.*=set noparent
per-file *_struct_traits*.*=file://ipc/SECURITY_OWNERS
diff --git a/chromium/third_party/blink/renderer/core/dom/README.md b/chromium/third_party/blink/renderer/core/dom/README.md
index 55fba416f2f..c6e41077f92 100644
--- a/chromium/third_party/blink/renderer/core/dom/README.md
+++ b/chromium/third_party/blink/renderer/core/dom/README.md
@@ -730,7 +730,7 @@ DCHECK. :(
Since `Node::UpdateDistributionForFlatTreeTraversal` can take O(N) in the worst
case (_even if the distribution flag is clean!_), you should be careful not to
call it in hot code paths. If you are not sure, please contact
-dom-dev@chromium.org, or add hayato@chromium.org to reviewers.
+dom-dev@chromium.org, or add masonfreed@chromium.org to reviewers.
Once Blink removes Shadow DOM v0 in the future, you don't need to call
`Node::UpdateDistributionForFlatTreeTraversal` before using `FlatTreeTraversal`
diff --git a/chromium/third_party/blink/renderer/core/dom/attr.idl b/chromium/third_party/blink/renderer/core/dom/attr.idl
index 0d099d80ac5..27c31ce893f 100644
--- a/chromium/third_party/blink/renderer/core/dom/attr.idl
+++ b/chromium/third_party/blink/renderer/core/dom/attr.idl
@@ -19,8 +19,9 @@
*/
// https://dom.spec.whatwg.org/#interface-attr
-
-interface Attr : Node {
+[
+ Exposed=Window
+] interface Attr : Node {
readonly attribute DOMString? namespaceURI;
readonly attribute DOMString? prefix;
readonly attribute DOMString localName;
diff --git a/chromium/third_party/blink/renderer/core/dom/attribute.h b/chromium/third_party/blink/renderer/core/dom/attribute.h
index 71151cb38ec..1869c509120 100644
--- a/chromium/third_party/blink/renderer/core/dom/attribute.h
+++ b/chromium/third_party/blink/renderer/core/dom/attribute.h
@@ -28,7 +28,7 @@
#include "build/build_config.h"
#include "third_party/blink/renderer/core/dom/qualified_name.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/dom/attribute_collection.h b/chromium/third_party/blink/renderer/core/dom/attribute_collection.h
index d7ec066dd18..c315c86c131 100644
--- a/chromium/third_party/blink/renderer/core/dom/attribute_collection.h
+++ b/chromium/third_party/blink/renderer/core/dom/attribute_collection.h
@@ -34,7 +34,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_DOM_ATTRIBUTE_COLLECTION_H_
#include "third_party/blink/renderer/core/dom/attribute.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/dom/cdata_section.idl b/chromium/third_party/blink/renderer/core/dom/cdata_section.idl
index 6cd8f22700d..aa09f9927b5 100644
--- a/chromium/third_party/blink/renderer/core/dom/cdata_section.idl
+++ b/chromium/third_party/blink/renderer/core/dom/cdata_section.idl
@@ -19,5 +19,7 @@
// https://dom.spec.whatwg.org/#interface-cdatasection
-interface CDATASection : Text {
+[
+ Exposed=Window
+] interface CDATASection : Text {
};
diff --git a/chromium/third_party/blink/renderer/core/dom/character_data.idl b/chromium/third_party/blink/renderer/core/dom/character_data.idl
index 40df5dd6e6a..3b1a441b2e9 100644
--- a/chromium/third_party/blink/renderer/core/dom/character_data.idl
+++ b/chromium/third_party/blink/renderer/core/dom/character_data.idl
@@ -18,8 +18,9 @@
*/
// https://dom.spec.whatwg.org/#interface-characterdata
-
-interface CharacterData : Node {
+[
+ Exposed=Window
+] interface CharacterData : Node {
attribute [TreatNullAs=EmptyString] DOMString data;
readonly attribute unsigned long length;
[RaisesException] DOMString substringData(unsigned long offset, unsigned long count);
diff --git a/chromium/third_party/blink/renderer/core/dom/child_node.h b/chromium/third_party/blink/renderer/core/dom/child_node.h
index c9358ce6298..4a985a63065 100644
--- a/chromium/third_party/blink/renderer/core/dom/child_node.h
+++ b/chromium/third_party/blink/renderer/core/dom/child_node.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_DOM_CHILD_NODE_H_
#include "third_party/blink/renderer/core/dom/node.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -15,19 +15,19 @@ class ChildNode {
public:
static void before(Node& node,
- const HeapVector<NodeOrString>& nodes,
+ const HeapVector<NodeOrStringOrTrustedScript>& nodes,
ExceptionState& exception_state) {
return node.Before(nodes, exception_state);
}
static void after(Node& node,
- const HeapVector<NodeOrString>& nodes,
+ const HeapVector<NodeOrStringOrTrustedScript>& nodes,
ExceptionState& exception_state) {
return node.After(nodes, exception_state);
}
static void replaceWith(Node& node,
- const HeapVector<NodeOrString>& nodes,
+ const HeapVector<NodeOrStringOrTrustedScript>& nodes,
ExceptionState& exception_state) {
return node.ReplaceWith(nodes, exception_state);
}
diff --git a/chromium/third_party/blink/renderer/core/dom/child_node.idl b/chromium/third_party/blink/renderer/core/dom/child_node.idl
index f455f952fd1..38bc7fec1ce 100644
--- a/chromium/third_party/blink/renderer/core/dom/child_node.idl
+++ b/chromium/third_party/blink/renderer/core/dom/child_node.idl
@@ -25,8 +25,8 @@
[
LegacyTreatAsPartialInterface
] interface mixin ChildNode {
- [Unscopable, RaisesException, CEReactions, CustomElementCallbacks] void before((Node or DOMString) ... nodes);
- [Unscopable, RaisesException, CEReactions, CustomElementCallbacks] void after((Node or DOMString)... nodes);
- [Unscopable, RaisesException, CEReactions, CustomElementCallbacks] void replaceWith((Node or DOMString)... nodes);
+ [Unscopable, RaisesException, CEReactions, CustomElementCallbacks] void before((Node or DOMString or TrustedScript) ... nodes);
+ [Unscopable, RaisesException, CEReactions, CustomElementCallbacks] void after((Node or DOMString or TrustedScript)... nodes);
+ [Unscopable, RaisesException, CEReactions, CustomElementCallbacks] void replaceWith((Node or DOMString or TrustedScript)... nodes);
[Unscopable, RaisesException, CEReactions, CustomElementCallbacks] void remove();
};
diff --git a/chromium/third_party/blink/renderer/core/dom/comment.h b/chromium/third_party/blink/renderer/core/dom/comment.h
index 8a527885143..152bb11eed1 100644
--- a/chromium/third_party/blink/renderer/core/dom/comment.h
+++ b/chromium/third_party/blink/renderer/core/dom/comment.h
@@ -40,7 +40,7 @@ class CORE_EXPORT Comment final : public CharacterData {
String nodeName() const override;
NodeType getNodeType() const override;
Node* Clone(Document&, CloneChildrenFlag) const override;
- void DetachLayoutTree(const AttachContext&) final {}
+ void DetachLayoutTree(bool performing_reattach) final {}
};
template <>
diff --git a/chromium/third_party/blink/renderer/core/dom/comment.idl b/chromium/third_party/blink/renderer/core/dom/comment.idl
index c22cc4a6d6f..06e5126c605 100644
--- a/chromium/third_party/blink/renderer/core/dom/comment.idl
+++ b/chromium/third_party/blink/renderer/core/dom/comment.idl
@@ -21,6 +21,7 @@
[
Constructor(optional DOMString data = ""),
- ConstructorCallWith=Document
+ ConstructorCallWith=Document,
+ Exposed=Window
] interface Comment : CharacterData {
};
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 63b85e3e108..e25e54d40b7 100644
--- a/chromium/third_party/blink/renderer/core/dom/container_node.cc
+++ b/chromium/third_party/blink/renderer/core/dom/container_node.cc
@@ -44,7 +44,6 @@
#include "third_party/blink/renderer/core/dom/whitespace_attacher.h"
#include "third_party/blink/renderer/core/events/mutation_event.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/html/forms/radio_node_list.h"
#include "third_party/blink/renderer/core/html/html_collection.h"
#include "third_party/blink/renderer/core/html/html_frame_owner_element.h"
@@ -59,6 +58,7 @@
#include "third_party/blink/renderer/platform/bindings/runtime_call_stats.h"
#include "third_party/blink/renderer/platform/bindings/script_forbidden_scope.h"
#include "third_party/blink/renderer/platform/bindings/v8_per_isolate_data.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
namespace blink {
@@ -976,16 +976,30 @@ void ContainerNode::RemovedFrom(ContainerNode& insertion_point) {
DISABLE_CFI_PERF
void ContainerNode::AttachLayoutTree(AttachContext& context) {
+ auto* element = DynamicTo<Element>(this);
+ if (element &&
+ element->StyleRecalcBlockedByDisplayLock(DisplayLockContext::kChildren)) {
+ // Since we block style recalc on descendants of this node due to display
+ // locking, none of its descendants should have the NeedsReattachLayoutTree
+ // bit set.
+ DCHECK(!ChildNeedsReattachLayoutTree());
+ // If an element is locked we shouldn't attach the layout tree for its
+ // descendants. We should notify that we blocked a reattach so that we will
+ // correctly attach the descendants when allowed.
+ element->GetDisplayLockContext()->NotifyReattachLayoutTreeWasBlocked();
+ Node::AttachLayoutTree(context);
+ return;
+ }
for (Node* child = firstChild(); child; child = child->nextSibling())
child->AttachLayoutTree(context);
Node::AttachLayoutTree(context);
ClearChildNeedsReattachLayoutTree();
}
-void ContainerNode::DetachLayoutTree(const AttachContext& context) {
+void ContainerNode::DetachLayoutTree(bool performing_reattach) {
for (Node* child = firstChild(); child; child = child->nextSibling())
- child->DetachLayoutTree(context);
- Node::DetachLayoutTree(context);
+ child->DetachLayoutTree(performing_reattach);
+ Node::DetachLayoutTree(performing_reattach);
}
void ContainerNode::ChildrenChanged(const ChildrenChange& change) {
@@ -1019,12 +1033,10 @@ void ContainerNode::CloneChildNodesFrom(const ContainerNode& node) {
AppendChild(child.Clone(GetDocument(), CloneChildrenFlag::kClone));
}
-LayoutRect ContainerNode::BoundingBox() const {
+PhysicalRect ContainerNode::BoundingBox() const {
if (!GetLayoutObject())
- return LayoutRect();
- return GetLayoutObject()
- ->AbsoluteBoundingBoxRectHandlingEmptyInline()
- .ToLayoutRect();
+ return PhysicalRect();
+ return GetLayoutObject()->AbsoluteBoundingBoxRectHandlingEmptyInline();
}
// This is used by FrameSelection to denote when the active-state of the page
@@ -1156,42 +1168,6 @@ void ContainerNode::SetHasFocusWithinUpToAncestor(bool flag, Node* ancestor) {
}
}
-void ContainerNode::SetActive(bool down) {
- if (down == IsActive())
- return;
-
- Node::SetActive(down);
-
- if (!GetLayoutObject()) {
- auto* this_element = DynamicTo<Element>(this);
- if (this_element && this_element->ChildrenOrSiblingsAffectedByActive()) {
- this_element->PseudoStateChanged(CSSSelector::kPseudoActive);
- } else {
- SetNeedsStyleRecalc(kLocalStyleChange,
- StyleChangeReasonForTracing::CreateWithExtraData(
- style_change_reason::kPseudoClass,
- style_change_extra_data::g_active));
- }
- return;
- }
-
- if (GetComputedStyle()->AffectedByActive()) {
- StyleChangeType change_type =
- GetComputedStyle()->HasPseudoStyle(kPseudoIdFirstLetter)
- ? kSubtreeStyleChange
- : kLocalStyleChange;
- SetNeedsStyleRecalc(change_type,
- StyleChangeReasonForTracing::CreateWithExtraData(
- style_change_reason::kPseudoClass,
- style_change_extra_data::g_active));
- }
- auto* this_element = DynamicTo<Element>(this);
- if (this_element && this_element->ChildrenOrSiblingsAffectedByActive())
- this_element->PseudoStateChanged(CSSSelector::kPseudoActive);
-
- GetLayoutObject()->InvalidateIfControlStateChanged(kPressedControlState);
-}
-
void ContainerNode::SetDragged(bool new_value) {
if (new_value == IsDragged())
return;
@@ -1231,30 +1207,6 @@ void ContainerNode::SetDragged(bool new_value) {
this_element->PseudoStateChanged(CSSSelector::kPseudoDrag);
}
-void ContainerNode::SetHovered(bool over) {
- if (over == IsHovered())
- return;
-
- Node::SetHovered(over);
-
- const ComputedStyle* style = GetComputedStyle();
- if (!style || style->AffectedByHover()) {
- StyleChangeType change_type = kLocalStyleChange;
- if (style && style->HasPseudoStyle(kPseudoIdFirstLetter))
- change_type = kSubtreeStyleChange;
- SetNeedsStyleRecalc(change_type,
- StyleChangeReasonForTracing::CreateWithExtraData(
- style_change_reason::kPseudoClass,
- style_change_extra_data::g_hover));
- }
- auto* this_element = DynamicTo<Element>(this);
- if (this_element && this_element->ChildrenOrSiblingsAffectedByHover())
- this_element->PseudoStateChanged(CSSSelector::kPseudoHover);
-
- if (LayoutObject* o = GetLayoutObject())
- o->InvalidateIfControlStateChanged(kHoverControlState);
-}
-
HTMLCollection* ContainerNode::Children() {
return EnsureCachedCollection<HTMLCollection>(kNodeChildren);
}
@@ -1434,24 +1386,6 @@ void ContainerNode::RebuildLayoutTreeForChild(
whitespace_attacher.DidVisitElement(element);
}
-void ContainerNode::RebuildNonDistributedChildren() {
- // Non-distributed children are:
- // 1. Children of shadow hosts which are not slotted (v1) or distributed to an
- // insertion point (v0).
- // 2. Children of <slot> (v1) and <content> (v0) elements which are not used
- // as fallback content when no nodes are slotted/distributed.
- //
- // These children will not take part in the flat tree, but we need to walk
- // them in order to clear dirtiness flags during layout tree rebuild. We
- // need to use a separate WhitespaceAttacher so that DidVisitText does not
- // mess up the WhitespaceAttacher for the layout tree rebuild of the nodes
- // which take part in the flat tree.
- WhitespaceAttacher whitespace_attacher;
- for (Node* child = lastChild(); child; child = child->previousSibling())
- RebuildLayoutTreeForChild(child, whitespace_attacher);
- ClearChildNeedsReattachLayoutTree();
-}
-
void ContainerNode::RebuildChildrenLayoutTrees(
WhitespaceAttacher& whitespace_attacher) {
DCHECK(!NeedsReattachLayoutTree());
@@ -1463,7 +1397,6 @@ void ContainerNode::RebuildChildrenLayoutTrees(
To<V0InsertionPoint>(this)->RebuildDistributedChildrenLayoutTrees(
whitespace_attacher);
}
- RebuildNonDistributedChildren();
return;
}
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 310a087e1e7..8649528aac9 100644
--- a/chromium/third_party/blink/renderer/core/dom/container_node.h
+++ b/chromium/third_party/blink/renderer/core/dom/container_node.h
@@ -149,16 +149,14 @@ class CORE_EXPORT ContainerNode : public Node {
void CloneChildNodesFrom(const ContainerNode&);
void AttachLayoutTree(AttachContext&) override;
- void DetachLayoutTree(const AttachContext& = AttachContext()) override;
- LayoutRect BoundingBox() const final;
+ void DetachLayoutTree(bool performing_reattach = false) override;
+ PhysicalRect BoundingBox() const final;
void SetFocused(bool, WebFocusType) override;
void SetHasFocusWithinUpToAncestor(bool, Node* ancestor);
void FocusStateChanged();
void FocusVisibleStateChanged();
void FocusWithinStateChanged();
- void SetActive(bool = true) override;
void SetDragged(bool) override;
- void SetHovered(bool = true) override;
void RemovedFrom(ContainerNode& insertion_point) override;
bool ChildrenOrSiblingsAffectedByFocus() const {
@@ -293,7 +291,6 @@ class CORE_EXPORT ContainerNode : public Node {
void RecalcDescendantStyles(const StyleRecalcChange);
void RebuildChildrenLayoutTrees(WhitespaceAttacher&);
void RebuildLayoutTreeForChild(Node* child, WhitespaceAttacher&);
- void RebuildNonDistributedChildren();
// -----------------------------------------------------------------------------
// Notification of document structure changes (see core/dom/node.h for more
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 a7eef75127d..a4d9bb3c278 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
@@ -34,7 +34,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/platform/weborigin/security_origin.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/dom/create_element_flags.h b/chromium/third_party/blink/renderer/core/dom/create_element_flags.h
index aea3a5c1631..37accd81586 100644
--- a/chromium/third_party/blink/renderer/core/dom/create_element_flags.h
+++ b/chromium/third_party/blink/renderer/core/dom/create_element_flags.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_DOM_CREATE_ELEMENT_FLAGS_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_DOM_CREATE_ELEMENT_FLAGS_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
class CreateElementFlags {
STACK_ALLOCATED();
diff --git a/chromium/third_party/blink/renderer/core/dom/document.cc b/chromium/third_party/blink/renderer/core/dom/document.cc
index 7e782a249da..920dab7c48d 100644
--- a/chromium/third_party/blink/renderer/core/dom/document.cc
+++ b/chromium/third_party/blink/renderer/core/dom/document.cc
@@ -40,7 +40,7 @@
#include "services/metrics/public/cpp/mojo_ukm_recorder.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "services/metrics/public/cpp/ukm_source_id.h"
-#include "services/metrics/public/mojom/ukm_interface.mojom-shared.h"
+#include "services/metrics/public/mojom/ukm_interface.mojom-blink.h"
#include "services/resource_coordinator/public/mojom/coordination_unit.mojom-blink.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
@@ -115,6 +115,7 @@
#include "third_party/blink/renderer/core/dom/layout_tree_builder_traversal.h"
#include "third_party/blink/renderer/core/dom/live_node_list.h"
#include "third_party/blink/renderer/core/dom/mutation_observer.h"
+#include "third_party/blink/renderer/core/dom/mutation_observer_notifier.h"
#include "third_party/blink/renderer/core/dom/node_child_removal_tracker.h"
#include "third_party/blink/renderer/core/dom/node_computed_style.h"
#include "third_party/blink/renderer/core/dom/node_iterator.h"
@@ -146,6 +147,8 @@
#include "third_party/blink/renderer/core/events/page_transition_event.h"
#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/execution_context/window_agent.h"
+#include "third_party/blink/renderer/core/execution_context/window_agent_factory.h"
#include "third_party/blink/renderer/core/feature_policy/document_policy.h"
#include "third_party/blink/renderer/core/feature_policy/feature_policy_parser.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
@@ -164,7 +167,6 @@
#include "third_party/blink/renderer/core/frame/report.h"
#include "third_party/blink/renderer/core/frame/reporting_context.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/frame/viewport_data.h"
#include "third_party/blink/renderer/core/frame/visual_viewport.h"
#include "third_party/blink/renderer/core/html/anchor_element_metrics.h"
@@ -278,14 +280,13 @@
#include "third_party/blink/renderer/platform/bindings/script_forbidden_scope.h"
#include "third_party/blink/renderer/platform/bindings/v8_dom_wrapper.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/date_components.h"
#include "third_party/blink/renderer/platform/geometry/length_functions.h"
#include "third_party/blink/renderer/platform/heap/heap.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/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h"
#include "third_party/blink/renderer/platform/instrumentation/resource_coordinator/document_resource_coordinator.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/language.h"
#include "third_party/blink/renderer/platform/loader/fetch/null_resource_fetcher_properties.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
@@ -297,10 +298,13 @@
#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/date_components.h"
#include "third_party/blink/renderer/platform/text/platform_locale.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
#include "third_party/blink/renderer/platform/weborigin/origin_access_entry.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/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/wtf/date_math.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/blink/renderer/platform/wtf/hash_functions.h"
@@ -388,7 +392,8 @@ static const unsigned kCMaxWriteRecursionDepth = 21;
// a layout without a delay.
// FIXME: For faster machines this value can really be lowered to 200. 250 is
// adequate, but a little high for dual G5s. :)
-static const int kCLayoutScheduleThreshold = 250;
+static const base::TimeDelta kCLayoutScheduleThreshold =
+ base::TimeDelta::FromMilliseconds(250);
// DOM Level 2 says (letters added):
//
@@ -595,20 +600,382 @@ class Document::NetworkStateObserver final
online_observer_handle_;
};
+// A helper class that allows the security context be initialized in the
+// process of constructing the document.
+class Document::SecurityContextInit : public FeaturePolicyParserDelegate {
+ STACK_ALLOCATED();
+
+ public:
+ SecurityContextInit(const DocumentInit& initializer,
+ DocumentClassFlags document_classes) {
+ // Content Security Policy can provide sandbox flags. In CSP
+ // 'self' will be determined when the policy is bound. That occurs
+ // once the document is constructed.
+ InitializeContentSecurityPolicy(initializer, document_classes);
+
+ // Sandbox flags can come from initializer, loader or CSP.
+ InitializeSandboxFlags(initializer);
+
+ // The origin can be opaque based on sandbox flags.
+ InitializeOrigin(initializer);
+
+ // Initialize origin trials, requires the post sandbox flags
+ // security origin.
+ InitializeOriginTrials(initializer);
+
+ // Initialize feature policy, depends on origin trials.
+ InitializeFeaturePolicy(initializer, document_classes);
+
+ // Initialize the agent. Depends on security origin.
+ InitializeAgent(initializer);
+ }
+
+ const scoped_refptr<SecurityOrigin>& GetSecurityOrigin() const {
+ return security_origin_;
+ }
+
+ WebSandboxFlags GetSandboxFlags() { return sandbox_flags_; }
+
+ ContentSecurityPolicy* GetCSP() const { return csp_; }
+
+ std::unique_ptr<FeaturePolicy> TakeFeaturePolicy() {
+ DCHECK(feature_policy_);
+ return std::move(feature_policy_);
+ }
+
+ const Vector<String>& FeaturePolicyParseMessages() const {
+ return feature_policy_parse_messages_;
+ }
+ const ParsedFeaturePolicy& ParsedHeader() const { return parsed_header_; }
+
+ OriginTrialContext* GetOriginTrialContext() { return origin_trials_; }
+
+ Agent* GetAgent() { return agent_; }
+
+ void CountFeaturePolicyUsage(mojom::WebFeature feature) override {
+ feature_count_.insert(feature);
+ }
+
+ bool FeaturePolicyFeatureObserved(
+ mojom::FeaturePolicyFeature feature) override {
+ if (parsed_feature_policies_.Contains(feature))
+ return true;
+ parsed_feature_policies_.insert(feature);
+ return false;
+ }
+
+ bool FeatureEnabled(OriginTrialFeature feature) const override {
+ return origin_trials_->IsFeatureEnabled(feature);
+ }
+
+ void ApplyPendingDataToDocument(Document& document) {
+ for (auto feature : feature_count_)
+ UseCounter::Count(document, feature);
+ for (auto feature : parsed_feature_policies_)
+ document.FeaturePolicyFeatureObserved(feature);
+ }
+
+ bool BindCSPImmediately() const { return bind_csp_immediately_; }
+
+ private:
+ void InitializeContentSecurityPolicy(const DocumentInit& initializer,
+ DocumentClassFlags document_classes) {
+ auto* frame = initializer.GetFrame();
+ ContentSecurityPolicy* last_origin_document_csp =
+ frame ? frame->Loader().GetLastOriginDocumentCSP() : nullptr;
+
+ KURL url;
+ if (initializer.ShouldSetURL()) {
+ url = initializer.Url();
+ if (url.IsEmpty())
+ url = BlankURL();
+ }
+
+ if (initializer.HasSecurityContext() && !initializer.OriginToCommit() &&
+ initializer.OwnerDocument()) {
+ // Alias certain security properties from |owner_document|. Used for
+ // the case of about:blank pages inheriting the security properties of
+ // their requestor context.
+ // Note that this is currently somewhat broken; Blink always inherits
+ // from the parent or opener, even though it should actually be
+ // inherited from the request initiator.
+ if (url.IsEmpty()) {
+ last_origin_document_csp =
+ initializer.OwnerDocument()->GetContentSecurityPolicy();
+ }
+ }
+
+ csp_ = initializer.GetContentSecurityPolicy();
+
+ if (!csp_ && initializer.ImportsController()) {
+ // If this document is an HTML import, grab a reference to its master
+ // document's Content Security Policy. We don't bind the CSP's delegate
+ // in 'InitSecurityPolicy' in this case, as we can't rebind the
+ // master document's policy object: The Content Security Policy's delegate
+ // needs to remain set to the master document.
+ csp_ =
+ initializer.ImportsController()->Master()->GetContentSecurityPolicy();
+ } else {
+ if (!csp_) {
+ csp_ = MakeGarbageCollected<ContentSecurityPolicy>();
+ bind_csp_immediately_ = true;
+ }
+
+ // We should inherit the navigation initiator CSP if the document is
+ // loaded using a local-scheme url.
+ if (last_origin_document_csp &&
+ (url.IsEmpty() || url.ProtocolIsAbout() || url.ProtocolIsData() ||
+ url.ProtocolIs("blob") || url.ProtocolIs("filesystem"))) {
+ csp_->CopyStateFrom(last_origin_document_csp);
+ }
+
+ if (document_classes & kPluginDocumentClass) {
+ // TODO(andypaicu): This should inherit the origin document's plugin
+ // types but because this could be a OOPIF document it might not have
+ // access. In this situation we fallback on using the parent/opener.
+ if (last_origin_document_csp) {
+ csp_->CopyPluginTypesFrom(last_origin_document_csp);
+ } else if (frame) {
+ Frame* inherit_from = frame->Tree().Parent()
+ ? frame->Tree().Parent()
+ : frame->Client()->Opener();
+ if (inherit_from && frame != inherit_from) {
+ DCHECK(
+ inherit_from->GetSecurityContext() &&
+ inherit_from->GetSecurityContext()->GetContentSecurityPolicy());
+ csp_->CopyPluginTypesFrom(
+ inherit_from->GetSecurityContext()->GetContentSecurityPolicy());
+ }
+ }
+ }
+ }
+ }
+
+ void InitializeSandboxFlags(const DocumentInit& initializer) {
+ sandbox_flags_ = initializer.GetSandboxFlags() | csp_->GetSandboxMask();
+ auto* frame = initializer.GetFrame();
+ if (frame && frame->Loader().GetDocumentLoader()->Archive()) {
+ // The URL of a Document loaded from a MHTML archive is controlled by
+ // the Content-Location header. This would allow UXSS, since
+ // Content-Location can be arbitrarily controlled to control the
+ // Document's URL and origin. Instead, force a Document loaded from a
+ // MHTML archive to be sandboxed, providing exceptions only for creating
+ // new windows.
+ sandbox_flags_ |=
+ (WebSandboxFlags::kAll &
+ ~(WebSandboxFlags::kPopups |
+ WebSandboxFlags::kPropagatesToAuxiliaryBrowsingContexts));
+ }
+ }
+
+ void InitializeOrigin(const DocumentInit& initializer) {
+ scoped_refptr<SecurityOrigin> document_origin =
+ initializer.GetDocumentOrigin();
+ if ((sandbox_flags_ & WebSandboxFlags::kOrigin) != WebSandboxFlags::kNone) {
+ scoped_refptr<SecurityOrigin> sandboxed_origin =
+ initializer.OriginToCommit()
+ ? initializer.OriginToCommit()
+ : document_origin->DeriveNewOpaqueOrigin();
+
+ // If we're supposed to inherit our security origin from our
+ // owner, but we're also sandboxed, the only things we inherit are
+ // the origin's potential trustworthiness and the ability to
+ // load local resources. The latter lets about:blank iframes in
+ // file:// URL documents load images and other resources from
+ // the file system.
+ //
+ // Note: Sandboxed about:srcdoc iframe without "allow-same-origin" aren't
+ // allowed to load user's file, even if its parent can.
+ if (initializer.OwnerDocument()) {
+ if (document_origin->IsPotentiallyTrustworthy())
+ sandboxed_origin->SetOpaqueOriginIsPotentiallyTrustworthy(true);
+ if (document_origin->CanLoadLocalResources() &&
+ !initializer.IsSrcdocDocument())
+ sandboxed_origin->GrantLoadLocalResources();
+ }
+ security_origin_ = sandboxed_origin;
+ } else {
+ security_origin_ = document_origin;
+ }
+
+ // If we are a page popup in LayoutTests ensure we use the popup
+ // owner's security origin so the tests can possibly access the
+ // document via internals API.
+ auto* frame = initializer.GetFrame();
+ if (IsPagePopupRunningInWebTest(frame)) {
+ security_origin_ = frame->PagePopupOwner()
+ ->GetDocument()
+ .GetSecurityOrigin()
+ ->IsolatedCopy();
+ }
+ }
+
+ void InitializeFeaturePolicy(const DocumentInit& initializer,
+ DocumentClassFlags document_classes) {
+ auto* frame = initializer.GetFrame();
+ // For a main frame, get inherited feature policy from the opener if any.
+ const FeaturePolicy::FeatureState* opener_feature_state = nullptr;
+ if (frame && frame->IsMainFrame() && !frame->OpenerFeatureState().empty()) {
+ opener_feature_state = &frame->OpenerFeatureState();
+ }
+
+ parsed_header_ = FeaturePolicyParser::ParseHeader(
+ initializer.FeaturePolicyHeader(), security_origin_,
+ &feature_policy_parse_messages_, this);
+
+ if (sandbox_flags_ != WebSandboxFlags::kNone &&
+ RuntimeEnabledFeatures::FeaturePolicyForSandboxEnabled()) {
+ // The sandbox flags might have come from CSP header or the browser; in
+ // such cases the sandbox is not part of the container policy. They are
+ // added to the header policy (which specifically makes sense in the case
+ // of CSP sandbox).
+ ApplySandboxFlagsToParsedFeaturePolicy(sandbox_flags_, parsed_header_);
+ }
+
+ ParsedFeaturePolicy container_policy;
+ if (frame && frame->Owner())
+ container_policy = frame->Owner()->GetFramePolicy().container_policy;
+
+ // TODO(icelland): This is problematic querying sandbox flags before
+ // feature policy is initialized.
+ if (RuntimeEnabledFeatures::BlockingFocusWithoutUserActivationEnabled() &&
+ frame && frame->Tree().Parent() &&
+ (sandbox_flags_ & WebSandboxFlags::kNavigation) !=
+ WebSandboxFlags::kNone) {
+ // Enforcing the policy for sandbox frames (for context see
+ // https://crbug.com/954349).
+ DisallowFeatureIfNotPresent(
+ mojom::FeaturePolicyFeature::kFocusWithoutUserActivation,
+ container_policy);
+ }
+
+ const FeaturePolicy* parent_feature_policy = nullptr;
+ if (frame && !frame->IsMainFrame()) {
+ parent_feature_policy =
+ frame->Tree().Parent()->GetSecurityContext()->GetFeaturePolicy();
+ }
+
+ // If we are a HTMLViewSourceDocument we use container, header or
+ // inherited policies. https://crbug.com/898688
+ if (document_classes & kViewSourceDocumentClass) {
+ feature_policy_ = FeaturePolicy::CreateFromParentPolicy(
+ nullptr, {}, security_origin_->ToUrlOrigin());
+ return;
+ }
+
+ // Feature policy should either come from a parent in the case of an
+ // embedded child frame, or from an opener if any when a new window is
+ // created by an opener. A main frame without an opener would not have a
+ // parent policy nor an opener feature state.
+ DCHECK(!parent_feature_policy || !opener_feature_state);
+ if (!opener_feature_state ||
+ !RuntimeEnabledFeatures::FeaturePolicyForSandboxEnabled()) {
+ feature_policy_ = FeaturePolicy::CreateFromParentPolicy(
+ parent_feature_policy, container_policy,
+ security_origin_->ToUrlOrigin());
+ } else {
+ DCHECK(!parent_feature_policy);
+ feature_policy_ = FeaturePolicy::CreateWithOpenerPolicy(
+ *opener_feature_state, security_origin_->ToUrlOrigin());
+ }
+ feature_policy_->SetHeaderPolicy(parsed_header_);
+ }
+
+ void InitializeOriginTrials(const DocumentInit& initializer) {
+ origin_trials_ = MakeGarbageCollected<OriginTrialContext>();
+
+ const String& header_value = initializer.OriginTrialsHeader();
+
+ if (header_value.IsEmpty())
+ return;
+ std::unique_ptr<Vector<String>> tokens(
+ OriginTrialContext::ParseHeaderValue(header_value));
+ if (!tokens)
+ return;
+ origin_trials_->AddTokens(security_origin_.get(), true, *tokens);
+ }
+
+ void InitializeAgent(const DocumentInit& initializer) {
+ auto* frame = initializer.GetFrame();
+
+ // If we are a page popup in LayoutTests ensure we use the popup
+ // owner's frame for looking up the Agent so the tests can possibly
+ // access the document via internals API.
+ if (IsPagePopupRunningInWebTest(frame)) {
+ frame = frame->PagePopupOwner()->GetDocument().GetFrame();
+ } else if (!frame) {
+ if (Document* context_document = initializer.ContextDocument()) {
+ frame = context_document->GetFrame();
+ } else if (Document* owner_document = initializer.OwnerDocument()) {
+ frame = owner_document->GetFrame();
+ }
+ }
+
+ if (frame) {
+ bool has_potential_universal_access_privilege = false;
+ if (Settings* settings = frame->GetSettings()) {
+ // TODO(keishi): Also check if AllowUniversalAccessFromFileURLs might
+ // dynamically change.
+ if (!settings->GetWebSecurityEnabled() ||
+ settings->GetAllowUniversalAccessFromFileURLs())
+ has_potential_universal_access_privilege = true;
+ }
+ agent_ = frame->window_agent_factory().GetAgentForOrigin(
+ has_potential_universal_access_privilege,
+ V8PerIsolateData::MainThreadIsolate(), security_origin_.get());
+ } else {
+ // ContextDocument is null only for Documents created in unit tests.
+ // In that case, use a throw away WindowAgent.
+ agent_ = MakeGarbageCollected<WindowAgent>(
+ V8PerIsolateData::MainThreadIsolate());
+ }
+ }
+
+ bool IsPagePopupRunningInWebTest(LocalFrame* frame) {
+ return frame && frame->GetPage()->GetChromeClient().IsPopup() &&
+ WebTestSupport::IsRunningWebTest();
+ }
+
+ scoped_refptr<SecurityOrigin> security_origin_;
+ WebSandboxFlags sandbox_flags_ = WebSandboxFlags::kNone;
+ std::unique_ptr<FeaturePolicy> feature_policy_;
+ Vector<String> feature_policy_parse_messages_;
+ ParsedFeaturePolicy parsed_header_;
+ Member<ContentSecurityPolicy> csp_;
+ Member<OriginTrialContext> origin_trials_;
+ Member<Agent> agent_;
+ HashSet<mojom::FeaturePolicyFeature> parsed_feature_policies_;
+ HashSet<mojom::WebFeature> feature_count_;
+ bool bind_csp_immediately_ = false;
+};
+
Document* Document::Create(Document& document) {
- Document* new_document = MakeGarbageCollected<Document>(
- DocumentInit::Create().WithContextDocument(&document).WithURL(
- BlankURL()));
- new_document->SetSecurityOrigin(document.GetMutableSecurityOrigin());
+ Document* new_document =
+ MakeGarbageCollected<Document>(DocumentInit::Create()
+ .WithContextDocument(&document)
+ .WithURL(BlankURL())
+ .WithOwnerDocument(&document));
new_document->SetContextFeatures(document.GetContextFeatures());
return new_document;
}
Document::Document(const DocumentInit& initializer,
DocumentClassFlags document_classes)
+ : Document(initializer,
+ SecurityContextInit(initializer, document_classes),
+ document_classes) {}
+
+Document::Document(const DocumentInit& initializer,
+ SecurityContextInit security_initializer,
+ DocumentClassFlags document_classes)
: ContainerNode(nullptr, kCreateDocument),
TreeScope(*this),
- ExecutionContext(V8PerIsolateData::MainThreadIsolate(), nullptr),
+ SecurityContext(security_initializer.GetSecurityOrigin(),
+ security_initializer.GetSandboxFlags(),
+ security_initializer.TakeFeaturePolicy()),
+ ExecutionContext(V8PerIsolateData::MainThreadIsolate(),
+ security_initializer.GetAgent(),
+ security_initializer.GetOriginTrialContext()),
evaluate_media_queries_on_style_recalc_(false),
pending_sheet_layout_(kNoLayoutWithPendingSheets),
frame_(initializer.GetFrame()),
@@ -647,7 +1014,6 @@ Document::Document(const DocumentInit& initializer,
was_discarded_(false),
load_event_progress_(kLoadEventCompleted),
is_freezing_in_progress_(false),
- start_time_(CurrentTime()),
script_runner_(MakeGarbageCollected<ScriptRunner>(this)),
xml_version_("1.0"),
xml_standalone_(kStandaloneUnspecified),
@@ -701,6 +1067,7 @@ Document::Document(const DocumentInit& initializer,
isolated_world_csp_map_(
MakeGarbageCollected<
HeapHashMap<int, Member<ContentSecurityPolicy>>>()) {
+ security_initializer.ApplyPendingDataToDocument(*this);
if (frame_) {
DCHECK(frame_->GetPage());
ProvideContextFeaturesToDocumentFrom(*this, *frame_->GetPage());
@@ -712,6 +1079,7 @@ Document::Document(const DocumentInit& initializer,
: nullptr;
if (registry && registration_context_)
registry->Entangle(registration_context_);
+ cookie_jar_ = std::make_unique<CookieJar>(this);
} else if (imports_controller_) {
fetcher_ = FrameFetchContext::CreateFetcherForImportedDocument(this);
} else {
@@ -740,12 +1108,8 @@ Document::Document(const DocumentInit& initializer,
UpdateBaseURL();
}
- InitSecurityContext(initializer);
- if (frame_)
- frame_->Client()->DidSetFramePolicyHeaders(GetSandboxFlags(), {});
-
- // TODO(tzik): Set up Agent for the current SecurityOrigin, and store it
- // with SetAgent().
+ InitSecurityContext(initializer, security_initializer);
+ FeaturePolicyInitialized(initializer, security_initializer);
InitDNSPrefetch();
@@ -1193,6 +1557,12 @@ ScriptValue Document::registerElement(ScriptState* script_state,
return constructor_builder.BindingsReturnValue();
}
+V0CustomElementRegistrationContext* Document::RegistrationContext() const {
+ if (RuntimeEnabledFeatures::CustomElementsV0Enabled(this))
+ return registration_context_.Get();
+ return nullptr;
+}
+
V0CustomElementMicrotaskRunQueue* Document::CustomElementMicrotaskRunQueue() {
if (!custom_element_microtask_run_queue_) {
custom_element_microtask_run_queue_ =
@@ -1969,158 +2339,206 @@ void Document::SetupFontBuilder(ComputedStyle& document_style) {
void Document::PropagateStyleToViewport() {
DCHECK(InStyleRecalc());
- if (!documentElement())
- return;
-
HTMLElement* body = this->body();
+ Element* document_element = this->documentElement();
- const ComputedStyle* body_style =
- body ? body->EnsureComputedStyle() : nullptr;
const ComputedStyle* document_element_style =
- documentElement()->EnsureComputedStyle();
-
- TouchAction effective_touch_action =
- document_element_style->GetEffectiveTouchAction();
- WritingMode root_writing_mode = document_element_style->GetWritingMode();
- TextDirection root_direction = document_element_style->Direction();
- if (body_style) {
- root_writing_mode = body_style->GetWritingMode();
- root_direction = body_style->Direction();
- }
-
- const ComputedStyle* background_style = document_element_style;
- // 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::BackgroundTransfersToView()
- if (IsHTMLHtmlElement(documentElement()) &&
- document_element_style->Display() != EDisplay::kNone &&
- IsHTMLBodyElement(body) && !background_style->HasBackground()) {
- background_style = body_style;
- }
-
- 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);
+ document_element && documentElement()->GetLayoutObject()
+ ? documentElement()->GetComputedStyle()
+ : nullptr;
+ const ComputedStyle* body_style =
+ body && body->GetLayoutObject() ? body->GetComputedStyle() : nullptr;
+
+ const ComputedStyle& viewport_style = GetLayoutView()->StyleRef();
+ scoped_refptr<ComputedStyle> new_viewport_style =
+ ComputedStyle::Clone(viewport_style);
+ bool changed = false;
+
+#define PROPAGATE_FROM(source, getter, setter, initial) \
+ PROPAGATE_VALUE(source ? source->getter() : initial, getter, setter);
+
+#define PROPAGATE_VALUE(value, getter, setter) \
+ if ((new_viewport_style->getter()) != (value)) { \
+ new_viewport_style->setter(value); \
+ changed = true; \
+ }
+
+ // Writing mode and direction
+ {
+ const ComputedStyle* direction_style =
+ body_style ? body_style : document_element_style;
+ PROPAGATE_FROM(direction_style, GetWritingMode, SetWritingMode,
+ WritingMode::kHorizontalTb);
+ PROPAGATE_FROM(direction_style, Direction, SetDirection,
+ TextDirection::kLtr);
+ }
+
+ // Background
+ {
+ const ComputedStyle* background_style = document_element_style;
+ // 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::BackgroundTransfersToView()
+ if (body_style && IsHTMLHtmlElement(documentElement()) &&
+ IsHTMLBodyElement(body) && !background_style->HasBackground()) {
+ background_style = body_style;
+ }
+
+ Color background_color = Color::kTransparent;
+ FillLayer background_layers(EFillLayerType::kBackground, true);
+ EImageRendering image_rendering = EImageRendering::kAuto;
+
+ if (background_style) {
+ 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();
+ }
+
+ if (viewport_style.VisitedDependentColor(GetCSSPropertyBackgroundColor()) !=
+ background_color ||
+ viewport_style.BackgroundLayers() != background_layers ||
+ viewport_style.ImageRendering() != image_rendering) {
+ changed = true;
+ new_viewport_style->SetBackgroundColor(background_color);
+ new_viewport_style->AccessBackgroundLayers() = background_layers;
+ new_viewport_style->SetImageRendering(image_rendering);
}
- image_rendering = background_style->ImageRendering();
}
- 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;
-
- ScrollBehavior scroll_behavior = document_element_style->GetScrollBehavior();
-
- EOverscrollBehavior overscroll_behavior_x =
- overflow_style->OverscrollBehaviorX();
- EOverscrollBehavior overscroll_behavior_y =
- overflow_style->OverscrollBehaviorY();
- using OverscrollBehaviorType = cc::OverscrollBehavior::OverscrollBehaviorType;
- if (IsInMainFrame()) {
- GetPage()->GetChromeClient().SetOverscrollBehavior(
- *GetFrame(),
- cc::OverscrollBehavior(
- static_cast<OverscrollBehaviorType>(overscroll_behavior_x),
- static_cast<OverscrollBehaviorType>(overscroll_behavior_y)));
- }
-
- // We only propagate the properties related to snap container since viewport
- // defining element cannot be a snap area.
- cc::ScrollSnapType snap_type = overflow_style->GetScrollSnapType();
- Length scroll_padding_top = overflow_style->ScrollPaddingTop();
- Length scroll_padding_right = overflow_style->ScrollPaddingRight();
- Length scroll_padding_bottom = overflow_style->ScrollPaddingBottom();
- Length scroll_padding_left = overflow_style->ScrollPaddingLeft();
-
- bool dark_color_scheme = document_element_style->DarkColorScheme();
+ // Overflow
+ {
+ const ComputedStyle* overflow_style = nullptr;
+ if (Element* viewport_element = ViewportDefiningElement()) {
+ 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);
+ }
+ }
+ }
- const ComputedStyle& viewport_style = GetLayoutView()->StyleRef();
- if (viewport_style.GetWritingMode() != root_writing_mode ||
- viewport_style.Direction() != root_direction ||
- viewport_style.VisitedDependentColor(GetCSSPropertyBackgroundColor()) !=
- background_color ||
- viewport_style.BackgroundLayers() != background_layers ||
- viewport_style.ImageRendering() != image_rendering ||
- viewport_style.OverflowAnchor() != overflow_anchor ||
- viewport_style.OverflowX() != overflow_x ||
- viewport_style.OverflowY() != overflow_y ||
- viewport_style.GetScrollSnapType() != snap_type ||
- viewport_style.GetScrollBehavior() != scroll_behavior ||
- viewport_style.OverscrollBehaviorX() != overscroll_behavior_x ||
- viewport_style.OverscrollBehaviorY() != overscroll_behavior_y ||
- viewport_style.ScrollPaddingTop() != scroll_padding_top ||
- viewport_style.ScrollPaddingRight() != scroll_padding_right ||
- viewport_style.ScrollPaddingBottom() != scroll_padding_bottom ||
- viewport_style.ScrollPaddingLeft() != scroll_padding_left ||
- viewport_style.GetEffectiveTouchAction() != effective_touch_action ||
- viewport_style.DarkColorScheme() != dark_color_scheme) {
- scoped_refptr<ComputedStyle> new_style =
- ComputedStyle::Clone(viewport_style);
- new_style->SetWritingMode(root_writing_mode);
- new_style->UpdateFontOrientation();
- new_style->SetDirection(root_direction);
- new_style->SetBackgroundColor(background_color);
- new_style->AccessBackgroundLayers() = background_layers;
- new_style->SetImageRendering(image_rendering);
- new_style->SetOverflowAnchor(overflow_anchor);
- new_style->SetOverflowX(overflow_x);
- new_style->SetOverflowY(overflow_y);
- new_style->SetScrollSnapType(snap_type);
- new_style->SetScrollBehavior(scroll_behavior);
- new_style->SetOverscrollBehaviorX(overscroll_behavior_x);
- new_style->SetOverscrollBehaviorY(overscroll_behavior_y);
- new_style->SetScrollPaddingTop(scroll_padding_top);
- new_style->SetScrollPaddingRight(scroll_padding_right);
- new_style->SetScrollPaddingBottom(scroll_padding_bottom);
- new_style->SetScrollPaddingLeft(scroll_padding_left);
- new_style->SetEffectiveTouchAction(effective_touch_action);
- new_style->SetDarkColorScheme(dark_color_scheme);
- GetLayoutView()->SetStyle(new_style);
- SetupFontBuilder(*new_style);
+ // TODO(954423, 952711): scroll-snap-* and overscroll-behavior (and most
+ // likely overflow-anchor) should be propagated from the document element
+ // and not the viewport defining element.
+
+ // We only propagate the properties related to snap container since viewport
+ // defining element cannot be a snap area.
+ PROPAGATE_FROM(overflow_style, GetScrollSnapType, SetScrollSnapType,
+ cc::ScrollSnapType());
+ PROPAGATE_FROM(overflow_style, ScrollPaddingTop, SetScrollPaddingTop,
+ Length());
+ PROPAGATE_FROM(overflow_style, ScrollPaddingRight, SetScrollPaddingRight,
+ Length());
+ PROPAGATE_FROM(overflow_style, ScrollPaddingBottom, SetScrollPaddingBottom,
+ Length());
+ PROPAGATE_FROM(overflow_style, ScrollPaddingLeft, SetScrollPaddingLeft,
+ Length());
+
+ PROPAGATE_FROM(overflow_style, OverscrollBehaviorX, SetOverscrollBehaviorX,
+ EOverscrollBehavior::kAuto);
+ PROPAGATE_FROM(overflow_style, OverscrollBehaviorY, SetOverscrollBehaviorY,
+ EOverscrollBehavior::kAuto);
+
+ // Counts any time scroll snapping and scroll padding break if we change its
+ // viewport propagation logic. Scroll snapping only breaks if body has
+ // non-none snap type that is different from the document one.
+ // TODO(952711): Remove once propagation logic change is complete.
+ if (document_element_style && body_style) {
+ bool snap_type_is_different =
+ !body_style->GetScrollSnapType().is_none &&
+ (body_style->GetScrollSnapType() !=
+ document_element_style->GetScrollSnapType());
+ bool scroll_padding_is_different =
+ body_style->ScrollPaddingTop() !=
+ document_element_style->ScrollPaddingTop() ||
+ body_style->ScrollPaddingBottom() !=
+ document_element_style->ScrollPaddingBottom() ||
+ body_style->ScrollPaddingLeft() !=
+ document_element_style->ScrollPaddingLeft() ||
+ body_style->ScrollPaddingRight() !=
+ document_element_style->ScrollPaddingRight();
+
+ if (snap_type_is_different) {
+ UseCounter::Count(*this, WebFeature::kScrollSnapOnViewportBreaks);
+ }
+ if (scroll_padding_is_different) {
+ UseCounter::Count(*this, WebFeature::kScrollPaddingOnViewportBreaks);
+ }
+ }
+
+ EOverflow overflow_x = EOverflow::kAuto;
+ EOverflow overflow_y = EOverflow::kAuto;
+ EOverflowAnchor overflow_anchor = EOverflowAnchor::kAuto;
+
+ if (overflow_style) {
+ overflow_x = overflow_style->OverflowX();
+ overflow_y = overflow_style->OverflowY();
+ overflow_anchor = overflow_style->OverflowAnchor();
+ // 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;
+
+ if (IsInMainFrame()) {
+ using OverscrollBehaviorType =
+ cc::OverscrollBehavior::OverscrollBehaviorType;
+ GetPage()->GetChromeClient().SetOverscrollBehavior(
+ *GetFrame(),
+ cc::OverscrollBehavior(static_cast<OverscrollBehaviorType>(
+ overflow_style->OverscrollBehaviorX()),
+ static_cast<OverscrollBehaviorType>(
+ overflow_style->OverscrollBehaviorY())));
+ }
+ }
+
+ PROPAGATE_VALUE(overflow_x, OverflowX, SetOverflowX)
+ PROPAGATE_VALUE(overflow_y, OverflowY, SetOverflowY)
+ PROPAGATE_VALUE(overflow_anchor, OverflowAnchor, SetOverflowAnchor);
+ }
+
+ // Misc
+ {
+ PROPAGATE_FROM(document_element_style, GetEffectiveTouchAction,
+ SetEffectiveTouchAction, TouchAction::kTouchActionAuto);
+ PROPAGATE_FROM(document_element_style, GetScrollBehavior, SetScrollBehavior,
+ kScrollBehaviorAuto);
+ PROPAGATE_FROM(document_element_style, DarkColorScheme, SetDarkColorScheme,
+ false);
+ }
+
+ if (changed) {
+ new_viewport_style->UpdateFontOrientation();
+ GetLayoutView()->SetStyle(new_viewport_style);
+ SetupFontBuilder(*new_viewport_style);
if (PaintLayerScrollableArea* scrollable_area =
GetLayoutView()->GetScrollableArea()) {
@@ -2132,15 +2550,18 @@ void Document::PropagateStyleToViewport() {
scrollable_area->VerticalScrollbar()->StyleChanged();
}
}
+
+#undef PROPAGATE_VALUE
+#undef PROPAGATE_FROM
}
#if DCHECK_IS_ON()
static void AssertLayoutTreeUpdated(Node& root) {
Node* node = &root;
while (node) {
- if (RuntimeEnabledFeatures::DisplayLockingEnabled() &&
- node->IsElementNode() &&
- ToElement(node)->StyleRecalcBlockedByDisplayLock(
+ auto* element = DynamicTo<Element>(node);
+ if (element && RuntimeEnabledFeatures::DisplayLockingEnabled() &&
+ element->StyleRecalcBlockedByDisplayLock(
DisplayLockContext::kChildren)) {
node = FlatTreeTraversal::NextSkippingChildren(*node);
continue;
@@ -2211,15 +2632,12 @@ void Document::UpdateStyleAndLayoutTree() {
return;
#if DCHECK_IS_ON()
- if (RuntimeEnabledFeatures::FastFlatTreeTraversalEnabled()) {
- int assigned_nodes_in_slot_count = 0;
- int nodes_which_have_assigned_slot_count = 0;
- FlatTreeTraversal::AssertFlatTreeNodeDataUpdated(
- *this, assigned_nodes_in_slot_count,
- nodes_which_have_assigned_slot_count);
- DCHECK_EQ(assigned_nodes_in_slot_count,
- nodes_which_have_assigned_slot_count);
- }
+ int assigned_nodes_in_slot_count = 0;
+ int nodes_which_have_assigned_slot_count = 0;
+ FlatTreeTraversal::AssertFlatTreeNodeDataUpdated(
+ *this, assigned_nodes_in_slot_count,
+ nodes_which_have_assigned_slot_count);
+ DCHECK_EQ(assigned_nodes_in_slot_count, nodes_which_have_assigned_slot_count);
#endif
// Entering here from inside layout, paint etc. would be catastrophic since
@@ -2453,9 +2871,10 @@ bool Document::NeedsLayoutTreeUpdateForNodeIncludingDisplayLocked(
(ancestor->NeedsAdjacentStyleRecalc() && !ignore_adjacent_style)) {
return true;
}
- if (!ancestor->IsElementNode())
+ auto* element = DynamicTo<Element>(ancestor);
+ if (!element)
continue;
- if (auto* context = ToElement(ancestor)->GetDisplayLockContext()) {
+ if (auto* context = element->GetDisplayLockContext()) {
// Even if the ancestor is style-clean, we might've previously
// blocked a style traversal going to the ancestor or its descendants.
if (context->StyleTraversalWasBlocked()) {
@@ -2541,8 +2960,20 @@ void Document::LayoutUpdated() {
// Plugins can run script inside layout which can detach the page.
// TODO(dcheng): Does it make sense to do any of this work if detached?
- if (GetFrame() && GetFrame()->IsMainFrame())
- GetFrame()->GetPage()->GetChromeClient().MainFrameLayoutUpdated();
+ if (GetFrame()) {
+ if (GetFrame()->IsMainFrame())
+ GetFrame()->GetPage()->GetChromeClient().MainFrameLayoutUpdated();
+
+ // We do attach here, during lifecycle update, because until then we
+ // don't have a good place that has access to its local root's FrameWidget.
+ // TODO(dcheng): If we create FrameWidget before Frame then we could move
+ // this to Document::Initialize().
+ if (Platform::Current()->IsThreadedAnimationEnabled() &&
+ GetSettings()->GetAcceleratedCompositingEnabled()) {
+ GetPage()->GetChromeClient().AttachCompositorAnimationTimeline(
+ Timeline().CompositorTimeline(), GetFrame());
+ }
+ }
Markers().InvalidateRectsForAllTextMatchMarkers();
@@ -2558,7 +2989,7 @@ void Document::LayoutUpdated() {
void Document::ClearFocusedElementSoon() {
if (!clear_focused_element_timer_.IsActive())
- clear_focused_element_timer_.StartOneShot(TimeDelta(), FROM_HERE);
+ clear_focused_element_timer_.StartOneShot(base::TimeDelta(), FROM_HERE);
}
void Document::ClearFocusedElementTimerFired(TimerBase*) {
@@ -2568,7 +2999,7 @@ void Document::ClearFocusedElementTimerFired(TimerBase*) {
focused_element_->blur();
}
-scoped_refptr<ComputedStyle> Document::StyleForPage(int page_index) {
+scoped_refptr<const ComputedStyle> Document::StyleForPage(int page_index) {
UpdateDistributionForUnknownReasons();
return EnsureStyleResolver().StyleForPage(page_index);
}
@@ -2614,7 +3045,7 @@ void Document::PageSizeAndMarginsInPixels(int page_index,
int& margin_right,
int& margin_bottom,
int& margin_left) {
- scoped_refptr<ComputedStyle> style = StyleForPage(page_index);
+ scoped_refptr<const ComputedStyle> style = StyleForPage(page_index);
double width = page_size.Width();
double height = page_size.Height();
@@ -2699,13 +3130,10 @@ void Document::Initialize() {
layout_view_ = new LayoutView(this);
SetLayoutObject(layout_view_);
- layout_view_->SetIsInWindow(true);
layout_view_->SetStyle(StyleResolver::StyleForViewport(*this));
- layout_view_->Compositor()->SetNeedsCompositingUpdate(
- kCompositingUpdateAfterCompositingInputChange);
AttachContext context;
- ContainerNode::AttachLayoutTree(context);
+ AttachLayoutTree(context);
// The TextAutosizer can't update layout view info while the Document is
// detached, so update now in case anything changed.
@@ -2722,26 +3150,16 @@ void Document::Initialize() {
// attached to a frame. Otherwise ContextLifecycleObserver::contextDestroyed
// wouldn't be fired.
network_state_observer_ = MakeGarbageCollected<NetworkStateObserver>(*this);
-
- if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) {
- CompositorAnimationTimeline* animation_timeline =
- Timeline().CompositorTimeline();
- if (animation_timeline) {
- GetPage()->GetChromeClient().AttachCompositorAnimationTimeline(
- animation_timeline, frame_.Get());
- }
- }
}
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())
return;
- GetViewportData().Shutdown();
+ // An active Document must have an associated frame.
+ CHECK(frame_);
// Frame navigation can cause a new Document to be attached. Don't allow that,
// since that will cause a situation where LocalFrame still has a Document
@@ -2752,12 +3170,26 @@ void Document::Shutdown() {
// Defer plugin dispose to avoid plugins trying to run script inside
// ScriptForbiddenScope, which will crash the renderer after
// https://crrev.com/200984
+ // TODO(dcheng): This is a temporary workaround, Document::Shutdown() should
+ // not be running script at all.
HTMLFrameOwnerElement::PluginDisposeSuspendScope suspend_plugin_dispose;
- // Don't allow script to run in the middle of detachLayoutTree() because a
+ // Don't allow script to run in the middle of DetachLayoutTree() because a
// detaching Document is not in a consistent state.
ScriptForbiddenScope forbid_script;
lifecycle_.AdvanceTo(DocumentLifecycle::kStopping);
+
+ // Do not add code before this without a documented reason. A postcondition of
+ // Shutdown() is that |frame_| must not have an attached Document. Allowing
+ // script execution when the Document is shutting down can make it easy to
+ // accidentally violate this condition, and the ordering of the scopers above
+ // is subtle due to legacy interactions with plugins.
+
+ if (num_canvases_ > 0)
+ UMA_HISTOGRAM_COUNTS_100("Blink.Canvas.NumCanvasesPerPage", num_canvases_);
+
+ GetViewportData().Shutdown();
+
View()->Dispose();
// TODO(crbug.com/729196): Trace why LocalFrameView::DetachFromLayout crashes.
CHECK(!View()->IsAttached());
@@ -2778,15 +3210,7 @@ void Document::Shutdown() {
markers_->PrepareForDestruction();
- if (GetPage()) {
- GetPage()->DocumentDetached(this);
- if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) {
- if (auto* compositor_timeline = Timeline().CompositorTimeline()) {
- GetPage()->GetChromeClient().DetachCompositorAnimationTimeline(
- compositor_timeline, frame_.Get());
- }
- }
- }
+ GetPage()->DocumentDetached(this);
probe::DocumentDetached(this);
@@ -2803,8 +3227,13 @@ void Document::Shutdown() {
CancelPendingJavaScriptUrls();
http_refresh_scheduler_->Cancel();
- if (layout_view_)
- layout_view_->SetIsInWindow(false);
+ if (Platform::Current()->IsThreadedAnimationEnabled() &&
+ GetSettings()->GetAcceleratedCompositingEnabled()) {
+ GetPage()->GetChromeClient().DetachCompositorAnimationTimeline(
+ Timeline().CompositorTimeline(), GetFrame());
+ }
+
+ layout_view_->CleanUpCompositor();
if (RegistrationContext())
RegistrationContext()->DocumentWasDetached();
@@ -2829,7 +3258,7 @@ void Document::Shutdown() {
computed_node_mapping_.clear();
layout_view_ = nullptr;
- ContainerNode::DetachLayoutTree();
+ DetachLayoutTree();
// TODO(crbug.com/729196): Trace why LocalFrameView::DetachFromLayout crashes.
CHECK(!View()->IsAttached());
@@ -2853,6 +3282,7 @@ void Document::Shutdown() {
DocumentShutdownNotifier::NotifyContextDestroyed();
SynchronousMutationNotifier::NotifyContextDestroyed();
+ cookie_jar_ = nullptr; // Not accessible after navigated away.
fetcher_->ClearContext();
// If this document is the master for an HTMLImportsController, sever that
// relationship. This ensures that we don't leave import loads in flight,
@@ -3098,12 +3528,17 @@ void Document::open(Document* entered_document,
if (entered_document && this != entered_document) {
auto* csp = MakeGarbageCollected<ContentSecurityPolicy>();
csp->CopyStateFrom(entered_document->GetContentSecurityPolicy());
+ // We inherit the sandbox flags of the entered document, so mask on
+ // the ones contained in the CSP.
+ sandbox_flags_ |= csp->GetSandboxMask();
InitContentSecurityPolicy(csp);
// Clear the hash fragment from the inherited URL to prevent a
// scroll-into-view for any document.open()'d frame.
KURL new_url = entered_document->Url();
new_url.SetFragmentIdentifier(String());
SetURL(new_url);
+ if (Loader())
+ Loader()->UpdateUrlForDocumentOpen(new_url);
SetSecurityOrigin(entered_document->GetMutableSecurityOrigin());
SetReferrerPolicy(entered_document->GetReferrerPolicy());
@@ -3329,7 +3764,7 @@ Element* Document::ViewportDefiningElement() const {
if (!root_element)
return nullptr;
const ComputedStyle* root_style = root_element->GetComputedStyle();
- if (!root_style)
+ if (!root_style || root_style->IsEnsuredInDisplayNone())
return nullptr;
if (body_element && root_style->IsOverflowVisible() &&
IsHTMLHtmlElement(*root_element))
@@ -3446,7 +3881,7 @@ void Document::ImplicitClose() {
}
if (GetFrame()->Loader().HasProvisionalNavigation() &&
- ElapsedTime() < kCLayoutScheduleThreshold) {
+ start_time_.Elapsed() < kCLayoutScheduleThreshold) {
// Just bail out. Before or during the onload we were shifted to another
// page. The old i-Bench suite does this. When this happens don't bother
// painting or laying out.
@@ -3505,7 +3940,7 @@ bool Document::ShouldComplete() {
!fetcher_->BlockingRequestCount() && !IsDelayingLoadEvent() &&
!javascript_url_task_handle_.IsActive() &&
load_event_progress_ != kLoadEventInProgress &&
- AllDescendantsAreComplete(this);
+ AllDescendantsAreComplete(this) && !Fetcher()->IsInRequestResource();
}
void Document::Abort() {
@@ -3602,9 +4037,9 @@ bool Document::DispatchBeforeUnloadEvent(ChromeClient* chrome_client,
auto& before_unload_event = *MakeGarbageCollected<BeforeUnloadEvent>();
before_unload_event.initEvent(event_type_names::kBeforeunload, false, true);
load_event_progress_ = kBeforeUnloadEventInProgress;
- const TimeTicks beforeunload_event_start = CurrentTimeTicks();
+ const base::TimeTicks beforeunload_event_start = base::TimeTicks::Now();
dom_window_->DispatchEvent(before_unload_event, this);
- const TimeTicks beforeunload_event_end = CurrentTimeTicks();
+ const base::TimeTicks beforeunload_event_end = base::TimeTicks::Now();
load_event_progress_ = kBeforeUnloadEventCompleted;
DEFINE_STATIC_LOCAL(
CustomCountHistogram, beforeunload_histogram,
@@ -3661,10 +4096,11 @@ bool Document::DispatchBeforeUnloadEvent(ChromeClient* chrome_client,
String text = before_unload_event.returnValue();
beforeunload_dialog_histogram.Count(
BeforeUnloadDialogHistogramEnum::kShowDialog);
- const TimeTicks beforeunload_confirmpanel_start = CurrentTimeTicks();
+ const base::TimeTicks beforeunload_confirmpanel_start =
+ base::TimeTicks::Now();
did_allow_navigation =
chrome_client->OpenBeforeUnloadConfirmPanel(text, frame_, is_reload);
- const TimeTicks beforeunload_confirmpanel_end = CurrentTimeTicks();
+ const base::TimeTicks beforeunload_confirmpanel_end = base::TimeTicks::Now();
if (did_allow_navigation) {
// Only record when a navigation occurs, since we want to understand
// the impact of the before unload dialog on overall input to navigation.
@@ -3692,11 +4128,11 @@ void Document::DispatchUnloadEvents(DocumentLoadTiming* timing) {
if (load_event_progress_ < kPageHideInProgress) {
load_event_progress_ = kPageHideInProgress;
if (LocalDOMWindow* window = domWindow()) {
- const TimeTicks pagehide_event_start = CurrentTimeTicks();
+ const base::TimeTicks pagehide_event_start = base::TimeTicks::Now();
window->DispatchEvent(
*PageTransitionEvent::Create(event_type_names::kPagehide, false),
this);
- const TimeTicks pagehide_event_end = CurrentTimeTicks();
+ const base::TimeTicks pagehide_event_end = base::TimeTicks::Now();
DEFINE_STATIC_LOCAL(
CustomCountHistogram, pagehide_histogram,
("DocumentEventTiming.PageHideDuration", 0, 10000000, 50));
@@ -3713,10 +4149,12 @@ void Document::DispatchUnloadEvents(DocumentLoadTiming* timing) {
if (page_visible) {
// Dispatch visibilitychange event, but don't bother doing
// other notifications as we're about to be unloaded.
- const TimeTicks pagevisibility_hidden_event_start = CurrentTimeTicks();
+ const base::TimeTicks pagevisibility_hidden_event_start =
+ base::TimeTicks::Now();
DispatchEvent(
*Event::CreateBubble(event_type_names::kVisibilitychange));
- const TimeTicks pagevisibility_hidden_event_end = CurrentTimeTicks();
+ const base::TimeTicks pagevisibility_hidden_event_end =
+ base::TimeTicks::Now();
DEFINE_STATIC_LOCAL(CustomCountHistogram, pagevisibility_histogram,
("DocumentEventTiming.PageVibilityHiddenDuration",
0, 10000000, 50));
@@ -3736,10 +4174,10 @@ void Document::DispatchUnloadEvents(DocumentLoadTiming* timing) {
if (timing && timing->UnloadEventStart().is_null() &&
timing->UnloadEventEnd().is_null()) {
DCHECK(!timing->NavigationStart().is_null());
- const TimeTicks unload_event_start = CurrentTimeTicks();
+ const base::TimeTicks unload_event_start = base::TimeTicks::Now();
timing->MarkUnloadEventStart(unload_event_start);
frame_->DomWindow()->DispatchEvent(unload_event, this);
- const TimeTicks unload_event_end = CurrentTimeTicks();
+ const base::TimeTicks unload_event_end = base::TimeTicks::Now();
DEFINE_STATIC_LOCAL(
CustomCountHistogram, unload_histogram,
("DocumentEventTiming.UnloadDuration", 0, 10000000, 50));
@@ -3755,11 +4193,11 @@ void Document::DispatchUnloadEvents(DocumentLoadTiming* timing) {
}
void Document::DispatchFreezeEvent() {
- const TimeTicks freeze_event_start = CurrentTimeTicks();
+ const base::TimeTicks freeze_event_start = base::TimeTicks::Now();
SetFreezingInProgress(true);
DispatchEvent(*Event::Create(event_type_names::kFreeze));
SetFreezingInProgress(false);
- const TimeTicks freeze_event_end = CurrentTimeTicks();
+ const base::TimeTicks freeze_event_end = base::TimeTicks::Now();
DEFINE_STATIC_LOCAL(CustomCountHistogram, freeze_histogram,
("DocumentEventTiming.FreezeDuration", 0, 10000000, 50));
freeze_histogram.CountMicroseconds(freeze_event_end - freeze_event_start);
@@ -3814,10 +4252,6 @@ bool Document::ShouldScheduleLayout() const {
return false;
}
-int Document::ElapsedTime() const {
- return static_cast<int>((CurrentTime() - start_time_) * 1000);
-}
-
void Document::write(const String& text,
Document* entered_document,
ExceptionState& exception_state) {
@@ -4146,23 +4580,23 @@ void Document::DidLoadAllImports() {
DidLoadAllScriptBlockingResources();
}
-void Document::DidAddPendingStylesheetInBody() {
+void Document::DidAddPendingParserBlockingStylesheet() {
if (ScriptableDocumentParser* parser = GetScriptableDocumentParser())
- parser->DidAddPendingStylesheetInBody();
+ parser->DidAddPendingParserBlockingStylesheet();
}
-void Document::DidRemoveAllPendingStylesheet() {
+void Document::DidRemoveAllPendingStylesheets() {
// Only imports on master documents can trigger rendering.
if (HTMLImportLoader* import = ImportLoader())
- import->DidRemoveAllPendingStylesheet();
+ import->DidRemoveAllPendingStylesheets();
if (!HaveImportsLoaded())
return;
DidLoadAllScriptBlockingResources();
}
-void Document::DidRemoveAllPendingBodyStylesheets() {
+void Document::DidLoadAllPendingParserBlockingStylesheets() {
if (ScriptableDocumentParser* parser = GetScriptableDocumentParser())
- parser->DidLoadAllBodyStylesheets();
+ parser->DidLoadAllPendingParserBlockingStylesheets();
}
void Document::DidLoadAllScriptBlockingResources() {
@@ -4287,7 +4721,7 @@ network::mojom::ReferrerPolicy Document::GetReferrerPolicy() const {
MouseEventWithHitTestResults Document::PerformMouseEventHitTest(
const HitTestRequest& request,
- const LayoutPoint& document_point,
+ const PhysicalOffset& document_point,
const WebMouseEvent& event) {
DCHECK(!GetLayoutView() || GetLayoutView()->IsLayoutView());
@@ -4298,7 +4732,7 @@ MouseEventWithHitTestResults Document::PerformMouseEventHitTest(
// lead to a premature layout() happening, which could show a flash of white.
// See also the similar code in EventHandler::hitTestResultAtPoint.
if (!GetLayoutView() || !View() || !View()->DidFirstLayout()) {
- HitTestLocation location((LayoutPoint()));
+ HitTestLocation location((PhysicalOffset()));
return MouseEventWithHitTestResults(event, location,
HitTestResult(request, location));
}
@@ -4507,9 +4941,11 @@ Node* Document::Clone(Document& factory, CloneChildrenFlag flag) const {
}
Document* Document::CloneDocumentWithoutChildren() const {
- DocumentInit init = DocumentInit::Create()
- .WithContextDocument(ContextDocument())
- .WithURL(Url());
+ DocumentInit init =
+ DocumentInit::Create()
+ .WithContextDocument(ContextDocument())
+ .WithURL(Url())
+ .WithOriginToCommit(GetSecurityOrigin()->IsolatedCopy());
if (IsXMLDocument()) {
if (IsXHTMLDocument())
return XMLDocument::CreateXHTML(
@@ -4523,7 +4959,6 @@ void Document::CloneDataFromDocument(const Document& other) {
SetCompatibilityMode(other.GetCompatibilityMode());
SetEncodingData(other.encoding_data_);
SetContextFeatures(other.GetContextFeatures());
- SetSecurityOrigin(other.GetSecurityOrigin()->IsolatedCopy());
SetMimeType(other.contentType());
}
@@ -4847,8 +5282,8 @@ Element* Document::SequentialFocusNavigationStartingPoint(
Node* node = sequential_focus_navigation_starting_point_->startContainer();
DCHECK_EQ(node,
sequential_focus_navigation_starting_point_->endContainer());
- if (node->IsElementNode())
- return ToElement(node);
+ if (auto* element = DynamicTo<Element>(node))
+ return element;
if (Element* neighbor_element = type == kWebFocusTypeForward
? ElementTraversal::Previous(*node)
: ElementTraversal::Next(*node))
@@ -4858,13 +5293,11 @@ Element* Document::SequentialFocusNavigationStartingPoint(
// Range::selectNodeContents didn't select contents because the element had
// no children.
- if (sequential_focus_navigation_starting_point_->startContainer()
- ->IsElementNode() &&
- !sequential_focus_navigation_starting_point_->startContainer()
- ->hasChildren() &&
+ auto* element = DynamicTo<Element>(
+ sequential_focus_navigation_starting_point_->startContainer());
+ if (element && !element->hasChildren() &&
sequential_focus_navigation_starting_point_->startOffset() == 0)
- return ToElement(
- sequential_focus_navigation_starting_point_->startContainer());
+ return element;
// A node selected by Range::selectNodeContents was removed from the
// document tree.
@@ -4876,19 +5309,16 @@ Element* Document::SequentialFocusNavigationStartingPoint(
// 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);
+ Node* previous = FlatTreeTraversal::Previous(*next_node);
+ for (; previous; previous = FlatTreeTraversal::Previous(*previous)) {
+ if (auto* element = DynamicTo<Element>(previous))
+ return element;
+ }
+ }
+ for (Node* next = next_node; next; next = FlatTreeTraversal::Next(*next)) {
+ if (auto* element = DynamicTo<Element>(next))
+ return element;
}
- if (next_node->IsElementNode())
- return ToElement(next_node);
- Node* next = next_node;
- do {
- next = FlatTreeTraversal::Next(*next);
- } while (next && !next->IsElementNode());
- return ToElement(next);
}
return nullptr;
}
@@ -5267,6 +5697,7 @@ void Document::WillChangeFrameOwnerProperties(int margin_width,
}
}
if (scrolling_mode != owner->ScrollingMode() && View()) {
+ View()->SetCanHaveScrollbars(scrolling_mode != kScrollbarAlwaysOff);
View()->SetNeedsLayout();
}
}
@@ -5277,10 +5708,6 @@ String Document::cookie(ExceptionState& exception_state) const {
CountUse(WebFeature::kCookieGet);
- // FIXME: The HTML5 DOM spec states that this attribute can raise an
- // InvalidStateError exception on getting if the Document has no
- // browsing context.
-
if (!GetSecurityOrigin()->CanAccessCookies()) {
if (IsSandboxed(WebSandboxFlags::kOrigin))
exception_state.ThrowSecurityError(
@@ -5295,11 +5722,10 @@ String Document::cookie(ExceptionState& exception_state) const {
CountUse(WebFeature::kFileAccessedCookies);
}
- KURL cookie_url = CookieURL();
- if (cookie_url.IsEmpty())
+ if (!cookie_jar_)
return String();
- return Cookies(this, cookie_url);
+ return cookie_jar_->Cookies();
}
void Document::setCookie(const String& value, ExceptionState& exception_state) {
@@ -5308,10 +5734,6 @@ void Document::setCookie(const String& value, ExceptionState& exception_state) {
UseCounter::Count(*this, WebFeature::kCookieSet);
- // FIXME: The HTML5 DOM spec states that this attribute can raise an
- // InvalidStateError exception on setting if the Document has no
- // browsing context.
-
if (!GetSecurityOrigin()->CanAccessCookies()) {
if (IsSandboxed(WebSandboxFlags::kOrigin))
exception_state.ThrowSecurityError(
@@ -5326,11 +5748,21 @@ void Document::setCookie(const String& value, ExceptionState& exception_state) {
UseCounter::Count(*this, WebFeature::kFileAccessedCookies);
}
- KURL cookie_url = CookieURL();
- if (cookie_url.IsEmpty())
+ if (!cookie_jar_)
return;
- SetCookies(this, cookie_url, value);
+ cookie_jar_->SetCookie(value);
+}
+
+bool Document::CookiesEnabled() const {
+ // Compatible behavior in contexts that don't have cookie access.
+ if (!GetSecurityOrigin()->CanAccessCookies())
+ return true;
+
+ if (!cookie_jar_)
+ return false;
+
+ return cookie_jar_->CookiesEnabled();
}
const AtomicString& Document::referrer() const {
@@ -5445,9 +5877,10 @@ String Document::lastModified() const {
// FIXME: If this document came from the file system, the HTML5
// specificiation tells us to read the last modification date from the file
// system.
- if (!found_date)
+ if (!found_date) {
date.SetMillisecondsSinceEpochForDateTime(
- ConvertToLocalTime(CurrentTimeMS()));
+ ConvertToLocalTime(base::Time::Now().ToDoubleT() * 1000.0));
+ }
return String::Format("%02d/%02d/%04d %02d:%02d:%02d", date.Month() + 1,
date.MonthDay(), date.FullYear(), date.Hour(),
date.Minute(), date.Second());
@@ -6009,48 +6442,23 @@ namespace {
using resource_coordinator::mojom::InterventionPolicy;
using resource_coordinator::mojom::PolicyControlledIntervention;
-typedef bool (*InterventionPolicyGetter)(const FeatureContext*);
-struct InterventionPolicyGetters {
- InterventionPolicyGetter opt_in_getter;
- InterventionPolicyGetter opt_out_getter;
-};
-
-// A helper function for setting intervention policy values on a frame en masse.
+// A helper function for setting intervention policy values on a frame.
void SetInitialInterventionPolicies(
DocumentResourceCoordinator* document_resource_coordinator,
- const ExecutionContext* context) {
- DEFINE_STATIC_LOCAL(Vector<InterventionPolicyGetters>,
- kInterventionPolicyGetters, ());
- if (kInterventionPolicyGetters.IsEmpty()) {
- InterventionPolicyGetters getters = {
- &RuntimeEnabledFeatures::PageLifecycleTransitionsOptInEnabled,
- &RuntimeEnabledFeatures::PageLifecycleTransitionsOptOutEnabled};
- kInterventionPolicyGetters.push_back(getters);
- const wtf_size_t kInterventionPolicyGettersSize = 1;
- static_assert(
- kInterventionPolicyGettersSize ==
- static_cast<wtf_size_t>(PolicyControlledIntervention::kMaxValue) +
- 1,
- "kInterventionPolicyGetters array must be kept in sync with "
- "mojom::PolicyControlledIntervention enum.");
- }
- // Note that these must be emitted in order, as the *last* policy being set
- // is used as a sentinel in the browser-side logic to infer that the frame has
- // transmitted all of its policy data.
- for (wtf_size_t i = 0; i < kInterventionPolicyGetters.size(); ++i) {
- bool opt_in = (*kInterventionPolicyGetters[i].opt_in_getter)(context);
- bool opt_out = (*kInterventionPolicyGetters[i].opt_out_getter)(context);
-
- // An explicit opt-out overrides an explicit opt-in if both are present.
- InterventionPolicy policy = InterventionPolicy::kDefault;
- if (opt_out)
- policy = InterventionPolicy::kOptOut;
- else if (opt_in)
- policy = InterventionPolicy::kOptIn;
-
- document_resource_coordinator->SetInterventionPolicy(
- static_cast<PolicyControlledIntervention>(i), policy);
+ ExecutionContext* context) {
+ // An explicit opt-out overrides an explicit opt-in if both are present.
+ InterventionPolicy policy = InterventionPolicy::kDefault;
+ if (RuntimeEnabledFeatures::PageLifecycleTransitionsOptOutEnabled(context)) {
+ policy = InterventionPolicy::kOptOut;
+ UseCounter::Count(context, WebFeature::kPageLifecycleTransitionsOptOut);
+ } else if (RuntimeEnabledFeatures::PageLifecycleTransitionsOptInEnabled(
+ context)) {
+ policy = InterventionPolicy::kOptIn;
+ UseCounter::Count(context, WebFeature::kPageLifecycleTransitionsOptIn);
}
+
+ document_resource_coordinator->SetInterventionPolicy(
+ PolicyControlledIntervention::kPageLifecycleTransitions, policy);
}
} // namespace
@@ -6126,7 +6534,7 @@ void Document::FinishedParsing() {
// on cache access since that could lead to huge caches being kept alive
// indefinitely by something innocuous like JS setting .innerHTML repeatedly
// on a timer.
- element_data_cache_clear_timer_.StartOneShot(TimeDelta::FromSeconds(10),
+ element_data_cache_clear_timer_.StartOneShot(base::TimeDelta::FromSeconds(10),
FROM_HERE);
// Parser should have picked up all preloads by now
@@ -6274,32 +6682,33 @@ HTMLLinkElement* Document::LinkCanonical() const {
});
}
-void Document::ApplyFeaturePolicyFromHeader(
- const String& feature_policy_header) {
- if (!feature_policy_header.IsEmpty())
+void Document::FeaturePolicyInitialized(
+ const DocumentInit& document_initializer,
+ const SecurityContextInit& security_initializer) {
+ // Processing of the feature policy header is done before the SecurityContext
+ // is initialized. This method just records the usage.
+ if (!document_initializer.FeaturePolicyHeader().IsEmpty())
UseCounter::Count(*this, WebFeature::kFeaturePolicyHeader);
- Vector<String> messages;
- auto declared_policy = FeaturePolicyParser::ParseHeader(
- feature_policy_header, GetSecurityOrigin(), &messages, this);
- for (auto& message : messages) {
+ for (const auto& message :
+ security_initializer.FeaturePolicyParseMessages()) {
AddConsoleMessage(
ConsoleMessage::Create(mojom::ConsoleMessageSource::kSecurity,
mojom::ConsoleMessageLevel::kError,
"Error with Feature-Policy header: " + message));
}
- if (GetSandboxFlags() != WebSandboxFlags::kNone &&
- RuntimeEnabledFeatures::FeaturePolicyForSandboxEnabled()) {
- // The sandbox flags might have come from CSP header or the browser; in such
- // cases the sandbox is not part of the container policy. They are added
- // to the header policy (which specifically makes sense in the case of CSP
- // sandbox).
- ApplySandboxFlagsToParsedFeaturePolicy(GetSandboxFlags(), declared_policy);
- }
- ApplyFeaturePolicy(declared_policy);
if (frame_) {
- frame_->Client()->DidSetFramePolicyHeaders(GetSandboxFlags(),
- declared_policy);
+ pending_parsed_headers_ = security_initializer.ParsedHeader();
}
+
+ // At this point, the document will not have been installed in the frame's
+ // LocalDOMWindow, so we cannot call frame_->IsFeatureEnabled. This calls
+ // SecurityContext::IsFeatureEnabled instead, which cannot report, but we
+ // don't need reporting here in any case.
+ is_vertical_scroll_enforced_ =
+ frame_ && !frame_->IsMainFrame() &&
+ RuntimeEnabledFeatures::ExperimentalProductivityFeaturesEnabled() &&
+ !GetFeaturePolicy()->IsFeatureEnabled(
+ mojom::FeaturePolicyFeature::kVerticalScroll);
}
const ParsedFeaturePolicy Document::GetOwnerContainerPolicy() const {
@@ -6318,36 +6727,12 @@ const FeaturePolicy* Document::GetParentFeaturePolicy() const {
return nullptr;
}
-void Document::ApplyFeaturePolicy(const ParsedFeaturePolicy& declared_policy) {
- // For a main frame, get inherited feature policy from the opener if any.
- const FeaturePolicy::FeatureState* opener_feature_state = nullptr;
- if (frame_ && frame_->IsMainFrame() &&
- !frame_->OpenerFeatureState().empty()) {
- opener_feature_state = &frame_->OpenerFeatureState();
- }
-
- auto container_policy = GetOwnerContainerPolicy();
- if (RuntimeEnabledFeatures::BlockingFocusWithoutUserActivationEnabled() &&
- frame_ && frame_->Tree().Parent() &&
- IsSandboxed(WebSandboxFlags::kNavigation)) {
- // Enforcing the policy for sandbox frames (for context see
- // https://crbug.com/954349).
- DisallowFeatureIfNotPresent(
- mojom::FeaturePolicyFeature::kFocusWithoutUserActivation,
- container_policy);
+void Document::ApplyPendingFeaturePolicyHeaders() {
+ if (frame_) {
+ frame_->Client()->DidSetFramePolicyHeaders(GetSandboxFlags(),
+ pending_parsed_headers_);
}
- InitializeFeaturePolicy(declared_policy, container_policy,
- GetParentFeaturePolicy(), opener_feature_state);
-
- // At this point, the document will not have been installed in the frame's
- // LocalDOMWindow, so we cannot call frame_->IsFeatureEnabled. This calls
- // SecurityContext::IsFeatureEnabled instead, which cannot report, but we
- // don't need reporting here in any case.
- is_vertical_scroll_enforced_ =
- frame_ && !frame_->IsMainFrame() &&
- RuntimeEnabledFeatures::ExperimentalProductivityFeaturesEnabled() &&
- !GetFeaturePolicy()->IsFeatureEnabled(
- mojom::FeaturePolicyFeature::kVerticalScroll);
+ pending_parsed_headers_.clear();
}
void Document::ApplyReportOnlyFeaturePolicyFromHeader(
@@ -6427,87 +6812,45 @@ ukm::SourceId Document::UkmSourceID() const {
return ukm_source_id_;
}
-void Document::InitSecurityContext(const DocumentInit& initializer) {
- DCHECK(!GetSecurityOrigin());
+void Document::InitContentSecurityPolicy(ContentSecurityPolicy* csp) {
+ SetContentSecurityPolicy(csp);
+ GetContentSecurityPolicy()->BindToDelegate(
+ GetContentSecurityPolicyDelegate());
+}
+void Document::InitSecurityContext(
+ const DocumentInit& initializer,
+ const SecurityContextInit& security_initializer) {
+ DCHECK(GetSecurityOrigin());
+
+ // If the CSP was provided by the DocumentLoader or is from ImportsController
+ // it doesn't need to be bound right now. ImportsController takes a reference
+ // to a master document's CSP which is already bound. Document construction
+ // occurs in the DocumentLoader occurs before the frame reference is bound so
+ // callbacks from binding the CSP delegate immediately would not get called
+ // if it was bound immediately. eg. Callbacks back to browser or console
+ // logging.
+ if (security_initializer.BindCSPImmediately()) {
+ InitContentSecurityPolicy(security_initializer.GetCSP());
+ } else {
+ SetContentSecurityPolicy(security_initializer.GetCSP());
+ }
if (!initializer.HasSecurityContext()) {
// No source for a security context.
// This can occur via document.implementation.createDocument().
cookie_url_ = KURL(g_empty_string);
- SetSecurityOrigin(SecurityOrigin::CreateUniqueOpaque());
- InitContentSecurityPolicy();
- ApplyFeaturePolicy({});
- return;
- }
-
- SandboxFlags sandbox_flags = initializer.GetSandboxFlags();
- if (fetcher_->Archive()) {
- // The URL of a Document loaded from a MHTML archive is controlled by the
- // Content-Location header. This would allow UXSS, since Content-Location
- // can be arbitrarily controlled to control the Document's URL and origin.
- // Instead, force a Document loaded from a MHTML archive to be sandboxed,
- // providing exceptions only for creating new windows.
- sandbox_flags |=
- (WebSandboxFlags::kAll &
- ~(WebSandboxFlags::kPopups |
- WebSandboxFlags::kPropagatesToAuxiliaryBrowsingContexts));
- }
- // In the common case, create the security context from the currently
- // loading URL with a fresh content security policy.
- EnforceSandboxFlags(sandbox_flags);
+ return;
+ }
SetInsecureRequestPolicy(initializer.GetInsecureRequestPolicy());
if (initializer.InsecureNavigationsToUpgrade()) {
for (auto to_upgrade : *initializer.InsecureNavigationsToUpgrade())
AddInsecureNavigationUpgrade(to_upgrade);
}
- ContentSecurityPolicy* last_origin_document_csp_ =
- frame_ ? frame_->Loader().GetLastOriginDocumentCSP() : nullptr;
-
- scoped_refptr<SecurityOrigin> document_origin =
- initializer.GetDocumentOrigin();
cookie_url_ = url_;
if (!initializer.OriginToCommit() && initializer.OwnerDocument()) {
- // Alias certain security properties from |owner_document|. Used for
- // the case of about:blank pages inheriting the security properties of
- // their requestor context.
- // Note that this is currently somewhat broken; Blink always inherits
- // from the parent or opener, even though it should actually be
- // inherited from the request initiator.
cookie_url_ = initializer.OwnerDocument()->CookieURL();
- if (url_.IsEmpty()) {
- last_origin_document_csp_ =
- initializer.OwnerDocument()->GetContentSecurityPolicy();
- }
- }
-
- if (IsSandboxed(WebSandboxFlags::kOrigin)) {
- DCHECK(!initializer.ContextDocument());
- scoped_refptr<SecurityOrigin> sandboxed_origin =
- initializer.OriginToCommit() ? initializer.OriginToCommit()
- : document_origin->DeriveNewOpaqueOrigin();
-
- // If we're supposed to inherit our security origin from our
- // owner, but we're also sandboxed, the only things we inherit are
- // the origin's potential trustworthiness and the ability to
- // load local resources. The latter lets about:blank iframes in
- // file:// URL documents load images and other resources from
- // the file system.
- if (initializer.OwnerDocument()) {
- if (document_origin->IsPotentiallyTrustworthy())
- sandboxed_origin->SetOpaqueOriginIsPotentiallyTrustworthy(true);
- if (document_origin->CanLoadLocalResources())
- sandboxed_origin->GrantLoadLocalResources();
- if (url_.IsEmpty()) {
- last_origin_document_csp_ =
- initializer.OwnerDocument()->GetContentSecurityPolicy();
- }
- }
- cookie_url_ = url_;
- SetSecurityOrigin(std::move(sandboxed_origin));
- } else {
- SetSecurityOrigin(std::move(document_origin));
}
// Set the address space before setting up CSP, as the latter may override
@@ -6527,18 +6870,6 @@ void Document::InitSecurityContext(const DocumentInit& initializer) {
SetAddressSpace(mojom::IPAddressSpace::kPublic);
}
- if (ImportsController()) {
- // If this document is an HTML import, grab a reference to it's master
- // document's Content Security Policy. We don't call
- // 'initContentSecurityPolicy' in this case, as we can't rebind the master
- // document's policy object: its ExecutionContext needs to remain tied to
- // the master document.
- SetContentSecurityPolicy(
- ImportsController()->Master()->GetContentSecurityPolicy());
- } else {
- InitContentSecurityPolicy(nullptr, last_origin_document_csp_);
- }
-
if (Settings* settings = initializer.GetSettings()) {
if (!settings->GetWebSecurityEnabled()) {
// Web security is turned off. We should let this document access every
@@ -6562,19 +6893,23 @@ void Document::InitSecurityContext(const DocumentInit& initializer) {
SecurityOrigin::Create(url_)->IsPotentiallyTrustworthy())
GetMutableSecurityOrigin()->SetOpaqueOriginIsPotentiallyTrustworthy(true);
- ParsedFeaturePolicy declared_policy = {};
- if (GetSandboxFlags() != WebSandboxFlags::kNone &&
- RuntimeEnabledFeatures::FeaturePolicyForSandboxEnabled()) {
- // If any sandbox flags are enforced above they should also be added as
- // part of a declared policy to properly initialize the sandbox feature
- // policies.
- ApplySandboxFlagsToParsedFeaturePolicy(GetSandboxFlags(), declared_policy);
- }
- ApplyFeaturePolicy(declared_policy);
-
InitSecureContextState();
}
+void Document::SetSecurityOrigin(scoped_refptr<SecurityOrigin> origin) {
+ // Enforce that we don't change access, we might change the reference (via
+ // IsolatedCopy but we can't change the security policy).
+ CHECK(origin);
+ CHECK(GetSecurityOrigin()->CanAccess(origin.get()));
+ SecurityContext::SetSecurityOrigin(origin);
+}
+
+void Document::BindContentSecurityPolicy() {
+ DCHECK(!GetContentSecurityPolicy()->IsBound());
+ GetContentSecurityPolicy()->BindToDelegate(
+ GetContentSecurityPolicyDelegate());
+}
+
void Document::InitSecureContextState() {
DCHECK_EQ(secure_context_state_, SecureContextState::kUnknown);
if (!GetSecurityOrigin()->IsPotentiallyTrustworthy()) {
@@ -6601,47 +6936,6 @@ void Document::InitSecureContextState() {
DCHECK_NE(secure_context_state_, SecureContextState::kUnknown);
}
-// the first parameter specifies a policy to use as the document csp meaning
-// the document will take ownership of the policy
-// the second parameter specifies a policy to inherit meaning the document
-// will attempt to copy over the policy
-void Document::InitContentSecurityPolicy(
- ContentSecurityPolicy* csp,
- const ContentSecurityPolicy* last_origin_document_csp) {
- SetContentSecurityPolicy(csp ? csp
- : MakeGarbageCollected<ContentSecurityPolicy>());
-
- GetContentSecurityPolicy()->BindToDelegate(
- GetContentSecurityPolicyDelegate());
-
- // We should inherit the navigation initiator CSP if the document is loaded
- // using a local-scheme url.
- if (last_origin_document_csp &&
- (url_.IsEmpty() || url_.ProtocolIsAbout() || url_.ProtocolIsData() ||
- url_.ProtocolIs("blob") || url_.ProtocolIs("filesystem"))) {
- GetContentSecurityPolicy()->CopyStateFrom(last_origin_document_csp);
- }
-
- if (IsPluginDocument()) {
- // TODO(andypaicu): This should inherit the origin document's plugin types
- // but because this could be a OOPIF document it might not have access.
- // In this situation we fallback on using the parent/opener.
- if (last_origin_document_csp) {
- GetContentSecurityPolicy()->CopyPluginTypesFrom(last_origin_document_csp);
- } else if (frame_) {
- Frame* inherit_from = frame_->Tree().Parent()
- ? frame_->Tree().Parent()
- : frame_->Client()->Opener();
- if (inherit_from && frame_ != inherit_from) {
- DCHECK(inherit_from->GetSecurityContext() &&
- inherit_from->GetSecurityContext()->GetContentSecurityPolicy());
- GetContentSecurityPolicy()->CopyPluginTypesFrom(
- inherit_from->GetSecurityContext()->GetContentSecurityPolicy());
- }
- }
- }
-}
-
bool Document::CanExecuteScripts(ReasonForCallingCanExecuteScripts reason) {
DCHECK(GetFrame())
<< "you are querying canExecuteScripts on a non contextDocument.";
@@ -6685,7 +6979,7 @@ bool Document::AllowInlineEventHandler(Node* node,
EventListener* listener,
const String& context_url,
const WTF::OrdinalNumber& context_line) {
- Element* element = node && node->IsElementNode() ? ToElement(node) : nullptr;
+ auto* element = DynamicTo<Element>(node);
// https://html.spec.whatwg.org/multipage/webappapis.html#event-handler-content-attributes
// Step 5.1. If the Should element's inline behavior be blocked by Content
@@ -6716,24 +7010,6 @@ bool Document::AllowInlineEventHandler(Node* node,
return true;
}
-void Document::EnforceSandboxFlags(SandboxFlags mask) {
- scoped_refptr<const SecurityOrigin> stand_in_origin = GetSecurityOrigin();
- bool is_potentially_trustworthy =
- stand_in_origin && stand_in_origin->IsPotentiallyTrustworthy();
- ApplySandboxFlags(mask, is_potentially_trustworthy);
-}
-
-void Document::UpdateSecurityOrigin(scoped_refptr<SecurityOrigin> origin) {
- SetSecurityOrigin(std::move(origin));
- DidUpdateSecurityOrigin();
-}
-
-void Document::DidUpdateSecurityOrigin() {
- if (!frame_)
- return;
- frame_->GetScriptController().UpdateSecurityOrigin(GetSecurityOrigin());
-}
-
bool Document::IsContextThread() const {
return IsMainThread();
}
@@ -6885,7 +7161,7 @@ void Document::TasksWereUnpaused() {
if (scripted_animation_controller_)
scripted_animation_controller_->Unpause();
- MutationObserver::ResumeSuspendedObservers();
+ GetWindowAgent().GetMutationObserverNotifier().ResumeSuspendedObservers();
if (dom_window_)
DOMWindowPerformance::performance(*dom_window_)->ResumeSuspendedObservers();
}
@@ -6967,7 +7243,7 @@ void Document::DecrementLoadEventDelayCountAndCheckLoadEvent() {
void Document::CheckLoadEventSoon() {
if (GetFrame() && !load_event_delay_timer_.IsActive())
- load_event_delay_timer_.StartOneShot(TimeDelta(), FROM_HERE);
+ load_event_delay_timer_.StartOneShot(base::TimeDelta(), FROM_HERE);
}
bool Document::IsDelayingLoadEvent() {
@@ -6991,7 +7267,7 @@ void Document::LoadPluginsSoon() {
// FIXME: Remove this timer once we don't need to compute layout to load
// plugins.
if (!plugin_loading_timer_.IsActive())
- plugin_loading_timer_.StartOneShot(TimeDelta(), FROM_HERE);
+ plugin_loading_timer_.StartOneShot(base::TimeDelta(), FROM_HERE);
}
void Document::PluginLoadingTimerFired(TimerBase*) {
@@ -7025,11 +7301,11 @@ void Document::ServiceScriptedAnimations(
base::TimeTicks monotonic_animation_start_time) {
if (!scripted_animation_controller_)
return;
- auto start_time = CurrentTimeTicks();
+ auto start_time = base::TimeTicks::Now();
scripted_animation_controller_->ServiceScriptedAnimations(
monotonic_animation_start_time);
if (GetFrame()) {
- GetFrame()->GetFrameScheduler()->AddTaskTime(CurrentTimeTicks() -
+ GetFrame()->GetFrameScheduler()->AddTaskTime(base::TimeTicks::Now() -
start_time);
}
}
@@ -7083,6 +7359,8 @@ DocumentLoader* Document::Loader() const {
if (!frame_)
return nullptr;
+ // TODO(dcheng): remove this check. frame_ is guaranteed to be non-null only
+ // if frame_->GetDocument() == this.
if (frame_->GetDocument() != this)
return nullptr;
@@ -7235,8 +7513,8 @@ void Document::UpdateHoverState(Element* inner_element_in_document) {
new_hover_element) {
Node* ancestor = FlatTreeTraversal::CommonAncestor(*old_hover_element,
*new_hover_element);
- if (ancestor && ancestor->IsElementNode())
- ancestor_element = ToElement(ancestor);
+ if (auto* element = DynamicTo<Element>(ancestor))
+ ancestor_element = element;
}
HeapVector<Member<Element>, 32> elements_to_remove_from_chain;
@@ -7298,6 +7576,11 @@ AnimationClock& Document::GetAnimationClock() {
return GetPage()->Animator().Clock();
}
+const AnimationClock& Document::GetAnimationClock() const {
+ DCHECK(GetPage());
+ return GetPage()->Animator().Clock();
+}
+
Document& Document::EnsureTemplateDocument() {
if (IsTemplateDocument())
return *this;
@@ -7328,7 +7611,7 @@ void Document::DidAssociateFormControl(Element* element) {
// We add a slight delay because this could be called rapidly.
if (!did_associate_form_controls_timer_.IsActive()) {
did_associate_form_controls_timer_.StartOneShot(
- TimeDelta::FromMilliseconds(300), FROM_HERE);
+ base::TimeDelta::FromMilliseconds(300), FROM_HERE);
}
}
@@ -7351,6 +7634,29 @@ TextAutosizer* Document::GetTextAutosizer() {
return text_autosizer_.Get();
}
+bool Document::SetPseudoStateForTesting(Element& element,
+ const String& pseudo,
+ bool matches) {
+ DCHECK(WebTestSupport::IsRunningWebTest());
+ auto& set = UserActionElements();
+ if (pseudo == ":focus") {
+ set.SetFocused(&element, matches);
+ element.PseudoStateChanged(CSSSelector::kPseudoFocus);
+ } else if (pseudo == ":focus-within") {
+ set.SetHasFocusWithin(&element, matches);
+ element.PseudoStateChanged(CSSSelector::kPseudoFocusWithin);
+ } else if (pseudo == ":active") {
+ set.SetActive(&element, matches);
+ element.PseudoStateChanged(CSSSelector::kPseudoActive);
+ } else if (pseudo == ":hover") {
+ set.SetHovered(&element, matches);
+ element.PseudoStateChanged(CSSSelector::kPseudoHover);
+ } else {
+ return false;
+ }
+ return true;
+}
+
void Document::SetAutofocusElement(Element* element) {
if (!element) {
autofocus_element_ = nullptr;
@@ -7864,6 +8170,10 @@ LazyLoadImageObserver& Document::EnsureLazyLoadImageObserver() {
return *lazy_load_image_observer_;
}
+WindowAgent& Document::GetWindowAgent() {
+ return *static_cast<WindowAgent*>(GetAgent());
+}
+
void Document::CountPotentialFeaturePolicyViolation(
mojom::FeaturePolicyFeature feature) const {
size_t index = static_cast<size_t>(feature);
@@ -8078,22 +8388,18 @@ void Document::CountDeprecation(mojom::WebFeature feature) {
// TODO(yoichio): We should remove these counters when v0 APIs are removed.
// crbug.com/946875.
if (const OriginTrialContext* origin_trial_context =
- OriginTrialContext::FromOrCreate(this)) {
+ GetOriginTrialContext()) {
if (feature == WebFeature::kHTMLImports &&
origin_trial_context->IsFeatureEnabled(
- OriginTrialFeature::kHTMLImports) &&
- !RuntimeEnabledFeatures::HTMLImportsEnabledByRuntimeFlag()) {
+ OriginTrialFeature::kHTMLImports)) {
CountUse(WebFeature::kHTMLImportsOnReverseOriginTrials);
} else if (feature == WebFeature::kElementCreateShadowRoot &&
origin_trial_context->IsFeatureEnabled(
- OriginTrialFeature::kShadowDOMV0) &&
- !RuntimeEnabledFeatures::ShadowDOMV0EnabledByRuntimeFlag()) {
+ OriginTrialFeature::kShadowDOMV0)) {
CountUse(WebFeature::kElementCreateShadowRootOnReverseOriginTrials);
} else if (feature == WebFeature::kDocumentRegisterElement &&
origin_trial_context->IsFeatureEnabled(
- OriginTrialFeature::kCustomElementsV0) &&
- !RuntimeEnabledFeatures::
- CustomElementsV0EnabledByRuntimeFlag()) {
+ OriginTrialFeature::kCustomElementsV0)) {
CountUse(WebFeature::kDocumentRegisterElementOnReverseOriginTrials);
}
}
@@ -8141,7 +8447,6 @@ void Document::Dispose() {
template class CORE_TEMPLATE_EXPORT Supplement<Document>;
} // namespace blink
-
#ifndef NDEBUG
static WeakDocumentSet& liveDocumentSet() {
DEFINE_STATIC_LOCAL(blink::Persistent<WeakDocumentSet>, set,
@@ -8152,8 +8457,9 @@ static WeakDocumentSet& liveDocumentSet() {
void showLiveDocumentInstances() {
WeakDocumentSet& set = liveDocumentSet();
fprintf(stderr, "There are %u documents currently alive:\n", set.size());
- for (blink::Document* document : set)
+ for (blink::Document* document : set) {
fprintf(stderr, "- Document %p URL: %s\n", document,
- document->Url().GetString().Utf8().data());
+ document->Url().GetString().Utf8().c_str());
+ }
}
#endif
diff --git a/chromium/third_party/blink/renderer/core/dom/document.h b/chromium/third_party/blink/renderer/core/dom/document.h
index 46208455b19..94976ee9652 100644
--- a/chromium/third_party/blink/renderer/core/dom/document.h
+++ b/chromium/third_party/blink/renderer/core/dom/document.h
@@ -39,7 +39,7 @@
#include "services/metrics/public/cpp/ukm_source_id.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/mojom/web_feature/web_feature.mojom-shared.h"
+#include "third_party/blink/public/mojom/web_feature/web_feature.mojom-blink.h"
#include "third_party/blink/public/platform/web_focus_type.h"
#include "third_party/blink/public/platform/web_insecure_request_policy.h"
#include "third_party/blink/renderer/core/accessibility/axid.h"
@@ -66,7 +66,7 @@
#include "third_party/blink/renderer/core/execution_context/security_context.h"
#include "third_party/blink/renderer/core/frame/dom_timer_coordinator.h"
#include "third_party/blink/renderer/core/frame/hosts_using_features.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
+#include "third_party/blink/renderer/core/frame/use_counter_helper.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/scroll/scroll_types.h"
@@ -99,9 +99,11 @@ class CanvasFontCache;
class ChromeClient;
class Comment;
class ComputedAccessibleNode;
+class WindowAgent;
class ComputedStyle;
class ConsoleMessage;
class ContextFeatures;
+class CookieJar;
class V0CustomElementMicrotaskRunQueue;
class V0CustomElementRegistrationContext;
class DOMImplementation;
@@ -144,7 +146,6 @@ class HitTestRequest;
class HttpRefreshScheduler;
class IdleRequestOptions;
class IntersectionObserverController;
-class LayoutPoint;
class LayoutView;
class LazyLoadImageObserver;
class LiveNodeListBase;
@@ -200,6 +201,7 @@ class WorkletAnimationController;
struct AnnotatedRegionValue;
struct FocusParams;
struct IconURL;
+struct PhysicalOffset;
using MouseEventWithHitTestResults = EventWithHitTestResults<WebMouseEvent>;
@@ -224,6 +226,7 @@ enum DocumentClass {
kMediaDocumentClass = 1 << 4,
kSVGDocumentClass = 1 << 5,
kXMLDocumentClass = 1 << 6,
+ kViewSourceDocumentClass = 1 << 7,
};
enum ShadowCascadeOrder {
@@ -536,7 +539,7 @@ class CORE_EXPORT Document : public ContainerNode,
kRunPostLayoutTasksSynchronously,
};
void UpdateStyleAndLayoutForNode(const Node*);
- scoped_refptr<ComputedStyle> StyleForPage(int page_index);
+ scoped_refptr<const ComputedStyle> StyleForPage(int page_index);
// Ensures that location-based data will be valid for a given node.
//
@@ -569,10 +572,7 @@ class CORE_EXPORT Document : public ContainerNode,
void Initialize();
virtual void Shutdown();
- void AttachLayoutTree(AttachContext&) override { NOTREACHED(); }
- void DetachLayoutTree(const AttachContext& = AttachContext()) override {
- NOTREACHED();
- }
+ void InitContentSecurityPolicy(ContentSecurityPolicy*);
// If you have a Document, use GetLayoutView() instead which is faster.
void GetLayoutObject() const = delete;
@@ -735,8 +735,16 @@ class CORE_EXPORT Document : public ContainerNode,
// FinishingPrinting denotes that the non-printing layout state is being
// restored.
- enum PrintingState { kNotPrinting, kPrinting, kFinishingPrinting };
+ enum PrintingState {
+ kNotPrinting,
+ kBeforePrinting,
+ kPrinting,
+ kFinishingPrinting
+ };
bool Printing() const { return printing_ == kPrinting; }
+ bool BeforePrintingOrPrinting() const {
+ return printing_ == kPrinting || printing_ == kBeforePrinting;
+ }
bool FinishingOrIsPrinting() {
return printing_ == kPrinting || printing_ == kFinishingPrinting;
}
@@ -770,14 +778,13 @@ class CORE_EXPORT Document : public ContainerNode,
bool HasFinishedParsing() const { return parsing_state_ == kFinishedParsing; }
bool ShouldScheduleLayout() const;
- int ElapsedTime() const;
TextLinkColors& GetTextLinkColors() { return text_link_colors_; }
const TextLinkColors& GetTextLinkColors() const { return text_link_colors_; }
VisitedLinkState& GetVisitedLinkState() const { return *visited_link_state_; }
MouseEventWithHitTestResults PerformMouseEventHitTest(const HitTestRequest&,
- const LayoutPoint&,
+ const PhysicalOffset&,
const WebMouseEvent&);
void SetHadKeyboardEvent(bool had_keyboard_event) {
@@ -793,6 +800,10 @@ class CORE_EXPORT Document : public ContainerNode,
const UserActionElementSet& UserActionElements() const {
return user_action_elements_;
}
+ // Returns false if the function fails. e.g. |pseudo| is not supported.
+ bool SetPseudoStateForTesting(Element& element,
+ const String& pseudo,
+ bool matches);
void SetAutofocusElement(Element*);
Element* AutofocusElement() const { return autofocus_element_.Get(); }
void SetSequentialFocusNavigationStartingPoint(Node*);
@@ -935,6 +946,7 @@ class CORE_EXPORT Document : public ContainerNode,
String cookie(ExceptionState&) const;
void setCookie(const String&, ExceptionState&);
+ bool CookiesEnabled() const;
const AtomicString& referrer() const;
@@ -1103,20 +1115,11 @@ class CORE_EXPORT Document : public ContainerNode,
const SVGDocumentExtensions* SvgExtensions();
SVGDocumentExtensions& AccessSVGExtensions();
- // the first parameter specifies a policy to use as the document csp meaning
- // the document will take ownership of the policy
- // the second parameter specifies a policy to inherit meaning the document
- // will attempt to copy over the policy
- void InitContentSecurityPolicy(ContentSecurityPolicy* = nullptr,
- const ContentSecurityPolicy* = nullptr);
-
bool AllowInlineEventHandler(Node*,
EventListener*,
const String& context_url,
const WTF::OrdinalNumber& context_line);
- void EnforceSandboxFlags(WebSandboxFlags mask) override;
-
void StatePopped(scoped_refptr<SerializedScriptValue>);
enum LoadEventProgress {
@@ -1214,9 +1217,7 @@ class CORE_EXPORT Document : public ContainerNode,
const AtomicString& name,
const ElementRegistrationOptions*,
ExceptionState&);
- V0CustomElementRegistrationContext* RegistrationContext() const {
- return registration_context_.Get();
- }
+ V0CustomElementRegistrationContext* RegistrationContext() const;
V0CustomElementMicrotaskRunQueue* CustomElementMicrotaskRunQueue();
void ClearImportsController();
@@ -1243,9 +1244,9 @@ class CORE_EXPORT Document : public ContainerNode,
ElementDataCache* GetElementDataCache() { return element_data_cache_.Get(); }
void DidLoadAllScriptBlockingResources();
- void DidAddPendingStylesheetInBody();
- void DidRemoveAllPendingStylesheet();
- void DidRemoveAllPendingBodyStylesheets();
+ void DidAddPendingParserBlockingStylesheet();
+ void DidLoadAllPendingParserBlockingStylesheets();
+ void DidRemoveAllPendingStylesheets();
bool InStyleRecalc() const {
return lifecycle_.GetState() == DocumentLifecycle::kInStyleRecalc;
@@ -1255,6 +1256,7 @@ class CORE_EXPORT Document : public ContainerNode,
Locale& GetCachedLocale(const AtomicString& locale = g_null_atom);
AnimationClock& GetAnimationClock();
+ const AnimationClock& GetAnimationClock() const;
DocumentTimeline& Timeline() const { return *timeline_; }
PendingAnimations& GetPendingAnimations() { return *pending_animations_; }
WorkletAnimationController& GetWorkletAnimationController() {
@@ -1296,8 +1298,6 @@ class CORE_EXPORT Document : public ContainerNode,
void MaybeHandleHttpRefresh(const String&, HttpRefreshType);
bool IsHttpRefreshScheduledWithin(double interval_in_seconds);
- void UpdateSecurityOrigin(scoped_refptr<SecurityOrigin>);
-
void SetHasViewportUnits() { has_viewport_units_ = true; }
bool HasViewportUnits() const { return has_viewport_units_; }
void SetResizedForViewportUnits();
@@ -1401,10 +1401,8 @@ class CORE_EXPORT Document : public ContainerNode,
// May return nullptr when PerformanceManager instrumentation is disabled.
DocumentResourceCoordinator* GetResourceCoordinator();
- // Set an explicit feature policy on this document in response to an HTTP
- // Feature-Policy header. This will be relayed to the embedder through the
- // LocalFrameClient.
- void ApplyFeaturePolicyFromHeader(const String& feature_policy_header);
+ // Apply pending feature policy headers.
+ void ApplyPendingFeaturePolicyHeaders();
// Set the report-only feature policy on this document in response to an HTTP
// Feature-Policy-Report-Only header.
@@ -1492,6 +1490,8 @@ class CORE_EXPORT Document : public ContainerNode,
LazyLoadImageObserver& EnsureLazyLoadImageObserver();
+ WindowAgent& GetWindowAgent();
+
// TODO(binji): See http://crbug.com/798572. This implementation shares the
// same agent cluster ID for any one document. The proper implementation of
// this function must follow the rules described here:
@@ -1511,14 +1511,6 @@ class CORE_EXPORT Document : public ContainerNode,
mojom::FeaturePolicyDisposition,
const String& message = g_empty_string) const override;
- bool IsParsedFeaturePolicy(mojom::FeaturePolicyFeature feature) const {
- return parsed_feature_policies_[static_cast<size_t>(feature)];
- }
-
- void SetParsedFeaturePolicy(mojom::FeaturePolicyFeature feature) {
- parsed_feature_policies_.set(static_cast<size_t>(feature));
- }
-
void IncrementNumberOfCanvases();
void ProcessJavaScriptUrl(const KURL&, ContentSecurityPolicyDisposition);
@@ -1584,10 +1576,18 @@ class CORE_EXPORT Document : public ContainerNode,
bool IsUseCounted(CSSPropertyID property,
UseCounterHelper::CSSPropertyType) const;
void ClearUseCounterForTesting(mojom::WebFeature);
+ void SetSecurityOrigin(scoped_refptr<SecurityOrigin>) final;
- protected:
- void DidUpdateSecurityOrigin() final;
+ // Bind Content Security Policy to this document. This will cause the
+ // CSP to resolve the 'self' attribute and all policies will then be
+ // applied to this document.
+ void BindContentSecurityPolicy();
+ bool HasPendingJavaScriptUrlsForTest() {
+ return !pending_javascript_urls_.IsEmpty();
+ }
+
+ protected:
void ClearXMLVersion() { xml_version_ = String(); }
virtual Document* CloneDocumentWithoutChildren() const;
@@ -1605,6 +1605,16 @@ class CORE_EXPORT Document : public ContainerNode,
FRIEND_TEST_ALL_PREFIXES(FrameFetchContextSubresourceFilterTest,
DuringOnFreeze);
class NetworkStateObserver;
+ class SecurityContextInit;
+
+ Document(const DocumentInit& initization,
+ SecurityContextInit init_helper,
+ DocumentClassFlags document_classes);
+
+ // Post initialization of the object handling of the feature policy.
+ void FeaturePolicyInitialized(
+ const DocumentInit& document_initializer,
+ const SecurityContextInit& security_initializer);
friend class AXContext;
void AddAXContext(AXContext*);
@@ -1619,7 +1629,8 @@ class CORE_EXPORT Document : public ContainerNode,
ScriptedAnimationController& EnsureScriptedAnimationController();
ScriptedIdleTaskController& EnsureScriptedIdleTaskController();
- void InitSecurityContext(const DocumentInit&);
+ void InitSecurityContext(const DocumentInit&,
+ const SecurityContextInit& security_initializer);
void InitSecureContextState();
SecurityContext& GetSecurityContext() final { return *this; }
const SecurityContext& GetSecurityContext() const final { return *this; }
@@ -1716,12 +1727,6 @@ class CORE_EXPORT Document : public ContainerNode,
const ParsedFeaturePolicy GetOwnerContainerPolicy() const;
const FeaturePolicy* GetParentFeaturePolicy() const;
- // Set the feature policy on this document, inheriting as necessary from the
- // parent document and frame owner (if they exist). The caller must ensure
- // that any changes to the declared policy are relayed to the embedder through
- // the LocalFrameClient.
- void ApplyFeaturePolicy(const ParsedFeaturePolicy& declared_policy);
-
// Returns true if use of |method_name| for markup insertion is allowed by
// feature policy; otherwise returns false and throws a DOM exception.
bool AllowedToUseDynamicMarkUpInsertion(const char* method_name,
@@ -1877,7 +1882,7 @@ class CORE_EXPORT Document : public ContainerNode,
bool is_freezing_in_progress_;
- double start_time_;
+ base::ElapsedTimer start_time_;
Member<ScriptRunner> script_runner_;
@@ -2053,16 +2058,16 @@ 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.
- std::bitset<static_cast<size_t>(mojom::FeaturePolicyFeature::kMaxValue) + 1>
- parsed_feature_policies_;
// Tracks which features have already been potentially violated in this
// document. This helps to count them only once per page load.
mutable std::bitset<
static_cast<size_t>(mojom::FeaturePolicyFeature::kMaxValue) + 1>
potentially_violated_features_;
+ // Pending parsed headers to send to browser after DidCommitNavigation
+ // IPC.
+ ParsedFeaturePolicy pending_parsed_headers_;
+
AtomicString override_last_modified_;
// Map from isolated world IDs to their ContentSecurityPolicy instances.
@@ -2083,6 +2088,9 @@ class CORE_EXPORT Document : public ContainerNode,
// embedder.
std::unique_ptr<DocumentResourceCoordinator> resource_coordinator_;
+ // Used for document.cookie. May be null.
+ std::unique_ptr<CookieJar> cookie_jar_;
+
// A dummy scheduler to return when the document is detached.
// All operations on it result in no-op, but due to this it's safe to
// use the returned value of GetScheduler() without additional checks.
diff --git a/chromium/third_party/blink/renderer/core/dom/document.idl b/chromium/third_party/blink/renderer/core/dom/document.idl
index 58daf6f794f..942785dcb82 100644
--- a/chromium/third_party/blink/renderer/core/dom/document.idl
+++ b/chromium/third_party/blink/renderer/core/dom/document.idl
@@ -34,6 +34,7 @@ typedef (HTMLScriptElement or SVGScriptElement) HTMLOrSVGScriptElement;
// https://html.spec.whatwg.org/C/#documents
[
+ Exposed=Window,
Constructor(),
ConstructorCallWith=Document
] interface Document : Node {
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 d820bef26ce..ba81ea167fe 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
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_DOM_DOCUMENT_AND_ELEMENT_EVENT_HANDLERS_H_
#include "third_party/blink/renderer/core/dom/events/event_target.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/dom/document_encoding_data.h b/chromium/third_party/blink/renderer/core/dom/document_encoding_data.h
index bc9032d85de..e7159e64840 100644
--- a/chromium/third_party/blink/renderer/core/dom/document_encoding_data.h
+++ b/chromium/third_party/blink/renderer/core/dom/document_encoding_data.h
@@ -31,7 +31,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_DOM_DOCUMENT_ENCODING_DATA_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_DOM_DOCUMENT_ENCODING_DATA_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/text_encoding.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/dom/document_fragment.idl b/chromium/third_party/blink/renderer/core/dom/document_fragment.idl
index 892a8fbc3bd..e69c55f80cd 100644
--- a/chromium/third_party/blink/renderer/core/dom/document_fragment.idl
+++ b/chromium/third_party/blink/renderer/core/dom/document_fragment.idl
@@ -21,7 +21,8 @@
[
Constructor,
- ConstructorCallWith=Document
+ ConstructorCallWith=Document,
+ Exposed=Window
] interface DocumentFragment : Node {
};
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 2971f967bc5..b05c7171dc0 100644
--- a/chromium/third_party/blink/renderer/core/dom/document_init.cc
+++ b/chromium/third_party/blink/renderer/core/dom/document_init.cc
@@ -94,17 +94,19 @@ DocumentLoader* DocumentInit::MasterDocumentLoader() const {
}
WebSandboxFlags DocumentInit::GetSandboxFlags() const {
- DCHECK(MasterDocumentLoader());
DocumentLoader* loader = MasterDocumentLoader();
- WebSandboxFlags flags = loader->GetFrame()->Loader().EffectiveSandboxFlags();
-
- // If the load was blocked by CSP, force the Document's origin to be unique,
- // so that the blocked document appears to be a normal cross-origin document's
- // load per CSP spec: https://www.w3.org/TR/CSP3/#directive-frame-ancestors.
- if (loader->WasBlockedAfterCSP()) {
- flags |= WebSandboxFlags::kOrigin;
+ WebSandboxFlags flags = sandbox_flags_;
+ if (loader) {
+ flags |= loader->GetFrame()->Loader().EffectiveSandboxFlags();
+
+ // If the load was blocked by CSP, force the Document's origin to be unique,
+ // so that the blocked document appears to be a normal cross-origin
+ // document's load per CSP spec:
+ // https://www.w3.org/TR/CSP3/#directive-frame-ancestors.
+ if (loader->WasBlockedAfterCSP()) {
+ flags |= WebSandboxFlags::kOrigin;
+ }
}
-
return flags;
}
@@ -242,4 +244,28 @@ Document* DocumentInit::ContextDocument() const {
return context_document_;
}
+DocumentInit& DocumentInit::WithFeaturePolicyHeader(const String& header) {
+ DCHECK(feature_policy_header_.IsEmpty());
+ feature_policy_header_ = header;
+ return *this;
+}
+
+DocumentInit& DocumentInit::WithOriginTrialsHeader(const String& header) {
+ DCHECK(origin_trials_header_.IsEmpty());
+ origin_trials_header_ = header;
+ return *this;
+}
+
+DocumentInit& DocumentInit::WithSandboxFlags(WebSandboxFlags flags) {
+ // Only allow adding more sandbox flags.
+ sandbox_flags_ |= flags;
+ return *this;
+}
+
+DocumentInit& DocumentInit::WithContentSecurityPolicy(
+ ContentSecurityPolicy* policy) {
+ content_security_policy_ = policy;
+ return *this;
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/dom/document_init.h b/chromium/third_party/blink/renderer/core/dom/document_init.h
index fef80d05366..cd5ed824b36 100644
--- a/chromium/third_party/blink/renderer/core/dom/document_init.h
+++ b/chromium/third_party/blink/renderer/core/dom/document_init.h
@@ -40,6 +40,7 @@
namespace blink {
+class ContentSecurityPolicy;
class Document;
class DocumentLoader;
class LocalFrame;
@@ -118,6 +119,19 @@ class CORE_EXPORT DocumentInit final {
V0CustomElementRegistrationContext* RegistrationContext(Document*) const;
DocumentInit& WithNewRegistrationContext();
+ DocumentInit& WithFeaturePolicyHeader(const String& header);
+ const String& FeaturePolicyHeader() const { return feature_policy_header_; }
+
+ DocumentInit& WithOriginTrialsHeader(const String& header);
+ const String& OriginTrialsHeader() const { return origin_trials_header_; }
+
+ DocumentInit& WithSandboxFlags(WebSandboxFlags flags);
+
+ DocumentInit& WithContentSecurityPolicy(ContentSecurityPolicy* policy);
+ ContentSecurityPolicy* GetContentSecurityPolicy() const {
+ return content_security_policy_;
+ }
+
private:
DocumentInit(HTMLImportsController*);
@@ -162,6 +176,18 @@ class CORE_EXPORT DocumentInit final {
Member<V0CustomElementRegistrationContext> registration_context_;
bool create_new_registration_context_;
+
+ // The feature policy set via response header.
+ String feature_policy_header_;
+
+ // The origin trial set via response header.
+ String origin_trials_header_;
+
+ // Additional sandbox flags
+ WebSandboxFlags sandbox_flags_ = WebSandboxFlags::kNone;
+
+ // Loader's CSP
+ Member<ContentSecurityPolicy> content_security_policy_;
};
} // namespace blink
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 54cda9215d8..5327f5ce96c 100644
--- a/chromium/third_party/blink/renderer/core/dom/document_lifecycle.h
+++ b/chromium/third_party/blink/renderer/core/dom/document_lifecycle.h
@@ -34,7 +34,7 @@
#include "base/auto_reset.h"
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
#if DCHECK_IS_ON()
diff --git a/chromium/third_party/blink/renderer/core/dom/document_or_shadow_root.h b/chromium/third_party/blink/renderer/core/dom/document_or_shadow_root.h
index 57f569395aa..0f62081a758 100644
--- a/chromium/third_party/blink/renderer/core/dom/document_or_shadow_root.h
+++ b/chromium/third_party/blink/renderer/core/dom/document_or_shadow_root.h
@@ -7,9 +7,9 @@
#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/use_counter.h"
#include "third_party/blink/renderer/core/fullscreen/fullscreen.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 044ea560e91..ef292f8c1c1 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
@@ -27,14 +27,14 @@ void DocumentParserTiming::MarkParserStart() {
if (parser_detached_ || !parser_start_.is_null())
return;
DCHECK(parser_stop_.is_null());
- parser_start_ = CurrentTimeTicks();
+ parser_start_ = base::TimeTicks::Now();
NotifyDocumentParserTimingChanged();
}
void DocumentParserTiming::MarkParserStop() {
if (parser_detached_ || parser_start_.is_null() || !parser_stop_.is_null())
return;
- parser_stop_ = CurrentTimeTicks();
+ parser_stop_ = base::TimeTicks::Now();
NotifyDocumentParserTimingChanged();
}
@@ -44,7 +44,7 @@ void DocumentParserTiming::MarkParserDetached() {
}
void DocumentParserTiming::RecordParserBlockedOnScriptLoadDuration(
- TimeDelta duration,
+ base::TimeDelta duration,
bool script_inserted_via_document_write) {
if (parser_detached_ || parser_start_.is_null() || !parser_stop_.is_null())
return;
@@ -55,7 +55,7 @@ void DocumentParserTiming::RecordParserBlockedOnScriptLoadDuration(
}
void DocumentParserTiming::RecordParserBlockedOnScriptExecutionDuration(
- TimeDelta duration,
+ base::TimeDelta duration,
bool script_inserted_via_document_write) {
if (parser_detached_ || parser_start_.is_null() || !parser_stop_.is_null())
return;
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 98dbc0b17dc..c015baa4a2c 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
@@ -51,7 +51,7 @@ class DocumentParserTiming final
// called multiple times, once for each time the parser yields on a script
// load.
void RecordParserBlockedOnScriptLoadDuration(
- TimeDelta duration,
+ base::TimeDelta duration,
bool script_inserted_via_document_write);
// Record a duration of time that the parser spent executing a script.
@@ -59,19 +59,19 @@ class DocumentParserTiming final
// was inserted via document.write. This may be called multiple times, once
// for each time the parser executes a script.
void RecordParserBlockedOnScriptExecutionDuration(
- TimeDelta duration,
+ base::TimeDelta duration,
bool script_inserted_via_document_write);
// The getters below return monotonically-increasing time, or zero if the
// given parser event has not yet occurred. See the comments for
// MonotonicallyIncreasingTime in platform/wtf/time.h for additional details.
- TimeTicks ParserStart() const { return parser_start_; }
- TimeTicks ParserStop() const { return parser_stop_; }
+ base::TimeTicks ParserStart() const { return parser_start_; }
+ base::TimeTicks ParserStop() const { return parser_stop_; }
// Returns the sum of all blocking script load durations reported via
// recordParseBlockedOnScriptLoadDuration.
- TimeDelta ParserBlockedOnScriptLoadDuration() const {
+ base::TimeDelta ParserBlockedOnScriptLoadDuration() const {
return parser_blocked_on_script_load_duration_;
}
@@ -79,13 +79,13 @@ class DocumentParserTiming final
// document.write reported via recordParseBlockedOnScriptLoadDuration. Note
// that some uncommon cases are not currently covered by this method. See
// crbug/600711 for details.
- TimeDelta ParserBlockedOnScriptLoadFromDocumentWriteDuration() const {
+ base::TimeDelta ParserBlockedOnScriptLoadFromDocumentWriteDuration() const {
return parser_blocked_on_script_load_from_document_write_duration_;
}
// Returns the sum of all script execution durations reported via
// recordParseBlockedOnScriptExecutionDuration.
- TimeDelta ParserBlockedOnScriptExecutionDuration() const {
+ base::TimeDelta ParserBlockedOnScriptExecutionDuration() const {
return parser_blocked_on_script_execution_duration_;
}
@@ -93,7 +93,8 @@ class DocumentParserTiming final
// document.write reported via recordParseBlockedOnScriptExecutionDuration.
// Note that some uncommon cases are not currently covered by this method. See
// crbug/600711 for details.
- TimeDelta ParserBlockedOnScriptExecutionFromDocumentWriteDuration() const {
+ base::TimeDelta ParserBlockedOnScriptExecutionFromDocumentWriteDuration()
+ const {
return parser_blocked_on_script_execution_from_document_write_duration_;
}
@@ -102,12 +103,13 @@ class DocumentParserTiming final
private:
void NotifyDocumentParserTimingChanged();
- TimeTicks parser_start_;
- TimeTicks parser_stop_;
- TimeDelta parser_blocked_on_script_load_duration_;
- TimeDelta parser_blocked_on_script_load_from_document_write_duration_;
- TimeDelta parser_blocked_on_script_execution_duration_;
- TimeDelta parser_blocked_on_script_execution_from_document_write_duration_;
+ base::TimeTicks parser_start_;
+ base::TimeTicks parser_stop_;
+ base::TimeDelta parser_blocked_on_script_load_duration_;
+ base::TimeDelta parser_blocked_on_script_load_from_document_write_duration_;
+ base::TimeDelta parser_blocked_on_script_execution_duration_;
+ base::TimeDelta
+ parser_blocked_on_script_execution_from_document_write_duration_;
bool parser_detached_ = false;
DISALLOW_COPY_AND_ASSIGN(DocumentParserTiming);
};
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 308b4f94b5e..c7675d16ceb 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
@@ -17,7 +17,7 @@
#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/page/page.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
namespace blink {
@@ -205,7 +205,7 @@ WebDistillabilityFeatures DocumentStatisticsCollector::CollectStatistics(
features.is_mobile_friendly = IsMobileFriendly(document);
- TimeTicks start_time = CurrentTimeTicks();
+ base::TimeTicks start_time = base::TimeTicks::Now();
// This should be cheap since collectStatistics is only called right after
// layout.
@@ -215,7 +215,7 @@ WebDistillabilityFeatures DocumentStatisticsCollector::CollectStatistics(
CollectFeatures(*body, features);
features.open_graph = HasOpenGraphArticle(*head);
- TimeDelta elapsed_time = CurrentTimeTicks() - start_time;
+ base::TimeDelta elapsed_time = base::TimeTicks::Now() - start_time;
DEFINE_STATIC_LOCAL(CustomCountHistogram, distillability_histogram,
("WebCore.DistillabilityUs", 1, 1000000, 50));
diff --git a/chromium/third_party/blink/renderer/core/dom/document_statistics_collector.h b/chromium/third_party/blink/renderer/core/dom/document_statistics_collector.h
index 731a949e5d5..3093013b08f 100644
--- a/chromium/third_party/blink/renderer/core/dom/document_statistics_collector.h
+++ b/chromium/third_party/blink/renderer/core/dom/document_statistics_collector.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_DOM_DOCUMENT_STATISTICS_COLLECTOR_H_
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 88b9214a4d5..badc5c26b9c 100644
--- a/chromium/third_party/blink/renderer/core/dom/document_test.cc
+++ b/chromium/third_party/blink/renderer/core/dom/document_test.cc
@@ -34,10 +34,9 @@
#include "base/strings/stringprintf.h"
#include "build/build_config.h"
-#include "services/network/public/mojom/referrer_policy.mojom-shared.h"
+#include "services/network/public/mojom/referrer_policy.mojom-blink.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/blink/public/web/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"
@@ -55,7 +54,7 @@
#include "third_party/blink/renderer/core/html/forms/html_input_element.h"
#include "third_party/blink/renderer/core/html/html_head_element.h"
#include "third_party/blink/renderer/core/html/html_link_element.h"
-#include "third_party/blink/renderer/core/loader/appcache/application_cache_host.h"
+#include "third_party/blink/renderer/core/loader/appcache/application_cache_host_for_frame.h"
#include "third_party/blink/renderer/core/loader/document_loader.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/page/validation_message_client.h"
@@ -64,6 +63,7 @@
#include "third_party/blink/renderer/platform/heap/heap.h"
#include "third_party/blink/renderer/platform/mojo/interface_invalidator.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/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"
@@ -74,6 +74,7 @@ class DocumentTest : public PageTestBase {
protected:
void TearDown() override {
ThreadState::Current()->CollectAllGarbageForTesting();
+ PageTestBase::TearDown();
}
void SetHtmlInnerHTML(const char*);
@@ -329,20 +330,18 @@ class MockDocumentValidationMessageClient
// ValidationMessageClient::trace(visitor); }
};
-class MockWebApplicationCacheHost : public blink::WebApplicationCacheHost {
+class MockApplicationCacheHost final : public ApplicationCacheHostForFrame {
public:
- MockWebApplicationCacheHost() = default;
- ~MockWebApplicationCacheHost() override = default;
+ MockApplicationCacheHost(DocumentLoader* loader)
+ : ApplicationCacheHostForFrame(loader,
+ /*interface_broker=*/nullptr,
+ /*task_runner=*/nullptr) {}
+ ~MockApplicationCacheHost() override = default;
void SelectCacheWithoutManifest() override {
without_manifest_was_called_ = true;
}
- bool SelectCacheWithManifest(const blink::WebURL& manifestURL) override {
- with_manifest_was_called_ = true;
- return true;
- }
- bool with_manifest_was_called_ = false;
bool without_manifest_was_called_ = false;
};
@@ -566,15 +565,14 @@ TEST_F(DocumentTest, referrerPolicyParsing) {
}
TEST_F(DocumentTest, OutgoingReferrer) {
- GetDocument().SetURL(KURL("https://www.example.com/hoge#fuga?piyo"));
- GetDocument().SetSecurityOrigin(
- SecurityOrigin::Create(KURL("https://www.example.com/")));
+ NavigateTo(KURL("https://www.example.com/hoge#fuga?piyo"));
EXPECT_EQ("https://www.example.com/hoge", GetDocument().OutgoingReferrer());
}
TEST_F(DocumentTest, OutgoingReferrerWithUniqueOrigin) {
- GetDocument().SetURL(KURL("https://www.example.com/hoge#fuga?piyo"));
- GetDocument().SetSecurityOrigin(SecurityOrigin::CreateUniqueOpaque());
+ NavigateTo(KURL("https://www.example.com/hoge#fuga?piyo"), "",
+ "sandbox allow-scripts");
+ EXPECT_TRUE(GetDocument().GetSecurityOrigin()->IsOpaque());
EXPECT_EQ(String(), GetDocument().OutgoingReferrer());
}
@@ -608,16 +606,11 @@ TEST_F(DocumentTest, StyleVersion) {
}
TEST_F(DocumentTest, EnforceSandboxFlags) {
- scoped_refptr<SecurityOrigin> origin =
- SecurityOrigin::CreateFromString("http://example.test");
- GetDocument().SetSecurityOrigin(origin);
- SandboxFlags mask = WebSandboxFlags::kNavigation;
- GetDocument().EnforceSandboxFlags(mask);
- EXPECT_EQ(origin, GetDocument().GetSecurityOrigin());
+ NavigateTo(KURL("http://example.test/"), "", "sandbox allow-same-origin");
+ EXPECT_FALSE(GetDocument().GetSecurityOrigin()->IsOpaque());
EXPECT_FALSE(GetDocument().GetSecurityOrigin()->IsPotentiallyTrustworthy());
- mask |= WebSandboxFlags::kOrigin;
- GetDocument().EnforceSandboxFlags(mask);
+ NavigateTo(KURL("http://example.test/"), "", "sandbox");
EXPECT_TRUE(GetDocument().GetSecurityOrigin()->IsOpaque());
EXPECT_FALSE(GetDocument().GetSecurityOrigin()->IsPotentiallyTrustworthy());
@@ -627,22 +620,16 @@ TEST_F(DocumentTest, EnforceSandboxFlags) {
url::SchemeType::SCHEME_WITH_HOST);
SchemeRegistry::RegisterURLSchemeBypassingSecureContextCheck(
"very-special-scheme");
- origin =
- SecurityOrigin::CreateFromString("very-special-scheme://example.test");
- GetDocument().SetSecurityOrigin(origin);
- GetDocument().EnforceSandboxFlags(mask);
+ NavigateTo(KURL("very-special-scheme://example.test"), "", "sandbox");
EXPECT_TRUE(GetDocument().GetSecurityOrigin()->IsOpaque());
EXPECT_FALSE(GetDocument().GetSecurityOrigin()->IsPotentiallyTrustworthy());
SchemeRegistry::RegisterURLSchemeAsSecure("very-special-scheme");
- GetDocument().SetSecurityOrigin(origin);
- GetDocument().EnforceSandboxFlags(mask);
+ NavigateTo(KURL("very-special-scheme://example.test"), "", "sandbox");
EXPECT_TRUE(GetDocument().GetSecurityOrigin()->IsOpaque());
EXPECT_TRUE(GetDocument().GetSecurityOrigin()->IsPotentiallyTrustworthy());
- origin = SecurityOrigin::CreateFromString("https://example.test");
- GetDocument().SetSecurityOrigin(origin);
- GetDocument().EnforceSandboxFlags(mask);
+ NavigateTo(KURL("https://example.test"), "", "sandbox");
EXPECT_TRUE(GetDocument().GetSecurityOrigin()->IsOpaque());
EXPECT_TRUE(GetDocument().GetSecurityOrigin()->IsPotentiallyTrustworthy());
}
@@ -881,8 +868,8 @@ TEST_F(DocumentTest, ValidationMessageCleanup) {
EXPECT_TRUE(mock_client->show_validation_message_was_called);
mock_client->Reset();
- // prepareForCommit() unloads the document, and shutdown.
- GetDocument().GetFrame()->PrepareForCommit();
+ // DetachDocument() unloads the document, and shutdowns.
+ GetDocument().GetFrame()->DetachDocument();
EXPECT_TRUE(mock_client->document_detached_was_called);
// Unload handler tried to show a validation message, but it should fail.
EXPECT_FALSE(mock_client->show_validation_message_was_called);
@@ -891,22 +878,16 @@ TEST_F(DocumentTest, ValidationMessageCleanup) {
}
TEST_F(DocumentTest, SandboxDisablesAppCache) {
- scoped_refptr<SecurityOrigin> origin =
- SecurityOrigin::CreateFromString("https://test.com");
- GetDocument().SetSecurityOrigin(origin);
- SandboxFlags mask = WebSandboxFlags::kOrigin;
- GetDocument().EnforceSandboxFlags(mask);
- GetDocument().SetURL(KURL("https://test.com/foobar/document"));
+ NavigateTo(KURL("https://test.com/foobar/document"), "", "sandbox");
+ GetDocument().Loader()->SetApplicationCacheHostForTesting(
+ MakeGarbageCollected<MockApplicationCacheHost>(GetDocument().Loader()));
ApplicationCacheHost* appcache_host =
GetDocument().Loader()->GetApplicationCacheHost();
- appcache_host->host_ = std::make_unique<MockWebApplicationCacheHost>();
appcache_host->SelectCacheWithManifest(
KURL("https://test.com/foobar/manifest"));
- MockWebApplicationCacheHost* mock_web_host =
- static_cast<MockWebApplicationCacheHost*>(appcache_host->host_.get());
- EXPECT_FALSE(mock_web_host->with_manifest_was_called_);
- EXPECT_TRUE(mock_web_host->without_manifest_was_called_);
+ auto* mock_host = static_cast<MockApplicationCacheHost*>(appcache_host);
+ EXPECT_TRUE(mock_host->without_manifest_was_called_);
}
// Verifies that calling EnsurePaintLocationDataValidForNode cleans compositor
@@ -1001,11 +982,10 @@ TEST_F(DocumentTest, InterfaceInvalidatorDestruction) {
// Test fixture parameterized on whether the "IsolatedWorldCSP" feature is
// enabled.
class IsolatedWorldCSPTest : public DocumentTest,
- public testing::WithParamInterface<bool> {
+ public testing::WithParamInterface<bool>,
+ private ScopedIsolatedWorldCSPForTest {
public:
- IsolatedWorldCSPTest() {
- RuntimeEnabledFeatures::SetIsolatedWorldCSPEnabled(GetParam());
- }
+ IsolatedWorldCSPTest() : ScopedIsolatedWorldCSPForTest(GetParam()) {}
private:
DISALLOW_COPY_AND_ASSIGN(IsolatedWorldCSPTest);
@@ -1092,13 +1072,7 @@ TEST_P(IsolatedWorldCSPTest, CSPForWorld) {
INSTANTIATE_TEST_SUITE_P(, IsolatedWorldCSPTest, testing::Values(true, false));
TEST_F(DocumentTest, CanExecuteScriptsWithSandboxAndIsolatedWorld) {
- constexpr SandboxFlags kSandboxMask = WebSandboxFlags::kScripts;
- GetDocument().EnforceSandboxFlags(kSandboxMask);
- // With FeaturePolicyForSandbox, all the sandbox flags must be explicitly
- // converted to equivalent feature policies. Since sandbox is enforced above,
- // the feature policies have to be reset; setting an empty header policy will
- // internally convert the newly set sandbox flags to policies.
- GetDocument().ApplyFeaturePolicyFromHeader("");
+ NavigateTo(KURL("https://www.example.com/"), "", "sandbox");
LocalFrame* frame = GetDocument().GetFrame();
frame->GetSettings()->SetScriptEnabled(true);
@@ -1226,12 +1200,12 @@ TEST_F(DocumentTest, PrefersColorSchemeChanged) {
* Tests for viewport-fit propagation.
*/
-class ViewportFitDocumentTest : public DocumentTest {
+class ViewportFitDocumentTest : public DocumentTest,
+ private ScopedDisplayCutoutAPIForTest {
public:
+ ViewportFitDocumentTest() : ScopedDisplayCutoutAPIForTest(true) {}
void SetUp() override {
DocumentTest::SetUp();
-
- RuntimeEnabledFeatures::SetDisplayCutoutAPIEnabled(true);
GetDocument().GetSettings()->SetViewportMetaEnabled(true);
}
diff --git a/chromium/third_party/blink/renderer/core/dom/document_timing.cc b/chromium/third_party/blink/renderer/core/dom/document_timing.cc
index bf58fc556fa..beb3f9deb31 100644
--- a/chromium/third_party/blink/renderer/core/dom/document_timing.cc
+++ b/chromium/third_party/blink/renderer/core/dom/document_timing.cc
@@ -28,7 +28,7 @@ void DocumentTiming::NotifyDocumentTimingChanged() {
}
void DocumentTiming::MarkDomLoading() {
- dom_loading_ = CurrentTimeTicks();
+ dom_loading_ = base::TimeTicks::Now();
TRACE_EVENT_MARK_WITH_TIMESTAMP1("blink.user_timing,rail", "domLoading",
dom_loading_, "frame",
ToTraceValue(GetFrame()));
@@ -36,7 +36,7 @@ void DocumentTiming::MarkDomLoading() {
}
void DocumentTiming::MarkDomInteractive() {
- dom_interactive_ = CurrentTimeTicks();
+ dom_interactive_ = base::TimeTicks::Now();
TRACE_EVENT_MARK_WITH_TIMESTAMP1("blink.user_timing,rail", "domInteractive",
dom_interactive_, "frame",
ToTraceValue(GetFrame()));
@@ -44,7 +44,7 @@ void DocumentTiming::MarkDomInteractive() {
}
void DocumentTiming::MarkDomContentLoadedEventStart() {
- dom_content_loaded_event_start_ = CurrentTimeTicks();
+ dom_content_loaded_event_start_ = base::TimeTicks::Now();
TRACE_EVENT_MARK_WITH_TIMESTAMP1(
"blink.user_timing,rail", "domContentLoadedEventStart",
dom_content_loaded_event_start_, "frame", ToTraceValue(GetFrame()));
@@ -52,7 +52,7 @@ void DocumentTiming::MarkDomContentLoadedEventStart() {
}
void DocumentTiming::MarkDomContentLoadedEventEnd() {
- dom_content_loaded_event_end_ = CurrentTimeTicks();
+ dom_content_loaded_event_end_ = base::TimeTicks::Now();
TRACE_EVENT_MARK_WITH_TIMESTAMP1(
"blink.user_timing,rail", "domContentLoadedEventEnd",
dom_content_loaded_event_end_, "frame", ToTraceValue(GetFrame()));
@@ -65,7 +65,7 @@ void DocumentTiming::MarkDomContentLoadedEventEnd() {
}
void DocumentTiming::MarkDomComplete() {
- dom_complete_ = CurrentTimeTicks();
+ dom_complete_ = base::TimeTicks::Now();
TRACE_EVENT_MARK_WITH_TIMESTAMP1("blink.user_timing,rail", "domComplete",
dom_complete_, "frame",
ToTraceValue(GetFrame()));
@@ -73,7 +73,7 @@ void DocumentTiming::MarkDomComplete() {
}
void DocumentTiming::MarkFirstLayout() {
- first_layout_ = CurrentTimeTicks();
+ first_layout_ = base::TimeTicks::Now();
TRACE_EVENT_MARK_WITH_TIMESTAMP1("blink.user_timing,rail", "firstLayout",
first_layout_, "frame",
ToTraceValue(GetFrame()));
diff --git a/chromium/third_party/blink/renderer/core/dom/document_timing.h b/chromium/third_party/blink/renderer/core/dom/document_timing.h
index 5aed8975f2c..e7bd49ec24e 100644
--- a/chromium/third_party/blink/renderer/core/dom/document_timing.h
+++ b/chromium/third_party/blink/renderer/core/dom/document_timing.h
@@ -48,16 +48,16 @@ class DocumentTiming final {
void MarkFirstLayout();
// These return monotonically-increasing time.
- TimeTicks DomLoading() const { return dom_loading_; }
- TimeTicks DomInteractive() const { return dom_interactive_; }
- TimeTicks DomContentLoadedEventStart() const {
+ base::TimeTicks DomLoading() const { return dom_loading_; }
+ base::TimeTicks DomInteractive() const { return dom_interactive_; }
+ base::TimeTicks DomContentLoadedEventStart() const {
return dom_content_loaded_event_start_;
}
- TimeTicks DomContentLoadedEventEnd() const {
+ base::TimeTicks DomContentLoadedEventEnd() const {
return dom_content_loaded_event_end_;
}
- TimeTicks DomComplete() const { return dom_complete_; }
- TimeTicks FirstLayout() const { return first_layout_; }
+ base::TimeTicks DomComplete() const { return dom_complete_; }
+ base::TimeTicks FirstLayout() const { return first_layout_; }
void Trace(Visitor*);
@@ -65,12 +65,12 @@ class DocumentTiming final {
LocalFrame* GetFrame() const;
void NotifyDocumentTimingChanged();
- TimeTicks dom_loading_;
- TimeTicks dom_interactive_;
- TimeTicks dom_content_loaded_event_start_;
- TimeTicks dom_content_loaded_event_end_;
- TimeTicks dom_complete_;
- TimeTicks first_layout_;
+ base::TimeTicks dom_loading_;
+ base::TimeTicks dom_interactive_;
+ base::TimeTicks dom_content_loaded_event_start_;
+ base::TimeTicks dom_content_loaded_event_end_;
+ base::TimeTicks dom_complete_;
+ base::TimeTicks first_layout_;
Member<Document> document_;
};
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 88741507205..1b064118925 100644
--- a/chromium/third_party/blink/renderer/core/dom/document_type.h
+++ b/chromium/third_party/blink/renderer/core/dom/document_type.h
@@ -57,7 +57,7 @@ class DocumentType final : public Node {
InsertionNotificationRequest InsertedInto(ContainerNode&) override;
void RemovedFrom(ContainerNode&) override;
- void DetachLayoutTree(const AttachContext&) final {}
+ void DetachLayoutTree(bool performing_reattach) final {}
String name_;
String public_id_;
diff --git a/chromium/third_party/blink/renderer/core/dom/document_type.idl b/chromium/third_party/blink/renderer/core/dom/document_type.idl
index 836148a3cf5..dea1eca0fcd 100644
--- a/chromium/third_party/blink/renderer/core/dom/document_type.idl
+++ b/chromium/third_party/blink/renderer/core/dom/document_type.idl
@@ -19,7 +19,9 @@
// https://dom.spec.whatwg.org/#interface-documenttype
-interface DocumentType : Node {
+[
+ Exposed=Window
+] interface DocumentType : Node {
readonly attribute DOMString name;
readonly attribute DOMString publicId;
readonly attribute DOMString systemId;
diff --git a/chromium/third_party/blink/renderer/core/dom/dom_exception.idl b/chromium/third_party/blink/renderer/core/dom/dom_exception.idl
index bbf3701e7e3..2e3e9adac67 100644
--- a/chromium/third_party/blink/renderer/core/dom/dom_exception.idl
+++ b/chromium/third_party/blink/renderer/core/dom/dom_exception.idl
@@ -31,8 +31,9 @@
// https://heycam.github.io/webidl/#es-DOMException
[
- Constructor(optional DOMString message = "", optional DOMString name = "Error"),
Exposed=(Window,Worker),
+ Constructor(optional DOMString message = "", optional DOMString name = "Error"),
+ Serializable,
DoNotCheckConstants
] interface DOMException {
diff --git a/chromium/third_party/blink/renderer/core/dom/dom_high_res_time_stamp.h b/chromium/third_party/blink/renderer/core/dom/dom_high_res_time_stamp.h
index 6a469caabfc..a4a00d42e99 100644
--- a/chromium/third_party/blink/renderer/core/dom/dom_high_res_time_stamp.h
+++ b/chromium/third_party/blink/renderer/core/dom/dom_high_res_time_stamp.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_DOM_DOM_HIGH_RES_TIME_STAMP_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_DOM_DOM_HIGH_RES_TIME_STAMP_H_
-#include "third_party/blink/renderer/platform/wtf/time.h"
+#include "base/time/time.h"
namespace blink {
@@ -21,12 +21,12 @@ inline double ConvertDOMHighResTimeStampToSeconds(
}
inline DOMHighResTimeStamp ConvertTimeTicksToDOMHighResTimeStamp(
- TimeTicks time) {
- return (time - TimeTicks()).InMillisecondsF();
+ base::TimeTicks time) {
+ return (time - base::TimeTicks()).InMillisecondsF();
}
inline DOMHighResTimeStamp ConvertTimeDeltaToDOMHighResTimeStamp(
- TimeDelta delta) {
+ base::TimeDelta delta) {
return delta.InMillisecondsF();
}
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 5e2b2fc592b..80a9ec9bc75 100644
--- a/chromium/third_party/blink/renderer/core/dom/dom_implementation.cc
+++ b/chromium/third_party/blink/renderer/core/dom/dom_implementation.cc
@@ -35,7 +35,6 @@
#include "third_party/blink/renderer/core/dom/text.h"
#include "third_party/blink/renderer/core/dom/xml_document.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/html/custom/v0_custom_element_registration_context.h"
#include "third_party/blink/renderer/core/html/html_document.h"
#include "third_party/blink/renderer/core/html/html_head_element.h"
@@ -54,6 +53,7 @@
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/graphics/image.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#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/security_origin.h"
@@ -83,8 +83,9 @@ XMLDocument* DOMImplementation::createDocument(
DocumentType* doctype,
ExceptionState& exception_state) {
XMLDocument* doc = nullptr;
- DocumentInit init =
- DocumentInit::Create().WithContextDocument(document_->ContextDocument());
+ DocumentInit init = DocumentInit::Create()
+ .WithContextDocument(document_->ContextDocument())
+ .WithOwnerDocument(document_->ContextDocument());
if (namespace_uri == svg_names::kNamespaceURI) {
doc = XMLDocument::CreateSVG(init);
} else if (namespace_uri == html_names::xhtmlNamespaceURI) {
@@ -94,7 +95,6 @@ XMLDocument* DOMImplementation::createDocument(
doc = MakeGarbageCollected<XMLDocument>(init);
}
- doc->SetSecurityOrigin(document_->GetMutableSecurityOrigin());
doc->SetContextFeatures(document_->GetContextFeatures());
Node* document_element = nullptr;
@@ -206,6 +206,7 @@ Document* DOMImplementation::createHTMLDocument(const String& title) {
DocumentInit init =
DocumentInit::Create()
.WithContextDocument(document_->ContextDocument())
+ .WithOwnerDocument(document_->ContextDocument())
.WithRegistrationContext(document_->RegistrationContext());
auto* d = MakeGarbageCollected<HTMLDocument>(init);
d->open();
@@ -217,7 +218,6 @@ Document* DOMImplementation::createHTMLDocument(const String& title) {
head_element->AppendChild(title_element);
title_element->AppendChild(d->createTextNode(title), ASSERT_NO_EXCEPTION);
}
- d->SetSecurityOrigin(document_->GetMutableSecurityOrigin());
d->SetContextFeatures(document_->GetContextFeatures());
return d;
}
diff --git a/chromium/third_party/blink/renderer/core/dom/dom_implementation.idl b/chromium/third_party/blink/renderer/core/dom/dom_implementation.idl
index b70e5421842..73eeb6ae0e2 100644
--- a/chromium/third_party/blink/renderer/core/dom/dom_implementation.idl
+++ b/chromium/third_party/blink/renderer/core/dom/dom_implementation.idl
@@ -20,7 +20,9 @@
// https://dom.spec.whatwg.org/#interface-domimplementation
-interface DOMImplementation {
+[
+ Exposed=Window
+] interface DOMImplementation {
[NewObject, RaisesException] DocumentType createDocumentType(DOMString qualifiedName, DOMString publicId, DOMString systemId);
[NewObject, RaisesException] XMLDocument createDocument(DOMString? namespaceURI, [TreatNullAs=EmptyString] DOMString qualifiedName, optional DocumentType? doctype = null);
// FIXME: createHTMLDocument should return a Document. crbug.com/238368
diff --git a/chromium/third_party/blink/renderer/core/dom/dom_node_ids.h b/chromium/third_party/blink/renderer/core/dom/dom_node_ids.h
index 1757dbabf6e..643aedeaab9 100644
--- a/chromium/third_party/blink/renderer/core/dom/dom_node_ids.h
+++ b/chromium/third_party/blink/renderer/core/dom/dom_node_ids.h
@@ -9,7 +9,7 @@
#include "third_party/blink/renderer/core/dom/node.h"
#include "third_party/blink/renderer/core/dom/weak_identifier_map.h"
#include "third_party/blink/renderer/platform/graphics/dom_node_id.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/dom/dom_string_list.cc b/chromium/third_party/blink/renderer/core/dom/dom_string_list.cc
index b68fd084575..95bb216ab7a 100644
--- a/chromium/third_party/blink/renderer/core/dom/dom_string_list.cc
+++ b/chromium/third_party/blink/renderer/core/dom/dom_string_list.cc
@@ -47,7 +47,7 @@ bool DOMStringList::contains(const String& string) const {
}
void DOMStringList::Sort() {
- std::sort(strings_.begin(), strings_.end(), WTF::CodePointCompareLessThan);
+ std::sort(strings_.begin(), strings_.end(), WTF::CodeUnitCompareLessThan);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/dom/dom_string_map.idl b/chromium/third_party/blink/renderer/core/dom/dom_string_map.idl
index 4c3ef5c2aa5..8f47e3ba021 100644
--- a/chromium/third_party/blink/renderer/core/dom/dom_string_map.idl
+++ b/chromium/third_party/blink/renderer/core/dom/dom_string_map.idl
@@ -26,7 +26,8 @@
// https://html.spec.whatwg.org/C/#the-domstringmap-interface
[
- OverrideBuiltins
+ OverrideBuiltins,
+ Exposed=Window
] interface DOMStringMap {
[ImplementedAs=item] getter DOMString (DOMString name);
[CEReactions, RaisesException] setter void (DOMString name, DOMString value);
diff --git a/chromium/third_party/blink/renderer/core/dom/element.cc b/chromium/third_party/blink/renderer/core/dom/element.cc
index a1bbda4ac2e..4a2d4ae1a8e 100644
--- a/chromium/third_party/blink/renderer/core/dom/element.cc
+++ b/chromium/third_party/blink/renderer/core/dom/element.cc
@@ -44,6 +44,7 @@
#include "third_party/blink/renderer/core/animation/css/css_animations.h"
#include "third_party/blink/renderer/core/aom/computed_accessible_node.h"
#include "third_party/blink/renderer/core/css/css_identifier_value.h"
+#include "third_party/blink/renderer/core/css/css_numeric_literal_value.h"
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
#include "third_party/blink/renderer/core/css/css_property_value_set.h"
#include "third_party/blink/renderer/core/css/css_selector_watch.h"
@@ -102,7 +103,6 @@
#include "third_party/blink/renderer/core/frame/scroll_into_view_options.h"
#include "third_party/blink/renderer/core/frame/scroll_to_options.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/frame/visual_viewport.h"
#include "third_party/blink/renderer/core/fullscreen/fullscreen.h"
#include "third_party/blink/renderer/core/geometry/dom_rect.h"
@@ -157,9 +157,9 @@
#include "third_party/blink/renderer/platform/bindings/v8_per_context_data.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/wtf/hash_functions.h"
-#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#include "third_party/blink/renderer/platform/wtf/text/text_position.h"
@@ -267,8 +267,14 @@ bool DefinitelyNewFormattingContext(const Node& node,
return false;
// The only block-container display types that potentially don't establish a
// new formatting context, are 'block' and 'list-item'.
- if (display != EDisplay::kBlock && display != EDisplay::kListItem)
- return true;
+ if (display != EDisplay::kBlock && display != EDisplay::kListItem) {
+ // DETAILS and SUMMARY elements partially or completely ignore the display
+ // type, though, and may end up disregarding the display type and just
+ // create block containers. And those don't necessarily create a formatting
+ // context.
+ if (!IsHTMLDetailsElement(node) && !IsHTMLSummaryElement(node))
+ return true;
+ }
if (!style.IsOverflowVisible())
return node.GetDocument().ViewportDefiningElement() != &node;
if (style.HasOutOfFlowPosition() || style.IsFloating() ||
@@ -277,7 +283,7 @@ bool DefinitelyNewFormattingContext(const Node& node,
return true;
if (node.GetDocument().documentElement() == &node)
return true;
- if (const Element* element = ToElementOrNull(&node)) {
+ if (const Element* element = DynamicTo<Element>(&node)) {
// Replaced elements are considered to create a new formatting context, in
// the sense that they can't possibly have children that participate in the
// same formatting context as their parent.
@@ -334,6 +340,18 @@ bool CalculateStyleShouldForceLegacyLayout(const Element& element,
if (style.HasTextCombine() && !style.IsHorizontalWritingMode())
return true;
+ if (style.InsideNGFragmentationContext()) {
+ // If we're inside an NG block fragmentation context, all fragmentable boxes
+ // must be laid out by NG natively. We only allow legacy layout objects if
+ // they are monolithic (e.g. replaced content, inline-table, and so
+ // on). Inline display types end up on a line, and are therefore monolithic,
+ // so we can allow those.
+ if (!style.IsDisplayInlineType()) {
+ if (style.IsDisplayTableType() || style.IsDisplayFlexibleOrGridBox())
+ return true;
+ }
+ }
+
return false;
}
@@ -348,6 +366,10 @@ Element::Element(const QualifiedName& tag_name,
ConstructionType type)
: ContainerNode(document, type), tag_name_(tag_name) {}
+Element* Element::GetAnimationTarget() {
+ return this;
+}
+
inline ElementRareData* Element::GetElementRareData() const {
DCHECK(HasRareData());
return static_cast<ElementRareData*>(RareData());
@@ -666,6 +688,8 @@ void Element::scrollIntoView(bool align_to_top) {
scrollIntoView(arg);
}
+// TODO(cathiechen): CSS direction hasn't been supported. (See:
+// crbug.com/982212, https://www.w3.org/TR/cssom-view-1/#beginning-edges).
static ScrollAlignment ToPhysicalAlignment(const ScrollIntoViewOptions* options,
ScrollOrientation axis,
bool is_horizontal_writing_mode,
@@ -731,7 +755,7 @@ void Element::ScrollIntoViewNoVisualUpdate(
ToPhysicalAlignment(options, kVerticalScroll, is_horizontal_writing_mode,
is_flipped_blocks_mode);
- LayoutRect bounds = BoundingBoxForScrollIntoView();
+ PhysicalRect bounds = BoundingBoxForScrollIntoView();
GetLayoutObject()->ScrollRectToVisible(
bounds, {align_x, align_y, kProgrammaticScroll,
/*make_visible_in_visual_viewport=*/true, behavior});
@@ -745,7 +769,7 @@ void Element::scrollIntoViewIfNeeded(bool center_if_needed) {
if (!GetLayoutObject())
return;
- LayoutRect bounds = BoundingBoxForScrollIntoView();
+ PhysicalRect bounds = BoundingBoxForScrollIntoView();
if (center_if_needed) {
GetLayoutObject()->ScrollRectToVisible(
bounds, {ScrollAlignment::kAlignCenterIfNeeded,
@@ -1584,6 +1608,24 @@ const AtomicString& Element::getAttributeNS(
return getAttribute(QualifiedName(g_null_atom, local_name, namespace_uri));
}
+std::pair<wtf_size_t, const QualifiedName>
+Element::LookupAttributeQNameInternal(const AtomicString& local_name) const {
+ AtomicString case_adjusted_local_name = LowercaseIfNecessary(local_name);
+ if (!GetElementData()) {
+ return std::make_pair(
+ kNotFound,
+ QualifiedName(g_null_atom, case_adjusted_local_name, g_null_atom));
+ }
+
+ AttributeCollection attributes = GetElementData()->Attributes();
+ wtf_size_t index = attributes.FindIndex(case_adjusted_local_name);
+ return std::make_pair(
+ index,
+ index != kNotFound
+ ? attributes[index].GetName()
+ : QualifiedName(g_null_atom, case_adjusted_local_name, g_null_atom));
+}
+
void Element::setAttribute(const AtomicString& local_name,
const AtomicString& value,
ExceptionState& exception_state) {
@@ -1595,22 +1637,9 @@ void Element::setAttribute(const AtomicString& local_name,
}
SynchronizeAttribute(local_name);
- AtomicString case_adjusted_local_name = LowercaseIfNecessary(local_name);
-
- if (!GetElementData()) {
- SetAttributeInternal(
- kNotFound,
- QualifiedName(g_null_atom, case_adjusted_local_name, g_null_atom),
- value, kNotInSynchronizationOfLazyAttribute);
- return;
- }
-
- AttributeCollection attributes = GetElementData()->Attributes();
- wtf_size_t index = attributes.FindIndex(case_adjusted_local_name);
- const QualifiedName& q_name =
- index != kNotFound
- ? attributes[index].GetName()
- : QualifiedName(g_null_atom, case_adjusted_local_name, g_null_atom);
+ wtf_size_t index;
+ QualifiedName q_name = QualifiedName::Null();
+ std::tie(index, q_name) = LookupAttributeQNameInternal(local_name);
SetAttributeInternal(index, q_name, value,
kNotInSynchronizationOfLazyAttribute);
}
@@ -1639,36 +1668,28 @@ void Element::SetSynchronizedLazyAttribute(const QualifiedName& name,
}
void Element::setAttribute(
- const AtomicString& name,
+ const AtomicString& local_name,
const StringOrTrustedHTMLOrTrustedScriptOrTrustedScriptURLOrTrustedURL&
string_or_TT,
ExceptionState& exception_state) {
- // TODO(vogelheim): Check whether this applies to non-HTML documents, too.
- AtomicString name_lowercase = LowercaseIfNecessary(name);
- const AttrNameToTrustedType* attribute_types = &GetCheckedAttributeTypes();
- AttrNameToTrustedType::const_iterator it =
- attribute_types->find(name_lowercase);
- if (it != attribute_types->end()) {
- String attr_value = GetStringFromSpecificTrustedType(
- string_or_TT, it->value, &GetDocument(), exception_state);
- if (!exception_state.HadException())
- setAttribute(name_lowercase, AtomicString(attr_value), exception_state);
- return;
- } else if (name_lowercase.StartsWith("on")) {
- // TODO(jakubvrana): This requires TrustedScript in all attributes starting
- // with "on", including e.g. "one". We use this pattern elsewhere (e.g. in
- // IsEventHandlerAttribute) but it's not ideal. Consider using the event
- // attribute of the resulting AttributeTriggers.
- String attr_value = GetStringFromSpecificTrustedType(
- string_or_TT, SpecificTrustedType::kTrustedScript, &GetDocument(),
- exception_state);
- if (!exception_state.HadException())
- setAttribute(name_lowercase, AtomicString(attr_value), exception_state);
+ if (!Document::IsValidName(local_name)) {
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kInvalidCharacterError,
+ "'" + local_name + "' is not a valid attribute name.");
return;
}
- AtomicString value_string =
- AtomicString(GetStringFromTrustedTypeWithoutCheck(string_or_TT));
- setAttribute(name_lowercase, value_string, exception_state);
+
+ SynchronizeAttribute(local_name);
+ wtf_size_t index;
+ QualifiedName q_name = QualifiedName::Null();
+ std::tie(index, q_name) = LookupAttributeQNameInternal(local_name);
+ String value = GetStringFromSpecificTrustedType(
+ string_or_TT, ExpectedTrustedTypeForAttribute(q_name), &GetDocument(),
+ exception_state);
+ if (exception_state.HadException())
+ return;
+ SetAttributeInternal(index, q_name, AtomicString(value),
+ kNotInSynchronizationOfLazyAttribute);
}
const AttrNameToTrustedType& Element::GetCheckedAttributeTypes() const {
@@ -1676,6 +1697,35 @@ const AttrNameToTrustedType& Element::GetCheckedAttributeTypes() const {
return attribute_map;
}
+SpecificTrustedType Element::ExpectedTrustedTypeForAttribute(
+ const QualifiedName& q_name) const {
+ // There are only a handful of namespaced attributes we care about
+ // (xlink:href), and all of those have identical Trusted Types
+ // properties to their namespace-less counterpart. So we check whether this
+ // is one of SVG's 'known' attributes, and if so just check the local
+ // name part as usual.
+ if (!q_name.NamespaceURI().IsNull() &&
+ !SVGAnimatedHref::IsKnownAttribute(q_name)) {
+ return SpecificTrustedType::kNone;
+ }
+
+ const AttrNameToTrustedType* attribute_types = &GetCheckedAttributeTypes();
+ AttrNameToTrustedType::const_iterator iter =
+ attribute_types->find(q_name.LocalName());
+ if (iter != attribute_types->end())
+ return iter->value;
+
+ if (q_name.LocalName().StartsWith("on")) {
+ // TODO(jakubvrana): This requires TrustedScript in all attributes
+ // starting with "on", including e.g. "one". We use this pattern elsewhere
+ // (e.g. in IsEventHandlerAttribute) but it's not ideal. Consider using
+ // the event attribute of the resulting AttributeTriggers.
+ return SpecificTrustedType::kTrustedScript;
+ }
+
+ return SpecificTrustedType::kNone;
+}
+
void Element::setAttribute(const QualifiedName& name,
const StringOrTrustedHTML& stringOrHTML,
ExceptionState& exception_state) {
@@ -2196,29 +2246,49 @@ void Element::RemovedFrom(ContainerNode& insertion_point) {
void Element::AttachLayoutTree(AttachContext& context) {
DCHECK(GetDocument().InStyleRecalc());
- ComputedStyle* style = MutableComputedStyle();
- if ((!style || style->IsEnsuredInDisplayNone()) &&
- !ChildNeedsReattachLayoutTree()) {
+ const ComputedStyle* style = GetComputedStyle();
+ bool being_rendered =
+ context.parent && style && !style->IsEnsuredInDisplayNone();
+ if (!being_rendered && !ChildNeedsReattachLayoutTree()) {
Node::AttachLayoutTree(context);
return;
}
AttachContext children_context(context);
-
- if (style && CanParticipateInFlatTree()) {
- // If an element requires forced legacy layout, all descendants need it too.
- if (ShouldForceLegacyLayout())
- children_context.force_legacy_layout = true;
- LegacyLayout legacy = children_context.force_legacy_layout
- ? LegacyLayout::kForce
- : LegacyLayout::kAuto;
- LayoutTreeBuilderForElement builder(*this, style);
- builder.CreateLayoutObjectIfNeeded(legacy);
+ LayoutObject* layout_object = nullptr;
+ if (CanParticipateInFlatTree()) {
+ if (being_rendered) {
+ // If an element requires forced legacy layout, all descendants need it
+ // too.
+ if (ShouldForceLegacyLayout())
+ children_context.force_legacy_layout = true;
+ LegacyLayout legacy = children_context.force_legacy_layout
+ ? LegacyLayout::kForce
+ : LegacyLayout::kAuto;
+ LayoutTreeBuilderForElement builder(*this, context, style, legacy);
+ builder.CreateLayoutObject();
+
+ layout_object = GetLayoutObject();
+ if (layout_object) {
+ children_context.previous_in_flow = nullptr;
+ children_context.parent = layout_object;
+ children_context.next_sibling = nullptr;
+ children_context.next_sibling_valid = true;
+ } else if (style->Display() != EDisplay::kContents) {
+ // The layout object creation was suppressed for other reasons than
+ // being display:none or display:contents (E.g.
+ // LayoutObject::CanHaveChildren() returning false). Make sure we don't
+ // attempt to create LayoutObjects further down the subtree.
+ children_context.parent = nullptr;
+ }
+ // For display:contents elements, we keep the previous_in_flow,
+ // next_sibling, and parent, in the context for attaching children.
+ } else {
+ // We are a display:none element. Set the parent to nullptr to make sure
+ // we never create any child layout boxes.
+ children_context.parent = nullptr;
+ }
}
-
- LayoutObject* layout_object = GetLayoutObject();
- if (layout_object)
- children_context.previous_in_flow = nullptr;
children_context.use_previous_in_flow = true;
AttachPseudoElement(kPseudoIdBefore, children_context);
@@ -2249,15 +2319,15 @@ void Element::AttachLayoutTree(AttachContext& context) {
display_lock_context->DidAttachLayoutTree();
}
-void Element::DetachLayoutTree(const AttachContext& context) {
+void Element::DetachLayoutTree(bool performing_reattach) {
HTMLFrameOwnerElement::PluginDisposeSuspendScope suspend_plugin_dispose;
if (HasRareData()) {
ElementRareData* data = GetElementRareData();
- if (!context.performing_reattach)
+ if (!performing_reattach)
data->ClearPseudoElements();
if (ElementAnimations* element_animations = data->GetElementAnimations()) {
- if (context.performing_reattach) {
+ if (performing_reattach) {
// FIXME: We call detach from within style recalc, so compositingState
// is not up to date.
// https://code.google.com/p/chromium/issues/detail?id=339847
@@ -2274,29 +2344,38 @@ void Element::DetachLayoutTree(const AttachContext& context) {
}
}
- DetachPseudoElement(kPseudoIdBefore, context);
+ DetachPseudoElement(kPseudoIdBefore, performing_reattach);
- if (ChildNeedsReattachLayoutTree() || GetComputedStyle()) {
+ // TODO(futhark): We need to traverse into IsUserActionElement() subtrees,
+ // even if they are already display:none because we do not clear the
+ // hovered/active bits as part of style recalc, but wait until the next time
+ // we do a hit test. That means we could be doing a forced layout tree update
+ // making a hovered subtree display:none and immediately remove the subtree
+ // leaving stale hovered/active state on ancestors. See relevant issues:
+ // https://crbug.com/967548
+ // https://crbug.com/939769
+ if (ChildNeedsReattachLayoutTree() || GetComputedStyle() ||
+ (!performing_reattach && IsUserActionElement())) {
if (ShadowRoot* shadow_root = GetShadowRoot()) {
- shadow_root->DetachLayoutTree(context);
- Node::DetachLayoutTree(context);
+ shadow_root->DetachLayoutTree(performing_reattach);
+ Node::DetachLayoutTree(performing_reattach);
} else {
- ContainerNode::DetachLayoutTree(context);
+ ContainerNode::DetachLayoutTree(performing_reattach);
}
} else {
- Node::DetachLayoutTree(context);
+ Node::DetachLayoutTree(performing_reattach);
}
- DetachPseudoElement(kPseudoIdAfter, context);
- DetachPseudoElement(kPseudoIdBackdrop, context);
- DetachPseudoElement(kPseudoIdFirstLetter, context);
+ DetachPseudoElement(kPseudoIdAfter, performing_reattach);
+ DetachPseudoElement(kPseudoIdBackdrop, performing_reattach);
+ DetachPseudoElement(kPseudoIdFirstLetter, performing_reattach);
- if (!context.performing_reattach) {
+ if (!performing_reattach) {
UpdateCallbackSelectors(GetComputedStyle(), nullptr);
SetComputedStyle(nullptr);
}
- if (!context.performing_reattach && IsUserActionElement()) {
+ if (!performing_reattach && IsUserActionElement()) {
if (IsHovered())
GetDocument().HoveredElementDetached(*this);
if (InActiveChain())
@@ -2613,16 +2692,16 @@ void Element::RebuildLayoutTree(WhitespaceAttacher& whitespace_attacher) {
if (NeedsReattachLayoutTree()) {
AttachContext reattach_context;
- if (const Node* parent = LayoutTreeBuilderTraversal::LayoutParent(*this)) {
- const LayoutObject* parent_object = parent->GetLayoutObject();
- if (parent_object && parent_object->ForceLegacyLayout())
- reattach_context.force_legacy_layout = true;
- }
+ reattach_context.parent =
+ LayoutTreeBuilderTraversal::ParentLayoutObject(*this);
+ if (reattach_context.parent && reattach_context.parent->ForceLegacyLayout())
+ reattach_context.force_legacy_layout = true;
ReattachLayoutTree(reattach_context);
whitespace_attacher.DidReattachElement(this,
reattach_context.previous_in_flow);
- } else {
- DCHECK(!StyleRecalcBlockedByDisplayLock(DisplayLockContext::kChildren));
+ } else if (!StyleRecalcBlockedByDisplayLock(DisplayLockContext::kChildren)) {
+ // TODO(crbug.com/972752): Make the condition above a DCHECK instead when
+ // style recalc and dirty bit propagation uses flat-tree traversal.
// We create a local WhitespaceAttacher when rebuilding children of an
// element with a LayoutObject since whitespace nodes do not rely on layout
// objects further up the tree. Also, if this Element's layout object is an
@@ -2656,7 +2735,8 @@ void Element::RebuildLayoutTree(WhitespaceAttacher& whitespace_attacher) {
DCHECK(!ChildNeedsStyleRecalc() ||
StyleRecalcBlockedByDisplayLock(DisplayLockContext::kChildren));
DCHECK(!NeedsReattachLayoutTree());
- DCHECK(!ChildNeedsReattachLayoutTree());
+ DCHECK(!ChildNeedsReattachLayoutTree() ||
+ StyleRecalcBlockedByDisplayLock(DisplayLockContext::kChildren));
}
void Element::RebuildShadowRootLayoutTree(
@@ -2664,7 +2744,6 @@ void Element::RebuildShadowRootLayoutTree(
DCHECK(IsShadowHost(this));
ShadowRoot* root = GetShadowRoot();
root->RebuildLayoutTree(whitespace_attacher);
- RebuildNonDistributedChildren();
}
void Element::RebuildPseudoElementLayoutTree(
@@ -3249,14 +3328,17 @@ void Element::setAttributeNS(
const StringOrTrustedHTMLOrTrustedScriptOrTrustedScriptURLOrTrustedURL&
string_or_TT,
ExceptionState& exception_state) {
- String value =
- GetStringFromTrustedType(string_or_TT, &GetDocument(), exception_state);
- if (exception_state.HadException())
- return;
QualifiedName parsed_name = g_any_name;
if (!ParseAttributeName(parsed_name, namespace_uri, qualified_name,
exception_state))
return;
+
+ String value = GetStringFromSpecificTrustedType(
+ string_or_TT, ExpectedTrustedTypeForAttribute(parsed_name),
+ &GetDocument(), exception_state);
+ if (exception_state.HadException())
+ return;
+
setAttribute(parsed_name, AtomicString(value));
}
@@ -3674,6 +3756,15 @@ void Element::UpdateForceLegacyLayout(const ComputedStyle& new_style,
// forced legacy layout in the ancestry, e.g. if this element no longer
// establishes a new formatting context.
ForceLegacyLayoutInFormattingContext(new_style);
+
+ // If we're inside an NG fragmentation context, we also need the entire
+ // fragmentation context to fall back to legacy layout. Note that once this
+ // has happened, the fragmentation context will be locked to legacy layout,
+ // even if all the reasons for requiring it in the first place disappear
+ // (e.g. if the only reason was a table, and that table is removed, we'll
+ // still be using legacy layout).
+ if (new_style.InsideNGFragmentationContext())
+ ForceLegacyLayoutInFragmentationContext(new_style);
} else if (old_force) {
// TODO(mstensho): If we have ancestors that got legacy layout just because
// of this child, we should clean it up, and switch the subtree back to NG,
@@ -3689,7 +3780,8 @@ void Element::ForceLegacyLayoutInFormattingContext(
bool found_bfc = false;
for (Element* ancestor = this; !found_bfc;) {
- ancestor = ToElementOrNull(LayoutTreeBuilderTraversal::Parent(*ancestor));
+ ancestor =
+ DynamicTo<Element>(LayoutTreeBuilderTraversal::Parent(*ancestor));
if (!ancestor || ancestor->ShouldForceLegacyLayout())
break;
const ComputedStyle* style = ancestor->GetComputedStyle();
@@ -3701,6 +3793,38 @@ void Element::ForceLegacyLayoutInFormattingContext(
}
}
+void Element::ForceLegacyLayoutInFragmentationContext(
+ const ComputedStyle& new_style) {
+ // This element cannot be laid out natively by LayoutNG. We now need to switch
+ // all enclosing block fragmentation contexts over to using legacy
+ // layout. Find the element that establishes the fragmentation context, and
+ // switch it over to legacy layout. Note that we walk the parent chain here,
+ // and not the containing block chain. This means that we may get false
+ // positives; e.g. if there's an absolutely positioned table, whose containing
+ // block of the table is on the outside of the fragmentation context, we're
+ // still going to fall back to legacy.
+ Element* parent;
+ for (Element* walker = this; walker; walker = parent) {
+ parent = DynamicTo<Element>(LayoutTreeBuilderTraversal::Parent(*walker));
+ if (!walker->GetComputedStyle()->SpecifiesColumns())
+ continue;
+
+ // Found an element that establishes a fragmentation context. Force it to do
+ // legacy layout. Keep looking for outer fragmentation contexts, since we
+ // need to force them over to legacy as well.
+ walker->SetShouldForceLegacyLayoutForChild(true);
+ walker->SetNeedsReattachLayoutTree();
+ if (parent && !parent->GetComputedStyle()->InsideNGFragmentationContext())
+ return;
+ }
+ DCHECK(GetDocument().Printing());
+ // Force legacy layout on the entire document, since we're printing, and
+ // there's some fragmentable box that needs legacy layout inside somewhere.
+ Element* root = GetDocument().documentElement();
+ root->SetShouldForceLegacyLayoutForChild(true);
+ root->SetNeedsReattachLayoutTree();
+}
+
bool Element::IsFocusedElementInDocument() const {
return this == GetDocument().FocusedElement();
}
@@ -3863,7 +3987,7 @@ Node* Element::InsertAdjacent(const String& where,
ExceptionState& exception_state) {
if (DeprecatedEqualIgnoringCase(where, "beforeBegin")) {
if (ContainerNode* parent = parentNode()) {
- parent->InsertBefore(new_child, this, exception_state);
+ parent->insertBefore(new_child, this, exception_state);
if (!exception_state.HadException())
return new_child;
}
@@ -3871,18 +3995,18 @@ Node* Element::InsertAdjacent(const String& where,
}
if (DeprecatedEqualIgnoringCase(where, "afterBegin")) {
- InsertBefore(new_child, firstChild(), exception_state);
+ insertBefore(new_child, firstChild(), exception_state);
return exception_state.HadException() ? nullptr : new_child;
}
if (DeprecatedEqualIgnoringCase(where, "beforeEnd")) {
- AppendChild(new_child, exception_state);
+ appendChild(new_child, exception_state);
return exception_state.HadException() ? nullptr : new_child;
}
if (DeprecatedEqualIgnoringCase(where, "afterEnd")) {
if (ContainerNode* parent = parentNode()) {
- parent->InsertBefore(new_child, nextSibling(), exception_state);
+ parent->insertBefore(new_child, nextSibling(), exception_state);
if (!exception_state.HadException())
return new_child;
}
@@ -4141,12 +4265,8 @@ const ComputedStyle* Element::EnsureComputedStyle(
if (PseudoElement* element = GetPseudoElement(pseudo_element_specifier))
return element->EnsureComputedStyle();
- if (!InActiveDocument()) {
- // FIXME: Try to do better than this. Ensure that styleForElement() works
- // for elements that are not in the document tree and figure out when to
- // destroy the computed style for such elements.
+ if (!InActiveDocument())
return nullptr;
- }
// EnsureComputedStyle is expected to be called to forcibly compute style for
// elements in display:none subtrees on otherwise style-clean documents. If
@@ -4169,17 +4289,11 @@ const ComputedStyle* Element::EnsureComputedStyle(
// 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
// values returned for the ":selection" pseudo-element will be correct.
- ComputedStyle* element_style = MutableComputedStyle();
+ const ComputedStyle* element_style = GetComputedStyle();
if (!element_style) {
if (CanParticipateInFlatTree()) {
- ContainerNode* parent = LayoutTreeBuilderTraversal::Parent(*this);
- if (parent)
+ if (ContainerNode* parent = LayoutTreeBuilderTraversal::Parent(*this))
parent->EnsureComputedStyle();
-
- ContainerNode* layout_parent =
- parent ? LayoutTreeBuilderTraversal::LayoutParent(*this) : nullptr;
- if (layout_parent)
- layout_parent->EnsureComputedStyle();
}
scoped_refptr<ComputedStyle> new_style = nullptr;
// TODO(crbug.com/953707): Avoid setting inline style during
@@ -4189,7 +4303,7 @@ const ComputedStyle* Element::EnsureComputedStyle(
else
new_style = OriginalStyleForLayoutObject();
element_style = new_style.get();
- element_style->SetIsEnsuredInDisplayNone();
+ new_style->SetIsEnsuredInDisplayNone();
SetComputedStyle(std::move(new_style));
}
@@ -4349,7 +4463,10 @@ void Element::UpdateFirstLetterPseudoElement(StyleUpdatePhase phase) {
}
StyleRecalcChange change(StyleRecalcChange::kRecalcDescendants);
- if (text_node_changed)
+ // Remaining text part should be next to first-letter pseudo element.
+ // See http://crbug.com/984389 for details.
+ if (text_node_changed || remaining_text_layout_object->PreviousSibling() !=
+ element->GetLayoutObject())
change = change.ForceReattachLayoutTree();
element->RecalcStyle(change);
@@ -4404,7 +4521,14 @@ PseudoElement* Element::CreatePseudoElementIfNeeded(PseudoId pseudo_id) {
if (pseudo_id == kPseudoIdBackdrop)
GetDocument().AddToTopLayer(pseudo_element, this);
- pseudo_element->SetComputedStyle(std::move(pseudo_style));
+ pseudo_element->SetComputedStyle(pseudo_style);
+
+ // Most pseudo elements get their style calculated upon insertion, which means
+ // that we don't get to RecalcOwnStyle() (regular DOM nodes do get there,
+ // since their style isn't calculated directly upon insertion). Need to check
+ // now if the element requires legacy layout.
+ if (RuntimeEnabledFeatures::LayoutNGEnabled())
+ pseudo_element->UpdateForceLegacyLayout(*pseudo_style, nullptr);
probe::PseudoElementCreated(pseudo_element);
@@ -4417,9 +4541,9 @@ void Element::AttachPseudoElement(PseudoId pseudo_id, AttachContext& context) {
}
void Element::DetachPseudoElement(PseudoId pseudo_id,
- const AttachContext& context) {
+ bool performing_reattach) {
if (PseudoElement* pseudo_element = GetPseudoElement(pseudo_id))
- pseudo_element->DetachLayoutTree(context);
+ pseudo_element->DetachLayoutTree(performing_reattach);
}
PseudoElement* Element::GetPseudoElement(PseudoId pseudo_id) const {
@@ -4434,9 +4558,8 @@ LayoutObject* Element::PseudoElementLayoutObject(PseudoId pseudo_id) const {
}
const ComputedStyle* Element::CachedStyleForPseudoElement(
- const PseudoStyleRequest& request,
- const ComputedStyle* parent_style) {
- ComputedStyle* style = MutableComputedStyle();
+ const PseudoStyleRequest& request) {
+ const ComputedStyle* style = GetComputedStyle();
if (!style || (request.pseudo_id < kFirstInternalPseudoId &&
!style->HasPseudoStyle(request.pseudo_id))) {
@@ -4447,8 +4570,7 @@ const ComputedStyle* Element::CachedStyleForPseudoElement(
style->GetCachedPseudoStyle(request.pseudo_id))
return cached;
- scoped_refptr<ComputedStyle> result =
- StyleForPseudoElement(request, parent_style);
+ scoped_refptr<ComputedStyle> result = StyleForPseudoElement(request, style);
if (result)
return style->AddCachedPseudoStyle(std::move(result));
return nullptr;
@@ -5286,8 +5408,8 @@ void Element::SetInlineStyleProperty(CSSPropertyID property_id,
double value,
CSSPrimitiveValue::UnitType unit,
bool important) {
- SetInlineStyleProperty(property_id, *CSSPrimitiveValue::Create(value, unit),
- important);
+ SetInlineStyleProperty(
+ property_id, *CSSNumericLiteralValue::Create(value, unit), important);
}
void Element::SetInlineStyleProperty(CSSPropertyID property_id,
@@ -5364,7 +5486,7 @@ void Element::AddPropertyToPresentationAttributeStyle(
double value,
CSSPrimitiveValue::UnitType unit) {
DCHECK(IsStyledElement());
- style->SetProperty(property_id, *CSSPrimitiveValue::Create(value, unit));
+ style->SetProperty(property_id, *CSSNumericLiteralValue::Create(value, unit));
}
void Element::AddPropertyToPresentationAttributeStyle(
@@ -5504,4 +5626,61 @@ bool Element::StyleRecalcBlockedByDisplayLock(
return context && !context->ShouldStyle(target);
}
+void Element::SetHovered(bool hovered) {
+ if (hovered == IsHovered())
+ return;
+
+ GetDocument().UserActionElements().SetHovered(this, hovered);
+
+ const ComputedStyle* style = GetComputedStyle();
+ if (!style || style->AffectedByHover()) {
+ StyleChangeType change_type = kLocalStyleChange;
+ if (style && style->HasPseudoStyle(kPseudoIdFirstLetter))
+ change_type = kSubtreeStyleChange;
+ SetNeedsStyleRecalc(change_type,
+ StyleChangeReasonForTracing::CreateWithExtraData(
+ style_change_reason::kPseudoClass,
+ style_change_extra_data::g_hover));
+ }
+ if (ChildrenOrSiblingsAffectedByHover())
+ PseudoStateChanged(CSSSelector::kPseudoHover);
+
+ if (LayoutObject* layout_object = GetLayoutObject())
+ layout_object->InvalidateIfControlStateChanged(kHoverControlState);
+}
+
+void Element::SetActive(bool active) {
+ if (active == IsActive())
+ return;
+
+ GetDocument().UserActionElements().SetActive(this, active);
+
+ if (!GetLayoutObject()) {
+ if (ChildrenOrSiblingsAffectedByActive()) {
+ PseudoStateChanged(CSSSelector::kPseudoActive);
+ } else {
+ SetNeedsStyleRecalc(kLocalStyleChange,
+ StyleChangeReasonForTracing::CreateWithExtraData(
+ style_change_reason::kPseudoClass,
+ style_change_extra_data::g_active));
+ }
+ return;
+ }
+
+ if (GetComputedStyle()->AffectedByActive()) {
+ StyleChangeType change_type =
+ GetComputedStyle()->HasPseudoStyle(kPseudoIdFirstLetter)
+ ? kSubtreeStyleChange
+ : kLocalStyleChange;
+ SetNeedsStyleRecalc(change_type,
+ StyleChangeReasonForTracing::CreateWithExtraData(
+ style_change_reason::kPseudoClass,
+ style_change_extra_data::g_active));
+ }
+ if (ChildrenOrSiblingsAffectedByActive())
+ PseudoStateChanged(CSSSelector::kPseudoActive);
+
+ GetLayoutObject()->InvalidateIfControlStateChanged(kPressedControlState);
+}
+
} // 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 8184c7e26de..717778454d4 100644
--- a/chromium/third_party/blink/renderer/core/dom/element.h
+++ b/chromium/third_party/blink/renderer/core/dom/element.h
@@ -27,6 +27,7 @@
#include "third_party/blink/public/platform/web_focus_type.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
+#include "third_party/blink/renderer/core/animation/animatable.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_selector.h"
@@ -153,7 +154,7 @@ typedef HeapVector<Member<Attr>> AttrNodeList;
typedef HashMap<AtomicString, SpecificTrustedType> AttrNameToTrustedType;
-class CORE_EXPORT Element : public ContainerNode {
+class CORE_EXPORT Element : public ContainerNode, public Animatable {
DEFINE_WRAPPERTYPEINFO();
public:
@@ -161,6 +162,9 @@ class CORE_EXPORT Element : public ContainerNode {
Element(const QualifiedName& tag_name, Document*, ConstructionType);
+ // Animatable implementation.
+ Element* GetAnimationTarget() override;
+
DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecopy, kBeforecopy)
DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecut, kBeforecut)
DEFINE_ATTRIBUTE_EVENT_LISTENER(beforepaste, kBeforepaste)
@@ -508,7 +512,7 @@ class CORE_EXPORT Element : public ContainerNode {
CloneChildrenFlag) {}
void AttachLayoutTree(AttachContext&) override;
- void DetachLayoutTree(const AttachContext& = AttachContext()) override;
+ void DetachLayoutTree(bool performing_reattach = false) override;
virtual LayoutObject* CreateLayoutObject(const ComputedStyle&, LegacyLayout);
virtual bool LayoutObjectIsNeeded(const ComputedStyle&) const;
@@ -731,9 +735,7 @@ class CORE_EXPORT Element : public ContainerNode {
PseudoElement* GetPseudoElement(PseudoId) const;
LayoutObject* PseudoElementLayoutObject(PseudoId) const;
- const ComputedStyle* CachedStyleForPseudoElement(
- const PseudoStyleRequest&,
- const ComputedStyle* parent_style = nullptr);
+ const ComputedStyle* CachedStyleForPseudoElement(const PseudoStyleRequest&);
scoped_refptr<ComputedStyle> StyleForPseudoElement(
const PseudoStyleRequest&,
const ComputedStyle* parent_style = nullptr);
@@ -912,6 +914,9 @@ class CORE_EXPORT Element : public ContainerNode {
void ActivateDisplayLockIfNeeded();
+ virtual void SetActive(bool active);
+ virtual void SetHovered(bool hovered);
+
protected:
const ElementData* GetElementData() const { return element_data_.Get(); }
UniqueElementData& EnsureUniqueElementData();
@@ -1029,7 +1034,7 @@ class CORE_EXPORT Element : public ContainerNode {
inline PseudoElement* CreatePseudoElementIfNeeded(PseudoId);
void AttachPseudoElement(PseudoId, AttachContext&);
- void DetachPseudoElement(PseudoId, const AttachContext&);
+ void DetachPseudoElement(PseudoId, bool performing_reattach);
ShadowRoot& CreateAndAttachShadowRoot(ShadowRootType);
@@ -1075,6 +1080,10 @@ class CORE_EXPORT Element : public ContainerNode {
SynchronizationOfLazyAttribute);
void RemoveAttributeInternal(wtf_size_t index,
SynchronizationOfLazyAttribute);
+ std::pair<wtf_size_t, const QualifiedName> LookupAttributeQNameInternal(
+ const AtomicString& local_name) const;
+ SpecificTrustedType ExpectedTrustedTypeForAttribute(
+ const QualifiedName&) const;
void CancelFocusAppearanceUpdate();
@@ -1163,6 +1172,12 @@ class CORE_EXPORT Element : public ContainerNode {
// within a formatting context.
void ForceLegacyLayoutInFormattingContext(const ComputedStyle& new_style);
+ // If this element requires legacy layout, and we're inside a fragmentation
+ // context, we need to force legacy layout for the entire fragmentation
+ // context. LayoutNG block fragmentation and legacy block fragmentation cannot
+ // cooperate within a fragmentation context.
+ void ForceLegacyLayoutInFragmentationContext(const ComputedStyle& new_style);
+
Member<ElementData> element_data_;
};
@@ -1209,59 +1224,19 @@ inline const T* ToElement(const Node* node) {
return static_cast<const T*>(node);
}
-template <typename T>
-inline T* ToElementOrNull(Node& node) {
- return IsElementOfType<const T>(node) ? static_cast<T*>(&node) : nullptr;
-}
-template <typename T>
-inline T* ToElementOrNull(Node* node) {
- return (node && IsElementOfType<const T>(*node)) ? static_cast<T*>(node)
- : nullptr;
-}
-template <typename T>
-inline const T* ToElementOrNull(const Node& node) {
- return IsElementOfType<const T>(node) ? static_cast<const T*>(&node)
- : nullptr;
-}
-template <typename T>
-inline const T* ToElementOrNull(const Node* node) {
- return (node && IsElementOfType<const T>(*node)) ? static_cast<const T*>(node)
- : nullptr;
-}
-
-template <typename T>
-inline T& ToElementOrDie(Node& node) {
- CHECK(IsElementOfType<const T>(node));
- return static_cast<T&>(node);
-}
-template <typename T>
-inline T* ToElementOrDie(Node* node) {
- CHECK(!node || IsElementOfType<const T>(*node));
- return static_cast<T*>(node);
-}
-template <typename T>
-inline const T& ToElementOrDie(const Node& node) {
- CHECK(IsElementOfType<const T>(node));
- return static_cast<const T&>(node);
-}
-template <typename T>
-inline const T* ToElementOrDie(const Node* node) {
- CHECK(!node || IsElementOfType<const T>(*node));
- return static_cast<const T*>(node);
-}
-
inline bool IsDisabledFormControl(const Node* node) {
- return node->IsElementNode() && ToElement(node)->IsDisabledFormControl();
+ auto* element = DynamicTo<Element>(node);
+ return element && element->IsDisabledFormControl();
}
inline Element* Node::parentElement() const {
- ContainerNode* parent = parentNode();
- return parent && parent->IsElementNode() ? ToElement(parent) : nullptr;
+ return DynamicTo<Element>(parentNode());
}
inline bool Element::FastHasAttribute(const QualifiedName& name) const {
#if DCHECK_IS_ON()
- DCHECK(FastAttributeLookupAllowed(name));
+ DCHECK(FastAttributeLookupAllowed(name))
+ << TagQName().ToString().Utf8() << "/@" << name.ToString().Utf8();
#endif
return GetElementData() &&
GetElementData()->Attributes().FindIndex(name) != kNotFound;
@@ -1270,7 +1245,8 @@ inline bool Element::FastHasAttribute(const QualifiedName& name) const {
inline const AtomicString& Element::FastGetAttribute(
const QualifiedName& name) const {
#if DCHECK_IS_ON()
- DCHECK(FastAttributeLookupAllowed(name));
+ DCHECK(FastAttributeLookupAllowed(name))
+ << TagQName().ToString().Utf8() << "/@" << name.ToString().Utf8();
#endif
if (GetElementData()) {
if (const Attribute* attribute = GetElementData()->Attributes().Find(name))
diff --git a/chromium/third_party/blink/renderer/core/dom/element.idl b/chromium/third_party/blink/renderer/core/dom/element.idl
index e133a964519..a6ea0464c71 100644
--- a/chromium/third_party/blink/renderer/core/dom/element.idl
+++ b/chromium/third_party/blink/renderer/core/dom/element.idl
@@ -26,7 +26,9 @@ callback ScrollStateCallback = void (ScrollState scrollState);
// https://dom.spec.whatwg.org/#interface-element
-interface Element : Node {
+[
+ Exposed=Window
+] interface Element : Node {
readonly attribute DOMString? namespaceURI;
readonly attribute DOMString? prefix;
readonly attribute DOMString localName;
@@ -55,7 +57,7 @@ interface Element : Node {
[CEReactions, CustomElementCallbacks] void removeAttributeNS(DOMString? namespaceURI, DOMString localName);
[Affects=Nothing] boolean hasAttribute(DOMString name);
[Affects=Nothing] boolean hasAttributeNS(DOMString? namespaceURI, DOMString localName);
- [RaisesException] boolean toggleAttribute(DOMString qualifiedName, optional boolean force);
+ [RaisesException, CEReactions, CustomElementCallbacks] boolean toggleAttribute(DOMString qualifiedName, optional boolean force);
Attr? getAttributeNode(DOMString name);
Attr? getAttributeNodeNS(DOMString? namespaceURI, DOMString localName);
@@ -142,6 +144,9 @@ interface Element : Node {
// Display locking. Returns a display lock context.
[RuntimeEnabled=DisplayLocking, ImplementedAs=getDisplayLockForBindings] readonly attribute DisplayLockContext displayLock;
+
+ // Element Timing
+ [RuntimeEnabled=ElementTiming, Affects=Nothing, CEReactions, Reflect=elementtiming] attribute DOMString elementTiming;
};
Element includes ParentNode;
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 5838d93c248..9c203350a96 100644
--- a/chromium/third_party/blink/renderer/core/dom/element_traversal.h
+++ b/chromium/third_party/blink/renderer/core/dom/element_traversal.h
@@ -31,7 +31,7 @@
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/dom/node_traversal.h"
#include "third_party/blink/renderer/core/dom/traversal_range.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -267,7 +267,7 @@ inline Element* Traversal<Element>::NextTemplate(NodeType& current) {
Node* node = NodeTraversal::Next(current);
while (node && !node->IsElementNode())
node = NodeTraversal::NextSkippingChildren(*node);
- return ToElement(node);
+ return To<Element>(node);
}
template <>
@@ -277,7 +277,7 @@ inline Element* Traversal<Element>::NextTemplate(NodeType& current,
Node* node = NodeTraversal::Next(current, stay_within);
while (node && !node->IsElementNode())
node = NodeTraversal::NextSkippingChildren(*node, stay_within);
- return ToElement(node);
+ return To<Element>(node);
}
// Generic versions.
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 9d9d41c7980..5539e59b0a6 100644
--- a/chromium/third_party/blink/renderer/core/dom/events/event.cc
+++ b/chromium/third_party/blink/renderer/core/dom/events/event.cc
@@ -34,11 +34,11 @@
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/frame/hosts_using_features.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/svg/svg_element.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/bindings/script_state.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
@@ -65,7 +65,7 @@ Event::Event() : Event("", Bubbles::kNo, Cancelable::kNo) {
Event::Event(const AtomicString& event_type,
Bubbles bubbles,
Cancelable cancelable,
- TimeTicks platform_time_stamp)
+ base::TimeTicks platform_time_stamp)
: Event(event_type,
bubbles,
cancelable,
@@ -80,13 +80,13 @@ Event::Event(const AtomicString& event_type,
bubbles,
cancelable,
composed_mode,
- CurrentTimeTicks()) {}
+ base::TimeTicks::Now()) {}
Event::Event(const AtomicString& event_type,
Bubbles bubbles,
Cancelable cancelable,
ComposedMode composed_mode,
- TimeTicks platform_time_stamp)
+ base::TimeTicks platform_time_stamp)
: type_(event_type),
bubbles_(bubbles == Bubbles::kYes),
cancelable_(cancelable == Cancelable::kYes),
@@ -109,7 +109,7 @@ Event::Event(const AtomicString& event_type,
Event::Event(const AtomicString& event_type,
const EventInit* initializer,
- TimeTicks platform_time_stamp)
+ base::TimeTicks platform_time_stamp)
: Event(event_type,
initializer->bubbles() ? Bubbles::kYes : Bubbles::kNo,
initializer->cancelable() ? Cancelable::kYes : Cancelable::kNo,
@@ -245,7 +245,6 @@ bool Event::IsErrorEvent() const {
void Event::preventDefault() {
if (handling_passive_ != PassiveMode::kNotPassive &&
handling_passive_ != PassiveMode::kNotPassiveDefault) {
- prevent_default_called_during_passive_ = true;
const LocalDOMWindow* window =
event_path_ ? event_path_->GetWindowEventContext().Window() : nullptr;
@@ -312,7 +311,6 @@ HeapVector<Member<EventTarget>> Event::composedPath(
void Event::SetHandlingPassive(PassiveMode mode) {
handling_passive_ = mode;
- prevent_default_called_during_passive_ = false;
}
HeapVector<Member<EventTarget>> Event::PathInternal(ScriptState* script_state,
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 caf976462a7..2274afba283 100644
--- a/chromium/third_party/blink/renderer/core/dom/events/event.h
+++ b/chromium/third_party/blink/renderer/core/dom/events/event.h
@@ -111,20 +111,20 @@ class CORE_EXPORT Event : public ScriptWrappable {
Bubbles,
Cancelable,
ComposedMode,
- TimeTicks platform_time_stamp);
+ base::TimeTicks platform_time_stamp);
Event(const AtomicString& type,
Bubbles,
Cancelable,
- TimeTicks platform_time_stamp);
+ base::TimeTicks platform_time_stamp);
Event(const AtomicString& type,
Bubbles,
Cancelable,
ComposedMode = ComposedMode::kScoped);
Event(const AtomicString& type,
const EventInit*,
- TimeTicks platform_time_stamp);
+ base::TimeTicks platform_time_stamp);
Event(const AtomicString& type, const EventInit* init)
- : Event(type, init, CurrentTimeTicks()) {}
+ : Event(type, init, base::TimeTicks::Now()) {}
~Event() override;
void initEvent(const AtomicString& type, bool bubbles, bool cancelable);
@@ -185,7 +185,7 @@ class CORE_EXPORT Event : public ScriptWrappable {
// using the platform timestamp (see |platform_time_stamp_|).
// For more info see http://crbug.com/160524
double timeStamp(ScriptState*) const;
- TimeTicks PlatformTimeStamp() const { return platform_time_stamp_; }
+ base::TimeTicks PlatformTimeStamp() const { return platform_time_stamp_; }
void stopPropagation() { propagation_stopped_ = true; }
void SetStopPropagation(bool stop_propagation) {
@@ -279,10 +279,6 @@ class CORE_EXPORT Event : public ScriptWrappable {
void SetHandlingPassive(PassiveMode);
- bool PreventDefaultCalledDuringPassive() const {
- return prevent_default_called_during_passive_;
- }
-
bool PreventDefaultCalledOnUncancelableEvent() const {
return prevent_default_called_on_uncancelable_event_;
}
@@ -332,9 +328,6 @@ class CORE_EXPORT Event : public ScriptWrappable {
unsigned was_initialized_ : 1;
unsigned is_trusted_ : 1;
- // Whether preventDefault was called when |handling_passive_| is
- // true. This field is reset on each call to SetHandlingPassive.
- unsigned prevent_default_called_during_passive_ : 1;
// Whether preventDefault was called on uncancelable event.
unsigned prevent_default_called_on_uncancelable_event_ : 1;
@@ -356,7 +349,7 @@ class CORE_EXPORT Event : public ScriptWrappable {
// The monotonic platform time in seconds, for input events it is the
// event timestamp provided by the host OS and reported in the original
// WebInputEvent instance.
- TimeTicks platform_time_stamp_;
+ base::TimeTicks platform_time_stamp_;
};
#define DEFINE_EVENT_TYPE_CASTS(typeName) \
diff --git a/chromium/third_party/blink/renderer/core/dom/events/event_dispatch_forbidden_scope.h b/chromium/third_party/blink/renderer/core/dom/events/event_dispatch_forbidden_scope.h
index 4a5462c6b3a..b67041a3a34 100644
--- a/chromium/third_party/blink/renderer/core/dom/events/event_dispatch_forbidden_scope.h
+++ b/chromium/third_party/blink/renderer/core/dom/events/event_dispatch_forbidden_scope.h
@@ -8,7 +8,7 @@
#include "base/auto_reset.h"
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
#include "third_party/blink/renderer/platform/wtf/wtf.h"
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 385c6f11fc2..2274c0d6a9b 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
@@ -43,13 +43,13 @@
#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/frame/settings.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/html_element.h"
#include "third_party/blink/renderer/core/inspector/inspector_trace_events.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/page/spatial_navigation_controller.h"
#include "third_party/blink/renderer/core/timing/event_timing.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
@@ -103,12 +103,14 @@ void EventDispatcher::DispatchSimulatedClick(
underlying_event, creation_scope))
.Dispatch();
+ Element* element = DynamicTo<Element>(node);
if (mouse_event_options != kSendNoEvents) {
EventDispatcher(node, *MouseEvent::Create(event_type_names::kMousedown,
node.GetDocument().domWindow(),
underlying_event, creation_scope))
.Dispatch();
- node.SetActive(true);
+ if (element)
+ element->SetActive(true);
EventDispatcher(node, *MouseEvent::Create(event_type_names::kMouseup,
node.GetDocument().domWindow(),
underlying_event, creation_scope))
@@ -116,7 +118,8 @@ void EventDispatcher::DispatchSimulatedClick(
}
// Some elements (e.g. the color picker) may set active state to true before
// calling this method and expect the state to be reset during the call.
- node.SetActive(false);
+ if (element)
+ element->SetActive(false);
// always send click
EventDispatcher(node, *MouseEvent::Create(event_type_names::kClick,
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 5b28648253b..f03112113da 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
@@ -50,12 +50,12 @@
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/performance_monitor.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/probe/core_probes.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/v8_dom_activity_logger.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.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"
@@ -138,7 +138,7 @@ void ReportBlockedEvent(EventTarget& target,
" ms due to main thread being busy. "
"Consider marking event handler as 'passive' to make the page more "
"responsive.",
- event.type().GetString().Utf8().data(), delayed.InMilliseconds());
+ event.type().GetString().Utf8().c_str(), delayed.InMilliseconds());
PerformanceMonitor::ReportGenericViolation(
target.GetExecutionContext(), PerformanceMonitor::kBlockedEvent,
message_text, delayed, listener->GetSourceLocation(target));
@@ -377,7 +377,7 @@ void EventTarget::SetDefaultAddEventListenerOptions(
"Consider marking event handler as 'passive' to make the page more "
"responsive. See "
"https://www.chromestatus.com/feature/5745543795965952",
- event_type.GetString().Utf8().data());
+ event_type.GetString().Utf8().c_str());
PerformanceMonitor::ReportGenericViolation(
GetExecutionContext(), PerformanceMonitor::kDiscouragedAPIUse,
@@ -501,7 +501,7 @@ void EventTarget::AddedEventListener(
String message_text = String::Format(
"Added synchronous DOM mutation listener to a '%s' event. "
"Consider using MutationObserver to make the page more responsive.",
- event_type.GetString().Utf8().data());
+ event_type.GetString().Utf8().c_str());
PerformanceMonitor::ReportGenericViolation(
context, PerformanceMonitor::kDiscouragedAPIUse, message_text,
base::TimeDelta(), nullptr);
@@ -875,7 +875,7 @@ bool EventTarget::FireEventListeners(Event& event,
base::TimeTicks now;
bool should_report_blocked_event = false;
if (!blocked_event_threshold.is_zero()) {
- now = CurrentTimeTicks();
+ now = base::TimeTicks::Now();
should_report_blocked_event =
now - event.PlatformTimeStamp() > blocked_event_threshold;
}
@@ -906,7 +906,6 @@ bool EventTarget::FireEventListeners(Event& event,
break;
event.SetHandlingPassive(EventPassiveMode(registered_listener));
- bool passive_forced = registered_listener.PassiveForcedForDocumentTarget();
probe::UserCallback probe(context, nullptr, event.type(), false, this);
probe::AsyncTask async_task(context, listener, "event",
@@ -927,17 +926,6 @@ bool EventTarget::FireEventListeners(Event& event,
now - event.PlatformTimeStamp());
}
- if (passive_forced) {
- DEFINE_STATIC_LOCAL(EnumerationHistogram, passive_forced_histogram,
- ("Event.PassiveForcedEventDispatchCancelled",
- kPassiveForcedListenerResultTypeMax));
- PassiveForcedListenerResultType breakage_type = kPreventDefaultNotCalled;
- if (event.PreventDefaultCalledDuringPassive())
- breakage_type = kDocumentLevelTouchPreventDefaultCalled;
-
- passive_forced_histogram.Count(breakage_type);
- }
-
event.SetHandlingPassive(Event::PassiveMode::kNotPassive);
CHECK_LE(i, size);
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 cf6d623ab93..6b48c93b59a 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
@@ -44,7 +44,7 @@
#include "third_party/blink/renderer/core/event_type_names.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/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
namespace blink {
@@ -114,8 +114,6 @@ class CORE_EXPORT EventTargetData final
// or the document you're in.
// - Your trace() method will need to call EventTargetWithInlineData::trace
// depending on the base class of your class.
-// - EventTargets do not support EAGERLY_FINALIZE. You need to use
-// a pre-finalizer instead.
class CORE_EXPORT EventTarget : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
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 6f9250e3db7..b0247e27cc6 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
@@ -8,49 +8,12 @@
namespace blink {
-enum PassiveForcedListenerResultType {
- kPreventDefaultNotCalled,
- kDocumentLevelTouchPreventDefaultCalled
-};
-
class EventTargetTest : public RenderingTest {
public:
EventTargetTest() = default;
~EventTargetTest() override = default;
};
-TEST_F(EventTargetTest, PreventDefaultNotCalled) {
- GetDocument().GetSettings()->SetScriptEnabled(true);
- HistogramTester histogram_tester;
- GetDocument().GetFrame()->GetScriptController().ExecuteScriptInMainWorld(
- "window.addEventListener('touchstart', function(e) {}, {});"
- "window.dispatchEvent(new TouchEvent('touchstart', "
- "{cancelable: "
- "false}));");
-
- histogram_tester.ExpectTotalCount("Event.PassiveForcedEventDispatchCancelled",
- 1);
- histogram_tester.ExpectUniqueSample(
- "Event.PassiveForcedEventDispatchCancelled", kPreventDefaultNotCalled, 1);
-}
-
-TEST_F(EventTargetTest, PreventDefaultCalled) {
- GetDocument().GetSettings()->SetScriptEnabled(true);
- HistogramTester histogram_tester;
- GetDocument().GetFrame()->GetScriptController().ExecuteScriptInMainWorld(
- "window.addEventListener('touchstart', function(e) "
- "{e.preventDefault();}, {});"
- "window.dispatchEvent(new TouchEvent('touchstart', "
- "{cancelable: "
- "false}));");
-
- histogram_tester.ExpectTotalCount("Event.PassiveForcedEventDispatchCancelled",
- 1);
- histogram_tester.ExpectUniqueSample(
- "Event.PassiveForcedEventDispatchCancelled",
- kDocumentLevelTouchPreventDefaultCalled, 1);
-}
-
TEST_F(EventTargetTest, UseCountPassiveTouchEventListener) {
EXPECT_FALSE(
GetDocument().IsUseCounted(WebFeature::kPassiveTouchEventListener));
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 38c9b9e9085..a1e641f23ef 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
@@ -101,7 +101,7 @@ LayoutText* FirstLetterPseudoElement::FirstLetterTextLayoutObject(
LayoutObject* parent_layout_object = nullptr;
// If we are looking at a first letter element then we need to find the
- // first letter text layoutObject from the parent node, and not ourselves.
+ // first letter text LayoutObject from the parent node, and not ourselves.
if (element.IsFirstLetterPseudoElement()) {
parent_layout_object =
element.ParentOrShadowHostElement()->GetLayoutObject();
@@ -147,9 +147,16 @@ LayoutText* FirstLetterPseudoElement::FirstLetterTextLayoutObject(
first_letter_text_layout_object->NextSibling();
} else if (first_letter_text_layout_object->IsListMarker() ||
first_letter_text_layout_object == marker) {
- first_letter_text_layout_object =
- first_letter_text_layout_object->NextInPreOrderAfterChildren(
- parent_layout_object);
+ // The list item marker may have out-of-flow siblings inside an anonymous
+ // block. Skip them to make sure we leave the anonymous block before
+ // continuing looking for the first letter text.
+ do {
+ first_letter_text_layout_object =
+ first_letter_text_layout_object->NextInPreOrderAfterChildren(
+ parent_layout_object);
+ } while (
+ first_letter_text_layout_object &&
+ first_letter_text_layout_object->IsFloatingOrOutOfFlowPositioned());
} else if (first_letter_text_layout_object
->IsFloatingOrOutOfFlowPositioned()) {
if (first_letter_text_layout_object->Style()->StyleType() ==
@@ -261,11 +268,29 @@ void FirstLetterPseudoElement::ClearRemainingTextLayoutObject() {
void FirstLetterPseudoElement::AttachLayoutTree(AttachContext& context) {
LayoutText* first_letter_text =
FirstLetterPseudoElement::FirstLetterTextLayoutObject(*this);
- PseudoElement::AttachLayoutTree(context);
- AttachFirstLetterTextLayoutObjects(first_letter_text);
+ // The FirstLetterPseudoElement should have been removed in
+ // Element::UpdateFirstLetterPseudoElement(). However if there existed a first
+ // letter before updating it, the layout tree will be different after
+ // DetachLayoutTree() called right before this method.
+ // If there is a bug in FirstLetterTextLayoutObject(), we might end up with
+ // null here. DCHECKing here, but handling the null pointer below to avoid
+ // crashes.
+ DCHECK(first_letter_text);
+
+ AttachContext first_letter_context(context);
+ first_letter_context.next_sibling = first_letter_text;
+ first_letter_context.next_sibling_valid = true;
+ if (first_letter_text) {
+ first_letter_context.parent = first_letter_text->Parent();
+ if (first_letter_context.parent->ForceLegacyLayout())
+ first_letter_context.force_legacy_layout = true;
+ }
+ PseudoElement::AttachLayoutTree(first_letter_context);
+ if (first_letter_text)
+ AttachFirstLetterTextLayoutObjects(first_letter_text);
}
-void FirstLetterPseudoElement::DetachLayoutTree(const AttachContext& context) {
+void FirstLetterPseudoElement::DetachLayoutTree(bool performing_reattach) {
if (remaining_text_layout_object_) {
if (remaining_text_layout_object_->GetNode() && GetDocument().IsActive()) {
auto* text_node = To<Text>(remaining_text_layout_object_->GetNode());
@@ -277,7 +302,7 @@ void FirstLetterPseudoElement::DetachLayoutTree(const AttachContext& context) {
}
remaining_text_layout_object_ = nullptr;
- PseudoElement::DetachLayoutTree(context);
+ PseudoElement::DetachLayoutTree(performing_reattach);
}
scoped_refptr<ComputedStyle>
@@ -326,7 +351,7 @@ void FirstLetterPseudoElement::AttachFirstLetterTextLayoutObjects(LayoutText* fi
remaining_text->SetFirstLetterPseudoElement(this);
remaining_text->SetIsRemainingTextLayoutObject(true);
- remaining_text->SetStyle(first_letter_text->MutableStyle());
+ remaining_text->SetStyle(first_letter_text->Style());
if (remaining_text->GetNode())
remaining_text->GetNode()->SetLayoutObject(remaining_text);
@@ -337,7 +362,7 @@ void FirstLetterPseudoElement::AttachFirstLetterTextLayoutObjects(LayoutText* fi
GetLayoutObject()->Parent()->AddChild(remaining_text, next_sibling);
// Construct text fragment for the first letter.
- ComputedStyle* const letter_style = MutableComputedStyle();
+ const ComputedStyle* const letter_style = GetComputedStyle();
LayoutTextFragment* letter = LayoutTextFragment::CreateAnonymous(
*this, old_text.Impl(), 0, length, legacy_layout);
letter->SetFirstLetterPseudoElement(this);
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 8bd53ea60b8..4b6e05a9b1e 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
@@ -53,7 +53,7 @@ class CORE_EXPORT FirstLetterPseudoElement final : public PseudoElement {
void UpdateTextFragments();
void AttachLayoutTree(AttachContext&) override;
- void DetachLayoutTree(const AttachContext& = AttachContext()) override;
+ void DetachLayoutTree(bool performing_reattach) override;
Node* InnerNodeForHitTesting() const override;
private:
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 ac1ae4982d2..ee891dc7b70 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
@@ -40,9 +40,8 @@ void FlatTreeTraversal::AssertFlatTreeNodeDataUpdated(
int& assigned_nodes_in_slot_count,
int& nodes_which_have_assigned_slot_count) {
for (Node& node : NodeTraversal::StartsAt(root)) {
- if (node.IsElementNode()) {
- Element& element = ToElement(node);
- if (ShadowRoot* shadow_root = element.ShadowRootIfV1()) {
+ if (auto* element = DynamicTo<Element>(node)) {
+ if (ShadowRoot* shadow_root = element->ShadowRootIfV1()) {
DCHECK(!shadow_root->NeedsSlotAssignmentRecalc());
AssertFlatTreeNodeDataUpdated(*shadow_root,
assigned_nodes_in_slot_count,
@@ -174,15 +173,6 @@ Node* FlatTreeTraversal::TraverseSiblings(const Node& node,
Node* FlatTreeTraversal::TraverseSiblingsForV1HostChild(
const Node& node,
TraversalDirection direction) {
- if (!RuntimeEnabledFeatures::FastFlatTreeTraversalEnabled()) {
- HTMLSlotElement* slot = node.AssignedSlot();
- if (!slot)
- return nullptr;
- return direction == kTraversalDirectionForward
- ? slot->AssignedNodeNextTo(node)
- : slot->AssignedNodePreviousTo(node);
- }
-
ShadowRoot* shadow_root = node.ParentElementShadowRoot();
DCHECK(shadow_root);
if (!shadow_root->HasSlotAssignment()) {
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 d9e091bc3a9..4518f906cd6 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
@@ -34,7 +34,7 @@
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/dom/traversal_range.h"
#include "third_party/blink/renderer/core/dom/v0_insertion_point.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -207,8 +207,7 @@ inline ContainerNode* FlatTreeTraversal::Parent(
}
inline Element* FlatTreeTraversal::ParentElement(const Node& node) {
- ContainerNode* parent = FlatTreeTraversal::Parent(node);
- return parent && parent->IsElementNode() ? ToElement(parent) : nullptr;
+ return DynamicTo<Element>(FlatTreeTraversal::Parent(node));
}
inline Node* FlatTreeTraversal::NextSibling(const Node& node) {
diff --git a/chromium/third_party/blink/renderer/core/dom/flat_tree_traversal_test.cc b/chromium/third_party/blink/renderer/core/dom/flat_tree_traversal_test.cc
index 8abef861e81..718f61219e3 100644
--- a/chromium/third_party/blink/renderer/core/dom/flat_tree_traversal_test.cc
+++ b/chromium/third_party/blink/renderer/core/dom/flat_tree_traversal_test.cc
@@ -49,7 +49,7 @@ void FlatTreeTraversalTest::SetupSampleHTML(const char* main_html,
unsigned index) {
Element* body = GetDocument().body();
body->SetInnerHTMLFromString(String::FromUTF8(main_html));
- Element* shadow_host = ToElement(NodeTraversal::ChildAt(*body, index));
+ auto* shadow_host = To<Element>(NodeTraversal::ChildAt(*body, index));
ShadowRoot& shadow_root = shadow_host->CreateV0ShadowRootForTesting();
shadow_root.SetInnerHTMLFromString(String::FromUTF8(shadow_html));
body->UpdateDistributionForFlatTreeTraversal();
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 5d144bac016..37faa19ae42 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
@@ -4,9 +4,9 @@
#include "third_party/blink/renderer/core/dom/frame_request_callback_collection.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/inspector/inspector_trace_events.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
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 dff91f03f84..0d7d82f9389 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
@@ -31,7 +31,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_DOM_GLOBAL_EVENT_HANDLERS_H_
#include "third_party/blink/renderer/core/dom/events/event_target.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/dom/icon_url.h b/chromium/third_party/blink/renderer/core/dom/icon_url.h
index e7ddc039845..04f45144db5 100644
--- a/chromium/third_party/blink/renderer/core/dom/icon_url.h
+++ b/chromium/third_party/blink/renderer/core/dom/icon_url.h
@@ -33,7 +33,7 @@
#include "third_party/blink/renderer/platform/geometry/int_size.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/allocator/allocator.h"
namespace blink {
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 9a97ccb6251..49077ce43a3 100644
--- a/chromium/third_party/blink/renderer/core/dom/idle_deadline.cc
+++ b/chromium/third_party/blink/renderer/core/dom/idle_deadline.cc
@@ -11,14 +11,14 @@
namespace blink {
-IdleDeadline::IdleDeadline(TimeTicks deadline, CallbackType callback_type)
+IdleDeadline::IdleDeadline(base::TimeTicks deadline, CallbackType callback_type)
: deadline_(deadline),
callback_type_(callback_type),
clock_(base::DefaultTickClock::GetInstance()) {}
double IdleDeadline::timeRemaining() const {
- TimeDelta time_remaining = deadline_ - clock_->NowTicks();
- if (time_remaining < TimeDelta() ||
+ base::TimeDelta time_remaining = deadline_ - clock_->NowTicks();
+ if (time_remaining < base::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 23593a6a4d6..834c6eb22f0 100644
--- a/chromium/third_party/blink/renderer/core/dom/idle_deadline.h
+++ b/chromium/third_party/blink/renderer/core/dom/idle_deadline.h
@@ -28,7 +28,7 @@ class CORE_EXPORT IdleDeadline : public ScriptWrappable {
kMaxValue = kCalledByTimeout
};
- IdleDeadline(TimeTicks deadline, CallbackType);
+ IdleDeadline(base::TimeTicks deadline, CallbackType);
double timeRemaining() const;
@@ -41,7 +41,7 @@ class CORE_EXPORT IdleDeadline : public ScriptWrappable {
void SetTickClockForTesting(const base::TickClock* clock) { clock_ = clock; }
private:
- TimeTicks deadline_;
+ base::TimeTicks deadline_;
CallbackType callback_type_;
const base::TickClock* clock_;
};
diff --git a/chromium/third_party/blink/renderer/core/dom/idle_deadline.idl b/chromium/third_party/blink/renderer/core/dom/idle_deadline.idl
index 806691f49f4..d245dab9f6c 100644
--- a/chromium/third_party/blink/renderer/core/dom/idle_deadline.idl
+++ b/chromium/third_party/blink/renderer/core/dom/idle_deadline.idl
@@ -4,7 +4,9 @@
// https://w3c.github.io/requestidlecallback/#window_extensions
-interface IdleDeadline {
+[
+ Exposed=Window
+] interface IdleDeadline {
double timeRemaining();
readonly attribute boolean didTimeout;
};
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 60ca7c7fa93..8116102c65a 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
@@ -27,6 +27,9 @@ class MockIdleDeadlineScheduler final : public ThreadScheduler {
bool ShouldYieldForHighPriorityWork() override { return true; }
bool CanExceedIdleDeadlineIfRequired() const override { return false; }
void PostIdleTask(const base::Location&, Thread::IdleTask) override {}
+ void PostDelayedIdleTask(const base::Location&,
+ base::TimeDelta,
+ Thread::IdleTask) override {}
void PostNonNestableIdleTask(const base::Location&,
Thread::IdleTask) override {}
std::unique_ptr<PageScheduler> CreatePageScheduler(
@@ -83,20 +86,20 @@ class IdleDeadlineTest : public testing::Test {
TEST_F(IdleDeadlineTest, DeadlineInFuture) {
auto* deadline = MakeGarbageCollected<IdleDeadline>(
- TimeTicks() + TimeDelta::FromSecondsD(1.25),
+ base::TimeTicks() + base::TimeDelta::FromSecondsD(1.25),
IdleDeadline::CallbackType::kCalledWhenIdle);
deadline->SetTickClockForTesting(test_task_runner_->GetMockTickClock());
- test_task_runner_->FastForwardBy(TimeDelta::FromSeconds(1));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromSeconds(1));
// Note: the deadline is computed with reduced resolution.
EXPECT_FLOAT_EQ(250.0, deadline->timeRemaining());
}
TEST_F(IdleDeadlineTest, DeadlineInPast) {
auto* deadline = MakeGarbageCollected<IdleDeadline>(
- TimeTicks() + TimeDelta::FromSecondsD(0.75),
+ base::TimeTicks() + base::TimeDelta::FromSecondsD(0.75),
IdleDeadline::CallbackType::kCalledWhenIdle);
deadline->SetTickClockForTesting(test_task_runner_->GetMockTickClock());
- test_task_runner_->FastForwardBy(TimeDelta::FromSeconds(1));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromSeconds(1));
EXPECT_FLOAT_EQ(0, deadline->timeRemaining());
}
@@ -105,10 +108,10 @@ TEST_F(IdleDeadlineTest, YieldForHighPriorityWork) {
ScopedSchedulerOverrider scheduler_overrider(&scheduler);
auto* deadline = MakeGarbageCollected<IdleDeadline>(
- TimeTicks() + TimeDelta::FromSecondsD(1.25),
+ base::TimeTicks() + base::TimeDelta::FromSecondsD(1.25),
IdleDeadline::CallbackType::kCalledWhenIdle);
deadline->SetTickClockForTesting(test_task_runner_->GetMockTickClock());
- test_task_runner_->FastForwardBy(TimeDelta::FromSeconds(1));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromSeconds(1));
EXPECT_FLOAT_EQ(0, deadline->timeRemaining());
}
diff --git a/chromium/third_party/blink/renderer/core/dom/ignore_opens_during_unload_count_incrementer.h b/chromium/third_party/blink/renderer/core/dom/ignore_opens_during_unload_count_incrementer.h
index 0863a139a31..6f2a222b0b4 100644
--- a/chromium/third_party/blink/renderer/core/dom/ignore_opens_during_unload_count_incrementer.h
+++ b/chromium/third_party/blink/renderer/core/dom/ignore_opens_during_unload_count_incrementer.h
@@ -7,7 +7,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/dom/document.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/dom/increment_load_event_delay_count.h b/chromium/third_party/blink/renderer/core/dom/increment_load_event_delay_count.h
index e2a155d5be1..ca66a451978 100644
--- a/chromium/third_party/blink/renderer/core/dom/increment_load_event_delay_count.h
+++ b/chromium/third_party/blink/renderer/core/dom/increment_load_event_delay_count.h
@@ -10,7 +10,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_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/allocator/allocator.h"
namespace blink {
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 2f7c788d947..b15d3178d5d 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
@@ -45,74 +45,48 @@
namespace blink {
-LayoutTreeBuilderForElement::LayoutTreeBuilderForElement(Element& element,
- ComputedStyle* style)
- : LayoutTreeBuilder(element, nullptr), style_(style) {
+LayoutTreeBuilderForElement::LayoutTreeBuilderForElement(
+ Element& element,
+ Node::AttachContext& context,
+ const ComputedStyle* style,
+ LegacyLayout legacy)
+ : LayoutTreeBuilder(element, context, style), legacy_(legacy) {
DCHECK(element.CanParticipateInFlatTree());
DCHECK(style_);
DCHECK(!style_->IsEnsuredInDisplayNone());
- // TODO(ecobos): Move the first-letter logic inside ParentLayoutObject too?
- // It's an extra (unnecessary) check for text nodes, though.
- if (element.IsFirstLetterPseudoElement()) {
- if (LayoutObject* next_layout_object =
- FirstLetterPseudoElement::FirstLetterTextLayoutObject(element))
- layout_object_parent_ = next_layout_object->Parent();
- } else {
- layout_object_parent_ =
- LayoutTreeBuilderTraversal::ParentLayoutObject(element);
- }
}
LayoutObject* LayoutTreeBuilderForElement::NextLayoutObject() const {
- DCHECK(layout_object_parent_);
-
+ if (node_->IsFirstLetterPseudoElement())
+ return context_.next_sibling;
if (node_->IsInTopLayer())
return LayoutTreeBuilderTraversal::NextInTopLayer(*node_);
-
- if (node_->IsFirstLetterPseudoElement())
- return FirstLetterPseudoElement::FirstLetterTextLayoutObject(*node_);
-
return LayoutTreeBuilder::NextLayoutObject();
}
LayoutObject* LayoutTreeBuilderForElement::ParentLayoutObject() const {
- if (layout_object_parent_) {
- // FIXME: Guarding this by ParentLayoutObject isn't quite right as the spec
- // for top layer only talks about display: none ancestors so putting a
- // <dialog> inside an <optgroup> seems like it should still work even though
- // this check will prevent it.
- if (node_->IsInTopLayer())
- return node_->GetDocument().GetLayoutView();
- }
-
- return layout_object_parent_;
+ if (node_->IsInTopLayer())
+ return node_->GetDocument().GetLayoutView();
+ return context_.parent;
}
DISABLE_CFI_PERF
-bool LayoutTreeBuilderForElement::ShouldCreateLayoutObject() const {
- if (!layout_object_parent_)
- return false;
-
+void LayoutTreeBuilderForElement::CreateLayoutObject() {
LayoutObject* parent_layout_object = ParentLayoutObject();
if (!parent_layout_object)
- return false;
+ return;
if (!parent_layout_object->CanHaveChildren())
- return false;
+ return;
if (node_->IsPseudoElement() &&
- !CanHaveGeneratedChildren(*parent_layout_object)) {
- return false;
- }
- return node_->LayoutObjectIsNeeded(*style_);
-}
+ !CanHaveGeneratedChildren(*parent_layout_object))
+ return;
+ if (!node_->LayoutObjectIsNeeded(*style_))
+ return;
-DISABLE_CFI_PERF
-void LayoutTreeBuilderForElement::CreateLayoutObject(LegacyLayout legacy) {
- LayoutObject* new_layout_object = node_->CreateLayoutObject(*style_, legacy);
+ LayoutObject* new_layout_object = node_->CreateLayoutObject(*style_, legacy_);
if (!new_layout_object)
return;
- LayoutObject* parent_layout_object = ParentLayoutObject();
-
if (!parent_layout_object->IsChildAllowed(new_layout_object, *style_)) {
new_layout_object->Destroy();
return;
@@ -126,9 +100,9 @@ void LayoutTreeBuilderForElement::CreateLayoutObject(LegacyLayout legacy) {
parent_layout_object->IsInsideFlowThread());
LayoutObject* next_layout_object = NextLayoutObject();
+ // SetStyle() can depend on LayoutObject() already being set.
node_->SetLayoutObject(new_layout_object);
- new_layout_object->SetStyle(
- style_); // SetStyle() can depend on LayoutObject() already being set.
+ new_layout_object->SetStyle(style_);
// Note: Adding new_layout_object instead of LayoutObject(). LayoutObject()
// may be a child of new_layout_object.
@@ -137,9 +111,14 @@ void LayoutTreeBuilderForElement::CreateLayoutObject(LegacyLayout legacy) {
LayoutObject*
LayoutTreeBuilderForText::CreateInlineWrapperForDisplayContentsIfNeeded() {
+ // If the parent element is not a display:contents element, the style and the
+ // parent style will be the same ComputedStyle object. Early out here.
+ if (style_ == context_.parent->Style())
+ return nullptr;
+
scoped_refptr<ComputedStyle> wrapper_style =
ComputedStyle::CreateInheritedDisplayContentsStyleIfNeeded(
- *style_, layout_object_parent_->StyleRef());
+ *style_, context_.parent->StyleRef());
if (!wrapper_style)
return nullptr;
@@ -150,35 +129,29 @@ LayoutTreeBuilderForText::CreateInlineWrapperForDisplayContentsIfNeeded() {
LayoutObject* inline_wrapper =
LayoutInline::CreateAnonymous(&node_->GetDocument());
inline_wrapper->SetStyle(wrapper_style);
- if (!layout_object_parent_->IsChildAllowed(inline_wrapper, *wrapper_style)) {
+ if (!context_.parent->IsChildAllowed(inline_wrapper, *wrapper_style)) {
inline_wrapper->Destroy();
return nullptr;
}
- layout_object_parent_->AddChild(inline_wrapper, NextLayoutObject());
+ context_.parent->AddChild(inline_wrapper, NextLayoutObject());
return inline_wrapper;
}
void LayoutTreeBuilderForText::CreateLayoutObject() {
- ComputedStyle& style = *style_;
-
- DCHECK(style_ == layout_object_parent_->GetNode()->GetComputedStyle() ||
- ToElement(LayoutTreeBuilderTraversal::Parent(*node_))
- ->HasDisplayContentsStyle());
-
- LayoutObject* next_layout_object;
+ const ComputedStyle& style = *style_;
+ LayoutObject* layout_object_parent = context_.parent;
+ LayoutObject* next_layout_object = NextLayoutObject();
if (LayoutObject* wrapper = CreateInlineWrapperForDisplayContentsIfNeeded()) {
- layout_object_parent_ = wrapper;
+ layout_object_parent = wrapper;
next_layout_object = nullptr;
- } else {
- next_layout_object = NextLayoutObject();
}
- LegacyLayout legacy_layout = layout_object_parent_->ForceLegacyLayout()
+ LegacyLayout legacy_layout = layout_object_parent->ForceLegacyLayout()
? LegacyLayout::kForce
: LegacyLayout::kAuto;
LayoutText* new_layout_object =
node_->CreateTextLayoutObject(style, legacy_layout);
- if (!layout_object_parent_->IsChildAllowed(new_layout_object, style)) {
+ if (!layout_object_parent->IsChildAllowed(new_layout_object, style)) {
new_layout_object->Destroy();
return;
}
@@ -188,11 +161,11 @@ void LayoutTreeBuilderForText::CreateLayoutObject() {
// using IsInsideFlowThread() in the StyleWillChange and StyleDidChange will
// fail.
new_layout_object->SetIsInsideFlowThread(
- layout_object_parent_->IsInsideFlowThread());
+ context_.parent->IsInsideFlowThread());
node_->SetLayoutObject(new_layout_object);
new_layout_object->SetStyle(&style);
- layout_object_parent_->AddChild(new_layout_object, next_layout_object);
+ layout_object_parent->AddChild(new_layout_object, next_layout_object);
}
} // namespace blink
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 f3f1bf9d27d..97047f10db2 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
@@ -30,7 +30,6 @@
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/core/dom/document.h"
-#include "third_party/blink/renderer/core/dom/layout_tree_builder_traversal.h"
#include "third_party/blink/renderer/core/dom/node.h"
#include "third_party/blink/renderer/core/dom/text.h"
#include "third_party/blink/renderer/core/layout/layout_inline.h"
@@ -59,25 +58,23 @@ class LayoutTreeBuilder {
STACK_ALLOCATED();
protected:
- LayoutTreeBuilder(NodeType& node, LayoutObject* layout_object_parent)
- : node_(node), layout_object_parent_(layout_object_parent) {
+ LayoutTreeBuilder(NodeType& node,
+ Node::AttachContext& context,
+ const ComputedStyle* style)
+ : node_(node), context_(context), style_(style) {
DCHECK(!node.GetLayoutObject());
DCHECK(node.GetDocument().InStyleRecalc());
DCHECK(node.InActiveDocument());
+ DCHECK(context.parent);
}
LayoutObject* NextLayoutObject() const {
- DCHECK(layout_object_parent_);
-
- // Avoid an O(N^2) walk over the children when reattaching all children of a
- // node.
- if (layout_object_parent_->GetNode() &&
- layout_object_parent_->GetNode()->NeedsReattachLayoutTree())
- return nullptr;
-
- LayoutObject* next =
- LayoutTreeBuilderTraversal::NextSiblingLayoutObject(*node_);
-
+ if (!context_.next_sibling_valid) {
+ context_.next_sibling =
+ LayoutTreeBuilderTraversal::NextSiblingLayoutObject(*node_);
+ context_.next_sibling_valid = true;
+ }
+ LayoutObject* next = context_.next_sibling;
// If a text node is wrapped in an anonymous inline for display:contents
// (see CreateInlineWrapperForDisplayContents()), use the wrapper as the
// next layout object. Otherwise we would need to add code to various
@@ -91,40 +88,37 @@ class LayoutTreeBuilder {
}
Member<NodeType> node_;
- LayoutObject* layout_object_parent_;
+ Node::AttachContext& context_;
+ const ComputedStyle* style_;
};
class LayoutTreeBuilderForElement : public LayoutTreeBuilder<Element> {
public:
- LayoutTreeBuilderForElement(Element&, ComputedStyle*);
+ LayoutTreeBuilderForElement(Element&,
+ Node::AttachContext&,
+ const ComputedStyle*,
+ LegacyLayout legacy);
- void CreateLayoutObjectIfNeeded(LegacyLayout legacy) {
- if (ShouldCreateLayoutObject())
- CreateLayoutObject(legacy);
- }
+ void CreateLayoutObject();
private:
LayoutObject* ParentLayoutObject() const;
LayoutObject* NextLayoutObject() const;
- bool ShouldCreateLayoutObject() const;
- void CreateLayoutObject(LegacyLayout);
- scoped_refptr<ComputedStyle> style_;
+ LegacyLayout legacy_;
};
class LayoutTreeBuilderForText : public LayoutTreeBuilder<Text> {
public:
LayoutTreeBuilderForText(Text& text,
- LayoutObject* layout_parent,
- ComputedStyle* style_from_parent)
- : LayoutTreeBuilder(text, layout_parent), style_(style_from_parent) {}
+ Node::AttachContext& context,
+ const ComputedStyle* style_from_parent)
+ : LayoutTreeBuilder(text, context, style_from_parent) {}
void CreateLayoutObject();
private:
LayoutObject* CreateInlineWrapperForDisplayContentsIfNeeded();
-
- scoped_refptr<ComputedStyle> style_;
};
} // namespace blink
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 4008787f16a..ef147408ca2 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
@@ -34,13 +34,15 @@
namespace blink {
inline static bool HasDisplayContentsStyle(const Node& node) {
- return node.IsElementNode() && ToElement(node).HasDisplayContentsStyle();
+ auto* element = DynamicTo<Element>(node);
+ return element && element->HasDisplayContentsStyle();
}
static bool IsLayoutObjectReparented(const LayoutObject* layout_object) {
- if (!layout_object->GetNode()->IsElementNode())
+ auto* element = DynamicTo<Element>(layout_object->GetNode());
+ if (!element)
return false;
- return ToElement(layout_object->GetNode())->IsInTopLayer();
+ return element->IsInTopLayer();
}
void LayoutTreeBuilderTraversal::ParentDetails::DidTraverseInsertionPoint(
@@ -97,9 +99,9 @@ Node* LayoutTreeBuilderTraversal::NextSibling(const Node& node) {
return next;
}
- Node* parent = FlatTreeTraversal::Parent(node);
- if (parent && parent->IsElementNode())
- return ToElement(parent)->GetPseudoElement(kPseudoIdAfter);
+ if (auto* parent_element =
+ DynamicTo<Element>(FlatTreeTraversal::Parent(node)))
+ return parent_element->GetPseudoElement(kPseudoIdAfter);
return nullptr;
}
@@ -116,24 +118,24 @@ Node* LayoutTreeBuilderTraversal::PreviousSibling(const Node& node) {
return previous;
}
- Node* parent = FlatTreeTraversal::Parent(node);
- if (parent && parent->IsElementNode())
- return ToElement(parent)->GetPseudoElement(kPseudoIdBefore);
+ if (auto* parent_element =
+ DynamicTo<Element>(FlatTreeTraversal::Parent(node)))
+ return parent_element->GetPseudoElement(kPseudoIdBefore);
return nullptr;
}
Node* LayoutTreeBuilderTraversal::LastChild(const Node& node) {
- if (!node.IsElementNode())
+ const auto* current_element = DynamicTo<Element>(node);
+ if (!current_element)
return FlatTreeTraversal::LastChild(node);
- const Element& current_element = ToElement(node);
- Node* last = current_element.GetPseudoElement(kPseudoIdAfter);
+ Node* last = current_element->GetPseudoElement(kPseudoIdAfter);
if (last)
return last;
- last = FlatTreeTraversal::LastChild(current_element);
+ last = FlatTreeTraversal::LastChild(*current_element);
if (!last)
- last = current_element.GetPseudoElement(kPseudoIdBefore);
+ last = current_element->GetPseudoElement(kPseudoIdBefore);
return last;
}
@@ -151,16 +153,16 @@ Node* LayoutTreeBuilderTraversal::Previous(const Node& node,
}
Node* LayoutTreeBuilderTraversal::FirstChild(const Node& node) {
- if (!node.IsElementNode())
+ const auto* current_element = DynamicTo<Element>(node);
+ if (!current_element)
return FlatTreeTraversal::FirstChild(node);
- const Element& current_element = ToElement(node);
- Node* first = current_element.GetPseudoElement(kPseudoIdBefore);
+ Node* first = current_element->GetPseudoElement(kPseudoIdBefore);
if (first)
return first;
first = FlatTreeTraversal::FirstChild(node);
if (!first)
- first = current_element.GetPseudoElement(kPseudoIdAfter);
+ first = current_element->GetPseudoElement(kPseudoIdAfter);
return first;
}
diff --git a/chromium/third_party/blink/renderer/core/dom/layout_tree_builder_traversal.h b/chromium/third_party/blink/renderer/core/dom/layout_tree_builder_traversal.h
index 6e9e0d8a354..300be78ef8e 100644
--- a/chromium/third_party/blink/renderer/core/dom/layout_tree_builder_traversal.h
+++ b/chromium/third_party/blink/renderer/core/dom/layout_tree_builder_traversal.h
@@ -31,7 +31,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/dom/v0_insertion_point.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -91,8 +91,7 @@ class CORE_EXPORT LayoutTreeBuilderTraversal {
static LayoutObject* NextInTopLayer(const Element&);
static inline Element* ParentElement(const Node& node) {
- ContainerNode* found = Parent(node);
- return found && found->IsElementNode() ? ToElement(found) : nullptr;
+ return DynamicTo<Element>(Parent(node));
}
private:
diff --git a/chromium/third_party/blink/renderer/core/dom/live_node_list_registry.h b/chromium/third_party/blink/renderer/core/dom/live_node_list_registry.h
index fb4b87df88b..b208eaa2adc 100644
--- a/chromium/third_party/blink/renderer/core/dom/live_node_list_registry.h
+++ b/chromium/third_party/blink/renderer/core/dom/live_node_list_registry.h
@@ -11,7 +11,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
#include "third_party/blink/renderer/platform/heap/heap_allocator.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
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 3318e6302c5..e9178821b50 100644
--- a/chromium/third_party/blink/renderer/core/dom/mutation_observer.cc
+++ b/chromium/third_party/blink/renderer/core/dom/mutation_observer.cc
@@ -36,10 +36,12 @@
#include "third_party/blink/renderer/bindings/core/v8/v8_mutation_callback.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/mutation_observer_init.h"
+#include "third_party/blink/renderer/core/dom/mutation_observer_notifier.h"
#include "third_party/blink/renderer/core/dom/mutation_observer_registration.h"
#include "third_party/blink/renderer/core/dom/mutation_record.h"
#include "third_party/blink/renderer/core/dom/node.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
+#include "third_party/blink/renderer/core/execution_context/window_agent.h"
#include "third_party/blink/renderer/core/html/html_slot_element.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
@@ -83,15 +85,6 @@ class MutationObserver::V8DelegateImpl final
Member<V8MutationCallback> callback_;
};
-static unsigned g_observer_priority = 0;
-
-struct MutationObserver::ObserverLessThan {
- bool operator()(const Member<MutationObserver>& lhs,
- const Member<MutationObserver>& rhs) {
- return lhs->priority_ < rhs->priority_;
- }
-};
-
MutationObserver* MutationObserver::Create(Delegate* delegate) {
DCHECK(IsMainThread());
return MakeGarbageCollected<MutationObserver>(delegate->GetExecutionContext(),
@@ -108,14 +101,15 @@ MutationObserver* MutationObserver::Create(ScriptState* script_state,
MutationObserver::MutationObserver(ExecutionContext* execution_context,
Delegate* delegate)
- : ContextClient(execution_context),
- delegate_(delegate),
- priority_(g_observer_priority++) {}
-
-MutationObserver::~MutationObserver() {
- CancelInspectorAsyncTasks();
+ : ContextClient(execution_context), delegate_(delegate) {
+ priority_ = GetDocument()
+ ->GetWindowAgent()
+ .GetMutationObserverNotifier()
+ .NextObserverPriority();
}
+MutationObserver::~MutationObserver() = default;
+
void MutationObserver::observe(Node* node,
const MutationObserverInit* observer_init,
ExceptionState& exception_state) {
@@ -221,66 +215,42 @@ void MutationObserver::ObservationEnded(
registrations_.erase(registration);
}
-static MutationObserverSet& ActiveMutationObservers() {
- DEFINE_STATIC_LOCAL(Persistent<MutationObserverSet>, active_observers,
- (MakeGarbageCollected<MutationObserverSet>()));
- return *active_observers;
-}
-
-using SlotChangeList = HeapVector<Member<HTMLSlotElement>>;
-
-// TODO(hayato): We should have a SlotChangeList for each unit of related
-// similar-origin browsing context.
-// https://html.spec.whatwg.org/C/#unit-of-related-similar-origin-browsing-contexts
-static SlotChangeList& ActiveSlotChangeList() {
- DEFINE_STATIC_LOCAL(Persistent<SlotChangeList>, slot_change_list,
- (MakeGarbageCollected<SlotChangeList>()));
- return *slot_change_list;
-}
-
-static MutationObserverSet& SuspendedMutationObservers() {
- DEFINE_STATIC_LOCAL(Persistent<MutationObserverSet>, suspended_observers,
- (MakeGarbageCollected<MutationObserverSet>()));
- return *suspended_observers;
-}
-
-static void EnsureEnqueueMicrotask() {
- if (ActiveMutationObservers().IsEmpty() && ActiveSlotChangeList().IsEmpty())
- Microtask::EnqueueMicrotask(WTF::Bind(&MutationObserver::DeliverMutations));
-}
-
+// static
void MutationObserver::EnqueueSlotChange(HTMLSlotElement& slot) {
DCHECK(IsMainThread());
- EnsureEnqueueMicrotask();
- ActiveSlotChangeList().push_back(&slot);
+ slot.GetDocument()
+ .GetWindowAgent()
+ .GetMutationObserverNotifier()
+ .EnqueueSlotChange(slot);
}
+// static
void MutationObserver::CleanSlotChangeList(Document& document) {
- SlotChangeList kept;
- kept.ReserveCapacity(ActiveSlotChangeList().size());
- for (auto& slot : ActiveSlotChangeList()) {
- if (slot->GetDocument() != document)
- kept.push_back(slot);
- }
- ActiveSlotChangeList().swap(kept);
+ document.GetWindowAgent().GetMutationObserverNotifier().CleanSlotChangeList(
+ document);
}
-static void ActivateObserver(MutationObserver* observer) {
- EnsureEnqueueMicrotask();
- ActiveMutationObservers().insert(observer);
+void MutationObserver::Activate() {
+ GetDocument()
+ ->GetWindowAgent()
+ .GetMutationObserverNotifier()
+ .ActivateObserver(this);
}
void MutationObserver::EnqueueMutationRecord(MutationRecord* mutation) {
DCHECK(IsMainThread());
+ ExecutionContext* execution_context = delegate_->GetExecutionContext();
+ // This might get called when the execution context is gone. crbug.com/982850
+ if (!execution_context)
+ return;
records_.push_back(mutation);
- ActivateObserver(this);
- probe::AsyncTaskScheduled(delegate_->GetExecutionContext(), mutation->type(),
- mutation);
+ Activate();
+ probe::AsyncTaskScheduled(execution_context, mutation->type(), mutation);
}
void MutationObserver::SetHasTransientRegistration() {
DCHECK(IsMainThread());
- ActivateObserver(this);
+ Activate();
}
HeapHashSet<Member<Node>> MutationObserver::GetObservedNodes() const {
@@ -326,52 +296,6 @@ void MutationObserver::Deliver() {
delegate_->Deliver(records, *this);
}
-void MutationObserver::ResumeSuspendedObservers() {
- DCHECK(IsMainThread());
- if (SuspendedMutationObservers().IsEmpty())
- return;
-
- MutationObserverVector suspended;
- CopyToVector(SuspendedMutationObservers(), suspended);
- for (const auto& observer : suspended) {
- if (!observer->ShouldBeSuspended()) {
- SuspendedMutationObservers().erase(observer);
- ActivateObserver(observer);
- }
- }
-}
-
-void MutationObserver::DeliverMutations() {
- // These steps are defined in DOM Standard's "notify mutation observers".
- // https://dom.spec.whatwg.org/#notify-mutation-observers
- DCHECK(IsMainThread());
-
- MutationObserverVector observers;
- CopyToVector(ActiveMutationObservers(), observers);
- ActiveMutationObservers().clear();
-
- SlotChangeList slots;
- slots.swap(ActiveSlotChangeList());
- for (const auto& slot : slots)
- slot->ClearSlotChangeEventEnqueued();
-
- std::sort(observers.begin(), observers.end(), ObserverLessThan());
- for (const auto& observer : observers) {
- if (!observer->GetExecutionContext()) {
- // The observer's execution context is already gone, as active observers
- // intentionally do not hold their execution context. Do nothing then.
- continue;
- }
-
- if (observer->ShouldBeSuspended())
- SuspendedMutationObservers().insert(observer);
- else
- observer->Deliver();
- }
- for (const auto& slot : slots)
- slot->DispatchSlotChangeEvent();
-}
-
void MutationObserver::Trace(Visitor* visitor) {
visitor->Trace(delegate_);
visitor->Trace(records_);
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 eaa2b38cb06..48a0ac5613e 100644
--- a/chromium/third_party/blink/renderer/core/dom/mutation_observer.h
+++ b/chromium/third_party/blink/renderer/core/dom/mutation_observer.h
@@ -56,10 +56,8 @@ class Node;
class ScriptState;
class V8MutationCallback;
-using MutationObserverSet = HeapHashSet<Member<MutationObserver>>;
using MutationObserverRegistrationSet =
HeapHashSet<WeakMember<MutationObserverRegistration>>;
-using MutationObserverVector = HeapVector<Member<MutationObserver>>;
using MutationRecordVector = HeapVector<Member<MutationRecord>>;
class CORE_EXPORT MutationObserver final
@@ -68,6 +66,8 @@ class CORE_EXPORT MutationObserver final
public ContextClient {
DEFINE_WRAPPERTYPEINFO();
USING_GARBAGE_COLLECTED_MIXIN(MutationObserver);
+ // Using CancelInspectorAsyncTasks as pre-finalizer to cancel async tasks.
+ USING_PRE_FINALIZER(MutationObserver, CancelInspectorAsyncTasks);
public:
enum ObservationFlags { kSubtree = 1 << 3, kAttributeFilter = 1 << 4 };
@@ -94,8 +94,6 @@ class CORE_EXPORT MutationObserver final
static MutationObserver* Create(Delegate*);
static MutationObserver* Create(ScriptState*, V8MutationCallback*);
- static void ResumeSuspendedObservers();
- static void DeliverMutations();
static void EnqueueSlotChange(HTMLSlotElement&);
static void CleanSlotChangeList(Document&);
@@ -114,16 +112,16 @@ class CORE_EXPORT MutationObserver final
bool HasPendingActivity() const override { return !records_.IsEmpty(); }
- // Eagerly finalized as destructor accesses heap object members.
- EAGERLY_FINALIZE();
void Trace(Visitor*) override;
- private:
- struct ObserverLessThan;
-
+ // Methods to be used by MutationObserverNotifier
void Deliver();
bool ShouldBeSuspended() const;
void CancelInspectorAsyncTasks();
+ unsigned priority() { return priority_; }
+
+ private:
+ void Activate();
Member<Delegate> delegate_;
HeapVector<Member<MutationRecord>> records_;
diff --git a/chromium/third_party/blink/renderer/core/dom/mutation_observer_notifier.cc b/chromium/third_party/blink/renderer/core/dom/mutation_observer_notifier.cc
new file mode 100644
index 00000000000..47240e5b540
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/dom/mutation_observer_notifier.cc
@@ -0,0 +1,115 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/dom/mutation_observer_notifier.h"
+
+#include "third_party/blink/renderer/core/dom/mutation_observer.h"
+#include "third_party/blink/renderer/core/html/html_slot_element.h"
+#include "third_party/blink/renderer/platform/bindings/microtask.h"
+
+namespace blink {
+
+MutationObserverNotifier::MutationObserverNotifier() {}
+
+void MutationObserverNotifier::EnqueueSlotChange(HTMLSlotElement& slot) {
+ EnqueueMicrotaskIfNecessary();
+ active_slot_change_list_.push_back(&slot);
+}
+
+void MutationObserverNotifier::CleanSlotChangeList(Document& document) {
+ SlotChangeList kept;
+ kept.ReserveCapacity(active_slot_change_list_.size());
+ for (auto& slot : active_slot_change_list_) {
+ if (slot->GetDocument() != document)
+ kept.push_back(slot);
+ }
+ active_slot_change_list_.swap(kept);
+}
+
+void MutationObserverNotifier::ActivateObserver(MutationObserver* observer) {
+ EnqueueMicrotaskIfNecessary();
+ active_mutation_observers_.insert(observer);
+}
+
+void MutationObserverNotifier::EnqueueMicrotaskIfNecessary() {
+ if (microtask_enqueued_) {
+ return;
+ }
+
+ // If this is called before inserting the observer or slot, they should both
+ // be empty.
+ DCHECK(active_mutation_observers_.IsEmpty());
+ DCHECK(active_slot_change_list_.IsEmpty());
+
+ microtask_enqueued_ = true;
+ Microtask::EnqueueMicrotask(WTF::Bind(
+ &MutationObserverNotifier::DeliverMutations, WrapPersistent(this)));
+}
+
+struct MutationObserverNotifier::ObserverLessThan {
+ bool operator()(const Member<MutationObserver>& lhs,
+ const Member<MutationObserver>& rhs) {
+ return lhs->priority() < rhs->priority();
+ }
+};
+
+void MutationObserverNotifier::DeliverMutations() {
+ // These steps are defined in DOM Standard's "notify mutation observers".
+ // https://dom.spec.whatwg.org/#notify-mutation-observers
+ DCHECK(IsMainThread());
+
+ microtask_enqueued_ = false;
+
+ MutationObserverVector observers;
+ CopyToVector(active_mutation_observers_, observers);
+ active_mutation_observers_.clear();
+
+ SlotChangeList slots;
+ slots.swap(active_slot_change_list_);
+ for (const auto& slot : slots)
+ slot->ClearSlotChangeEventEnqueued();
+
+ std::sort(observers.begin(), observers.end(), ObserverLessThan());
+ for (const auto& observer : observers) {
+ if (!observer->GetExecutionContext()) {
+ // The observer's execution context is already gone, as active observers
+ // intentionally do not hold their execution context. Do nothing then.
+ continue;
+ }
+
+ if (observer->ShouldBeSuspended())
+ suspended_mutation_observers_.insert(observer);
+ else
+ observer->Deliver();
+ }
+ for (const auto& slot : slots)
+ slot->DispatchSlotChangeEvent();
+}
+
+void MutationObserverNotifier::ResumeSuspendedObservers() {
+ DCHECK(IsMainThread());
+ if (suspended_mutation_observers_.IsEmpty())
+ return;
+
+ MutationObserverVector suspended;
+ CopyToVector(suspended_mutation_observers_, suspended);
+ for (const auto& observer : suspended) {
+ if (!observer->ShouldBeSuspended()) {
+ suspended_mutation_observers_.erase(observer);
+ ActivateObserver(observer);
+ }
+ }
+}
+
+unsigned MutationObserverNotifier::NextObserverPriority() {
+ return ++last_observer_priority_;
+}
+
+void MutationObserverNotifier::Trace(Visitor* visitor) {
+ visitor->Trace(active_mutation_observers_);
+ visitor->Trace(suspended_mutation_observers_);
+ visitor->Trace(active_slot_change_list_);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/dom/mutation_observer_notifier.h b/chromium/third_party/blink/renderer/core/dom/mutation_observer_notifier.h
new file mode 100644
index 00000000000..85911759153
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/dom/mutation_observer_notifier.h
@@ -0,0 +1,54 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_DOM_MUTATION_OBSERVER_NOTIFIER_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_DOM_MUTATION_OBSERVER_NOTIFIER_H_
+
+#include "third_party/blink/renderer/platform/heap/handle.h"
+
+namespace blink {
+
+class Document;
+class MutationObserver;
+class HTMLSlotElement;
+
+// In charge of mutation observer related state that should be managed per
+// WindowAgent.
+class MutationObserverNotifier final
+ : public GarbageCollectedFinalized<MutationObserverNotifier> {
+ public:
+ MutationObserverNotifier();
+
+ void Trace(Visitor*);
+
+ void EnqueueSlotChange(HTMLSlotElement&);
+ void CleanSlotChangeList(Document&);
+ void ActivateObserver(MutationObserver*);
+ void ResumeSuspendedObservers();
+ // Returns the priority that should be assigned to the next MutationObserver.
+ unsigned NextObserverPriority();
+
+ // Callback called to deliver the accumulated mutations.
+ void DeliverMutations();
+
+ private:
+ struct ObserverLessThan;
+
+ // Schedules the DeliverMutations() callback if necessary.
+ void EnqueueMicrotaskIfNecessary();
+
+ using MutationObserverSet = HeapHashSet<Member<MutationObserver>>;
+ using SlotChangeList = HeapVector<Member<HTMLSlotElement>>;
+ using MutationObserverVector = HeapVector<Member<MutationObserver>>;
+
+ bool microtask_enqueued_ = false;
+ MutationObserverSet active_mutation_observers_;
+ MutationObserverSet suspended_mutation_observers_;
+ SlotChangeList active_slot_change_list_;
+ unsigned last_observer_priority_ = 0;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_DOM_MUTATION_OBSERVER_NOTIFIER_H_
diff --git a/chromium/third_party/blink/renderer/core/dom/mutation_record.idl b/chromium/third_party/blink/renderer/core/dom/mutation_record.idl
index 72315000376..03608f6688a 100644
--- a/chromium/third_party/blink/renderer/core/dom/mutation_record.idl
+++ b/chromium/third_party/blink/renderer/core/dom/mutation_record.idl
@@ -30,7 +30,9 @@
// https://dom.spec.whatwg.org/#interface-mutationrecord
-interface MutationRecord {
+[
+ Exposed=Window
+] interface MutationRecord {
readonly attribute DOMString type;
readonly attribute Node target;
[SameObject] readonly attribute NodeList addedNodes;
diff --git a/chromium/third_party/blink/renderer/core/dom/named_node_map.idl b/chromium/third_party/blink/renderer/core/dom/named_node_map.idl
index bbb53e84483..13482eba277 100644
--- a/chromium/third_party/blink/renderer/core/dom/named_node_map.idl
+++ b/chromium/third_party/blink/renderer/core/dom/named_node_map.idl
@@ -21,7 +21,8 @@
// https://dom.spec.whatwg.org/#interface-namednodemap
[
- LegacyUnenumerableNamedProperties
+ LegacyUnenumerableNamedProperties,
+ Exposed=Window
] interface NamedNodeMap {
[Affects=Nothing] readonly attribute unsigned long length;
[Affects=Nothing, MeasureAs=NamedNodeMapItem] getter Attr? item(unsigned long index);
diff --git a/chromium/third_party/blink/renderer/core/dom/names_map.h b/chromium/third_party/blink/renderer/core/dom/names_map.h
index 9e87028ced6..659a2e30b10 100644
--- a/chromium/third_party/blink/renderer/core/dom/names_map.h
+++ b/chromium/third_party/blink/renderer/core/dom/names_map.h
@@ -10,7 +10,7 @@
#include "base/optional.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/dom/space_split_string.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string_hash.h"
diff --git a/chromium/third_party/blink/renderer/core/dom/node.cc b/chromium/third_party/blink/renderer/core/dom/node.cc
index 1b5bfc0912f..e5f180ec410 100644
--- a/chromium/third_party/blink/renderer/core/dom/node.cc
+++ b/chromium/third_party/blink/renderer/core/dom/node.cc
@@ -26,7 +26,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/node_or_string_or_trusted_script.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"
@@ -86,7 +86,6 @@
#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/local_frame_view.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/fullscreen/fullscreen.h"
#include "third_party/blink/renderer/core/html/custom/custom_element.h"
#include "third_party/blink/renderer/core/html/html_dialog_element.h"
@@ -115,13 +114,13 @@
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/microtask.h"
#include "third_party/blink/renderer/platform/bindings/v8_dom_wrapper.h"
-#include "third_party/blink/renderer/platform/instance_counters.h"
+#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/traced_value.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.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/hash_set.h"
-#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
@@ -169,7 +168,7 @@ struct SameSizeAsNode : EventTarget {
NodeRenderingData::NodeRenderingData(
LayoutObject* layout_object,
- scoped_refptr<ComputedStyle> computed_style)
+ scoped_refptr<const ComputedStyle> computed_style)
: layout_object_(layout_object), computed_style_(computed_style) {}
NodeRenderingData::~NodeRenderingData() {
@@ -177,7 +176,7 @@ NodeRenderingData::~NodeRenderingData() {
}
void NodeRenderingData::SetComputedStyle(
- scoped_refptr<ComputedStyle> computed_style) {
+ scoped_refptr<const ComputedStyle> computed_style) {
DCHECK_NE(&SharedEmptyData(), this);
computed_style_ = computed_style;
}
@@ -224,9 +223,9 @@ void Node::DumpStatistics() {
for (Node* node : liveNodeSet()) {
if (node->hasRareData()) {
++nodesWithRareData;
- if (node->isElementNode()) {
+ if (auto* element = DynamicTo<Element>(node)) {
++elementsWithRareData;
- if (toElement(node)->hasNamedNodeMap())
+ if (element->hasNamedNodeMap())
++elementsWithNamedNodeMap;
}
}
@@ -236,7 +235,7 @@ void Node::DumpStatistics() {
++elementNodes;
// Tag stats
- Element* element = toElement(node);
+ auto* element = To<Element>(node);
HashMap<String, size_t>::AddResult result =
perTagCount.add(element->tagName(), 1);
if (!result.isNewEntry)
@@ -423,8 +422,7 @@ Node* Node::PseudoAwareNextSibling() const {
}
Node* Node::PseudoAwareFirstChild() const {
- if (IsElementNode()) {
- const Element* current_element = ToElement(this);
+ if (const auto* current_element = DynamicTo<Element>(this)) {
Node* first = current_element->GetPseudoElement(kPseudoIdBefore);
if (first)
return first;
@@ -438,8 +436,7 @@ Node* Node::PseudoAwareFirstChild() const {
}
Node* Node::PseudoAwareLastChild() const {
- if (IsElementNode()) {
- const Element* current_element = ToElement(this);
+ if (const auto* current_element = DynamicTo<Element>(this)) {
Node* last = current_element->GetPseudoElement(kPseudoIdAfter);
if (last)
return last;
@@ -518,8 +515,14 @@ void Node::NativeApplyScroll(ScrollState& scroll_state) {
if (!GetLayoutObject())
return;
- // All elements in the scroll chain should be boxes.
- DCHECK(GetLayoutObject()->IsBox());
+ // All elements in the scroll chain should be boxes. However, in a scroll
+ // gesture sequence, the scroll chain is only computed on GestureScrollBegin.
+ // The type of layout object of the nodes in the scroll chain can change
+ // between GestureScrollUpdate and GestureScrollBegin (e.g. from script
+ // setting one of the nodes to display:inline). If there is no box there will
+ // not be a scrollable area to scroll, so just return.
+ if (!GetLayoutObject()->IsBox())
+ return;
if (scroll_state.FullyConsumed())
return;
@@ -543,7 +546,7 @@ void Node::NativeApplyScroll(ScrollState& scroll_state) {
ScrollResult result = scrollable_area->UserScroll(
ScrollGranularity(static_cast<int>(scroll_state.deltaGranularity())),
- delta);
+ delta, ScrollableArea::ScrollCallback());
if (!result.DidScroll())
return;
@@ -666,6 +669,10 @@ void Node::DidEndCustomizedScrollPhase() {
Node* Node::insertBefore(Node* new_child,
Node* ref_child,
ExceptionState& exception_state) {
+ new_child = TrustedTypesCheckForScriptNode(new_child, exception_state);
+ if (!new_child)
+ return nullptr;
+
auto* this_node = DynamicTo<ContainerNode>(this);
if (this_node)
return this_node->InsertBefore(new_child, ref_child, exception_state);
@@ -683,6 +690,10 @@ Node* Node::insertBefore(Node* new_child, Node* ref_child) {
Node* Node::replaceChild(Node* new_child,
Node* old_child,
ExceptionState& exception_state) {
+ new_child = TrustedTypesCheckForScriptNode(new_child, exception_state);
+ if (!new_child)
+ return nullptr;
+
auto* this_node = DynamicTo<ContainerNode>(this);
if (this_node)
return this_node->ReplaceChild(new_child, old_child, exception_state);
@@ -713,6 +724,10 @@ Node* Node::removeChild(Node* old_child) {
}
Node* Node::appendChild(Node* new_child, ExceptionState& exception_state) {
+ new_child = TrustedTypesCheckForScriptNode(new_child, exception_state);
+ if (!new_child)
+ return nullptr;
+
auto* this_node = DynamicTo<ContainerNode>(this);
if (this_node)
return this_node->AppendChild(new_child, exception_state);
@@ -727,17 +742,19 @@ Node* Node::appendChild(Node* new_child) {
return appendChild(new_child, ASSERT_NO_EXCEPTION);
}
-static bool IsNodeInNodes(const Node* const node,
- const HeapVector<NodeOrString>& nodes) {
- for (const NodeOrString& node_or_string : nodes) {
+static bool IsNodeInNodes(
+ const Node* const node,
+ const HeapVector<NodeOrStringOrTrustedScript>& nodes) {
+ for (const NodeOrStringOrTrustedScript& node_or_string : nodes) {
if (node_or_string.IsNode() && node_or_string.GetAsNode() == node)
return true;
}
return false;
}
-static Node* FindViablePreviousSibling(const Node& node,
- const HeapVector<NodeOrString>& nodes) {
+static Node* FindViablePreviousSibling(
+ const Node& node,
+ const HeapVector<NodeOrStringOrTrustedScript>& nodes) {
for (Node* sibling = node.previousSibling(); sibling;
sibling = sibling->previousSibling()) {
if (!IsNodeInNodes(sibling, nodes))
@@ -746,8 +763,9 @@ static Node* FindViablePreviousSibling(const Node& node,
return nullptr;
}
-static Node* FindViableNextSibling(const Node& node,
- const HeapVector<NodeOrString>& nodes) {
+static Node* FindViableNextSibling(
+ const Node& node,
+ const HeapVector<NodeOrStringOrTrustedScript>& nodes) {
for (Node* sibling = node.nextSibling(); sibling;
sibling = sibling->nextSibling()) {
if (!IsNodeInNodes(sibling, nodes))
@@ -756,79 +774,162 @@ static Node* FindViableNextSibling(const Node& node,
return nullptr;
}
-static Node* NodeOrStringToNode(const NodeOrString& node_or_string,
- Document& document) {
- if (node_or_string.IsNode())
+static Node* NodeOrStringToNode(
+ const NodeOrStringOrTrustedScript& node_or_string,
+ Document& document,
+ bool needs_trusted_types_check,
+ ExceptionState& exception_state) {
+ if (!needs_trusted_types_check) {
+ // Without trusted type checks, we simply extract the string from whatever
+ // constituent type we find.
+ if (node_or_string.IsNode())
+ return node_or_string.GetAsNode();
+ if (node_or_string.IsTrustedScript()) {
+ return Text::Create(document,
+ node_or_string.GetAsTrustedScript()->toString());
+ }
+ return Text::Create(document, node_or_string.GetAsString());
+ }
+
+ // With trusted type checks, we can process trusted script or non-text nodes
+ // directly. Strings or text nodes need to be checked.
+ if (node_or_string.IsNode() && !node_or_string.GetAsNode()->IsTextNode())
return node_or_string.GetAsNode();
- return Text::Create(document, node_or_string.GetAsString());
+
+ if (node_or_string.IsTrustedScript()) {
+ return Text::Create(document,
+ node_or_string.GetAsTrustedScript()->toString());
+ }
+
+ String string_value = node_or_string.IsString()
+ ? node_or_string.GetAsString()
+ : node_or_string.GetAsNode()->textContent();
+
+ string_value =
+ GetStringFromTrustedScript(string_value, &document, exception_state);
+ if (exception_state.HadException())
+ return nullptr;
+ return Text::Create(document, string_value);
}
// Returns nullptr if an exception was thrown.
-static Node* ConvertNodesIntoNode(const HeapVector<NodeOrString>& nodes,
- Document& document,
- ExceptionState& exception_state) {
+static Node* ConvertNodesIntoNode(
+ const Node* parent,
+ const HeapVector<NodeOrStringOrTrustedScript>& nodes,
+ Document& document,
+ ExceptionState& exception_state) {
+ bool needs_check =
+ IsHTMLScriptElement(parent) && document.IsTrustedTypesEnabledForDoc();
+
if (nodes.size() == 1)
- return NodeOrStringToNode(nodes[0], document);
+ return NodeOrStringToNode(nodes[0], document, needs_check, exception_state);
Node* fragment = DocumentFragment::Create(document);
- for (const NodeOrString& node_or_string : nodes) {
- fragment->appendChild(NodeOrStringToNode(node_or_string, document),
- exception_state);
+ for (const NodeOrStringOrTrustedScript& node_or_string_or_trusted_script :
+ nodes) {
+ Node* node = NodeOrStringToNode(node_or_string_or_trusted_script, document,
+ needs_check, exception_state);
+ if (node)
+ fragment->appendChild(node, exception_state);
if (exception_state.HadException())
return nullptr;
}
return fragment;
}
-void Node::Prepend(const HeapVector<NodeOrString>& nodes,
+void Node::Prepend(const HeapVector<NodeOrStringOrTrustedScript>& nodes,
ExceptionState& exception_state) {
- if (Node* node = ConvertNodesIntoNode(nodes, GetDocument(), exception_state))
- insertBefore(node, firstChild(), exception_state);
+ auto* this_node = DynamicTo<ContainerNode>(this);
+ if (!this_node) {
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kHierarchyRequestError,
+ "This node type does not support this method.");
+ return;
+ }
+
+ if (Node* node =
+ ConvertNodesIntoNode(this, nodes, GetDocument(), exception_state))
+ this_node->InsertBefore(node, firstChild(), exception_state);
}
-void Node::Append(const HeapVector<NodeOrString>& nodes,
+void Node::Append(const HeapVector<NodeOrStringOrTrustedScript>& nodes,
ExceptionState& exception_state) {
- if (Node* node = ConvertNodesIntoNode(nodes, GetDocument(), exception_state))
- appendChild(node, exception_state);
+ auto* this_node = DynamicTo<ContainerNode>(this);
+ if (!this_node) {
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kHierarchyRequestError,
+ "This node type does not support this method.");
+ return;
+ }
+
+ if (Node* node =
+ ConvertNodesIntoNode(this, nodes, GetDocument(), exception_state))
+ this_node->AppendChild(node, exception_state);
}
-void Node::Before(const HeapVector<NodeOrString>& nodes,
+void Node::Before(const HeapVector<NodeOrStringOrTrustedScript>& nodes,
ExceptionState& exception_state) {
Node* parent = parentNode();
if (!parent)
return;
+ auto* parent_node = DynamicTo<ContainerNode>(parent);
+ if (!parent_node) {
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kHierarchyRequestError,
+ "This node type does not support this method.");
+ return;
+ }
Node* viable_previous_sibling = FindViablePreviousSibling(*this, nodes);
- if (Node* node = ConvertNodesIntoNode(nodes, GetDocument(), exception_state))
- parent->insertBefore(node,
- viable_previous_sibling
- ? viable_previous_sibling->nextSibling()
- : parent->firstChild(),
- exception_state);
+ if (Node* node =
+ ConvertNodesIntoNode(parent, nodes, GetDocument(), exception_state)) {
+ parent_node->InsertBefore(node,
+ viable_previous_sibling
+ ? viable_previous_sibling->nextSibling()
+ : parent->firstChild(),
+ exception_state);
+ }
}
-void Node::After(const HeapVector<NodeOrString>& nodes,
+void Node::After(const HeapVector<NodeOrStringOrTrustedScript>& nodes,
ExceptionState& exception_state) {
Node* parent = parentNode();
if (!parent)
return;
+ auto* parent_node = DynamicTo<ContainerNode>(parent);
+ if (!parent_node) {
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kHierarchyRequestError,
+ "This node type does not support this method.");
+ return;
+ }
Node* viable_next_sibling = FindViableNextSibling(*this, nodes);
- if (Node* node = ConvertNodesIntoNode(nodes, GetDocument(), exception_state))
- parent->insertBefore(node, viable_next_sibling, exception_state);
+ if (Node* node =
+ ConvertNodesIntoNode(parent, nodes, GetDocument(), exception_state))
+ parent_node->InsertBefore(node, viable_next_sibling, exception_state);
}
-void Node::ReplaceWith(const HeapVector<NodeOrString>& nodes,
+void Node::ReplaceWith(const HeapVector<NodeOrStringOrTrustedScript>& nodes,
ExceptionState& exception_state) {
Node* parent = parentNode();
if (!parent)
return;
+ auto* parent_node = DynamicTo<ContainerNode>(parent);
+ if (!parent_node) {
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kHierarchyRequestError,
+ "This node type does not support this method.");
+ return;
+ }
+
Node* viable_next_sibling = FindViableNextSibling(*this, nodes);
- Node* node = ConvertNodesIntoNode(nodes, GetDocument(), exception_state);
+ Node* node =
+ ConvertNodesIntoNode(parent, nodes, GetDocument(), exception_state);
if (exception_state.HadException())
return;
- if (parent == parentNode())
- parent->replaceChild(node, this, exception_state);
+ if (parent_node == parentNode())
+ parent_node->ReplaceChild(node, this, exception_state);
else
- parent->insertBefore(node, viable_next_sibling, exception_state);
+ parent_node->InsertBefore(node, viable_next_sibling, exception_state);
}
void Node::remove(ExceptionState& exception_state) {
@@ -913,7 +1014,7 @@ void Node::SetLayoutObject(LayoutObject* layout_object) {
data_.node_layout_data_ = node_layout_data;
}
-void Node::SetComputedStyle(scoped_refptr<ComputedStyle> computed_style) {
+void Node::SetComputedStyle(scoped_refptr<const ComputedStyle> computed_style) {
// We don't set computed style for text nodes.
DCHECK(IsElementNode());
@@ -953,20 +1054,18 @@ LayoutBoxModelObject* Node::GetLayoutBoxModelObject() const {
: nullptr;
}
-LayoutRect Node::BoundingBox() const {
+PhysicalRect Node::BoundingBox() const {
if (GetLayoutObject())
- return LayoutRect(GetLayoutObject()->AbsoluteBoundingBoxRect());
- return LayoutRect();
+ return PhysicalRect(GetLayoutObject()->AbsoluteBoundingBoxRect());
+ return PhysicalRect();
}
-LayoutRect Node::BoundingBoxForScrollIntoView() const {
+PhysicalRect Node::BoundingBoxForScrollIntoView() const {
if (GetLayoutObject()) {
- return GetLayoutObject()
- ->AbsoluteBoundingBoxRectForScrollIntoView()
- .ToLayoutRect();
+ return GetLayoutObject()->AbsoluteBoundingBoxRectForScrollIntoView();
}
- return LayoutRect();
+ return PhysicalRect();
}
Node& Node::ShadowIncludingRoot() const {
@@ -1058,7 +1157,7 @@ void Node::RecalcDistribution() {
}
void Node::SetIsLink(bool is_link) {
- SetFlag(is_link && !SVGImage::IsInSVGImage(ToElement(this)), kIsLinkFlag);
+ SetFlag(is_link && !SVGImage::IsInSVGImage(To<Element>(this)), kIsLinkFlag);
}
void Node::SetNeedsStyleInvalidation() {
@@ -1111,9 +1210,9 @@ void Node::MarkAncestorsWithChildNeedsStyleRecalc() {
// 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(
- DisplayLockContext::kChildren)) {
+ auto* ancestor_element = DynamicTo<Element>(ancestor);
+ if (ancestor_element && ancestor_element->StyleRecalcBlockedByDisplayLock(
+ DisplayLockContext::kChildren)) {
break;
}
}
@@ -1133,10 +1232,10 @@ void Node::MarkAncestorsWithChildNeedsStyleRecalc() {
GetDocument().LockedDisplayLockCount() > 0) {
for (auto* ancestor_copy = ancestor; ancestor_copy;
ancestor_copy = ancestor_copy->ParentOrShadowHostNode()) {
- if (ancestor_copy->IsElementNode() &&
- ToElement(ancestor_copy)
- ->StyleRecalcBlockedByDisplayLock(
- DisplayLockContext::kChildren)) {
+ auto* ancestor_copy_element = DynamicTo<Element>(ancestor_copy);
+ if (ancestor_copy_element &&
+ ancestor_copy_element->StyleRecalcBlockedByDisplayLock(
+ DisplayLockContext::kChildren)) {
return;
}
}
@@ -1208,13 +1307,14 @@ void Node::SetNeedsStyleRecalc(StyleChangeType change_type,
if (change_type > existing_change_type)
SetStyleChange(change_type);
+ auto* this_element = DynamicTo<Element>(this);
if (existing_change_type == kNoStyleChange &&
- (!IsElementNode() || !ToElement(this)->StyleRecalcBlockedByDisplayLock(
- DisplayLockContext::kSelf)))
+ (!this_element || !this_element->StyleRecalcBlockedByDisplayLock(
+ DisplayLockContext::kSelf)))
MarkAncestorsWithChildNeedsStyleRecalc();
- if (IsElementNode() && HasRareData())
- ToElement(*this).SetAnimationStyleChange(false);
+ if (this_element && HasRareData())
+ this_element->SetAnimationStyleChange(false);
if (auto* svg_element = DynamicTo<SVGElement>(this))
svg_element->SetNeedsStyleRecalcForInstances(change_type, reason);
@@ -1224,8 +1324,9 @@ void Node::ClearNeedsStyleRecalc() {
node_flags_ &= ~kStyleChangeMask;
ClearFlag(kForceReattachLayoutTree);
- if (IsElementNode() && HasRareData())
- ToElement(*this).SetAnimationStyleChange(false);
+ auto* element = DynamicTo<Element>(this);
+ if (element && HasRareData())
+ element->SetAnimationStyleChange(false);
}
bool Node::InActiveDocument() const {
@@ -1247,7 +1348,7 @@ bool Node::IsInert() const {
DCHECK(!ChildNeedsDistributionRecalc());
- if (this != GetDocument()) {
+ if (this != GetDocument() && this != GetDocument().documentElement()) {
const Element* modal_element = GetDocument().ActiveModalDialog();
if (!modal_element)
modal_element = Fullscreen::FullscreenElementFrom(GetDocument());
@@ -1258,9 +1359,10 @@ bool Node::IsInert() const {
}
if (RuntimeEnabledFeatures::InertAttributeEnabled()) {
- const Element* element = IsElementNode()
- ? ToElement(this)
- : FlatTreeTraversal::ParentElement(*this);
+ const auto* element = DynamicTo<Element>(this);
+ if (!element)
+ element = FlatTreeTraversal::ParentElement(*this);
+
while (element) {
if (element->hasAttribute(html_names::kInertAttr))
return true;
@@ -1406,7 +1508,7 @@ Node* Node::CommonAncestor(const Node& other,
void Node::ReattachLayoutTree(AttachContext& context) {
context.performing_reattach = true;
- DetachLayoutTree(context);
+ DetachLayoutTree(context.performing_reattach);
AttachLayoutTree(context);
DCHECK(!NeedsReattachLayoutTree());
}
@@ -1428,9 +1530,9 @@ void Node::AttachLayoutTree(AttachContext& context) {
cache->UpdateCacheAfterNodeIsAttached(this);
}
-void Node::DetachLayoutTree(const AttachContext& context) {
+void Node::DetachLayoutTree(bool performing_reattach) {
DCHECK(GetDocument().Lifecycle().StateAllowsDetach());
- DCHECK(!context.performing_reattach ||
+ DCHECK(!performing_reattach ||
GetDocument().GetStyleEngine().InRebuildLayoutTree());
DocumentLifecycle::DetachScope will_detach(GetDocument().Lifecycle());
if (GetLayoutObject())
@@ -1492,9 +1594,10 @@ bool Node::CanStartSelection() const {
// eliminate all the checks since those elements will never have class names,
// inline style, or other things that this apparently guards against.
bool Node::IsStyledElement() const {
+ auto* this_element = DynamicTo<Element>(this);
return IsHTMLElement() || IsSVGElement() ||
- (IsElementNode() &&
- ToElement(this)->namespaceURI() == mathml_names::kNamespaceURI);
+ (this_element &&
+ this_element->namespaceURI() == mathml_names::kNamespaceURI);
}
bool Node::CanParticipateInFlatTree() const {
@@ -1511,7 +1614,7 @@ AtomicString Node::SlotName() const {
DCHECK(IsSlotable());
if (IsElementNode()) {
return HTMLSlotElement::NormalizeSlotName(
- ToElement(*this).FastGetAttribute(html_names::kSlotAttr));
+ To<Element>(*this).FastGetAttribute(html_names::kSlotAttr));
}
DCHECK(IsTextNode());
return g_empty_atom;
@@ -1586,10 +1689,7 @@ Element* Node::ParentOrShadowHostElement() const {
if (auto* shadow_root = DynamicTo<ShadowRoot>(parent))
return &shadow_root->host();
- if (!parent->IsElementNode())
- return nullptr;
-
- return ToElement(parent);
+ return DynamicTo<Element>(parent);
}
ContainerNode* Node::ParentOrShadowHostOrTemplateHostNode() const {
@@ -1626,11 +1726,12 @@ bool Node::isEqualNode(Node* other) const {
if (this_attr->namespaceURI() != other_attr->namespaceURI())
return false;
- } else if (IsElementNode()) {
- if (ToElement(this)->TagQName() != ToElement(other)->TagQName())
+ } else if (auto* this_element = DynamicTo<Element>(this)) {
+ auto* other_element = DynamicTo<Element>(other);
+ if (this_element->TagQName() != other_element->TagQName())
return false;
- if (!ToElement(this)->HasEquivalentAttributes(ToElement(*other)))
+ if (!this_element->HasEquivalentAttributes(*other_element))
return false;
} else if (nodeName() != other->nodeName()) {
return false;
@@ -1693,7 +1794,7 @@ const AtomicString& Node::lookupPrefix(
switch (getNodeType()) {
case kElementNode:
- context = ToElement(this);
+ context = To<Element>(this);
break;
case kDocumentNode:
context = To<Document>(this)->documentElement();
@@ -1732,7 +1833,7 @@ const AtomicString& Node::lookupNamespaceURI(
// https://dom.spec.whatwg.org/#locate-a-namespace
switch (getNodeType()) {
case kElementNode: {
- const Element& element = ToElement(*this);
+ const auto& element = To<Element>(*this);
// 1. If its namespace is not null and its namespace prefix is prefix,
// then return namespace.
@@ -2008,20 +2109,19 @@ uint16_t Node::compareDocumentPosition(const Node* other_node,
String Node::DebugName() const {
StringBuilder name;
AppendUnsafe(name, DebugNodeName());
- if (IsElementNode()) {
- const Element& this_element = ToElement(*this);
- if (this_element.HasID()) {
+ if (const auto* this_element = DynamicTo<Element>(this)) {
+ if (this_element->HasID()) {
name.Append(" id=\'");
- AppendUnsafe(name, this_element.GetIdAttribute());
+ AppendUnsafe(name, this_element->GetIdAttribute());
name.Append('\'');
}
- if (this_element.HasClass()) {
+ if (this_element->HasClass()) {
name.Append(" class=\'");
- for (wtf_size_t i = 0; i < this_element.ClassNames().size(); ++i) {
+ for (wtf_size_t i = 0; i < this_element->ClassNames().size(); ++i) {
if (i > 0)
name.Append(' ');
- AppendUnsafe(name, this_element.ClassNames()[i]);
+ AppendUnsafe(name, this_element->ClassNames()[i]);
}
name.Append('\'');
}
@@ -2036,9 +2136,10 @@ String Node::DebugNodeName() const {
static void DumpAttributeDesc(const Node& node,
const QualifiedName& name,
StringBuilder& builder) {
- if (!node.IsElementNode())
+ auto* element = DynamicTo<Element>(node);
+ if (!element)
return;
- const AtomicString& value = ToElement(node).getAttribute(name);
+ const AtomicString& value = element->getAttribute(name);
if (value.IsEmpty())
return;
builder.Append(' ');
@@ -2048,7 +2149,7 @@ static void DumpAttributeDesc(const Node& node,
}
std::ostream& operator<<(std::ostream& ostream, const Node& node) {
- return ostream << node.ToString().Utf8().data();
+ return ostream << node.ToString().Utf8();
}
std::ostream& operator<<(std::ostream& ostream, const Node* node) {
@@ -2114,9 +2215,9 @@ void Node::PrintNodePathTo(std::ostream& stream) const {
switch (node->getNodeType()) {
case kElementNode: {
- stream << "/" << node->nodeName().Utf8().data();
+ stream << "/" << node->nodeName().Utf8();
- const Element* element = ToElement(node);
+ const auto* element = To<Element>(node);
const AtomicString& idattr = element->GetIdAttribute();
bool has_id_attr = !idattr.IsNull() && !idattr.IsEmpty();
if (node->previousSibling() || node->nextSibling()) {
@@ -2128,12 +2229,12 @@ void Node::PrintNodePathTo(std::ostream& stream) const {
}
}
if (has_id_attr)
- stream << "[@id=\"" << idattr.Utf8().data()
+ stream << "[@id=\"" << idattr.Utf8()
<< "\" and position()=" << count << "]";
else
stream << "[" << count << "]";
} else if (has_id_attr) {
- stream << "[@id=\"" << idattr.Utf8().data() << "\"]";
+ stream << "[@id=\"" << idattr.Utf8() << "\"]";
}
break;
}
@@ -2141,7 +2242,7 @@ void Node::PrintNodePathTo(std::ostream& stream) const {
stream << "/text()";
break;
case kAttributeNode:
- stream << "/@" << node->nodeName().Utf8().data();
+ stream << "/@" << node->nodeName().Utf8();
break;
default:
break;
@@ -2171,18 +2272,17 @@ static void AppendMarkedTree(const String& base_indent,
builder.Append("\n");
indent.Append('\t');
- if (node.IsElementNode()) {
- const Element& element = ToElement(node);
- if (Element* pseudo = element.GetPseudoElement(kPseudoIdBefore))
+ if (const auto* element = DynamicTo<Element>(node)) {
+ if (Element* pseudo = element->GetPseudoElement(kPseudoIdBefore))
AppendMarkedTree(indent.ToString(), pseudo, marked_node1, marked_label1,
marked_node2, marked_label2, builder);
- if (Element* pseudo = element.GetPseudoElement(kPseudoIdAfter))
+ if (Element* pseudo = element->GetPseudoElement(kPseudoIdAfter))
AppendMarkedTree(indent.ToString(), pseudo, marked_node1, marked_label1,
marked_node2, marked_label2, builder);
- if (Element* pseudo = element.GetPseudoElement(kPseudoIdFirstLetter))
+ if (Element* pseudo = element->GetPseudoElement(kPseudoIdFirstLetter))
AppendMarkedTree(indent.ToString(), pseudo, marked_node1, marked_label1,
marked_node2, marked_label2, builder);
- if (Element* pseudo = element.GetPseudoElement(kPseudoIdBackdrop))
+ if (Element* pseudo = element->GetPseudoElement(kPseudoIdBackdrop))
AppendMarkedTree(indent.ToString(), pseudo, marked_node1, marked_label1,
marked_node2, marked_label2, builder);
}
@@ -2267,7 +2367,7 @@ static void PrintSubTreeAcrossFrame(const Node* node,
std::ostream& stream) {
if (node == marked_node)
stream << "*";
- stream << indent.Utf8().data() << *node << "\n";
+ stream << indent.Utf8() << *node << "\n";
if (auto* frame_owner_element = DynamicTo<HTMLFrameOwnerElement>(node)) {
PrintSubTreeAcrossFrame(frame_owner_element->contentDocument(), marked_node,
indent + "\t", stream);
@@ -2303,7 +2403,7 @@ 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().
- return ToElement(const_cast<Node*>(node));
+ return To<Element>(const_cast<Node*>(node));
}
}
@@ -2326,11 +2426,11 @@ void Node::WillMoveToNewDocument(Document& old_document,
old_document.GetFrame()->GetEventHandlerRegistry().DidMoveOutOfPage(*this);
- if (IsElementNode()) {
+ if (auto* this_element = DynamicTo<Element>(this)) {
StylePropertyMapReadOnly* computed_style_map_item =
- old_document.RemoveComputedStyleMapItem(ToElement(this));
+ old_document.RemoveComputedStyleMapItem(this_element);
if (computed_style_map_item) {
- new_document.AddComputedStyleMapItem(ToElement(this),
+ new_document.AddComputedStyleMapItem(this_element,
computed_style_map_item);
}
}
@@ -2812,10 +2912,6 @@ HTMLSlotElement* Node::AssignedSlot() const {
ShadowRoot* root = V1ShadowRootOfParent();
if (!root)
return nullptr;
- if (!RuntimeEnabledFeatures::FastFlatTreeTraversalEnabled()) {
- // Don't recalc assignment in this case.
- return root->AssignedSlotFor(*this);
- }
if (!root->HasSlotAssignment())
return nullptr;
@@ -2824,7 +2920,7 @@ HTMLSlotElement* Node::AssignedSlot() const {
// in executing RecalcAssignment(), however, unfortunately,
// that could happen as follows:
//
- // 1. RecalsAssignment() can detach a node
+ // 1. RecalcAssignment() can detach a node
// 2. Then, DetachLayoutTree() may use FlatTreeTraversal via the hook of
// AXObjectCacheImpl::ChildrenChanged().
//
@@ -2867,18 +2963,10 @@ void Node::SetHasFocusWithin(bool flag) {
GetDocument().UserActionElements().SetHasFocusWithin(this, flag);
}
-void Node::SetActive(bool flag) {
- GetDocument().UserActionElements().SetActive(this, flag);
-}
-
void Node::SetDragged(bool flag) {
GetDocument().UserActionElements().SetDragged(this, flag);
}
-void Node::SetHovered(bool flag) {
- GetDocument().UserActionElements().SetHovered(this, flag);
-}
-
bool Node::IsUserActionElementActive() const {
DCHECK(IsUserActionElement());
return GetDocument().UserActionElements().IsActive(this);
@@ -2933,7 +3021,7 @@ void Node::SetCustomElementState(CustomElementState new_state) {
DCHECK(IsHTMLElement());
DCHECK_NE(kV0Upgraded, GetV0CustomElementState());
- Element* element = ToElement(this);
+ auto* element = To<Element>(this);
bool was_defined = element->IsDefined();
node_flags_ = (node_flags_ & ~kCustomElementStateMask) |
@@ -2971,8 +3059,8 @@ void Node::SetV0CustomElementState(V0CustomElementState new_state) {
SetFlag(new_state == kV0Upgraded, kV0CustomElementUpgradedFlag);
if (old_state == kV0NotCustomElement || new_state == kV0Upgraded) {
- ToElement(this)->PseudoStateChanged(CSSSelector::kPseudoUnresolved);
- ToElement(this)->PseudoStateChanged(CSSSelector::kPseudoDefined);
+ To<Element>(this)->PseudoStateChanged(CSSSelector::kPseudoUnresolved);
+ To<Element>(this)->PseudoStateChanged(CSSSelector::kPseudoDefined);
}
}
@@ -3059,6 +3147,21 @@ void Node::FlatTreeParentChanged() {
SetForceReattachLayoutTree();
}
+Node* Node::TrustedTypesCheckForScriptNode(
+ Node* child,
+ ExceptionState& exception_state) const {
+ DCHECK(child);
+ bool needs_check = IsHTMLScriptElement(this) && child->IsTextNode() &&
+ GetDocument().IsTrustedTypesEnabledForDoc();
+ if (!needs_check)
+ return child;
+
+ child = TrustedTypesCheckForHTMLScriptElement(child, &GetDocument(),
+ exception_state);
+ DCHECK_EQ(!child, exception_state.HadException());
+ return child;
+}
+
void Node::Trace(Visitor* visitor) {
visitor->Trace(parent_or_shadow_host_node_);
visitor->Trace(previous_);
@@ -3085,7 +3188,7 @@ void showNode(const blink::Node* node) {
void showTree(const blink::Node* node) {
if (node)
- LOG(INFO) << "\n" << node->ToTreeStringForThis().Utf8().data();
+ LOG(INFO) << "\n" << node->ToTreeStringForThis().Utf8();
else
LOG(INFO) << "Cannot showTree for <null>";
}
diff --git a/chromium/third_party/blink/renderer/core/dom/node.h b/chromium/third_party/blink/renderer/core/dom/node.h
index 41debcfc1cf..751c3e79e55 100644
--- a/chromium/third_party/blink/renderer/core/dom/node.h
+++ b/chromium/third_party/blink/renderer/core/dom/node.h
@@ -34,9 +34,9 @@
#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/layout/geometry/physical_rect.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/geometry/layout_rect.h"
// This needs to be here because element.cc also depends on it.
#define DUMP_NODE_STATISTICS 0
@@ -63,7 +63,7 @@ class MutationObserver;
class MutationObserverRegistration;
class NodeList;
class NodeListsNodeData;
-class NodeOrString;
+class NodeOrStringOrTrustedScript;
class NodeRareData;
class QualifiedName;
class RegisteredEventListener;
@@ -165,13 +165,12 @@ class CORE_EXPORT Node : public EventTarget {
// Override operator new to allocate Node subtype objects onto
// a dedicated heap.
- static void* AllocateObject(size_t size, bool is_eager) {
+ static void* AllocateObject(size_t size) {
ThreadState* state =
ThreadStateFor<ThreadingTrait<Node>::kAffinity>::GetState();
const char* type_name = "blink::Node";
return state->Heap().AllocateOnArenaIndex(
- state, size,
- is_eager ? BlinkGC::kEagerSweepArenaIndex : BlinkGC::kNodeArenaIndex,
+ state, size, BlinkGC::kNodeArenaIndex,
GCInfoTrait<EventTarget>::Index(), type_name);
}
@@ -220,11 +219,12 @@ class CORE_EXPORT Node : public EventTarget {
// https://dom.spec.whatwg.org/#concept-closed-shadow-hidden
bool IsClosedShadowHiddenFrom(const Node&) const;
- void Prepend(const HeapVector<NodeOrString>&, ExceptionState&);
- void Append(const HeapVector<NodeOrString>&, ExceptionState&);
- void Before(const HeapVector<NodeOrString>&, ExceptionState&);
- void After(const HeapVector<NodeOrString>&, ExceptionState&);
- void ReplaceWith(const HeapVector<NodeOrString>&, ExceptionState&);
+ void Prepend(const HeapVector<NodeOrStringOrTrustedScript>&, ExceptionState&);
+ void Append(const HeapVector<NodeOrStringOrTrustedScript>&, ExceptionState&);
+ void Before(const HeapVector<NodeOrStringOrTrustedScript>&, ExceptionState&);
+ void After(const HeapVector<NodeOrStringOrTrustedScript>&, ExceptionState&);
+ void ReplaceWith(const HeapVector<NodeOrStringOrTrustedScript>&,
+ ExceptionState&);
void remove(ExceptionState&);
void remove();
@@ -265,7 +265,7 @@ class CORE_EXPORT Node : public EventTarget {
bool SupportsAltText();
- void SetComputedStyle(scoped_refptr<ComputedStyle> computed_style);
+ void SetComputedStyle(scoped_refptr<const ComputedStyle> computed_style);
// Other methods (not part of DOM)
@@ -565,9 +565,7 @@ class CORE_EXPORT Node : public EventTarget {
virtual void SetFocused(bool flag, WebFocusType);
virtual void SetHasFocusWithin(bool flag);
- virtual void SetActive(bool flag = true);
virtual void SetDragged(bool flag);
- virtual void SetHovered(bool flag = true);
virtual int tabIndex() const;
@@ -582,7 +580,7 @@ class CORE_EXPORT Node : public EventTarget {
// inert to prevent text selection.
bool IsInert() const;
- virtual LayoutRect BoundingBox() const;
+ virtual PhysicalRect BoundingBox() const;
IntRect PixelSnappedBoundingBox() const {
return PixelSnappedIntRect(BoundingBox());
}
@@ -590,7 +588,7 @@ class CORE_EXPORT Node : public EventTarget {
// BoundingBoxForScrollIntoView() is the node's scroll snap area.
// It is expanded from the BoundingBox() by scroll-margin.
// https://drafts.csswg.org/css-scroll-snap-1/#scroll-snap-area
- LayoutRect BoundingBoxForScrollIntoView() const;
+ PhysicalRect BoundingBoxForScrollIntoView() const;
unsigned NodeIndex() const;
@@ -675,11 +673,19 @@ class CORE_EXPORT Node : public EventTarget {
// we don't need to backtrack past display:none/contents and out of flow
// objects when we need to do whitespace re-attachment.
LayoutObject* previous_in_flow = nullptr;
- // Set to true if the Attach/DetachLayoutTree is done as part of the
+ // The parent LayoutObject to use when inserting a new child into the layout
+ // tree in LayoutTreeBuilder::CreateLayoutObject.
+ LayoutObject* parent = nullptr;
+ // LayoutObject to be used as the next pointer when inserting a LayoutObject
+ // into the tree.
+ LayoutObject* next_sibling = nullptr;
+ // Set to true if the AttachLayoutTree is done as part of the
// RebuildLayoutTree pass.
bool performing_reattach = false;
// True if the previous_in_flow member is up-to-date, even if it is nullptr.
bool use_previous_in_flow = false;
+ // True if the next_sibling member is up-to-date, even if it is nullptr.
+ bool next_sibling_valid = false;
// True if we need to force legacy layout objects for the entire subtree.
bool force_legacy_layout = false;
@@ -695,12 +701,8 @@ class CORE_EXPORT Node : public EventTarget {
// Detaches the node from the layout tree, making it invisible in the rendered
// view. This method will remove the node's layout object from the layout tree
// and delete it.
- virtual void DetachLayoutTree(const AttachContext& = AttachContext());
+ virtual void DetachLayoutTree(bool performing_reattach = false);
- void ReattachLayoutTree() {
- AttachContext context;
- ReattachLayoutTree(context);
- }
void ReattachLayoutTree(AttachContext&);
// ---------------------------------------------------------------------------
@@ -709,7 +711,7 @@ class CORE_EXPORT Node : public EventTarget {
// 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.
- ComputedStyle* MutableComputedStyle() const;
+ ComputedStyle* MutableComputedStyleForEditingDeprecated() const;
const ComputedStyle* GetComputedStyle() const;
const ComputedStyle* ParentComputedStyle() const;
const ComputedStyle& ComputedStyleRef() const;
@@ -1049,6 +1051,9 @@ class CORE_EXPORT Node : public EventTarget {
const HeapHashSet<Member<MutationObserverRegistration>>*
TransientMutationObserverRegistry();
+ inline Node* TrustedTypesCheckForScriptNode(Node* child,
+ ExceptionState&) const;
+
uint32_t node_flags_;
Member<Node> parent_or_shadow_host_node_;
Member<TreeScope> tree_scope_;
diff --git a/chromium/third_party/blink/renderer/core/dom/node.idl b/chromium/third_party/blink/renderer/core/dom/node.idl
index 73f5989dc29..758feb3d188 100644
--- a/chromium/third_party/blink/renderer/core/dom/node.idl
+++ b/chromium/third_party/blink/renderer/core/dom/node.idl
@@ -20,7 +20,9 @@
// https://dom.spec.whatwg.org/#interface-node
-interface Node : EventTarget {
+[
+ Exposed=Window
+] interface Node : EventTarget {
const unsigned short ELEMENT_NODE = 1;
const unsigned short ATTRIBUTE_NODE = 2;
const unsigned short TEXT_NODE = 3;
diff --git a/chromium/third_party/blink/renderer/core/dom/node_computed_style.h b/chromium/third_party/blink/renderer/core/dom/node_computed_style.h
index e4411b966d7..a870a3d2610 100644
--- a/chromium/third_party/blink/renderer/core/dom/node_computed_style.h
+++ b/chromium/third_party/blink/renderer/core/dom/node_computed_style.h
@@ -33,11 +33,11 @@
namespace blink {
-inline const ComputedStyle* Node::GetComputedStyle() const {
- return MutableComputedStyle();
+inline ComputedStyle* Node::MutableComputedStyleForEditingDeprecated() const {
+ return const_cast<ComputedStyle*>(GetComputedStyle());
}
-inline ComputedStyle* Node::MutableComputedStyle() const {
+inline const ComputedStyle* Node::GetComputedStyle() const {
if (IsElementNode()) {
return HasRareData()
? data_.rare_data_->GetNodeRenderingData()->GetComputedStyle()
@@ -45,7 +45,7 @@ inline ComputedStyle* Node::MutableComputedStyle() const {
}
// Text nodes and Document.
if (LayoutObject* layout_object = GetLayoutObject())
- return layout_object->MutableStyle();
+ return layout_object->Style();
return nullptr;
}
diff --git a/chromium/third_party/blink/renderer/core/dom/node_filter.idl b/chromium/third_party/blink/renderer/core/dom/node_filter.idl
index e8ca30b88f1..f7ce8bcd7dc 100644
--- a/chromium/third_party/blink/renderer/core/dom/node_filter.idl
+++ b/chromium/third_party/blink/renderer/core/dom/node_filter.idl
@@ -21,7 +21,8 @@
// https://dom.spec.whatwg.org/#interface-nodefilter
[
- DoNotCheckConstants
+ DoNotCheckConstants,
+ Exposed=Window
] callback interface NodeFilter {
// Constants for acceptNode()
const unsigned short FILTER_ACCEPT = 1;
diff --git a/chromium/third_party/blink/renderer/core/dom/node_iterator.idl b/chromium/third_party/blink/renderer/core/dom/node_iterator.idl
index 54865148d29..2f88bafd866 100644
--- a/chromium/third_party/blink/renderer/core/dom/node_iterator.idl
+++ b/chromium/third_party/blink/renderer/core/dom/node_iterator.idl
@@ -20,7 +20,9 @@
// https://dom.spec.whatwg.org/#interface-nodeiterator
-interface NodeIterator {
+[
+ Exposed=Window
+] interface NodeIterator {
[SameObject] readonly attribute Node root;
readonly attribute Node referenceNode;
readonly attribute boolean pointerBeforeReferenceNode;
diff --git a/chromium/third_party/blink/renderer/core/dom/node_iterator_base.cc b/chromium/third_party/blink/renderer/core/dom/node_iterator_base.cc
index 5c09ca00ba3..493dc8882cf 100644
--- a/chromium/third_party/blink/renderer/core/dom/node_iterator_base.cc
+++ b/chromium/third_party/blink/renderer/core/dom/node_iterator_base.cc
@@ -27,8 +27,8 @@
#include "third_party/blink/renderer/bindings/core/v8/v8_node_filter.h"
#include "third_party/blink/renderer/core/dom/node.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/platform/bindings/exception_state.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/dom/node_list.idl b/chromium/third_party/blink/renderer/core/dom/node_list.idl
index 405afd6afb9..2c3f716f590 100644
--- a/chromium/third_party/blink/renderer/core/dom/node_list.idl
+++ b/chromium/third_party/blink/renderer/core/dom/node_list.idl
@@ -20,7 +20,9 @@
// https://dom.spec.whatwg.org/#interface-nodelist
-interface NodeList {
+[
+ Exposed=Window
+] interface NodeList {
[Affects=Nothing] getter Node? item(unsigned long index);
[Affects=Nothing] readonly attribute unsigned long length;
iterable<Node>;
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 80df6dfb43f..2d22fa4a219 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
@@ -67,8 +67,8 @@ class NodeRenderingData {
USING_FAST_MALLOC(NodeRenderingData);
public:
- explicit NodeRenderingData(LayoutObject*,
- scoped_refptr<ComputedStyle> computed_style);
+ NodeRenderingData(LayoutObject*,
+ scoped_refptr<const ComputedStyle> computed_style);
~NodeRenderingData();
LayoutObject* GetLayoutObject() const { return layout_object_; }
@@ -77,15 +77,17 @@ class NodeRenderingData {
layout_object_ = layout_object;
}
- ComputedStyle* GetComputedStyle() const { return computed_style_.get(); }
- void SetComputedStyle(scoped_refptr<ComputedStyle> computed_style);
+ const ComputedStyle* GetComputedStyle() const {
+ return computed_style_.get();
+ }
+ void SetComputedStyle(scoped_refptr<const ComputedStyle> computed_style);
static NodeRenderingData& SharedEmptyData();
bool IsSharedEmptyData() { return this == &SharedEmptyData(); }
private:
LayoutObject* layout_object_;
- scoped_refptr<ComputedStyle> computed_style_;
+ scoped_refptr<const ComputedStyle> computed_style_;
DISALLOW_COPY_AND_ASSIGN(NodeRenderingData);
};
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 fcda4bce575..06e48e53797 100644
--- a/chromium/third_party/blink/renderer/core/dom/node_test.cc
+++ b/chromium/third_party/blink/renderer/core/dom/node_test.cc
@@ -10,6 +10,7 @@
#include "third_party/blink/renderer/core/dom/comment.h"
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/dom/flat_tree_traversal.h"
+#include "third_party/blink/renderer/core/dom/layout_tree_builder.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/shadow_root_init.h"
@@ -40,6 +41,7 @@ class NodeTest : public EditingTestBase {
GetDocument().Lifecycle().AdvanceTo(DocumentLifecycle::kInStyleRecalc);
GetDocument().GetStyleEngine().RecalcStyle({});
Node::AttachContext context;
+ context.parent = LayoutTreeBuilderTraversal::ParentLayoutObject(node);
GetDocument().GetStyleEngine().in_layout_tree_rebuild_ = true;
node.ReattachLayoutTree(context);
return context.previous_in_flow;
diff --git a/chromium/third_party/blink/renderer/core/dom/node_traversal.h b/chromium/third_party/blink/renderer/core/dom/node_traversal.h
index f3a0b9df120..3dd5e077aa9 100644
--- a/chromium/third_party/blink/renderer/core/dom/node_traversal.h
+++ b/chromium/third_party/blink/renderer/core/dom/node_traversal.h
@@ -32,7 +32,7 @@
#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/dom/traversal_range.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/dom/non_document_type_child_node.h b/chromium/third_party/blink/renderer/core/dom/non_document_type_child_node.h
index 9edba9edc7c..d8b191affed 100644
--- a/chromium/third_party/blink/renderer/core/dom/non_document_type_child_node.h
+++ b/chromium/third_party/blink/renderer/core/dom/non_document_type_child_node.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/dom/element_traversal.h"
#include "third_party/blink/renderer/core/dom/node.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/dom/parent_node.h b/chromium/third_party/blink/renderer/core/dom/parent_node.h
index 88132e882ae..e8d5caf077b 100644
--- a/chromium/third_party/blink/renderer/core/dom/parent_node.h
+++ b/chromium/third_party/blink/renderer/core/dom/parent_node.h
@@ -35,7 +35,7 @@
#include "third_party/blink/renderer/core/dom/element_traversal.h"
#include "third_party/blink/renderer/core/html/html_collection.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -64,13 +64,13 @@ class ParentNode {
}
static void prepend(Node& node,
- const HeapVector<NodeOrString>& nodes,
+ const HeapVector<NodeOrStringOrTrustedScript>& nodes,
ExceptionState& exception_state) {
return node.Prepend(nodes, exception_state);
}
static void append(Node& node,
- const HeapVector<NodeOrString>& nodes,
+ const HeapVector<NodeOrStringOrTrustedScript>& nodes,
ExceptionState& exception_state) {
return node.Append(nodes, exception_state);
}
diff --git a/chromium/third_party/blink/renderer/core/dom/parent_node.idl b/chromium/third_party/blink/renderer/core/dom/parent_node.idl
index 6c99394eeea..f8beb25cd01 100644
--- a/chromium/third_party/blink/renderer/core/dom/parent_node.idl
+++ b/chromium/third_party/blink/renderer/core/dom/parent_node.idl
@@ -38,8 +38,8 @@
[Affects=Nothing, PerWorldBindings] readonly attribute Element? lastElementChild;
[Affects=Nothing] readonly attribute unsigned long childElementCount;
- [Unscopable, RaisesException, CEReactions, CustomElementCallbacks] void prepend((Node or DOMString)... nodes);
- [Unscopable, RaisesException, CEReactions, CustomElementCallbacks] void append((Node or DOMString)... nodes);
+ [Unscopable, RaisesException, CEReactions, CustomElementCallbacks] void prepend((Node or DOMString or TrustedScript)... nodes);
+ [Unscopable, RaisesException, CEReactions, CustomElementCallbacks] void append((Node or DOMString or TrustedScript)... nodes);
// [Unscopable] Element? query(DOMString relativeSelectors);
// [NewObject, Unscopable] Elements queryAll(DOMString relativeSelectors);
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 6198225564d..0d77d764fd6 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
@@ -43,7 +43,6 @@
#include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.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/text/cstring.h"
namespace blink {
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 0f3dcb29ea8..d718532ea3b 100644
--- a/chromium/third_party/blink/renderer/core/dom/processing_instruction.cc
+++ b/chromium/third_party/blink/renderer/core/dom/processing_instruction.cc
@@ -163,8 +163,8 @@ void ProcessingInstruction::Process(const String& href, const String& charset) {
loading_ = true;
if (is_xsl_) {
DCHECK(RuntimeEnabledFeatures::XSLTEnabled());
- params.MutableResourceRequest().SetFetchRequestMode(
- network::mojom::FetchRequestMode::kSameOrigin);
+ params.MutableResourceRequest().SetMode(
+ network::mojom::RequestMode::kSameOrigin);
XSLStyleSheetResource::Fetch(params, GetDocument().Fetcher(), this);
} else {
params.SetCharset(charset.IsEmpty() ? GetDocument().Encoding()
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 93c9a12cdc2..415ad69e302 100644
--- a/chromium/third_party/blink/renderer/core/dom/processing_instruction.h
+++ b/chromium/third_party/blink/renderer/core/dom/processing_instruction.h
@@ -81,7 +81,7 @@ class CORE_EXPORT ProcessingInstruction final : public CharacterData,
InsertionNotificationRequest InsertedInto(ContainerNode&) override;
void RemovedFrom(ContainerNode&) override;
- void DetachLayoutTree(const AttachContext&) final {}
+ void DetachLayoutTree(bool performing_reattach) final {}
bool CheckStyleSheet(String& href, String& charset);
void Process(const String& href, const String& charset);
diff --git a/chromium/third_party/blink/renderer/core/dom/processing_instruction.idl b/chromium/third_party/blink/renderer/core/dom/processing_instruction.idl
index a58cfbfdcb3..d7a40a3062e 100644
--- a/chromium/third_party/blink/renderer/core/dom/processing_instruction.idl
+++ b/chromium/third_party/blink/renderer/core/dom/processing_instruction.idl
@@ -20,7 +20,9 @@
// https://dom.spec.whatwg.org/#interface-processinginstruction
-interface ProcessingInstruction : CharacterData {
+[
+ Exposed=Window
+] interface ProcessingInstruction : CharacterData {
readonly attribute DOMString target;
// ProcessingInstruction includes LinkStyle
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 2f1cd6bcec9..ad19f70133b 100644
--- a/chromium/third_party/blink/renderer/core/dom/pseudo_element.cc
+++ b/chromium/third_party/blink/renderer/core/dom/pseudo_element.cc
@@ -31,13 +31,13 @@
#include "third_party/blink/renderer/core/dom/element_rare_data.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/frame/use_counter.h"
#include "third_party/blink/renderer/core/layout/generated_children.h"
#include "third_party/blink/renderer/core/layout/layout_object.h"
#include "third_party/blink/renderer/core/layout/layout_quote.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/content_data.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
@@ -142,7 +142,7 @@ void PseudoElement::Dispose() {
PseudoElement::AttachLayoutTreeScope::AttachLayoutTreeScope(
PseudoElement* element)
: element_(element) {
- if (ComputedStyle* style = element->MutableComputedStyle()) {
+ if (const ComputedStyle* style = element->GetComputedStyle()) {
if (style->Display() == EDisplay::kContents) {
original_style_ = style;
element->SetComputedStyle(element->LayoutStyleForDisplayContents(*style));
@@ -172,7 +172,7 @@ void PseudoElement::AttachLayoutTree(AttachContext& context) {
DCHECK(layout_object->Parent());
DCHECK(CanHaveGeneratedChildren(*layout_object->Parent()));
- ComputedStyle& style = layout_object->MutableStyleRef();
+ const ComputedStyle& style = layout_object->StyleRef();
if (style.StyleType() != kPseudoIdBefore &&
style.StyleType() != kPseudoIdAfter)
return;
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 e54dedc2810..a26d47bd337 100644
--- a/chromium/third_party/blink/renderer/core/dom/pseudo_element.h
+++ b/chromium/third_party/blink/renderer/core/dom/pseudo_element.h
@@ -69,7 +69,7 @@ class CORE_EXPORT PseudoElement : public Element {
private:
Member<PseudoElement> element_;
- scoped_refptr<ComputedStyle> original_style_;
+ scoped_refptr<const ComputedStyle> original_style_;
};
PseudoId pseudo_id_;
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 0551faa2e5d..2223714cd21 100644
--- a/chromium/third_party/blink/renderer/core/dom/qualified_name.h
+++ b/chromium/third_party/blink/renderer/core/dom/qualified_name.h
@@ -22,7 +22,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_DOM_QUALIFIED_NAME_H_
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_table_deleted_value_type.h"
#include "third_party/blink/renderer/platform/wtf/hash_traits.h"
#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
diff --git a/chromium/third_party/blink/renderer/core/dom/range.cc b/chromium/third_party/blink/renderer/core/dom/range.cc
index 9cc0d21984e..b0405107630 100644
--- a/chromium/third_party/blink/renderer/core/dom/range.cc
+++ b/chromium/third_party/blink/renderer/core/dom/range.cc
@@ -60,7 +60,6 @@
#include "third_party/blink/renderer/platform/geometry/float_quad.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
-#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
namespace blink {
@@ -994,8 +993,8 @@ DocumentFragment* Range::createContextualFragmentFromString(
if (!start_.Offset() &&
(node->IsDocumentNode() || node->IsDocumentFragment()))
element = nullptr;
- else if (node->IsElementNode())
- element = ToElement(node);
+ else if (auto* node_element = DynamicTo<Element>(node))
+ element = node_element;
else
element = node->parentElement();
@@ -1676,11 +1675,12 @@ void Range::GetBorderAndTextQuads(Vector<FloatQuad>& quads) const {
for (const Node* node = FirstNode(); node != stop_node;
node = NodeTraversal::Next(*node)) {
- if (node->IsElementNode()) {
+ auto* element_node = DynamicTo<Element>(node);
+ if (element_node) {
if (!selected_elements.Contains(node) ||
selected_elements.Contains(node->parentNode()))
continue;
- LayoutObject* const layout_object = ToElement(node)->GetLayoutObject();
+ LayoutObject* const layout_object = element_node->GetLayoutObject();
if (!layout_object)
continue;
Vector<FloatQuad> element_quads;
@@ -1817,7 +1817,6 @@ void showTree(const blink::Range* range) {
->ToMarkedTreeString(range->startContainer(), "S",
range->endContainer(), "E")
.Utf8()
- .data()
<< "start offset: " << range->startOffset()
<< ", end offset: " << range->endOffset();
} else {
diff --git a/chromium/third_party/blink/renderer/core/dom/range.idl b/chromium/third_party/blink/renderer/core/dom/range.idl
index 20959766617..c2ee325331f 100644
--- a/chromium/third_party/blink/renderer/core/dom/range.idl
+++ b/chromium/third_party/blink/renderer/core/dom/range.idl
@@ -21,7 +21,8 @@
// https://dom.spec.whatwg.org/#interface-range
[
Constructor,
- ConstructorCallWith=Document
+ ConstructorCallWith=Document,
+ Exposed=Window
] interface Range {
readonly attribute Node startContainer;
readonly attribute unsigned long startOffset;
diff --git a/chromium/third_party/blink/renderer/core/dom/scriptable_document_parser.h b/chromium/third_party/blink/renderer/core/dom/scriptable_document_parser.h
index 8f13d6a6ea1..61ac0c87702 100644
--- a/chromium/third_party/blink/renderer/core/dom/scriptable_document_parser.h
+++ b/chromium/third_party/blink/renderer/core/dom/scriptable_document_parser.h
@@ -48,8 +48,8 @@ class CORE_EXPORT ScriptableDocumentParser : public DecodedDataDocumentParser {
virtual void ExecuteScriptsWaitingForResources() {}
virtual bool IsWaitingForScripts() const = 0;
- virtual void DidAddPendingStylesheetInBody() {}
- virtual void DidLoadAllBodyStylesheets() {}
+ virtual void DidAddPendingParserBlockingStylesheet() {}
+ virtual void DidLoadAllPendingParserBlockingStylesheets() {}
// These are used to expose the current line/column to the scripting system.
virtual bool IsParsingAtLineNumber() const;
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 2629f8f4b55..72057a2e44f 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
@@ -15,7 +15,7 @@
#include "third_party/blink/renderer/core/dom/frame_request_callback_collection.h"
#include "third_party/blink/renderer/core/testing/dummy_page_holder.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
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 4d47f46b233..b2aa933fce8 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
@@ -11,7 +11,7 @@
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/inspector/inspector_trace_events.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
@@ -34,7 +34,7 @@ class IdleRequestCallbackWrapper
static void IdleTaskFired(
scoped_refptr<IdleRequestCallbackWrapper> callback_wrapper,
- TimeTicks deadline) {
+ base::TimeTicks deadline) {
if (ScriptedIdleTaskController* controller =
callback_wrapper->Controller()) {
// If we are going to yield immediately, reschedule the callback for
@@ -54,7 +54,7 @@ class IdleRequestCallbackWrapper
scoped_refptr<IdleRequestCallbackWrapper> callback_wrapper) {
if (ScriptedIdleTaskController* controller =
callback_wrapper->Controller()) {
- controller->CallbackFired(callback_wrapper->Id(), CurrentTimeTicks(),
+ controller->CallbackFired(callback_wrapper->Id(), base::TimeTicks::Now(),
IdleDeadline::CallbackType::kCalledByTimeout);
}
callback_wrapper->Cancel();
@@ -122,7 +122,7 @@ ScriptedIdleTaskController::RegisterCallback(
DCHECK(idle_task);
CallbackId id = NextCallbackId();
- TimeTicks queue_timestamp = TimeTicks::Now();
+ base::TimeTicks queue_timestamp = base::TimeTicks::Now();
uint32_t timeout_millis = options->timeout();
idle_tasks_.Set(id, MakeGarbageCollected<QueuedIdleTask>(
idle_task, queue_timestamp, timeout_millis));
@@ -153,7 +153,7 @@ void ScriptedIdleTaskController::ScheduleCallback(
FROM_HERE,
WTF::Bind(&internal::IdleRequestCallbackWrapper::TimeoutFired,
callback_wrapper),
- TimeDelta::FromMilliseconds(timeout_millis));
+ base::TimeDelta::FromMilliseconds(timeout_millis));
}
}
@@ -170,7 +170,7 @@ void ScriptedIdleTaskController::CancelCallback(CallbackId id) {
void ScriptedIdleTaskController::CallbackFired(
CallbackId id,
- TimeTicks deadline,
+ base::TimeTicks deadline,
IdleDeadline::CallbackType callback_type) {
if (!idle_tasks_.Contains(id))
return;
@@ -190,7 +190,7 @@ void ScriptedIdleTaskController::CallbackFired(
void ScriptedIdleTaskController::RunCallback(
CallbackId id,
- TimeTicks deadline,
+ base::TimeTicks deadline,
IdleDeadline::CallbackType callback_type) {
DCHECK(!paused_);
@@ -205,8 +205,8 @@ void ScriptedIdleTaskController::RunCallback(
IdleTask* idle_task = queued_idle_task->task();
DCHECK(idle_task);
- TimeTicks now = CurrentTimeTicks();
- TimeDelta allotted_time = std::max(deadline - now, TimeDelta());
+ base::TimeTicks now = base::TimeTicks::Now();
+ base::TimeDelta allotted_time = std::max(deadline - now, base::TimeDelta());
probe::AsyncTask async_task(GetExecutionContext(), idle_task);
probe::UserCallback probe(GetExecutionContext(), "requestIdleCallback",
@@ -252,7 +252,7 @@ void ScriptedIdleTaskController::ContextUnpaused() {
Vector<CallbackId> pending_timeouts;
pending_timeouts_.swap(pending_timeouts);
for (auto& id : pending_timeouts)
- RunCallback(id, CurrentTimeTicks(),
+ RunCallback(id, base::TimeTicks::Now(),
IdleDeadline::CallbackType::kCalledByTimeout);
// Repost idle tasks for any remaining callbacks.
@@ -268,7 +268,7 @@ void ScriptedIdleTaskController::ContextUnpaused() {
void ScriptedIdleTaskController::RecordIdleTaskMetrics(
QueuedIdleTask* queued_idle_task,
- TimeTicks run_timestamp,
+ base::TimeTicks run_timestamp,
IdleDeadline::CallbackType callback_type) {
UMA_HISTOGRAM_ENUMERATION(
"WebCore.ScriptedIdleTaskController.IdleTaskCallbackType", callback_type);
@@ -290,7 +290,7 @@ void ScriptedIdleTaskController::RecordIdleTaskMetrics(
ScriptedIdleTaskController::QueuedIdleTask::QueuedIdleTask(
IdleTask* idle_task,
- TimeTicks queue_timestamp,
+ base::TimeTicks queue_timestamp,
uint32_t timeout_millis)
: task_(idle_task),
queue_timestamp_(queue_timestamp),
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 b5803ffb5b3..4138b60733b 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
@@ -83,26 +83,26 @@ class CORE_EXPORT ScriptedIdleTaskController
void ContextLifecycleStateChanged(mojom::FrameLifecycleState) override;
void CallbackFired(CallbackId,
- TimeTicks deadline,
+ base::TimeTicks deadline,
IdleDeadline::CallbackType);
private:
class QueuedIdleTask : public GarbageCollectedFinalized<QueuedIdleTask> {
public:
QueuedIdleTask(IdleTask*,
- TimeTicks queue_timestamp,
+ base::TimeTicks queue_timestamp,
uint32_t timeout_millis);
virtual ~QueuedIdleTask() = default;
virtual void Trace(Visitor*);
IdleTask* task() { return task_; }
- TimeTicks queue_timestamp() const { return queue_timestamp_; }
+ base::TimeTicks queue_timestamp() const { return queue_timestamp_; }
uint32_t timeout_millis() const { return timeout_millis_; }
private:
Member<IdleTask> task_;
- TimeTicks queue_timestamp_;
+ base::TimeTicks queue_timestamp_;
uint32_t timeout_millis_;
};
@@ -121,10 +121,12 @@ class CORE_EXPORT ScriptedIdleTaskController
!WTF::IsHashTraitsEmptyValue<Traits, CallbackId>(id);
}
- void RunCallback(CallbackId, TimeTicks deadline, IdleDeadline::CallbackType);
+ void RunCallback(CallbackId,
+ base::TimeTicks deadline,
+ IdleDeadline::CallbackType);
void RecordIdleTaskMetrics(QueuedIdleTask*,
- TimeTicks run_timestamp,
+ base::TimeTicks run_timestamp,
IdleDeadline::CallbackType);
ThreadScheduler* scheduler_; // Not owned.
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 6af4c16b57d..6148dacc6af 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
@@ -45,6 +45,11 @@ class MockScriptedIdleTaskControllerScheduler final : public ThreadScheduler {
Thread::IdleTask idle_task) override {
idle_task_ = std::move(idle_task);
}
+ void PostDelayedIdleTask(const base::Location&,
+ base::TimeDelta,
+ Thread::IdleTask) override {
+ NOTIMPLEMENTED();
+ }
void PostNonNestableIdleTask(const base::Location&,
Thread::IdleTask) override {}
std::unique_ptr<PageScheduler> CreatePageScheduler(
@@ -73,7 +78,7 @@ class MockScriptedIdleTaskControllerScheduler final : public ThreadScheduler {
void SetV8Isolate(v8::Isolate* isolate) override {}
- void RunIdleTask() { std::move(idle_task_).Run(TimeTicks()); }
+ void RunIdleTask() { std::move(idle_task_).Run(base::TimeTicks()); }
bool HasIdleTask() const { return !!idle_task_; }
private:
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
deleted file mode 100644
index f4cfc3c6bdb..00000000000
--- a/chromium/third_party/blink/renderer/core/dom/scripted_task_queue.cc
+++ /dev/null
@@ -1,113 +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/dom/scripted_task_queue.h"
-
-#include <memory>
-#include <utility>
-
-#include "base/macros.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/core/v8/v8_task_queue_post_callback.h"
-#include "third_party/blink/renderer/core/dom/abort_signal.h"
-#include "third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h"
-#include "third_party/blink/renderer/platform/wtf/functional.h"
-
-namespace blink {
-
-class ScriptedTaskQueue::WrappedCallback
- : public GarbageCollectedFinalized<WrappedCallback> {
- public:
- WrappedCallback(V8TaskQueuePostCallback* callback,
- ScriptPromiseResolver* resolver,
- TaskHandle task_handle)
- : callback_(callback),
- resolver_(resolver),
- task_handle_(std::move(task_handle)) {}
-
- void Trace(Visitor* visitor) {
- visitor->Trace(callback_);
- visitor->Trace(resolver_);
- }
-
- void Invoke() {
- callback_->InvokeAndReportException(nullptr);
- resolver_->Resolve();
- }
-
- void Reject() { resolver_->Reject(); }
-
- private:
- Member<V8TaskQueuePostCallback> callback_;
- Member<ScriptPromiseResolver> resolver_;
- TaskHandle task_handle_;
-
- DISALLOW_COPY_AND_ASSIGN(WrappedCallback);
-};
-
-ScriptedTaskQueue::ScriptedTaskQueue(ExecutionContext* context,
- TaskType task_type)
- : ContextLifecycleObserver(context) {
- task_runner_ = GetExecutionContext()->GetTaskRunner(task_type);
-}
-
-void ScriptedTaskQueue::Trace(Visitor* visitor) {
- visitor->Trace(pending_tasks_);
- ScriptWrappable::Trace(visitor);
- ContextLifecycleObserver::Trace(visitor);
-}
-
-ScriptPromise ScriptedTaskQueue::postTask(ScriptState* script_state,
- V8TaskQueuePostCallback* callback,
- AbortSignal* signal) {
- CallbackId id = next_callback_id_++;
-
- auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state);
-
- if (signal) {
- if (signal->aborted()) {
- resolver->Reject();
- return resolver->Promise();
- }
-
- signal->AddAlgorithm(
- WTF::Bind(&ScriptedTaskQueue::AbortTask, WrapPersistent(this), id));
- }
-
- TaskHandle task_handle = PostCancellableTask(
- *task_runner_, FROM_HERE,
- WTF::Bind(&ScriptedTaskQueue::CallbackFired, WrapPersistent(this), id));
-
- pending_tasks_.Set(id, MakeGarbageCollected<WrappedCallback>(
- callback, resolver, std::move(task_handle)));
-
- return resolver->Promise();
-}
-
-void ScriptedTaskQueue::CallbackFired(CallbackId id) {
- auto task_iter = pending_tasks_.find(id);
- if (task_iter == pending_tasks_.end())
- return;
-
- task_iter->value->Invoke();
- // Can't use the iterator here since running the task
- // might invalidate it.
- pending_tasks_.erase(id);
-}
-
-void ScriptedTaskQueue::AbortTask(CallbackId id) {
- auto task_iter = pending_tasks_.find(id);
- if (task_iter == pending_tasks_.end())
- return;
-
- task_iter->value->Reject();
- pending_tasks_.erase(id);
-}
-
-void ScriptedTaskQueue::ContextDestroyed(ExecutionContext*) {
- pending_tasks_.clear();
-}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/dom/scripted_task_queue.h b/chromium/third_party/blink/renderer/core/dom/scripted_task_queue.h
deleted file mode 100644
index 98bebb59bb8..00000000000
--- a/chromium/third_party/blink/renderer/core/dom/scripted_task_queue.h
+++ /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.
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_DOM_SCRIPTED_TASK_QUEUE_H_
-#define THIRD_PARTY_BLINK_RENDERER_CORE_DOM_SCRIPTED_TASK_QUEUE_H_
-
-#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
-#include "third_party/blink/renderer/core/execution_context/context_lifecycle_observer.h"
-#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
-#include "third_party/blink/renderer/platform/heap/handle.h"
-
-namespace blink {
-
-class AbortSignal;
-class ScriptState;
-class V8TaskQueuePostCallback;
-
-// This class corresponds to the ScriptedTaskQueue interface.
-class CORE_EXPORT ScriptedTaskQueue final : public ScriptWrappable,
- public ContextLifecycleObserver {
- DEFINE_WRAPPERTYPEINFO();
- USING_GARBAGE_COLLECTED_MIXIN(ScriptedTaskQueue);
-
- public:
- static ScriptedTaskQueue* Create(ExecutionContext* context,
- TaskType task_type) {
- return MakeGarbageCollected<ScriptedTaskQueue>(context, task_type);
- }
-
- explicit ScriptedTaskQueue(ExecutionContext*, TaskType);
-
- using CallbackId = int;
-
- ScriptPromise postTask(ScriptState*,
- V8TaskQueuePostCallback* callback,
- AbortSignal*);
-
- void CallbackFired(CallbackId id);
-
- void Trace(Visitor*) override;
-
- private:
- // ContextLifecycleObserver interface.
- void ContextDestroyed(ExecutionContext*) override;
-
- void AbortTask(CallbackId id);
-
- class WrappedCallback;
- HeapHashMap<CallbackId, Member<WrappedCallback>> pending_tasks_;
- CallbackId next_callback_id_ = 1;
- scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_CORE_DOM_SCRIPTED_TASK_QUEUE_H_
diff --git a/chromium/third_party/blink/renderer/core/dom/scripted_task_queue.idl b/chromium/third_party/blink/renderer/core/dom/scripted_task_queue.idl
deleted file mode 100644
index 6eeb70b8b40..00000000000
--- a/chromium/third_party/blink/renderer/core/dom/scripted_task_queue.idl
+++ /dev/null
@@ -1,9 +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.
-
-callback TaskQueuePostCallback = void ();
-
-[RuntimeEnabled=WorkerTaskQueue] interface ScriptedTaskQueue {
- [CallWith=ScriptState] Promise<any> postTask(TaskQueuePostCallback callback, optional AbortSignal signal = null);
-};
diff --git a/chromium/third_party/blink/renderer/core/dom/scripted_task_queue_controller.cc b/chromium/third_party/blink/renderer/core/dom/scripted_task_queue_controller.cc
deleted file mode 100644
index fa6c7adc8e3..00000000000
--- a/chromium/third_party/blink/renderer/core/dom/scripted_task_queue_controller.cc
+++ /dev/null
@@ -1,60 +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/dom/scripted_task_queue_controller.h"
-
-#include "third_party/blink/renderer/core/dom/document.h"
-#include "third_party/blink/renderer/core/dom/scripted_task_queue.h"
-#include "third_party/blink/renderer/platform/bindings/exception_state.h"
-#include "third_party/blink/renderer/platform/bindings/script_state.h"
-
-namespace blink {
-
-const char ScriptedTaskQueueController::kSupplementName[] =
- "ScriptedTaskQueueController";
-
-ScriptedTaskQueueController* ScriptedTaskQueueController::From(
- Document& document) {
- ScriptedTaskQueueController* task_queue_controller =
- Supplement<Document>::From<ScriptedTaskQueueController>(document);
- if (!task_queue_controller) {
- task_queue_controller =
- MakeGarbageCollected<ScriptedTaskQueueController>(&document);
- Supplement<Document>::ProvideTo(document, task_queue_controller);
- }
- return task_queue_controller;
-}
-
-ScriptedTaskQueueController::ScriptedTaskQueueController(
- ExecutionContext* context)
- : ContextLifecycleObserver(context) {}
-
-void ScriptedTaskQueueController::Trace(Visitor* visitor) {
- visitor->Trace(task_queues_);
- Supplement<Document>::Trace(visitor);
- ScriptWrappable::Trace(visitor);
- ContextLifecycleObserver::Trace(visitor);
-}
-
-ScriptedTaskQueue* ScriptedTaskQueueController::defaultQueue(
- const String& queue_name) {
- auto iter = task_queues_.find(queue_name);
- if (iter != task_queues_.end()) {
- return iter->value.Get();
- }
-
- TaskType task_type = TaskType::kExperimentalWebSchedulingBestEffort;
- if (queue_name == "user-interaction")
- task_type = TaskType::kExperimentalWebSchedulingUserInteraction;
- else if (queue_name != "best-effort")
- NOTREACHED();
-
- auto* task_queue =
- ScriptedTaskQueue::Create(GetExecutionContext(), task_type);
- task_queues_.insert(queue_name, task_queue);
-
- return task_queue;
-}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/dom/scripted_task_queue_controller.h b/chromium/third_party/blink/renderer/core/dom/scripted_task_queue_controller.h
deleted file mode 100644
index 07446c95222..00000000000
--- a/chromium/third_party/blink/renderer/core/dom/scripted_task_queue_controller.h
+++ /dev/null
@@ -1,47 +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_DOM_SCRIPTED_TASK_QUEUE_CONTROLLER_H_
-#define THIRD_PARTY_BLINK_RENDERER_CORE_DOM_SCRIPTED_TASK_QUEUE_CONTROLLER_H_
-
-#include "third_party/blink/renderer/core/dom/document.h"
-#include "third_party/blink/renderer/core/execution_context/context_lifecycle_observer.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/supplementable.h"
-#include "third_party/blink/renderer/platform/wtf/hash_map.h"
-#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
-
-namespace blink {
-
-class Document;
-
-class ScriptedTaskQueue;
-
-// This class corresponds to the ScriptedTaskQueueController interface.
-class CORE_EXPORT ScriptedTaskQueueController final
- : public ScriptWrappable,
- public ContextLifecycleObserver,
- public Supplement<Document> {
- DEFINE_WRAPPERTYPEINFO();
- USING_GARBAGE_COLLECTED_MIXIN(ScriptedTaskQueueController);
-
- public:
- static const char kSupplementName[];
-
- static ScriptedTaskQueueController* From(Document&);
-
- ScriptedTaskQueue* defaultQueue(const String&);
-
- explicit ScriptedTaskQueueController(ExecutionContext*);
-
- void Trace(Visitor*) override;
-
- private:
- HeapHashMap<String, Member<ScriptedTaskQueue>> task_queues_;
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_CORE_DOM_SCRIPTED_TASK_QUEUE_CONTROLLER_H_
diff --git a/chromium/third_party/blink/renderer/core/dom/scripted_task_queue_controller.idl b/chromium/third_party/blink/renderer/core/dom/scripted_task_queue_controller.idl
deleted file mode 100644
index be7e6275d2c..00000000000
--- a/chromium/third_party/blink/renderer/core/dom/scripted_task_queue_controller.idl
+++ /dev/null
@@ -1,9 +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.
-
-enum MainThreadTaskQueueType { "user-interaction", "best-effort" };
-
-[RuntimeEnabled=WorkerTaskQueue] interface ScriptedTaskQueueController {
- [ImplementedAs=defaultQueue] ScriptedTaskQueue default(MainThreadTaskQueueType queue_type);
-};
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 e1b14d1c5db..6bfc4a63f3f 100644
--- a/chromium/third_party/blink/renderer/core/dom/shadow_root.cc
+++ b/chromium/third_party/blink/renderer/core/dom/shadow_root.cc
@@ -223,7 +223,7 @@ void ShadowRoot::ChildrenChanged(const ChildrenChange& change) {
CheckForSiblingStyleChanges(
change.type == kElementRemoved ? kSiblingElementRemoved
: kSiblingElementInserted,
- ToElement(change.sibling_changed), change.sibling_before_change,
+ To<Element>(change.sibling_changed.Get()), change.sibling_before_change,
change.sibling_after_change);
}
}
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 18f775932e8..5cce67184ee 100644
--- a/chromium/third_party/blink/renderer/core/dom/shadow_root.h
+++ b/chromium/third_party/blink/renderer/core/dom/shadow_root.h
@@ -67,7 +67,7 @@ class CORE_EXPORT ShadowRoot final : public DocumentFragment, public TreeScope {
Element& host() const {
DCHECK(ParentOrShadowHostNode());
- return *ToElement(ParentOrShadowHostNode());
+ return *To<Element>(ParentOrShadowHostNode());
}
ShadowRootType GetType() const { return static_cast<ShadowRootType>(type_); }
String mode() const {
@@ -210,9 +210,10 @@ inline void ShadowRoot::DistributeIfNeeded() {
}
inline ShadowRoot* Node::GetShadowRoot() const {
- if (!IsElementNode())
+ auto* this_element = DynamicTo<Element>(this);
+ if (!this_element)
return nullptr;
- return ToElement(this)->GetShadowRoot();
+ return this_element->GetShadowRoot();
}
inline ShadowRoot* Element::ShadowRootIfV1() const {
diff --git a/chromium/third_party/blink/renderer/core/dom/shadow_root.idl b/chromium/third_party/blink/renderer/core/dom/shadow_root.idl
index 851c72ef254..ec004dfb701 100644
--- a/chromium/third_party/blink/renderer/core/dom/shadow_root.idl
+++ b/chromium/third_party/blink/renderer/core/dom/shadow_root.idl
@@ -24,8 +24,9 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-// https://w3c.github.io/webcomponents/spec/shadow/#the-shadowroot-interface
+// https://dom.spec.whatwg.org/#interface-shadowroot
+[Exposed=Window]
interface ShadowRoot : DocumentFragment {
readonly attribute ShadowRootMode mode;
readonly attribute Element host;
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 35aa3469ae7..bac9cd8ba82 100644
--- a/chromium/third_party/blink/renderer/core/dom/sink_document.cc
+++ b/chromium/third_party/blink/renderer/core/dom/sink_document.cc
@@ -26,7 +26,7 @@
#include "third_party/blink/renderer/core/dom/sink_document.h"
#include "third_party/blink/renderer/core/dom/raw_data_document_parser.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
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 e838fa3a301..ddb5ccf1aef 100644
--- a/chromium/third_party/blink/renderer/core/dom/slot_assignment.cc
+++ b/chromium/third_party/blink/renderer/core/dom/slot_assignment.cc
@@ -154,12 +154,10 @@ void SlotAssignment::DidRemoveSlotInternal(
if (FindHostChildBySlotName(slot_name)) {
// |slot| lost assigned nodes
if (slot_mutation_type == SlotMutationType::kRemoved) {
- if (RuntimeEnabledFeatures::FastFlatTreeTraversalEnabled()) {
- // |slot|'s previously assigned nodes' flat tree node data became
- // dirty. Call SetNeedsAssignmentRecalc() to clear their flat tree
- // node data surely in recalc timing.
- SetNeedsAssignmentRecalc();
- }
+ // |slot|'s previously assigned nodes' flat tree node data became
+ // dirty. Call SetNeedsAssignmentRecalc() to clear their flat tree
+ // node data surely in recalc timing.
+ SetNeedsAssignmentRecalc();
slot.DidSlotChangeAfterRemovedFromShadowTree();
} else {
slot.DidSlotChangeAfterRenaming();
@@ -288,8 +286,7 @@ void SlotAssignment::RecalcAssignment() {
if (slot) {
slot->AppendAssignedNode(child);
} else {
- if (RuntimeEnabledFeatures::FastFlatTreeTraversalEnabled())
- child.ClearFlatTreeNodeData();
+ child.ClearFlatTreeNodeData();
child.RemovedFromFlatTree();
}
}
diff --git a/chromium/third_party/blink/renderer/core/dom/slot_assignment_engine.cc b/chromium/third_party/blink/renderer/core/dom/slot_assignment_engine.cc
index d3eb72116d4..4c247b4017e 100644
--- a/chromium/third_party/blink/renderer/core/dom/slot_assignment_engine.cc
+++ b/chromium/third_party/blink/renderer/core/dom/slot_assignment_engine.cc
@@ -40,6 +40,9 @@ void SlotAssignmentEngine::Disconnected(ShadowRoot& shadow_root) {
}
void SlotAssignmentEngine::RecalcSlotAssignments() {
+ if (shadow_roots_needing_recalc_.IsEmpty())
+ return;
+ TRACE_EVENT0("blink", "SlotAssignmentEngine::RecalcSlotAssignments");
for (auto& shadow_root :
HeapHashSet<WeakMember<ShadowRoot>>(shadow_roots_needing_recalc_)) {
DCHECK(shadow_root->isConnected());
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 e5c4dea67e6..39054a0e03f 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
@@ -71,7 +71,7 @@ void RemoveWhiteSpaceOnlyTextNode(ContainerNode& container) {
if (auto* text = DynamicTo<Text>(descendant)) {
if (text->ContainsOnlyWhitespaceOrEmpty())
text->remove();
- } else if (Element* element = ToElementOrNull(descendant)) {
+ } else if (auto* element = DynamicTo<Element>(descendant)) {
if (ShadowRoot* shadow_root = element->OpenShadowRoot())
RemoveWhiteSpaceOnlyTextNode(*shadow_root);
}
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 e69a933905b..21ac9d79269 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
@@ -22,7 +22,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_DOM_SPACE_SPLIT_STRING_H_
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
diff --git a/chromium/third_party/blink/renderer/core/dom/static_range.idl b/chromium/third_party/blink/renderer/core/dom/static_range.idl
index 71005a55ffa..0aa967a0ad9 100644
--- a/chromium/third_party/blink/renderer/core/dom/static_range.idl
+++ b/chromium/third_party/blink/renderer/core/dom/static_range.idl
@@ -4,7 +4,9 @@
// https://w3c.github.io/staticrange/#interface-staticrange
-interface StaticRange {
+[
+ Exposed=Window
+] interface StaticRange {
readonly attribute Node startContainer;
readonly attribute unsigned long startOffset;
readonly attribute Node endContainer;
diff --git a/chromium/third_party/blink/renderer/core/dom/task_type_traits.h b/chromium/third_party/blink/renderer/core/dom/task_type_traits.h
index 523e0a628ed..ce9699d292b 100644
--- a/chromium/third_party/blink/renderer/core/dom/task_type_traits.h
+++ b/chromium/third_party/blink/renderer/core/dom/task_type_traits.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_DOM_TASK_TYPE_TRAITS_H_
#include "third_party/blink/public/platform/task_type.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_traits.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/dom/text.cc b/chromium/third_party/blink/renderer/core/dom/text.cc
index 65c3f628152..d6d073afb9d 100644
--- a/chromium/third_party/blink/renderer/core/dom/text.cc
+++ b/chromium/third_party/blink/renderer/core/dom/text.cc
@@ -42,7 +42,6 @@
#include "third_party/blink/renderer/core/svg_names.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/wtf/text/cstring.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
namespace blink {
@@ -250,9 +249,9 @@ static inline bool EndsWithWhitespace(const String& text) {
}
static inline bool CanHaveWhitespaceChildren(
- const LayoutObject& parent,
const ComputedStyle& style,
const Text::AttachContext& context) {
+ const LayoutObject& parent = *context.parent;
// <button> and <fieldset> should allow whitespace even though
// LayoutFlexibleBox doesn't.
if (parent.IsLayoutButton() || parent.IsFieldset())
@@ -275,10 +274,10 @@ static inline bool CanHaveWhitespaceChildren(
}
bool Text::TextLayoutObjectIsNeeded(const AttachContext& context,
- const ComputedStyle& style,
- const LayoutObject& parent) const {
+ const ComputedStyle& style) const {
DCHECK(!GetDocument().ChildNeedsDistributionRecalc());
+ const LayoutObject& parent = *context.parent;
if (!parent.CanHaveChildren())
return false;
@@ -294,7 +293,7 @@ bool Text::TextLayoutObjectIsNeeded(const AttachContext& context,
if (!ContainsOnlyWhitespaceOrEmpty())
return true;
- if (!CanHaveWhitespaceChildren(parent, style, context))
+ if (!CanHaveWhitespaceChildren(style, context))
return false;
// pre-wrap in SVG never makes layoutObject.
@@ -339,47 +338,41 @@ LayoutText* Text::CreateTextLayoutObject(const ComputedStyle& style,
}
void Text::AttachLayoutTree(AttachContext& context) {
- ContainerNode* style_parent = LayoutTreeBuilderTraversal::Parent(*this);
- LayoutObject* parent_layout_object =
- LayoutTreeBuilderTraversal::ParentLayoutObject(*this);
-
- if (style_parent && parent_layout_object) {
- DCHECK(style_parent->GetComputedStyle());
- if (TextLayoutObjectIsNeeded(context, *style_parent->GetComputedStyle(),
- *parent_layout_object)) {
- LayoutTreeBuilderForText(*this, parent_layout_object,
- style_parent->MutableComputedStyle())
- .CreateLayoutObject();
- context.previous_in_flow = GetLayoutObject();
+ if (context.parent) {
+ ContainerNode* style_parent = LayoutTreeBuilderTraversal::Parent(*this);
+ if (style_parent) {
+ const ComputedStyle* style = style_parent->GetComputedStyle();
+ DCHECK(style);
+ if (TextLayoutObjectIsNeeded(context, *style)) {
+ LayoutTreeBuilderForText(*this, context, style).CreateLayoutObject();
+ context.previous_in_flow = GetLayoutObject();
+ }
}
}
CharacterData::AttachLayoutTree(context);
}
-void Text::ReattachLayoutTreeIfNeeded(const AttachContext& context) {
+void Text::ReattachLayoutTreeIfNeeded(AttachContext& context) {
bool layout_object_is_needed = false;
ContainerNode* style_parent = LayoutTreeBuilderTraversal::Parent(*this);
- LayoutObject* parent_layout_object =
- LayoutTreeBuilderTraversal::ParentLayoutObject(*this);
- if (style_parent && parent_layout_object) {
+ if (style_parent && context.parent) {
DCHECK(style_parent->GetComputedStyle());
- layout_object_is_needed = TextLayoutObjectIsNeeded(
- context, *style_parent->GetComputedStyle(), *parent_layout_object);
+ layout_object_is_needed =
+ TextLayoutObjectIsNeeded(context, *style_parent->GetComputedStyle());
}
if (layout_object_is_needed == !!GetLayoutObject())
return;
- AttachContext reattach_context;
+ AttachContext reattach_context(context);
reattach_context.performing_reattach = true;
if (layout_object_is_needed) {
DCHECK(!GetLayoutObject());
- LayoutTreeBuilderForText(*this, parent_layout_object,
- style_parent->MutableComputedStyle())
+ LayoutTreeBuilderForText(*this, context, style_parent->GetComputedStyle())
.CreateLayoutObject();
} else {
- DetachLayoutTree(reattach_context);
+ DetachLayoutTree(true /* performing_reattach*/);
}
CharacterData::AttachLayoutTree(reattach_context);
}
@@ -393,7 +386,7 @@ bool NeedsWhitespaceLayoutObject(const ComputedStyle& style) {
} // namespace
void Text::RecalcTextStyle(const StyleRecalcChange change) {
- scoped_refptr<ComputedStyle> new_style =
+ scoped_refptr<const ComputedStyle> new_style =
GetDocument().EnsureStyleResolver().StyleForText(this);
if (LayoutText* layout_text = GetLayoutObject()) {
const ComputedStyle* layout_parent_style =
@@ -422,7 +415,9 @@ void Text::RebuildTextLayoutTree(WhitespaceAttacher& whitespace_attacher) {
DCHECK(NeedsReattachLayoutTree());
DCHECK(parentNode());
- ReattachLayoutTree();
+ AttachContext context;
+ context.parent = LayoutTreeBuilderTraversal::ParentLayoutObject(*this);
+ ReattachLayoutTree(context);
whitespace_attacher.DidReattachText(this);
ClearNeedsReattachLayoutTree();
}
@@ -437,17 +432,22 @@ static bool ShouldUpdateLayoutByReattaching(const Text& text_node,
// In general we do not want to branch on lifecycle states such as
// |ChildNeedsDistributionRecalc|, but this code tries to figure out if we can
// use an optimized code path that avoids reattach.
+ Node::AttachContext context;
+ context.parent = text_layout_object->Parent();
if (!text_node.GetDocument().ChildNeedsDistributionRecalc() &&
- !text_node.TextLayoutObjectIsNeeded(Node::AttachContext(),
- *text_layout_object->Style(),
- *text_layout_object->Parent())) {
+ !text_node.TextLayoutObjectIsNeeded(context,
+ *text_layout_object->Style())) {
return true;
}
if (text_layout_object->IsTextFragment()) {
// Changes of |textNode| may change first letter part, so we should
- // reattach.
- return ToLayoutTextFragment(text_layout_object)
- ->GetFirstLetterPseudoElement();
+ // reattach. Note: When |textNode| is empty or holds collapsed white spaces
+ // |text_fragment_layout_object| represents first-letter part but it isn't
+ // inside first-letter-pseudo element. See http://crbug.com/978947
+ const auto& text_fragment_layout_object =
+ *ToLayoutTextFragment(text_layout_object);
+ return text_fragment_layout_object.GetFirstLetterPseudoElement() ||
+ !text_fragment_layout_object.IsRemainingTextLayoutObject();
}
return false;
}
diff --git a/chromium/third_party/blink/renderer/core/dom/text.h b/chromium/third_party/blink/renderer/core/dom/text.h
index b029cb878f7..519f53553de 100644
--- a/chromium/third_party/blink/renderer/core/dom/text.h
+++ b/chromium/third_party/blink/renderer/core/dom/text.h
@@ -62,14 +62,13 @@ class CORE_EXPORT Text : public CharacterData {
void RecalcTextStyle(const StyleRecalcChange);
void RebuildTextLayoutTree(WhitespaceAttacher&);
bool TextLayoutObjectIsNeeded(const AttachContext&,
- const ComputedStyle&,
- const LayoutObject& parent) const;
+ const ComputedStyle&) const;
LayoutText* CreateTextLayoutObject(const ComputedStyle&, LegacyLayout);
void UpdateTextLayoutObject(unsigned offset_of_replaced_data,
unsigned length_of_replaced_data);
void AttachLayoutTree(AttachContext&) final;
- void ReattachLayoutTreeIfNeeded(const AttachContext&);
+ void ReattachLayoutTreeIfNeeded(AttachContext&);
bool CanContainRangeEndPoint() const final { return true; }
NodeType getNodeType() const override;
diff --git a/chromium/third_party/blink/renderer/core/dom/text.idl b/chromium/third_party/blink/renderer/core/dom/text.idl
index 36f98f54d0a..d199fd7adf7 100644
--- a/chromium/third_party/blink/renderer/core/dom/text.idl
+++ b/chromium/third_party/blink/renderer/core/dom/text.idl
@@ -21,7 +21,8 @@
[
Constructor(optional DOMString data = ""),
- ConstructorCallWith=Document
+ ConstructorCallWith=Document,
+ Exposed=Window
] interface Text : CharacterData {
[NewObject, DoNotTestNewObject, RaisesException] Text splitText(unsigned long offset);
[MeasureAs=TextWholeText] readonly attribute DOMString wholeText;
diff --git a/chromium/third_party/blink/renderer/core/dom/text_link_colors.h b/chromium/third_party/blink/renderer/core/dom/text_link_colors.h
index ba443457589..9ce3ff09788 100644
--- a/chromium/third_party/blink/renderer/core/dom/text_link_colors.h
+++ b/chromium/third_party/blink/renderer/core/dom/text_link_colors.h
@@ -33,7 +33,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/platform/graphics/color.h"
#include "third_party/blink/renderer/platform/graphics/color_scheme.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 0da8aa21d92..da82754f998 100644
--- a/chromium/third_party/blink/renderer/core/dom/text_test.cc
+++ b/chromium/third_party/blink/renderer/core/dom/text_test.cc
@@ -47,17 +47,18 @@ TEST_F(TextTest, TextLayoutObjectIsNeeded_CannotHaveChildren) {
Element* img = GetDocument().getElementById("image");
ASSERT_TRUE(img);
- const LayoutObject* img_layout = img->GetLayoutObject();
+ LayoutObject* img_layout = img->GetLayoutObject();
ASSERT_TRUE(img_layout);
const ComputedStyle& style = img_layout->StyleRef();
Text* text = Text::Create(GetDocument(), "dummy");
Node::AttachContext context;
- EXPECT_FALSE(text->TextLayoutObjectIsNeeded(context, style, *img_layout));
+ context.parent = img_layout;
+ EXPECT_FALSE(text->TextLayoutObjectIsNeeded(context, style));
context.use_previous_in_flow = true;
- EXPECT_FALSE(text->TextLayoutObjectIsNeeded(context, style, *img_layout));
+ EXPECT_FALSE(text->TextLayoutObjectIsNeeded(context, style));
}
TEST_F(TextTest, TextLayoutObjectIsNeeded_EditingText) {
@@ -67,7 +68,7 @@ TEST_F(TextTest, TextLayoutObjectIsNeeded_EditingText) {
Element* parent = GetDocument().getElementById("parent");
ASSERT_TRUE(parent);
- const LayoutObject* parent_layout = parent->GetLayoutObject();
+ LayoutObject* parent_layout = parent->GetLayoutObject();
ASSERT_TRUE(parent_layout);
const ComputedStyle& style = parent_layout->StyleRef();
@@ -76,18 +77,15 @@ TEST_F(TextTest, TextLayoutObjectIsNeeded_EditingText) {
Text* text = Text::CreateEditingText(GetDocument(), "dummy");
Node::AttachContext context;
- EXPECT_TRUE(
- text_empty->TextLayoutObjectIsNeeded(context, style, *parent_layout));
- EXPECT_TRUE(text_whitespace->TextLayoutObjectIsNeeded(context, style,
- *parent_layout));
- EXPECT_TRUE(text->TextLayoutObjectIsNeeded(context, style, *parent_layout));
+ context.parent = parent_layout;
+ EXPECT_TRUE(text_empty->TextLayoutObjectIsNeeded(context, style));
+ EXPECT_TRUE(text_whitespace->TextLayoutObjectIsNeeded(context, style));
+ EXPECT_TRUE(text->TextLayoutObjectIsNeeded(context, style));
context.use_previous_in_flow = true;
- EXPECT_TRUE(
- text_empty->TextLayoutObjectIsNeeded(context, style, *parent_layout));
- EXPECT_TRUE(text_whitespace->TextLayoutObjectIsNeeded(context, style,
- *parent_layout));
- EXPECT_TRUE(text->TextLayoutObjectIsNeeded(context, style, *parent_layout));
+ EXPECT_TRUE(text_empty->TextLayoutObjectIsNeeded(context, style));
+ EXPECT_TRUE(text_whitespace->TextLayoutObjectIsNeeded(context, style));
+ EXPECT_TRUE(text->TextLayoutObjectIsNeeded(context, style));
}
TEST_F(TextTest, TextLayoutObjectIsNeeded_Empty) {
@@ -97,16 +95,17 @@ TEST_F(TextTest, TextLayoutObjectIsNeeded_Empty) {
Element* parent = GetDocument().getElementById("parent");
ASSERT_TRUE(parent);
- const LayoutObject* parent_layout = parent->GetLayoutObject();
+ LayoutObject* parent_layout = parent->GetLayoutObject();
ASSERT_TRUE(parent_layout);
const ComputedStyle& style = parent_layout->StyleRef();
Text* text = Text::Create(GetDocument(), "");
Node::AttachContext context;
- EXPECT_FALSE(text->TextLayoutObjectIsNeeded(context, style, *parent_layout));
+ context.parent = parent_layout;
+ EXPECT_FALSE(text->TextLayoutObjectIsNeeded(context, style));
context.use_previous_in_flow = true;
- EXPECT_FALSE(text->TextLayoutObjectIsNeeded(context, style, *parent_layout));
+ EXPECT_FALSE(text->TextLayoutObjectIsNeeded(context, style));
}
TEST_F(TextTest, TextLayoutObjectIsNeeded_Whitespace) {
@@ -132,47 +131,58 @@ TEST_F(TextTest, TextLayoutObjectIsNeeded_Whitespace) {
Text* whitespace = Text::Create(GetDocument(), " ");
Node::AttachContext context;
-
+ context.parent = block;
EXPECT_FALSE(
- whitespace->TextLayoutObjectIsNeeded(context, block->StyleRef(), *block));
- EXPECT_FALSE(whitespace->TextLayoutObjectIsNeeded(
- context, in_line->StyleRef(), *in_line));
+ whitespace->TextLayoutObjectIsNeeded(context, block->StyleRef()));
+ context.parent = in_line;
+ EXPECT_FALSE(
+ whitespace->TextLayoutObjectIsNeeded(context, in_line->StyleRef()));
context.use_previous_in_flow = true;
+ context.parent = block;
EXPECT_FALSE(
- whitespace->TextLayoutObjectIsNeeded(context, block->StyleRef(), *block));
- EXPECT_TRUE(whitespace->TextLayoutObjectIsNeeded(context, in_line->StyleRef(),
- *in_line));
+ whitespace->TextLayoutObjectIsNeeded(context, block->StyleRef()));
+ context.parent = in_line;
+ EXPECT_TRUE(
+ whitespace->TextLayoutObjectIsNeeded(context, in_line->StyleRef()));
context.previous_in_flow = in_line;
+ context.parent = block;
+ EXPECT_TRUE(whitespace->TextLayoutObjectIsNeeded(context, block->StyleRef()));
+ context.parent = in_line;
EXPECT_TRUE(
- whitespace->TextLayoutObjectIsNeeded(context, block->StyleRef(), *block));
- EXPECT_TRUE(whitespace->TextLayoutObjectIsNeeded(context, in_line->StyleRef(),
- *in_line));
+ whitespace->TextLayoutObjectIsNeeded(context, in_line->StyleRef()));
context.previous_in_flow = space_at_end;
+ context.parent = block;
EXPECT_FALSE(
- whitespace->TextLayoutObjectIsNeeded(context, block->StyleRef(), *block));
- EXPECT_FALSE(whitespace->TextLayoutObjectIsNeeded(
- context, in_line->StyleRef(), *in_line));
+ whitespace->TextLayoutObjectIsNeeded(context, block->StyleRef()));
+ context.parent = in_line;
+ EXPECT_FALSE(
+ whitespace->TextLayoutObjectIsNeeded(context, in_line->StyleRef()));
context.previous_in_flow = no_space;
+ context.parent = block;
+ EXPECT_TRUE(whitespace->TextLayoutObjectIsNeeded(context, block->StyleRef()));
+ context.parent = in_line;
EXPECT_TRUE(
- whitespace->TextLayoutObjectIsNeeded(context, block->StyleRef(), *block));
- EXPECT_TRUE(whitespace->TextLayoutObjectIsNeeded(context, in_line->StyleRef(),
- *in_line));
+ whitespace->TextLayoutObjectIsNeeded(context, in_line->StyleRef()));
context.previous_in_flow = block;
+ context.parent = block;
+ EXPECT_FALSE(
+ whitespace->TextLayoutObjectIsNeeded(context, block->StyleRef()));
+ context.parent = in_line;
EXPECT_FALSE(
- whitespace->TextLayoutObjectIsNeeded(context, block->StyleRef(), *block));
- EXPECT_FALSE(whitespace->TextLayoutObjectIsNeeded(
- context, in_line->StyleRef(), *in_line));
+ whitespace->TextLayoutObjectIsNeeded(context, in_line->StyleRef()));
context.previous_in_flow = br;
+ context.parent = block;
EXPECT_FALSE(
- whitespace->TextLayoutObjectIsNeeded(context, block->StyleRef(), *block));
- EXPECT_FALSE(whitespace->TextLayoutObjectIsNeeded(
- context, in_line->StyleRef(), *in_line));
+ whitespace->TextLayoutObjectIsNeeded(context, block->StyleRef()));
+ context.parent = in_line;
+ EXPECT_FALSE(
+ whitespace->TextLayoutObjectIsNeeded(context, in_line->StyleRef()));
}
TEST_F(TextTest, TextLayoutObjectIsNeeded_PreserveNewLine) {
@@ -184,30 +194,28 @@ TEST_F(TextTest, TextLayoutObjectIsNeeded_PreserveNewLine) {
UpdateAllLifecyclePhasesForTest();
Text* text = Text::Create(GetDocument(), " ");
+ Node::AttachContext context;
Element* pre = GetDocument().getElementById("pre");
ASSERT_TRUE(pre);
- const LayoutObject* pre_layout = pre->GetLayoutObject();
- ASSERT_TRUE(pre_layout);
- const ComputedStyle& pre_style = pre_layout->StyleRef();
- EXPECT_TRUE(text->TextLayoutObjectIsNeeded(Node::AttachContext(), pre_style,
- *pre_layout));
+ context.parent = pre->GetLayoutObject();
+ ASSERT_TRUE(context.parent);
+ const ComputedStyle& pre_style = context.parent->StyleRef();
+ EXPECT_TRUE(text->TextLayoutObjectIsNeeded(context, pre_style));
Element* pre_line = GetDocument().getElementById("pre-line");
ASSERT_TRUE(pre_line);
- const LayoutObject* pre_line_layout = pre_line->GetLayoutObject();
- ASSERT_TRUE(pre_line_layout);
- const ComputedStyle& pre_line_style = pre_line_layout->StyleRef();
- EXPECT_TRUE(text->TextLayoutObjectIsNeeded(Node::AttachContext(),
- pre_line_style, *pre_line_layout));
+ context.parent = pre_line->GetLayoutObject();
+ ASSERT_TRUE(context.parent);
+ const ComputedStyle& pre_line_style = context.parent->StyleRef();
+ EXPECT_TRUE(text->TextLayoutObjectIsNeeded(context, pre_line_style));
Element* pre_wrap = GetDocument().getElementById("pre-wrap");
ASSERT_TRUE(pre_wrap);
- const LayoutObject* pre_wrap_layout = pre_wrap->GetLayoutObject();
- ASSERT_TRUE(pre_wrap_layout);
- const ComputedStyle& pre_wrap_style = pre_wrap_layout->StyleRef();
- EXPECT_TRUE(text->TextLayoutObjectIsNeeded(Node::AttachContext(),
- pre_wrap_style, *pre_wrap_layout));
+ context.parent = pre_wrap->GetLayoutObject();
+ ASSERT_TRUE(context.parent);
+ const ComputedStyle& pre_wrap_style = context.parent->StyleRef();
+ EXPECT_TRUE(text->TextLayoutObjectIsNeeded(context, pre_wrap_style));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/dom/throw_on_dynamic_markup_insertion_count_incrementer.h b/chromium/third_party/blink/renderer/core/dom/throw_on_dynamic_markup_insertion_count_incrementer.h
index 9d262983e42..706b40aedf8 100644
--- a/chromium/third_party/blink/renderer/core/dom/throw_on_dynamic_markup_insertion_count_incrementer.h
+++ b/chromium/third_party/blink/renderer/core/dom/throw_on_dynamic_markup_insertion_count_incrementer.h
@@ -7,7 +7,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/dom/document.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/dom/transform_source.h b/chromium/third_party/blink/renderer/core/dom/transform_source.h
index e74f3d2a127..46ba990df5a 100644
--- a/chromium/third_party/blink/renderer/core/dom/transform_source.h
+++ b/chromium/third_party/blink/renderer/core/dom/transform_source.h
@@ -22,7 +22,7 @@
#include <libxml/tree.h>
#include "base/macros.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 ecfdcd8a468..939b145467c 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
@@ -33,7 +33,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_DOM_TREE_ORDERED_MAP_H_
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.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.h"
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 f6d8ffff744..cddece0932f 100644
--- a/chromium/third_party/blink/renderer/core/dom/tree_scope.cc
+++ b/chromium/third_party/blink/renderer/core/dom/tree_scope.cc
@@ -265,7 +265,7 @@ Element* TreeScope::HitTestPointInternal(Node* node,
if (node->IsPseudoElement() || node->IsTextNode())
element = node->ParentOrShadowHostElement();
else
- element = ToElement(node);
+ element = To<Element>(node);
if (!element)
return nullptr;
if (type == HitTestPointType::kWebExposed)
@@ -284,7 +284,7 @@ static bool ShouldAcceptNonElementNode(const Node& node) {
// SVG text content elements has no background, and are thus not
// hit during the background phase of hit-testing. Because of that
// we need to allow any child (Text) node of these elements.
- return IsSVGTextContentElement(*parent);
+ return IsA<SVGTextContentElement>(parent);
}
HeapVector<Member<Element>> TreeScope::ElementsFromHitTestResult(
@@ -302,8 +302,8 @@ HeapVector<Member<Element>> TreeScope::ElementsFromHitTestResult(
if (node == last_node)
continue;
- if (node && node->IsElementNode()) {
- elements.push_back(ToElement(node));
+ if (auto* element = DynamicTo<Element>(node)) {
+ elements.push_back(element);
last_node = node;
}
}
@@ -489,8 +489,8 @@ Element* TreeScope::AdjustedFocusedElement() const {
// - InsertionPoint
// - shadow host
// - Document::focusedElement()
- // So, it's safe to do toElement().
- return ToElement(context.Target()->ToNode());
+ // So, it's safe to do To<Element>().
+ return To<Element>(context.Target()->ToNode());
}
}
return nullptr;
diff --git a/chromium/third_party/blink/renderer/core/dom/tree_scope_adopter.cc b/chromium/third_party/blink/renderer/core/dom/tree_scope_adopter.cc
index bd94af51c08..95da2bf2e77 100644
--- a/chromium/third_party/blink/renderer/core/dom/tree_scope_adopter.cc
+++ b/chromium/third_party/blink/renderer/core/dom/tree_scope_adopter.cc
@@ -69,16 +69,16 @@ void TreeScopeAdopter::MoveTreeToNewScope(Node& root) const {
rare_data->NodeLists()->AdoptTreeScope();
}
- if (!node.IsElementNode())
+ auto* element = DynamicTo<Element>(node);
+ if (!element)
continue;
- Element& element = ToElement(node);
- if (HeapVector<Member<Attr>>* attrs = element.GetAttrNodeList()) {
+ if (HeapVector<Member<Attr>>* attrs = element->GetAttrNodeList()) {
for (const auto& attr : *attrs)
MoveTreeToNewScope(*attr);
}
- if (ShadowRoot* shadow = element.GetShadowRoot()) {
+ if (ShadowRoot* shadow = element->GetShadowRoot()) {
shadow->SetParentTreeScope(NewScope());
if (will_move_to_new_document)
MoveShadowTreeToNewDocument(*shadow, old_document, new_document);
@@ -109,16 +109,16 @@ void TreeScopeAdopter::MoveTreeToNewDocument(Node& root,
for (Node& node : NodeTraversal::InclusiveDescendantsOf(root)) {
MoveNodeToNewDocument(node, old_document, new_document);
- if (!node.IsElementNode())
+ auto* element = DynamicTo<Element>(node);
+ if (!element)
continue;
- Element& element = ToElement(node);
- if (HeapVector<Member<Attr>>* attrs = element.GetAttrNodeList()) {
+ if (HeapVector<Member<Attr>>* attrs = element->GetAttrNodeList()) {
for (const auto& attr : *attrs)
MoveTreeToNewDocument(*attr, old_document, new_document);
}
- if (ShadowRoot* shadow_root = element.GetShadowRoot())
+ if (ShadowRoot* shadow_root = element->GetShadowRoot())
MoveShadowTreeToNewDocument(*shadow_root, old_document, new_document);
}
}
@@ -161,7 +161,7 @@ inline void TreeScopeAdopter::MoveNodeToNewDocument(
old_document.MoveNodeIteratorsToNewDocument(node, new_document);
if (node.GetCustomElementState() == CustomElementState::kCustom) {
- CustomElement::EnqueueAdoptedCallback(ToElement(node), old_document,
+ CustomElement::EnqueueAdoptedCallback(To<Element>(node), old_document,
new_document);
}
diff --git a/chromium/third_party/blink/renderer/core/dom/tree_walker.idl b/chromium/third_party/blink/renderer/core/dom/tree_walker.idl
index 523ca96cc68..6f4f65cc18d 100644
--- a/chromium/third_party/blink/renderer/core/dom/tree_walker.idl
+++ b/chromium/third_party/blink/renderer/core/dom/tree_walker.idl
@@ -20,7 +20,9 @@
// https://dom.spec.whatwg.org/#interface-treewalker
-interface TreeWalker {
+[
+ Exposed=Window
+] interface TreeWalker {
[SameObject] readonly attribute Node root;
readonly attribute unsigned long whatToShow;
readonly attribute NodeFilter? filter;
diff --git a/chromium/third_party/blink/renderer/core/dom/user_action_element_set.cc b/chromium/third_party/blink/renderer/core/dom/user_action_element_set.cc
index eabc3e8a053..b2985558174 100644
--- a/chromium/third_party/blink/renderer/core/dom/user_action_element_set.cc
+++ b/chromium/third_party/blink/renderer/core/dom/user_action_element_set.cc
@@ -43,19 +43,21 @@ void UserActionElementSet::DidDetach(Element& element) {
bool UserActionElementSet::HasFlags(const Node* node, unsigned flags) const {
DCHECK(node->IsUserActionElement() && node->IsElementNode());
- return HasFlags(ToElement(node), flags);
+ return HasFlags(To<Element>(node), flags);
}
void UserActionElementSet::SetFlags(Node* node, unsigned flags) {
- if (!node->IsElementNode())
+ auto* this_element = DynamicTo<Element>(node);
+ if (!this_element)
return;
- return SetFlags(ToElement(node), flags);
+ return SetFlags(this_element, flags);
}
void UserActionElementSet::ClearFlags(Node* node, unsigned flags) {
- if (!node->IsElementNode())
+ auto* this_element = DynamicTo<Element>(node);
+ if (!this_element)
return;
- return ClearFlags(ToElement(node), flags);
+ return ClearFlags(this_element, flags);
}
inline bool UserActionElementSet::HasFlags(const Element* element,
diff --git a/chromium/third_party/blink/renderer/core/dom/user_gesture_indicator.cc b/chromium/third_party/blink/renderer/core/dom/user_gesture_indicator.cc
index 477a3bbdbe2..c40f78bf82a 100644
--- a/chromium/third_party/blink/renderer/core/dom/user_gesture_indicator.cc
+++ b/chromium/third_party/blink/renderer/core/dom/user_gesture_indicator.cc
@@ -7,7 +7,7 @@
#include "base/time/default_clock.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/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
@@ -16,9 +16,6 @@ namespace blink {
// User gestures timeout in 1 second.
const double kUserGestureTimeout = 1.0;
-// For out of process tokens we allow a 10 second delay.
-const double kUserGestureOutOfProcessTimeout = 10.0;
-
UserGestureToken::UserGestureToken(Status status)
: consumable_gestures_(0),
clock_(base::DefaultClock::GetInstance()),
@@ -48,7 +45,7 @@ bool UserGestureToken::ConsumeGesture() {
}
void UserGestureToken::SetTimeoutPolicy(TimeoutPolicy policy) {
- if (!HasTimedOut() && HasGestures() && policy > timeout_policy_)
+ if (HasGestures() && policy > timeout_policy_)
timeout_policy_ = policy;
}
@@ -59,10 +56,7 @@ void UserGestureToken::ResetTimestamp() {
bool UserGestureToken::HasTimedOut() const {
if (timeout_policy_ == kHasPaused)
return false;
- double timeout = timeout_policy_ == kOutOfProcess
- ? kUserGestureOutOfProcessTimeout
- : kUserGestureTimeout;
- return clock_->Now().ToDoubleT() - timestamp_ > timeout;
+ return clock_->Now().ToDoubleT() - timestamp_ > kUserGestureTimeout;
}
bool UserGestureToken::WasForwardedCrossProcess() const {
@@ -80,29 +74,13 @@ enum GestureMergeState {
kGestureMergeStateEnd = 1 << 2,
};
-// Remove this when user gesture propagation is standardized. See
-// https://crbug.com/404161.
-static void RecordUserGestureMerge(const UserGestureToken& old_token,
- const UserGestureToken& new_token) {
- DEFINE_STATIC_LOCAL(EnumerationHistogram, gesture_merge_histogram,
- ("Blink.Gesture.Merged", kGestureMergeStateEnd));
- int sample = 0;
- if (old_token.HasGestures())
- sample |= kOldTokenHasGesture;
- if (new_token.HasGestures())
- sample |= kNewTokenHasGesture;
- gesture_merge_histogram.Count(sample);
-}
-
UserGestureToken* UserGestureIndicator::root_token_ = nullptr;
void UserGestureIndicator::UpdateRootToken() {
- if (!root_token_) {
+ if (!root_token_)
root_token_ = token_.get();
- } else {
- RecordUserGestureMerge(*root_token_, *token_);
+ else
token_->TransferGestureTo(root_token_);
- }
}
UserGestureIndicator::UserGestureIndicator(
diff --git a/chromium/third_party/blink/renderer/core/dom/user_gesture_indicator.h b/chromium/third_party/blink/renderer/core/dom/user_gesture_indicator.h
index b64df7c10aa..9a3cb1db403 100644
--- a/chromium/third_party/blink/renderer/core/dom/user_gesture_indicator.h
+++ b/chromium/third_party/blink/renderer/core/dom/user_gesture_indicator.h
@@ -28,24 +28,22 @@ class CORE_EXPORT UserGestureToken : public RefCounted<UserGestureToken> {
public:
enum Status { kNewGesture, kPossiblyExistingGesture };
- enum TimeoutPolicy { kDefault, kOutOfProcess, kHasPaused };
+ enum TimeoutPolicy { kDefault, kHasPaused };
~UserGestureToken() = default;
- // TODO(mustaq): The only user of this method is PepperPluginInstanceImpl. We
- // need to investigate the usecase closely.
- bool HasGestures() const;
-
void SetClockForTesting(const base::Clock* clock) { clock_ = clock; }
void ResetTimestampForTesting() { ResetTimestamp(); }
private:
+ FRIEND_TEST_ALL_PREFIXES(UserGestureIndicatorTest, Timeouts);
UserGestureToken(Status);
void TransferGestureTo(UserGestureToken*);
bool ConsumeGesture();
void SetTimeoutPolicy(TimeoutPolicy);
void ResetTimestamp();
+ bool HasGestures() const;
bool HasTimedOut() const;
bool WasForwardedCrossProcess() const;
void SetWasForwardedCrossProcess();
diff --git a/chromium/third_party/blink/renderer/core/dom/user_gesture_indicator_test.cc b/chromium/third_party/blink/renderer/core/dom/user_gesture_indicator_test.cc
index f58b5981024..561d8784c5c 100644
--- a/chromium/third_party/blink/renderer/core/dom/user_gesture_indicator_test.cc
+++ b/chromium/third_party/blink/renderer/core/dom/user_gesture_indicator_test.cc
@@ -122,9 +122,9 @@ TEST(UserGestureIndicatorTest, Timeouts) {
// reset it so it gets the Now() of the mock clock.
token->ResetTimestampForTesting();
EXPECT_TRUE(token->HasGestures());
- test_task_runner->FastForwardBy(TimeDelta::FromSecondsD(0.75));
+ test_task_runner->FastForwardBy(base::TimeDelta::FromSecondsD(0.75));
EXPECT_TRUE(token->HasGestures());
- test_task_runner->FastForwardBy(TimeDelta::FromSecondsD(0.75));
+ test_task_runner->FastForwardBy(base::TimeDelta::FromSecondsD(0.75));
EXPECT_FALSE(token->HasGestures());
}
@@ -141,15 +141,15 @@ TEST(UserGestureIndicatorTest, Timeouts) {
// clock, reset it so it gets the Now() of the mock clock.
token->ResetTimestampForTesting();
EXPECT_TRUE(token->HasGestures());
- test_task_runner->FastForwardBy(TimeDelta::FromSecondsD(0.75));
+ test_task_runner->FastForwardBy(base::TimeDelta::FromSecondsD(0.75));
EXPECT_TRUE(token->HasGestures());
}
{
UserGestureIndicator user_gesture_scope(token.get());
- test_task_runner->FastForwardBy(TimeDelta::FromSecondsD(0.75));
+ test_task_runner->FastForwardBy(base::TimeDelta::FromSecondsD(0.75));
EXPECT_TRUE(token->HasGestures());
- test_task_runner->FastForwardBy(TimeDelta::FromSecondsD(0.75));
+ test_task_runner->FastForwardBy(base::TimeDelta::FromSecondsD(0.75));
EXPECT_FALSE(token->HasGestures());
}
}
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 ace284eaca5..7eacc3d59f6 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
@@ -56,6 +56,15 @@ void V0InsertionPoint::SetDistributedNodes(
// Attempt not to reattach nodes that would be distributed to the exact same
// location by comparing the old and new distributions.
+ if (DistributedNodesAreFallback() && distributed_nodes.size() &&
+ distributed_nodes.at(0)->parentNode() != this) {
+ // Detach fallback nodes. Host children which are no longer distributed are
+ // detached in the DistributionPool destructor.
+ for (wtf_size_t i = 0; i < distributed_nodes_.size(); ++i)
+ distributed_nodes_.at(i)->RemovedFromFlatTree();
+ distributed_nodes_.Clear();
+ }
+
wtf_size_t i = 0;
wtf_size_t j = 0;
@@ -103,12 +112,9 @@ void V0InsertionPoint::SetDistributedNodes(
}
void V0InsertionPoint::AttachLayoutTree(AttachContext& context) {
- // We need to attach the distribution here so that they're inserted in the
- // right order otherwise the n^2 protection inside LayoutTreeBuilder will
- // cause them to be inserted in the wrong place later. This also lets
- // distributed nodes benefit from the n^2 protection. If the distributed
- // children are the direct fallback children they are attached in
- // ContainerNodes::AttachLayoutTree() via the base class call below.
+ // If the distributed children are the direct fallback children they are
+ // attached in ContainerNodes::AttachLayoutTree() via the base class call
+ // below.
if (!DistributedNodesAreFallback()) {
AttachContext children_context(context);
for (wtf_size_t i = 0; i < distributed_nodes_.size(); ++i)
@@ -119,11 +125,11 @@ void V0InsertionPoint::AttachLayoutTree(AttachContext& context) {
HTMLElement::AttachLayoutTree(context);
}
-void V0InsertionPoint::DetachLayoutTree(const AttachContext& context) {
+void V0InsertionPoint::DetachLayoutTree(bool performing_reattach) {
for (wtf_size_t i = 0; i < distributed_nodes_.size(); ++i)
- distributed_nodes_.at(i)->DetachLayoutTree(context);
+ distributed_nodes_.at(i)->DetachLayoutTree(performing_reattach);
- HTMLElement::DetachLayoutTree(context);
+ HTMLElement::DetachLayoutTree(performing_reattach);
}
void V0InsertionPoint::RebuildDistributedChildrenLayoutTrees(
@@ -147,8 +153,8 @@ void V0InsertionPoint::DidRecalcStyle(const StyleRecalcChange change) {
Node* node = distributed_nodes_.at(i);
if (!change.TraverseChild(*node))
continue;
- if (node->IsElementNode())
- ToElement(node)->RecalcStyle(change);
+ if (auto* this_element = DynamicTo<Element>(node))
+ this_element->RecalcStyle(change);
else if (auto* text_node = DynamicTo<Text>(node))
text_node->RecalcTextStyle(change);
}
diff --git a/chromium/third_party/blink/renderer/core/dom/v0_insertion_point.h b/chromium/third_party/blink/renderer/core/dom/v0_insertion_point.h
index e519ec03e5c..327aa3817f3 100644
--- a/chromium/third_party/blink/renderer/core/dom/v0_insertion_point.h
+++ b/chromium/third_party/blink/renderer/core/dom/v0_insertion_point.h
@@ -56,7 +56,7 @@ class CORE_EXPORT V0InsertionPoint : public HTMLElement {
virtual bool CanAffectSelector() const { return false; }
void AttachLayoutTree(AttachContext&) override;
- void DetachLayoutTree(const AttachContext& = AttachContext()) override;
+ void DetachLayoutTree(bool performing_reattach) override;
void RebuildDistributedChildrenLayoutTrees(WhitespaceAttacher&);
size_t DistributedNodesSize() const { return distributed_nodes_.size(); }
@@ -112,8 +112,8 @@ inline ShadowRoot* ShadowRootWhereNodeCanBeDistributedForV0(const Node& node) {
return nullptr;
if (IsActiveV0InsertionPoint(*parent))
return node.ContainingShadowRoot();
- if (parent->IsElementNode())
- return ToElement(parent)->GetShadowRoot();
+ if (auto* parent_element = DynamicTo<Element>(parent))
+ return parent_element->GetShadowRoot();
return nullptr;
}
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 9436255585c..4f9fdc11299 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
@@ -69,10 +69,10 @@ static void InvalidateStyleForAllLinksRecursively(
if (node.IsLink()) {
if (invalidate_visited_link_hashes && IsHTMLAnchorElement(node))
ToHTMLAnchorElement(node).InvalidateCachedVisitedLinkHash();
- ToElement(node).PseudoStateChanged(CSSSelector::kPseudoLink);
- ToElement(node).PseudoStateChanged(CSSSelector::kPseudoVisited);
- ToElement(node).PseudoStateChanged(CSSSelector::kPseudoWebkitAnyLink);
- ToElement(node).PseudoStateChanged(CSSSelector::kPseudoAnyLink);
+ To<Element>(node).PseudoStateChanged(CSSSelector::kPseudoLink);
+ To<Element>(node).PseudoStateChanged(CSSSelector::kPseudoVisited);
+ To<Element>(node).PseudoStateChanged(CSSSelector::kPseudoWebkitAnyLink);
+ To<Element>(node).PseudoStateChanged(CSSSelector::kPseudoAnyLink);
}
if (ShadowRoot* root = node.GetShadowRoot()) {
InvalidateStyleForAllLinksRecursively(*root,
@@ -91,11 +91,11 @@ void VisitedLinkState::InvalidateStyleForAllLinks(
static void InvalidateStyleForLinkRecursively(Node& root_node,
LinkHash link_hash) {
for (Node& node : NodeTraversal::StartsAt(root_node)) {
- if (node.IsLink() && LinkHashForElement(ToElement(node)) == link_hash) {
- ToElement(node).PseudoStateChanged(CSSSelector::kPseudoLink);
- ToElement(node).PseudoStateChanged(CSSSelector::kPseudoVisited);
- ToElement(node).PseudoStateChanged(CSSSelector::kPseudoWebkitAnyLink);
- ToElement(node).PseudoStateChanged(CSSSelector::kPseudoAnyLink);
+ if (node.IsLink() && LinkHashForElement(To<Element>(node)) == link_hash) {
+ To<Element>(node).PseudoStateChanged(CSSSelector::kPseudoLink);
+ To<Element>(node).PseudoStateChanged(CSSSelector::kPseudoVisited);
+ To<Element>(node).PseudoStateChanged(CSSSelector::kPseudoWebkitAnyLink);
+ To<Element>(node).PseudoStateChanged(CSSSelector::kPseudoAnyLink);
}
if (ShadowRoot* root = node.GetShadowRoot())
InvalidateStyleForLinkRecursively(*root, link_hash);
diff --git a/chromium/third_party/blink/renderer/core/dom/weak_identifier_map.h b/chromium/third_party/blink/renderer/core/dom/weak_identifier_map.h
index cd2f21d0ed4..9b6f9608965 100644
--- a/chromium/third_party/blink/renderer/core/dom/weak_identifier_map.h
+++ b/chromium/third_party/blink/renderer/core/dom/weak_identifier_map.h
@@ -8,7 +8,7 @@
#include <limits>
#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/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
namespace blink {
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 2334e8fcbe9..a4dbdb24af0 100644
--- a/chromium/third_party/blink/renderer/core/dom/whitespace_attacher.cc
+++ b/chromium/third_party/blink/renderer/core/dom/whitespace_attacher.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/dom/whitespace_attacher.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/layout_tree_builder.h"
#include "third_party/blink/renderer/core/dom/text.h"
#include "third_party/blink/renderer/core/layout/layout_text.h"
#include "third_party/blink/renderer/platform/bindings/script_forbidden_scope.h"
@@ -75,8 +75,11 @@ void WhitespaceAttacher::DidVisitText(Text* text) {
if (LayoutObject* text_layout_object = text->GetLayoutObject()) {
ReattachWhitespaceSiblings(text_layout_object);
} else {
- if (last_text_node_->ContainsOnlyWhitespaceOrEmpty())
- last_text_node_->ReattachLayoutTreeIfNeeded(Node::AttachContext());
+ if (last_text_node_->ContainsOnlyWhitespaceOrEmpty()) {
+ Node::AttachContext context;
+ context.parent = LayoutTreeBuilderTraversal::ParentLayoutObject(*text);
+ last_text_node_->ReattachLayoutTreeIfNeeded(context);
+ }
}
SetLastTextNode(text);
if (reattach_all_whitespace_nodes_ && text->ContainsOnlyWhitespaceOrEmpty())
@@ -114,6 +117,8 @@ void WhitespaceAttacher::ReattachWhitespaceSiblings(
Node::AttachContext context;
context.previous_in_flow = previous_in_flow;
context.use_previous_in_flow = true;
+ context.parent =
+ LayoutTreeBuilderTraversal::ParentLayoutObject(*last_text_node_);
for (Node* sibling = last_text_node_; sibling;
sibling = LayoutTreeBuilderTraversal::NextLayoutSibling(*sibling)) {
@@ -134,6 +139,8 @@ void WhitespaceAttacher::ReattachWhitespaceSiblings(
!sibling_layout_object->IsFloatingOrOutOfFlowPositioned()) {
break;
}
+ context.next_sibling_valid = false;
+ context.next_sibling = nullptr;
}
SetLastTextNode(nullptr);
}
@@ -165,8 +172,8 @@ void WhitespaceAttacher::UpdateLastTextNodeFromDisplayContents() {
return;
}
- DCHECK(!sibling->IsElementNode() ||
- !ToElement(sibling)->HasDisplayContentsStyle());
+ auto* sibling_element = DynamicTo<Element>(sibling);
+ DCHECK(!sibling_element || !sibling_element->HasDisplayContentsStyle());
for (; sibling && sibling != last_text_node_;
sibling = LayoutTreeBuilderTraversal::NextLayoutSibling(*sibling)) {
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 3003f492026..da281640af4 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
@@ -256,7 +256,7 @@ TEST_F(WhitespaceAttacherTest,
UpdateAllLifecyclePhasesForTest();
Element* div = GetDocument().getElementById("block");
- Element* contents = ToElement(div->nextSibling());
+ auto* contents = To<Element>(div->nextSibling());
auto* text = To<Text>(contents->firstChild());
EXPECT_FALSE(contents->GetLayoutObject());
EXPECT_FALSE(text->GetLayoutObject());
@@ -282,7 +282,7 @@ TEST_F(WhitespaceAttacherTest,
UpdateAllLifecyclePhasesForTest();
Element* span = GetDocument().getElementById("inline");
- Element* contents = ToElement(span->nextSibling());
+ auto* contents = To<Element>(span->nextSibling());
auto* text = To<Text>(contents->firstChild());
EXPECT_FALSE(contents->GetLayoutObject());
EXPECT_TRUE(text->GetLayoutObject());
@@ -307,7 +307,7 @@ TEST_F(WhitespaceAttacherTest,
UpdateAllLifecyclePhasesForTest();
Element* div = GetDocument().getElementById("block");
- Element* contents = ToElement(div->nextSibling());
+ auto* contents = To<Element>(div->nextSibling());
auto* text = To<Text>(contents->nextSibling());
EXPECT_FALSE(contents->GetLayoutObject());
EXPECT_FALSE(text->GetLayoutObject());
@@ -335,7 +335,7 @@ TEST_F(WhitespaceAttacherTest,
UpdateAllLifecyclePhasesForTest();
Element* div = GetDocument().getElementById("block");
- Element* contents = ToElement(div->nextSibling());
+ auto* contents = To<Element>(div->nextSibling());
auto* text = To<Text>(contents->nextSibling());
EXPECT_FALSE(contents->GetLayoutObject());
EXPECT_FALSE(text->GetLayoutObject());
@@ -363,7 +363,7 @@ TEST_F(WhitespaceAttacherTest, WhitespaceDeepInsideDisplayContents) {
UpdateAllLifecyclePhasesForTest();
Element* span = GetDocument().getElementById("inline");
- Element* contents = ToElement(span->nextSibling());
+ auto* contents = To<Element>(span->nextSibling());
auto* text = To<Text>(GetDocument().getElementById("inner")->firstChild());
EXPECT_TRUE(text->GetLayoutObject());
@@ -389,9 +389,9 @@ TEST_F(WhitespaceAttacherTest, MultipleDisplayContents) {
UpdateAllLifecyclePhasesForTest();
Element* span = GetDocument().getElementById("inline");
- Element* first_contents = ToElement(span->nextSibling());
- Element* second_contents = ToElement(first_contents->nextSibling());
- Element* last_contents = ToElement(second_contents->nextSibling());
+ auto* first_contents = To<Element>(span->nextSibling());
+ auto* second_contents = To<Element>(first_contents->nextSibling());
+ auto* last_contents = To<Element>(second_contents->nextSibling());
auto* text = To<Text>(last_contents->firstChild());
EXPECT_TRUE(text->GetLayoutObject());
@@ -423,7 +423,7 @@ TEST_F(WhitespaceAttacherTest, SlottedWhitespaceInsideDisplayContents) {
UpdateAllLifecyclePhasesForTest();
Element* span = shadow_root.getElementById("inline");
- Element* contents = ToElement(span->nextSibling());
+ auto* contents = To<Element>(span->nextSibling());
auto* text = To<Text>(host->firstChild());
EXPECT_TRUE(text->GetLayoutObject());
diff --git a/chromium/third_party/blink/renderer/core/dom/xml_document.idl b/chromium/third_party/blink/renderer/core/dom/xml_document.idl
index df60667a563..77ac6091c0c 100644
--- a/chromium/third_party/blink/renderer/core/dom/xml_document.idl
+++ b/chromium/third_party/blink/renderer/core/dom/xml_document.idl
@@ -25,5 +25,7 @@
// https://dom.spec.whatwg.org/#xmldocument
-interface XMLDocument : Document {
+[
+ Exposed=Window
+] interface XMLDocument : Document {
};
diff --git a/chromium/third_party/blink/renderer/core/editing/BUILD.gn b/chromium/third_party/blink/renderer/core/editing/BUILD.gn
index 415e88eb0ea..b9cd43556be 100644
--- a/chromium/third_party/blink/renderer/core/editing/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/editing/BUILD.gn
@@ -343,6 +343,7 @@ jumbo_source_set("unit_tests") {
"commands/insert_list_command_test.cc",
"commands/insert_paragraph_separator_command_test.cc",
"commands/insert_text_command_test.cc",
+ "commands/move_commands_test.cc",
"commands/replace_selection_command_test.cc",
"commands/set_character_data_command_test.cc",
"commands/split_text_node_command_test.cc",
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 33898e3e187..d4d67a3a60b 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
@@ -26,6 +26,7 @@
#include "third_party/blink/renderer/core/editing/commands/apply_style_command.h"
#include "third_party/blink/renderer/core/css/css_computed_style_declaration.h"
+#include "third_party/blink/renderer/core/css/css_numeric_literal_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_property_value_set.h"
@@ -48,7 +49,6 @@
#include "third_party/blink/renderer/core/editing/visible_selection.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/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/html_font_element.h"
#include "third_party/blink/renderer/core/html/html_span_element.h"
#include "third_party/blink/renderer/core/html_names.h"
@@ -56,6 +56,7 @@
#include "third_party/blink/renderer/core/layout/layout_text.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
@@ -510,8 +511,8 @@ void ApplyStyleCommand::ApplyRelativeFontStyleChange(
if (current_font_size != desired_font_size) {
inline_style->SetProperty(
CSSPropertyID::kFontSize,
- *CSSPrimitiveValue::Create(desired_font_size,
- CSSPrimitiveValue::UnitType::kPixels),
+ *CSSNumericLiteralValue::Create(desired_font_size,
+ CSSPrimitiveValue::UnitType::kPixels),
false);
SetNodeAttribute(element, kStyleAttr,
AtomicString(inline_style->AsText()));
@@ -532,11 +533,14 @@ void ApplyStyleCommand::ApplyRelativeFontStyleChange(
}
static ContainerNode* DummySpanAncestorForNode(const Node* node) {
- while (node && (!node->IsElementNode() ||
- !IsStyleSpanOrSpanWithOnlyStyleAttribute(ToElement(node))))
- node = node->parentNode();
+ if (!node)
+ return nullptr;
- return node ? node->parentNode() : nullptr;
+ for (Node& current : NodeTraversal::InclusiveAncestorsOf(*node)) {
+ if (IsStyleSpanOrSpanWithOnlyStyleAttribute(DynamicTo<Element>(current)))
+ return current.parentNode();
+ }
+ return nullptr;
}
void ApplyStyleCommand::CleanupUnstyledAppleStyleSpans(
@@ -615,7 +619,7 @@ HTMLElement* ApplyStyleCommand::SplitAncestorsWithUnicodeBidi(
// Split every ancestor through highest ancestor with embedding.
Node* current_node = node;
while (current_node) {
- Element* parent = ToElement(current_node->parentNode());
+ auto* parent = To<Element>(current_node->parentNode());
if (before ? current_node->previousSibling() : current_node->nextSibling())
SplitElement(parent, before ? current_node : current_node->nextSibling());
if (parent == highest_ancestor_with_unicode_bidi)
@@ -639,7 +643,7 @@ void ApplyStyleCommand::RemoveEmbeddingUpToEnclosingBlock(
if (!runner.IsStyledElement())
continue;
- Element* element = ToElement(&runner);
+ auto* element = To<Element>(&runner);
CSSValueID unicode_bidi = GetIdentifierValue(
MakeGarbageCollected<CSSComputedStyleDeclaration>(element),
CSSPropertyID::kUnicodeBidi);
@@ -1283,7 +1287,7 @@ static Element* UnsplittableElementForPosition(const Position& p) {
// Since enclosingNodeOfType won't search beyond the highest root editable
// node, this code works even if the closest table cell was outside of the
// root editable node.
- Element* enclosing_cell = ToElement(EnclosingNodeOfType(p, &IsTableCell));
+ auto* enclosing_cell = To<Element>(EnclosingNodeOfType(p, &IsTableCell));
if (enclosing_cell)
return enclosing_cell;
@@ -1376,8 +1380,8 @@ void ApplyStyleCommand::PushDownInlineStyleAroundNode(
GetChildNodes(To<ContainerNode>(*current), current_children);
Element* styled_element = nullptr;
if (current->IsStyledElement() &&
- IsStyledInlineElementToRemove(ToElement(current))) {
- styled_element = ToElement(current);
+ IsStyledInlineElementToRemove(To<Element>(current))) {
+ styled_element = To<Element>(current);
elements_to_push_down.push_back(styled_element);
}
@@ -1699,8 +1703,8 @@ bool ApplyStyleCommand::MergeStartWithPreviousIfIdentical(
if (previous_sibling &&
AreIdenticalElements(*start_node, *previous_sibling)) {
- Element* previous_element = ToElement(previous_sibling);
- Element* element = ToElement(start_node);
+ auto* previous_element = To<Element>(previous_sibling);
+ auto* element = To<Element>(start_node);
Node* start_child = element->firstChild();
DCHECK(start_child);
MergeIdenticalElements(previous_element, element, editing_state);
@@ -1742,8 +1746,8 @@ bool ApplyStyleCommand::MergeEndWithNextIfIdentical(
Node* next_sibling = end_node->nextSibling();
if (next_sibling && AreIdenticalElements(*end_node, *next_sibling)) {
- Element* next_element = ToElement(next_sibling);
- Element* element = ToElement(end_node);
+ auto* next_element = To<Element>(next_sibling);
+ auto* element = To<Element>(end_node);
Node* next_child = next_element->firstChild();
MergeIdenticalElements(element, next_element, editing_state);
@@ -1797,22 +1801,22 @@ void ApplyStyleCommand::SurroundNodeRangeWithElement(
Node* next_sibling = element->nextSibling();
Node* previous_sibling = element->previousSibling();
- if (next_sibling && next_sibling->IsElementNode() &&
- HasEditableStyle(*next_sibling) &&
- AreIdenticalElements(*element, ToElement(*next_sibling))) {
- MergeIdenticalElements(element, ToElement(next_sibling), editing_state);
+ auto* next_sibling_element = DynamicTo<Element>(next_sibling);
+ if (next_sibling_element && HasEditableStyle(*next_sibling) &&
+ AreIdenticalElements(*element, *next_sibling_element)) {
+ MergeIdenticalElements(element, next_sibling_element, editing_state);
if (editing_state->IsAborted())
return;
}
- if (previous_sibling && previous_sibling->IsElementNode() &&
- HasEditableStyle(*previous_sibling)) {
- Node* merged_element = previous_sibling->nextSibling();
- if (merged_element->IsElementNode() && HasEditableStyle(*merged_element) &&
- AreIdenticalElements(ToElement(*previous_sibling),
- ToElement(*merged_element))) {
- MergeIdenticalElements(ToElement(previous_sibling),
- ToElement(merged_element), editing_state);
+ auto* previous_sibling_element = DynamicTo<Element>(previous_sibling);
+ if (previous_sibling_element && HasEditableStyle(*previous_sibling)) {
+ auto* merged_element = DynamicTo<Element>(previous_sibling->nextSibling());
+ if (merged_element &&
+ HasEditableStyle(*(previous_sibling->nextSibling())) &&
+ AreIdenticalElements(*previous_sibling_element, *merged_element)) {
+ MergeIdenticalElements(previous_sibling_element, merged_element,
+ editing_state);
if (editing_state->IsAborted())
return;
}
@@ -2041,12 +2045,12 @@ float ApplyStyleCommand::ComputedFontSize(Node* node) {
return 0;
const auto* value = To<CSSPrimitiveValue>(
- style->GetPropertyCSSValue(GetCSSPropertyFontSize()));
+ style->GetPropertyCSSValue(CSSPropertyID::kFontSize));
if (!value)
return 0;
// TODO(yosin): We should have printer for |CSSPrimitiveValue::UnitType|.
- DCHECK(value->TypeWithCalcResolved() == CSSPrimitiveValue::UnitType::kPixels);
+ DCHECK(value->IsPx());
return value->GetFloatValue();
}
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/clipboard_commands.h b/chromium/third_party/blink/renderer/core/editing/commands/clipboard_commands.h
index 4aa6f80477d..6e0f5518437 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/clipboard_commands.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/clipboard_commands.h
@@ -33,7 +33,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_EDITING_COMMANDS_CLIPBOARD_COMMANDS_H_
#include "third_party/blink/renderer/core/editing/forward.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
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 b8f011b43a7..8d641404bc9 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
@@ -365,9 +365,10 @@ 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() == kObjectTag));
+ auto* parent_element = DynamicTo<Element>(parent);
+ ABORT_EDITING_COMMAND_IF(
+ !CanHaveChildrenForEditing(parent) &&
+ !(parent_element && parent_element->TagQName() == kObjectTag));
ABORT_EDITING_COMMAND_IF(!HasEditableStyle(*parent) &&
parent->InActiveDocument());
ApplyCommandToComposite(MakeGarbageCollected<AppendNodeCommand>(parent, node),
@@ -1192,7 +1193,7 @@ void CompositeEditCommand::CloneParagraphUnderNewElement(
for (wtf_size_t i = ancestors.size(); i != 0; --i) {
Node* item = ancestors[i - 1].Get();
Node* child = item->cloneNode(IsDisplayInsideTable(item));
- AppendNode(child, ToElement(last_node), editing_state);
+ AppendNode(child, To<Element>(last_node), editing_state);
if (editing_state->IsAborted())
return;
last_node = child;
@@ -1686,7 +1687,7 @@ bool CompositeEditCommand::BreakOutOfEmptyListItem(
// should become
// <ul><li> <div><br></div> hello</li></ul>
// at the end
- SplitElement(ToElement(block_enclosing_list), list_node);
+ SplitElement(To<Element>(block_enclosing_list), list_node);
RemoveNodePreservingChildren(list_node->parentNode(), editing_state);
if (editing_state->IsAborted())
return false;
@@ -1713,7 +1714,7 @@ bool CompositeEditCommand::BreakOutOfEmptyListItem(
// If emptyListItem follows another list item or nested list, split the list
// node.
if (IsListItem(previous_list_node) || IsHTMLListElement(previous_list_node))
- SplitElement(ToElement(list_node), empty_list_item);
+ SplitElement(To<Element>(list_node), empty_list_item);
// If emptyListItem is followed by other list item or nested list, then
// insert newBlock before the list node. Because we have splitted the
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/delete_selection_options.h b/chromium/third_party/blink/renderer/core/editing/commands/delete_selection_options.h
index ef1038c5904..92377355d1c 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/delete_selection_options.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/delete_selection_options.h
@@ -7,7 +7,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/document_exec_command.cc b/chromium/third_party/blink/renderer/core/editing/commands/document_exec_command.cc
index abf10cdfc54..c8fe153b384 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/document_exec_command.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/document_exec_command.cc
@@ -36,10 +36,10 @@
#include "third_party/blink/renderer/core/editing/editing_tri_state.h"
#include "third_party/blink/renderer/core/editing/editor.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/html/forms/text_control_element.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/editing_command_test.cc b/chromium/third_party/blink/renderer/core/editing/commands/editing_command_test.cc
index c24e8917608..e1bfe875c48 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/editing_command_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/editing_command_test.cc
@@ -7,8 +7,11 @@
#include "third_party/blink/renderer/core/editing/commands/editor_command.h"
#include "third_party/blink/renderer/core/editing/commands/editor_command_names.h"
#include "third_party/blink/renderer/core/editing/editor.h"
+#include "third_party/blink/renderer/core/editing/frame_selection.h"
+#include "third_party/blink/renderer/core/editing/selection_template.h"
#include "third_party/blink/renderer/core/editing/testing/editing_test_base.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/platform/wtf/text/wtf_string.h"
namespace blink {
@@ -38,7 +41,7 @@ class EditingCommandTest : public EditingTestBase {};
TEST_F(EditingCommandTest, EditorCommandOrder) {
for (size_t i = 1; i < base::size(kCommandNameEntries); ++i) {
EXPECT_GT(0,
- WTF::CodePointCompareIgnoringASCIICase(
+ WTF::CodeUnitCompareIgnoringASCIICase(
kCommandNameEntries[i - 1].name, kCommandNameEntries[i].name))
<< "EDITOR_COMMAND_MAP must be case-folding ordered. Incorrect index:"
<< i;
@@ -79,4 +82,64 @@ TEST_F(EditingCommandTest, CreateCommandFromInvalidString) {
}
}
+TEST_F(EditingCommandTest, EnabledVisibleSelection) {
+ Editor& editor = GetDocument().GetFrame()->GetEditor();
+ const EditorCommand command =
+ editor.CreateCommand("MoveRightAndModifySelection");
+ Selection().SetSelection(
+ SetSelectionTextToBody("<div contenteditable>a|b<div>"),
+ SetSelectionOptions());
+ Element* div = GetDocument().QuerySelector("div");
+ GetDocument().SetFocusedElement(
+ div,
+ FocusParams(SelectionBehaviorOnFocus::kNone, kWebFocusTypeNone, nullptr));
+ EXPECT_TRUE(command.IsEnabled());
+ div->removeAttribute("contenteditable");
+ EXPECT_FALSE(command.IsEnabled());
+ GetDocument().GetFrame()->GetSettings()->SetCaretBrowsingEnabled(true);
+ EXPECT_TRUE(command.IsEnabled());
+}
+
+TEST_F(EditingCommandTest, EnabledVisibleSelectionAndMark) {
+ Editor& editor = GetDocument().GetFrame()->GetEditor();
+ const EditorCommand command = editor.CreateCommand("SelectToMark");
+ Selection().SetSelection(
+ SetSelectionTextToBody("<div contenteditable>a|b<div>"),
+ SetSelectionOptions());
+ Element* div = GetDocument().QuerySelector("div");
+ GetDocument().SetFocusedElement(
+ div,
+ FocusParams(SelectionBehaviorOnFocus::kNone, kWebFocusTypeNone, nullptr));
+ EXPECT_FALSE(command.IsEnabled());
+ editor.SetMark();
+ EXPECT_TRUE(command.IsEnabled());
+ div->removeAttribute("contenteditable");
+ EXPECT_FALSE(command.IsEnabled());
+ GetDocument().GetFrame()->GetSettings()->SetCaretBrowsingEnabled(true);
+ EXPECT_TRUE(command.IsEnabled());
+}
+
+TEST_F(EditingCommandTest, EnabledInEditableTextOrCaretBrowsing) {
+ Editor& editor = GetDocument().GetFrame()->GetEditor();
+ const EditorCommand command = editor.CreateCommand("MoveRight");
+
+ SetBodyContent("<div>abc</div>");
+ GetDocument().GetFrame()->GetSettings()->SetCaretBrowsingEnabled(false);
+ EXPECT_FALSE(command.IsEnabled());
+ GetDocument().GetFrame()->GetSettings()->SetCaretBrowsingEnabled(true);
+ EXPECT_TRUE(command.IsEnabled());
+
+ GetDocument().GetFrame()->GetSettings()->SetCaretBrowsingEnabled(false);
+ Selection().SetSelection(
+ SetSelectionTextToBody("<div contenteditable>a|b<div>"),
+ SetSelectionOptions());
+ Element* div = GetDocument().QuerySelector("div");
+ GetDocument().SetFocusedElement(
+ div,
+ FocusParams(SelectionBehaviorOnFocus::kNone, kWebFocusTypeNone, nullptr));
+ EXPECT_TRUE(command.IsEnabled());
+ div->removeAttribute("contenteditable");
+ EXPECT_FALSE(command.IsEnabled());
+}
+
} // namespace blink
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 332305aba57..e00a5c11d4d 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
@@ -39,7 +39,6 @@
#include "third_party/blink/renderer/core/editing/visible_position.h"
#include "third_party/blink/renderer/core/editing/visible_selection.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/frame/web_feature_forward.h"
#include "third_party/blink/renderer/core/html/html_body_element.h"
#include "third_party/blink/renderer/core/html/html_html_element.h"
@@ -47,6 +46,7 @@
#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/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
@@ -80,7 +80,7 @@ Node* HighestNodeToRemoveInPruning(Node* node, const Node* exclude_node) {
}
Element* EnclosingTableCell(const Position& p) {
- return ToElement(EnclosingNodeOfType(p, IsTableCell));
+ return To<Element>(EnclosingNodeOfType(p, IsTableCell));
}
bool IsTableStructureNode(const Node* node) {
@@ -132,18 +132,18 @@ Node* EnclosingEmptyListItem(const VisiblePosition& visible_pos) {
}
bool AreIdenticalElements(const Node& first, const Node& second) {
- if (!first.IsElementNode() || !second.IsElementNode())
+ const auto* first_element = DynamicTo<Element>(first);
+ const auto* second_element = DynamicTo<Element>(second);
+ if (!first_element || !second_element)
return false;
- const Element& first_element = ToElement(first);
- const Element& second_element = ToElement(second);
- if (!first_element.HasTagName(second_element.TagQName()))
+ if (!first_element->HasTagName(second_element->TagQName()))
return false;
- if (!first_element.HasEquivalentAttributes(second_element))
+ if (!first_element->HasEquivalentAttributes(*second_element))
return false;
- return HasEditableStyle(first_element) && HasEditableStyle(second_element);
+ return HasEditableStyle(*first_element) && HasEditableStyle(*second_element);
}
// FIXME: need to dump this
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/editing_state.h b/chromium/third_party/blink/renderer/core/editing/commands/editing_state.h
index e1840d17c0d..f5b63acbfe8 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/editing_state.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/editing_state.h
@@ -7,7 +7,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
namespace blink {
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 43530091ebe..4476c4673d6 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
@@ -60,6 +60,7 @@
#include "third_party/blink/renderer/core/editing/visible_position.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/settings.h"
#include "third_party/blink/renderer/core/html/html_br_element.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/input/event_handler.h"
@@ -68,8 +69,8 @@
#include "third_party/blink/renderer/core/scroll/scrollbar.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
-#include "third_party/blink/renderer/platform/histogram.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
#include <iterator>
@@ -101,10 +102,10 @@ WebEditingCommandType WebEditingCommandTypeFromCommandName(
const CommandNameEntry* result = std::lower_bound(
std::begin(kCommandNameEntries), std::end(kCommandNameEntries),
command_name, [](const CommandNameEntry& entry, const String& needle) {
- return CodePointCompareIgnoringASCIICase(needle, entry.name) > 0;
+ return CodeUnitCompareIgnoringASCIICase(needle, entry.name) > 0;
});
if (result != std::end(kCommandNameEntries) &&
- CodePointCompareIgnoringASCIICase(command_name, result->name) == 0)
+ CodeUnitCompareIgnoringASCIICase(command_name, result->name) == 0)
return result->type;
return WebEditingCommandType::kInvalid;
}
@@ -1046,11 +1047,13 @@ static bool EnabledVisibleSelection(LocalFrame& frame,
!frame.Selection().SelectionHasFocus())
return false;
- // The term "visible" here includes a caret in editable text or a range in any
- // text.
+ // The term "visible" here includes a caret in editable text, a range in any
+ // text, or a caret in non-editable text when caret browsing is enabled.
const VisibleSelection& selection =
CreateVisibleSelection(frame.GetEditor().SelectionForCommand(event));
- return (selection.IsCaret() && selection.IsContentEditable()) ||
+ return (selection.IsCaret() &&
+ (selection.IsContentEditable() ||
+ frame.GetSettings()->GetCaretBrowsingEnabled())) ||
selection.IsRange();
}
@@ -1065,7 +1068,9 @@ static bool EnabledVisibleSelectionAndMark(LocalFrame& frame,
const VisibleSelection& selection =
CreateVisibleSelection(frame.GetEditor().SelectionForCommand(event));
- return ((selection.IsCaret() && selection.IsContentEditable()) ||
+ return ((selection.IsCaret() &&
+ (selection.IsContentEditable() ||
+ frame.GetSettings()->GetCaretBrowsingEnabled())) ||
selection.IsRange()) &&
!frame.GetEditor().Mark().IsNone();
}
@@ -1096,6 +1101,13 @@ static bool EnabledInEditableText(LocalFrame& frame,
CreateVisiblePosition(selection.Base()).DeepEquivalent());
}
+static bool EnabledInEditableTextOrCaretBrowsing(LocalFrame& frame,
+ Event* event,
+ EditorCommandSource source) {
+ return frame.GetSettings()->GetCaretBrowsingEnabled() ||
+ EnabledInEditableText(frame, event, source);
+}
+
static bool EnabledDelete(LocalFrame& frame,
Event* event,
EditorCommandSource source) {
@@ -1480,184 +1492,198 @@ static const EditorInternalCommand* InternalCommand(
StyleCommands::StateTextWritingDirectionRightToLeft, ValueStateOrNull,
kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveBackward, MoveCommands::ExecuteMoveBackward,
- SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone,
- ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
+ SupportedFromMenuOrKeyBinding, EnabledInEditableTextOrCaretBrowsing,
+ StateNone, ValueStateOrNull, kNotTextInsertion,
+ CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveBackwardAndModifySelection,
MoveCommands::ExecuteMoveBackwardAndModifySelection,
SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone,
ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveDown, MoveCommands::ExecuteMoveDown,
- SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone,
- ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
+ SupportedFromMenuOrKeyBinding, EnabledInEditableTextOrCaretBrowsing,
+ StateNone, ValueStateOrNull, kNotTextInsertion,
+ CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveDownAndModifySelection,
MoveCommands::ExecuteMoveDownAndModifySelection,
SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone,
ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveForward, MoveCommands::ExecuteMoveForward,
- SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone,
- ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
+ SupportedFromMenuOrKeyBinding, EnabledInEditableTextOrCaretBrowsing,
+ StateNone, ValueStateOrNull, kNotTextInsertion,
+ CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveForwardAndModifySelection,
MoveCommands::ExecuteMoveForwardAndModifySelection,
SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone,
ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveLeft, MoveCommands::ExecuteMoveLeft,
- SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone,
- ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
+ SupportedFromMenuOrKeyBinding, EnabledInEditableTextOrCaretBrowsing,
+ StateNone, ValueStateOrNull, kNotTextInsertion,
+ CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveLeftAndModifySelection,
MoveCommands::ExecuteMoveLeftAndModifySelection,
SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone,
ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMovePageDown, MoveCommands::ExecuteMovePageDown,
- SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone,
- ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
+ SupportedFromMenuOrKeyBinding, EnabledInEditableTextOrCaretBrowsing,
+ StateNone, ValueStateOrNull, kNotTextInsertion,
+ CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMovePageDownAndModifySelection,
MoveCommands::ExecuteMovePageDownAndModifySelection,
SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone,
ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMovePageUp, MoveCommands::ExecuteMovePageUp,
- SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone,
- ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
+ SupportedFromMenuOrKeyBinding, EnabledInEditableTextOrCaretBrowsing,
+ StateNone, ValueStateOrNull, kNotTextInsertion,
+ CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMovePageUpAndModifySelection,
MoveCommands::ExecuteMovePageUpAndModifySelection,
SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone,
ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveParagraphBackward,
MoveCommands::ExecuteMoveParagraphBackward,
- SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone,
- ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
+ SupportedFromMenuOrKeyBinding, EnabledInEditableTextOrCaretBrowsing,
+ StateNone, ValueStateOrNull, kNotTextInsertion,
+ CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveParagraphBackwardAndModifySelection,
MoveCommands::ExecuteMoveParagraphBackwardAndModifySelection,
SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone,
ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveParagraphForward,
MoveCommands::ExecuteMoveParagraphForward, SupportedFromMenuOrKeyBinding,
- EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion,
- CanNotExecuteWhenDisabled},
+ EnabledInEditableTextOrCaretBrowsing, StateNone, ValueStateOrNull,
+ kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveParagraphForwardAndModifySelection,
MoveCommands::ExecuteMoveParagraphForwardAndModifySelection,
SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone,
ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveRight, MoveCommands::ExecuteMoveRight,
- SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone,
- ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
+ SupportedFromMenuOrKeyBinding, EnabledInEditableTextOrCaretBrowsing,
+ StateNone, ValueStateOrNull, kNotTextInsertion,
+ CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveRightAndModifySelection,
MoveCommands::ExecuteMoveRightAndModifySelection,
SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone,
ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveToBeginningOfDocument,
MoveCommands::ExecuteMoveToBeginningOfDocument,
- SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone,
- ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
+ SupportedFromMenuOrKeyBinding, EnabledInEditableTextOrCaretBrowsing,
+ StateNone, ValueStateOrNull, kNotTextInsertion,
+ CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveToBeginningOfDocumentAndModifySelection,
MoveCommands::ExecuteMoveToBeginningOfDocumentAndModifySelection,
SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone,
ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveToBeginningOfLine,
MoveCommands::ExecuteMoveToBeginningOfLine,
- SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone,
- ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
+ SupportedFromMenuOrKeyBinding, EnabledInEditableTextOrCaretBrowsing,
+ StateNone, ValueStateOrNull, kNotTextInsertion,
+ CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveToBeginningOfLineAndModifySelection,
MoveCommands::ExecuteMoveToBeginningOfLineAndModifySelection,
SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone,
ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveToBeginningOfParagraph,
MoveCommands::ExecuteMoveToBeginningOfParagraph,
- SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone,
- ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
+ SupportedFromMenuOrKeyBinding, EnabledInEditableTextOrCaretBrowsing,
+ StateNone, ValueStateOrNull, kNotTextInsertion,
+ CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveToBeginningOfParagraphAndModifySelection,
MoveCommands::ExecuteMoveToBeginningOfParagraphAndModifySelection,
SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone,
ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveToBeginningOfSentence,
MoveCommands::ExecuteMoveToBeginningOfSentence,
- SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone,
- ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
+ SupportedFromMenuOrKeyBinding, EnabledInEditableTextOrCaretBrowsing,
+ StateNone, ValueStateOrNull, kNotTextInsertion,
+ CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveToBeginningOfSentenceAndModifySelection,
MoveCommands::ExecuteMoveToBeginningOfSentenceAndModifySelection,
SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone,
ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveToEndOfDocument,
MoveCommands::ExecuteMoveToEndOfDocument, SupportedFromMenuOrKeyBinding,
- EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion,
- CanNotExecuteWhenDisabled},
+ EnabledInEditableTextOrCaretBrowsing, StateNone, ValueStateOrNull,
+ kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveToEndOfDocumentAndModifySelection,
MoveCommands::ExecuteMoveToEndOfDocumentAndModifySelection,
SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone,
ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveToEndOfLine,
MoveCommands::ExecuteMoveToEndOfLine, SupportedFromMenuOrKeyBinding,
- EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion,
- CanNotExecuteWhenDisabled},
+ EnabledInEditableTextOrCaretBrowsing, StateNone, ValueStateOrNull,
+ kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveToEndOfLineAndModifySelection,
MoveCommands::ExecuteMoveToEndOfLineAndModifySelection,
SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone,
ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveToEndOfParagraph,
MoveCommands::ExecuteMoveToEndOfParagraph, SupportedFromMenuOrKeyBinding,
- EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion,
- CanNotExecuteWhenDisabled},
+ EnabledInEditableTextOrCaretBrowsing, StateNone, ValueStateOrNull,
+ kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveToEndOfParagraphAndModifySelection,
MoveCommands::ExecuteMoveToEndOfParagraphAndModifySelection,
SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone,
ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveToEndOfSentence,
MoveCommands::ExecuteMoveToEndOfSentence, SupportedFromMenuOrKeyBinding,
- EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion,
- CanNotExecuteWhenDisabled},
+ EnabledInEditableTextOrCaretBrowsing, StateNone, ValueStateOrNull,
+ kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveToEndOfSentenceAndModifySelection,
MoveCommands::ExecuteMoveToEndOfSentenceAndModifySelection,
SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone,
ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveToLeftEndOfLine,
MoveCommands::ExecuteMoveToLeftEndOfLine, SupportedFromMenuOrKeyBinding,
- EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion,
- CanNotExecuteWhenDisabled},
+ EnabledInEditableTextOrCaretBrowsing, StateNone, ValueStateOrNull,
+ kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveToLeftEndOfLineAndModifySelection,
MoveCommands::ExecuteMoveToLeftEndOfLineAndModifySelection,
SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone,
ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveToRightEndOfLine,
MoveCommands::ExecuteMoveToRightEndOfLine, SupportedFromMenuOrKeyBinding,
- EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion,
- CanNotExecuteWhenDisabled},
+ EnabledInEditableTextOrCaretBrowsing, StateNone, ValueStateOrNull,
+ kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveToRightEndOfLineAndModifySelection,
MoveCommands::ExecuteMoveToRightEndOfLineAndModifySelection,
SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone,
ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveUp, MoveCommands::ExecuteMoveUp,
- SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone,
- ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
+ SupportedFromMenuOrKeyBinding, EnabledInEditableTextOrCaretBrowsing,
+ StateNone, ValueStateOrNull, kNotTextInsertion,
+ CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveUpAndModifySelection,
MoveCommands::ExecuteMoveUpAndModifySelection,
SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone,
ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveWordBackward,
MoveCommands::ExecuteMoveWordBackward, SupportedFromMenuOrKeyBinding,
- EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion,
- CanNotExecuteWhenDisabled},
+ EnabledInEditableTextOrCaretBrowsing, StateNone, ValueStateOrNull,
+ kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveWordBackwardAndModifySelection,
MoveCommands::ExecuteMoveWordBackwardAndModifySelection,
SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone,
ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveWordForward,
MoveCommands::ExecuteMoveWordForward, SupportedFromMenuOrKeyBinding,
- EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion,
- CanNotExecuteWhenDisabled},
+ EnabledInEditableTextOrCaretBrowsing, StateNone, ValueStateOrNull,
+ kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveWordForwardAndModifySelection,
MoveCommands::ExecuteMoveWordForwardAndModifySelection,
SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone,
ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveWordLeft, MoveCommands::ExecuteMoveWordLeft,
- SupportedFromMenuOrKeyBinding, EnabledInEditableText, StateNone,
- ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
+ SupportedFromMenuOrKeyBinding, EnabledInEditableTextOrCaretBrowsing,
+ StateNone, ValueStateOrNull, kNotTextInsertion,
+ CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveWordLeftAndModifySelection,
MoveCommands::ExecuteMoveWordLeftAndModifySelection,
SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone,
ValueStateOrNull, kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveWordRight,
MoveCommands::ExecuteMoveWordRight, SupportedFromMenuOrKeyBinding,
- EnabledInEditableText, StateNone, ValueStateOrNull, kNotTextInsertion,
- CanNotExecuteWhenDisabled},
+ EnabledInEditableTextOrCaretBrowsing, StateNone, ValueStateOrNull,
+ kNotTextInsertion, CanNotExecuteWhenDisabled},
{WebEditingCommandType::kMoveWordRightAndModifySelection,
MoveCommands::ExecuteMoveWordRightAndModifySelection,
SupportedFromMenuOrKeyBinding, EnabledVisibleSelection, StateNone,
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 d4670e1891e..8f6215d8715 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
@@ -45,8 +45,8 @@ using namespace html_names;
static Node* EnclosingBlockToSplitTreeTo(Node* start_node);
static bool IsElementForFormatBlock(const QualifiedName& tag_name);
static inline bool IsElementForFormatBlock(Node* node) {
- return node->IsElementNode() &&
- IsElementForFormatBlock(ToElement(node)->TagQName());
+ auto* element = DynamicTo<Element>(node);
+ return element && IsElementForFormatBlock(element->TagQName());
}
static Element* EnclosingBlockFlowElement(
@@ -170,8 +170,7 @@ Element* FormatBlockCommand::ElementForFormatBlockCommand(
if (!element || common_ancestor->contains(element))
return nullptr;
- return common_ancestor->IsElementNode() ? ToElement(common_ancestor)
- : nullptr;
+ return DynamicTo<Element>(common_ancestor);
}
bool IsElementForFormatBlock(const QualifiedName& tag_name) {
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 e0c550f0bb0..ab283d72b39 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
@@ -158,7 +158,7 @@ void IndentOutdentCommand::IndentIntoBlockquote(const Position& start,
const Position& end,
HTMLElement*& target_blockquote,
EditingState* editing_state) {
- Element* enclosing_cell = ToElement(EnclosingNodeOfType(start, &IsTableCell));
+ auto* enclosing_cell = To<Element>(EnclosingNodeOfType(start, &IsTableCell));
Element* element_to_split_to;
if (enclosing_cell)
element_to_split_to = enclosing_cell;
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/insert_commands.h b/chromium/third_party/blink/renderer/core/editing/commands/insert_commands.h
index 19a633e0a66..0ac3d424ebc 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/insert_commands.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/insert_commands.h
@@ -32,7 +32,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_EDITING_COMMANDS_INSERT_COMMANDS_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_EDITING_COMMANDS_INSERT_COMMANDS_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
namespace blink {
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 ddf9e35d81a..c7fcbbbedd2 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
@@ -402,7 +402,7 @@ bool InsertListCommand::DoApplyForSingleParagraph(
list_element);
Element* outer_block =
first_child_in_list && IsBlockFlowElement(*first_child_in_list)
- ? ToElement(first_child_in_list)
+ ? To<Element>(first_child_in_list)
: list_element;
MoveParagraphWithClones(
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/move_commands.cc b/chromium/third_party/blink/renderer/core/editing/commands/move_commands.cc
index c9c11f8f260..b84a47076e3 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/move_commands.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/move_commands.cc
@@ -31,21 +31,29 @@
#include "third_party/blink/renderer/core/editing/commands/move_commands.h"
+#include "third_party/blink/renderer/core/dom/node_computed_style.h"
#include "third_party/blink/renderer/core/editing/editing_behavior.h"
#include "third_party/blink/renderer/core/editing/editing_utilities.h"
#include "third_party/blink/renderer/core/editing/editor.h"
#include "third_party/blink/renderer/core/editing/frame_selection.h"
#include "third_party/blink/renderer/core/editing/selection_modifier.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/layout/layout_box.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
namespace blink {
unsigned MoveCommands::VerticalScrollDistance(LocalFrame& frame) {
- const Element* const focused_element = frame.GetDocument()->FocusedElement();
- if (!focused_element)
- return 0;
+ const Element* focused_element = frame.GetDocument()->FocusedElement();
+ if (!focused_element) {
+ if (frame.GetSettings()->GetCaretBrowsingEnabled()) {
+ focused_element = frame.GetDocument()->ActiveElement();
+ }
+
+ if (!focused_element)
+ return 0;
+ }
LayoutObject* const layout_object = focused_element->GetLayoutObject();
if (!layout_object || !layout_object->IsBox())
return 0;
@@ -55,7 +63,8 @@ unsigned MoveCommands::VerticalScrollDistance(LocalFrame& frame) {
return 0;
if (!(style->OverflowY() == EOverflow::kScroll ||
style->OverflowY() == EOverflow::kAuto ||
- HasEditableStyle(*focused_element)))
+ HasEditableStyle(*focused_element) ||
+ frame.GetSettings()->GetCaretBrowsingEnabled()))
return 0;
const ScrollableArea& scrollable_area = *frame.View()->LayoutViewport();
const int height = std::min<int>(layout_box.ClientHeight().ToInt(),
@@ -71,6 +80,9 @@ bool MoveCommands::ModifySelectionWithPageGranularity(
SelectionModifyAlteration alter,
unsigned vertical_distance,
SelectionModifyVerticalDirection direction) {
+ if (alter == SelectionModifyAlteration::kMove)
+ UpdateSelectionForCaretBrowsing(frame);
+
SelectionModifier selection_modifier(
frame, frame.Selection().GetSelectionInDOMTree());
selection_modifier.SetSelectionIsDirectional(
@@ -94,16 +106,87 @@ bool MoveCommands::ModifySelectionWithPageGranularity(
.Behavior()
.ShouldConsiderSelectionAsDirectional())
.Build());
+
+ UpdateFocusForCaretBrowsing(frame);
+
return true;
}
+bool MoveCommands::MoveSelection(LocalFrame& frame,
+ SelectionModifyDirection direction,
+ TextGranularity granularity) {
+ UpdateSelectionForCaretBrowsing(frame);
+ const bool modified =
+ frame.Selection().Modify(SelectionModifyAlteration::kMove, direction,
+ granularity, SetSelectionBy::kUser);
+ if (modified)
+ UpdateFocusForCaretBrowsing(frame);
+
+ return modified;
+}
+
+void MoveCommands::UpdateFocusForCaretBrowsing(LocalFrame& frame) {
+ if (!frame.GetSettings()->GetCaretBrowsingEnabled())
+ return;
+
+ SelectionInDOMTree selection = frame.Selection().GetSelectionInDOMTree();
+ if (!selection.IsCaret())
+ return;
+
+ Node* node = selection.Extent().ComputeContainerNode();
+ if (!node)
+ return;
+
+ const ComputedStyle* style = node->GetComputedStyle();
+ if (!style || style->UserModify() != EUserModify::kReadOnly)
+ return;
+
+ Element* new_focused_element = nullptr;
+
+ while (node) {
+ if (node->IsElementNode() && ToElement(node)->IsFocusable()) {
+ new_focused_element = ToElement(node);
+ break;
+ }
+ node = node->ParentOrShadowHostNode();
+ }
+
+ if (new_focused_element == frame.GetDocument()->FocusedElement())
+ return;
+
+ frame.GetDocument()->SetFocusedElement(
+ new_focused_element,
+ FocusParams(SelectionBehaviorOnFocus::kNone, kWebFocusTypeNone, nullptr));
+}
+
+void MoveCommands::UpdateSelectionForCaretBrowsing(LocalFrame& frame) {
+ if (!frame.GetSettings()->GetCaretBrowsingEnabled())
+ return;
+
+ if (frame.Selection().SelectionHasFocus())
+ return;
+
+ Element* activeElement = frame.GetDocument()->ActiveElement();
+ if (!activeElement)
+ return;
+
+ frame.Selection().SetSelection(
+ SelectionInDOMTree::Builder()
+ .Collapse(Position::FirstPositionInOrBeforeNode(*activeElement))
+ .Build(),
+ SetSelectionOptions::Builder()
+ .SetShouldCloseTyping(true)
+ .SetShouldClearTypingStyle(true)
+ .SetDoNotSetFocus(true)
+ .Build());
+}
+
bool MoveCommands::ExecuteMoveBackward(LocalFrame& frame,
Event*,
EditorCommandSource,
const String&) {
- frame.Selection().Modify(SelectionModifyAlteration::kMove,
- SelectionModifyDirection::kBackward,
- TextGranularity::kCharacter, SetSelectionBy::kUser);
+ MoveSelection(frame, SelectionModifyDirection::kBackward,
+ TextGranularity::kCharacter);
return true;
}
@@ -121,9 +204,8 @@ bool MoveCommands::ExecuteMoveDown(LocalFrame& frame,
Event*,
EditorCommandSource,
const String&) {
- return frame.Selection().Modify(
- SelectionModifyAlteration::kMove, SelectionModifyDirection::kForward,
- TextGranularity::kLine, SetSelectionBy::kUser);
+ return MoveSelection(frame, SelectionModifyDirection::kForward,
+ TextGranularity::kLine);
}
bool MoveCommands::ExecuteMoveDownAndModifySelection(LocalFrame& frame,
@@ -140,9 +222,8 @@ bool MoveCommands::ExecuteMoveForward(LocalFrame& frame,
Event*,
EditorCommandSource,
const String&) {
- frame.Selection().Modify(SelectionModifyAlteration::kMove,
- SelectionModifyDirection::kForward,
- TextGranularity::kCharacter, SetSelectionBy::kUser);
+ MoveSelection(frame, SelectionModifyDirection::kForward,
+ TextGranularity::kCharacter);
return true;
}
@@ -160,9 +241,8 @@ bool MoveCommands::ExecuteMoveLeft(LocalFrame& frame,
Event*,
EditorCommandSource,
const String&) {
- return frame.Selection().Modify(
- SelectionModifyAlteration::kMove, SelectionModifyDirection::kLeft,
- TextGranularity::kCharacter, SetSelectionBy::kUser);
+ return MoveSelection(frame, SelectionModifyDirection::kLeft,
+ TextGranularity::kCharacter);
}
bool MoveCommands::ExecuteMoveLeftAndModifySelection(LocalFrame& frame,
@@ -227,9 +307,8 @@ bool MoveCommands::ExecuteMoveParagraphBackward(LocalFrame& frame,
Event*,
EditorCommandSource,
const String&) {
- frame.Selection().Modify(SelectionModifyAlteration::kMove,
- SelectionModifyDirection::kBackward,
- TextGranularity::kParagraph, SetSelectionBy::kUser);
+ MoveSelection(frame, SelectionModifyDirection::kBackward,
+ TextGranularity::kParagraph);
return true;
}
@@ -248,9 +327,8 @@ bool MoveCommands::ExecuteMoveParagraphForward(LocalFrame& frame,
Event*,
EditorCommandSource,
const String&) {
- frame.Selection().Modify(SelectionModifyAlteration::kMove,
- SelectionModifyDirection::kForward,
- TextGranularity::kParagraph, SetSelectionBy::kUser);
+ MoveSelection(frame, SelectionModifyDirection::kForward,
+ TextGranularity::kParagraph);
return true;
}
@@ -269,9 +347,8 @@ bool MoveCommands::ExecuteMoveRight(LocalFrame& frame,
Event*,
EditorCommandSource,
const String&) {
- return frame.Selection().Modify(
- SelectionModifyAlteration::kMove, SelectionModifyDirection::kRight,
- TextGranularity::kCharacter, SetSelectionBy::kUser);
+ return MoveSelection(frame, SelectionModifyDirection::kRight,
+ TextGranularity::kCharacter);
}
bool MoveCommands::ExecuteMoveRightAndModifySelection(LocalFrame& frame,
@@ -288,9 +365,8 @@ bool MoveCommands::ExecuteMoveToBeginningOfDocument(LocalFrame& frame,
Event*,
EditorCommandSource,
const String&) {
- frame.Selection().Modify(
- SelectionModifyAlteration::kMove, SelectionModifyDirection::kBackward,
- TextGranularity::kDocumentBoundary, SetSelectionBy::kUser);
+ MoveSelection(frame, SelectionModifyDirection::kBackward,
+ TextGranularity::kDocumentBoundary);
return true;
}
@@ -309,9 +385,8 @@ bool MoveCommands::ExecuteMoveToBeginningOfLine(LocalFrame& frame,
Event*,
EditorCommandSource,
const String&) {
- frame.Selection().Modify(
- SelectionModifyAlteration::kMove, SelectionModifyDirection::kBackward,
- TextGranularity::kLineBoundary, SetSelectionBy::kUser);
+ MoveSelection(frame, SelectionModifyDirection::kBackward,
+ TextGranularity::kLineBoundary);
return true;
}
@@ -330,9 +405,8 @@ bool MoveCommands::ExecuteMoveToBeginningOfParagraph(LocalFrame& frame,
Event*,
EditorCommandSource,
const String&) {
- frame.Selection().Modify(
- SelectionModifyAlteration::kMove, SelectionModifyDirection::kBackward,
- TextGranularity::kParagraphBoundary, SetSelectionBy::kUser);
+ MoveSelection(frame, SelectionModifyDirection::kBackward,
+ TextGranularity::kParagraphBoundary);
return true;
}
@@ -351,9 +425,8 @@ bool MoveCommands::ExecuteMoveToBeginningOfSentence(LocalFrame& frame,
Event*,
EditorCommandSource,
const String&) {
- frame.Selection().Modify(
- SelectionModifyAlteration::kMove, SelectionModifyDirection::kBackward,
- TextGranularity::kSentenceBoundary, SetSelectionBy::kUser);
+ MoveSelection(frame, SelectionModifyDirection::kBackward,
+ TextGranularity::kSentenceBoundary);
return true;
}
@@ -372,9 +445,8 @@ bool MoveCommands::ExecuteMoveToEndOfDocument(LocalFrame& frame,
Event*,
EditorCommandSource,
const String&) {
- frame.Selection().Modify(
- SelectionModifyAlteration::kMove, SelectionModifyDirection::kForward,
- TextGranularity::kDocumentBoundary, SetSelectionBy::kUser);
+ MoveSelection(frame, SelectionModifyDirection::kForward,
+ TextGranularity::kDocumentBoundary);
return true;
}
@@ -393,9 +465,8 @@ bool MoveCommands::ExecuteMoveToEndOfLine(LocalFrame& frame,
Event*,
EditorCommandSource,
const String&) {
- frame.Selection().Modify(
- SelectionModifyAlteration::kMove, SelectionModifyDirection::kForward,
- TextGranularity::kLineBoundary, SetSelectionBy::kUser);
+ MoveSelection(frame, SelectionModifyDirection::kForward,
+ TextGranularity::kLineBoundary);
return true;
}
@@ -413,9 +484,8 @@ bool MoveCommands::ExecuteMoveToEndOfParagraph(LocalFrame& frame,
Event*,
EditorCommandSource,
const String&) {
- frame.Selection().Modify(
- SelectionModifyAlteration::kMove, SelectionModifyDirection::kForward,
- TextGranularity::kParagraphBoundary, SetSelectionBy::kUser);
+ MoveSelection(frame, SelectionModifyDirection::kForward,
+ TextGranularity::kParagraphBoundary);
return true;
}
@@ -434,9 +504,8 @@ bool MoveCommands::ExecuteMoveToEndOfSentence(LocalFrame& frame,
Event*,
EditorCommandSource,
const String&) {
- frame.Selection().Modify(
- SelectionModifyAlteration::kMove, SelectionModifyDirection::kForward,
- TextGranularity::kSentenceBoundary, SetSelectionBy::kUser);
+ MoveSelection(frame, SelectionModifyDirection::kForward,
+ TextGranularity::kSentenceBoundary);
return true;
}
@@ -455,9 +524,8 @@ bool MoveCommands::ExecuteMoveToLeftEndOfLine(LocalFrame& frame,
Event*,
EditorCommandSource,
const String&) {
- frame.Selection().Modify(
- SelectionModifyAlteration::kMove, SelectionModifyDirection::kLeft,
- TextGranularity::kLineBoundary, SetSelectionBy::kUser);
+ MoveSelection(frame, SelectionModifyDirection::kLeft,
+ TextGranularity::kLineBoundary);
return true;
}
@@ -476,9 +544,8 @@ bool MoveCommands::ExecuteMoveToRightEndOfLine(LocalFrame& frame,
Event*,
EditorCommandSource,
const String&) {
- frame.Selection().Modify(
- SelectionModifyAlteration::kMove, SelectionModifyDirection::kRight,
- TextGranularity::kLineBoundary, SetSelectionBy::kUser);
+ MoveSelection(frame, SelectionModifyDirection::kRight,
+ TextGranularity::kLineBoundary);
return true;
}
@@ -497,9 +564,8 @@ bool MoveCommands::ExecuteMoveUp(LocalFrame& frame,
Event*,
EditorCommandSource,
const String&) {
- return frame.Selection().Modify(
- SelectionModifyAlteration::kMove, SelectionModifyDirection::kBackward,
- TextGranularity::kLine, SetSelectionBy::kUser);
+ return MoveSelection(frame, SelectionModifyDirection::kBackward,
+ TextGranularity::kLine);
}
bool MoveCommands::ExecuteMoveUpAndModifySelection(LocalFrame& frame,
@@ -516,9 +582,8 @@ bool MoveCommands::ExecuteMoveWordBackward(LocalFrame& frame,
Event*,
EditorCommandSource,
const String&) {
- frame.Selection().Modify(SelectionModifyAlteration::kMove,
- SelectionModifyDirection::kBackward,
- TextGranularity::kWord, SetSelectionBy::kUser);
+ MoveSelection(frame, SelectionModifyDirection::kBackward,
+ TextGranularity::kWord);
return true;
}
@@ -537,9 +602,8 @@ bool MoveCommands::ExecuteMoveWordForward(LocalFrame& frame,
Event*,
EditorCommandSource,
const String&) {
- frame.Selection().Modify(SelectionModifyAlteration::kMove,
- SelectionModifyDirection::kForward,
- TextGranularity::kWord, SetSelectionBy::kUser);
+ MoveSelection(frame, SelectionModifyDirection::kForward,
+ TextGranularity::kWord);
return true;
}
@@ -557,9 +621,7 @@ bool MoveCommands::ExecuteMoveWordLeft(LocalFrame& frame,
Event*,
EditorCommandSource,
const String&) {
- frame.Selection().Modify(SelectionModifyAlteration::kMove,
- SelectionModifyDirection::kLeft,
- TextGranularity::kWord, SetSelectionBy::kUser);
+ MoveSelection(frame, SelectionModifyDirection::kLeft, TextGranularity::kWord);
return true;
}
@@ -577,9 +639,8 @@ bool MoveCommands::ExecuteMoveWordRight(LocalFrame& frame,
Event*,
EditorCommandSource,
const String&) {
- frame.Selection().Modify(SelectionModifyAlteration::kMove,
- SelectionModifyDirection::kRight,
- TextGranularity::kWord, SetSelectionBy::kUser);
+ MoveSelection(frame, SelectionModifyDirection::kRight,
+ TextGranularity::kWord);
return true;
}
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/move_commands.h b/chromium/third_party/blink/renderer/core/editing/commands/move_commands.h
index 4eaf2cc9868..062c6416e4f 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/move_commands.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/move_commands.h
@@ -32,7 +32,8 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_EDITING_COMMANDS_MOVE_COMMANDS_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_EDITING_COMMANDS_MOVE_COMMANDS_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
namespace blink {
@@ -42,10 +43,12 @@ class LocalFrame;
enum class EditorCommandSource;
enum class SelectionModifyAlteration;
+enum class SelectionModifyDirection;
enum class SelectionModifyVerticalDirection;
+enum class TextGranularity;
// This class provides static functions about commands related to move.
-class MoveCommands {
+class CORE_EXPORT MoveCommands {
STATIC_ONLY(MoveCommands);
public:
@@ -257,6 +260,26 @@ class MoveCommands {
SelectionModifyAlteration,
unsigned,
SelectionModifyVerticalDirection);
+
+ // Wraps FrameSelection::Modify for case where the selection is moved by the
+ // user. Returns false if the "selectstart" event is dispatched and canceled,
+ // otherwise returns true (return value does not indicate whether the
+ // selection was modified).
+ static bool MoveSelection(LocalFrame&,
+ SelectionModifyDirection,
+ TextGranularity);
+
+ // If caret browsing is enabled and the caret is in a non-editable region then
+ // UpdateFocusForCaretBrowsing moves focus to the nearest focusable ancestor
+ // of the caret, if there is one. This will, for example, move focus to anchor
+ // elements when the caret enters an anchor. If there is no focusable ancestor
+ // then focus will move to the body.
+ static void UpdateFocusForCaretBrowsing(LocalFrame&);
+
+ // If caret browsing is enabled and the caret/selection is not in focus then
+ // UpdateSelectionForCaretBrowsing moves the caret to the first position in
+ // the active element.
+ static void UpdateSelectionForCaretBrowsing(LocalFrame&);
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/move_commands_test.cc b/chromium/third_party/blink/renderer/core/editing/commands/move_commands_test.cc
new file mode 100644
index 00000000000..7de107b8210
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/editing/commands/move_commands_test.cc
@@ -0,0 +1,327 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include <string>
+
+#include "build/build_config.h"
+#include "third_party/blink/renderer/core/dom/element.h"
+#include "third_party/blink/renderer/core/editing/commands/move_commands.h"
+#include "third_party/blink/renderer/core/editing/editor.h"
+#include "third_party/blink/renderer/core/editing/frame_selection.h"
+#include "third_party/blink/renderer/core/editing/selection_template.h"
+#include "third_party/blink/renderer/core/editing/testing/editing_test_base.h"
+#include "third_party/blink/renderer/core/frame/settings.h"
+
+namespace blink {
+
+class MoveCommandsTest : public EditingTestBase {
+ protected:
+ void VerifyCaretBrowsingPositionAndFocusUpdate(
+ const std::string& initial_selection_text,
+ const AtomicString& initial_focus_element,
+ bool (*execute)(LocalFrame&, Event*, EditorCommandSource, const String&),
+ const std::string& final_selection_text,
+ const AtomicString& final_focus_element) {
+ Selection().SetSelection(SetSelectionTextToBody(initial_selection_text),
+ SetSelectionOptions());
+ GetDocument().SetFocusedElement(
+ GetDocument().QuerySelector(initial_focus_element),
+ FocusParams(SelectionBehaviorOnFocus::kNone, kWebFocusTypeNone,
+ nullptr));
+ GetDocument().GetFrame()->GetSettings()->SetCaretBrowsingEnabled(true);
+ execute(*GetDocument().GetFrame(), nullptr,
+ EditorCommandSource::kMenuOrKeyBinding, String());
+ EXPECT_EQ(final_selection_text, GetSelectionTextFromBody());
+ EXPECT_EQ(GetDocument().QuerySelector(final_focus_element),
+ GetDocument().ActiveElement());
+ }
+};
+
+// The following CaretBrowsingPositionAndFocusUpdate_Move* tests verify that the
+// move commands are using UpdateFocusForCaretBrowsing to adjust caret position
+// and focus while caret browsing.
+
+TEST_F(MoveCommandsTest, CaretBrowsingPositionAndFocusUpdate_MoveBackward) {
+ VerifyCaretBrowsingPositionAndFocusUpdate(
+ "<div><a href=\"foo\">a</a>|b</div>", "body",
+ MoveCommands::ExecuteMoveBackward, "<div><a href=\"foo\">|a</a>b</div>",
+ "a");
+}
+
+TEST_F(MoveCommandsTest, CaretBrowsingPositionAndFocusUpdate_MoveDown) {
+ VerifyCaretBrowsingPositionAndFocusUpdate(
+ "<div>a|b</div><div><a href=\"foo\">cd</a></div>", "body",
+ MoveCommands::ExecuteMoveDown,
+#if !defined(OS_MACOSX)
+ "<div>ab</div><div><a href=\"foo\">c|d</a></div>", "a");
+#else // defined(OS_MACOSX)
+ // MoveDown navigates visually, placing caret at different position for
+ // macOS.
+ "<div>ab</div><div><a href=\"foo\">|cd</a></div>", "a");
+#endif // !defined(OS_MACOSX)
+}
+
+TEST_F(MoveCommandsTest, CaretBrowsingPositionAndFocusUpdate_MoveForward) {
+ VerifyCaretBrowsingPositionAndFocusUpdate(
+ "<div>a|<a href=\"foo\">b</a></div>", "body",
+ MoveCommands::ExecuteMoveForward, "<div>a<a href=\"foo\">b|</a></div>",
+ "a");
+}
+
+TEST_F(MoveCommandsTest, CaretBrowsingPositionAndFocusUpdate_MoveLeft) {
+ VerifyCaretBrowsingPositionAndFocusUpdate(
+ "<div><a href=\"foo\">a</a>|b</div>", "body",
+ MoveCommands::ExecuteMoveLeft, "<div><a href=\"foo\">|a</a>b</div>", "a");
+}
+
+TEST_F(MoveCommandsTest,
+ CaretBrowsingPositionAndFocusUpdate_MoveParagraphBackward) {
+ VerifyCaretBrowsingPositionAndFocusUpdate(
+ "<div><a href=\"foo\">a</a>|b</div>", "body",
+ MoveCommands::ExecuteMoveParagraphBackward,
+ "<div><a href=\"foo\">|a</a>b</div>", "a");
+}
+
+TEST_F(MoveCommandsTest,
+ CaretBrowsingPositionAndFocusUpdate_MoveParagraphForward) {
+ VerifyCaretBrowsingPositionAndFocusUpdate(
+ "<div>a|<a href=\"foo\">b</a></div>", "body",
+ MoveCommands::ExecuteMoveParagraphForward,
+ "<div>a<a href=\"foo\">b|</a></div>", "a");
+}
+
+TEST_F(MoveCommandsTest, CaretBrowsingPositionAndFocusUpdate_MoveRight) {
+ VerifyCaretBrowsingPositionAndFocusUpdate(
+ "<div>a|<a href=\"foo\">b</a></div>", "body",
+ MoveCommands::ExecuteMoveRight, "<div>a<a href=\"foo\">b|</a></div>",
+ "a");
+}
+
+TEST_F(MoveCommandsTest,
+ CaretBrowsingPositionAndFocusUpdate_MoveToBeginningOfDocument) {
+ VerifyCaretBrowsingPositionAndFocusUpdate(
+ "<div><a href=\"foo\">a</a>|b</div>", "body",
+ MoveCommands::ExecuteMoveToBeginningOfDocument,
+ "<div><a href=\"foo\">|a</a>b</div>", "a");
+}
+
+TEST_F(MoveCommandsTest,
+ CaretBrowsingPositionAndFocusUpdate_MoveToBeginningOfLine) {
+ VerifyCaretBrowsingPositionAndFocusUpdate(
+ "<div><a href=\"foo\">a</a>|b</div>", "body",
+ MoveCommands::ExecuteMoveToBeginningOfLine,
+ "<div><a href=\"foo\">|a</a>b</div>", "a");
+}
+
+TEST_F(MoveCommandsTest,
+ CaretBrowsingPositionAndFocusUpdate_MoveToBeginningOfParagraph) {
+ VerifyCaretBrowsingPositionAndFocusUpdate(
+ "<div><a href=\"foo\">a</a>|b</div>", "body",
+ MoveCommands::ExecuteMoveToBeginningOfParagraph,
+ "<div><a href=\"foo\">|a</a>b</div>", "a");
+}
+
+TEST_F(MoveCommandsTest,
+ CaretBrowsingPositionAndFocusUpdate_MoveToBeginningOfSentence) {
+ VerifyCaretBrowsingPositionAndFocusUpdate(
+ "<div><a href=\"foo\">a</a>|b</div>", "body",
+ MoveCommands::ExecuteMoveToBeginningOfSentence,
+ "<div><a href=\"foo\">|a</a>b</div>", "a");
+}
+
+TEST_F(MoveCommandsTest,
+ CaretBrowsingPositionAndFocusUpdate_MoveToEndOfDocument) {
+ VerifyCaretBrowsingPositionAndFocusUpdate(
+ "<div>a|<a href=\"foo\">b</a></div>", "body",
+ MoveCommands::ExecuteMoveToEndOfDocument,
+ "<div>a<a href=\"foo\">b|</a></div>", "a");
+}
+
+TEST_F(MoveCommandsTest, CaretBrowsingPositionAndFocusUpdate_MoveToEndOfLine) {
+ VerifyCaretBrowsingPositionAndFocusUpdate(
+ "<div>a|<a href=\"foo\">b</a></div>", "body",
+ MoveCommands::ExecuteMoveToEndOfLine,
+ "<div>a<a href=\"foo\">b|</a></div>", "a");
+}
+
+TEST_F(MoveCommandsTest,
+ CaretBrowsingPositionAndFocusUpdate_MoveToEndOfParagraph) {
+ VerifyCaretBrowsingPositionAndFocusUpdate(
+ "<div>a|<a href=\"foo\">b</a></div>", "body",
+ MoveCommands::ExecuteMoveToEndOfParagraph,
+ "<div>a<a href=\"foo\">b|</a></div>", "a");
+}
+
+TEST_F(MoveCommandsTest,
+ CaretBrowsingPositionAndFocusUpdate_MoveToEndOfSentence) {
+ VerifyCaretBrowsingPositionAndFocusUpdate(
+ "<div>a|<a href=\"foo\">b</a></div>", "body",
+ MoveCommands::ExecuteMoveToEndOfSentence,
+ "<div>a<a href=\"foo\">b|</a></div>", "a");
+}
+
+TEST_F(MoveCommandsTest,
+ CaretBrowsingPositionAndFocusUpdate_MoveToLeftEndOfLine) {
+ VerifyCaretBrowsingPositionAndFocusUpdate(
+ "<div><a href=\"foo\">a</a>|b</div>", "body",
+ MoveCommands::ExecuteMoveToLeftEndOfLine,
+ "<div><a href=\"foo\">|a</a>b</div>", "a");
+}
+
+TEST_F(MoveCommandsTest,
+ CaretBrowsingPositionAndFocusUpdate_MoveToRightEndOfLine) {
+ VerifyCaretBrowsingPositionAndFocusUpdate(
+ "<div>a|<a href=\"foo\">b</a></div>", "body",
+ MoveCommands::ExecuteMoveToRightEndOfLine,
+ "<div>a<a href=\"foo\">b|</a></div>", "a");
+}
+
+TEST_F(MoveCommandsTest, CaretBrowsingPositionAndFocusUpdate_MoveUp) {
+ VerifyCaretBrowsingPositionAndFocusUpdate(
+ "<div><a href=\"foo\">ab</a></div><div>c|d</div>", "body",
+ MoveCommands::ExecuteMoveUp,
+#if !defined(OS_MACOSX)
+ "<div><a href=\"foo\">a|b</a></div><div>cd</div>", "a");
+#else // defined(OS_MACOSX)
+ // MoveUp navigates visually, placing caret at different position for
+ // macOS.
+ "<div><a href=\"foo\">|ab</a></div><div>cd</div>", "a");
+#endif // !defined(OS_MACOSX)
+}
+
+TEST_F(MoveCommandsTest, CaretBrowsingPositionAndFocusUpdate_MoveWordBackward) {
+ VerifyCaretBrowsingPositionAndFocusUpdate(
+ "<div><a href=\"foo\">a</a>|b</div>", "body",
+ MoveCommands::ExecuteMoveWordBackward,
+ "<div><a href=\"foo\">|a</a>b</div>", "a");
+}
+
+TEST_F(MoveCommandsTest, CaretBrowsingPositionAndFocusUpdate_MoveWordForward) {
+ VerifyCaretBrowsingPositionAndFocusUpdate(
+ "<div>a|<a href=\"foo\">b</a></div>", "body",
+ MoveCommands::ExecuteMoveWordForward,
+ "<div>a<a href=\"foo\">b|</a></div>", "a");
+}
+
+TEST_F(MoveCommandsTest, CaretBrowsingPositionAndFocusUpdate_MoveWordLeft) {
+ VerifyCaretBrowsingPositionAndFocusUpdate(
+ "<div><a href=\"foo\">a</a>|b</div>", "body",
+ MoveCommands::ExecuteMoveWordLeft, "<div><a href=\"foo\">|a</a>b</div>",
+ "a");
+}
+
+TEST_F(MoveCommandsTest, CaretBrowsingPositionAndFocusUpdate_MoveWordRight) {
+ VerifyCaretBrowsingPositionAndFocusUpdate(
+ "<div>a|<a href=\"foo\"> b</a></div>", "body",
+ MoveCommands::ExecuteMoveWordRight, "<div>a<a href=\"foo\"> b|</a></div>",
+ "a");
+}
+
+// This test verifies that focus returns to the body after browsing out of a
+// focusable element.
+TEST_F(MoveCommandsTest,
+ CaretBrowsingPositionAndFocusUpdate_ExitingFocusableElement) {
+ VerifyCaretBrowsingPositionAndFocusUpdate(
+ "<div><a href=\"foo\">a|</a>b</div>", "a", MoveCommands::ExecuteMoveRight,
+ "<div><a href=\"foo\">a</a>b|</div>", "body");
+}
+
+// This test verifies that caret browsing into a focusable element does not
+// move focus if inside an editable region.
+TEST_F(MoveCommandsTest, CaretBrowsingPositionAndFocusUpdate_EditableElements) {
+ VerifyCaretBrowsingPositionAndFocusUpdate(
+ "<div contenteditable>a|<a href=\"foo\">b</a>c</div>", "div",
+ MoveCommands::ExecuteMoveRight,
+ "<div contenteditable>a<a href=\"foo\">b|</a>c</div>", "div");
+}
+
+// This test verifies that another focusable element (the button element) can be
+// moved into while caret browsing and gains focus, just like an anchor
+// element.
+TEST_F(MoveCommandsTest,
+ CaretBrowsingPositionAndFocusUpdate_MoveRightButtonElement) {
+ VerifyCaretBrowsingPositionAndFocusUpdate(
+ "<div>Some text to the left of the button|<button>Click "
+ "Me!</button></div>",
+ "body", MoveCommands::ExecuteMoveRight,
+ "<div>Some text to the left of the button<button>C|lick "
+ "Me!</button></div>",
+ "button");
+}
+
+// This test verifies that an element with tabindex set can be moved
+// into while caret browsing and gains focus, just like an anchor element.
+TEST_F(MoveCommandsTest,
+ CaretBrowsingPositionAndFocusUpdate_MoveRightElementWithTabIndex) {
+ VerifyCaretBrowsingPositionAndFocusUpdate(
+ "<div>Some text to the left of the span|<span tabindex=\"0\">Span with "
+ "tabindex set</span></div>",
+ "body", MoveCommands::ExecuteMoveRight,
+ "<div>Some text to the left of the span<span tabindex=\"0\">S|pan with "
+ "tabindex set</span></div>",
+ "span");
+}
+
+// This test verifies that an input element will be skipped when caret browsing
+// and not gain focus.
+TEST_F(MoveCommandsTest,
+ CaretBrowsingPositionAndFocusUpdate_MoveRightInputElement) {
+ VerifyCaretBrowsingPositionAndFocusUpdate(
+ "<div>Some text to the left of the input element|<input type=\"text\" "
+ "value=\"This is some initial text\">Some text to the right of the input "
+ "element</div>",
+ "body", MoveCommands::ExecuteMoveRight,
+ "<div>Some text to the left of the input element<input type=\"text\" "
+ "value=\"This is some initial text\">|Some text to the right of the "
+ "input element</div>",
+ "body");
+}
+
+// This test verifies that a contentEditable element will be skipped when caret
+// browsing and not gain focus.
+TEST_F(MoveCommandsTest,
+ CaretBrowsingPositionAndFocusUpdate_MoveRightContentEditableElement) {
+ VerifyCaretBrowsingPositionAndFocusUpdate(
+ "<div>Some text to the left of the contentEditable element|<span "
+ "contentEditable=\"true\">I am content editable</span>Some text to the "
+ "right of the contentEditable element</div>",
+ "body", MoveCommands::ExecuteMoveRight,
+ "<div>Some text to the left of the contentEditable element<span "
+ "contenteditable=\"true\">I am content editable</span>|Some text to the "
+ "right of the contentEditable element</div>",
+ "body");
+}
+
+// This test verifies that a textarea element will be skipped when caret
+// browsing and not gain focus.
+TEST_F(MoveCommandsTest,
+ CaretBrowsingPositionAndFocusUpdate_MoveRightTextAreaElement) {
+ VerifyCaretBrowsingPositionAndFocusUpdate(
+ "<div>Some text to the left of the textarea element|<textarea>I am in a "
+ "textarea</textarea>Some text to the "
+ "right of the textarea element</div>",
+ "body", MoveCommands::ExecuteMoveRight,
+ "<div>Some text to the left of the textarea element<textarea>I am in a "
+ "textarea</textarea>|Some text to the "
+ "right of the textarea element</div>",
+ "body");
+}
+
+// This test verifies that while caret browsing if you try to move the caret
+// when it is not in focus then it jumps to the active element before moving.
+TEST_F(MoveCommandsTest, CaretBrowsingSelectionUpdate) {
+ Selection().SetSelection(
+ SetSelectionTextToBody("<div>|a<a href=\"foo\">b</a></div>"),
+ SetSelectionOptions());
+ GetDocument().SetFocusedElement(
+ GetDocument().QuerySelector("a"),
+ FocusParams(SelectionBehaviorOnFocus::kNone, kWebFocusTypeNone, nullptr));
+ GetDocument().GetFrame()->GetSettings()->SetCaretBrowsingEnabled(true);
+ MoveCommands::ExecuteMoveRight(*GetDocument().GetFrame(), nullptr,
+ EditorCommandSource::kMenuOrKeyBinding,
+ String());
+ EXPECT_EQ("<div>a<a href=\"foo\">b|</a></div>", GetSelectionTextFromBody());
+}
+
+} // namespace blink
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 16890313a8f..3e9be2f1704 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
@@ -52,7 +52,6 @@
#include "third_party/blink/renderer/core/editing/visible_units.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"
#include "third_party/blink/renderer/core/html/forms/html_input_element.h"
#include "third_party/blink/renderer/core/html/forms/html_select_element.h"
#include "third_party/blink/renderer/core/html/html_br_element.h"
@@ -67,6 +66,7 @@
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
@@ -556,7 +556,7 @@ void ReplaceSelectionCommand::RemoveRedundantStylesAndKeepStyleSpanInline(
if (!node->IsStyledElement())
continue;
- Element* element = ToElement(node);
+ auto* element = To<Element>(node);
const CSSPropertyValueSet* inline_style = element->InlineStyle();
EditingStyle* new_inline_style =
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/split_text_node_containing_element_command.cc b/chromium/third_party/blink/renderer/core/editing/commands/split_text_node_containing_element_command.cc
index 4fb767ba315..77a2d6368ac 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/split_text_node_containing_element_command.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/split_text_node_containing_element_command.cc
@@ -55,10 +55,10 @@ void SplitTextNodeContainingElementCommand::DoApply(EditingState*) {
LayoutObject* parent_layout_object = parent->GetLayoutObject();
if (!parent_layout_object || !parent_layout_object->IsInline()) {
WrapContentsInDummySpan(parent);
- Node* first_child = parent->firstChild();
- if (!first_child || !first_child->IsElementNode())
+ auto* first_child_element = DynamicTo<Element>(parent->firstChild());
+ if (!first_child_element)
return;
- parent = ToElement(first_child);
+ parent = first_child_element;
}
SplitElement(parent, text_.Get());
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/style_commands.cc b/chromium/third_party/blink/renderer/core/editing/commands/style_commands.cc
index 46a362991dd..00eef3d1f00 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/style_commands.cc
+++ b/chromium/third_party/blink/renderer/core/editing/commands/style_commands.cc
@@ -85,7 +85,7 @@ bool StyleCommands::ApplyCommandToFrame(LocalFrame& frame,
EditorCommandSource source,
InputEvent::InputType input_type,
CSSPropertyValueSet* style) {
- // TODO(editnig-dev): We don't call shouldApplyStyle when the source is DOM;
+ // TODO(editing-dev): We don't call shouldApplyStyle when the source is DOM;
// is there a good reason for that?
switch (source) {
case EditorCommandSource::kMenuOrKeyBinding:
@@ -315,7 +315,7 @@ bool StyleCommands::ExecuteToggleStyleInList(LocalFrame& frame,
const String new_style =
ComputeToggleStyleInList(*selection_style, property_id, value);
- // TODO(editnig-dev): We shouldn't be having to convert new style into text.
+ // TODO(editing-dev): We shouldn't be having to convert new style into text.
// We should have setPropertyCSSValue.
auto* const new_mutable_style =
MakeGarbageCollected<MutableCSSPropertyValueSet>(kHTMLQuirksMode);
@@ -444,7 +444,7 @@ WritingDirection StyleCommands::TextDirectionForSelection(
const CSSComputedStyleDeclaration& style =
*MakeGarbageCollected<CSSComputedStyleDeclaration>(&node);
const CSSValue* unicode_bidi =
- style.GetPropertyCSSValue(GetCSSPropertyUnicodeBidi());
+ style.GetPropertyCSSValue(CSSPropertyID::kUnicodeBidi);
auto* unicode_bidi_identifier_value =
DynamicTo<CSSIdentifierValue>(unicode_bidi);
if (!unicode_bidi_identifier_value)
@@ -478,11 +478,11 @@ WritingDirection StyleCommands::TextDirectionForSelection(
if (!runner.IsStyledElement())
continue;
- Element* element = &ToElement(runner);
+ auto* element = To<Element>(&runner);
const CSSComputedStyleDeclaration& style =
*MakeGarbageCollected<CSSComputedStyleDeclaration>(element);
const CSSValue* unicode_bidi =
- style.GetPropertyCSSValue(GetCSSPropertyUnicodeBidi());
+ style.GetPropertyCSSValue(CSSPropertyID::kUnicodeBidi);
auto* unicode_bidi_identifier_value =
DynamicTo<CSSIdentifierValue>(unicode_bidi);
if (!unicode_bidi_identifier_value)
@@ -499,7 +499,7 @@ WritingDirection StyleCommands::TextDirectionForSelection(
DCHECK(EditingStyleUtilities::IsEmbedOrIsolate(unicode_bidi_value))
<< static_cast<int>(unicode_bidi_value);
const CSSValue* direction =
- style.GetPropertyCSSValue(GetCSSPropertyDirection());
+ style.GetPropertyCSSValue(CSSPropertyID::kDirection);
auto* direction_identifier_value = DynamicTo<CSSIdentifierValue>(direction);
if (!direction_identifier_value)
continue;
@@ -534,7 +534,7 @@ EditingTriState StyleCommands::StateTextWritingDirection(
WritingDirection selection_direction = TextDirectionForSelection(
frame.Selection().ComputeVisibleSelectionInDOMTreeDeprecated(),
frame.GetEditor().TypingStyle(), has_nested_or_multiple_embeddings);
- // TODO(editnig-dev): We should be returning MixedTriState when
+ // TODO(editing-dev): We should be returning MixedTriState when
// selectionDirection == direction && hasNestedOrMultipleEmbeddings
return (selection_direction == direction &&
!has_nested_or_multiple_embeddings)
@@ -584,7 +584,7 @@ String StyleCommands::SelectionStartCSSPropertyValue(
String StyleCommands::ValueStyle(LocalFrame& frame, CSSPropertyID property_id) {
frame.GetDocument()->UpdateStyleAndLayout();
- // TODO(editnig-dev): Rather than retrieving the style at the start of the
+ // TODO(editing-dev): Rather than retrieving the style at the start of the
// current selection, we should retrieve the style present throughout the
// selection for non-Mac platforms.
return SelectionStartCSSPropertyValue(frame, property_id);
diff --git a/chromium/third_party/blink/renderer/core/editing/commands/style_commands.h b/chromium/third_party/blink/renderer/core/editing/commands/style_commands.h
index cece1e2a9c7..0400ca28394 100644
--- a/chromium/third_party/blink/renderer/core/editing/commands/style_commands.h
+++ b/chromium/third_party/blink/renderer/core/editing/commands/style_commands.h
@@ -33,7 +33,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_EDITING_COMMANDS_STYLE_COMMANDS_H_
#include "third_party/blink/renderer/core/events/input_event.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
namespace blink {
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 c47e61e631a..00b108c3512 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,10 +22,8 @@ namespace blink {
class ComputeLayerSelectionTest : public EditingTestBase {
public:
void SetUp() override {
+ EnableCompositing();
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);
LoadAhem();
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 098c788bdbe..862ff5be65b 100644
--- a/chromium/third_party/blink/renderer/core/editing/dom_selection.cc
+++ b/chromium/third_party/blink/renderer/core/editing/dom_selection.cc
@@ -44,9 +44,9 @@
#include "third_party/blink/renderer/core/editing/visible_selection.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/use_counter.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/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/editing/editing_behavior.h b/chromium/third_party/blink/renderer/core/editing/editing_behavior.h
index 90f13baf5da..719119aef3a 100644
--- a/chromium/third_party/blink/renderer/core/editing/editing_behavior.h
+++ b/chromium/third_party/blink/renderer/core/editing/editing_behavior.h
@@ -23,7 +23,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/editing/editing_behavior_types.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
class KeyboardEvent;
diff --git a/chromium/third_party/blink/renderer/core/editing/editing_strategy.h b/chromium/third_party/blink/renderer/core/editing/editing_strategy.h
index d44796248ec..4b4454df103 100644
--- a/chromium/third_party/blink/renderer/core/editing/editing_strategy.h
+++ b/chromium/third_party/blink/renderer/core/editing/editing_strategy.h
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/dom/flat_tree_traversal.h"
#include "third_party/blink/renderer/core/dom/node_traversal.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
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 d9c7d725653..f8d9d45259b 100644
--- a/chromium/third_party/blink/renderer/core/editing/editing_style.cc
+++ b/chromium/third_party/blink/renderer/core/editing/editing_style.cc
@@ -30,6 +30,7 @@
#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_numeric_literal_value.h"
#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_value_set.h"
@@ -100,7 +101,7 @@ enum EditingPropertiesType {
static const Vector<const CSSProperty*>& AllEditingProperties() {
DEFINE_STATIC_LOCAL(Vector<const CSSProperty*>, properties, ());
if (properties.IsEmpty()) {
- CSSProperty::FilterEnabledCSSPropertiesIntoVector(
+ CSSProperty::FilterWebExposedCSSPropertiesIntoVector(
kStaticEditingProperties, base::size(kStaticEditingProperties),
properties);
for (wtf_size_t index = 0; index < properties.size(); index++) {
@@ -116,7 +117,7 @@ static const Vector<const CSSProperty*>& AllEditingProperties() {
static const Vector<const CSSProperty*>& InheritableEditingProperties() {
DEFINE_STATIC_LOCAL(Vector<const CSSProperty*>, properties, ());
if (properties.IsEmpty()) {
- CSSProperty::FilterEnabledCSSPropertiesIntoVector(
+ CSSProperty::FilterWebExposedCSSPropertiesIntoVector(
kStaticEditingProperties, base::size(kStaticEditingProperties),
properties);
for (wtf_size_t index = 0; index < properties.size();) {
@@ -397,8 +398,6 @@ const CSSValue* HTMLFontSizeEquivalent::AttributeValueAsCSSValue(
return CSSIdentifierValue::Create(size);
}
-float EditingStyle::no_font_delta_ = 0.0f;
-
EditingStyle::EditingStyle(ContainerNode* node,
PropertiesToInclude properties_to_include) {
Init(node, properties_to_include);
@@ -517,7 +516,7 @@ void EditingStyle::Init(Node* node, PropertiesToInclude properties_to_include) {
/* important */ false, node->GetDocument().GetSecureContextMode());
}
if (const CSSValue* value = computed_style_at_position->GetPropertyCSSValue(
- GetCSSPropertyWebkitTextDecorationsInEffect())) {
+ CSSPropertyID::kWebkitTextDecorationsInEffect)) {
mutable_style_->SetProperty(
CSSPropertyID::kTextDecoration, value->CssText(),
/* important */ false, node->GetDocument().GetSecureContextMode());
@@ -537,8 +536,8 @@ void EditingStyle::Init(Node* node, PropertiesToInclude properties_to_include) {
// ReplaceSelectionCommandTest_TextAutosizingDoesntInflateText gets here.
mutable_style_->SetProperty(
CSSPropertyID::kFontSize,
- CSSPrimitiveValue::Create(computed_style->SpecifiedFontSize(),
- CSSPrimitiveValue::UnitType::kPixels)
+ CSSNumericLiteralValue::Create(computed_style->SpecifiedFontSize(),
+ CSSPrimitiveValue::UnitType::kPixels)
->CssText(),
/* important */ false, node->GetDocument().GetSecureContextMode());
}
@@ -622,7 +621,7 @@ void EditingStyle::ExtractFontSizeDelta() {
bool EditingStyle::IsEmpty() const {
return (!mutable_style_ || mutable_style_->IsEmpty()) &&
- font_size_delta_ == no_font_delta_;
+ font_size_delta_ == kNoFontDelta;
}
bool EditingStyle::GetTextDirection(WritingDirection& writing_direction) const {
@@ -674,7 +673,7 @@ void EditingStyle::OverrideWithStyle(const CSSPropertyValueSet* style) {
void EditingStyle::Clear() {
mutable_style_.Clear();
is_monospace_font_ = false;
- font_size_delta_ = no_font_delta_;
+ font_size_delta_ = kNoFontDelta;
}
EditingStyle* EditingStyle::Copy() const {
@@ -703,10 +702,10 @@ static const CSSPropertyID kStaticBlockProperties[] = {
CSSPropertyID::kTextAlignLast, CSSPropertyID::kTextIndent,
CSSPropertyID::kTextJustify, CSSPropertyID::kWidows};
-static Vector<const CSSProperty*>& BlockPropertiesVector() {
+static const Vector<const CSSProperty*>& BlockPropertiesVector() {
DEFINE_STATIC_LOCAL(Vector<const CSSProperty*>, properties, ());
if (properties.IsEmpty()) {
- CSSProperty::FilterEnabledCSSPropertiesIntoVector(
+ CSSProperty::FilterWebExposedCSSPropertiesIntoVector(
kStaticBlockProperties, base::size(kStaticBlockProperties), properties);
}
return properties;
@@ -877,9 +876,10 @@ EditingTriState EditingStyle::TriStateOfStyle(
To<CSSIdentifierValue>(mutable_style_->GetPropertyCSSValue(
CSSPropertyID::kVerticalAlign));
if (EditingStyleUtilities::HasAncestorVerticalAlignStyle(
- node, vertical_align->GetValueID()))
- node.MutableComputedStyle()->SetVerticalAlign(
+ node, vertical_align->GetValueID())) {
+ node.MutableComputedStyleForEditingDeprecated()->SetVerticalAlign(
vertical_align->ConvertTo<EVerticalAlign>());
+ }
}
// Pass EditingStyle::DoNotIgnoreTextOnlyProperties without checking if
@@ -1452,7 +1452,8 @@ void EditingStyle::MergeStyleFromRulesForSerialization(Element* element) {
continue;
if (primitive_value->IsPercentage()) {
if (const CSSValue* computed_property_value =
- computed_style_for_element->GetPropertyCSSValue(css_property)) {
+ computed_style_for_element->GetPropertyCSSValue(
+ property.Name())) {
from_computed_style->AddRespectingCascade(
CSSPropertyValue(css_property, *computed_property_value));
}
@@ -1876,25 +1877,32 @@ int LegacyFontSizeFromCSSValue(Document* document,
bool is_monospace_font,
LegacyFontSizeMode mode) {
if (const auto* primitive_value = DynamicTo<CSSPrimitiveValue>(value)) {
- CSSPrimitiveValue::LengthUnitType length_type;
- if (CSSPrimitiveValue::UnitTypeToLengthUnitType(
- primitive_value->TypeWithCalcResolved(), length_type) &&
- length_type == CSSPrimitiveValue::kUnitTypePixels) {
- double conversion =
- CSSPrimitiveValue::ConversionToCanonicalUnitsScaleFactor(
- primitive_value->TypeWithCalcResolved());
- int pixel_font_size =
- clampTo<int>(primitive_value->GetDoubleValue() * conversion);
- int legacy_font_size = FontSizeFunctions::LegacyFontSize(
- document, pixel_font_size, is_monospace_font);
- // Use legacy font size only if pixel value matches exactly to that of
- // legacy font size.
- if (mode == kAlwaysUseLegacyFontSize ||
- FontSizeFunctions::FontSizeForKeyword(
- document, legacy_font_size, is_monospace_font) == pixel_font_size)
- return legacy_font_size;
-
- return 0;
+ if (primitive_value->IsLength()) {
+ // TODO(crbug.com/979895): This doesn't seem to be handle math functions
+ // correctly. This is the result of a refactoring, and may have revealed
+ // an existing bug. Fix it if necessary.
+ CSSPrimitiveValue::UnitType length_unit =
+ primitive_value->IsNumericLiteralValue()
+ ? To<CSSNumericLiteralValue>(primitive_value)->GetType()
+ : CSSPrimitiveValue::UnitType::kPixels;
+ if (!CSSPrimitiveValue::IsRelativeUnit(length_unit)) {
+ double conversion =
+ CSSPrimitiveValue::ConversionToCanonicalUnitsScaleFactor(
+ length_unit);
+ int pixel_font_size =
+ clampTo<int>(primitive_value->GetDoubleValue() * conversion);
+ int legacy_font_size = FontSizeFunctions::LegacyFontSize(
+ document, pixel_font_size, is_monospace_font);
+ // Use legacy font size only if pixel value matches exactly to that of
+ // legacy font size.
+ if (mode == kAlwaysUseLegacyFontSize ||
+ FontSizeFunctions::FontSizeForKeyword(document, legacy_font_size,
+ is_monospace_font) ==
+ pixel_font_size)
+ return legacy_font_size;
+
+ return 0;
+ }
}
}
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 fc7be19b48c..9700794ebce 100644
--- a/chromium/third_party/blink/renderer/core/editing/editing_style.h
+++ b/chromium/third_party/blink/renderer/core/editing/editing_style.h
@@ -74,7 +74,7 @@ class CORE_EXPORT EditingStyle final : public GarbageCollected<EditingStyle> {
kExtractMatchingStyle,
kDoNotExtractMatchingStyle
};
- static float no_font_delta_;
+ static constexpr float kNoFontDelta = 0.0f;
EditingStyle() = default;
EditingStyle(ContainerNode*,
@@ -147,7 +147,7 @@ class CORE_EXPORT EditingStyle final : public GarbageCollected<EditingStyle> {
int LegacyFontSize(Document*) const;
float FontSizeDelta() const { return font_size_delta_; }
- bool HasFontSizeDelta() const { return font_size_delta_ != no_font_delta_; }
+ bool HasFontSizeDelta() const { return font_size_delta_ != kNoFontDelta; }
void SetProperty(CSSPropertyID,
const String& value,
@@ -177,7 +177,7 @@ class CORE_EXPORT EditingStyle final : public GarbageCollected<EditingStyle> {
Member<MutableCSSPropertyValueSet> mutable_style_;
bool is_monospace_font_ = false;
- float font_size_delta_ = no_font_delta_;
+ float font_size_delta_ = kNoFontDelta;
bool is_vertical_align_ = false;
friend class HTMLElementEquivalent;
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 d18447573c3..b25aba94c04 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
@@ -118,7 +118,7 @@ EditingStyle* EditingStyleUtilities::CreateWrappingStyleForSerialization(
break;
if (node.IsStyledElement() && !IsMailHTMLBlockquoteElement(&node)) {
wrapping_style->MergeInlineAndImplicitStyleOfElement(
- ToElement(&node), EditingStyle::kDoNotOverrideValues,
+ To<Element>(&node), EditingStyle::kDoNotOverrideValues,
EditingStyle::kEditingPropertiesInEffect);
}
}
@@ -232,7 +232,7 @@ const CSSValue* EditingStyleUtilities::BackgroundColorValueInEffect(
MakeGarbageCollected<CSSComputedStyleDeclaration>(ancestor);
if (!HasTransparentBackgroundColor(ancestor_style)) {
return ancestor_style->GetPropertyCSSValue(
- GetCSSPropertyBackgroundColor());
+ CSSPropertyID::kBackgroundColor);
}
}
return nullptr;
diff --git a/chromium/third_party/blink/renderer/core/editing/editing_style_utilities.h b/chromium/third_party/blink/renderer/core/editing/editing_style_utilities.h
index c4e4d23119d..efaf957f088 100644
--- a/chromium/third_party/blink/renderer/core/editing/editing_style_utilities.h
+++ b/chromium/third_party/blink/renderer/core/editing/editing_style_utilities.h
@@ -36,7 +36,7 @@
#include "third_party/blink/renderer/core/css_value_keywords.h"
#include "third_party/blink/renderer/core/dom/container_node.h"
#include "third_party/blink/renderer/core/editing/forward.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 e3cb2446601..cf155d1aae5 100644
--- a/chromium/third_party/blink/renderer/core/editing/editing_utilities.cc
+++ b/chromium/third_party/blink/renderer/core/editing/editing_utilities.cc
@@ -53,7 +53,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/core/frame/local_frame_view.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/canvas/html_canvas_element.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"
@@ -75,6 +74,7 @@
#include "third_party/blink/renderer/core/svg/svg_image_element.h"
#include "third_party/blink/renderer/platform/graphics/static_bitmap_image.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.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"
@@ -412,7 +412,7 @@ bool IsEditableElement(const Node& node) {
return true;
}
- if (auto* element = ToElementOrNull(const_cast<Node*>(&node)))
+ if (auto* element = DynamicTo<Element>(&node))
return EqualIgnoringASCIICase(element->getAttribute(kRoleAttr), "textbox");
return false;
@@ -426,14 +426,14 @@ bool IsRootEditableElement(const Node& node) {
}
Element* RootEditableElement(const Node& node) {
- const Node* result = nullptr;
+ const Element* result = nullptr;
for (const Node* n = &node; n && HasEditableStyle(*n); n = n->parentNode()) {
- if (n->IsElementNode())
- result = n;
+ if (auto* element = DynamicTo<Element>(n))
+ result = element;
if (node.GetDocument().body() == n)
break;
}
- return ToElement(const_cast<Node*>(result));
+ return const_cast<Element*>(result);
}
ContainerNode* HighestEditableRoot(const Position& position) {
@@ -967,9 +967,7 @@ template <typename Strategy>
Element* EnclosingBlockAlgorithm(const PositionTemplate<Strategy>& position,
EditingBoundaryCrossingRule rule) {
Node* enclosing_node = EnclosingNodeOfType(position, IsEnclosingBlock, rule);
- return enclosing_node && enclosing_node->IsElementNode()
- ? ToElement(enclosing_node)
- : nullptr;
+ return DynamicTo<Element>(enclosing_node);
}
Element* EnclosingBlock(const Position& position,
@@ -984,11 +982,11 @@ Element* EnclosingBlock(const PositionInFlatTree& position,
Element* EnclosingBlockFlowElement(const Node& node) {
if (IsBlockFlowElement(node))
- return const_cast<Element*>(&ToElement(node));
+ return const_cast<Element*>(To<Element>(&node));
for (Node& runner : NodeTraversal::AncestorsOf(node)) {
if (IsBlockFlowElement(runner) || IsHTMLBodyElement(runner))
- return ToElement(&runner);
+ return To<Element>(&runner);
}
return nullptr;
}
@@ -1065,7 +1063,7 @@ static Element* TableElementJustBeforeAlgorithm(
MostBackwardCaretPosition(visible_position.DeepEquivalent()));
if (IsDisplayInsideTable(upstream.AnchorNode()) &&
upstream.AtLastEditingPositionForNode())
- return ToElement(upstream.AnchorNode());
+ return To<Element>(upstream.AnchorNode());
return nullptr;
}
@@ -1085,7 +1083,7 @@ Element* TableElementJustAfter(const VisiblePosition& visible_position) {
MostForwardCaretPosition(visible_position.DeepEquivalent()));
if (IsDisplayInsideTable(downstream.AnchorNode()) &&
downstream.AtFirstEditingPositionForNode())
- return ToElement(downstream.AnchorNode());
+ return To<Element>(downstream.AnchorNode());
return nullptr;
}
@@ -1132,10 +1130,14 @@ bool IsPresentationalHTMLElement(const Node* node) {
Element* AssociatedElementOf(const Position& position) {
Node* node = position.AnchorNode();
- if (!node || node->IsElementNode())
- return ToElement(node);
+ if (!node)
+ return nullptr;
+
+ if (auto* element = DynamicTo<Element>(node))
+ return element;
+
ContainerNode* parent = NodeTraversal::Parent(*node);
- return parent && parent->IsElementNode() ? ToElement(parent) : nullptr;
+ return DynamicTo<Element>(parent);
}
Element* EnclosingElementWithTag(const Position& p,
@@ -1145,9 +1147,9 @@ Element* EnclosingElementWithTag(const Position& p,
ContainerNode* root = HighestEditableRoot(p);
for (Node& runner : NodeTraversal::InclusiveAncestorsOf(*p.AnchorNode())) {
- if (!runner.IsElementNode())
+ auto* ancestor = DynamicTo<Element>(runner);
+ if (!ancestor)
continue;
- Element* ancestor = ToElement(&runner);
if (root && !HasEditableStyle(*ancestor))
continue;
if (ancestor->HasTagName(tag_name))
@@ -1309,14 +1311,13 @@ HTMLSpanElement* CreateTabSpanElement(Document& document) {
PositionWithAffinity PositionRespectingEditingBoundary(
const Position& position,
- const LayoutPoint& local_point,
+ const PhysicalOffset& local_point,
Node* target_node) {
const LayoutObject* target_object = target_node->GetLayoutObject();
if (!target_object)
return PositionWithAffinity();
- // Note that local_point is in flipped blocks direction.
- LayoutPoint selection_end_point = local_point;
+ PhysicalOffset selection_end_point = local_point;
Element* editable_element = RootEditableElementOf(position);
if (editable_element && !editable_element->contains(target_node)) {
@@ -1324,13 +1325,11 @@ PositionWithAffinity PositionRespectingEditingBoundary(
if (!editable_object)
return PositionWithAffinity();
- // TODO(yosin): This kIgnoreTransforms correct here?
+ // TODO(yosin): Is this kIgnoreTransforms correct here?
PhysicalOffset absolute_point = target_object->LocalToAbsolutePoint(
- target_object->FlipForWritingMode(selection_end_point),
- kIgnoreTransforms);
- selection_end_point = editable_object->FlipForWritingMode(
- editable_object->AbsoluteToLocalPoint(absolute_point,
- kIgnoreTransforms));
+ selection_end_point, kIgnoreTransforms);
+ selection_end_point = editable_object->AbsoluteToLocalPoint(
+ absolute_point, kIgnoreTransforms);
target_object = editable_object;
}
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 2b9988196cb..e2e9992852f 100644
--- a/chromium/third_party/blink/renderer/core/editing/editing_utilities.h
+++ b/chromium/third_party/blink/renderer/core/editing/editing_utilities.h
@@ -256,7 +256,7 @@ bool IsRichlyEditablePosition(const Position&);
PositionWithAffinity PositionRespectingEditingBoundary(
const Position&,
- const LayoutPoint& local_point,
+ const PhysicalOffset& local_point,
Node* target_node);
Position ComputePositionForNodeRemoval(const Position&, const Node&);
diff --git a/chromium/third_party/blink/renderer/core/editing/editor.cc b/chromium/third_party/blink/renderer/core/editing/editor.cc
index a0f26786c74..f6ed360b362 100644
--- a/chromium/third_party/blink/renderer/core/editing/editor.cc
+++ b/chromium/third_party/blink/renderer/core/editing/editor.cc
@@ -72,7 +72,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/frame/settings.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/forms/html_input_element.h"
#include "third_party/blink/renderer/core/html/forms/html_text_area_element.h"
#include "third_party/blink/renderer/core/html/html_image_element.h"
@@ -88,6 +87,7 @@
#include "third_party/blink/renderer/core/scroll/scroll_alignment.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/wtf/text/character_names.h"
@@ -677,7 +677,7 @@ void Editor::AddToKillRing(const EphemeralRange& range) {
EphemeralRange Editor::RangeForPoint(const IntPoint& frame_point) const {
const PositionWithAffinity position_with_affinity =
- GetFrame().PositionForPoint(frame_point);
+ GetFrame().PositionForPoint(PhysicalOffset(frame_point));
if (position_with_affinity.IsNull())
return EphemeralRange();
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 9cd6bc70781..5f5d2be79cd 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
@@ -26,7 +26,7 @@
#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/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.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"
@@ -133,7 +133,8 @@ String ElementInnerTextCollector::RunOn(const Element& element) {
// static
bool ElementInnerTextCollector::HasDisplayContentsStyle(const Node& node) {
- return node.IsElementNode() && ToElement(node).HasDisplayContentsStyle();
+ auto* element = DynamicTo<Element>(node);
+ return element && element->HasDisplayContentsStyle();
}
// An element is *being rendered* if it has any associated CSS layout boxes,
@@ -262,8 +263,8 @@ void ElementInnerTextCollector::ProcessLayoutText(const LayoutText& layout_text,
return;
}
- const NGMappingUnitRange range = mapping->GetMappingUnitsForNode(text_node);
- for (const NGOffsetMappingUnit& unit : range) {
+ for (const NGOffsetMappingUnit& unit :
+ mapping->GetMappingUnitsForNode(text_node)) {
result_.EmitText(
StringView(mapping->GetText(), unit.TextContentStart(),
unit.TextContentEnd() - unit.TextContentStart()));
@@ -278,8 +279,8 @@ void ElementInnerTextCollector::ProcessNode(const Node& node) {
// 2. If the node is display locked, then we should not process it or its
// children, since they are not visible or accessible via innerText.
- if (node.IsElementNode()) {
- auto* context = ToElement(node).GetDisplayLockContext();
+ if (auto* element = DynamicTo<Element>(node)) {
+ auto* context = element->GetDisplayLockContext();
if (context && context->IsLocked())
return;
}
diff --git a/chromium/third_party/blink/renderer/core/editing/ephemeral_range.cc b/chromium/third_party/blink/renderer/core/editing/ephemeral_range.cc
index 6af4259b13e..081263d7b16 100644
--- a/chromium/third_party/blink/renderer/core/editing/ephemeral_range.cc
+++ b/chromium/third_party/blink/renderer/core/editing/ephemeral_range.cc
@@ -175,12 +175,9 @@ void EphemeralRangeTemplate<Strategy>::ShowTreeForThis() const {
->ToMarkedTreeString(StartPosition().AnchorNode(), "S",
EndPosition().AnchorNode(), "E")
.Utf8()
- .data()
- << "start: "
- << StartPosition().ToAnchorTypeAndOffsetString().Utf8().data()
+ << "start: " << StartPosition().ToAnchorTypeAndOffsetString().Utf8()
<< std::endl
- << "end: "
- << EndPosition().ToAnchorTypeAndOffsetString().Utf8().data();
+ << "end: " << EndPosition().ToAnchorTypeAndOffsetString().Utf8();
}
#endif
diff --git a/chromium/third_party/blink/renderer/core/editing/finder/find_buffer.cc b/chromium/third_party/blink/renderer/core/editing/finder/find_buffer.cc
index 1012fce3f1e..afdb08647d2 100644
--- a/chromium/third_party/blink/renderer/core/editing/finder/find_buffer.cc
+++ b/chromium/third_party/blink/renderer/core/editing/finder/find_buffer.cc
@@ -254,9 +254,10 @@ void FindBuffer::CollectScopedForcedUpdates(Node& start_node,
// We assume |start_node| is always visible/activatable if locked, so we don't
// need to check activatability of ancestors here.
for (Node& ancestor : FlatTreeTraversal::InclusiveAncestorsOf(*node)) {
- if (!ancestor.IsElementNode())
+ auto* ancestor_element = DynamicTo<Element>(ancestor);
+ if (!ancestor_element)
continue;
- PushScopedForcedUpdateIfNeeded(ToElement(ancestor));
+ PushScopedForcedUpdateIfNeeded(*ancestor_element);
}
while (node && node != node_after_block && node != search_range_end_node) {
@@ -265,8 +266,8 @@ void FindBuffer::CollectScopedForcedUpdates(Node& start_node,
node = FlatTreeTraversal::NextSkippingChildren(*node);
continue;
}
- if (node->IsElementNode())
- PushScopedForcedUpdateIfNeeded(ToElement(*node));
+ if (auto* element = DynamicTo<Element>(node))
+ PushScopedForcedUpdateIfNeeded(*element);
node = FlatTreeTraversal::Next(*node);
}
}
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
index 6a4da377c65..033dc3fce11 100644
--- 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
@@ -15,14 +15,15 @@
#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/heap/heap.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
namespace blink {
namespace {
const int kFindingTimeoutMS = 100;
-constexpr TimeDelta kFindTaskTestTimeout = TimeDelta::FromSeconds(10);
+constexpr base::TimeDelta kFindTaskTestTimeout =
+ base::TimeDelta::FromSeconds(10);
} // namespace
class FindTaskController::IdleFindTask
@@ -55,7 +56,7 @@ class FindTaskController::IdleFindTask
void ForceInvocationForTesting() {
invoke(MakeGarbageCollected<IdleDeadline>(
- CurrentTimeTicks() + kFindTaskTestTimeout,
+ base::TimeTicks::Now() + kFindTaskTestTimeout,
IdleDeadline::CallbackType::kCalledWhenIdle));
}
@@ -73,10 +74,6 @@ class FindTaskController::IdleFindTask
PositionInFlatTree(), 0 /* match_count */);
}
- const TimeDelta time_available =
- TimeDelta::FromMillisecondsD(deadline->timeRemaining());
- const TimeTicks start_time = CurrentTimeTicks();
-
Document& document = *controller_->GetLocalFrame()->GetDocument();
PositionInFlatTree search_start =
PositionInFlatTree::FirstPositionInNode(document);
@@ -147,10 +144,6 @@ class FindTaskController::IdleFindTask
break;
}
- 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_task_start_position,
match_count);
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 f9b608fcbbf..559f5c55ed0 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
@@ -60,7 +60,7 @@
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/layout/text_autosizer.h"
#include "third_party/blink/renderer/core/page/page.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/timer.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
@@ -88,7 +88,7 @@ static void ScrollToVisible(Range* match) {
ScrollBehavior scroll_behavior =
smooth_find_enabled ? kScrollBehaviorSmooth : kScrollBehaviorAuto;
first_node.GetLayoutObject()->ScrollRectToVisible(
- LayoutRect(match->BoundingBox()),
+ PhysicalRect(match->BoundingBox()),
WebScrollIntoViewParams(
ScrollAlignment::kAlignCenterIfNeeded,
ScrollAlignment::kAlignCenterIfNeeded, kUserScroll,
@@ -256,10 +256,10 @@ void TextFinder::SetFindEndstateFocusAndSelection() {
const EphemeralRange active_match_range(active_match);
if (node) {
for (Node& runner : NodeTraversal::InclusiveAncestorsOf(*node)) {
- if (!runner.IsElementNode())
+ auto* element = DynamicTo<Element>(runner);
+ if (!element)
continue;
- Element& element = ToElement(runner);
- if (element.IsFocusable()) {
+ if (element->IsFocusable()) {
// Found a focusable parent node. Set the active match as the
// selection and focus to the focusable node.
GetFrame()->Selection().SetSelectionAndEndTyping(
@@ -267,8 +267,8 @@ void TextFinder::SetFindEndstateFocusAndSelection() {
.SetBaseAndExtent(active_match_range)
.Build());
GetFrame()->GetDocument()->SetFocusedElement(
- &element, FocusParams(SelectionBehaviorOnFocus::kNone,
- kWebFocusTypeNone, nullptr));
+ element, FocusParams(SelectionBehaviorOnFocus::kNone,
+ kWebFocusTypeNone, nullptr));
return;
}
}
@@ -278,13 +278,13 @@ void TextFinder::SetFindEndstateFocusAndSelection() {
// This, for example, sets focus to the first link if you search for
// text and text that is within one or more links.
for (Node& runner : active_match_range.Nodes()) {
- if (!runner.IsElementNode())
+ auto* element = DynamicTo<Element>(runner);
+ if (!element)
continue;
- Element& element = ToElement(runner);
- if (element.IsFocusable()) {
+ if (element->IsFocusable()) {
GetFrame()->GetDocument()->SetFocusedElement(
- &element, FocusParams(SelectionBehaviorOnFocus::kNone,
- kWebFocusTypeNone, nullptr));
+ element, FocusParams(SelectionBehaviorOnFocus::kNone,
+ kWebFocusTypeNone, nullptr));
return;
}
}
@@ -621,7 +621,7 @@ int TextFinder::SelectFindMatch(unsigned index, WebRect* selection_rect) {
if (active_match_->FirstNode() &&
active_match_->FirstNode()->GetLayoutObject()) {
active_match_->FirstNode()->GetLayoutObject()->ScrollRectToVisible(
- LayoutRect(active_match_bounding_box),
+ PhysicalRect(active_match_bounding_box),
WebScrollIntoViewParams(ScrollAlignment::kAlignCenterIfNeeded,
ScrollAlignment::kAlignCenterIfNeeded,
kUserScroll));
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 99b243cd89c..f56e897421e 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
@@ -496,7 +496,7 @@ TEST_F(TextFinderTest, FindTextJavaScriptUpdatesDOM) {
EXPECT_TRUE(active_now);
// Add new text to DOM and try FindNext.
- Element* i_element = ToElement(GetDocument().body()->lastChild());
+ auto* i_element = To<Element>(GetDocument().body()->lastChild());
ASSERT_TRUE(i_element);
i_element->SetInnerHTMLFromString("ZZFindMe");
GetDocument().UpdateStyleAndLayout();
@@ -550,7 +550,7 @@ TEST_F(TextFinderTest, FindTextJavaScriptUpdatesDOMAfterNoMatches) {
EXPECT_FALSE(active_now);
// Add new text to DOM and try FindNext.
- Element* i_element = ToElement(GetDocument().body()->lastChild());
+ auto* i_element = To<Element>(GetDocument().body()->lastChild());
ASSERT_TRUE(i_element);
i_element->SetInnerHTMLFromString("ZZFindMe");
GetDocument().UpdateStyleAndLayout();
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 b078ed8849a..c0aa7016c7b 100644
--- a/chromium/third_party/blink/renderer/core/editing/frame_caret.cc
+++ b/chromium/third_party/blink/renderer/core/editing/frame_caret.cc
@@ -116,7 +116,7 @@ void FrameCaret::StartBlinkCaret() {
if (caret_blink_timer_->IsActive())
return;
- TimeDelta blink_interval = LayoutTheme::GetTheme().CaretBlinkInterval();
+ base::TimeDelta blink_interval = LayoutTheme::GetTheme().CaretBlinkInterval();
if (!blink_interval.is_zero())
caret_blink_timer_->StartRepeating(blink_interval, FROM_HERE);
@@ -150,8 +150,9 @@ void FrameCaret::UpdateStyleAndLayoutIfNeeded() {
bool should_paint_caret =
should_paint_caret_ && IsActive() &&
caret_visibility_ == CaretVisibility::kVisible &&
- IsEditablePosition(
- selection_editor_->ComputeVisibleSelectionInDOMTree().Start());
+ (IsEditablePosition(
+ selection_editor_->ComputeVisibleSelectionInDOMTree().Start()) ||
+ frame_->GetSettings()->GetCaretBrowsingEnabled());
display_item_client_->UpdateStyleAndLayoutIfNeeded(
should_paint_caret ? CaretPosition() : PositionWithAffinity());
@@ -187,17 +188,25 @@ void FrameCaret::PaintCaret(GraphicsContext& context,
}
bool FrameCaret::ShouldBlinkCaret() const {
+ // Don't blink the caret if it isn't visible or positioned.
if (caret_visibility_ != CaretVisibility::kVisible || !IsActive())
return false;
Element* root = RootEditableElementOf(CaretPosition().GetPosition());
- if (!root)
- return false;
-
- Element* focused_element = root->GetDocument().FocusedElement();
- if (!focused_element)
- return false;
+ if (root) {
+ // Caret is contained in editable content. If there is no focused element,
+ // don't blink the caret.
+ Element* focused_element = root->GetDocument().FocusedElement();
+ if (!focused_element)
+ return false;
+ } else {
+ // Caret is not contained in editable content--see if caret browsing is
+ // enabled. If it isn't, don't blink the caret.
+ if (!frame_->GetSettings()->GetCaretBrowsingEnabled())
+ return false;
+ }
+ // Only blink the caret if the selection has focus.
return frame_->Selection().SelectionHasFocus();
}
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 d48cf0dbb1a..1081d4ccd5d 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
@@ -9,6 +9,7 @@
#include "third_party/blink/renderer/core/editing/selection_template.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/core/frame/settings.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/scheduler/test/fake_task_runner.h"
@@ -43,11 +44,11 @@ TEST_F(FrameCaretTest, BlinkAfterTyping) {
caret.RecreateCaretBlinkTimerForTesting(task_runner.get());
const double kInterval = 10;
LayoutTheme::GetTheme().SetCaretBlinkInterval(
- TimeDelta::FromSecondsD(kInterval));
+ base::TimeDelta::FromSecondsD(kInterval));
GetDocument().GetPage()->GetFocusController().SetActive(true);
GetDocument().GetPage()->GetFocusController().SetFocused(true);
GetDocument().body()->SetInnerHTMLFromString("<textarea>");
- Element* editor = ToElement(GetDocument().body()->firstChild());
+ auto* editor = To<Element>(GetDocument().body()->firstChild());
editor->focus();
UpdateAllLifecyclePhasesForTest();
@@ -95,4 +96,14 @@ TEST_F(FrameCaretTest, ShouldNotBlinkWhenSelectionLooseFocus) {
EXPECT_FALSE(ShouldBlinkCaret(caret));
}
+TEST_F(FrameCaretTest, ShouldBlinkCaretWhileCaretBrowsing) {
+ FrameCaret& caret = Selection().FrameCaretForTesting();
+ Selection().SetSelection(SetSelectionTextToBody("<div>a|b</div>"),
+ SetSelectionOptions());
+ Selection().SetCaretVisible(true);
+ EXPECT_FALSE(ShouldBlinkCaret(caret));
+ GetDocument().GetFrame()->GetSettings()->SetCaretBrowsingEnabled(true);
+ EXPECT_TRUE(ShouldBlinkCaret(caret));
+}
+
} // namespace blink
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 a74ea982471..8567849e845 100644
--- a/chromium/third_party/blink/renderer/core/editing/frame_selection.cc
+++ b/chromium/third_party/blink/renderer/core/editing/frame_selection.cc
@@ -84,7 +84,6 @@
#include "third_party/blink/renderer/platform/geometry/float_quad.h"
#include "third_party/blink/renderer/platform/graphics/graphics_context.h"
#include "third_party/blink/renderer/platform/text/unicode_utilities.h"
-#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
#define EDIT_DEBUG 0
@@ -522,7 +521,8 @@ bool FrameSelection::ShouldPaintCaret(const LayoutBlock& block) const {
bool result = frame_caret_->ShouldPaintCaret(block);
DCHECK(!result ||
(ComputeVisibleSelectionInDOMTree().IsCaret() &&
- IsEditablePosition(ComputeVisibleSelectionInDOMTree().Start())));
+ (IsEditablePosition(ComputeVisibleSelectionInDOMTree().Start()) ||
+ frame_->GetSettings()->GetCaretBrowsingEnabled())));
return result;
}
@@ -568,7 +568,7 @@ void FrameSelection::PaintCaret(GraphicsContext& context,
frame_caret_->PaintCaret(context, paint_offset);
}
-bool FrameSelection::Contains(const LayoutPoint& point) {
+bool FrameSelection::Contains(const PhysicalOffset& point) {
if (!GetDocument().GetLayoutView())
return false;
@@ -969,15 +969,15 @@ String FrameSelection::SelectedTextForClipboard() const {
.Build());
}
-LayoutRect FrameSelection::AbsoluteUnclippedBounds() const {
+PhysicalRect FrameSelection::AbsoluteUnclippedBounds() const {
LocalFrameView* view = frame_->View();
LayoutView* layout_view = frame_->ContentLayoutObject();
if (!view || !layout_view)
- return LayoutRect();
+ return PhysicalRect();
view->UpdateLifecycleToLayoutClean();
- return LayoutRect(layout_selection_->AbsoluteSelectionBounds());
+ return PhysicalRect(layout_selection_->AbsoluteSelectionBounds());
}
IntRect FrameSelection::ComputeRectToScroll(
@@ -1018,9 +1018,8 @@ void FrameSelection::RevealSelection(const ScrollAlignment& alignment,
// This function is needed to make sure that ComputeRectToScroll below has the
// sticky offset info available before the computation.
GetDocument().EnsurePaintLocationDataValidForNode(start.AnchorNode());
- LayoutRect selection_rect =
- LayoutRect(ComputeRectToScroll(reveal_extent_option));
- if (selection_rect == LayoutRect() ||
+ PhysicalRect selection_rect(ComputeRectToScroll(reveal_extent_option));
+ if (selection_rect == PhysicalRect() ||
!start.AnchorNode()->GetLayoutObject()->EnclosingBox())
return;
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 48efc248c0d..2478f729188 100644
--- a/chromium/third_party/blink/renderer/core/editing/frame_selection.h
+++ b/chromium/third_party/blink/renderer/core/editing/frame_selection.h
@@ -60,6 +60,7 @@ enum class SelectionState;
class TextIteratorBehavior;
struct PaintInvalidatorContext;
struct PhysicalOffset;
+struct PhysicalRect;
enum RevealExtentOption { kRevealExtent, kDoNotRevealExtent };
@@ -172,7 +173,7 @@ class CORE_EXPORT FrameSelection final
// the frame you entirely selected.
void SelectFrameElementInParentIfFullySelected();
- bool Contains(const LayoutPoint&);
+ bool Contains(const PhysicalOffset&);
bool Modify(SelectionModifyAlteration,
SelectionModifyDirection,
@@ -258,7 +259,7 @@ class CORE_EXPORT FrameSelection final
// This returns last layouted selection bounds of LayoutSelection rather than
// SelectionEditor keeps.
- LayoutRect AbsoluteUnclippedBounds() const;
+ PhysicalRect AbsoluteUnclippedBounds() const;
// TODO(tkent): This function has a bug that scrolling doesn't work well in
// a case of RangeSelection. crbug.com/443061
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 444efad3fc7..3ba2c413a9c 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
@@ -24,6 +24,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/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"
#include "third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h"
@@ -154,7 +155,7 @@ TEST_F(FrameSelectionTest, PaintCaretShouldNotLayout) {
}
#define EXPECT_EQ_SELECTED_TEXT(text) \
- EXPECT_EQ(text, WebString(Selection().SelectedText()).Utf8())
+ EXPECT_EQ(text, Selection().SelectedText().Utf8())
TEST_F(FrameSelectionTest, SelectWordAroundCaret) {
// "Foo Bar Baz,"
@@ -1055,7 +1056,7 @@ TEST_F(FrameSelectionTest, SelectionBounds) {
const int node_margin_top = 2;
// The top of the node should be visible but the bottom should be outside
// by the viewport. The unclipped selection bounds should not be clipped.
- EXPECT_EQ(LayoutRect(0, node_margin_top, node_width, node_height),
+ EXPECT_EQ(PhysicalRect(0, node_margin_top, node_width, node_height),
Selection().AbsoluteUnclippedBounds());
// Scroll 500px down so the top of the node is outside the viewport and the
@@ -1064,14 +1065,14 @@ TEST_F(FrameSelectionTest, SelectionBounds) {
LocalFrameView* frame_view = GetDocument().View();
frame_view->LayoutViewport()->SetScrollOffset(ScrollOffset(0, scroll_offset),
kProgrammaticScroll);
- EXPECT_EQ(LayoutRect(0, node_margin_top, node_width, node_height),
+ EXPECT_EQ(PhysicalRect(0, node_margin_top, node_width, node_height),
frame_view->FrameToDocument(Selection().AbsoluteUnclippedBounds()));
// Adjust the page scale factor which changes the selection bounds as seen
// through the viewport. The unclipped selection bounds should not be clipped.
const int page_scale_factor = 2;
GetPage().SetPageScaleFactor(page_scale_factor);
- EXPECT_EQ(LayoutRect(0, node_margin_top, node_width, node_height),
+ EXPECT_EQ(PhysicalRect(0, node_margin_top, node_width, node_height),
frame_view->FrameToDocument(Selection().AbsoluteUnclippedBounds()));
}
@@ -1083,11 +1084,11 @@ TEST_F(FrameSelectionTest, SelectionContainsBidiBoundary) {
SetSelectionOptions());
// Check the right half of 'c'
- const LayoutPoint c_right(35, 13);
+ const PhysicalOffset c_right(35, 13);
EXPECT_TRUE(Selection().Contains(c_right));
// Check the left half of "F"
- const LayoutPoint f_left(45, 13);
+ const PhysicalOffset f_left(45, 13);
EXPECT_TRUE(Selection().Contains(f_left));
}
diff --git a/chromium/third_party/blink/renderer/core/editing/granularity_strategy.h b/chromium/third_party/blink/renderer/core/editing/granularity_strategy.h
index 58377bf5936..e0e0e2409f4 100644
--- a/chromium/third_party/blink/renderer/core/editing/granularity_strategy.h
+++ b/chromium/third_party/blink/renderer/core/editing/granularity_strategy.h
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/editing/forward.h"
#include "third_party/blink/renderer/core/editing/selection_strategy.h"
#include "third_party/blink/renderer/platform/geometry/int_size.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 ea555e8a4f1..61cd633411e 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
@@ -25,7 +25,7 @@
namespace blink {
#define EXPECT_EQ_SELECTED_TEXT(text) \
- EXPECT_EQ(text, WebString(Selection().SelectedText()).Utf8())
+ EXPECT_EQ(text, Selection().SelectedText().Utf8())
IntPoint VisiblePositionToContentsPoint(const VisiblePosition& pos) {
IntPoint result = AbsoluteSelectionBoundsOf(pos).MinXMaxYCorner();
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 6215e623ed8..b99f960d378 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
@@ -28,10 +28,10 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/graphics/color.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
-#include "ui/base/ime/mojo/ime_types.mojom-shared.h"
+#include "ui/base/ime/mojo/ime_types.mojom-blink.h"
namespace blink {
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 57005359f49..69746ece4e9 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
@@ -337,7 +337,7 @@ std::pair<ContainerNode*, PlainTextRange> PlainTextRangeForEphemeralRange(
}
int ComputeAutocapitalizeFlags(const Element* element) {
- const HTMLElement* const html_element = ToHTMLElementOrNull(element);
+ const auto* const html_element = DynamicTo<HTMLElement>(element);
if (!html_element)
return 0;
@@ -548,6 +548,22 @@ bool InputMethodController::CommitText(
return InsertTextAndMoveCaret(text, relative_caret_position, ime_text_spans);
}
+bool InputMethodController::ReplaceText(const String& text,
+ PlainTextRange range) {
+ EventQueueScope scope;
+ const PlainTextRange old_selection(GetSelectionOffsets());
+ if (!SetSelectionOffsets(range))
+ return false;
+ if (!InsertText(text))
+ return false;
+ wtf_size_t selection_delta = text.length() - range.length();
+ wtf_size_t start = old_selection.Start();
+ wtf_size_t end = old_selection.End();
+ return SetSelectionOffsets(
+ {start >= range.End() ? start + selection_delta : start,
+ end >= range.End() ? end + selection_delta : end});
+}
+
bool InputMethodController::ReplaceComposition(const String& text) {
// Verify that the caller is using an EventQueueScope to suppress the input
// event from being fired until the proper time (e.g. after applying an IME
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 6bb7ad039d4..37cde8df034 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
@@ -78,6 +78,9 @@ class CORE_EXPORT InputMethodController final
const Vector<ImeTextSpan>& ime_text_spans,
int relative_caret_position);
+ // Replaces the text in the specified range without changing the selection.
+ bool ReplaceText(const String&, PlainTextRange);
+
// Inserts ongoing composing text; changes the selection to the end of
// the inserting text if DoNotKeepSelection, or holds the selection if
// KeepSelection.
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 b344229cb9d..9706813c703 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
@@ -136,7 +136,7 @@ TEST_F(InputMethodControllerTest, BackspaceFromEndOfInput) {
String::FromUTF8("foo\xE2\x98\x85")); // U+2605 == "black star"
GetDocument().UpdateStyleAndLayout();
Controller().SetEditableSelectionOffsets(PlainTextRange(4, 4));
- EXPECT_STREQ("foo\xE2\x98\x85", input->value().Utf8().data());
+ EXPECT_EQ("foo\xE2\x98\x85", input->value().Utf8());
Controller().ExtendSelectionAndDelete(1, 0);
EXPECT_EQ("foo", input->value());
@@ -144,7 +144,7 @@ TEST_F(InputMethodControllerTest, BackspaceFromEndOfInput) {
String::FromUTF8("foo\xF0\x9F\x8F\x86")); // U+1F3C6 == "trophy"
GetDocument().UpdateStyleAndLayout();
Controller().SetEditableSelectionOffsets(PlainTextRange(4, 4));
- EXPECT_STREQ("foo\xF0\x9F\x8F\x86", input->value().Utf8().data());
+ EXPECT_EQ("foo\xF0\x9F\x8F\x86", input->value().Utf8());
Controller().ExtendSelectionAndDelete(1, 0);
EXPECT_EQ("foo", input->value());
@@ -152,7 +152,7 @@ TEST_F(InputMethodControllerTest, BackspaceFromEndOfInput) {
input->setValue(String::FromUTF8("foo\xE0\xB8\x81\xE0\xB9\x89"));
GetDocument().UpdateStyleAndLayout();
Controller().SetEditableSelectionOffsets(PlainTextRange(4, 4));
- EXPECT_STREQ("foo\xE0\xB8\x81\xE0\xB9\x89", input->value().Utf8().data());
+ EXPECT_EQ("foo\xE0\xB8\x81\xE0\xB9\x89", input->value().Utf8());
Controller().ExtendSelectionAndDelete(1, 0);
EXPECT_EQ("foo", input->value());
@@ -207,10 +207,10 @@ TEST_F(InputMethodControllerTest, SetCompositionAfterEmoji) {
.ComputeOffsetInContainerNode());
Controller().SetComposition(String("a"), ime_text_spans, 1, 1);
- EXPECT_STREQ("\xF0\x9F\x8F\x86\x61", div->innerText().Utf8().data());
+ EXPECT_EQ("\xF0\x9F\x8F\x86\x61", div->innerText().Utf8());
Controller().SetComposition(String("ab"), ime_text_spans, 2, 2);
- EXPECT_STREQ("\xF0\x9F\x8F\x86\x61\x62", div->innerText().Utf8().data());
+ EXPECT_EQ("\xF0\x9F\x8F\x86\x61\x62", div->innerText().Utf8());
}
TEST_F(InputMethodControllerTest, SetCompositionWithGraphemeCluster) {
@@ -258,18 +258,18 @@ TEST_F(InputMethodControllerTest,
ime_text_spans, 1);
Controller().CommitText("\nab ", ime_text_spans, 1);
Controller().SetComposition(String("c"), ime_text_spans, 1, 1);
- EXPECT_STREQ(
+ EXPECT_EQ(
"\xE0\xA4\xB9\xE0\xA5\x87\xE0\xA4\xB2\xE0\xA5\x8D\xE0\xA4\xB2\xE0\xA5"
"\x8B\nab c",
- div->innerText().Utf8().data());
+ div->innerText().Utf8());
EXPECT_EQ(11u, Controller().GetSelectionOffsets().Start());
EXPECT_EQ(11u, Controller().GetSelectionOffsets().End());
Controller().SetComposition(String("cd"), ime_text_spans, 2, 2);
- EXPECT_STREQ(
+ EXPECT_EQ(
"\xE0\xA4\xB9\xE0\xA5\x87\xE0\xA4\xB2\xE0\xA5\x8D\xE0\xA4\xB2\xE0\xA5"
"\x8B\nab cd",
- div->innerText().Utf8().data());
+ div->innerText().Utf8());
EXPECT_EQ(12u, Controller().GetSelectionOffsets().Start());
EXPECT_EQ(12u, Controller().GetSelectionOffsets().End());
}
@@ -288,22 +288,22 @@ TEST_F(InputMethodControllerTest, SetCompositionKeepingStyle) {
// Subtract a character.
Controller().SetComposition(String("12345789"), ime_text_spans, 8, 8);
- EXPECT_STREQ("abc1<b>2</b>3457<b>8</b>9d<b>e</b>f",
- div->InnerHTMLAsString().Utf8().data());
+ EXPECT_EQ("abc1<b>2</b>3457<b>8</b>9d<b>e</b>f",
+ div->InnerHTMLAsString().Utf8());
EXPECT_EQ(11u, Controller().GetSelectionOffsets().Start());
EXPECT_EQ(11u, Controller().GetSelectionOffsets().End());
// Append a character.
Controller().SetComposition(String("123456789"), ime_text_spans, 9, 9);
- EXPECT_STREQ("abc1<b>2</b>34567<b>8</b>9d<b>e</b>f",
- div->InnerHTMLAsString().Utf8().data());
+ EXPECT_EQ("abc1<b>2</b>34567<b>8</b>9d<b>e</b>f",
+ div->InnerHTMLAsString().Utf8());
EXPECT_EQ(12u, Controller().GetSelectionOffsets().Start());
EXPECT_EQ(12u, Controller().GetSelectionOffsets().End());
// Subtract and append characters.
Controller().SetComposition(String("123hello789"), ime_text_spans, 11, 11);
- EXPECT_STREQ("abc1<b>2</b>3hello7<b>8</b>9d<b>e</b>f",
- div->InnerHTMLAsString().Utf8().data());
+ EXPECT_EQ("abc1<b>2</b>3hello7<b>8</b>9d<b>e</b>f",
+ div->InnerHTMLAsString().Utf8());
}
TEST_F(InputMethodControllerTest, SetCompositionWithEmojiKeepingStyle) {
@@ -322,13 +322,11 @@ TEST_F(InputMethodControllerTest, SetCompositionWithEmojiKeepingStyle) {
// surrogate pair to the previous one.
Controller().SetComposition(String::FromUTF8("\xF0\x9F\x8F\xAB"),
ime_text_spans, 2, 2);
- EXPECT_STREQ("<b>\xF0\x9F\x8F\xAB</b>",
- div->InnerHTMLAsString().Utf8().data());
+ EXPECT_EQ("<b>\xF0\x9F\x8F\xAB</b>", div->InnerHTMLAsString().Utf8());
Controller().SetComposition(String::FromUTF8("\xF0\x9F\x8F\xA0"),
ime_text_spans, 2, 2);
- EXPECT_STREQ("<b>\xF0\x9F\x8F\xA0</b>",
- div->InnerHTMLAsString().Utf8().data());
+ EXPECT_EQ("<b>\xF0\x9F\x8F\xA0</b>", div->InnerHTMLAsString().Utf8());
}
TEST_F(InputMethodControllerTest,
@@ -349,12 +347,11 @@ TEST_F(InputMethodControllerTest,
// 1 grapheme cluster.
Controller().SetComposition(String::FromUTF8("\xE0\xB0\x83\xE0\xB0\x83"),
ime_text_spans, 2, 2);
- EXPECT_STREQ("<b>\xE0\xB0\x83\xE0\xB0\x83</b>",
- div->InnerHTMLAsString().Utf8().data());
+ EXPECT_EQ("<b>\xE0\xB0\x83\xE0\xB0\x83</b>", div->InnerHTMLAsString().Utf8());
Controller().SetComposition(String::FromUTF8("\xE0\xB0\x83"), ime_text_spans,
1, 1);
- EXPECT_STREQ("<b>\xE0\xB0\x83</b>", div->InnerHTMLAsString().Utf8().data());
+ EXPECT_EQ("<b>\xE0\xB0\x83</b>", div->InnerHTMLAsString().Utf8());
}
TEST_F(InputMethodControllerTest, FinishComposingTextKeepingStyle) {
@@ -664,7 +661,7 @@ TEST_F(InputMethodControllerTest,
input->setValue(String::FromUTF8("foo\xE2\x98\x85"));
GetDocument().UpdateStyleAndLayout();
Controller().SetEditableSelectionOffsets(PlainTextRange(4, 4));
- EXPECT_STREQ("foo\xE2\x98\x85", input->value().Utf8().data());
+ EXPECT_EQ("foo\xE2\x98\x85", input->value().Utf8());
Controller().DeleteSurroundingText(1, 0);
EXPECT_EQ("foo", input->value());
@@ -672,7 +669,7 @@ TEST_F(InputMethodControllerTest,
input->setValue(String::FromUTF8("foo\xF0\x9F\x8F\x86"));
GetDocument().UpdateStyleAndLayout();
Controller().SetEditableSelectionOffsets(PlainTextRange(5, 5));
- EXPECT_STREQ("foo\xF0\x9F\x8F\x86", input->value().Utf8().data());
+ EXPECT_EQ("foo\xF0\x9F\x8F\x86", input->value().Utf8());
Controller().DeleteSurroundingText(1, 0);
EXPECT_EQ("foo", input->value());
@@ -680,7 +677,7 @@ TEST_F(InputMethodControllerTest,
input->setValue(String::FromUTF8("foo\xE0\xB8\x81\xE0\xB9\x89"));
GetDocument().UpdateStyleAndLayout();
Controller().SetEditableSelectionOffsets(PlainTextRange(5, 5));
- EXPECT_STREQ("foo\xE0\xB8\x81\xE0\xB9\x89", input->value().Utf8().data());
+ EXPECT_EQ("foo\xE0\xB8\x81\xE0\xB9\x89", input->value().Utf8());
Controller().DeleteSurroundingText(1, 0);
EXPECT_EQ("foo", input->value());
@@ -688,17 +685,15 @@ TEST_F(InputMethodControllerTest,
input->setValue(String::FromUTF8("foo\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86"));
GetDocument().UpdateStyleAndLayout();
Controller().SetEditableSelectionOffsets(PlainTextRange(7, 7));
- EXPECT_STREQ("foo\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86",
- input->value().Utf8().data());
+ EXPECT_EQ("foo\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86", input->value().Utf8());
Controller().DeleteSurroundingText(2, 0);
- EXPECT_STREQ("foo\xF0\x9F\x8F\x86", input->value().Utf8().data());
+ EXPECT_EQ("foo\xF0\x9F\x8F\x86", input->value().Utf8());
// "trophy" + "trophy".
input->setValue(String::FromUTF8("foo\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86"));
GetDocument().UpdateStyleAndLayout();
Controller().SetEditableSelectionOffsets(PlainTextRange(7, 7));
- EXPECT_STREQ("foo\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86",
- input->value().Utf8().data());
+ EXPECT_EQ("foo\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86", input->value().Utf8());
Controller().DeleteSurroundingText(3, 0);
EXPECT_EQ("foo", input->value());
@@ -706,8 +701,7 @@ TEST_F(InputMethodControllerTest,
input->setValue(String::FromUTF8("foo\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86"));
GetDocument().UpdateStyleAndLayout();
Controller().SetEditableSelectionOffsets(PlainTextRange(7, 7));
- EXPECT_STREQ("foo\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86",
- input->value().Utf8().data());
+ EXPECT_EQ("foo\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86", input->value().Utf8());
Controller().DeleteSurroundingText(4, 0);
EXPECT_EQ("foo", input->value());
@@ -715,8 +709,7 @@ TEST_F(InputMethodControllerTest,
input->setValue(String::FromUTF8("foo\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86"));
GetDocument().UpdateStyleAndLayout();
Controller().SetEditableSelectionOffsets(PlainTextRange(7, 7));
- EXPECT_STREQ("foo\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86",
- input->value().Utf8().data());
+ EXPECT_EQ("foo\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86", input->value().Utf8());
Controller().DeleteSurroundingText(5, 0);
EXPECT_EQ("fo", input->value());
}
@@ -730,7 +723,7 @@ TEST_F(InputMethodControllerTest,
input->setValue(String::FromUTF8("\xE2\x98\x85 foo"));
GetDocument().UpdateStyleAndLayout();
Controller().SetEditableSelectionOffsets(PlainTextRange(0, 0));
- EXPECT_STREQ("\xE2\x98\x85 foo", input->value().Utf8().data());
+ EXPECT_EQ("\xE2\x98\x85 foo", input->value().Utf8());
Controller().DeleteSurroundingText(0, 1);
EXPECT_EQ(" foo", input->value());
@@ -738,7 +731,7 @@ TEST_F(InputMethodControllerTest,
input->setValue(String::FromUTF8("\xF0\x9F\x8F\x86 foo"));
GetDocument().UpdateStyleAndLayout();
Controller().SetEditableSelectionOffsets(PlainTextRange(0, 0));
- EXPECT_STREQ("\xF0\x9F\x8F\x86 foo", input->value().Utf8().data());
+ EXPECT_EQ("\xF0\x9F\x8F\x86 foo", input->value().Utf8());
Controller().DeleteSurroundingText(0, 1);
EXPECT_EQ(" foo", input->value());
@@ -746,7 +739,7 @@ TEST_F(InputMethodControllerTest,
input->setValue(String::FromUTF8("\xE0\xB8\x81\xE0\xB9\x89 foo"));
GetDocument().UpdateStyleAndLayout();
Controller().SetEditableSelectionOffsets(PlainTextRange(0, 0));
- EXPECT_STREQ("\xE0\xB8\x81\xE0\xB9\x89 foo", input->value().Utf8().data());
+ EXPECT_EQ("\xE0\xB8\x81\xE0\xB9\x89 foo", input->value().Utf8());
Controller().DeleteSurroundingText(0, 1);
EXPECT_EQ(" foo", input->value());
@@ -754,17 +747,15 @@ TEST_F(InputMethodControllerTest,
input->setValue(String::FromUTF8("\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86 foo"));
GetDocument().UpdateStyleAndLayout();
Controller().SetEditableSelectionOffsets(PlainTextRange(0, 0));
- EXPECT_STREQ("\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86 foo",
- input->value().Utf8().data());
+ EXPECT_EQ("\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86 foo", input->value().Utf8());
Controller().DeleteSurroundingText(0, 2);
- EXPECT_STREQ("\xF0\x9F\x8F\x86 foo", input->value().Utf8().data());
+ EXPECT_EQ("\xF0\x9F\x8F\x86 foo", input->value().Utf8());
// "trophy" + "trophy".
input->setValue(String::FromUTF8("\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86 foo"));
GetDocument().UpdateStyleAndLayout();
Controller().SetEditableSelectionOffsets(PlainTextRange(0, 0));
- EXPECT_STREQ("\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86 foo",
- input->value().Utf8().data());
+ EXPECT_EQ("\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86 foo", input->value().Utf8());
Controller().DeleteSurroundingText(0, 3);
EXPECT_EQ(" foo", input->value());
@@ -772,8 +763,7 @@ TEST_F(InputMethodControllerTest,
input->setValue(String::FromUTF8("\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86 foo"));
GetDocument().UpdateStyleAndLayout();
Controller().SetEditableSelectionOffsets(PlainTextRange(0, 0));
- EXPECT_STREQ("\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86 foo",
- input->value().Utf8().data());
+ EXPECT_EQ("\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86 foo", input->value().Utf8());
Controller().DeleteSurroundingText(0, 4);
EXPECT_EQ(" foo", input->value());
@@ -781,8 +771,7 @@ TEST_F(InputMethodControllerTest,
input->setValue(String::FromUTF8("\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86 foo"));
GetDocument().UpdateStyleAndLayout();
Controller().SetEditableSelectionOffsets(PlainTextRange(0, 0));
- EXPECT_STREQ("\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86 foo",
- input->value().Utf8().data());
+ EXPECT_EQ("\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86 foo", input->value().Utf8());
Controller().DeleteSurroundingText(0, 5);
EXPECT_EQ("foo", input->value());
}
@@ -796,8 +785,7 @@ TEST_F(InputMethodControllerTest,
input->setValue(String::FromUTF8("\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86"));
GetDocument().UpdateStyleAndLayout();
Controller().SetEditableSelectionOffsets(PlainTextRange(2, 2));
- EXPECT_STREQ("\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86",
- input->value().Utf8().data());
+ EXPECT_EQ("\xF0\x9F\x8F\x86\xF0\x9F\x8F\x86", input->value().Utf8());
Controller().DeleteSurroundingText(1, 1);
EXPECT_EQ("", input->value());
}
@@ -850,7 +838,7 @@ TEST_F(InputMethodControllerTest,
Controller().SetEditableSelectionOffsets(PlainTextRange(8, 8));
Controller().DeleteSurroundingTextInCodePoints(2, 0);
- EXPECT_STREQ("a\xE2\x98\x85 \xF0\x9F\x8F\x86 ", input->value().Utf8().data());
+ EXPECT_EQ("a\xE2\x98\x85 \xF0\x9F\x8F\x86 ", input->value().Utf8());
Controller().DeleteSurroundingTextInCodePoints(4, 0);
EXPECT_EQ("a", input->value());
@@ -865,7 +853,7 @@ TEST_F(InputMethodControllerTest,
// grapheme cluster (2 code points). The root cause is that we adjust the
// selection by grapheme cluster in deleteSurroundingText().
Controller().DeleteSurroundingTextInCodePoints(1, 0);
- EXPECT_STREQ("a\xE2\x98\x85 \xF0\x9F\x8F\x86 ", input->value().Utf8().data());
+ EXPECT_EQ("a\xE2\x98\x85 \xF0\x9F\x8F\x86 ", input->value().Utf8());
}
TEST_F(InputMethodControllerTest,
@@ -880,7 +868,7 @@ TEST_F(InputMethodControllerTest,
Controller().SetEditableSelectionOffsets(PlainTextRange(0, 0));
Controller().DeleteSurroundingTextInCodePoints(0, 5);
- EXPECT_STREQ("\xE0\xB8\x81\xE0\xB9\x89", input->value().Utf8().data());
+ EXPECT_EQ("\xE0\xB8\x81\xE0\xB9\x89", input->value().Utf8());
Controller().DeleteSurroundingTextInCodePoints(0, 1);
// TODO(yabinh): Same here. We should only delete 1 code point.
@@ -898,7 +886,7 @@ TEST_F(InputMethodControllerTest,
GetDocument().UpdateStyleAndLayout();
Controller().SetEditableSelectionOffsets(PlainTextRange(3, 3));
Controller().DeleteSurroundingTextInCodePoints(2, 2);
- EXPECT_STREQ("a\xE0\xB8\x81\xE0\xB9\x89", input->value().Utf8().data());
+ EXPECT_EQ("a\xE0\xB8\x81\xE0\xB9\x89", input->value().Utf8());
}
TEST_F(InputMethodControllerTest, DeleteSurroundingTextInCodePointsWithImage) {
@@ -928,28 +916,23 @@ TEST_F(InputMethodControllerTest,
GetDocument().UpdateStyleAndLayout();
// The invalid high surrogate is encoded as '\xED\xA0\xBC', and invalid low
// surrogate is encoded as '\xED\xBF\x86'.
- EXPECT_STREQ("a\xED\xA0\xBC\xE2\x98\x85\xED\xBF\x86 ",
- input->value().Utf8().data());
+ EXPECT_EQ("a\xED\xA0\xBC\xE2\x98\x85\xED\xBF\x86 ", input->value().Utf8());
Controller().SetEditableSelectionOffsets(PlainTextRange(5, 5));
// Delete a SPACE.
Controller().DeleteSurroundingTextInCodePoints(1, 0);
- EXPECT_STREQ("a\xED\xA0\xBC\xE2\x98\x85\xED\xBF\x86",
- input->value().Utf8().data());
+ EXPECT_EQ("a\xED\xA0\xBC\xE2\x98\x85\xED\xBF\x86", input->value().Utf8());
// Do nothing since there is an invalid surrogate in the requested range.
Controller().DeleteSurroundingTextInCodePoints(2, 0);
- EXPECT_STREQ("a\xED\xA0\xBC\xE2\x98\x85\xED\xBF\x86",
- input->value().Utf8().data());
+ EXPECT_EQ("a\xED\xA0\xBC\xE2\x98\x85\xED\xBF\x86", input->value().Utf8());
Controller().SetEditableSelectionOffsets(PlainTextRange(0, 0));
// Delete 'a'.
Controller().DeleteSurroundingTextInCodePoints(0, 1);
- EXPECT_STREQ("\xED\xA0\xBC\xE2\x98\x85\xED\xBF\x86",
- input->value().Utf8().data());
+ EXPECT_EQ("\xED\xA0\xBC\xE2\x98\x85\xED\xBF\x86", input->value().Utf8());
// Do nothing since there is an invalid surrogate in the requested range.
Controller().DeleteSurroundingTextInCodePoints(0, 2);
- EXPECT_STREQ("\xED\xA0\xBC\xE2\x98\x85\xED\xBF\x86",
- input->value().Utf8().data());
+ EXPECT_EQ("\xED\xA0\xBC\xE2\x98\x85\xED\xBF\x86", input->value().Utf8());
}
TEST_F(InputMethodControllerTest, SetCompositionForInputWithNewCaretPositions) {
@@ -1317,7 +1300,7 @@ TEST_F(InputMethodControllerTest, CompositionInputEventForInsertEmptyText) {
GetDocument().setTitle(g_empty_string);
GetDocument().UpdateStyleAndLayout();
Controller().CommitText("", ime_text_spans, 0);
- EXPECT_STREQ("", GetDocument().title().Utf8().data());
+ EXPECT_EQ("", GetDocument().title().Utf8());
GetDocument().setTitle(g_empty_string);
Controller().SetComposition("n", ime_text_spans, 1, 1);
@@ -1643,10 +1626,9 @@ TEST_F(InputMethodControllerTest,
// Check that the marker is still attached to " text" and includes the space
// before "text" but not the space after
EXPECT_EQ(1u, GetDocument().Markers().Markers().size());
- ASSERT_STREQ("\xC2\xA0text",
- GetMarkedText(GetDocument().Markers(), div->firstChild(), 0)
- .Utf8()
- .data());
+ ASSERT_EQ(
+ "\xC2\xA0text",
+ GetMarkedText(GetDocument().Markers(), div->firstChild(), 0).Utf8());
}
TEST_F(InputMethodControllerTest,
@@ -1671,10 +1653,9 @@ TEST_F(InputMethodControllerTest,
// Check that the marker is still attached to "text " and includes the space
// after "text" but not the space before
EXPECT_EQ(1u, GetDocument().Markers().Markers().size());
- ASSERT_STREQ("text\xC2\xA0",
- GetMarkedText(GetDocument().Markers(), div->firstChild(), 0)
- .Utf8()
- .data());
+ ASSERT_EQ(
+ "text\xC2\xA0",
+ GetMarkedText(GetDocument().Markers(), div->firstChild(), 0).Utf8());
}
TEST_F(
@@ -1701,10 +1682,9 @@ TEST_F(
// Check that the marker is still attached to " text " and includes both the
// space before "text" and the space after
EXPECT_EQ(1u, GetDocument().Markers().Markers().size());
- ASSERT_STREQ("\xC2\xA0text\xC2\xA0",
- GetMarkedText(GetDocument().Markers(), div->firstChild(), 0)
- .Utf8()
- .data());
+ ASSERT_EQ(
+ "\xC2\xA0text\xC2\xA0",
+ GetMarkedText(GetDocument().Markers(), div->firstChild(), 0).Utf8());
}
TEST_F(InputMethodControllerTest, ContentDependentMarker_ReplaceStartOfMarker) {
@@ -1742,10 +1722,9 @@ TEST_F(InputMethodControllerTest,
// Verify marker is under "Original text"
EXPECT_EQ(1u, GetDocument().Markers().Markers().size());
- ASSERT_STREQ("Original text",
- GetMarkedText(GetDocument().Markers(), div->firstChild(), 0)
- .Utf8()
- .data());
+ ASSERT_EQ(
+ "Original text",
+ GetMarkedText(GetDocument().Markers(), div->firstChild(), 0).Utf8());
}
TEST_F(InputMethodControllerTest,
@@ -1824,10 +1803,9 @@ TEST_F(InputMethodControllerTest, ContentIndependentMarker_ReplaceEndOfMarker) {
// Verify marker is under "Initial string"
EXPECT_EQ(1u, GetDocument().Markers().Markers().size());
- ASSERT_STREQ("Initial string",
- GetMarkedText(GetDocument().Markers(), div->firstChild(), 0)
- .Utf8()
- .data());
+ ASSERT_EQ(
+ "Initial string",
+ GetMarkedText(GetDocument().Markers(), div->firstChild(), 0).Utf8());
}
TEST_F(InputMethodControllerTest,
@@ -1911,10 +1889,9 @@ TEST_F(InputMethodControllerTest,
// Verify marker is under "string"
EXPECT_EQ(1u, GetDocument().Markers().Markers().size());
- ASSERT_STREQ("string",
- GetMarkedText(GetDocument().Markers(), div->firstChild(), 0)
- .Utf8()
- .data());
+ ASSERT_EQ(
+ "string",
+ GetMarkedText(GetDocument().Markers(), div->firstChild(), 0).Utf8());
}
TEST_F(InputMethodControllerTest,
@@ -2555,8 +2532,7 @@ TEST_F(InputMethodControllerTest, SetCompositionTamilVirama) {
EXPECT_EQ(1u, div->CountChildren());
auto* text = To<Text>(div->firstChild());
- EXPECT_STREQ("\xE0\xAE\x9A\xE0\xAF\x8D\xE0\xAE\x9A",
- text->data().Utf8().data());
+ EXPECT_EQ("\xE0\xAE\x9A\xE0\xAF\x8D\xE0\xAE\x9A", text->data().Utf8());
Range* range = GetCompositionRange();
EXPECT_EQ(2u, range->startOffset());
@@ -3188,7 +3164,7 @@ TEST_F(InputMethodControllerTest, AutocapitalizeTextInputFlags) {
GetDocument().write(element);
GetDocument().UpdateStyleAndLayout();
- ToElement(GetDocument().body()->lastChild())->focus();
+ To<Element>(GetDocument().body()->lastChild())->focus();
EXPECT_EQ(expected_flags,
Controller().TextInputInfo().flags & autocapitalize_mask);
diff --git a/chromium/third_party/blink/renderer/core/editing/inline_box_position.h b/chromium/third_party/blink/renderer/core/editing/inline_box_position.h
index 61f253c2f59..3d58ea1ad42 100644
--- a/chromium/third_party/blink/renderer/core/editing/inline_box_position.h
+++ b/chromium/third_party/blink/renderer/core/editing/inline_box_position.h
@@ -32,7 +32,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/editing/forward.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/editing/inline_box_traversal.h b/chromium/third_party/blink/renderer/core/editing/inline_box_traversal.h
index 5bccc36e0ed..c3c3ea20c7d 100644
--- a/chromium/third_party/blink/renderer/core/editing/inline_box_traversal.h
+++ b/chromium/third_party/blink/renderer/core/editing/inline_box_traversal.h
@@ -8,7 +8,7 @@
// TODO(xiaochengh): Rename this file to |bidi_adjustment.h|
#include "third_party/blink/renderer/core/editing/forward.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/editing/iterators/bit_stack.h b/chromium/third_party/blink/renderer/core/editing/iterators/bit_stack.h
index 9909e04cd38..cdbb6362b3f 100644
--- a/chromium/third_party/blink/renderer/core/editing/iterators/bit_stack.h
+++ b/chromium/third_party/blink/renderer/core/editing/iterators/bit_stack.h
@@ -27,7 +27,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_EDITING_ITERATORS_BIT_STACK_H_
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/editing/iterators/fully_clipped_state_stack.h b/chromium/third_party/blink/renderer/core/editing/iterators/fully_clipped_state_stack.h
index 0e8ca69fa0e..3f60c01e7bf 100644
--- a/chromium/third_party/blink/renderer/core/editing/iterators/fully_clipped_state_stack.h
+++ b/chromium/third_party/blink/renderer/core/editing/iterators/fully_clipped_state_stack.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/editing/editing_strategy.h"
#include "third_party/blink/renderer/core/editing/iterators/bit_stack.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/editing/iterators/simplified_backwards_text_iterator_test.cc b/chromium/third_party/blink/renderer/core/editing/iterators/simplified_backwards_text_iterator_test.cc
index 58ae10e0f9d..cf442f1828e 100644
--- a/chromium/third_party/blink/renderer/core/editing/iterators/simplified_backwards_text_iterator_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/iterators/simplified_backwards_text_iterator_test.cc
@@ -35,8 +35,7 @@ class SimplifiedBackwardsTextIteratorTest : public EditingTestBase {
is_first = false;
builder.Append(iterator.GetTextState().GetTextForTesting());
}
- CString utf8 = builder.ToString().Utf8();
- return std::string(utf8.data(), utf8.length());
+ return builder.ToString().Utf8();
}
};
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 c757ad3ce79..9ba1a257880 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
@@ -36,7 +36,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/frame/local_frame_view.h"
-#include "third_party/blink/renderer/core/frame/use_counter.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/html/html_element.h"
@@ -46,6 +45,7 @@
#include "third_party/blink/renderer/core/layout/layout_table_cell.h"
#include "third_party/blink/renderer/core/layout/layout_table_row.h"
#include "third_party/blink/renderer/platform/fonts/font.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
namespace blink {
@@ -78,7 +78,8 @@ TextIteratorBehavior AdjustBehaviorFlags<EditingInFlatTreeStrategy>(
}
static inline bool HasDisplayContents(const Node& node) {
- return node.IsElementNode() && ToElement(node).HasDisplayContentsStyle();
+ auto* element = DynamicTo<Element>(node);
+ return element && element->HasDisplayContentsStyle();
}
// Checks if |advance()| skips the descendants of |node|, which is the case if
@@ -175,8 +176,8 @@ bool ShouldHandleChildren(const Node& node,
if (!behavior.EntersTextControls() && IsTextControl(node))
return false;
- if (node.IsElementNode()) {
- if (auto* context = ToElement(node).GetDisplayLockContext())
+ if (auto* element = DynamicTo<Element>(node)) {
+ if (auto* context = element->GetDisplayLockContext())
return context->IsActivatable();
}
return true;
@@ -324,10 +325,10 @@ void TextIteratorAlgorithm<Strategy>::Advance() {
} else {
// Enter author shadow roots, from youngest, if any and if necessary.
if (iteration_progress_ < kHandledOpenShadowRoots) {
+ auto* element = DynamicTo<Element>(node_.Get());
if (std::is_same<Strategy, EditingStrategy>::value &&
- EntersOpenShadowRoots() && node_->IsElementNode() &&
- ToElement(node_)->OpenShadowRoot()) {
- ShadowRoot* youngest_shadow_root = ToElement(node_)->OpenShadowRoot();
+ EntersOpenShadowRoots() && element && element->OpenShadowRoot()) {
+ ShadowRoot* youngest_shadow_root = element->OpenShadowRoot();
DCHECK(youngest_shadow_root->GetType() == ShadowRootType::V0 ||
youngest_shadow_root->GetType() == ShadowRootType::kOpen);
node_ = youngest_shadow_root;
@@ -345,7 +346,7 @@ void TextIteratorAlgorithm<Strategy>::Advance() {
if (std::is_same<Strategy, EditingStrategy>::value &&
EntersTextControls() && layout_object->IsTextControl()) {
ShadowRoot* user_agent_shadow_root =
- ToElement(node_)->UserAgentShadowRoot();
+ To<Element>(node_.Get())->UserAgentShadowRoot();
DCHECK(user_agent_shadow_root->IsUserAgent());
node_ = user_agent_shadow_root;
iteration_progress_ = kHandledNone;
diff --git a/chromium/third_party/blink/renderer/core/editing/iterators/text_iterator_behavior.h b/chromium/third_party/blink/renderer/core/editing/iterators/text_iterator_behavior.h
index ce1897327a0..232842e603a 100644
--- a/chromium/third_party/blink/renderer/core/editing/iterators/text_iterator_behavior.h
+++ b/chromium/third_party/blink/renderer/core/editing/iterators/text_iterator_behavior.h
@@ -7,7 +7,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 2add728c3d5..004aeee0331 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
@@ -148,7 +148,7 @@ std::string TextIteratorTest::IterateWithIterator(
text_chunks.Append(iterator.GetText().GetTextForTesting());
text_chunks.Append(']');
}
- return std::string(text_chunks.ToString().Utf8().data());
+ return text_chunks.ToString().Utf8();
}
Range* TextIteratorTest::GetBodyRange() const {
diff --git a/chromium/third_party/blink/renderer/core/editing/iterators/text_searcher_icu.cc b/chromium/third_party/blink/renderer/core/editing/iterators/text_searcher_icu.cc
index ccb05314833..f9fd3b7f315 100644
--- a/chromium/third_party/blink/renderer/core/editing/iterators/text_searcher_icu.cc
+++ b/chromium/third_party/blink/renderer/core/editing/iterators/text_searcher_icu.cc
@@ -33,7 +33,7 @@
#include "third_party/blink/renderer/platform/text/text_boundaries.h"
#include "third_party/blink/renderer/platform/text/text_break_iterator_internal_icu.h"
#include "third_party/blink/renderer/platform/text/unicode_utilities.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/character_names.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
@@ -50,7 +50,7 @@ UStringSearch* CreateSearcher() {
CurrentSearchLocaleID() + String("@collation=search");
UStringSearch* searcher =
usearch_open(&kNewlineCharacter, 1, &kNewlineCharacter, 1,
- search_collator_name.Utf8().data(), nullptr, &status);
+ search_collator_name.Utf8().c_str(), nullptr, &status);
DCHECK(status == U_ZERO_ERROR || status == U_USING_FALLBACK_WARNING ||
status == U_USING_DEFAULT_WARNING)
<< status;
diff --git a/chromium/third_party/blink/renderer/core/editing/iterators/text_searcher_icu.h b/chromium/third_party/blink/renderer/core/editing/iterators/text_searcher_icu.h
index 071f02fdd00..1f251e96514 100644
--- a/chromium/third_party/blink/renderer/core/editing/iterators/text_searcher_icu.h
+++ b/chromium/third_party/blink/renderer/core/editing/iterators/text_searcher_icu.h
@@ -8,7 +8,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/editing/finder/find_options.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/string_view.h"
#include "third_party/blink/renderer/platform/wtf/text/unicode.h"
diff --git a/chromium/third_party/blink/renderer/core/editing/keyboard_test.cc b/chromium/third_party/blink/renderer/core/editing/keyboard_test.cc
index d216985824e..356c4353370 100644
--- a/chromium/third_party/blink/renderer/core/editing/keyboard_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/keyboard_test.cc
@@ -66,9 +66,7 @@ class KeyboardTest : public testing::Test {
WebInputEvent::GetStaticTimeStampForTests());
event.text[0] = key_code;
event.windows_key_code = key_code;
- CString key_utf8 = key.Utf8();
- event.dom_key = ui::KeycodeConverter::KeyStringToDomKey(
- std::string(key_utf8.data(), key_utf8.length()));
+ event.dom_key = ui::KeycodeConverter::KeyStringToDomKey(key.Utf8());
return event;
}
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 9405b0e232c..4087870d9ce 100644
--- a/chromium/third_party/blink/renderer/core/editing/layout_selection.cc
+++ b/chromium/third_party/blink/renderer/core/editing/layout_selection.cc
@@ -910,8 +910,8 @@ void PrintSelectionStatus(std::ostream& ostream, const Node& node) {
ostream << (void*)&node;
if (node.IsTextNode())
ostream << "#text";
- else if (const Element* element = ToElementOrNull(node))
- ostream << element->tagName().Utf8().data();
+ else if (const auto* element = DynamicTo<Element>(node))
+ ostream << element->tagName().Utf8();
LayoutObject* layout_object = node.GetLayoutObject();
if (!layout_object) {
ostream << " <null LayoutObject>";
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 28b1d5b4f49..d24c62f105e 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
@@ -33,7 +33,7 @@ static LayoutTextFragment* FirstLetterPartFor(
class LayoutSelectionTestBase : public EditingTestBase {
protected:
static void PrintText(std::ostream& ostream, const Text& text) {
- ostream << "'" << text.data().Utf8().data() << "'";
+ ostream << "'" << text.data().Utf8() << "'";
}
static void PrintLayoutTextInfo(const FrameSelection& selection,
@@ -83,8 +83,8 @@ class LayoutSelectionTestBase : public EditingTestBase {
wtf_size_t depth) {
if (const Text* text = DynamicTo<Text>(node))
PrintText(ostream, *text);
- else if (const Element* element = ToElementOrNull(node))
- ostream << element->tagName().Utf8().data();
+ else if (const auto* element = DynamicTo<Element>(node))
+ ostream << element->tagName().Utf8();
else
ostream << node;
@@ -96,7 +96,7 @@ class LayoutSelectionTestBase : public EditingTestBase {
PrintLayoutObjectInfo(selection, ostream, layout_object);
if (LayoutTextFragment* first_letter = FirstLetterPartFor(layout_object)) {
ostream << std::endl
- << RepeatString(" ", depth + 1).Utf8().data() << ":first-letter";
+ << RepeatString(" ", depth + 1).Utf8() << ":first-letter";
PrintLayoutObjectInfo(selection, ostream, first_letter);
}
}
@@ -105,14 +105,14 @@ class LayoutSelectionTestBase : public EditingTestBase {
std::ostream& ostream,
const Node& node,
wtf_size_t depth) {
- ostream << RepeatString(" ", depth).Utf8().data();
+ ostream << RepeatString(" ", depth).Utf8();
if (IsHTMLStyleElement(node)) {
ostream << "<style> ";
return;
}
PrintSelectionInfo(selection, ostream, node, depth);
if (ShadowRoot* shadow_root = node.GetShadowRoot()) {
- ostream << std::endl << RepeatString(" ", depth + 1).Utf8().data();
+ ostream << std::endl << RepeatString(" ", depth + 1).Utf8();
ostream << "#shadow-root ";
for (Node* child = shadow_root->firstChild(); child;
child = child->nextSibling()) {
@@ -808,7 +808,7 @@ TEST_P(LayoutSelectionTest, ClearByRemoveLayoutObject) {
" 'baz', End(0,3), ShouldInvalidate ",
DumpSelectionInfo());
- Element* span_baz = ToElement(GetDocument().body()->lastChild());
+ auto* span_baz = To<Element>(GetDocument().body()->lastChild());
span_baz->SetInlineStyleProperty(CSSPropertyID::kDisplay, CSSValueID::kNone);
GetDocument().UpdateStyleAndLayout();
Selection().CommitAppearanceIfNeeded();
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 1d017c4a7e0..5f0e04ca791 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
@@ -191,10 +191,10 @@ TEST_F(LinkSelectionTest, HandCursorDuringLinkDrag) {
->LocalFrameRoot()
.GetEventHandler()
.ScheduleCursorUpdate();
- test::RunDelayedTasks(TimeDelta::FromMilliseconds(50));
+ test::RunDelayedTasks(base::TimeDelta::FromMilliseconds(50));
const auto& cursor =
main_frame_->GetFrame()->GetChromeClient().LastSetCursorForTesting();
- EXPECT_EQ(Cursor::kHand, cursor.GetType());
+ EXPECT_EQ(ui::CursorType::kHand, cursor.GetType());
}
TEST_F(LinkSelectionTest, DragOnNothingShowsPointer) {
@@ -203,10 +203,10 @@ TEST_F(LinkSelectionTest, DragOnNothingShowsPointer) {
->LocalFrameRoot()
.GetEventHandler()
.ScheduleCursorUpdate();
- test::RunDelayedTasks(TimeDelta::FromMilliseconds(50));
+ test::RunDelayedTasks(base::TimeDelta::FromMilliseconds(50));
const auto& cursor =
main_frame_->GetFrame()->GetChromeClient().LastSetCursorForTesting();
- EXPECT_EQ(Cursor::kPointer, cursor.GetType());
+ EXPECT_EQ(ui::CursorType::kPointer, cursor.GetType());
}
TEST_F(LinkSelectionTest, CaretCursorOverLinkDuringSelection) {
@@ -216,10 +216,10 @@ TEST_F(LinkSelectionTest, CaretCursorOverLinkDuringSelection) {
->LocalFrameRoot()
.GetEventHandler()
.ScheduleCursorUpdate();
- test::RunDelayedTasks(TimeDelta::FromMilliseconds(50));
+ test::RunDelayedTasks(base::TimeDelta::FromMilliseconds(50));
const auto& cursor =
main_frame_->GetFrame()->GetChromeClient().LastSetCursorForTesting();
- EXPECT_EQ(Cursor::kIBeam, cursor.GetType());
+ EXPECT_EQ(ui::CursorType::kIBeam, cursor.GetType());
}
TEST_F(LinkSelectionTest, HandCursorOverLinkAfterContextMenu) {
@@ -235,10 +235,10 @@ TEST_F(LinkSelectionTest, HandCursorOverLinkAfterContextMenu) {
frame->GetPage()->GetContextMenuController().ClearContextMenu();
frame->LocalFrameRoot().GetEventHandler().ScheduleCursorUpdate();
- test::RunDelayedTasks(TimeDelta::FromMilliseconds(50));
+ test::RunDelayedTasks(base::TimeDelta::FromMilliseconds(50));
const auto& cursor =
main_frame_->GetFrame()->GetChromeClient().LastSetCursorForTesting();
- EXPECT_EQ(Cursor::kHand, cursor.GetType());
+ EXPECT_EQ(ui::CursorType::kHand, cursor.GetType());
}
TEST_F(LinkSelectionTest, SingleClickWithAltStartsDownload) {
diff --git a/chromium/third_party/blink/renderer/core/editing/markers/document_marker.h b/chromium/third_party/blink/renderer/core/editing/markers/document_marker.h
index 97d05a100fb..7124abe6223 100644
--- a/chromium/third_party/blink/renderer/core/editing/markers/document_marker.h
+++ b/chromium/third_party/blink/renderer/core/editing/markers/document_marker.h
@@ -27,7 +27,7 @@
#include "third_party/blink/renderer/core/core_export.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/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/vector_traits.h"
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 0ccaf7f0954..023cfc51c4b 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
@@ -985,7 +985,7 @@ void DocumentMarkerController::ShowMarkers() const {
builder.Append("\n");
}
LOG(INFO) << markers_.size() << " nodes have markers:\n"
- << builder.ToString().Utf8().data();
+ << builder.ToString().Utf8();
}
#endif
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 cb2a6946f9a..5453ea97203 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
@@ -81,7 +81,7 @@ void DocumentMarkerControllerTest::MarkNodeContentsTextMatch(Node* node) {
TEST_F(DocumentMarkerControllerTest, DidMoveToNewDocument) {
SetBodyContent("<b><i>foo</i></b>");
- Element* parent = ToElement(GetDocument().body()->firstChild()->firstChild());
+ auto* parent = To<Element>(GetDocument().body()->firstChild()->firstChild());
MarkNodeContents(parent);
EXPECT_EQ(1u, MarkerController().Markers().size());
Persistent<Document> another_document = MakeGarbageCollected<Document>();
@@ -96,8 +96,8 @@ TEST_F(DocumentMarkerControllerTest, DidMoveToNewDocument) {
TEST_F(DocumentMarkerControllerTest, NodeWillBeRemovedMarkedByNormalize) {
SetBodyContent("<b><i>foo</i></b>");
{
- Element* parent =
- ToElement(GetDocument().body()->firstChild()->firstChild());
+ auto* parent =
+ To<Element>(GetDocument().body()->firstChild()->firstChild());
parent->AppendChild(CreateTextNode("bar"));
MarkNodeContents(parent);
EXPECT_EQ(2u, MarkerController().Markers().size());
@@ -111,7 +111,7 @@ TEST_F(DocumentMarkerControllerTest, NodeWillBeRemovedMarkedByNormalize) {
TEST_F(DocumentMarkerControllerTest, NodeWillBeRemovedMarkedByRemoveChildren) {
SetBodyContent("<b><i>foo</i></b>");
- Element* parent = ToElement(GetDocument().body()->firstChild()->firstChild());
+ auto* parent = To<Element>(GetDocument().body()->firstChild()->firstChild());
MarkNodeContents(parent);
EXPECT_EQ(1u, MarkerController().Markers().size());
parent->RemoveChildren();
@@ -124,8 +124,8 @@ TEST_F(DocumentMarkerControllerTest, NodeWillBeRemovedMarkedByRemoveChildren) {
TEST_F(DocumentMarkerControllerTest, NodeWillBeRemovedByRemoveMarked) {
SetBodyContent("<b><i>foo</i></b>");
{
- Element* parent =
- ToElement(GetDocument().body()->firstChild()->firstChild());
+ auto* parent =
+ To<Element>(GetDocument().body()->firstChild()->firstChild());
MarkNodeContents(parent);
EXPECT_EQ(1u, MarkerController().Markers().size());
parent->RemoveChild(parent->firstChild());
@@ -139,8 +139,8 @@ TEST_F(DocumentMarkerControllerTest, NodeWillBeRemovedByRemoveMarked) {
TEST_F(DocumentMarkerControllerTest, NodeWillBeRemovedMarkedByRemoveAncestor) {
SetBodyContent("<b><i>foo</i></b>");
{
- Element* parent =
- ToElement(GetDocument().body()->firstChild()->firstChild());
+ auto* parent =
+ To<Element>(GetDocument().body()->firstChild()->firstChild());
MarkNodeContents(parent);
EXPECT_EQ(1u, MarkerController().Markers().size());
parent->parentNode()->parentNode()->RemoveChild(parent->parentNode());
@@ -154,8 +154,8 @@ TEST_F(DocumentMarkerControllerTest, NodeWillBeRemovedMarkedByRemoveAncestor) {
TEST_F(DocumentMarkerControllerTest, NodeWillBeRemovedMarkedByRemoveParent) {
SetBodyContent("<b><i>foo</i></b>");
{
- Element* parent =
- ToElement(GetDocument().body()->firstChild()->firstChild());
+ auto* parent =
+ To<Element>(GetDocument().body()->firstChild()->firstChild());
MarkNodeContents(parent);
EXPECT_EQ(1u, MarkerController().Markers().size());
parent->parentNode()->RemoveChild(parent);
@@ -169,8 +169,8 @@ TEST_F(DocumentMarkerControllerTest, NodeWillBeRemovedMarkedByRemoveParent) {
TEST_F(DocumentMarkerControllerTest, NodeWillBeRemovedMarkedByReplaceChild) {
SetBodyContent("<b><i>foo</i></b>");
{
- Element* parent =
- ToElement(GetDocument().body()->firstChild()->firstChild());
+ auto* parent =
+ To<Element>(GetDocument().body()->firstChild()->firstChild());
MarkNodeContents(parent);
EXPECT_EQ(1u, MarkerController().Markers().size());
parent->ReplaceChild(CreateTextNode("bar"), parent->firstChild());
@@ -184,8 +184,8 @@ TEST_F(DocumentMarkerControllerTest, NodeWillBeRemovedMarkedByReplaceChild) {
TEST_F(DocumentMarkerControllerTest, NodeWillBeRemovedBySetInnerHTML) {
SetBodyContent("<b><i>foo</i></b>");
{
- Element* parent =
- ToElement(GetDocument().body()->firstChild()->firstChild());
+ auto* parent =
+ To<Element>(GetDocument().body()->firstChild()->firstChild());
MarkNodeContents(parent);
EXPECT_EQ(1u, MarkerController().Markers().size());
SetBodyContent("");
@@ -201,8 +201,8 @@ TEST_F(DocumentMarkerControllerTest, SynchronousMutationNotificationAfterGC) {
SetBodyContent("<b><i>foo</i></b>");
Persistent<Text> sibling_text = CreateTextNode("bar");
{
- Element* parent =
- ToElement(GetDocument().body()->firstChild()->firstChild());
+ auto* parent =
+ To<Element>(GetDocument().body()->firstChild()->firstChild());
parent->parentNode()->AppendChild(sibling_text);
MarkNodeContents(parent);
EXPECT_EQ(1u, MarkerController().Markers().size());
@@ -221,7 +221,7 @@ TEST_F(DocumentMarkerControllerTest, SynchronousMutationNotificationAfterGC) {
TEST_F(DocumentMarkerControllerTest, UpdateRenderedRects) {
SetBodyContent("<div style='margin: 100px'>foo</div>");
- Element* div = ToElement(GetDocument().body()->firstChild());
+ auto* div = To<Element>(GetDocument().body()->firstChild());
MarkNodeContentsTextMatch(div);
Vector<IntRect> rendered_rects =
MarkerController().LayoutRectsForTextMatchMarkers();
@@ -250,7 +250,7 @@ TEST_F(DocumentMarkerControllerTest, CompositionMarkersNotMerged) {
TEST_F(DocumentMarkerControllerTest, SetMarkerActiveTest) {
SetBodyContent("<b>foo</b>");
- Element* b_element = ToElement(GetDocument().body()->firstChild());
+ auto* b_element = To<Element>(GetDocument().body()->firstChild());
EphemeralRange ephemeral_range = EphemeralRange::RangeOfContents(*b_element);
Position start_b_element =
ToPositionInDOMTree(ephemeral_range.StartPosition());
diff --git a/chromium/third_party/blink/renderer/core/editing/markers/styleable_marker.h b/chromium/third_party/blink/renderer/core/editing/markers/styleable_marker.h
index 86294a6ed88..6d78e8d6a4a 100644
--- a/chromium/third_party/blink/renderer/core/editing/markers/styleable_marker.h
+++ b/chromium/third_party/blink/renderer/core/editing/markers/styleable_marker.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/editing/markers/document_marker.h"
#include "third_party/blink/renderer/platform/wtf/casting.h"
-#include "ui/base/ime/mojo/ime_types.mojom-shared.h"
+#include "ui/base/ime/mojo/ime_types.mojom-blink.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker_replacement_scope.h b/chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker_replacement_scope.h
index a6616c91e77..2591e423fe7 100644
--- a/chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker_replacement_scope.h
+++ b/chromium/third_party/blink/renderer/core/editing/markers/suggestion_marker_replacement_scope.h
@@ -7,7 +7,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/editing/markers/text_match_marker.cc b/chromium/third_party/blink/renderer/core/editing/markers/text_match_marker.cc
index 797cf3c2c68..276a5f1fd46 100644
--- a/chromium/third_party/blink/renderer/core/editing/markers/text_match_marker.cc
+++ b/chromium/third_party/blink/renderer/core/editing/markers/text_match_marker.cc
@@ -27,21 +27,21 @@ bool TextMatchMarker::IsRendered() const {
return layout_status_ == LayoutStatus::kValidNotNull;
}
-bool TextMatchMarker::Contains(const LayoutPoint& point) const {
+bool TextMatchMarker::Contains(const PhysicalOffset& point) const {
DCHECK_EQ(layout_status_, LayoutStatus::kValidNotNull);
- return layout_rect_.Contains(point);
+ return rect_.Contains(point);
}
-void TextMatchMarker::SetLayoutRect(const LayoutRect& rect) {
- if (layout_status_ == LayoutStatus::kValidNotNull && rect == layout_rect_)
+void TextMatchMarker::SetRect(const PhysicalRect& rect) {
+ if (layout_status_ == LayoutStatus::kValidNotNull && rect == rect_)
return;
layout_status_ = LayoutStatus::kValidNotNull;
- layout_rect_ = rect;
+ rect_ = rect;
}
-const LayoutRect& TextMatchMarker::GetLayoutRect() const {
+const PhysicalRect& TextMatchMarker::GetRect() const {
DCHECK_EQ(layout_status_, LayoutStatus::kValidNotNull);
- return layout_rect_;
+ return rect_;
}
void TextMatchMarker::NullifyLayoutRect() {
diff --git a/chromium/third_party/blink/renderer/core/editing/markers/text_match_marker.h b/chromium/third_party/blink/renderer/core/editing/markers/text_match_marker.h
index 88b0acb8c74..5920fac69ed 100644
--- a/chromium/third_party/blink/renderer/core/editing/markers/text_match_marker.h
+++ b/chromium/third_party/blink/renderer/core/editing/markers/text_match_marker.h
@@ -28,7 +28,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_EDITING_MARKERS_TEXT_MATCH_MARKER_H_
#include "third_party/blink/renderer/core/editing/markers/document_marker.h"
-#include "third_party/blink/renderer/platform/geometry/layout_rect.h"
+#include "third_party/blink/renderer/core/layout/geometry/physical_rect.h"
#include "third_party/blink/renderer/platform/wtf/casting.h"
namespace blink {
@@ -54,9 +54,9 @@ class CORE_EXPORT TextMatchMarker final : public DocumentMarker {
void SetIsActiveMatch(bool active);
bool IsRendered() const;
- bool Contains(const LayoutPoint&) const;
- void SetLayoutRect(const LayoutRect&);
- const LayoutRect& GetLayoutRect() const;
+ bool Contains(const PhysicalOffset&) const;
+ void SetRect(const PhysicalRect&);
+ const PhysicalRect& GetRect() const;
void NullifyLayoutRect();
void Invalidate();
@@ -65,7 +65,7 @@ class CORE_EXPORT TextMatchMarker final : public DocumentMarker {
private:
MatchStatus match_status_;
LayoutStatus layout_status_ = LayoutStatus::kInvalid;
- LayoutRect layout_rect_;
+ PhysicalRect rect_;
DISALLOW_COPY_AND_ASSIGN(TextMatchMarker);
};
diff --git a/chromium/third_party/blink/renderer/core/editing/markers/text_match_marker_list_impl.cc b/chromium/third_party/blink/renderer/core/editing/markers/text_match_marker_list_impl.cc
index 6842d1e1233..c1b3d44267b 100644
--- a/chromium/third_party/blink/renderer/core/editing/markers/text_match_marker_list_impl.cc
+++ b/chromium/third_party/blink/renderer/core/editing/markers/text_match_marker_list_impl.cc
@@ -85,8 +85,8 @@ static void UpdateMarkerLayoutRect(const Node& node, TextMatchMarker& marker) {
LocalFrameView* frame_view = node.GetDocument().GetFrame()->View();
DCHECK(frame_view);
- marker.SetLayoutRect(
- frame_view->FrameToDocument(LayoutRect(ComputeTextRect(range))));
+ marker.SetRect(
+ frame_view->FrameToDocument(PhysicalRect(ComputeTextRect(range))));
}
Vector<IntRect> TextMatchMarkerListImpl::LayoutRects(const Node& node) const {
@@ -98,7 +98,7 @@ Vector<IntRect> TextMatchMarkerListImpl::LayoutRects(const Node& node) const {
UpdateMarkerLayoutRect(node, *text_match_marker);
if (!text_match_marker->IsRendered())
continue;
- result.push_back(PixelSnappedIntRect(text_match_marker->GetLayoutRect()));
+ result.push_back(PixelSnappedIntRect(text_match_marker->GetRect()));
}
return result;
diff --git a/chromium/third_party/blink/renderer/core/editing/plain_text_range.h b/chromium/third_party/blink/renderer/core/editing/plain_text_range.h
index 62af2e98095..9a220a89a7c 100644
--- a/chromium/third_party/blink/renderer/core/editing/plain_text_range.h
+++ b/chromium/third_party/blink/renderer/core/editing/plain_text_range.h
@@ -29,7 +29,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/editing/forward.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/wtf_size_t.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/editing/position.cc b/chromium/third_party/blink/renderer/core/editing/position.cc
index 7e6855cf162..eb060bff194 100644
--- a/chromium/third_party/blink/renderer/core/editing/position.cc
+++ b/chromium/third_party/blink/renderer/core/editing/position.cc
@@ -29,7 +29,6 @@
#include <ostream> // NOLINT
#include "third_party/blink/renderer/core/editing/editing_utilities.h"
#include "third_party/blink/renderer/core/editing/text_affinity.h"
-#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
namespace blink {
@@ -710,8 +709,8 @@ void PositionTemplate<Strategy>::ShowTreeForThis() const {
return;
}
LOG(INFO) << "\n"
- << AnchorNode()->ToTreeStringForThis().Utf8().data()
- << ToAnchorTypeAndOffsetString().Utf8().data();
+ << AnchorNode()->ToTreeStringForThis().Utf8()
+ << ToAnchorTypeAndOffsetString().Utf8();
}
template <typename Strategy>
@@ -721,8 +720,8 @@ void PositionTemplate<Strategy>::ShowTreeForThisInFlatTree() const {
return;
}
LOG(INFO) << "\n"
- << AnchorNode()->ToFlatTreeStringForThis().Utf8().data()
- << ToAnchorTypeAndOffsetString().Utf8().data();
+ << AnchorNode()->ToFlatTreeStringForThis().Utf8()
+ << ToAnchorTypeAndOffsetString().Utf8();
}
#endif // DCHECK_IS_ON()
@@ -733,7 +732,7 @@ static std::ostream& PrintPosition(std::ostream& ostream,
if (position.IsNull())
return ostream << "null";
return ostream << position.AnchorNode() << "@"
- << position.ToAnchorTypeAndOffsetString().Utf8().data();
+ << position.ToAnchorTypeAndOffsetString().Utf8();
}
std::ostream& operator<<(std::ostream& ostream,
diff --git a/chromium/third_party/blink/renderer/core/editing/selection.idl b/chromium/third_party/blink/renderer/core/editing/selection.idl
index d6d5cf0464b..c789c376c11 100644
--- a/chromium/third_party/blink/renderer/core/editing/selection.idl
+++ b/chromium/third_party/blink/renderer/core/editing/selection.idl
@@ -29,6 +29,7 @@
// https://w3c.github.io/selection-api/#selection-interface
[
+ Exposed=Window,
ImplementedAs=DOMSelection
] interface Selection {
[MeasureAs=SelectionAnchorNode] readonly attribute Node? anchorNode;
diff --git a/chromium/third_party/blink/renderer/core/editing/selection_adjuster.h b/chromium/third_party/blink/renderer/core/editing/selection_adjuster.h
index 37c31e98965..904b9b21f8b 100644
--- a/chromium/third_party/blink/renderer/core/editing/selection_adjuster.h
+++ b/chromium/third_party/blink/renderer/core/editing/selection_adjuster.h
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/editing/forward.h"
#include "third_party/blink/renderer/core/editing/text_granularity.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 997a60860ff..8a9ee855603 100644
--- a/chromium/third_party/blink/renderer/core/editing/selection_controller.cc
+++ b/chromium/third_party/blink/renderer/core/editing/selection_controller.cc
@@ -335,8 +335,8 @@ bool SelectionController::HandleSingleClick(
// Don't restart the selection when the mouse is pressed on an
// existing selection so we can allow for text dragging.
if (LocalFrameView* view = frame_->View()) {
- const LayoutPoint v_point = view->ConvertFromRootFrame(
- FlooredIntPoint(event.Event().PositionInRootFrame()));
+ const PhysicalOffset v_point(view->ConvertFromRootFrame(
+ FlooredIntPoint(event.Event().PositionInRootFrame())));
if (!extend_selection && this->Selection().Contains(v_point)) {
mouse_down_was_single_click_in_selection_ = true;
if (!event.Event().FromTouch())
@@ -472,8 +472,8 @@ static bool ShouldRespectSVGTextBoundaries(
void SelectionController::UpdateSelectionForMouseDrag(
const HitTestResult& hit_test_result,
- const LayoutPoint& drag_start_pos,
- const LayoutPoint& last_known_mouse_position) {
+ const PhysicalOffset& drag_start_pos,
+ const PhysicalOffset& last_known_mouse_position) {
if (!mouse_down_may_start_select_)
return;
@@ -598,15 +598,6 @@ bool SelectionController::UpdateSelectionForMouseDownDispatchingSelectStart(
return true;
}
-static bool IsEmptyWordRange(const EphemeralRangeInFlatTree range) {
- const String& str = PlainText(
- range, TextIteratorBehavior::Builder()
- .SetEmitsObjectReplacementCharacter(
- HasEditableStyle(*range.StartPosition().AnchorNode()))
- .Build());
- return str.SimplifyWhiteSpace().ContainsOnlyWhitespaceOrEmpty();
-}
-
bool SelectionController::SelectClosestWordFromHitTestResult(
const HitTestResult& result,
AppendTrailingWhitespace append_trailing_whitespace,
@@ -623,9 +614,10 @@ bool SelectionController::SelectClosestWordFromHitTestResult(
// and isn't desirable for touch).
HitTestResult adjusted_hit_test_result = result;
if (select_input_event_type == SelectInputEventType::kTouch &&
- result.GetImage())
+ result.GetImage()) {
adjusted_hit_test_result.SetNodeAndPosition(result.InnerNode(),
- LayoutPoint(0, 0));
+ PhysicalOffset());
+ }
const PositionInFlatTreeWithAffinity pos =
CreateVisiblePosition(
@@ -650,7 +642,17 @@ bool SelectionController::SelectClosestWordFromHitTestResult(
// If node doesn't have text except space, tab or line break, do not
// select that 'empty' area.
EphemeralRangeInFlatTree range = new_selection.ComputeRange();
- if (IsEmptyWordRange(range))
+ const String word = PlainText(
+ range, TextIteratorBehavior::Builder()
+ .SetEmitsObjectReplacementCharacter(
+ HasEditableStyle(*range.StartPosition().AnchorNode()))
+ .Build());
+ if (word.length() >= 1 && word[0] == '\n') {
+ // We should not select word from end of line, e.g.
+ // "(1)|\n(2)" => "(1)^\n(|2)". See http://crbug.com/974569
+ return false;
+ }
+ if (word.SimplifyWhiteSpace().ContainsOnlyWhitespaceOrEmpty())
return false;
Element* const editable =
@@ -1014,14 +1016,15 @@ bool SelectionController::HandleMousePressEvent(
void SelectionController::HandleMouseDraggedEvent(
const MouseEventWithHitTestResults& event,
const IntPoint& mouse_down_pos,
- const LayoutPoint& drag_start_pos,
- const LayoutPoint& last_known_mouse_position) {
+ const PhysicalOffset& drag_start_pos,
+ const PhysicalOffset& last_known_mouse_position) {
TRACE_EVENT0("blink", "SelectionController::handleMouseDraggedEvent");
if (!Selection().IsAvailable())
return;
if (selection_state_ != SelectionState::kExtendedSelection) {
- HitTestRequest request(HitTestRequest::kReadOnly | HitTestRequest::kActive);
+ HitTestRequest request(HitTestRequest::kReadOnly | HitTestRequest::kActive |
+ HitTestRequest::kRetargetForInert);
HitTestLocation location(mouse_down_pos);
HitTestResult result(request, location);
frame_->GetDocument()->GetLayoutView()->HitTest(location, result);
@@ -1034,8 +1037,8 @@ void SelectionController::HandleMouseDraggedEvent(
}
void SelectionController::UpdateSelectionForMouseDrag(
- const LayoutPoint& drag_start_pos,
- const LayoutPoint& last_known_mouse_position) {
+ const PhysicalOffset& drag_start_pos,
+ const PhysicalOffset& last_known_mouse_position) {
LocalFrameView* view = frame_->View();
if (!view)
return;
@@ -1044,7 +1047,8 @@ void SelectionController::UpdateSelectionForMouseDrag(
return;
HitTestRequest request(HitTestRequest::kReadOnly | HitTestRequest::kActive |
- HitTestRequest::kMove);
+ HitTestRequest::kMove |
+ HitTestRequest::kRetargetForInert);
HitTestLocation location(view->ViewportToFrame(last_known_mouse_position));
HitTestResult result(request, location);
layout_view->HitTest(location, result);
@@ -1054,7 +1058,7 @@ void SelectionController::UpdateSelectionForMouseDrag(
bool SelectionController::HandleMouseReleaseEvent(
const MouseEventWithHitTestResults& event,
- const LayoutPoint& drag_start_pos) {
+ const PhysicalOffset& drag_start_pos) {
TRACE_EVENT0("blink", "SelectionController::handleMouseReleaseEvent");
if (!Selection().IsAvailable())
@@ -1068,7 +1072,8 @@ bool SelectionController::HandleMouseReleaseEvent(
// editing, place the caret.
if (mouse_down_was_single_click_in_selection_ &&
selection_state_ != SelectionState::kExtendedSelection &&
- drag_start_pos == FlooredIntPoint(event.Event().PositionInRootFrame()) &&
+ drag_start_pos == PhysicalOffset(FlooredIntPoint(
+ event.Event().PositionInRootFrame())) &&
Selection().ComputeVisibleSelectionInDOMTreeDeprecated().IsRange() &&
event.Event().button != WebPointerProperties::Button::kRight) {
// TODO(editing-dev): Use of UpdateStyleAndLayout
@@ -1203,7 +1208,7 @@ static bool HitTestResultIsMisspelled(const HitTestResult& result) {
void SelectionController::SendContextMenuEvent(
const MouseEventWithHitTestResults& mev,
- const LayoutPoint& position) {
+ const PhysicalOffset& position) {
if (!Selection().IsAvailable())
return;
if (Selection().Contains(position) || mev.GetScrollbar() ||
@@ -1242,8 +1247,8 @@ void SelectionController::PassMousePressEventToSubframe(
// greyed out even though we're clicking on the selection. This looks
// really strange (having the whole frame be greyed out), so we deselect the
// selection.
- IntPoint p = frame_->View()->ConvertFromRootFrame(
- FlooredIntPoint(mev.Event().PositionInRootFrame()));
+ PhysicalOffset p(frame_->View()->ConvertFromRootFrame(
+ FlooredIntPoint(mev.Event().PositionInRootFrame())));
if (!Selection().Contains(p))
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 3bcd0af0406..a92a5b1b16e 100644
--- a/chromium/third_party/blink/renderer/core/editing/selection_controller.h
+++ b/chromium/third_party/blink/renderer/core/editing/selection_controller.h
@@ -55,21 +55,22 @@ class CORE_EXPORT SelectionController final
bool HandleMousePressEvent(const MouseEventWithHitTestResults&);
void HandleMouseDraggedEvent(const MouseEventWithHitTestResults&,
const IntPoint&,
- const LayoutPoint&,
- const LayoutPoint&);
+ const PhysicalOffset&,
+ const PhysicalOffset&);
bool HandleMouseReleaseEvent(const MouseEventWithHitTestResults&,
- const LayoutPoint&);
+ const PhysicalOffset&);
bool HandlePasteGlobalSelection(const WebMouseEvent&);
bool HandleGestureLongPress(const HitTestResult&);
void HandleGestureTwoFingerTap(const GestureEventWithHitTestResults&);
void HandleGestureLongTap(const GestureEventWithHitTestResults&);
- void UpdateSelectionForMouseDrag(const LayoutPoint&, const LayoutPoint&);
+ void UpdateSelectionForMouseDrag(const PhysicalOffset&,
+ const PhysicalOffset&);
void UpdateSelectionForMouseDrag(const HitTestResult&,
- const LayoutPoint&,
- const LayoutPoint&);
+ const PhysicalOffset&,
+ const PhysicalOffset&);
void SendContextMenuEvent(const MouseEventWithHitTestResults&,
- const LayoutPoint&);
+ const PhysicalOffset&);
void PassMousePressEventToSubframe(const MouseEventWithHitTestResults&);
void InitializeSelectionState();
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 64a15750c14..2804becec2d 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
@@ -11,13 +11,28 @@
#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/input/event_handler.h"
+#include "third_party/blink/renderer/core/layout/layout_object.h"
namespace blink {
class SelectionControllerTest : public EditingTestBase {
protected:
+ using AppendTrailingWhitespace =
+ SelectionController::AppendTrailingWhitespace;
+ using SelectInputEventType = SelectionController::SelectInputEventType;
+
SelectionControllerTest() = default;
+ SelectionController& Controller() {
+ return GetFrame().GetEventHandler().GetSelectionController();
+ }
+
+ static PositionWithAffinity GetPositionFromHitTestResult(
+ const HitTestResult& hit_test_result) {
+ return hit_test_result.InnerNode()->GetLayoutObject()->PositionForPoint(
+ hit_test_result.LocalPoint());
+ }
+
VisibleSelection VisibleSelectionInDOMTree() const {
return Selection().ComputeVisibleSelectionInDOMTree();
}
@@ -26,6 +41,10 @@ class SelectionControllerTest : public EditingTestBase {
return Selection().GetSelectionInFlatTree();
}
+ bool SelectClosestWordFromHitTestResult(
+ const HitTestResult& result,
+ AppendTrailingWhitespace append_trailing_whitespace,
+ SelectInputEventType select_input_event_type);
void SetCaretAtHitTestResult(const HitTestResult&);
void SetNonDirectionalSelectionIfNeeded(const SelectionInFlatTree&,
TextGranularity);
@@ -34,6 +53,14 @@ class SelectionControllerTest : public EditingTestBase {
DISALLOW_COPY_AND_ASSIGN(SelectionControllerTest);
};
+bool SelectionControllerTest::SelectClosestWordFromHitTestResult(
+ const HitTestResult& result,
+ AppendTrailingWhitespace append_trailing_whitespace,
+ SelectInputEventType select_input_event_type) {
+ return Controller().SelectClosestWordFromHitTestResult(
+ result, append_trailing_whitespace, select_input_event_type);
+}
+
void SelectionControllerTest::SetCaretAtHitTestResult(
const HitTestResult& hit_test_result) {
GetFrame().GetEventHandler().GetSelectionController().SetCaretAtHitTestResult(
@@ -205,4 +232,64 @@ TEST_F(SelectionControllerTest, AdjustSelectionWithTrailingWhitespace) {
EXPECT_EQ(PositionInFlatTree::AfterNode(*input), result.ComputeEndPosition());
}
+// For http://crbug.com/974569
+TEST_F(SelectionControllerTest,
+ SelectClosestWordFromHitTestResultAtEndOfLine1) {
+ InsertStyleElement("body { margin: 0; padding: 0; font: 10px monospace; }");
+ SetBodyContent("<pre>(1)\n(2)</pre>");
+
+ // Click/Tap after "(1)"
+ HitTestLocation location(IntPoint(40, 10));
+ HitTestResult result =
+ GetFrame().GetEventHandler().HitTestResultAtLocation(location);
+ ASSERT_EQ("<pre>(1)|\n(2)</pre>",
+ GetSelectionTextFromBody(
+ SelectionInDOMTree::Builder()
+ .Collapse(GetPositionFromHitTestResult(result))
+ .Build()));
+
+ // Select word by mouse
+ EXPECT_TRUE(SelectClosestWordFromHitTestResult(
+ result, AppendTrailingWhitespace::kDontAppend,
+ SelectInputEventType::kMouse));
+ EXPECT_EQ("<pre>(1)^\n(|2)</pre>", GetSelectionTextFromBody());
+
+ // Select word by tap
+ EXPECT_FALSE(SelectClosestWordFromHitTestResult(
+ result, AppendTrailingWhitespace::kDontAppend,
+ SelectInputEventType::kTouch));
+ EXPECT_EQ("<pre>(1)^\n(|2)</pre>", GetSelectionTextFromBody())
+ << "selection isn't changed";
+}
+
+TEST_F(SelectionControllerTest,
+ SelectClosestWordFromHitTestResultAtEndOfLine2) {
+ InsertStyleElement("body { margin: 0; padding: 0; font: 10px monospace; }");
+ SetBodyContent("<pre>ab:\ncd</pre>");
+
+ // Click/Tap after "(1)"
+ HitTestLocation location(IntPoint(40, 10));
+ HitTestResult result =
+ GetFrame().GetEventHandler().HitTestResultAtLocation(location);
+ ASSERT_EQ("<pre>ab:|\ncd</pre>",
+ GetSelectionTextFromBody(
+ SelectionInDOMTree::Builder()
+ .Collapse(GetPositionFromHitTestResult(result))
+ .Build()));
+
+ // Select word by mouse
+ EXPECT_TRUE(SelectClosestWordFromHitTestResult(
+ result, AppendTrailingWhitespace::kDontAppend,
+ SelectInputEventType::kMouse));
+ // TODO(yosin): This should be "<pre>ab:^\ncd|</pre>"
+ EXPECT_EQ("<pre>ab:^\nc|d</pre>", GetSelectionTextFromBody());
+
+ // Select word by tap
+ EXPECT_FALSE(SelectClosestWordFromHitTestResult(
+ result, AppendTrailingWhitespace::kDontAppend,
+ SelectInputEventType::kTouch));
+ EXPECT_EQ("<pre>ab:^\nc|d</pre>", GetSelectionTextFromBody())
+ << "selection isn't changed";
+}
+
} // namespace blink
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 a79885a1c0d..bc8ade5dd94 100644
--- a/chromium/third_party/blink/renderer/core/editing/selection_editor.cc
+++ b/chromium/third_party/blink/renderer/core/editing/selection_editor.cc
@@ -173,7 +173,7 @@ static Position ComputePositionForChildrenRemoval(const Position& position,
#endif
if (!container.ContainsIncludingHostElements(*node))
return position;
- if (auto* element = ToElementOrNull(container)) {
+ if (auto* element = DynamicTo<Element>(container)) {
if (auto* shadow_root = element->GetShadowRoot()) {
// Removal of light children does not affect position in the
// shadow tree.
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 f17b36f4aae..1620aea5126 100644
--- a/chromium/third_party/blink/renderer/core/editing/selection_modifier.h
+++ b/chromium/third_party/blink/renderer/core/editing/selection_modifier.h
@@ -32,7 +32,7 @@
#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/geometry/layout_unit.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/editing/selection_modifier_line.cc b/chromium/third_party/blink/renderer/core/editing/selection_modifier_line.cc
index 85a41e063cc..b69cd3379ce 100644
--- a/chromium/third_party/blink/renderer/core/editing/selection_modifier_line.cc
+++ b/chromium/third_party/blink/renderer/core/editing/selection_modifier_line.cc
@@ -109,7 +109,7 @@ class AbstractLineBox {
return AbstractLineBox();
}
- LayoutPoint AbsoluteLineDirectionPointToLocalPointInBlock(
+ PhysicalOffset AbsoluteLineDirectionPointToLocalPointInBlock(
LayoutUnit line_direction_point) {
DCHECK(!IsNull());
const LayoutBlockFlow& containing_block = GetBlock();
@@ -121,31 +121,24 @@ class AbstractLineBox {
PhysicalOffset(containing_block.ScrolledContentOffset());
}
- if (containing_block.Style()->IsHorizontalWritingMode()) {
- return LayoutPoint(
- LayoutUnit(line_direction_point - absolute_block_point.left),
- BlockDirectionPointInLine());
+ if (containing_block.IsHorizontalWritingMode()) {
+ return PhysicalOffset(line_direction_point - absolute_block_point.left,
+ PhysicalBlockOffset());
}
-
- return LayoutPoint(
- BlockDirectionPointInLine(),
- LayoutUnit(line_direction_point - absolute_block_point.top));
+ return PhysicalOffset(PhysicalBlockOffset(),
+ line_direction_point - absolute_block_point.top);
}
const LayoutObject* ClosestLeafChildForPoint(
- const LayoutPoint& point,
+ const PhysicalOffset& point,
bool only_editable_leaves) const {
DCHECK(!IsNull());
if (IsOldLayout()) {
- return GetRootInlineBox().ClosestLeafChildForPoint(point,
- only_editable_leaves);
+ return GetRootInlineBox().ClosestLeafChildForPoint(
+ GetBlock().FlipForWritingMode(point), only_editable_leaves);
}
- const LayoutSize unit_square(1, 1);
- const PhysicalRect physical_rect =
- GetBlock().FlipForWritingMode(LayoutRect(point, unit_square));
- const PhysicalOffset physical_point = physical_rect.offset;
const PhysicalOffset local_physical_point =
- physical_point - ng_box_fragment_->Children()[ng_child_index_].offset;
+ point - ng_box_fragment_->Children()[ng_child_index_].offset;
return GetLineBoxFragment().ClosestLeafChildForPoint(local_physical_point,
only_editable_leaves);
}
@@ -173,17 +166,17 @@ class AbstractLineBox {
return *To<LayoutBlockFlow>(ng_box_fragment_->GetLayoutObject());
}
- LayoutUnit BlockDirectionPointInLine() const {
+ LayoutUnit PhysicalBlockOffset() const {
DCHECK(!IsNull());
- if (IsOldLayout())
- return GetRootInlineBox().BlockDirectionPointInLine();
+ if (IsOldLayout()) {
+ return GetBlock().FlipForWritingMode(
+ GetRootInlineBox().BlockDirectionPointInLine());
+ }
const PhysicalOffset physical_offset =
ng_box_fragment_->Children()[ng_child_index_].offset;
- const LogicalOffset logical_offset = physical_offset.ConvertToLogical(
- ng_box_fragment_->Style().GetWritingMode(),
- GetLineBoxFragment().BaseDirection(), ng_box_fragment_->Size(),
- GetLineBoxFragment().Size());
- return logical_offset.block_offset;
+ return ng_box_fragment_->Style().IsHorizontalWritingMode()
+ ? physical_offset.top
+ : physical_offset.left;
}
bool IsOldLayout() const { return type_ == Type::kOldLayout; }
@@ -425,7 +418,7 @@ VisiblePosition SelectionModifier::PreviousLinePosition(
if (!line.IsNull()) {
// FIXME: Can be wrong for multi-column layout and with transforms.
- LayoutPoint point_in_line =
+ PhysicalOffset point_in_line =
line.AbsoluteLineDirectionPointToLocalPointInBlock(
line_direction_point);
const LayoutObject* closest_leaf_child =
@@ -495,7 +488,7 @@ VisiblePosition SelectionModifier::NextLinePosition(
if (!line.IsNull()) {
// FIXME: Can be wrong for multi-column layout and with transforms.
- LayoutPoint point_in_line =
+ PhysicalOffset point_in_line =
line.AbsoluteLineDirectionPointToLocalPointInBlock(
line_direction_point);
const LayoutObject* closest_leaf_child =
diff --git a/chromium/third_party/blink/renderer/core/editing/selection_template.cc b/chromium/third_party/blink/renderer/core/editing/selection_template.cc
index ed84f0c5087..8a6a042da43 100644
--- a/chromium/third_party/blink/renderer/core/editing/selection_template.cc
+++ b/chromium/third_party/blink/renderer/core/editing/selection_template.cc
@@ -133,11 +133,8 @@ void SelectionTemplate<Strategy>::ShowTreeForThis() const {
->ToMarkedTreeString(base_.AnchorNode(), "B",
extent_.AnchorNode(), "E")
.Utf8()
- .data()
- << "base: " << base_.ToAnchorTypeAndOffsetString().Utf8().data()
- << "\n"
- << "extent: "
- << extent_.ToAnchorTypeAndOffsetString().Utf8().data();
+ << "base: " << base_.ToAnchorTypeAndOffsetString().Utf8() << "\n"
+ << "extent: " << extent_.ToAnchorTypeAndOffsetString().Utf8();
}
#endif
diff --git a/chromium/third_party/blink/renderer/core/editing/selection_template.h b/chromium/third_party/blink/renderer/core/editing/selection_template.h
index 19083b68305..80b9ff306c5 100644
--- a/chromium/third_party/blink/renderer/core/editing/selection_template.h
+++ b/chromium/third_party/blink/renderer/core/editing/selection_template.h
@@ -12,7 +12,7 @@
#include "third_party/blink/renderer/core/editing/position.h"
#include "third_party/blink/renderer/core/editing/selection_type.h"
#include "third_party/blink/renderer/core/editing/text_affinity.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 c8404c7a8be..88ad33f41fb 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
@@ -183,7 +183,7 @@ bool MarkupAccumulator::ShouldIgnoreElement(const Element& element) const {
AtomicString MarkupAccumulator::AppendElement(const Element& element) {
const ElementSerializationData data = AppendStartTagOpen(element);
- if (SerializeAsHTMLDocument(element)) {
+ if (SerializeAsHTML()) {
// https://html.spec.whatwg.org/C/#html-fragment-serialisation-algorithm
AttributeCollection attributes = element.Attributes();
@@ -225,7 +225,7 @@ MarkupAccumulator::ElementSerializationData
MarkupAccumulator::AppendStartTagOpen(const Element& element) {
ElementSerializationData data;
data.serialized_prefix_ = element.prefix();
- if (SerializeAsHTMLDocument(element)) {
+ if (SerializeAsHTML()) {
formatter_.AppendStartTagOpen(markup_, element);
return data;
}
@@ -349,7 +349,7 @@ void MarkupAccumulator::AppendStartTagClose(const Element& element) {
void MarkupAccumulator::AppendAttribute(const Element& element,
const Attribute& attribute) {
String value = formatter_.ResolveURLIfNeeded(element, attribute);
- if (SerializeAsHTMLDocument(element)) {
+ if (SerializeAsHTML()) {
MarkupFormatter::AppendAttributeAsHTML(markup_, attribute, value);
} else {
AppendAttributeAsXMLWithNamespace(element, attribute, value);
@@ -446,7 +446,7 @@ EntityMask MarkupAccumulator::EntityMaskForText(const Text& text) const {
}
void MarkupAccumulator::PushNamespaces(const Element& element) {
- if (SerializeAsHTMLDocument(element))
+ if (SerializeAsHTML())
return;
DCHECK_GT(namespace_stack_.size(), 0u);
// TODO(tkent): Avoid to copy the whole map.
@@ -457,7 +457,7 @@ void MarkupAccumulator::PushNamespaces(const Element& element) {
}
void MarkupAccumulator::PopNamespaces(const Element& element) {
- if (SerializeAsHTMLDocument(element))
+ if (SerializeAsHTML())
return;
namespace_stack_.pop_back();
}
@@ -532,8 +532,8 @@ AtomicString MarkupAccumulator::GeneratePrefix(
return generated_prefix;
}
-bool MarkupAccumulator::SerializeAsHTMLDocument(const Node& node) const {
- return formatter_.SerializeAsHTMLDocument(node);
+bool MarkupAccumulator::SerializeAsHTML() const {
+ return formatter_.SerializeAsHTML();
}
std::pair<Node*, Element*> MarkupAccumulator::GetAuxiliaryDOMTree(
@@ -553,7 +553,7 @@ void MarkupAccumulator::SerializeNodesWithNamespaces(
return;
}
- const Element& target_element = ToElement(target_node);
+ const auto& target_element = To<Element>(target_node);
if (ShouldIgnoreElement(target_element))
return;
@@ -563,8 +563,8 @@ void MarkupAccumulator::SerializeNodesWithNamespaces(
if (!children_only)
prefix_override = AppendElement(target_element);
- bool has_end_tag = !(SerializeAsHTMLDocument(target_element) &&
- ElementCannotHaveEndTag(target_element));
+ bool has_end_tag =
+ !(SerializeAsHTML() && ElementCannotHaveEndTag(target_element));
if (has_end_tag) {
const Node* parent = &target_element;
if (auto* template_element = ToHTMLTemplateElementOrNull(target_element))
@@ -596,7 +596,7 @@ void MarkupAccumulator::SerializeNodesWithNamespaces(
template <typename Strategy>
String MarkupAccumulator::SerializeNodes(const Node& target_node,
ChildrenOnly children_only) {
- if (!SerializeAsHTMLDocument(target_node)) {
+ if (!SerializeAsHTML()) {
// https://w3c.github.io/DOM-Parsing/#dfn-xml-serialization
DCHECK_EQ(namespace_stack_.size(), 0u);
// 2. Let prefix map be a new namespace prefix map.
diff --git a/chromium/third_party/blink/renderer/core/editing/serializers/markup_accumulator.h b/chromium/third_party/blink/renderer/core/editing/serializers/markup_accumulator.h
index 4f00b51b223..0b936ae89aa 100644
--- a/chromium/third_party/blink/renderer/core/editing/serializers/markup_accumulator.h
+++ b/chromium/third_party/blink/renderer/core/editing/serializers/markup_accumulator.h
@@ -46,8 +46,7 @@ class MarkupAccumulator {
STACK_ALLOCATED();
public:
- MarkupAccumulator(AbsoluteURLs,
- SerializationType = SerializationType::kAsOwnerDocument);
+ MarkupAccumulator(AbsoluteURLs, SerializationType);
virtual ~MarkupAccumulator();
template <typename Strategy>
@@ -62,7 +61,7 @@ class MarkupAccumulator {
StringBuilder markup_;
private:
- bool SerializeAsHTMLDocument(const Node&) const;
+ bool SerializeAsHTML() const;
String ToString() { return markup_.ToString(); }
void AppendString(const String&);
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 5837555ddcd..83320613a45 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
@@ -51,7 +51,7 @@ using namespace html_names;
struct EntityDescription {
UChar entity;
- const CString& reference;
+ const std::string& reference;
EntityMask mask;
};
@@ -71,8 +71,8 @@ static inline void AppendCharactersReplacingEntitiesInternal(
entity_maps[entity_index].mask & entity_mask) {
result.Append(text + position_after_last_entity,
i - position_after_last_entity);
- const CString& replacement = entity_maps[entity_index].reference;
- result.Append(replacement.data(), replacement.length());
+ const std::string& replacement = entity_maps[entity_index].reference;
+ result.Append(replacement.c_str(), replacement.length());
position_after_last_entity = i + 1;
break;
}
@@ -88,14 +88,14 @@ void MarkupFormatter::AppendCharactersReplacingEntities(
unsigned offset,
unsigned length,
EntityMask entity_mask) {
- DEFINE_STATIC_LOCAL(const CString, amp_reference, ("&amp;"));
- DEFINE_STATIC_LOCAL(const CString, lt_reference, ("&lt;"));
- DEFINE_STATIC_LOCAL(const CString, gt_reference, ("&gt;"));
- DEFINE_STATIC_LOCAL(const CString, quot_reference, ("&quot;"));
- DEFINE_STATIC_LOCAL(const CString, nbsp_reference, ("&nbsp;"));
- DEFINE_STATIC_LOCAL(const CString, tab_reference, ("&#9;"));
- DEFINE_STATIC_LOCAL(const CString, line_feed_reference, ("&#10;"));
- DEFINE_STATIC_LOCAL(const CString, carriage_return_reference, ("&#13;"));
+ DEFINE_STATIC_LOCAL(const std::string, amp_reference, ("&amp;"));
+ DEFINE_STATIC_LOCAL(const std::string, lt_reference, ("&lt;"));
+ DEFINE_STATIC_LOCAL(const std::string, gt_reference, ("&gt;"));
+ DEFINE_STATIC_LOCAL(const std::string, quot_reference, ("&quot;"));
+ DEFINE_STATIC_LOCAL(const std::string, nbsp_reference, ("&nbsp;"));
+ DEFINE_STATIC_LOCAL(const std::string, tab_reference, ("&#9;"));
+ DEFINE_STATIC_LOCAL(const std::string, line_feed_reference, ("&#10;"));
+ DEFINE_STATIC_LOCAL(const std::string, carriage_return_reference, ("&#13;"));
static const EntityDescription kEntityMaps[] = {
{'&', amp_reference, kEntityAmp},
@@ -379,7 +379,7 @@ void MarkupFormatter::AppendCDATASection(StringBuilder& result,
}
EntityMask MarkupFormatter::EntityMaskForText(const Text& text) const {
- if (!SerializeAsHTMLDocument(text))
+ if (!SerializeAsHTML())
return kEntityMaskInPCDATA;
// TODO(hajimehoshi): We need to switch EditingStrategy.
@@ -405,7 +405,7 @@ EntityMask MarkupFormatter::EntityMaskForText(const Text& text) const {
// separate end tag.
// 4. Other elements self-close.
bool MarkupFormatter::ShouldSelfClose(const Element& element) const {
- if (SerializeAsHTMLDocument(element))
+ if (SerializeAsHTML())
return false;
if (element.HasChildren())
return false;
@@ -414,10 +414,8 @@ bool MarkupFormatter::ShouldSelfClose(const Element& element) const {
return true;
}
-bool MarkupFormatter::SerializeAsHTMLDocument(const Node& node) const {
- if (serialization_type_ == SerializationType::kForcedXML)
- return false;
- return node.GetDocument().IsHTMLDocument();
+bool MarkupFormatter::SerializeAsHTML() const {
+ return serialization_type_ == SerializationType::kHTML;
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/editing/serializers/markup_formatter.h b/chromium/third_party/blink/renderer/core/editing/serializers/markup_formatter.h
index d7bd90f8cc9..48112fc4181 100644
--- a/chromium/third_party/blink/renderer/core/editing/serializers/markup_formatter.h
+++ b/chromium/third_party/blink/renderer/core/editing/serializers/markup_formatter.h
@@ -63,7 +63,7 @@ enum EntityMask {
kEntityMaskInHTMLAttributeValue = kEntityAmp | kEntityQuot | kEntityNbsp,
};
-enum class SerializationType { kAsOwnerDocument, kForcedXML };
+enum class SerializationType { kHTML, kXML };
class MarkupFormatter final {
STACK_ALLOCATED();
@@ -94,8 +94,7 @@ class MarkupFormatter final {
const String& data);
static void AppendXMLDeclaration(StringBuilder&, const Document&);
- MarkupFormatter(AbsoluteURLs,
- SerializationType = SerializationType::kAsOwnerDocument);
+ MarkupFormatter(AbsoluteURLs, SerializationType);
~MarkupFormatter();
void AppendStartMarkup(StringBuilder&, const Node&);
@@ -105,7 +104,7 @@ class MarkupFormatter final {
const AtomicString& prefix,
const AtomicString& local_name);
- bool SerializeAsHTMLDocument(const Node&) const;
+ bool SerializeAsHTML() const;
void AppendText(StringBuilder&, const Text&);
// Serialize '<' and the element name.
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 d1ed7fd0184..7810ae7f6ac 100644
--- a/chromium/third_party/blink/renderer/core/editing/serializers/serialization.cc
+++ b/chromium/third_party/blink/renderer/core/editing/serializers/serialization.cc
@@ -461,7 +461,10 @@ String CreateMarkup(const Node* node,
if (!node)
return "";
- MarkupAccumulator accumulator(should_resolve_urls);
+ MarkupAccumulator accumulator(should_resolve_urls,
+ node->GetDocument().IsHTMLDocument()
+ ? SerializationType::kHTML
+ : SerializationType::kXML);
return accumulator.SerializeNodes<EditingStrategy>(*node, children_only);
}
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 a9e90b2075f..14b776f23b1 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
@@ -58,7 +58,9 @@ StyledMarkupAccumulator::StyledMarkupAccumulator(
Document* document,
AnnotateForInterchange should_annotate,
ConvertBlocksToInlines convert_blocks_to_inlines)
- : formatter_(should_resolve_urls),
+ : formatter_(should_resolve_urls,
+ document->IsHTMLDocument() ? SerializationType::kHTML
+ : SerializationType::kXML),
start_(start),
end_(end),
document_(document),
@@ -174,7 +176,7 @@ void StyledMarkupAccumulator::AppendAttribute(StringBuilder& result,
const Element& element,
const Attribute& attribute) {
String value = formatter_.ResolveURLIfNeeded(element, attribute);
- if (formatter_.SerializeAsHTMLDocument(element)) {
+ if (formatter_.SerializeAsHTML()) {
MarkupFormatter::AppendAttributeAsHTML(result, attribute, value);
} else {
MarkupFormatter::AppendAttributeAsXMLWithoutNamespace(result, attribute,
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 502f8dd2a4f..43c63a99348 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
@@ -359,27 +359,23 @@ Node* StyledMarkupTraverser<Strategy>::Traverse(Node* start_node,
} else {
next = Strategy::Next(*n);
if (IsEnclosingBlock(n) && CanHaveChildrenForEditing(n) &&
- next == past_end && !ContainsOnlyBRElement(ToElement(*n))) {
+ next == past_end && !ContainsOnlyBRElement(To<Element>(*n))) {
// Don't write out empty block containers that aren't fully selected
// unless the block container only contains br element.
continue;
}
- if (!n->GetLayoutObject() &&
- (!n->IsElementNode() || !ToElement(n)->HasDisplayContentsStyle()) &&
- !EnclosingElementWithTag(FirstPositionInOrBeforeNode(*n),
- kSelectTag)) {
- next = Strategy::NextSkippingChildren(*n);
- // Don't skip over pastEnd.
- if (past_end && Strategy::IsDescendantOf(*past_end, *n))
- next = past_end;
- } else {
+ auto* element = DynamicTo<Element>(n);
+ if (n->GetLayoutObject() ||
+ (element && element->HasDisplayContentsStyle()) ||
+ EnclosingElementWithTag(FirstPositionInOrBeforeNode(*n),
+ kSelectTag)) {
// Add the node to the markup if we're not skipping the descendants
AppendStartMarkup(*n);
// If node has no children, close the tag now.
if (Strategy::HasChildren(*n)) {
- if (next == past_end && ContainsOnlyBRElement(ToElement(*n))) {
+ if (next == past_end && ContainsOnlyBRElement(*element)) {
// node is not fully selected and node contains only one br element
// as child. Close the br tag now.
AppendStartMarkup(*next);
@@ -392,6 +388,11 @@ Node* StyledMarkupTraverser<Strategy>::Traverse(Node* start_node,
}
AppendEndMarkup(*n);
last_closed = n;
+ } else {
+ next = Strategy::NextSkippingChildren(*n);
+ // Don't skip over pastEnd.
+ if (past_end && Strategy::IsDescendantOf(*past_end, *n))
+ next = past_end;
}
}
@@ -466,15 +467,15 @@ void StyledMarkupTraverser<Strategy>::WrapWithNode(ContainerNode& node,
accumulator_->PushMarkup(markup.ToString());
return;
}
- if (!node.IsElementNode())
+ auto* element = DynamicTo<Element>(node);
+ if (!element)
return;
- Element& element = ToElement(node);
- if (ShouldApplyWrappingStyle(element) || NeedsInlineStyle(element))
- accumulator_->AppendElementWithInlineStyle(markup, element, style);
+ if (ShouldApplyWrappingStyle(*element) || NeedsInlineStyle(*element))
+ accumulator_->AppendElementWithInlineStyle(markup, *element, style);
else
- accumulator_->AppendElement(markup, element);
+ accumulator_->AppendElement(markup, *element);
accumulator_->PushMarkup(markup.ToString());
- accumulator_->AppendEndTag(ToElement(node));
+ accumulator_->AppendEndTag(*element);
}
template <typename Strategy>
@@ -482,9 +483,11 @@ EditingStyle* StyledMarkupTraverser<Strategy>::CreateInlineStyleIfNeeded(
Node& node) {
if (!accumulator_)
return nullptr;
- if (!node.IsElementNode())
+
+ auto* element = DynamicTo<Element>(node);
+ if (!element)
return nullptr;
- EditingStyle* inline_style = CreateInlineStyle(ToElement(node));
+ EditingStyle* inline_style = CreateInlineStyle(*element);
if (ShouldConvertBlocksToInlines() && IsEnclosingBlock(&node))
inline_style->ForceInline();
return inline_style;
@@ -517,7 +520,7 @@ void StyledMarkupTraverser<Strategy>::AppendStartMarkup(Node& node) {
break;
}
case Node::kElementNode: {
- Element& element = ToElement(node);
+ auto& element = To<Element>(node);
if ((element.IsHTMLElement() && ShouldAnnotate()) ||
ShouldApplyWrappingStyle(element)) {
EditingStyle* inline_style = CreateInlineStyle(element);
@@ -535,9 +538,10 @@ void StyledMarkupTraverser<Strategy>::AppendStartMarkup(Node& node) {
template <typename Strategy>
void StyledMarkupTraverser<Strategy>::AppendEndMarkup(Node& node) {
- if (!accumulator_ || !node.IsElementNode())
+ auto* element = DynamicTo<Element>(node);
+ if (!accumulator_ || !element)
return;
- accumulator_->AppendEndTag(ToElement(node));
+ accumulator_->AppendEndTag(*element);
}
template <typename Strategy>
diff --git a/chromium/third_party/blink/renderer/core/editing/serializers/styled_markup_serializer_test.cc b/chromium/third_party/blink/renderer/core/editing/serializers/styled_markup_serializer_test.cc
index 9179f50a12a..2ad2264d0a4 100644
--- a/chromium/third_party/blink/renderer/core/editing/serializers/styled_markup_serializer_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/serializers/styled_markup_serializer_test.cc
@@ -41,7 +41,7 @@ std::string StyledMarkupSerializerTest::Serialize(
GetDocument().body(), PositionAnchorType::kBeforeChildren);
PositionTemplate<Strategy> end = PositionTemplate<Strategy>(
GetDocument().body(), PositionAnchorType::kAfterChildren);
- return CreateMarkup(start, end, should_annotate).Utf8().data();
+ return CreateMarkup(start, end, should_annotate).Utf8();
}
template <typename Strategy>
@@ -49,7 +49,7 @@ std::string StyledMarkupSerializerTest::SerializePart(
const PositionTemplate<Strategy>& start,
const PositionTemplate<Strategy>& end,
AnnotateForInterchange should_annotate) {
- return CreateMarkup(start, end, should_annotate).Utf8().data();
+ return CreateMarkup(start, end, should_annotate).Utf8();
}
TEST_F(StyledMarkupSerializerTest, TextOnly) {
diff --git a/chromium/third_party/blink/renderer/core/editing/set_selection_options.h b/chromium/third_party/blink/renderer/core/editing/set_selection_options.h
index 9cbb5824a57..4d1ec501c82 100644
--- a/chromium/third_party/blink/renderer/core/editing/set_selection_options.h
+++ b/chromium/third_party/blink/renderer/core/editing/set_selection_options.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/editing/text_granularity.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 44875dbb12a..a01a37b8201 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
@@ -63,11 +63,10 @@ const Element* ColdModeSpellCheckRequester::CurrentFocusedEditable() const {
if (position.IsNull())
return nullptr;
- const ContainerNode* root = HighestEditableRoot(position);
- if (!root || !root->isConnected() || !root->IsElementNode())
+ const auto* element = DynamicTo<Element>(HighestEditableRoot(position));
+ if (!element || !element->isConnected())
return nullptr;
- const Element* element = ToElement(root);
if (!element->IsSpellCheckingEnabled() ||
!SpellChecker::IsSpellCheckingEnabledAt(position))
return nullptr;
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 d0cb5f66b49..33c45dbf40e 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
@@ -28,13 +28,15 @@ namespace blink {
namespace {
-constexpr TimeDelta kColdModeTimerInterval = TimeDelta::FromMilliseconds(1000);
-constexpr TimeDelta kConsecutiveColdModeTimerInterval =
- TimeDelta::FromMilliseconds(200);
+constexpr base::TimeDelta kColdModeTimerInterval =
+ base::TimeDelta::FromMilliseconds(1000);
+constexpr base::TimeDelta kConsecutiveColdModeTimerInterval =
+ base::TimeDelta::FromMilliseconds(200);
const int kHotModeRequestTimeoutMS = 200;
const int kInvalidHandle = -1;
const int kDummyHandleForForcedInvocation = -2;
-constexpr TimeDelta kIdleSpellcheckTestTimeout = TimeDelta::FromSeconds(10);
+constexpr base::TimeDelta kIdleSpellcheckTestTimeout =
+ base::TimeDelta::FromSeconds(10);
} // namespace
@@ -140,9 +142,9 @@ void IdleSpellCheckController::SetNeedsColdModeInvocation() {
return;
DCHECK(!cold_mode_timer_.IsActive());
- TimeDelta interval = state_ == State::kInColdModeInvocation
- ? kConsecutiveColdModeTimerInterval
- : kColdModeTimerInterval;
+ base::TimeDelta interval = state_ == State::kInColdModeInvocation
+ ? kConsecutiveColdModeTimerInterval
+ : kColdModeTimerInterval;
cold_mode_timer_.StartOneShot(interval, FROM_HERE);
state_ = State::kColdModeTimerStarted;
}
@@ -227,7 +229,7 @@ void IdleSpellCheckController::ForceInvocationForTesting() {
return;
auto* deadline = MakeGarbageCollected<IdleDeadline>(
- CurrentTimeTicks() + kIdleSpellcheckTestTimeout,
+ base::TimeTicks::Now() + kIdleSpellcheckTestTimeout,
IdleDeadline::CallbackType::kCalledWhenIdle);
switch (state_) {
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 05bea664cf8..c84093f2124 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
@@ -38,7 +38,7 @@
#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/forms/text_control_element.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
namespace blink {
@@ -198,8 +198,8 @@ bool SpellCheckRequester::RequestCheckingFor(const EphemeralRange& range,
if (!request)
return false;
- const TimeTicks current_request_time = CurrentTimeTicks();
- if (request_num == 0 && last_request_time_ > TimeTicks()) {
+ const base::TimeTicks current_request_time = base::TimeTicks::Now();
+ if (request_num == 0 && last_request_time_ > base::TimeTicks()) {
UMA_HISTOGRAM_TIMES("WebCore.SpellChecker.RequestInterval",
current_request_time - last_request_time_);
}
@@ -297,7 +297,7 @@ void SpellCheckRequester::DidCheck(int sequence) {
ClearProcessingRequest();
if (!request_queue_.IsEmpty())
- timer_to_process_queued_request_.StartOneShot(TimeDelta(), FROM_HERE);
+ timer_to_process_queued_request_.StartOneShot(base::TimeDelta(), FROM_HERE);
}
void SpellCheckRequester::DidCheckSucceed(
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 8a2196688c7..c1c350854e3 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
@@ -121,7 +121,7 @@ class CORE_EXPORT SpellCheckRequester final
int last_request_sequence_;
int last_processed_sequence_;
- TimeTicks last_request_time_;
+ base::TimeTicks last_request_time_;
TaskRunnerTimer<SpellCheckRequester> timer_to_process_queued_request_;
diff --git a/chromium/third_party/blink/renderer/core/editing/spellcheck/text_checking.h b/chromium/third_party/blink/renderer/core/editing/spellcheck/text_checking.h
index a629159462e..7fa929d7b66 100644
--- a/chromium/third_party/blink/renderer/core/editing/spellcheck/text_checking.h
+++ b/chromium/third_party/blink/renderer/core/editing/spellcheck/text_checking.h
@@ -31,7 +31,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_EDITING_SPELLCHECK_TEXT_CHECKING_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_EDITING_SPELLCHECK_TEXT_CHECKING_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
diff --git a/chromium/third_party/blink/renderer/core/editing/state_machines/backspace_state_machine.h b/chromium/third_party/blink/renderer/core/editing/state_machines/backspace_state_machine.h
index 5ae422a1032..2b085cd6b01 100644
--- a/chromium/third_party/blink/renderer/core/editing/state_machines/backspace_state_machine.h
+++ b/chromium/third_party/blink/renderer/core/editing/state_machines/backspace_state_machine.h
@@ -10,7 +10,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/editing/state_machines/text_segmentation_machine_state.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/unicode.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/editing/state_machines/backward_code_point_state_machine.h b/chromium/third_party/blink/renderer/core/editing/state_machines/backward_code_point_state_machine.h
index 8a6be8d9b7f..3b136f522a4 100644
--- a/chromium/third_party/blink/renderer/core/editing/state_machines/backward_code_point_state_machine.h
+++ b/chromium/third_party/blink/renderer/core/editing/state_machines/backward_code_point_state_machine.h
@@ -8,7 +8,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/editing/state_machines/text_segmentation_machine_state.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/unicode.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/editing/state_machines/backward_grapheme_boundary_state_machine.h b/chromium/third_party/blink/renderer/core/editing/state_machines/backward_grapheme_boundary_state_machine.h
index efac1ee242b..9e201fdfb0d 100644
--- a/chromium/third_party/blink/renderer/core/editing/state_machines/backward_grapheme_boundary_state_machine.h
+++ b/chromium/third_party/blink/renderer/core/editing/state_machines/backward_grapheme_boundary_state_machine.h
@@ -10,7 +10,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/editing/state_machines/text_segmentation_machine_state.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/unicode.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/editing/state_machines/forward_code_point_state_machine.h b/chromium/third_party/blink/renderer/core/editing/state_machines/forward_code_point_state_machine.h
index dda9b50eb1e..78b0e7775d8 100644
--- a/chromium/third_party/blink/renderer/core/editing/state_machines/forward_code_point_state_machine.h
+++ b/chromium/third_party/blink/renderer/core/editing/state_machines/forward_code_point_state_machine.h
@@ -8,7 +8,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/editing/state_machines/text_segmentation_machine_state.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/unicode.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/editing/state_machines/forward_grapheme_boundary_state_machine.h b/chromium/third_party/blink/renderer/core/editing/state_machines/forward_grapheme_boundary_state_machine.h
index 9e612dfd5c9..f4362e3a517 100644
--- a/chromium/third_party/blink/renderer/core/editing/state_machines/forward_grapheme_boundary_state_machine.h
+++ b/chromium/third_party/blink/renderer/core/editing/state_machines/forward_grapheme_boundary_state_machine.h
@@ -10,7 +10,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/editing/state_machines/text_segmentation_machine_state.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/unicode.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/editing/testing/selection_sample.cc b/chromium/third_party/blink/renderer/core/editing/testing/selection_sample.cc
index 349c344bf74..0d1b3a50ac2 100644
--- a/chromium/third_party/blink/renderer/core/editing/testing/selection_sample.cc
+++ b/chromium/third_party/blink/renderer/core/editing/testing/selection_sample.cc
@@ -17,6 +17,7 @@
#include "third_party/blink/renderer/core/html/html_collection.h"
#include "third_party/blink/renderer/core/html/html_template_element.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
+#include "third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h"
namespace blink {
@@ -150,8 +151,8 @@ class Parser final {
// Traverses descendants of |node|. The |node| may be removed when it is
// |CharacterData| node contains only selection markers.
void Traverse(Node* node) {
- if (node->IsElementNode()) {
- HandleElementNode(ToElement(node));
+ if (auto* element = DynamicTo<Element>(node)) {
+ HandleElementNode(element);
return;
}
if (auto* data = DynamicTo<CharacterData>(node)) {
@@ -178,7 +179,7 @@ class Serializer final {
std::string Serialize(const ContainerNode& root) {
SerializeChildren(root);
- return builder_.ToString().Utf8().data();
+ return builder_.ToString().Utf8();
}
private:
@@ -258,7 +259,7 @@ class Serializer final {
attributes.push_back(&attribute);
std::sort(attributes.begin(), attributes.end(),
[](const Attribute* attribute1, const Attribute* attribute2) {
- return CodePointCompareLessThan(
+ return CodeUnitCompareLessThan(
attribute1->GetName().ToString(),
attribute2->GetName().ToString());
});
@@ -282,8 +283,8 @@ class Serializer final {
}
void HandleNode(const Node& node) {
- if (node.IsElementNode()) {
- HandleElementNode(ToElement(node));
+ if (auto* element = DynamicTo<Element>(node)) {
+ HandleElementNode(*element);
return;
}
if (node.IsTextNode()) {
diff --git a/chromium/third_party/blink/renderer/core/editing/testing/selection_sample.h b/chromium/third_party/blink/renderer/core/editing/testing/selection_sample.h
index 4425482df1e..5d1fcd78147 100644
--- a/chromium/third_party/blink/renderer/core/editing/testing/selection_sample.h
+++ b/chromium/third_party/blink/renderer/core/editing/testing/selection_sample.h
@@ -8,7 +8,7 @@
#include <string>
#include "third_party/blink/renderer/core/editing/forward.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
namespace blink {
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 1cc8985d084..e3aca5b3669 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
@@ -13,7 +13,7 @@
#include "third_party/blink/renderer/core/editing/forward.h"
#include "third_party/blink/renderer/core/editing/iterators/text_iterator_behavior.h"
#include "third_party/blink/renderer/platform/heap/member.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
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 fc7dd0600a2..e6db282def1 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
@@ -12,6 +12,7 @@
#include "third_party/blink/renderer/core/layout/layout_block_flow.h"
#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.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 "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
@@ -33,8 +34,7 @@ class ParameterizedTextOffsetMappingTest
builder.Append(text.Left(offset));
builder.Append('|');
builder.Append(text.Substring(offset));
- const CString result8 = builder.ToString().Utf8();
- return std::string(result8.data(), result8.length());
+ return builder.ToString().Utf8();
}
std::string GetRange(const std::string& selection_text) {
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 5f05aed1381..b57fa554227 100644
--- a/chromium/third_party/blink/renderer/core/editing/text_segments.h
+++ b/chromium/third_party/blink/renderer/core/editing/text_segments.h
@@ -7,7 +7,7 @@
#include "base/optional.h"
#include "third_party/blink/renderer/core/editing/forward.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
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 0078e35dacd..e2d8c4ebd6a 100644
--- a/chromium/third_party/blink/renderer/core/editing/visible_position.cc
+++ b/chromium/third_party/blink/renderer/core/editing/visible_position.cc
@@ -41,7 +41,6 @@
#include "third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/geometry/float_quad.h"
-#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/editing/visible_selection.cc b/chromium/third_party/blink/renderer/core/editing/visible_selection.cc
index 991cb0046c7..6ce08a7c752 100644
--- a/chromium/third_party/blink/renderer/core/editing/visible_selection.cc
+++ b/chromium/third_party/blink/renderer/core/editing/visible_selection.cc
@@ -38,7 +38,6 @@
#include "third_party/blink/renderer/platform/geometry/layout_point.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
#include "third_party/blink/renderer/platform/wtf/text/character_names.h"
-#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
namespace blink {
@@ -381,10 +380,8 @@ void VisibleSelectionTemplate<Strategy>::ShowTreeForThis() const {
->ToMarkedTreeString(Start().AnchorNode(), "S",
End().AnchorNode(), "E")
.Utf8()
- .data()
- << "start: " << Start().ToAnchorTypeAndOffsetString().Utf8().data()
- << "\n"
- << "end: " << End().ToAnchorTypeAndOffsetString().Utf8().data();
+ << "start: " << Start().ToAnchorTypeAndOffsetString().Utf8() << "\n"
+ << "end: " << End().ToAnchorTypeAndOffsetString().Utf8();
}
#endif
diff --git a/chromium/third_party/blink/renderer/core/editing/visible_selection.h b/chromium/third_party/blink/renderer/core/editing/visible_selection.h
index 74e26cdd854..14eaf8f1814 100644
--- a/chromium/third_party/blink/renderer/core/editing/visible_selection.h
+++ b/chromium/third_party/blink/renderer/core/editing/visible_selection.h
@@ -34,7 +34,7 @@
#include "third_party/blink/renderer/core/editing/text_affinity.h"
#include "third_party/blink/renderer/core/editing/text_granularity.h"
#include "third_party/blink/renderer/core/editing/visible_units.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 082ab153185..80585db39cb 100644
--- a/chromium/third_party/blink/renderer/core/editing/visible_units.cc
+++ b/chromium/third_party/blink/renderer/core/editing/visible_units.cc
@@ -26,6 +26,7 @@
#include "third_party/blink/renderer/core/editing/visible_units.h"
+#include "third_party/blink/renderer/core/display_lock/display_lock_utilities.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/first_letter_pseudo_element.h"
@@ -473,7 +474,8 @@ PositionWithAffinity PositionForContentsPointRespectingEditingBoundary(
LocalFrame* frame) {
HitTestRequest request = HitTestRequest::kMove | HitTestRequest::kReadOnly |
HitTestRequest::kActive |
- HitTestRequest::kIgnoreClipping;
+ HitTestRequest::kIgnoreClipping |
+ HitTestRequest::kRetargetForInert;
HitTestLocation location(contents_point);
HitTestResult result(request, location);
frame->GetDocument()->GetLayoutView()->HitTest(location, result);
@@ -653,6 +655,9 @@ static PositionTemplate<Strategy> MostBackwardCaretPosition(
layout_object->Style()->Visibility() != EVisibility::kVisible)
continue;
+ if (DisplayLockUtilities::NearestLockedExclusiveAncestor(*current_node))
+ continue;
+
if (rule == kCanCrossEditingBoundary && boundary_crossed) {
last_visible = current_pos;
break;
@@ -728,7 +733,8 @@ bool HasInvisibleFirstLetter(const Node* node) {
ToLayoutTextFragmentOrNull(AssociatedLayoutObjectOf(*node, 0));
if (!first_letter || first_letter == remaining_text)
return false;
- return first_letter->StyleRef().Visibility() != EVisibility::kVisible;
+ return first_letter->StyleRef().Visibility() != EVisibility::kVisible ||
+ DisplayLockUtilities::NearestLockedExclusiveAncestor(*node);
}
} // namespace
@@ -799,6 +805,9 @@ PositionTemplate<Strategy> MostForwardCaretPosition(
layout_object->Style()->Visibility() != EVisibility::kVisible)
continue;
+ if (DisplayLockUtilities::NearestLockedExclusiveAncestor(*current_node))
+ continue;
+
if (rule == kCanCrossEditingBoundary && boundary_crossed)
return current_pos.DeprecatedComputePosition();
@@ -893,6 +902,9 @@ static bool IsVisuallyEquivalentCandidateAlgorithm(
if (layout_object->Style()->Visibility() != EVisibility::kVisible)
return false;
+ if (DisplayLockUtilities::NearestLockedExclusiveAncestor(*anchor_node))
+ return false;
+
if (layout_object->IsBR()) {
// TODO(leviw) The condition should be
// anchor_type_ == PositionAnchorType::kBeforeAnchor, but for now we
diff --git a/chromium/third_party/blink/renderer/core/editing/visible_units_line_test.cc b/chromium/third_party/blink/renderer/core/editing/visible_units_line_test.cc
index fb84e5a4480..f2cc911f76c 100644
--- a/chromium/third_party/blink/renderer/core/editing/visible_units_line_test.cc
+++ b/chromium/third_party/blink/renderer/core/editing/visible_units_line_test.cc
@@ -697,12 +697,11 @@ TEST_F(VisibleUnitsLineTest, TextOverflowEllipsis) {
SetBodyContent("<div>foo foo</div>");
Element* div = GetDocument().QuerySelector("div");
Node* text = div->firstChild();
- // TODO(crbug.com/947593): Support Start/EndOfLine with ellipsis on LayoutNG
EXPECT_EQ(
- LayoutNGEnabled() ? Position() : Position(text, 0),
+ Position(text, 0),
StartOfLine(CreateVisiblePositionInDOMTree(*text, 6)).DeepEquivalent());
EXPECT_EQ(
- LayoutNGEnabled() ? Position() : Position(text, 7),
+ Position(text, 7),
EndOfLine(CreateVisiblePositionInDOMTree(*text, 6)).DeepEquivalent());
}
diff --git a/chromium/third_party/blink/renderer/core/events/animation_event.idl b/chromium/third_party/blink/renderer/core/events/animation_event.idl
index 5e1af4ecac0..b8e9c218515 100644
--- a/chromium/third_party/blink/renderer/core/events/animation_event.idl
+++ b/chromium/third_party/blink/renderer/core/events/animation_event.idl
@@ -26,7 +26,8 @@
// https://drafts.csswg.org/css-animations/#interface-animationevent
[
- Constructor(DOMString type, optional AnimationEventInit eventInitDict)
+ Constructor(DOMString type, optional AnimationEventInit eventInitDict),
+ Exposed=Window
] interface AnimationEvent : Event {
readonly attribute DOMString animationName;
readonly attribute double elapsedTime;
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 e9aeb2b5fd2..56048609344 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
@@ -11,9 +11,12 @@ namespace blink {
AnimationPlaybackEvent::AnimationPlaybackEvent(const AtomicString& type,
double current_time,
double timeline_time)
- : Event(type, Bubbles::kNo, Cancelable::kNo),
- current_time_(current_time),
- timeline_time_(timeline_time) {}
+ : Event(type, Bubbles::kNo, Cancelable::kNo) {
+ if (!std::isnan(current_time))
+ current_time_ = current_time;
+ if (!std::isnan(timeline_time))
+ timeline_time_ = timeline_time;
+}
AnimationPlaybackEvent::AnimationPlaybackEvent(
const AtomicString& type,
diff --git a/chromium/third_party/blink/renderer/core/events/animation_playback_event.idl b/chromium/third_party/blink/renderer/core/events/animation_playback_event.idl
index b26c27d0d4a..7579153ec93 100644
--- a/chromium/third_party/blink/renderer/core/events/animation_playback_event.idl
+++ b/chromium/third_party/blink/renderer/core/events/animation_playback_event.idl
@@ -6,7 +6,8 @@
[
Constructor(DOMString type, optional AnimationPlaybackEventInit eventInitDict),
- RuntimeEnabled=WebAnimationsAPI
+ RuntimeEnabled=WebAnimationsAPI,
+ Exposed=Window
] interface AnimationPlaybackEvent : Event {
readonly attribute double? currentTime;
readonly attribute double? timelineTime;
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 bfbb4f9e8f0..e7dd93818a8 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
@@ -6,7 +6,6 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_EVENTS_APPLICATION_CACHE_ERROR_EVENT_H_
#include "third_party/blink/public/mojom/appcache/appcache.mojom-blink.h"
-#include "third_party/blink/public/web/web_application_cache_host_client.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/application_cache_error_event_init.h"
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 cedcc0c65ee..69814ff5fb1 100644
--- a/chromium/third_party/blink/renderer/core/events/composition_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/composition_event.cc
@@ -40,7 +40,7 @@ CompositionEvent::CompositionEvent(const AtomicString& type,
Bubbles::kYes,
Cancelable::kYes,
ComposedMode::kComposed,
- CurrentTimeTicks(),
+ base::TimeTicks::Now(),
view,
0,
view ? view->GetInputDeviceCapabilities()->FiresTouchEvents(false)
diff --git a/chromium/third_party/blink/renderer/core/events/current_input_event.h b/chromium/third_party/blink/renderer/core/events/current_input_event.h
index 3820049ee0a..909b5f3d4c2 100644
--- a/chromium/third_party/blink/renderer/core/events/current_input_event.h
+++ b/chromium/third_party/blink/renderer/core/events/current_input_event.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_EVENTS_CURRENT_INPUT_EVENT_H_
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 429daf97210..fcfbeddcf3a 100644
--- a/chromium/third_party/blink/renderer/core/events/drag_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/drag_event.cc
@@ -15,7 +15,7 @@ DragEvent::DragEvent() : data_transfer_(nullptr) {}
DragEvent::DragEvent(const AtomicString& type,
const DragEventInit* initializer,
- TimeTicks platform_time_stamp,
+ base::TimeTicks platform_time_stamp,
SyntheticEventType synthetic_event_type)
: MouseEvent(type, initializer, platform_time_stamp, synthetic_event_type),
data_transfer_(initializer->getDataTransfer()) {}
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 11a6c43854e..25041f8cf89 100644
--- a/chromium/third_party/blink/renderer/core/events/drag_event.h
+++ b/chromium/third_party/blink/renderer/core/events/drag_event.h
@@ -21,7 +21,7 @@ class CORE_EXPORT DragEvent final : public MouseEvent {
static DragEvent* Create(const AtomicString& type,
const DragEventInit* initializer,
- TimeTicks platform_time_stamp,
+ base::TimeTicks platform_time_stamp,
SyntheticEventType synthetic_event_type) {
return MakeGarbageCollected<DragEvent>(
type, initializer, platform_time_stamp, synthetic_event_type);
@@ -30,13 +30,13 @@ class CORE_EXPORT DragEvent final : public MouseEvent {
static DragEvent* Create(const AtomicString& type,
const DragEventInit* initializer) {
return MakeGarbageCollected<DragEvent>(
- type, initializer, CurrentTimeTicks(), kRealOrIndistinguishable);
+ type, initializer, base::TimeTicks::Now(), kRealOrIndistinguishable);
}
DragEvent();
DragEvent(const AtomicString& type,
const DragEventInit*,
- TimeTicks platform_time_stamp,
+ base::TimeTicks platform_time_stamp,
SyntheticEventType);
DataTransfer* getDataTransfer() const override {
diff --git a/chromium/third_party/blink/renderer/core/events/event_factory.h b/chromium/third_party/blink/renderer/core/events/event_factory.h
index 295e1181cfb..4ffe7f483c2 100644
--- a/chromium/third_party/blink/renderer/core/events/event_factory.h
+++ b/chromium/third_party/blink/renderer/core/events/event_factory.h
@@ -29,7 +29,7 @@
#include <memory>
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
namespace blink {
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 f115ea22870..3a1712dac5a 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
@@ -83,6 +83,7 @@
"controllerchange",
"cookiechange",
"copy",
+ "contentdelete",
"crossoriginmessage",
"cuechange",
"cut",
@@ -145,6 +146,7 @@
"gotpointercapture",
"hashchange",
"icecandidate",
+ "icecandidateerror",
"iceconnectionstatechange",
"icegatheringstatechange",
"inactive",
@@ -221,6 +223,7 @@
"progress",
"processorerror",
"push",
+ "pushsubscriptionchange",
"quicstream",
"ratechange",
"reading",
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 f34dfbcf03f..da2ebd38125 100644
--- a/chromium/third_party/blink/renderer/core/events/focus_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/focus_event.cc
@@ -52,7 +52,7 @@ FocusEvent::FocusEvent(const AtomicString& type,
bubbles,
Cancelable::kNo,
ComposedMode::kComposed,
- CurrentTimeTicks(),
+ base::TimeTicks::Now(),
view,
detail,
source_capabilities),
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 bf2ce4c915a..f941210803b 100644
--- a/chromium/third_party/blink/renderer/core/events/message_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/message_event.cc
@@ -126,7 +126,8 @@ MessageEvent::MessageEvent(scoped_refptr<SerializedScriptValue> data,
EventTarget* source,
Vector<MessagePortChannel> channels,
UserActivation* user_activation,
- bool transfer_user_activation)
+ bool transfer_user_activation,
+ bool allow_autoplay)
: Event(event_type_names::kMessage, Bubbles::kNo, Cancelable::kNo),
data_type_(kDataTypeSerializedScriptValue),
data_as_serialized_script_value_(
@@ -136,7 +137,8 @@ MessageEvent::MessageEvent(scoped_refptr<SerializedScriptValue> data,
source_(source),
channels_(std::move(channels)),
user_activation_(user_activation),
- transfer_user_activation_(transfer_user_activation) {
+ transfer_user_activation_(transfer_user_activation),
+ allow_autoplay_(allow_autoplay) {
DCHECK(IsValidSource(source_.Get()));
}
@@ -216,7 +218,8 @@ void MessageEvent::initMessageEvent(const AtomicString& type,
EventTarget* source,
MessagePortArray* ports,
UserActivation* user_activation,
- bool transfer_user_activation) {
+ bool transfer_user_activation,
+ bool allow_autoplay) {
if (IsBeingDispatched())
return;
@@ -233,6 +236,7 @@ void MessageEvent::initMessageEvent(const AtomicString& type,
is_ports_dirty_ = true;
user_activation_ = user_activation;
transfer_user_activation_ = transfer_user_activation;
+ allow_autoplay_ = allow_autoplay;
}
void MessageEvent::initMessageEvent(const AtomicString& type,
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 c38e56dd5c2..13462d968eb 100644
--- a/chromium/third_party/blink/renderer/core/events/message_event.h
+++ b/chromium/third_party/blink/renderer/core/events/message_event.h
@@ -41,7 +41,7 @@
#include "third_party/blink/renderer/core/fileapi/blob.h"
#include "third_party/blink/renderer/core/messaging/message_port.h"
#include "third_party/blink/renderer/core/typed_arrays/dom_array_buffer.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -79,10 +79,11 @@ class CORE_EXPORT MessageEvent final : public Event {
const String& last_event_id = String(),
EventTarget* source = nullptr,
UserActivation* user_activation = nullptr,
- bool transfer_user_activation = false) {
+ bool transfer_user_activation = false,
+ bool allow_autoplay = false) {
return MakeGarbageCollected<MessageEvent>(
std::move(data), origin, last_event_id, source, std::move(channels),
- user_activation, transfer_user_activation);
+ user_activation, transfer_user_activation, allow_autoplay);
}
static MessageEvent* CreateError(const String& origin = String(),
EventTarget* source = nullptr) {
@@ -121,7 +122,8 @@ class CORE_EXPORT MessageEvent final : public Event {
EventTarget* source,
Vector<MessagePortChannel>,
UserActivation* user_activation,
- bool transfer_user_activation);
+ bool transfer_user_activation,
+ bool allow_autoplay);
// Creates a "messageerror" event.
MessageEvent(const String& origin, EventTarget* source);
MessageEvent(const String& data, const String& origin);
@@ -146,7 +148,8 @@ class CORE_EXPORT MessageEvent final : public Event {
EventTarget* source,
MessagePortArray*,
UserActivation* user_activation,
- bool transfer_user_activation = false);
+ bool transfer_user_activation = false,
+ bool allow_autoplay = false);
void initMessageEvent(const AtomicString& type,
bool bubbles,
bool cancelable,
@@ -165,6 +168,7 @@ class CORE_EXPORT MessageEvent final : public Event {
bool isPortsDirty() const { return is_ports_dirty_; }
UserActivation* userActivation() const { return user_activation_; }
bool transferUserActivation() const { return transfer_user_activation_; }
+ bool allowAutoplay() const { return allow_autoplay_; }
Vector<MessagePortChannel> ReleaseChannels() { return std::move(channels_); }
@@ -231,6 +235,7 @@ class CORE_EXPORT MessageEvent final : public Event {
Vector<MessagePortChannel> channels_;
Member<UserActivation> user_activation_;
bool transfer_user_activation_ = false;
+ bool allow_autoplay_ = false;
};
} // namespace blink
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 4a13e313942..0d986fc9c4e 100644
--- a/chromium/third_party/blink/renderer/core/events/mouse_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/mouse_event.cc
@@ -30,7 +30,6 @@
#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"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/input/input_device_capabilities.h"
#include "third_party/blink/renderer/core/layout/layout_object.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
@@ -41,6 +40,7 @@
#include "third_party/blink/renderer/core/svg/svg_element.h"
#include "third_party/blink/renderer/platform/bindings/dom_wrapper_world.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
@@ -119,7 +119,7 @@ MouseEvent* MouseEvent::Create(ScriptState* script_state,
MouseEvent* MouseEvent::Create(const AtomicString& event_type,
const MouseEventInit* initializer,
- TimeTicks platform_time_stamp,
+ base::TimeTicks platform_time_stamp,
SyntheticEventType synthetic_event_type,
WebMenuSourceType menu_source_type) {
return MakeGarbageCollected<MouseEvent>(
@@ -157,8 +157,9 @@ MouseEvent* MouseEvent::Create(const AtomicString& event_type,
initializer->setButtons(
MouseEvent::WebInputEventModifiersToButtons(modifiers));
- TimeTicks timestamp = underlying_event ? underlying_event->PlatformTimeStamp()
- : CurrentTimeTicks();
+ base::TimeTicks timestamp = underlying_event
+ ? underlying_event->PlatformTimeStamp()
+ : base::TimeTicks::Now();
MouseEvent* created_event = MakeGarbageCollected<MouseEvent>(
event_type, initializer, timestamp, synthetic_type);
@@ -183,7 +184,7 @@ MouseEvent::MouseEvent()
MouseEvent::MouseEvent(const AtomicString& event_type,
const MouseEventInit* initializer,
- TimeTicks platform_time_stamp,
+ base::TimeTicks platform_time_stamp,
SyntheticEventType synthetic_event_type,
WebMenuSourceType menu_source_type)
: UIEventWithKeyState(event_type, initializer, platform_time_stamp),
@@ -245,10 +246,10 @@ void MouseEvent::SetCoordinatesFromWebPointerProperties(
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()) {
+ if (!RuntimeEnabledFeatures::ConsolidatedMovementXYEnabled()) {
+ // 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);
}
@@ -516,10 +517,19 @@ void MouseEvent::ComputeRelativePosition() {
layer_location_ = view->DocumentToFrame(scaled_page_location);
// FIXME: Does this differ from PaintLayer::ConvertToLayerCoords?
- for (PaintLayer* layer = n->GetLayoutObject()->EnclosingLayer(); layer;
- layer = layer->ContainingLayer()) {
- layer_location_ -= DoubleSize(layer->Location().left.ToDouble(),
- layer->Location().top.ToDouble());
+ PaintLayer* layer = n->GetLayoutObject()->EnclosingLayer();
+ while (layer) {
+ PhysicalOffset physical_offset = layer->Location();
+ if (layer->GetLayoutObject().IsInFlowPositioned())
+ physical_offset += layer->GetLayoutObject().OffsetForInFlowPosition();
+ PaintLayer* containing_layer = layer->ContainingLayer();
+ if (containing_layer) {
+ physical_offset -=
+ PhysicalOffset(containing_layer->ScrolledContentOffset());
+ }
+ layer_location_ -= DoubleSize(physical_offset.left.ToDouble(),
+ physical_offset.top.ToDouble());
+ layer = containing_layer;
}
if (inverse_zoom_factor != 1.0f)
layer_location_.Scale(inverse_zoom_factor, inverse_zoom_factor);
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 e5afe20bd72..83aa0014700 100644
--- a/chromium/third_party/blink/renderer/core/events/mouse_event.h
+++ b/chromium/third_party/blink/renderer/core/events/mouse_event.h
@@ -55,7 +55,7 @@ class CORE_EXPORT MouseEvent : public UIEventWithKeyState {
static MouseEvent* Create(const AtomicString& event_type,
const MouseEventInit*,
- TimeTicks platform_time_stamp,
+ base::TimeTicks platform_time_stamp,
SyntheticEventType,
WebMenuSourceType);
@@ -70,11 +70,11 @@ class CORE_EXPORT MouseEvent : public UIEventWithKeyState {
MouseEvent(const AtomicString& type,
const MouseEventInit*,
- TimeTicks platform_time_stamp,
+ base::TimeTicks platform_time_stamp,
SyntheticEventType = kRealOrIndistinguishable,
WebMenuSourceType = kMenuSourceNone);
MouseEvent(const AtomicString& type, const MouseEventInit* init)
- : MouseEvent(type, init, CurrentTimeTicks()) {}
+ : MouseEvent(type, init, base::TimeTicks::Now()) {}
MouseEvent();
~MouseEvent() override;
diff --git a/chromium/third_party/blink/renderer/core/events/navigator_events.h b/chromium/third_party/blink/renderer/core/events/navigator_events.h
index 98da73b0c55..feb55ed88bd 100644
--- a/chromium/third_party/blink/renderer/core/events/navigator_events.h
+++ b/chromium/third_party/blink/renderer/core/events/navigator_events.h
@@ -31,7 +31,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_EVENTS_NAVIGATOR_EVENTS_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_EVENTS_NAVIGATOR_EVENTS_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 a7501d92c46..7cd8a9856fd 100644
--- a/chromium/third_party/blink/renderer/core/events/pointer_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/pointer_event.cc
@@ -12,7 +12,7 @@ namespace blink {
PointerEvent::PointerEvent(const AtomicString& type,
const PointerEventInit* initializer,
- TimeTicks platform_time_stamp)
+ base::TimeTicks platform_time_stamp)
: MouseEvent(type, initializer, platform_time_stamp),
pointer_id_(0),
width_(0),
@@ -111,7 +111,7 @@ HeapVector<Member<PointerEvent>> PointerEvent::getPredictedEvents() {
return predicted_events_;
}
-TimeTicks PointerEvent::OldestPlatformTimeStamp() const {
+base::TimeTicks PointerEvent::OldestPlatformTimeStamp() const {
if (coalesced_events_.size() > 0) {
// Assume that time stamps of coalesced events are in ascending order.
return coalesced_events_[0]->PlatformTimeStamp();
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 2afd951b1d2..ec3a1adb136 100644
--- a/chromium/third_party/blink/renderer/core/events/pointer_event.h
+++ b/chromium/third_party/blink/renderer/core/events/pointer_event.h
@@ -16,18 +16,18 @@ class CORE_EXPORT PointerEvent final : public MouseEvent {
public:
static PointerEvent* Create(const AtomicString& type,
const PointerEventInit* initializer,
- TimeTicks platform_time_stamp) {
+ base::TimeTicks platform_time_stamp) {
return MakeGarbageCollected<PointerEvent>(type, initializer,
platform_time_stamp);
}
static PointerEvent* Create(const AtomicString& type,
const PointerEventInit* initializer) {
- return PointerEvent::Create(type, initializer, CurrentTimeTicks());
+ return PointerEvent::Create(type, initializer, base::TimeTicks::Now());
}
PointerEvent(const AtomicString&,
const PointerEventInit*,
- TimeTicks platform_time_stamp);
+ base::TimeTicks platform_time_stamp);
PointerId pointerId() const { return pointer_id_; }
double width() const { return width_; }
@@ -63,7 +63,7 @@ class CORE_EXPORT PointerEvent final : public MouseEvent {
HeapVector<Member<PointerEvent>> getCoalescedEvents();
HeapVector<Member<PointerEvent>> getPredictedEvents();
- TimeTicks OldestPlatformTimeStamp() const;
+ base::TimeTicks OldestPlatformTimeStamp() const;
DispatchEventResult DispatchEvent(EventDispatcher&) override;
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 1cc1a41d034..1f39eec4f0f 100644
--- a/chromium/third_party/blink/renderer/core/events/pointer_event.idl
+++ b/chromium/third_party/blink/renderer/core/events/pointer_event.idl
@@ -5,7 +5,8 @@
// https://w3c.github.io/pointerevents/#pointerevent-interface
[
- Constructor(DOMString type, optional PointerEventInit eventInitDict)
+ Constructor(DOMString type, optional PointerEventInit eventInitDict),
+ Exposed=Window
] interface PointerEvent : MouseEvent {
[MeasureAs=PointerEventAttributeCount] readonly attribute long pointerId;
[MeasureAs=PointerEventAttributeCount] readonly attribute double width;
@@ -20,5 +21,5 @@
// https://w3c.github.io/pointerevents/extension.html#extensions-to-the-pointerevent-interface
sequence<PointerEvent> getCoalescedEvents();
- [RuntimeEnabled=PredictedEvents] sequence<PointerEvent> getPredictedEvents();
+ [RuntimeEnabled=PredictedEvents, Measure] 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 8b8dba7f378..8ede380f0d9 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
@@ -6,6 +6,8 @@
#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/page/chrome_client.h"
+#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/platform/geometry/float_size.h"
namespace blink {
@@ -94,13 +96,36 @@ void UpdateCommonPointerEventInit(const WebPointerEvent& web_pointer_event,
MouseEvent::SetCoordinatesFromWebPointerProperties(
web_pointer_event_in_root_frame, dom_window, pointer_event_init);
- if (RuntimeEnabledFeatures::MovementXYInBlinkEnabled() &&
- web_pointer_event.GetType() == WebInputEvent::kPointerMove) {
- // TODO(eirage): pointerrawupdate 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 (RuntimeEnabledFeatures::ConsolidatedMovementXYEnabled() &&
+ (web_pointer_event.GetType() == WebInputEvent::kPointerMove ||
+ web_pointer_event.GetType() == WebInputEvent::kPointerRawUpdate)) {
+ // TODO(crbug.com/907309): Current movementX/Y is in physical pixel when
+ // zoom-for-dsf is enabled. Here we apply the device-scale-factor to align
+ // with the current behavior. We need to figure out what is the best
+ // behavior here.
+ float device_scale_factor = 1;
+ if (dom_window && dom_window->GetFrame()) {
+ LocalFrame* frame = dom_window->GetFrame();
+ if (frame->GetPage()->DeviceScaleFactorDeprecated() == 1) {
+ device_scale_factor = frame->GetPage()
+ ->GetChromeClient()
+ .GetScreenInfo()
+ .device_scale_factor;
+ }
+ }
+
+ // movementX/Y is type int for pointerevent, so we still need to truncated
+ // the coordinates before calculate movement.
+ pointer_event_init->setMovementX(
+ base::saturated_cast<int>(web_pointer_event.PositionInScreen().x *
+ device_scale_factor) -
+ base::saturated_cast<int>(last_global_position.X() *
+ device_scale_factor));
+ pointer_event_init->setMovementY(
+ base::saturated_cast<int>(web_pointer_event.PositionInScreen().y *
+ device_scale_factor) -
+ base::saturated_cast<int>(last_global_position.Y() *
+ device_scale_factor));
}
// If width/height is unknown we let PointerEventInit set it to 1.
@@ -139,8 +164,9 @@ HeapVector<Member<PointerEvent>> PointerEventFactory::CreateEventSequence(
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());
+ FloatPoint last_global_position =
+ GetLastPointerPosition(pointer_event_init->pointerId(),
+ event_list.front(), web_pointer_event.GetType());
for (const auto& event : event_list) {
DCHECK_EQ(web_pointer_event.id, event.id);
@@ -292,8 +318,8 @@ PointerEvent* PointerEventFactory::Create(
pointer_event_init->setView(view);
UpdateCommonPointerEventInit(
web_pointer_event,
- GetLastPointerPosition(pointer_event_init->pointerId(),
- web_pointer_event),
+ GetLastPointerPosition(pointer_event_init->pointerId(), web_pointer_event,
+ event_type),
view, pointer_event_init);
UIEventWithKeyState::SetFromWebInputEventModifiers(
@@ -316,25 +342,37 @@ PointerEvent* PointerEventFactory::Create(
pointer_event_init->setCoalescedEvents(coalesced_pointer_events);
pointer_event_init->setPredictedEvents(predicted_pointer_events);
- SetLastPosition(pointer_event_init->pointerId(), web_pointer_event);
+ SetLastPosition(pointer_event_init->pointerId(),
+ web_pointer_event.PositionInScreen(), event_type);
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());
+ const FloatPoint& position_in_screen,
+ WebInputEvent::Type event_type) {
+ if (event_type == WebInputEvent::kPointerRawUpdate)
+ pointerrawupdate_last_position_mapping_.Set(pointer_id, position_in_screen);
+ else
+ pointer_id_last_position_mapping_.Set(pointer_id, position_in_screen);
}
void PointerEventFactory::RemoveLastPosition(const int pointer_id) {
pointer_id_last_position_mapping_.erase(pointer_id);
+ pointerrawupdate_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);
+ const WebPointerProperties& event,
+ WebInputEvent::Type event_type) const {
+ if (event_type == WebInputEvent::kPointerRawUpdate) {
+ if (pointerrawupdate_last_position_mapping_.Contains(pointer_id))
+ return pointerrawupdate_last_position_mapping_.at(pointer_id);
+ } else {
+ 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();
@@ -342,7 +380,7 @@ FloatPoint PointerEventFactory::GetLastPointerPosition(
PointerEvent* PointerEventFactory::CreatePointerCancelEvent(
const int pointer_id,
- TimeTicks platfrom_time_stamp) {
+ base::TimeTicks platfrom_time_stamp) {
DCHECK(pointer_id_mapping_.Contains(pointer_id));
pointer_id_mapping_.Set(
pointer_id,
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 9ee75320ade..3122d6fc8e4 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
@@ -5,13 +5,11 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_EVENTS_POINTER_EVENT_FACTORY_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_EVENTS_POINTER_EVENT_FACTORY_H_
-#include <unordered_map>
-
#include "third_party/blink/public/platform/web_pointer_event.h"
#include "third_party/blink/public/platform/web_pointer_properties.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/events/pointer_event.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
namespace blink {
@@ -38,7 +36,7 @@ class CORE_EXPORT PointerEventFactory {
LocalDOMWindow* view);
PointerEvent* CreatePointerCancelEvent(const PointerId pointer_id,
- TimeTicks platfrom_time_stamp);
+ base::TimeTicks platfrom_time_stamp);
// For creating raw update events in chorded button case.
PointerEvent* CreatePointerRawUpdateEvent(PointerEvent*);
@@ -80,6 +78,7 @@ class CORE_EXPORT PointerEventFactory {
bool IsPrimary(const WebPointerProperties&) const;
static const PointerId kMouseId;
+ static const PointerId kInvalidId;
// Removes pointer_id from the map.
void RemoveLastPosition(const PointerId pointer_id);
@@ -88,7 +87,12 @@ class CORE_EXPORT PointerEventFactory {
// Otherwise it returns the PositionInScreen of the given events, so we will
// get movement = 0 when there is no last position.
FloatPoint GetLastPointerPosition(PointerId pointer_id,
- const WebPointerProperties& event) const;
+ const WebPointerProperties& event,
+ WebInputEvent::Type event_type) const;
+
+ void SetLastPosition(PointerId pointer_id,
+ const FloatPoint& position_in_screen,
+ WebInputEvent::Type event_type);
private:
// We use int64_t to cover the whole range for PointerId with no
@@ -141,10 +145,6 @@ class CORE_EXPORT PointerEventFactory {
const Vector<WebPointerEvent>& event_list,
LocalDOMWindow* view);
- void SetLastPosition(PointerId pointer_id, const WebPointerProperties& event);
-
- static const PointerId kInvalidId;
-
PointerId current_id_;
HashMap<IncomingId,
PointerId,
@@ -161,6 +161,7 @@ class CORE_EXPORT PointerEventFactory {
1];
PointerIdKeyMap<FloatPoint> pointer_id_last_position_mapping_;
+ PointerIdKeyMap<FloatPoint> pointerrawupdate_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 c169f7278b7..fd680c5b14d 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
@@ -123,12 +123,13 @@ class PointerEventFactoryTest : public testing::Test {
pointer_event->pointerId(),
WebPointerProperties(1, WebPointerProperties::PointerType::kUnknown,
WebPointerProperties::Button::kNoButton,
- WebFloatPoint(50, 50), WebFloatPoint(20, 20))),
+ WebFloatPoint(50, 50), WebFloatPoint(20, 20)),
+ type),
FloatPoint(100, 100));
return pointer_event;
}
void CreateAndCheckPointerTransitionEvent(PointerEvent*, const AtomicString&);
- void CheckNonHoveringPointers(const std::set<int>& expected);
+ void CheckNonHoveringPointers(const HashSet<int>& expected);
PointerEventFactory pointer_event_factory_;
int expected_mouse_id_;
@@ -177,7 +178,7 @@ void PointerEventFactoryTest::CreateAndCheckPointerTransitionEvent(
}
void PointerEventFactoryTest::CheckNonHoveringPointers(
- const std::set<int>& expected_pointers) {
+ const HashSet<int>& expected_pointers) {
Vector<int> pointers =
pointer_event_factory_.GetPointerIdsOfNonHoveringPointers();
EXPECT_EQ(pointers.size(), expected_pointers.size());
@@ -589,7 +590,8 @@ TEST_F(PointerEventFactoryTest, LastPointerPosition) {
expected_mouse_id_,
WebPointerProperties(1, WebPointerProperties::PointerType::kUnknown,
WebPointerProperties::Button::kNoButton,
- WebFloatPoint(50, 50), WebFloatPoint(20, 20))),
+ WebFloatPoint(50, 50), WebFloatPoint(20, 20)),
+ WebInputEvent::kPointerMove),
FloatPoint(20, 20));
}
diff --git a/chromium/third_party/blink/renderer/core/events/portal_activate_event.cc b/chromium/third_party/blink/renderer/core/events/portal_activate_event.cc
index d7666402f98..ddd5dfa8795 100644
--- a/chromium/third_party/blink/renderer/core/events/portal_activate_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/portal_activate_event.cc
@@ -21,16 +21,16 @@ namespace blink {
PortalActivateEvent* PortalActivateEvent::Create(
LocalFrame* frame,
const base::UnguessableToken& predecessor_portal_token,
- mojom::blink::PortalAssociatedPtr predecessor_portal_ptr,
- mojom::blink::PortalClientAssociatedRequest
- predecessor_portal_client_request,
+ mojo::PendingAssociatedRemote<mojom::blink::Portal> predecessor_portal,
+ mojo::PendingAssociatedReceiver<mojom::blink::PortalClient>
+ predecessor_portal_client_receiver,
scoped_refptr<SerializedScriptValue> data,
MessagePortArray* ports,
OnPortalActivatedCallback callback) {
return MakeGarbageCollected<PortalActivateEvent>(
frame->GetDocument(), predecessor_portal_token,
- std::move(predecessor_portal_ptr),
- std::move(predecessor_portal_client_request),
+ std::move(predecessor_portal),
+ std::move(predecessor_portal_client_receiver),
SerializedScriptValue::Unpack(std::move(data)), ports,
std::move(callback));
}
@@ -44,21 +44,21 @@ PortalActivateEvent* PortalActivateEvent::Create(
PortalActivateEvent::PortalActivateEvent(
Document* document,
const base::UnguessableToken& predecessor_portal_token,
- mojom::blink::PortalAssociatedPtr predecessor_portal_ptr,
- mojom::blink::PortalClientAssociatedRequest
- predecessor_portal_client_request,
+ mojo::PendingAssociatedRemote<mojom::blink::Portal> predecessor_portal,
+ mojo::PendingAssociatedReceiver<mojom::blink::PortalClient>
+ predecessor_portal_client_receiver,
UnpackedSerializedScriptValue* data,
MessagePortArray* ports,
OnPortalActivatedCallback callback)
: Event(event_type_names::kPortalactivate,
Bubbles::kNo,
Cancelable::kNo,
- CurrentTimeTicks()),
+ base::TimeTicks::Now()),
document_(document),
predecessor_portal_token_(predecessor_portal_token),
- predecessor_portal_ptr_(std::move(predecessor_portal_ptr)),
- predecessor_portal_client_request_(
- std::move(predecessor_portal_client_request)),
+ predecessor_portal_(std::move(predecessor_portal)),
+ predecessor_portal_client_receiver_(
+ std::move(predecessor_portal_client_receiver)),
data_(data),
ports_(ports),
on_portal_activated_callback_(std::move(callback)) {}
@@ -120,7 +120,7 @@ const AtomicString& PortalActivateEvent::InterfaceName() const {
HTMLPortalElement* PortalActivateEvent::adoptPredecessor(
ExceptionState& exception_state) {
- if (!predecessor_portal_ptr_) {
+ if (!predecessor_portal_) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidStateError,
"The PortalActivateEvent is not associated with a predecessor browsing "
@@ -129,16 +129,16 @@ HTMLPortalElement* PortalActivateEvent::adoptPredecessor(
}
HTMLPortalElement* portal = MakeGarbageCollected<HTMLPortalElement>(
- *document_, predecessor_portal_token_, std::move(predecessor_portal_ptr_),
- std::move(predecessor_portal_client_request_));
+ *document_, predecessor_portal_token_, std::move(predecessor_portal_),
+ std::move(predecessor_portal_client_receiver_));
std::move(on_portal_activated_callback_).Run(true);
return portal;
}
void PortalActivateEvent::DetachPortalIfNotAdopted() {
- if (predecessor_portal_ptr_) {
+ if (predecessor_portal_) {
std::move(on_portal_activated_callback_).Run(false);
- predecessor_portal_ptr_.reset();
+ predecessor_portal_.reset();
}
}
diff --git a/chromium/third_party/blink/renderer/core/events/portal_activate_event.h b/chromium/third_party/blink/renderer/core/events/portal_activate_event.h
index 60afce12d08..5c7f209ff2b 100644
--- a/chromium/third_party/blink/renderer/core/events/portal_activate_event.h
+++ b/chromium/third_party/blink/renderer/core/events/portal_activate_event.h
@@ -6,6 +6,9 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_EVENTS_PORTAL_ACTIVATE_EVENT_H_
#include "base/unguessable_token.h"
+#include "mojo/public/cpp/bindings/associated_remote.h"
+#include "mojo/public/cpp/bindings/pending_associated_receiver.h"
+#include "mojo/public/cpp/bindings/pending_associated_remote.h"
#include "third_party/blink/public/mojom/portal/portal.mojom-blink.h"
#include "third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h"
#include "third_party/blink/renderer/bindings/core/v8/serialization/unpacked_serialized_script_value.h"
@@ -36,9 +39,9 @@ class CORE_EXPORT PortalActivateEvent : public Event {
static PortalActivateEvent* Create(
LocalFrame* frame,
const base::UnguessableToken& predecessor_portal_token,
- mojom::blink::PortalAssociatedPtr predecessor_portal_ptr,
- mojom::blink::PortalClientAssociatedRequest
- predecessor_portal_client_request,
+ mojo::PendingAssociatedRemote<mojom::blink::Portal> predecessor_portal,
+ mojo::PendingAssociatedReceiver<mojom::blink::PortalClient>
+ predecessor_portal_client_receiver,
scoped_refptr<SerializedScriptValue> data,
MessagePortArray* ports,
OnPortalActivatedCallback callback);
@@ -47,14 +50,15 @@ class CORE_EXPORT PortalActivateEvent : public Event {
static PortalActivateEvent* Create(const AtomicString& type,
const PortalActivateEventInit*);
- PortalActivateEvent(Document* document,
- const base::UnguessableToken& predecessor_portal_token,
- mojom::blink::PortalAssociatedPtr predecessor_portal_ptr,
- mojom::blink::PortalClientAssociatedRequest
- predecessor_portal_client_request,
- UnpackedSerializedScriptValue* data,
- MessagePortArray*,
- OnPortalActivatedCallback callback);
+ PortalActivateEvent(
+ Document* document,
+ const base::UnguessableToken& predecessor_portal_token,
+ mojo::PendingAssociatedRemote<mojom::blink::Portal> predecessor_portal,
+ mojo::PendingAssociatedReceiver<mojom::blink::PortalClient>
+ predecessor_portal_client_receiver,
+ UnpackedSerializedScriptValue* data,
+ MessagePortArray*,
+ OnPortalActivatedCallback callback);
PortalActivateEvent(const AtomicString& type, const PortalActivateEventInit*);
~PortalActivateEvent() override;
@@ -73,9 +77,9 @@ class CORE_EXPORT PortalActivateEvent : public Event {
private:
Member<Document> document_;
base::UnguessableToken predecessor_portal_token_;
- mojom::blink::PortalAssociatedPtr predecessor_portal_ptr_;
- mojom::blink::PortalClientAssociatedRequest
- predecessor_portal_client_request_;
+ mojo::AssociatedRemote<mojom::blink::Portal> predecessor_portal_;
+ mojo::PendingAssociatedReceiver<mojom::blink::PortalClient>
+ predecessor_portal_client_receiver_;
// Set if this came from a serialized value.
Member<UnpackedSerializedScriptValue> data_;
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 42afd1031e9..cbf041b6d0c 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
@@ -31,7 +31,8 @@ enum SecurityPolicyViolationEventDisposition {
[
Constructor(DOMString type),
- Constructor(DOMString type, SecurityPolicyViolationEventInit eventInitDict)
+ Constructor(DOMString type, SecurityPolicyViolationEventInit eventInitDict),
+ Exposed=(Window,Worker)
] interface SecurityPolicyViolationEvent : Event {
// TODO(foolip): The spec says "documentURL".
[Measure] readonly attribute DOMString documentURI;
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 3c7b317ec2b..afda4ad0a69 100644
--- a/chromium/third_party/blink/renderer/core/events/text_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/text_event.cc
@@ -71,7 +71,7 @@ TextEvent::TextEvent(AbstractView* view,
Bubbles::kYes,
Cancelable::kYes,
ComposedMode::kComposed,
- CurrentTimeTicks(),
+ base::TimeTicks::Now(),
view,
0,
nullptr),
@@ -90,7 +90,7 @@ TextEvent::TextEvent(AbstractView* view,
Bubbles::kYes,
Cancelable::kYes,
ComposedMode::kComposed,
- CurrentTimeTicks(),
+ base::TimeTicks::Now(),
view,
0,
nullptr),
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 a006923d4cc..ee8e3c161ae 100644
--- a/chromium/third_party/blink/renderer/core/events/touch_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/touch_event.cc
@@ -34,174 +34,19 @@
#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_view.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/html_element.h"
#include "third_party/blink/renderer/core/input/input_device_capabilities.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/platform/bindings/dom_wrapper_world.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
namespace {
-// These offsets change indicies into the ListenerHistogram
-// enumeration. The addition of a series of offsets then
-// produces the resulting ListenerHistogram value.
-// TODO(dtapuska): Remove all of these histogram counts once
-// https://crbug.com/599609 is fixed.
-const size_t kTouchTargetHistogramRootScrollerOffset = 6;
-const size_t kTouchTargetHistogramScrollableDocumentOffset = 3;
-const size_t kTouchTargetHistogramAlreadyHandledOffset = 0;
-const size_t kTouchTargetHistogramNotHandledOffset = 1;
-const size_t kTouchTargetHistogramHandledOffset = 2;
-const size_t kCapturingOffset = 0;
-const size_t kAtTargetOffset = 12;
-const size_t kBubblingOffset = 24;
-
-enum TouchTargetAndDispatchResultType {
- // The following enums represent state captured during the CAPTURING_PHASE.
-
- // Non-root-scroller, non-scrollable document, already handled.
- kCapturingNonRootScrollerNonScrollableAlreadyHandled,
- // Non-root-scroller, non-scrollable document, not handled.
- kCapturingNonRootScrollerNonScrollableNotHandled,
- // Non-root-scroller, non-scrollable document, handled application.
- kCapturingNonRootScrollerNonScrollableHandled,
- // Non-root-scroller, scrollable document, already handled.
- kCapturingNonRootScrollerScrollableDocumentAlreadyHandled,
- // Non-root-scroller, scrollable document, not handled.
- kCapturingNonRootScrollerScrollableDocumentNotHandled,
- // Non-root-scroller, scrollable document, handled application.
- kCapturingNonRootScrollerScrollableDocumentHandled,
- // Root-scroller, non-scrollable document, already handled.
- kCapturingRootScrollerNonScrollableAlreadyHandled,
- // Root-scroller, non-scrollable document, not handled.
- kCapturingRootScrollerNonScrollableNotHandled,
- // Root-scroller, non-scrollable document, handled.
- kCapturingRootScrollerNonScrollableHandled,
- // Root-scroller, scrollable document, already handled.
- kCapturingRootScrollerScrollableDocumentAlreadyHandled,
- // Root-scroller, scrollable document, not handled.
- kCapturingRootScrollerScrollableDocumentNotHandled,
- // Root-scroller, scrollable document, handled.
- kCapturingRootScrollerScrollableDocumentHandled,
-
- // The following enums represent state captured during the AT_TARGET phase.
-
- // Non-root-scroller, non-scrollable document, already handled.
- kNonRootScrollerNonScrollableAlreadyHandled,
- // Non-root-scroller, non-scrollable document, not handled.
- kNonRootScrollerNonScrollableNotHandled,
- // Non-root-scroller, non-scrollable document, handled application.
- kNonRootScrollerNonScrollableHandled,
- // Non-root-scroller, scrollable document, already handled.
- kNonRootScrollerScrollableDocumentAlreadyHandled,
- // Non-root-scroller, scrollable document, not handled.
- kNonRootScrollerScrollableDocumentNotHandled,
- // Non-root-scroller, scrollable document, handled application.
- kNonRootScrollerScrollableDocumentHandled,
- // Root-scroller, non-scrollable document, already handled.
- kRootScrollerNonScrollableAlreadyHandled,
- // Root-scroller, non-scrollable document, not handled.
- kRootScrollerNonScrollableNotHandled,
- // Root-scroller, non-scrollable document, handled.
- kRootScrollerNonScrollableHandled,
- // Root-scroller, scrollable document, already handled.
- kRootScrollerScrollableDocumentAlreadyHandled,
- // Root-scroller, scrollable document, not handled.
- kRootScrollerScrollableDocumentNotHandled,
- // Root-scroller, scrollable document, handled.
- kRootScrollerScrollableDocumentHandled,
-
- // The following enums represent state captured during the BUBBLING_PHASE.
-
- // Non-root-scroller, non-scrollable document, already handled.
- kBubblingNonRootScrollerNonScrollableAlreadyHandled,
- // Non-root-scroller, non-scrollable document, not handled.
- kBubblingNonRootScrollerNonScrollableNotHandled,
- // Non-root-scroller, non-scrollable document, handled application.
- kBubblingNonRootScrollerNonScrollableHandled,
- // Non-root-scroller, scrollable document, already handled.
- kBubblingNonRootScrollerScrollableDocumentAlreadyHandled,
- // Non-root-scroller, scrollable document, not handled.
- kBubblingNonRootScrollerScrollableDocumentNotHandled,
- // Non-root-scroller, scrollable document, handled application.
- kBubblingNonRootScrollerScrollableDocumentHandled,
- // Root-scroller, non-scrollable document, already handled.
- kBubblingRootScrollerNonScrollableAlreadyHandled,
- // Root-scroller, non-scrollable document, not handled.
- kBubblingRootScrollerNonScrollableNotHandled,
- // Root-scroller, non-scrollable document, handled.
- kBubblingRootScrollerNonScrollableHandled,
- // Root-scroller, scrollable document, already handled.
- kBubblingRootScrollerScrollableDocumentAlreadyHandled,
- // Root-scroller, scrollable document, not handled.
- kBubblingRootScrollerScrollableDocumentNotHandled,
- // Root-scroller, scrollable document, handled.
- kBubblingRootScrollerScrollableDocumentHandled,
-
- kTouchTargetAndDispatchResultTypeMax,
-};
-
-void LogTouchTargetHistogram(EventTarget* event_target,
- uint8_t phase,
- bool default_prevented_before_current_target,
- bool default_prevented) {
- int result = 0;
- Document* document = nullptr;
-
- switch (phase) {
- default:
- case Event::kNone:
- return;
- case Event::kCapturingPhase:
- result += kCapturingOffset;
- break;
- case Event::kAtTarget:
- result += kAtTargetOffset;
- break;
- case Event::kBubblingPhase:
- result += kBubblingOffset;
- break;
- }
-
- if (const LocalDOMWindow* dom_window = event_target->ToLocalDOMWindow()) {
- // Treat the window as a root scroller as well.
- document = dom_window->document();
- result += kTouchTargetHistogramRootScrollerOffset;
- } else if (Node* node = event_target->ToNode()) {
- // Report if the target node is the document or body.
- if (node->IsDocumentNode() ||
- node->GetDocument().documentElement() == node ||
- node->GetDocument().body() == node) {
- result += kTouchTargetHistogramRootScrollerOffset;
- }
- document = &node->GetDocument();
- }
-
- if (document) {
- LocalFrameView* view = document->View();
- if (view && view->LayoutViewport()->ScrollsOverflow())
- result += kTouchTargetHistogramScrollableDocumentOffset;
- }
-
- if (default_prevented_before_current_target)
- result += kTouchTargetHistogramAlreadyHandledOffset;
- else if (default_prevented)
- result += kTouchTargetHistogramHandledOffset;
- else
- result += kTouchTargetHistogramNotHandledOffset;
-
- DEFINE_STATIC_LOCAL(EnumerationHistogram, root_document_listener_histogram,
- ("Event.Touch.TargetAndDispatchResult2",
- kTouchTargetAndDispatchResultTypeMax));
- root_document_listener_histogram.Count(
- static_cast<TouchTargetAndDispatchResultType>(result));
-}
-
// Helper function to get WebTouchEvent from WebCoalescedInputEvent.
const WebTouchEvent* GetWebTouchEvent(const WebCoalescedInputEvent& event) {
return static_cast<const WebTouchEvent*>(&event.Event());
@@ -209,8 +54,7 @@ const WebTouchEvent* GetWebTouchEvent(const WebCoalescedInputEvent& event) {
} // namespace
TouchEvent::TouchEvent()
- : default_prevented_before_current_target_(false),
- current_touch_action_(TouchAction::kTouchActionAuto) {}
+ : current_touch_action_(TouchAction::kTouchActionAuto) {}
TouchEvent::TouchEvent(const WebCoalescedInputEvent& event,
TouchList* touches,
@@ -236,7 +80,6 @@ TouchEvent::TouchEvent(const WebCoalescedInputEvent& event,
touches_(touches),
target_touches_(target_touches),
changed_touches_(changed_touches),
- default_prevented_before_current_target_(false),
current_touch_action_(current_touch_action) {
DCHECK(WebInputEvent::IsTouchEventType(event.Event().GetType()));
native_event_.reset(new WebCoalescedInputEvent(event));
@@ -329,20 +172,6 @@ bool TouchEvent::IsTouchStartOrFirstTouchMove() const {
return GetWebTouchEvent(*native_event_)->touch_start_or_first_touch_move;
}
-void TouchEvent::DoneDispatchingEventAtCurrentTarget() {
- // Do not log for non-cancelable events, events that don't block
- // scrolling, have more than one touch point or aren't on the main frame.
- if (!cancelable() || !IsTouchStartOrFirstTouchMove() ||
- !(touches_ && touches_->length() == 1) ||
- !(view() && view()->GetFrame() && view()->GetFrame()->IsMainFrame()))
- return;
-
- bool canceled = defaultPrevented();
- LogTouchTargetHistogram(currentTarget(), eventPhase(),
- default_prevented_before_current_target_, canceled);
- default_prevented_before_current_target_ = canceled;
-}
-
void TouchEvent::Trace(blink::Visitor* visitor) {
visitor->Trace(touches_);
visitor->Trace(target_touches_);
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 f180f0acd23..674a084e07a 100644
--- a/chromium/third_party/blink/renderer/core/events/touch_event.h
+++ b/chromium/third_party/blink/renderer/core/events/touch_event.h
@@ -91,8 +91,6 @@ class CORE_EXPORT TouchEvent final : public UIEventWithKeyState {
void preventDefault() override;
- void DoneDispatchingEventAtCurrentTarget() override;
-
const WebCoalescedInputEvent* NativeEvent() const {
return native_event_.get();
}
@@ -108,8 +106,6 @@ class CORE_EXPORT TouchEvent final : public UIEventWithKeyState {
Member<TouchList> target_touches_;
Member<TouchList> changed_touches_;
- bool default_prevented_before_current_target_;
-
// The current effective touch action computed before each
// touchstart event is generated. It is used for UMA histograms.
TouchAction current_touch_action_;
diff --git a/chromium/third_party/blink/renderer/core/events/touch_event_test.cc b/chromium/third_party/blink/renderer/core/events/touch_event_test.cc
index e94aded4ece..71d5b0ee26d 100644
--- a/chromium/third_party/blink/renderer/core/events/touch_event_test.cc
+++ b/chromium/third_party/blink/renderer/core/events/touch_event_test.cc
@@ -9,9 +9,10 @@
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/core/frame/frame_console.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
-#include "third_party/blink/renderer/core/frame/use_counter.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/instrumentation/use_counter.h"
+#include "third_party/blink/renderer/platform/wtf/vector.h"
using testing::ElementsAre;
@@ -34,14 +35,14 @@ class ConsoleCapturingChromeClient : public EmptyChromeClient {
}
// Expose console output.
- const std::vector<String>& Messages() { return messages_; }
- const std::vector<mojom::ConsoleMessageSource>& MessageSources() {
+ const Vector<String>& Messages() { return messages_; }
+ const Vector<mojom::ConsoleMessageSource>& MessageSources() {
return message_sources_;
}
private:
- std::vector<String> messages_;
- std::vector<mojom::ConsoleMessageSource> message_sources_;
+ Vector<String> messages_;
+ Vector<mojom::ConsoleMessageSource> message_sources_;
};
class TouchEventTest : public PageTestBase {
@@ -55,8 +56,8 @@ class TouchEventTest : public PageTestBase {
Page::InsertOrdinaryPageForTesting(&GetPage());
}
- const std::vector<String>& Messages() { return chrome_client_->Messages(); }
- const std::vector<mojom::ConsoleMessageSource>& MessageSources() {
+ const Vector<String>& Messages() { return chrome_client_->Messages(); }
+ const Vector<mojom::ConsoleMessageSource>& MessageSources() {
return chrome_client_->MessageSources();
}
diff --git a/chromium/third_party/blink/renderer/core/events/transition_event.idl b/chromium/third_party/blink/renderer/core/events/transition_event.idl
index 48e0674b7cf..7d09afc944b 100644
--- a/chromium/third_party/blink/renderer/core/events/transition_event.idl
+++ b/chromium/third_party/blink/renderer/core/events/transition_event.idl
@@ -27,7 +27,8 @@
// https://drafts.csswg.org/css-transitions/#transition-events
[
- Constructor(DOMString type, optional TransitionEventInit eventInitDict)
+ Constructor(DOMString type, optional TransitionEventInit eventInitDict),
+ Exposed=Window
] interface TransitionEvent : Event {
readonly attribute DOMString propertyName;
readonly attribute double elapsedTime;
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 fbb2d01b0b7..8b67e72c6a3 100644
--- a/chromium/third_party/blink/renderer/core/events/ui_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/ui_event.cc
@@ -33,7 +33,7 @@ UIEvent::UIEvent(const AtomicString& event_type,
Bubbles bubbles,
Cancelable cancelable,
ComposedMode composed_mode,
- TimeTicks platform_time_stamp,
+ base::TimeTicks platform_time_stamp,
AbstractView* view_arg,
int detail_arg,
InputDeviceCapabilities* source_capabilities_arg)
@@ -48,7 +48,7 @@ UIEvent::UIEvent(const AtomicString& event_type,
UIEvent::UIEvent(const AtomicString& event_type,
const UIEventInit* initializer,
- TimeTicks platform_time_stamp)
+ base::TimeTicks platform_time_stamp)
: Event(event_type, initializer, platform_time_stamp),
view_(initializer->view()),
detail_(initializer->detail()),
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 2f0757d3966..26bb1daac7f 100644
--- a/chromium/third_party/blink/renderer/core/events/ui_event.h
+++ b/chromium/third_party/blink/renderer/core/events/ui_event.h
@@ -51,15 +51,15 @@ class CORE_EXPORT UIEvent : public Event {
Bubbles,
Cancelable,
ComposedMode,
- TimeTicks platform_time_stamp,
+ base::TimeTicks platform_time_stamp,
AbstractView*,
int detail,
InputDeviceCapabilities* source_capabilities);
UIEvent(const AtomicString&,
const UIEventInit*,
- TimeTicks platform_time_stamp);
+ base::TimeTicks platform_time_stamp);
UIEvent(const AtomicString& type, const UIEventInit* init)
- : UIEvent(type, init, CurrentTimeTicks()) {}
+ : UIEvent(type, init, base::TimeTicks::Now()) {}
~UIEvent() override;
void initUIEvent(const AtomicString& type,
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 9860d401742..de489e9fb73 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
@@ -31,7 +31,7 @@ UIEventWithKeyState::UIEventWithKeyState(
AbstractView* view,
int detail,
WebInputEvent::Modifiers modifiers,
- TimeTicks platform_time_stamp,
+ base::TimeTicks platform_time_stamp,
InputDeviceCapabilities* source_capabilities)
: UIEvent(type,
bubbles,
@@ -45,7 +45,7 @@ UIEventWithKeyState::UIEventWithKeyState(
UIEventWithKeyState::UIEventWithKeyState(const AtomicString& type,
const EventModifierInit* initializer,
- TimeTicks platform_time_stamp)
+ base::TimeTicks platform_time_stamp)
: UIEvent(type, initializer, platform_time_stamp), modifiers_(0) {
if (initializer->ctrlKey())
modifiers_ |= WebInputEvent::kControlKey;
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 0962cb93d77..20f22b5d40e 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
@@ -72,14 +72,14 @@ class CORE_EXPORT UIEventWithKeyState : public UIEvent {
AbstractView*,
int detail,
WebInputEvent::Modifiers,
- TimeTicks platform_time_stamp,
+ base::TimeTicks platform_time_stamp,
InputDeviceCapabilities* source_capabilities = nullptr);
UIEventWithKeyState(const AtomicString& type,
const EventModifierInit* initializer,
- TimeTicks platform_time_stamp);
+ base::TimeTicks platform_time_stamp);
UIEventWithKeyState(const AtomicString& type,
const EventModifierInit* initializer)
- : UIEventWithKeyState(type, initializer, CurrentTimeTicks()) {}
+ : UIEventWithKeyState(type, initializer, base::TimeTicks::Now()) {}
void InitModifiers(bool ctrl_key,
bool alt_key,
bool shift_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 5b1ac749742..bf0e1d18471 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
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/dom/events/event_target.h"
#include "third_party/blink/renderer/core/event_type_names.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/platform/instrumentation/use_counter.h"
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 13471c7cfba..72cf67f1b29 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
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/dom/events/event_target.h"
#include "third_party/blink/renderer/core/event_type_names.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/platform/instrumentation/use_counter.h"
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 1e303160bb2..da06675f5aa 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
@@ -321,7 +321,7 @@ WebKeyboardEventBuilder::WebKeyboardEventBuilder(const KeyboardEvent& event) {
Vector<WebMouseEvent> TransformWebMouseEventVector(
LocalFrameView* frame_view,
- const std::vector<const WebInputEvent*>& coalesced_events) {
+ const WebVector<const WebInputEvent*>& coalesced_events) {
Vector<WebMouseEvent> result;
for (auto* const event : coalesced_events) {
DCHECK(WebInputEvent::IsMouseEventType(event->GetType()));
@@ -333,7 +333,7 @@ Vector<WebMouseEvent> TransformWebMouseEventVector(
Vector<WebPointerEvent> TransformWebPointerEventVector(
LocalFrameView* frame_view,
- const std::vector<const WebInputEvent*>& coalesced_events) {
+ const WebVector<const WebInputEvent*>& coalesced_events) {
float scale = FrameScale(frame_view);
FloatPoint translation = FrameTranslation(frame_view);
Vector<WebPointerEvent> result;
diff --git a/chromium/third_party/blink/renderer/core/events/web_input_event_conversion.h b/chromium/third_party/blink/renderer/core/events/web_input_event_conversion.h
index 18d1681e622..81c55799996 100644
--- a/chromium/third_party/blink/renderer/core/events/web_input_event_conversion.h
+++ b/chromium/third_party/blink/renderer/core/events/web_input_event_conversion.h
@@ -31,7 +31,6 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_EVENTS_WEB_INPUT_EVENT_CONVERSION_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_EVENTS_WEB_INPUT_EVENT_CONVERSION_H_
-#include <vector>
#include "third_party/blink/public/platform/web_coalesced_input_event.h"
#include "third_party/blink/public/platform/web_input_event.h"
#include "third_party/blink/public/platform/web_keyboard_event.h"
@@ -92,10 +91,10 @@ CORE_EXPORT WebPointerEvent TransformWebPointerEvent(LocalFrameView*,
Vector<WebMouseEvent> CORE_EXPORT
TransformWebMouseEventVector(LocalFrameView*,
- const std::vector<const WebInputEvent*>&);
+ const WebVector<const WebInputEvent*>&);
Vector<WebPointerEvent> CORE_EXPORT
TransformWebPointerEventVector(LocalFrameView*,
- const std::vector<const WebInputEvent*>&);
+ const WebVector<const WebInputEvent*>&);
} // namespace blink
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 ad6352becee..4047e3baccf 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
@@ -384,9 +384,9 @@ TEST(WebInputEventConversionTest, InputEventsTransform) {
120);
web_mouse_event2.movement_y = 30;
- std::vector<const WebInputEvent*> events;
- events.push_back(&web_mouse_event1);
- events.push_back(&web_mouse_event2);
+ WebVector<const WebInputEvent*> events;
+ events.emplace_back(&web_mouse_event1);
+ events.emplace_back(&web_mouse_event2);
Vector<WebMouseEvent> coalescedevents =
TransformWebMouseEventVector(view, events);
@@ -558,9 +558,9 @@ TEST(WebInputEventConversionTest, InputEventsTransform) {
WebFloatPoint(120, 90), WebFloatPoint(120, 90)),
60, 30);
- std::vector<const WebInputEvent*> events;
- events.push_back(&web_pointer_event1);
- events.push_back(&web_pointer_event2);
+ WebVector<const WebInputEvent*> events;
+ events.emplace_back(&web_pointer_event1);
+ events.emplace_back(&web_pointer_event2);
Vector<WebPointerEvent> coalescedevents =
TransformWebPointerEventVector(view, events);
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 1a00d01282a..df4b42305e6 100644
--- a/chromium/third_party/blink/renderer/core/events/wheel_event.cc
+++ b/chromium/third_party/blink/renderer/core/events/wheel_event.cc
@@ -28,7 +28,7 @@
#include "third_party/blink/renderer/core/event_interface_names.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/use_counter.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/execution_context/context_lifecycle_state_observer.cc b/chromium/third_party/blink/renderer/core/execution_context/context_lifecycle_state_observer.cc
index 811db206e0e..f0dcd0a9284 100644
--- a/chromium/third_party/blink/renderer/core/execution_context/context_lifecycle_state_observer.cc
+++ b/chromium/third_party/blink/renderer/core/execution_context/context_lifecycle_state_observer.cc
@@ -27,7 +27,7 @@
#include "third_party/blink/renderer/core/execution_context/context_lifecycle_state_observer.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
-#include "third_party/blink/renderer/platform/instance_counters.h"
+#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h"
namespace blink {
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 b5b69f6310f..c1738656b66 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
@@ -36,30 +36,37 @@
#include "third_party/blink/renderer/core/execution_context/context_lifecycle_state_observer.h"
#include "third_party/blink/renderer/core/fileapi/public_url_manager.h"
#include "third_party/blink/renderer/core/frame/csp/execution_context_csp_delegate.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/origin_trials/origin_trial_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_global_scope.h"
#include "third_party/blink/renderer/core/workers/worker_thread.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object_snapshot.h"
#include "third_party/blink/renderer/platform/loader/fetch/memory_cache.h"
#include "third_party/blink/renderer/platform/mojo/interface_invalidator.h"
+#include "third_party/blink/renderer/platform/scheduler/public/event_loop.h"
#include "third_party/blink/renderer/platform/weborigin/security_policy.h"
namespace blink {
-ExecutionContext::ExecutionContext(v8::Isolate* isolate, Agent* agent)
+ExecutionContext::ExecutionContext(v8::Isolate* isolate,
+ Agent* agent,
+ OriginTrialContext* origin_trial_context)
: isolate_(isolate),
circular_sequential_id_(0),
in_dispatch_error_event_(false),
is_context_destroyed_(false),
csp_delegate_(MakeGarbageCollected<ExecutionContextCSPDelegate>(*this)),
agent_(agent),
+ origin_trial_context_(origin_trial_context),
window_interaction_tokens_(0),
referrer_policy_(network::mojom::ReferrerPolicy::kDefault),
- invalidator_(std::make_unique<InterfaceInvalidator>()) {}
+ invalidator_(std::make_unique<InterfaceInvalidator>()) {
+ if (origin_trial_context_)
+ origin_trial_context_->BindExecutionContext(this);
+}
ExecutionContext::~ExecutionContext() = default;
@@ -102,11 +109,6 @@ void ExecutionContext::NotifyContextDestroyed() {
ContextLifecycleNotifier::NotifyContextDestroyed();
}
-bool ExecutionContext::FeatureEnabled(OriginTrialFeature feature) const {
- const OriginTrialContext* context = OriginTrialContext::From(this);
- return context && context->IsFeatureEnabled(feature);
-}
-
void ExecutionContext::AddConsoleMessageImpl(mojom::ConsoleMessageSource source,
mojom::ConsoleMessageLevel level,
const String& message,
@@ -266,6 +268,7 @@ void ExecutionContext::Trace(blink::Visitor* visitor) {
visitor->Trace(pending_exceptions_);
visitor->Trace(csp_delegate_);
visitor->Trace(agent_);
+ visitor->Trace(origin_trial_context_);
ContextLifecycleNotifier::Trace(visitor);
ConsoleLogger::Trace(visitor);
Supplementable<ExecutionContext>::Trace(visitor);
@@ -281,6 +284,31 @@ bool ExecutionContext::IsSameAgentCluster(
return this_id == other_id;
}
+v8::MicrotaskQueue* ExecutionContext::GetMicrotaskQueue() const {
+ // TODO(keishi): Convert to DCHECK once we assign agents everywhere.
+ if (!agent_)
+ return nullptr;
+ DCHECK(agent_->event_loop());
+ return agent_->event_loop()->microtask_queue();
+}
+
+bool ExecutionContext::FeatureEnabled(OriginTrialFeature feature) const {
+ return origin_trial_context_ &&
+ origin_trial_context_->IsFeatureEnabled(feature);
+}
+
+void ExecutionContext::CountFeaturePolicyUsage(mojom::WebFeature feature) {
+ UseCounter::Count(*this, feature);
+}
+
+bool ExecutionContext::FeaturePolicyFeatureObserved(
+ mojom::FeaturePolicyFeature feature) {
+ if (parsed_feature_policies_[static_cast<size_t>(feature)])
+ return true;
+ parsed_feature_policies_.set(static_cast<size_t>(feature));
+ return false;
+}
+
bool ExecutionContext::RequireTrustedTypes() const {
return GetSecurityContext().TrustedTypesRequiredByPolicy() &&
RuntimeEnabledFeatures::TrustedDOMTypesEnabled(this);
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 381f59b7e26..084fdb384af 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
@@ -28,6 +28,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_EXECUTION_CONTEXT_EXECUTION_CONTEXT_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_EXECUTION_CONTEXT_EXECUTION_CONTEXT_H_
+#include <bitset>
#include <memory>
#include "base/location.h"
@@ -39,8 +40,9 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/execution_context/context_lifecycle_notifier.h"
#include "third_party/blink/renderer/core/execution_context/context_lifecycle_observer.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
+#include "third_party/blink/renderer/core/feature_policy/feature_policy_parser_delegate.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/loader/fetch/console_logger.h"
#include "third_party/blink/renderer/platform/loader/fetch/https_state.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
@@ -81,6 +83,7 @@ class FrameOrWorkerScheduler;
class InterfaceInvalidator;
class KURL;
class LocalDOMWindow;
+class OriginTrialContext;
class PublicURLManager;
class ResourceFetcher;
class SecurityContext;
@@ -123,7 +126,7 @@ class CORE_EXPORT ExecutionContext : public ContextLifecycleNotifier,
public Supplementable<ExecutionContext>,
public ConsoleLogger,
public UseCounter,
- public FeatureContext {
+ public FeaturePolicyParserDelegate {
MERGE_GARBAGE_COLLECTED_MIXINS();
public:
@@ -213,9 +216,6 @@ class CORE_EXPORT ExecutionContext : public ContextLifecycleNotifier,
void SetLifecycleState(mojom::FrameLifecycleState);
void NotifyContextDestroyed() override;
- // FeatureContext override
- bool FeatureEnabled(OriginTrialFeature) const override;
-
using ConsoleLogger::AddConsoleMessage;
void AddConsoleMessage(ConsoleMessage* message,
@@ -298,19 +298,28 @@ class CORE_EXPORT ExecutionContext : public ContextLifecycleNotifier,
v8::Isolate* GetIsolate() const { return isolate_; }
Agent* GetAgent() const { return agent_; }
+ v8::MicrotaskQueue* GetMicrotaskQueue() const;
+
+ OriginTrialContext* GetOriginTrialContext() const {
+ return origin_trial_context_;
+ }
+
virtual TrustedTypePolicyFactory* GetTrustedTypes() const { return nullptr; }
+ // FeaturePolicyParserDelegate override
+ bool FeatureEnabled(OriginTrialFeature) const override;
+ void CountFeaturePolicyUsage(mojom::WebFeature feature) override;
+ bool FeaturePolicyFeatureObserved(
+ mojom::FeaturePolicyFeature feature) override;
+
bool RequireTrustedTypes() const;
protected:
- explicit ExecutionContext(v8::Isolate* isolate, Agent* agent);
+ ExecutionContext(v8::Isolate* isolate,
+ Agent* agent,
+ OriginTrialContext* origin_trial_context);
~ExecutionContext() override;
- void SetAgent(Agent* agent) {
- DCHECK(agent);
- agent_ = agent;
- }
-
private:
// ConsoleLogger implementation.
void AddConsoleMessageImpl(mojom::ConsoleMessageSource,
@@ -340,6 +349,8 @@ class CORE_EXPORT ExecutionContext : public ContextLifecycleNotifier,
Member<Agent> agent_;
+ Member<OriginTrialContext> origin_trial_context_;
+
// Counter that keeps track of how many window interaction calls are allowed
// for this ExecutionContext. Callers are expected to call
// |allowWindowInteraction()| and |consumeWindowInteraction()| in order to
@@ -350,6 +361,11 @@ class CORE_EXPORT ExecutionContext : public ContextLifecycleNotifier,
std::unique_ptr<InterfaceInvalidator> invalidator_;
+ // Tracks which feature policies have already been parsed, so as not to count
+ // them multiple times.
+ std::bitset<static_cast<size_t>(mojom::FeaturePolicyFeature::kMaxValue) + 1>
+ parsed_feature_policies_;
+
DISALLOW_COPY_AND_ASSIGN(ExecutionContext);
};
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 d8138e2b7f1..f2670bd81c9 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
@@ -5,6 +5,7 @@
#include "third_party/blink/renderer/core/execution_context/remote_security_context.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.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/assertions.h"
@@ -40,8 +41,37 @@ void RemoteSecurityContext::ResetReplicatedContentSecurityPolicy() {
GetContentSecurityPolicy()->SetupSelf(*GetSecurityOrigin());
}
-void RemoteSecurityContext::ResetSandboxFlags() {
- sandbox_flags_ = WebSandboxFlags::kNone;
+void RemoteSecurityContext::ResetAndEnforceSandboxFlags(WebSandboxFlags flags) {
+ sandbox_flags_ = flags;
+
+ if (IsSandboxed(WebSandboxFlags::kOrigin) && GetSecurityOrigin() &&
+ !GetSecurityOrigin()->IsOpaque()) {
+ SetSecurityOrigin(GetSecurityOrigin()->DeriveNewOpaqueOrigin());
+ }
+}
+
+void RemoteSecurityContext::InitializeFeaturePolicy(
+ const ParsedFeaturePolicy& parsed_header,
+ const ParsedFeaturePolicy& container_policy,
+ const FeaturePolicy* parent_feature_policy,
+ const FeaturePolicy::FeatureState* opener_feature_state) {
+ // Feature policy should either come from a parent in the case of an embedded
+ // child frame, or from an opener if any when a new window is created by an
+ // opener. A main frame without an opener would not have a parent policy nor
+ // an opener feature state.
+ DCHECK(!parent_feature_policy || !opener_feature_state);
+ report_only_feature_policy_ = nullptr;
+ if (!opener_feature_state ||
+ !RuntimeEnabledFeatures::FeaturePolicyForSandboxEnabled()) {
+ feature_policy_ = FeaturePolicy::CreateFromParentPolicy(
+ parent_feature_policy, container_policy,
+ security_origin_->ToUrlOrigin());
+ } else {
+ DCHECK(!parent_feature_policy);
+ feature_policy_ = FeaturePolicy::CreateWithOpenerPolicy(
+ *opener_feature_state, security_origin_->ToUrlOrigin());
+ }
+ feature_policy_->SetHeaderPolicy(parsed_header);
}
} // namespace blink
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 28c511b9f0c..9ef0272e5d8 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
@@ -23,10 +23,24 @@ class CORE_EXPORT RemoteSecurityContext
void SetReplicatedOrigin(scoped_refptr<SecurityOrigin>);
void ResetReplicatedContentSecurityPolicy();
- void ResetSandboxFlags();
-
- // FIXME: implement
- void DidUpdateSecurityOrigin() override {}
+ void ResetAndEnforceSandboxFlags(WebSandboxFlags flags);
+
+ // Constructs the enforcement FeaturePolicy struct for this security context.
+ // The resulting FeaturePolicy is a combination of:
+ // * |parsed_header|: from the FeaturePolicy part of the response headers.
+ // * |container_policy|: from <iframe>'s allow attribute.
+ // * |parent_feature_policy|: which is the current state of feature policies
+ // in a parent browsing context (frame).
+ // * |opener_feature_state|: the current state of the policies in an opener
+ // if any.
+ // Note that at most one of the |parent_feature_policy| or
+ // |opener_feature_state| should be provided. The |container_policy| is empty
+ // for a top-level security context.
+ void InitializeFeaturePolicy(
+ const ParsedFeaturePolicy& parsed_header,
+ const ParsedFeaturePolicy& container_policy,
+ const FeaturePolicy* parent_feature_policy,
+ const FeaturePolicy::FeatureState* opener_feature_state);
};
} // 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 0f0cd2b6f1d..b87c486a599 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
@@ -68,21 +68,28 @@ inline const char* GetImagePolicyHistogramName(
} // namespace
// static
-std::vector<unsigned> SecurityContext::SerializeInsecureNavigationSet(
+WebVector<unsigned> SecurityContext::SerializeInsecureNavigationSet(
const InsecureNavigationsSet& set) {
// The set is serialized as a sorted array. Sorting it makes it easy to know
// if two serialized sets are equal.
- std::vector<unsigned> serialized;
+ WebVector<unsigned> serialized;
serialized.reserve(set.size());
for (unsigned host : set)
- serialized.push_back(host);
+ serialized.emplace_back(host);
std::sort(serialized.begin(), serialized.end());
return serialized;
}
SecurityContext::SecurityContext()
- : sandbox_flags_(WebSandboxFlags::kNone),
+ : SecurityContext(nullptr, WebSandboxFlags::kNone, nullptr) {}
+
+SecurityContext::SecurityContext(scoped_refptr<SecurityOrigin> origin,
+ WebSandboxFlags sandbox_flags,
+ std::unique_ptr<FeaturePolicy> feature_policy)
+ : sandbox_flags_(sandbox_flags),
+ security_origin_(std::move(origin)),
+ feature_policy_(std::move(feature_policy)),
address_space_(mojom::IPAddressSpace::kPublic),
insecure_request_policy_(kLeaveInsecureRequestsAlone),
require_safe_types_(false) {}
@@ -144,25 +151,6 @@ bool SecurityContext::IsSandboxed(WebSandboxFlags mask) const {
return (sandbox_flags_ & mask) != WebSandboxFlags::kNone;
}
-void SecurityContext::EnforceSandboxFlags(WebSandboxFlags mask) {
- ApplySandboxFlags(mask);
-}
-
-void SecurityContext::ApplySandboxFlags(WebSandboxFlags mask,
- bool is_potentially_trustworthy) {
- sandbox_flags_ |= mask;
-
- if (IsSandboxed(WebSandboxFlags::kOrigin) && GetSecurityOrigin() &&
- !GetSecurityOrigin()->IsOpaque()) {
- scoped_refptr<SecurityOrigin> security_origin =
- GetSecurityOrigin()->DeriveNewOpaqueOrigin();
- security_origin->SetOpaqueOriginIsPotentiallyTrustworthy(
- is_potentially_trustworthy);
- SetSecurityOrigin(std::move(security_origin));
- DidUpdateSecurityOrigin();
- }
-}
-
String SecurityContext::addressSpaceForBindings() const {
switch (address_space_) {
case mojom::IPAddressSpace::kPublic:
@@ -199,36 +187,6 @@ void SecurityContext::SetFeaturePolicy(
feature_policy_ = std::move(feature_policy);
}
-void SecurityContext::InitializeFeaturePolicy(
- const ParsedFeaturePolicy& parsed_header,
- const ParsedFeaturePolicy& container_policy,
- const FeaturePolicy* parent_feature_policy,
- const FeaturePolicy::FeatureState* opener_feature_state) {
- // Feature policy should either come from a parent in the case of an embedded
- // child frame, or from an opener if any when a new window is created by an
- // opener. A main frame without an opener would not have a parent policy nor
- // an opener feature state.
- DCHECK(!parent_feature_policy || !opener_feature_state);
- report_only_feature_policy_ = nullptr;
- if (!HasCustomizedFeaturePolicy()) {
- feature_policy_ = FeaturePolicy::CreateFromParentPolicy(
- nullptr, {}, security_origin_->ToUrlOrigin());
- return;
- }
-
- if (!opener_feature_state ||
- !RuntimeEnabledFeatures::FeaturePolicyForSandboxEnabled()) {
- feature_policy_ = FeaturePolicy::CreateFromParentPolicy(
- parent_feature_policy, container_policy,
- security_origin_->ToUrlOrigin());
- } else {
- DCHECK(!parent_feature_policy);
- feature_policy_ = FeaturePolicy::CreateWithOpenerPolicy(
- *opener_feature_state, security_origin_->ToUrlOrigin());
- }
- feature_policy_->SetHeaderPolicy(parsed_header);
-}
-
// Uses the parent enforcing policy as the basis for the report-only policy.
void SecurityContext::AddReportOnlyFeaturePolicy(
const ParsedFeaturePolicy& parsed_report_only_header,
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 8e39a29a5aa..0324d2aee37 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
@@ -31,6 +31,7 @@
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/public/common/feature_policy/feature_policy.h"
#include "third_party/blink/public/platform/web_insecure_request_policy.h"
+#include "third_party/blink/public/platform/web_vector.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/platform/heap/handle.h"
@@ -72,7 +73,7 @@ class CORE_EXPORT SecurityContext : public GarbageCollectedMixin {
void Trace(blink::Visitor*) override;
using InsecureNavigationsSet = HashSet<unsigned, WTF::AlreadyHashed>;
- static std::vector<unsigned> SerializeInsecureNavigationSet(
+ static WebVector<unsigned> SerializeInsecureNavigationSet(
const InsecureNavigationsSet&);
const SecurityOrigin* GetSecurityOrigin() const {
@@ -87,12 +88,10 @@ class CORE_EXPORT SecurityContext : public GarbageCollectedMixin {
// Explicitly override the security origin for this security context.
// Note: It is dangerous to change the security origin of a script context
// that already contains content.
- void SetSecurityOrigin(scoped_refptr<SecurityOrigin>);
- virtual void DidUpdateSecurityOrigin() = 0;
+ virtual void SetSecurityOrigin(scoped_refptr<SecurityOrigin>);
WebSandboxFlags GetSandboxFlags() const { return sandbox_flags_; }
bool IsSandboxed(WebSandboxFlags mask) const;
- virtual void EnforceSandboxFlags(WebSandboxFlags mask);
void SetAddressSpace(mojom::IPAddressSpace space) { address_space_ = space; }
mojom::IPAddressSpace AddressSpace() const { return address_space_; }
@@ -103,7 +102,7 @@ class CORE_EXPORT SecurityContext : public GarbageCollectedMixin {
bool TrustedTypesRequiredByPolicy() const;
// https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-insecure-navigations-set
- void SetInsecureNavigationsSet(const std::vector<unsigned>& set) {
+ void SetInsecureNavigationsSet(const WebVector<unsigned>& set) {
insecure_navigations_to_upgrade_.clear();
for (unsigned hash : set)
insecure_navigations_to_upgrade_.insert(hash);
@@ -135,22 +134,6 @@ class CORE_EXPORT SecurityContext : public GarbageCollectedMixin {
return feature_policy_.get();
}
void SetFeaturePolicy(std::unique_ptr<FeaturePolicy> feature_policy);
- // Constructs the enforcement FeaturePolicy struct for this security context.
- // The resulted FeaturePolicy is a combination of:
- // * |parsed_header|: from the FeaturePolicy part of the response headers.
- // * |container_policy|: from <iframe>'s allow attribute.
- // * |parent_feature_policy|: which is the current state of feature policies
- // in a parent browsing context (frame).
- // * |opener_feature_state|: the current state of the policies in an opener
- // if any.
- // Note that at most one of the |parent_feature_policy| or
- // |opener_feature_state| should be provided. The |container_policy| is empty
- // for a top-level security context.
- void InitializeFeaturePolicy(
- const ParsedFeaturePolicy& parsed_header,
- const ParsedFeaturePolicy& container_policy,
- const FeaturePolicy* parent_feature_policy,
- const FeaturePolicy::FeatureState* opener_feature_state);
void AddReportOnlyFeaturePolicy(
const ParsedFeaturePolicy& parsed_report_only_header,
const ParsedFeaturePolicy& container_policy,
@@ -180,31 +163,23 @@ class CORE_EXPORT SecurityContext : public GarbageCollectedMixin {
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
- // potentially trustworthy bit from |is_potentially_trustworthy|.
- void ApplySandboxFlags(WebSandboxFlags mask,
- bool is_potentially_trustworthy = false);
-
protected:
SecurityContext();
+ SecurityContext(scoped_refptr<SecurityOrigin> origin,
+ WebSandboxFlags sandbox_flags,
+ std::unique_ptr<FeaturePolicy> feature_policy);
virtual ~SecurityContext();
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; }
-
WebSandboxFlags 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_;
+ private:
+ Member<ContentSecurityPolicy> content_security_policy_;
+
mojom::IPAddressSpace address_space_;
WebInsecureRequestPolicy insecure_request_policy_;
bool mixed_autoupgrade_opt_out_;
diff --git a/chromium/third_party/blink/renderer/core/execution_context/window_agent.cc b/chromium/third_party/blink/renderer/core/execution_context/window_agent.cc
index 2d9ac181390..1d67764baae 100644
--- a/chromium/third_party/blink/renderer/core/execution_context/window_agent.cc
+++ b/chromium/third_party/blink/renderer/core/execution_context/window_agent.cc
@@ -3,18 +3,21 @@
// found in the LICENSE file.
#include "third_party/blink/renderer/core/execution_context/window_agent.h"
-#include "third_party/blink/renderer/core/dom/mutation_observer.h"
-#include "third_party/blink/renderer/core/html/custom/custom_element_reaction_stack.h"
-#include "third_party/blink/renderer/platform/scheduler/public/event_loop.h"
+
+#include "third_party/blink/renderer/core/dom/mutation_observer_notifier.h"
namespace blink {
-WindowAgent::WindowAgent(v8::Isolate* isolate) : Agent(isolate) {}
+WindowAgent::WindowAgent(v8::Isolate* isolate)
+ : Agent(isolate),
+ mutation_observer_notifier_(
+ MakeGarbageCollected<MutationObserverNotifier>()) {}
WindowAgent::~WindowAgent() = default;
void WindowAgent::Trace(Visitor* visitor) {
Agent::Trace(visitor);
+ visitor->Trace(mutation_observer_notifier_);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/execution_context/window_agent.h b/chromium/third_party/blink/renderer/core/execution_context/window_agent.h
index 3775250d2af..df47d5d393e 100644
--- a/chromium/third_party/blink/renderer/core/execution_context/window_agent.h
+++ b/chromium/third_party/blink/renderer/core/execution_context/window_agent.h
@@ -6,7 +6,6 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_EXECUTION_CONTEXT_WINDOW_AGENT_H_
#include "third_party/blink/renderer/core/execution_context/agent.h"
-#include "third_party/blink/renderer/platform/heap/heap.h"
namespace v8 {
class Isolate;
@@ -14,6 +13,8 @@ class Isolate;
namespace blink {
+class MutationObserverNotifier;
+
// This corresponds to similar-origin window agent, that is shared by a group
// of Documents that are mutually reachable and have the same-site origins.
// https://html.spec.whatwg.org/C#similar-origin-window-agent
@@ -29,10 +30,16 @@ class WindowAgent final : public Agent {
void Trace(blink::Visitor*) override;
+ MutationObserverNotifier& GetMutationObserverNotifier() {
+ return *mutation_observer_notifier_;
+ }
+
private:
+ // For MutationObserver.
+ Member<MutationObserverNotifier> mutation_observer_notifier_;
+
// TODO(tzik): Move per-agent data here with the correct granularity.
- // E.g. ActiveMutationObservers and CustomElementReactionStack should move
- // here.
+ // E.g. CustomElementReactionStack should move here.
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/exported/BUILD.gn b/chromium/third_party/blink/renderer/core/exported/BUILD.gn
index ac43281e88d..b0afed24b0a 100644
--- a/chromium/third_party/blink/renderer/core/exported/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/exported/BUILD.gn
@@ -5,18 +5,10 @@ import("//third_party/blink/renderer/core/core.gni")
blink_core_sources("exported") {
sources = [
- "application_cache_host_for_shared_worker.cc",
- "application_cache_host_for_shared_worker.h",
"local_frame_client_impl.cc",
"local_frame_client_impl.h",
- "renderer_webapplicationcachehost_impl.cc",
- "renderer_webapplicationcachehost_impl.h",
- "web_application_cache_host_impl.cc",
- "web_application_cache_host_impl.h",
"web_array_buffer.cc",
"web_array_buffer_converter.cc",
- "web_associated_url_loader_impl.cc",
- "web_associated_url_loader_impl.h",
"web_blob.cc",
"web_console_message.cc",
"web_content_holder.cc",
@@ -50,6 +42,7 @@ blink_core_sources("exported") {
"web_language_detection_details.cc",
"web_local_frame_client.cc",
"web_memory_statistics.cc",
+ "web_message_port_converter.cc",
"web_meta_element.cc",
"web_navigation_params.cc",
"web_node.cc",
@@ -66,6 +59,7 @@ blink_core_sources("exported") {
"web_remote_frame_impl.cc",
"web_remote_frame_impl.h",
"web_render_theme.cc",
+ "web_scoped_page_pauser.cc",
"web_scoped_user_gesture.cc",
"web_scoped_window_focus_allowed_indicator.cc",
"web_script_controller.cc",
diff --git a/chromium/third_party/blink/renderer/core/exported/application_cache_host_for_shared_worker.cc b/chromium/third_party/blink/renderer/core/exported/application_cache_host_for_shared_worker.cc
deleted file mode 100644
index e178c0e0606..00000000000
--- a/chromium/third_party/blink/renderer/core/exported/application_cache_host_for_shared_worker.cc
+++ /dev/null
@@ -1,54 +0,0 @@
-// Copyright 2019 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "third_party/blink/renderer/core/exported/application_cache_host_for_shared_worker.h"
-
-namespace blink {
-
-ApplicationCacheHostForSharedWorker::ApplicationCacheHostForSharedWorker(
- WebApplicationCacheHostClient* client,
- const base::UnguessableToken& appcache_host_id,
- scoped_refptr<base::SingleThreadTaskRunner> task_runner)
- : WebApplicationCacheHostImpl(nullptr /* WebLocalFrame* */,
- client,
- appcache_host_id,
- std::move(task_runner)) {}
-
-ApplicationCacheHostForSharedWorker::~ApplicationCacheHostForSharedWorker() =
- default;
-
-void ApplicationCacheHostForSharedWorker::WillStartMainResourceRequest(
- const WebURL& url,
- const String& method,
- const WebApplicationCacheHost* spawning_host) {}
-
-void ApplicationCacheHostForSharedWorker::DidReceiveResponseForMainResource(
- const WebURLResponse&) {}
-
-void ApplicationCacheHostForSharedWorker::SelectCacheWithoutManifest() {}
-
-bool ApplicationCacheHostForSharedWorker::SelectCacheWithManifest(
- const WebURL& manifestURL) {
- return true;
-}
-
-void ApplicationCacheHostForSharedWorker::LogMessage(
- mojom::blink::ConsoleMessageLevel log_level,
- const String& message) {}
-
-void ApplicationCacheHostForSharedWorker::SetSubresourceFactory(
- network::mojom::blink::URLLoaderFactoryPtr url_loader_factory) {}
-
-std::unique_ptr<WebApplicationCacheHost>
-WebApplicationCacheHost::CreateWebApplicationCacheHostForSharedWorker(
- WebApplicationCacheHostClient* client,
- const base::UnguessableToken& appcache_host_id,
- scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
- auto application_cache_host_for_shared_worker =
- std::make_unique<ApplicationCacheHostForSharedWorker>(
- client, appcache_host_id, std::move(task_runner));
- return std::move(application_cache_host_for_shared_worker);
-}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/exported/application_cache_host_for_shared_worker.h b/chromium/third_party/blink/renderer/core/exported/application_cache_host_for_shared_worker.h
deleted file mode 100644
index 922fb8f8104..00000000000
--- a/chromium/third_party/blink/renderer/core/exported/application_cache_host_for_shared_worker.h
+++ /dev/null
@@ -1,46 +0,0 @@
-// Copyright 2019 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_EXPORTED_APPLICATION_CACHE_HOST_FOR_SHARED_WORKER_H_
-#define THIRD_PARTY_BLINK_RENDERER_CORE_EXPORTED_APPLICATION_CACHE_HOST_FOR_SHARED_WORKER_H_
-
-#include "base/unguessable_token.h"
-#include "third_party/blink/renderer/core/exported/web_application_cache_host_impl.h"
-
-namespace blink {
-
-class ApplicationCacheHostForSharedWorker final
- : public WebApplicationCacheHostImpl {
- public:
- ApplicationCacheHostForSharedWorker(
- WebApplicationCacheHostClient* client,
- const base::UnguessableToken& appcache_host_id,
- scoped_refptr<base::SingleThreadTaskRunner> task_runner);
- ~ApplicationCacheHostForSharedWorker() override;
-
- // Main resource loading is different for workers. The main resource is
- // loaded by the worker using WorkerClassicScriptLoader.
- // These overrides are stubbed out.
- void WillStartMainResourceRequest(
- const WebURL& url,
- const String& method,
- const WebApplicationCacheHost* spawning_host) override;
- void DidReceiveResponseForMainResource(const WebURLResponse&) override;
-
- // Cache selection is also different for workers. We know at construction
- // time what cache to select and do so then.
- // These overrides are stubbed out.
- void SelectCacheWithoutManifest() override;
- bool SelectCacheWithManifest(const WebURL& manifestURL) override;
-
- // mojom::blink::AppCacheFrontend:
- void LogMessage(mojom::blink::ConsoleMessageLevel log_level,
- const String& message) override;
- void SetSubresourceFactory(
- network::mojom::blink::URLLoaderFactoryPtr url_loader_factory) override;
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_CORE_EXPORTED_APPLICATION_CACHE_HOST_FOR_SHARED_WORKER_H_
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 d2c64ae89fa..95cd13bd1c5 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
@@ -47,7 +47,6 @@
#include "third_party/blink/public/platform/web_url.h"
#include "third_party/blink/public/platform/web_url_error.h"
#include "third_party/blink/public/platform/web_vector.h"
-#include "third_party/blink/public/web/web_application_cache_host.h"
#include "third_party/blink/public/web/web_autofill_client.h"
#include "third_party/blink/public/web/web_document.h"
#include "third_party/blink/public/web/web_dom_event.h"
@@ -93,11 +92,10 @@
#include "third_party/blink/renderer/core/page/plugin_data.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/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.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/wtf/text/cstring.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "v8/include/v8.h"
@@ -761,10 +759,10 @@ void LocalFrameClientImpl::DidObserveNewCssPropertyUsage(int css_property,
}
}
-void LocalFrameClientImpl::DidObserveLayoutJank(double jank_fraction,
- bool after_input_or_scroll) {
+void LocalFrameClientImpl::DidObserveLayoutShift(double score,
+ bool after_input_or_scroll) {
if (WebLocalFrameClient* client = web_frame_->Client())
- client->DidObserveLayoutJank(jank_fraction, after_input_or_scroll);
+ client->DidObserveLayoutShift(score, after_input_or_scroll);
}
void LocalFrameClientImpl::DidObserveLazyLoadBehavior(
@@ -856,10 +854,10 @@ LocalFrame* LocalFrameClientImpl::CreateFrame(
std::pair<RemoteFrame*, base::UnguessableToken>
LocalFrameClientImpl::CreatePortal(
HTMLPortalElement* portal,
- mojom::blink::PortalAssociatedRequest request,
- mojom::blink::PortalClientAssociatedPtrInfo client) {
- return web_frame_->CreatePortal(portal, std::move(request),
- std::move(client));
+ mojo::PendingAssociatedReceiver<mojom::blink::Portal> portal_receiver,
+ mojo::PendingAssociatedRemote<mojom::blink::PortalClient> portal_client) {
+ return web_frame_->CreatePortal(portal, std::move(portal_receiver),
+ std::move(portal_client));
}
RemoteFrame* LocalFrameClientImpl::AdoptPortal(HTMLPortalElement* portal) {
@@ -921,12 +919,6 @@ WebRemotePlaybackClient* LocalFrameClientImpl::CreateWebRemotePlaybackClient(
html_media_element);
}
-WebCookieJar* LocalFrameClientImpl::CookieJar() const {
- if (!web_frame_->Client())
- return nullptr;
- return web_frame_->Client()->CookieJar();
-}
-
void LocalFrameClientImpl::FrameFocused() const {
if (web_frame_->Client())
web_frame_->Client()->FrameFocused();
@@ -946,7 +938,7 @@ void LocalFrameClientImpl::DidEnforceInsecureRequestPolicy(
}
void LocalFrameClientImpl::DidEnforceInsecureNavigationsSet(
- const std::vector<unsigned>& set) {
+ const WebVector<unsigned>& set) {
if (!web_frame_->Client())
return;
web_frame_->Client()->DidEnforceInsecureNavigationsSet(set);
@@ -1012,16 +1004,6 @@ WebContentSettingsClient* LocalFrameClientImpl::GetContentSettingsClient() {
return web_frame_->GetContentSettingsClient();
}
-std::unique_ptr<WebApplicationCacheHost>
-LocalFrameClientImpl::CreateApplicationCacheHost(
- DocumentLoader* loader,
- WebApplicationCacheHostClient* client) {
- if (!web_frame_->Client())
- return nullptr;
- return web_frame_->Client()->CreateApplicationCacheHost(
- WebDocumentLoaderImpl::FromDocumentLoader(loader), client);
-}
-
void LocalFrameClientImpl::DispatchDidChangeManifest() {
CoreInitializer::GetInstance().DidChangeManifest(*web_frame_->GetFrame());
}
@@ -1158,8 +1140,11 @@ void LocalFrameClientImpl::AnnotatedRegionsChanged() {
web_frame_->Client()->DraggableRegionsChanged();
}
-void LocalFrameClientImpl::DidBlockFramebust(const KURL& url) {
- web_frame_->Client()->DidBlockFramebust(url);
+void LocalFrameClientImpl::DidBlockNavigation(
+ const KURL& blocked_url,
+ const KURL& initiator_url,
+ blink::NavigationBlockedReason reason) {
+ web_frame_->Client()->DidBlockNavigation(blocked_url, initiator_url, reason);
}
base::UnguessableToken LocalFrameClientImpl::GetDevToolsFrameToken() const {
@@ -1213,6 +1198,11 @@ void LocalFrameClientImpl::FrameRectsChanged(const IntRect& frame_rect) {
web_frame_->Client()->FrameRectsChanged(frame_rect);
}
+void LocalFrameClientImpl::LifecycleStateChanged(
+ mojom::FrameLifecycleState state) {
+ web_frame_->Client()->LifecycleStateChanged(state);
+}
+
bool LocalFrameClientImpl::IsPluginHandledExternally(
HTMLPlugInElement& plugin_element,
const KURL& resource_url,
@@ -1264,6 +1254,17 @@ void LocalFrameClientImpl::TransferUserActivationFrom(
WebLocalFrameImpl::FromFrame(source_frame));
}
+void LocalFrameClientImpl::UpdateSubresourceFactory(
+ std::unique_ptr<blink::URLLoaderFactoryBundleInfo> info) {
+ DCHECK(web_frame_->Client());
+ web_frame_->Client()->UpdateSubresourceFactory(std::move(info));
+}
+
+WebLocalFrameClient::AppCacheType LocalFrameClientImpl::GetAppCacheType() {
+ DCHECK(web_frame_->Client());
+ return web_frame_->Client()->GetAppCacheType();
+}
+
STATIC_ASSERT_ENUM(DownloadCrossOriginRedirects::kFollow,
WebLocalFrameClient::CrossOriginRedirects::kFollow);
STATIC_ASSERT_ENUM(DownloadCrossOriginRedirects::kNavigate,
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 74725eaf9db..991a32bfe9a 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
@@ -150,8 +150,7 @@ class LocalFrameClientImpl final : public LocalFrameClient {
void DidObserveLoadingBehavior(WebLoadingBehaviorFlag) override;
void DidObserveNewFeatureUsage(mojom::WebFeature) override;
void DidObserveNewCssPropertyUsage(int, bool) override;
- void DidObserveLayoutJank(double jank_fraction,
- bool after_input_or_scroll) override;
+ void DidObserveLayoutShift(double score, bool after_input_or_scroll) override;
void DidObserveLazyLoadBehavior(
WebLocalFrameClient::LazyLoadBehavior lazy_load_behavior) override;
bool ShouldTrackUseCounter(const KURL&) override;
@@ -182,8 +181,8 @@ class LocalFrameClientImpl final : public LocalFrameClient {
HTMLFrameOwnerElement*) override;
std::pair<RemoteFrame*, base::UnguessableToken> CreatePortal(
HTMLPortalElement*,
- mojom::blink::PortalAssociatedRequest,
- mojom::blink::PortalClientAssociatedPtrInfo) override;
+ mojo::PendingAssociatedReceiver<mojom::blink::Portal>,
+ mojo::PendingAssociatedRemote<mojom::blink::PortalClient>) override;
RemoteFrame* AdoptPortal(HTMLPortalElement*) override;
WebPluginContainerImpl* CreatePlugin(HTMLPlugInElement&,
const KURL&,
@@ -203,11 +202,10 @@ class LocalFrameClientImpl final : public LocalFrameClient {
bool AllowContentInitiatedDataUrlNavigations(const KURL&) override;
- WebCookieJar* CookieJar() const override;
void FrameFocused() const override;
void DidChangeName(const String&) override;
void DidEnforceInsecureRequestPolicy(WebInsecureRequestPolicy) override;
- void DidEnforceInsecureNavigationsSet(const std::vector<unsigned>&) override;
+ void DidEnforceInsecureNavigationsSet(const WebVector<unsigned>&) override;
void DidChangeFramePolicy(Frame* child_frame, const FramePolicy&) override;
void DidSetFramePolicyHeaders(
WebSandboxFlags,
@@ -225,10 +223,6 @@ class LocalFrameClientImpl final : public LocalFrameClient {
override;
WebContentSettingsClient* GetContentSettingsClient() override;
- std::unique_ptr<WebApplicationCacheHost> CreateApplicationCacheHost(
- DocumentLoader*,
- WebApplicationCacheHostClient*) override;
-
void DispatchDidChangeManifest() override;
unsigned BackForwardLength() override;
@@ -282,7 +276,9 @@ class LocalFrameClientImpl final : public LocalFrameClient {
void AnnotatedRegionsChanged() override;
- void DidBlockFramebust(const KURL&) override;
+ void DidBlockNavigation(const KURL& blocked_url,
+ const KURL& initiator_url,
+ blink::NavigationBlockedReason reason) override;
base::UnguessableToken GetDevToolsFrameToken() const override;
@@ -305,6 +301,8 @@ class LocalFrameClientImpl final : public LocalFrameClient {
void FrameRectsChanged(const IntRect&) override;
+ void LifecycleStateChanged(mojom::FrameLifecycleState state) override;
+
bool IsPluginHandledExternally(HTMLPlugInElement&,
const KURL&,
const String&) override;
@@ -324,6 +322,10 @@ class LocalFrameClientImpl final : public LocalFrameClient {
void TransferUserActivationFrom(LocalFrame* source_frame) override;
+ void UpdateSubresourceFactory(
+ std::unique_ptr<blink::URLLoaderFactoryBundleInfo> info) override;
+ WebLocalFrameClient::AppCacheType GetAppCacheType() override;
+
private:
struct DocumentInterfaceBrokerForwarderTraits {
using Interface = mojom::blink::DocumentInterfaceBroker;
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 381c93e5101..8fb33677069 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
@@ -30,6 +30,7 @@
#include "third_party/blink/renderer/core/exported/local_frame_client_impl.h"
+#include "mojo/public/cpp/bindings/remote.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/web/web_local_frame_client.h"
@@ -39,7 +40,6 @@
#include "third_party/blink/renderer/core/frame/web_local_frame_impl.h"
#include "third_party/blink/renderer/core/testing/document_interface_broker_test_helpers.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
-#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
using testing::_;
@@ -76,8 +76,8 @@ class LocalFrameClientImplTest : public testing::Test {
WebString UserAgent() {
// The test always returns the same user agent .
- WTF::CString user_agent = GetLocalFrameClient().UserAgent().Utf8();
- return WebString::FromUTF8(user_agent.data(), user_agent.length());
+ std::string user_agent = GetLocalFrameClient().UserAgent().Utf8();
+ return WebString::FromUTF8(user_agent.c_str(), user_agent.length());
}
WebLocalFrameImpl* MainFrame() { return helper_.LocalMainFrame(); }
@@ -118,11 +118,11 @@ TEST_F(LocalFrameClientImplTest, TestDocumentInterfaceBrokerOverride) {
MainFrame()->GetFrame()->SetDocumentInterfaceBrokerForTesting(
doc.PassInterface().PassHandle());
- mojom::blink::FrameHostTestInterfacePtr frame_test;
+ mojo::Remote<mojom::blink::FrameHostTestInterface> frame_test;
MainFrame()
->GetFrame()
->GetDocumentInterfaceBroker()
- .GetFrameHostTestInterface(mojo::MakeRequest(&frame_test));
+ .GetFrameHostTestInterface(frame_test.BindNewPipeAndPassReceiver());
frame_test->GetName(base::BindOnce([](const WTF::String& result) {
EXPECT_EQ(result, kGetNameTestResponse);
}));
diff --git a/chromium/third_party/blink/renderer/core/exported/renderer_webapplicationcachehost_impl.cc b/chromium/third_party/blink/renderer/core/exported/renderer_webapplicationcachehost_impl.cc
deleted file mode 100644
index c2c24db0516..00000000000
--- a/chromium/third_party/blink/renderer/core/exported/renderer_webapplicationcachehost_impl.cc
+++ /dev/null
@@ -1,66 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "third_party/blink/renderer/core/exported/renderer_webapplicationcachehost_impl.h"
-
-#include "third_party/blink/public/common/loader/url_loader_factory_bundle.h"
-#include "third_party/blink/public/web/web_console_message.h"
-#include "third_party/blink/public/web/web_local_frame.h"
-#include "third_party/blink/public/web/web_local_frame_client.h"
-#include "third_party/blink/public/web/web_view.h"
-#include "third_party/blink/renderer/platform/web_test_support.h"
-
-namespace blink {
-
-RendererWebApplicationCacheHostImpl::RendererWebApplicationCacheHostImpl(
- WebLocalFrame* web_local_frame,
- WebApplicationCacheHostClient* client,
- const base::UnguessableToken& appcache_host_id,
- scoped_refptr<base::SingleThreadTaskRunner> task_runner)
- : WebApplicationCacheHostImpl(web_local_frame,
- client,
- appcache_host_id,
- std::move(task_runner)),
- web_local_frame_(web_local_frame) {}
-
-void RendererWebApplicationCacheHostImpl::LogMessage(
- mojom::blink::ConsoleMessageLevel log_level,
- const String& message) {
- if (WebTestSupport::IsRunningWebTest())
- return;
-
- if (!web_local_frame_ || !web_local_frame_->View() ||
- !web_local_frame_->View()->MainFrame())
- return;
-
- WebFrame* main_frame = web_local_frame_->View()->MainFrame();
- if (!main_frame->IsWebLocalFrame())
- return;
- // TODO(michaeln): Make app cache host per-frame and correctly report to the
- // involved frame.
- main_frame->ToWebLocalFrame()->AddMessageToConsole(WebConsoleMessage(
- static_cast<mojom::blink::ConsoleMessageLevel>(log_level), message));
-}
-
-void RendererWebApplicationCacheHostImpl::SetSubresourceFactory(
- network::mojom::blink::URLLoaderFactoryPtr url_loader_factory) {
- auto info = std::make_unique<URLLoaderFactoryBundleInfo>();
- info->appcache_factory_info().set_handle(
- url_loader_factory.PassInterface().PassHandle());
- web_local_frame_->Client()->UpdateSubresourceFactory(std::move(info));
-}
-
-std::unique_ptr<WebApplicationCacheHost>
-WebApplicationCacheHost::CreateWebApplicationCacheHostForFrame(
- WebLocalFrame* frame,
- WebApplicationCacheHostClient* client,
- const base::UnguessableToken& appcache_host_id,
- scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
- auto renderer_webapplicationcachehost_impl =
- std::make_unique<RendererWebApplicationCacheHostImpl>(
- frame, client, appcache_host_id, std::move(task_runner));
- return std::move(renderer_webapplicationcachehost_impl);
-}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/exported/renderer_webapplicationcachehost_impl.h b/chromium/third_party/blink/renderer/core/exported/renderer_webapplicationcachehost_impl.h
deleted file mode 100644
index d0726b3a552..00000000000
--- a/chromium/third_party/blink/renderer/core/exported/renderer_webapplicationcachehost_impl.h
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_EXPORTED_RENDERER_WEBAPPLICATIONCACHEHOST_IMPL_H_
-#define THIRD_PARTY_BLINK_RENDERER_CORE_EXPORTED_RENDERER_WEBAPPLICATIONCACHEHOST_IMPL_H_
-
-#include "third_party/blink/renderer/core/exported/web_application_cache_host_impl.h"
-
-namespace blink {
-class WebLocalFrame;
-
-class RendererWebApplicationCacheHostImpl : public WebApplicationCacheHostImpl {
- public:
- RendererWebApplicationCacheHostImpl(
- WebLocalFrame* web_frame,
- blink::WebApplicationCacheHostClient* client,
- const base::UnguessableToken& appcache_host_id,
- scoped_refptr<base::SingleThreadTaskRunner> task_runner);
-
- // mojom::blink::AppCacheHostFrontend:
- void LogMessage(mojom::blink::ConsoleMessageLevel log_level,
- const String& message) override;
-
- void SetSubresourceFactory(
- network::mojom::blink::URLLoaderFactoryPtr url_loader_factory) override;
-
- private:
- // Stores the WebLocalFrame. |this| keeps it as a raw pointer because |this|'s
- // owned by ApplicationCacheHost which is destroyed when
- // DocumentLoader::DetachFromFrame is called.
- WebLocalFrame* web_local_frame_;
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_CORE_EXPORTED_RENDERER_WEBAPPLICATIONCACHEHOST_IMPL_H_
diff --git a/chromium/third_party/blink/renderer/core/exported/web_application_cache_host_impl.cc b/chromium/third_party/blink/renderer/core/exported/web_application_cache_host_impl.cc
deleted file mode 100644
index ad8c3b16c10..00000000000
--- a/chromium/third_party/blink/renderer/core/exported/web_application_cache_host_impl.cc
+++ /dev/null
@@ -1,353 +0,0 @@
-// Copyright 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "third_party/blink/renderer/core/exported/web_application_cache_host_impl.h"
-
-#include "third_party/blink/public/mojom/frame/document_interface_broker.mojom-blink.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_string.h"
-#include "third_party/blink/public/platform/web_url.h"
-#include "third_party/blink/public/platform/web_url_response.h"
-#include "third_party/blink/public/web/web_application_cache_host_client.h"
-#include "third_party/blink/public/web/web_frame.h"
-#include "third_party/blink/public/web/web_local_frame.h"
-#include "third_party/blink/renderer/core/frame/local_frame_client.h"
-
-namespace blink {
-
-namespace {
-
-const char kHttpGETMethod[] = "GET";
-
-// Note: the order of the elements in this array must match those
-// of the EventID enum in appcache_interfaces.h.
-const char* const kEventNames[] = {"Checking", "Error", "NoUpdate",
- "Downloading", "Progress", "UpdateReady",
- "Cached", "Obsolete"};
-
-KURL ClearUrlRef(const WebURL& web_url) {
- KURL url(web_url);
- if (!url.HasFragmentIdentifier())
- return url;
- url.RemoveFragmentIdentifier();
- return url;
-}
-
-mojom::blink::DocumentInterfaceBroker* GetDocumentInterfaceBroker(
- WebLocalFrame* web_frame) {
- if (!web_frame)
- return nullptr;
- Frame* frame = WebFrame::ToCoreFrame(*web_frame);
- if (auto* local_frame = DynamicTo<LocalFrame>(frame))
- return local_frame->Client()->GetDocumentInterfaceBroker();
- return nullptr;
-}
-
-} // namespace
-
-WebApplicationCacheHostImpl::WebApplicationCacheHostImpl(
- WebLocalFrame* web_frame,
- WebApplicationCacheHostClient* client,
- const base::UnguessableToken& appcache_host_id,
- scoped_refptr<base::SingleThreadTaskRunner> task_runner)
- : binding_(this),
- client_(client),
- status_(mojom::blink::AppCacheStatus::APPCACHE_STATUS_UNCACHED),
- is_scheme_supported_(false),
- is_get_method_(false),
- is_new_master_entry_(MAYBE_NEW_ENTRY),
- was_select_cache_called_(false) {
- DCHECK(client);
- // PlzNavigate: The browser passes the ID to be used.
- if (!appcache_host_id.is_empty())
- host_id_ = appcache_host_id;
- else
- host_id_ = base::UnguessableToken::Create();
-
- mojom::blink::AppCacheFrontendPtr frontend_ptr;
- binding_.Bind(mojo::MakeRequest(&frontend_ptr, task_runner), task_runner);
-
- mojom::blink::DocumentInterfaceBroker* interface_broker =
- GetDocumentInterfaceBroker(web_frame);
- if (interface_broker) {
- interface_broker->RegisterAppCacheHost(
- mojo::MakeRequest(&backend_host_, std::move(task_runner)),
- std::move(frontend_ptr), host_id_);
- return;
- }
-
- DEFINE_STATIC_LOCAL(
- const mojom::blink::AppCacheBackendPtr, backend_ptr, ([] {
- mojom::blink::AppCacheBackendPtr result;
- Platform::Current()->GetInterfaceProvider()->GetInterface(
- mojo::MakeRequest(&result));
- return result;
- }()));
-
- // Once we have 'WebContextInterfaceBroker', we can call this function through
- // it like render frame.
- // Refer to the design document, 'https://bit.ly/2GT0rZv'.
- backend_ptr.get()->RegisterHost(
- mojo::MakeRequest(&backend_host_, std::move(task_runner)),
- std::move(frontend_ptr), host_id_);
-}
-
-WebApplicationCacheHostImpl::~WebApplicationCacheHostImpl() = default;
-
-void WebApplicationCacheHostImpl::CacheSelected(
- mojom::blink::AppCacheInfoPtr info) {
- cache_info_ = *info;
- client_->DidChangeCacheAssociation();
- if (select_cache_for_shared_worker_completion_callback_)
- std::move(select_cache_for_shared_worker_completion_callback_).Run();
-}
-
-void WebApplicationCacheHostImpl::EventRaised(
- mojom::blink::AppCacheEventID event_id) {
- DCHECK_NE(event_id,
- mojom::blink::AppCacheEventID::
- APPCACHE_PROGRESS_EVENT); // See OnProgressEventRaised.
- DCHECK_NE(event_id,
- mojom::blink::AppCacheEventID::
- APPCACHE_ERROR_EVENT); // See OnErrorEventRaised.
-
- // Emit logging output prior to calling out to script as we can get
- // deleted within the script event handler.
- const char kFormatString[] = "Application Cache %s event";
- String message =
- String::Format(kFormatString, kEventNames[static_cast<int>(event_id)]);
- LogMessage(mojom::blink::ConsoleMessageLevel::kInfo, message);
-
- switch (event_id) {
- case mojom::blink::AppCacheEventID::APPCACHE_CHECKING_EVENT:
- status_ = mojom::blink::AppCacheStatus::APPCACHE_STATUS_CHECKING;
- break;
- case mojom::blink::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT:
- status_ = mojom::blink::AppCacheStatus::APPCACHE_STATUS_DOWNLOADING;
- break;
- case mojom::blink::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT:
- status_ = mojom::blink::AppCacheStatus::APPCACHE_STATUS_UPDATE_READY;
- break;
- case mojom::blink::AppCacheEventID::APPCACHE_CACHED_EVENT:
- case mojom::blink::AppCacheEventID::APPCACHE_NO_UPDATE_EVENT:
- status_ = mojom::blink::AppCacheStatus::APPCACHE_STATUS_IDLE;
- break;
- case mojom::blink::AppCacheEventID::APPCACHE_OBSOLETE_EVENT:
- status_ = mojom::blink::AppCacheStatus::APPCACHE_STATUS_OBSOLETE;
- break;
- default:
- NOTREACHED();
- break;
- }
-
- client_->NotifyEventListener(event_id);
-}
-
-void WebApplicationCacheHostImpl::ProgressEventRaised(const KURL& url,
- int num_total,
- int num_complete) {
- // Emit logging output prior to calling out to script as we can get
- // deleted within the script event handler.
- const char kFormatString[] = "Application Cache Progress event (%d of %d) %s";
- String message = String::Format(kFormatString, num_complete, num_total,
- url.GetString().Utf8().data());
- LogMessage(mojom::blink::ConsoleMessageLevel::kInfo, message);
- status_ = mojom::blink::AppCacheStatus::APPCACHE_STATUS_DOWNLOADING;
- client_->NotifyProgressEventListener(url, num_total, num_complete);
-}
-
-void WebApplicationCacheHostImpl::ErrorEventRaised(
- mojom::blink::AppCacheErrorDetailsPtr details) {
- // Emit logging output prior to calling out to script as we can get
- // deleted within the script event handler.
- const char kFormatString[] = "Application Cache Error event: %s";
- String full_message =
- String::Format(kFormatString, details->message.Utf8().data());
- LogMessage(mojom::blink::ConsoleMessageLevel::kError, full_message);
-
- status_ = cache_info_.is_complete
- ? mojom::blink::AppCacheStatus::APPCACHE_STATUS_IDLE
- : mojom::blink::AppCacheStatus::APPCACHE_STATUS_UNCACHED;
- if (details->is_cross_origin) {
- // Don't leak detailed information to script for cross-origin resources.
- DCHECK_EQ(mojom::blink::AppCacheErrorReason::APPCACHE_RESOURCE_ERROR,
- details->reason);
- client_->NotifyErrorEventListener(details->reason, details->url, 0,
- WebString());
- } else {
- client_->NotifyErrorEventListener(details->reason, details->url,
- details->status, details->message);
- }
-}
-
-void WebApplicationCacheHostImpl::WillStartMainResourceRequest(
- const WebURL& url,
- const String& method,
- const WebApplicationCacheHost* spawning_host) {
- original_main_resource_url_ = ClearUrlRef(url);
-
- is_get_method_ = (method == kHttpGETMethod);
- DCHECK(method == method.UpperASCII());
-
- const WebApplicationCacheHostImpl* spawning_host_impl =
- static_cast<const WebApplicationCacheHostImpl*>(spawning_host);
- if (spawning_host_impl && (spawning_host_impl != this) &&
- (spawning_host_impl->status_ !=
- mojom::blink::AppCacheStatus::APPCACHE_STATUS_UNCACHED)) {
- backend_host_->SetSpawningHostId(spawning_host_impl->host_id());
- }
-}
-
-void WebApplicationCacheHostImpl::SelectCacheWithoutManifest() {
- if (was_select_cache_called_)
- return;
- was_select_cache_called_ = true;
-
- status_ =
- (document_response_.AppCacheID() == mojom::blink::kAppCacheNoCacheId)
- ? mojom::blink::AppCacheStatus::APPCACHE_STATUS_UNCACHED
- : mojom::blink::AppCacheStatus::APPCACHE_STATUS_CHECKING;
- is_new_master_entry_ = OLD_ENTRY;
- backend_host_->SelectCache(document_url_, document_response_.AppCacheID(),
- KURL());
-}
-
-bool WebApplicationCacheHostImpl::SelectCacheWithManifest(
- const WebURL& manifest_url) {
- if (was_select_cache_called_)
- return true;
- was_select_cache_called_ = true;
-
- KURL manifest_kurl(ClearUrlRef(manifest_url));
-
- // 6.9.6 The application cache selection algorithm
- // Check for new 'master' entries.
- if (document_response_.AppCacheID() == mojom::blink::kAppCacheNoCacheId) {
- if (is_scheme_supported_ && is_get_method_ &&
- SecurityOrigin::AreSameSchemeHostPort(manifest_kurl, document_url_)) {
- status_ = mojom::blink::AppCacheStatus::APPCACHE_STATUS_CHECKING;
- is_new_master_entry_ = NEW_ENTRY;
- } else {
- status_ = mojom::blink::AppCacheStatus::APPCACHE_STATUS_UNCACHED;
- is_new_master_entry_ = OLD_ENTRY;
- manifest_kurl = KURL();
- }
- backend_host_->SelectCache(document_url_, mojom::blink::kAppCacheNoCacheId,
- manifest_kurl);
- return true;
- }
-
- DCHECK_EQ(OLD_ENTRY, is_new_master_entry_);
-
- // 6.9.6 The application cache selection algorithm
- // Check for 'foreign' entries.
- KURL document_manifest_kurl(document_response_.AppCacheManifestURL());
- if (document_manifest_kurl != manifest_kurl) {
- backend_host_->MarkAsForeignEntry(document_url_,
- document_response_.AppCacheID());
- status_ = mojom::blink::AppCacheStatus::APPCACHE_STATUS_UNCACHED;
- return false; // the navigation will be restarted
- }
-
- status_ = mojom::blink::AppCacheStatus::APPCACHE_STATUS_CHECKING;
-
- // It's a 'master' entry that's already in the cache.
- backend_host_->SelectCache(document_url_, document_response_.AppCacheID(),
- manifest_kurl);
- return true;
-}
-
-void WebApplicationCacheHostImpl::DidReceiveResponseForMainResource(
- const WebURLResponse& response) {
- document_response_ = response;
- document_url_ = ClearUrlRef(document_response_.CurrentRequestUrl());
- if (document_url_ != original_main_resource_url_)
- is_get_method_ = true; // A redirect was involved.
- original_main_resource_url_ = KURL();
-
- is_scheme_supported_ =
- Platform::Current()->IsURLSupportedForAppCache(document_url_);
- if ((document_response_.AppCacheID() != mojom::blink::kAppCacheNoCacheId) ||
- !is_scheme_supported_ || !is_get_method_)
- is_new_master_entry_ = OLD_ENTRY;
-}
-
-mojom::blink::AppCacheStatus WebApplicationCacheHostImpl::GetStatus() {
- return status_;
-}
-
-bool WebApplicationCacheHostImpl::StartUpdate() {
- bool result = false;
- backend_host_->StartUpdate(&result);
- if (!result)
- return false;
- if (status_ == mojom::blink::AppCacheStatus::APPCACHE_STATUS_IDLE ||
- status_ == mojom::blink::AppCacheStatus::APPCACHE_STATUS_UPDATE_READY) {
- status_ = mojom::blink::AppCacheStatus::APPCACHE_STATUS_CHECKING;
- } else {
- status_ = mojom::blink::AppCacheStatus::APPCACHE_STATUS_UNCACHED;
- backend_host_->GetStatus(&status_);
- }
- return true;
-}
-
-bool WebApplicationCacheHostImpl::SwapCache() {
- bool result = false;
- backend_host_->SwapCache(&result);
- if (!result)
- return false;
- backend_host_->GetStatus(&status_);
- return true;
-}
-
-void WebApplicationCacheHostImpl::GetAssociatedCacheInfo(
- WebApplicationCacheHost::CacheInfo* info) {
- info->manifest_url = cache_info_.manifest_url;
- if (!cache_info_.is_complete)
- return;
- info->creation_time = cache_info_.creation_time.ToDoubleT();
- info->update_time = cache_info_.last_update_time.ToDoubleT();
- info->response_sizes = cache_info_.response_sizes;
- info->padding_sizes = cache_info_.padding_sizes;
-}
-
-const base::UnguessableToken& WebApplicationCacheHostImpl::GetHostID() const {
- return host_id_;
-}
-
-void WebApplicationCacheHostImpl::GetResourceList(
- WebVector<ResourceInfo>* resources) {
- if (!cache_info_.is_complete)
- return;
- Vector<mojom::blink::AppCacheResourceInfoPtr> boxed_infos;
- backend_host_->GetResourceList(&boxed_infos);
- Vector<mojom::blink::AppCacheResourceInfo> resource_infos;
- for (auto& b : boxed_infos) {
- resource_infos.emplace_back(std::move(*b));
- }
-
- WebVector<ResourceInfo> web_resources(resource_infos.size());
- for (size_t i = 0; i < resource_infos.size(); ++i) {
- web_resources[i].response_size = resource_infos[i].response_size;
- web_resources[i].padding_size = resource_infos[i].padding_size;
- web_resources[i].is_master = resource_infos[i].is_master;
- web_resources[i].is_explicit = resource_infos[i].is_explicit;
- web_resources[i].is_manifest = resource_infos[i].is_manifest;
- web_resources[i].is_foreign = resource_infos[i].is_foreign;
- web_resources[i].is_fallback = resource_infos[i].is_fallback;
- web_resources[i].url = resource_infos[i].url;
- }
- resources->Swap(web_resources);
-}
-
-void WebApplicationCacheHostImpl::SelectCacheForSharedWorker(
- int64_t app_cache_id,
- base::OnceClosure completion_callback) {
- select_cache_for_shared_worker_completion_callback_ =
- std::move(completion_callback);
- backend_host_->SelectCacheForSharedWorker(app_cache_id);
-}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/exported/web_application_cache_host_impl.h b/chromium/third_party/blink/renderer/core/exported/web_application_cache_host_impl.h
deleted file mode 100644
index 16bc58e8d4b..00000000000
--- a/chromium/third_party/blink/renderer/core/exported/web_application_cache_host_impl.h
+++ /dev/null
@@ -1,84 +0,0 @@
-// Copyright 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_EXPORTED_WEB_APPLICATION_CACHE_HOST_IMPL_H_
-#define THIRD_PARTY_BLINK_RENDERER_CORE_EXPORTED_WEB_APPLICATION_CACHE_HOST_IMPL_H_
-
-#include "mojo/public/cpp/bindings/binding.h"
-#include "third_party/blink/public/mojom/appcache/appcache.mojom-blink.h"
-#include "third_party/blink/public/mojom/appcache/appcache_info.mojom-blink.h"
-#include "third_party/blink/public/mojom/devtools/console_message.mojom-blink.h"
-#include "third_party/blink/public/platform/web_url_response.h"
-#include "third_party/blink/public/platform/web_vector.h"
-#include "third_party/blink/public/web/web_application_cache_host.h"
-#include "third_party/blink/renderer/platform/weborigin/kurl.h"
-
-namespace blink {
-
-class WebApplicationCacheHostClient;
-
-class WebApplicationCacheHostImpl : public WebApplicationCacheHost,
- public mojom::blink::AppCacheFrontend {
- public:
- WebApplicationCacheHostImpl(
- // |web_frame| is used for accessing to DocumentInterfaceBroker. As it's
- // not used for workers, |web_frame| is null for workers.
- WebLocalFrame* web_frame,
- WebApplicationCacheHostClient* client,
- const base::UnguessableToken& appcache_host_id,
- scoped_refptr<base::SingleThreadTaskRunner> task_runner);
- ~WebApplicationCacheHostImpl() override;
-
- const base::UnguessableToken& host_id() const { return host_id_; }
- WebApplicationCacheHostClient* client() const { return client_; }
-
- // mojom::blink::AppCacheFrontend
- void CacheSelected(mojom::blink::AppCacheInfoPtr info) override;
- void EventRaised(mojom::blink::AppCacheEventID event_id) override;
- void ProgressEventRaised(const KURL& url,
- int32_t num_total,
- int32_t num_complete) override;
- void ErrorEventRaised(mojom::blink::AppCacheErrorDetailsPtr details) override;
-
- // WebApplicationCacheHost:
- void WillStartMainResourceRequest(
- const WebURL& url,
- const String& method,
- const WebApplicationCacheHost* spawning_host) override;
- void SelectCacheWithoutManifest() override;
- bool SelectCacheWithManifest(const WebURL& manifestURL) override;
- void DidReceiveResponseForMainResource(const WebURLResponse&) override;
- mojom::blink::AppCacheStatus GetStatus() override;
- bool StartUpdate() override;
- bool SwapCache() override;
- void GetResourceList(WebVector<ResourceInfo>* resources) override;
- void GetAssociatedCacheInfo(CacheInfo* info) override;
- const base::UnguessableToken& GetHostID() const override;
- void SelectCacheForSharedWorker(
- int64_t app_cache_id,
- base::OnceClosure completion_callback) override;
-
- private:
- enum IsNewMasterEntry { MAYBE_NEW_ENTRY, NEW_ENTRY, OLD_ENTRY };
-
- mojo::Binding<mojom::blink::AppCacheFrontend> binding_;
- WebApplicationCacheHostClient* client_;
- mojom::blink::AppCacheHostPtr backend_host_;
- base::UnguessableToken host_id_;
- mojom::blink::AppCacheStatus status_;
- WebURLResponse document_response_;
- KURL document_url_;
- bool is_scheme_supported_;
- bool is_get_method_;
- IsNewMasterEntry is_new_master_entry_;
- mojom::blink::AppCacheInfo cache_info_;
- KURL original_main_resource_url_; // Used to detect redirection.
- bool was_select_cache_called_;
- // Invoked when CacheSelected() is called.
- base::OnceClosure select_cache_for_shared_worker_completion_callback_;
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_CORE_EXPORTED_WEB_APPLICATION_CACHE_HOST_IMPL_H_
diff --git a/chromium/third_party/blink/renderer/core/exported/web_content_holder.cc b/chromium/third_party/blink/renderer/core/exported/web_content_holder.cc
index ac665fe9d27..53de7a0fde1 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_content_holder.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_content_holder.cc
@@ -4,25 +4,38 @@
#include "third_party/blink/public/web/web_content_holder.h"
-#include "third_party/blink/renderer/core/content_capture/content_holder.h"
+#include "third_party/blink/renderer/core/dom/node.h"
+#include "third_party/blink/renderer/core/layout/layout_object.h"
namespace blink {
-WebContentHolder::~WebContentHolder() = default;
+WebContentHolder::WebContentHolder(const WebContentHolder& other) {
+ private_ = other.private_;
+}
+
+WebContentHolder& WebContentHolder::operator=(const WebContentHolder& other) {
+ private_ = other.private_;
+ return *this;
+}
+
+WebContentHolder::~WebContentHolder() {
+ private_.Reset();
+}
WebString WebContentHolder::GetValue() const {
- return private_->GetValue();
+ return private_->nodeValue();
}
WebRect WebContentHolder::GetBoundingBox() const {
- return private_->GetBoundingBox();
+ if (auto* layout_obj = private_->GetLayoutObject())
+ return EnclosingIntRect(layout_obj->VisualRectInDocument());
+ return IntRect();
}
uint64_t WebContentHolder::GetId() const {
- return private_->GetId();
+ return reinterpret_cast<uint64_t>(private_.Get());
}
-WebContentHolder::WebContentHolder(scoped_refptr<ContentHolder> content_holder)
- : private_(std::move(content_holder)) {}
+WebContentHolder::WebContentHolder(Node& node) : private_(&node) {}
} // namespace blink
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 070d44b4690..633f611c4d5 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
@@ -38,6 +38,7 @@
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_float_rect.h"
#include "third_party/blink/public/platform/web_rect.h"
+#include "third_party/blink/public/platform/web_scoped_page_pauser.h"
#include "third_party/blink/public/platform/web_string.h"
#include "third_party/blink/public/web/web_settings.h"
#include "third_party/blink/public/web/web_view_client.h"
@@ -81,10 +82,10 @@
#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"
-#include "third_party/blink/renderer/platform/cross_thread_functional.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/instrumentation/tracing/trace_event.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.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"
@@ -164,7 +165,7 @@ class ClientMessageLoopAdapter : public MainThreadDebugger::ClientMessageLoop {
view->GetChromeClient().NotifyPopupOpeningObservers();
// 2. Disable active objects
- WebView::WillEnterModalLoop();
+ page_pauser_ = WebScopedPagePauser::Create();
// 3. Process messages until quitNow is called.
message_loop_->Run();
@@ -193,7 +194,7 @@ class ClientMessageLoopAdapter : public MainThreadDebugger::ClientMessageLoop {
// NOTE: This code used to be above right after the |mesasge_loop_->Run()|
// code, but it is moved here to support browser-side navigation.
message_loop_->QuitNow();
- WebView::DidExitModalLoop();
+ page_pauser_.reset();
WebFrameWidgetBase::SetIgnoreInputEvents(false);
}
@@ -212,6 +213,7 @@ class ClientMessageLoopAdapter : public MainThreadDebugger::ClientMessageLoop {
bool running_for_debug_break_;
bool running_for_page_wait_;
std::unique_ptr<Platform::NestedMessageLoopRunner> message_loop_;
+ std::unique_ptr<WebScopedPagePauser> page_pauser_;
static ClientMessageLoopAdapter* instance_;
};
@@ -411,7 +413,7 @@ void WebDevToolsAgentImpl::InspectElement(const WebPoint& point_in_local_root) {
HitTestRequest request(hit_type);
WebMouseEvent dummy_event(WebInputEvent::kMouseDown,
WebInputEvent::kNoModifiers,
- WTF::CurrentTimeTicks());
+ base::TimeTicks::Now());
dummy_event.SetPositionInWidget(point.x, point.y);
IntPoint transformed_point = FlooredIntPoint(
TransformWebMouseEvent(web_local_frame_impl_->GetFrameView(), dummy_event)
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 9f454704438..6821e70a8b3 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
@@ -34,9 +34,11 @@
#include <utility>
#include "base/memory/ptr_util.h"
-#include "third_party/blink/public/mojom/loader/mhtml_load_result.mojom-shared.h"
+#include "third_party/blink/public/common/features.h"
+#include "third_party/blink/public/mojom/loader/mhtml_load_result.mojom-blink.h"
#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_network_provider.h"
#include "third_party/blink/public/platform/web_document_subresource_filter.h"
+#include "third_party/blink/public/platform/web_loading_hints_provider.h"
#include "third_party/blink/public/platform/web_url.h"
#include "third_party/blink/public/platform/web_url_error.h"
#include "third_party/blink/public/platform/web_vector.h"
@@ -143,6 +145,18 @@ void WebDocumentLoaderImpl::SetSubresourceFilter(
*GetFrame()->GetDocument(), base::WrapUnique(subresource_filter)));
}
+void WebDocumentLoaderImpl::SetLoadingHintsProvider(
+ std::unique_ptr<blink::WebLoadingHintsProvider> loading_hints_provider) {
+ if (!base::FeatureList::IsEnabled(
+ blink::features::kSendPreviewsLoadingHintsBeforeCommit)) {
+ return;
+ }
+
+ DocumentLoader::SetPreviewsResourceLoadingHints(
+ PreviewsResourceLoadingHints::CreateFromLoadingHintsProvider(
+ *GetFrame()->GetDocument(), std::move(loading_hints_provider)));
+}
+
void WebDocumentLoaderImpl::SetServiceWorkerNetworkProvider(
std::unique_ptr<WebServiceWorkerNetworkProvider> provider) {
DocumentLoader::SetServiceWorkerNetworkProvider(std::move(provider));
@@ -175,7 +189,7 @@ WebArchiveInfo WebDocumentLoaderImpl::GetArchiveInfo() const {
}
bool WebDocumentLoaderImpl::HadUserGesture() const {
- return DocumentLoader::had_transient_activation();
+ return DocumentLoader::HadTransientActivation();
}
bool WebDocumentLoaderImpl::IsListingFtpDirectory() const {
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 17a17c7a91c..ee485ff11f1 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
@@ -75,6 +75,8 @@ class CORE_EXPORT WebDocumentLoaderImpl final : public DocumentLoader,
ExtraData* GetExtraData() const override;
void SetExtraData(std::unique_ptr<ExtraData>) override;
void SetSubresourceFilter(WebDocumentSubresourceFilter*) override;
+ void SetLoadingHintsProvider(
+ std::unique_ptr<blink::WebLoadingHintsProvider>) override;
void SetServiceWorkerNetworkProvider(
std::unique_ptr<WebServiceWorkerNetworkProvider>) override;
WebServiceWorkerNetworkProvider* GetServiceWorkerNetworkProvider() override;
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 65462aa8a22..bee856dac70 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
@@ -4,9 +4,6 @@
#include "third_party/blink/public/platform/web_document_subresource_filter.h"
-#include <string>
-#include <vector>
-
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/platform/platform.h"
@@ -33,7 +30,7 @@ class TestDocumentSubresourceFilter : public WebDocumentSubresourceFilter {
LoadPolicy GetLoadPolicy(const WebURL& resource_url,
mojom::RequestContextType) override {
- std::string resource_path = WebString(KURL(resource_url).GetPath()).Utf8();
+ String resource_path = KURL(resource_url).GetPath();
if (std::find(queried_subresource_paths_.begin(),
queried_subresource_paths_.end(),
resource_path) == queried_subresource_paths_.end()) {
@@ -59,13 +56,13 @@ class TestDocumentSubresourceFilter : public WebDocumentSubresourceFilter {
blacklisted_suffixes_.push_back(suffix);
}
- const std::vector<std::string>& QueriedSubresourcePaths() const {
+ const Vector<String>& QueriedSubresourcePaths() const {
return queried_subresource_paths_;
}
private:
// Using STL types for compatibility with gtest/gmock.
- std::vector<std::string> queried_subresource_paths_;
+ Vector<String> queried_subresource_paths_;
Vector<String> blacklisted_suffixes_;
LoadPolicy load_policy_;
};
@@ -110,7 +107,7 @@ class WebDocumentSubresourceFilterTest : public testing::Test {
void LoadDocument(TestDocumentSubresourceFilter::LoadPolicy policy) {
client_.SetLoadPolicyFromNextLoad(policy);
frame_test_helpers::LoadFrame(MainFrame(),
- BaseURL() + "foo_with_image.html");
+ BaseURL().Utf8() + "foo_with_image.html");
}
void ExpectSubresourceWasLoaded(bool loaded) {
@@ -120,17 +117,16 @@ class WebDocumentSubresourceFilterTest : public testing::Test {
EXPECT_EQ(loaded, !!image_element->naturalWidth());
}
- const std::string& BaseURL() const { return base_url_; }
+ const String& BaseURL() const { return base_url_; }
WebLocalFrameImpl* MainFrame() { return web_view_helper_.LocalMainFrame(); }
- const std::vector<std::string>& QueriedSubresourcePaths() const {
+ const Vector<String>& QueriedSubresourcePaths() const {
return client_.SubresourceFilter()->QueriedSubresourcePaths();
}
private:
- void RegisterMockedHttpURLLoad(const std::string& file_name) {
+ void RegisterMockedHttpURLLoad(const String& file_name) {
url_test_helpers::RegisterMockedURLLoadFromBase(
- WebString::FromUTF8(base_url_), test::CoreTestDataPath(),
- WebString::FromUTF8(file_name));
+ WebString(base_url_), test::CoreTestDataPath(), WebString(file_name));
}
// testing::Test:
@@ -142,7 +138,7 @@ class WebDocumentSubresourceFilterTest : public testing::Test {
SubresourceFilteringWebFrameClient client_;
frame_test_helpers::WebViewHelper web_view_helper_;
- std::string base_url_;
+ String base_url_;
};
TEST_F(WebDocumentSubresourceFilterTest, AllowedSubresource) {
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 3b15ac85ea6..63d0f3efcea 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
@@ -92,7 +92,7 @@ WebDOMMessageEvent::WebDOMMessageEvent(TransferableMessage message,
Unwrap<MessageEvent>()->initMessageEvent(
"message", false, false, std::move(msg.message), origin,
"" /*lastEventId*/, window, ports, user_activation,
- msg.transfer_user_activation);
+ msg.transfer_user_activation, msg.allow_autoplay);
}
WebString WebDOMMessageEvent::Origin() const {
@@ -105,6 +105,7 @@ TransferableMessage WebDOMMessageEvent::AsMessage() {
msg.ports = Unwrap<MessageEvent>()->ReleaseChannels();
msg.transfer_user_activation =
Unwrap<MessageEvent>()->transferUserActivation();
+ msg.allow_autoplay = Unwrap<MessageEvent>()->allowAutoplay();
UserActivation* user_activation = Unwrap<MessageEvent>()->userActivation();
TransferableMessage transferable_msg = ToTransferableMessage(std::move(msg));
if (user_activation) {
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 00e0fefdf77..41aaa70da10 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_element.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_element.cc
@@ -41,6 +41,7 @@
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/graphics/image.h"
+#include "third_party/blink/renderer/platform/wtf/casting.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
@@ -172,7 +173,7 @@ WebElement& WebElement::operator=(Element* elem) {
}
WebElement::operator Element*() const {
- return ToElement(private_.Get());
+ return blink::To<Element>(private_.Get());
}
} // namespace blink
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 47db70bcd1e..1cb2230f63c 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
@@ -93,13 +93,15 @@ TEST_F(WebElementTest, IsAutonomousCustomElement) {
)JS");
GetDocument().body()->appendChild(script);
auto* v0typeext = GetDocument().body()->lastChild();
- EXPECT_FALSE(WebElement(ToElement(v0typeext)).IsAutonomousCustomElement());
+ EXPECT_FALSE(WebElement(To<Element>(v0typeext)).IsAutonomousCustomElement());
auto* v0autonomous = v0typeext->previousSibling();
- EXPECT_TRUE(WebElement(ToElement(v0autonomous)).IsAutonomousCustomElement());
+ EXPECT_TRUE(
+ WebElement(To<Element>(v0autonomous)).IsAutonomousCustomElement());
auto* v1builtin = v0autonomous->previousSibling();
- EXPECT_FALSE(WebElement(ToElement(v1builtin)).IsAutonomousCustomElement());
+ EXPECT_FALSE(WebElement(To<Element>(v1builtin)).IsAutonomousCustomElement());
auto* v1autonomous = v1builtin->previousSibling();
- EXPECT_TRUE(WebElement(ToElement(v1autonomous)).IsAutonomousCustomElement());
+ EXPECT_TRUE(
+ WebElement(To<Element>(v1autonomous)).IsAutonomousCustomElement());
}
TEST_F(WebElementTest, ShadowRoot) {
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 07d35bbbc43..9c623dc2bc0 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
@@ -248,6 +248,10 @@ unsigned WebFormControlElement::UniqueRendererFormControlId() const {
return ConstUnwrap<HTMLFormControlElement>()->UniqueRendererFormControlId();
}
+int32_t WebFormControlElement::GetAxId() const {
+ return ConstUnwrap<HTMLFormControlElement>()->GetAxId();
+}
+
WebFormControlElement::WebFormControlElement(HTMLFormControlElement* elem)
: WebElement(elem) {}
@@ -262,7 +266,7 @@ WebFormControlElement& WebFormControlElement::operator=(
}
WebFormControlElement::operator HTMLFormControlElement*() const {
- return ToHTMLFormControlElement(private_.Get());
+ return blink::To<HTMLFormControlElement>(private_.Get());
}
} // namespace blink
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 37180de77d6..d6f8ba5af36 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
@@ -66,13 +66,13 @@ void WebFormElement::GetFormControlElements(
WebVector<WebFormControlElement>& result) const {
const HTMLFormElement* form = ConstUnwrap<HTMLFormElement>();
Vector<WebFormControlElement> form_control_elements;
-
- const ListedElement::List& listed_elements = form->ListedElements();
- for (ListedElement::List::const_iterator it = listed_elements.begin();
- it != listed_elements.end(); ++it) {
- if ((*it)->IsFormControlElement())
- form_control_elements.push_back(ToHTMLFormControlElement(*it));
+ for (const auto& element : form->ListedElements()) {
+ if (auto* form_control =
+ blink::DynamicTo<HTMLFormControlElement>(element.Get())) {
+ form_control_elements.push_back(form_control);
+ }
}
+
result.Assign(form_control_elements);
}
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 722965fb717..93f09745dea 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
@@ -122,7 +122,7 @@ WebFormElementObserver* WebFormElementObserver::Create(
WebFormElementObserverImpl::WebFormElementObserverImpl(
HTMLElement& element,
base::OnceClosure callback)
- : self_keep_alive_(this) {
+ : self_keep_alive_(PERSISTENT_FROM_HERE, this) {
mutation_callback_ =
MakeGarbageCollected<ObserverCallback>(element, std::move(callback));
}
diff --git a/chromium/third_party/blink/renderer/core/exported/web_frame.cc b/chromium/third_party/blink/renderer/core/exported/web_frame.cc
index d9a61124a42..84ab9c73661 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_frame.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_frame.cc
@@ -40,7 +40,7 @@ bool WebFrame::Swap(WebFrame* frame) {
// wasn't detached before continuing with the swap.
// FIXME: There is no unit test for this condition, so one needs to be
// written.
- if (!old_frame->PrepareForCommit()) {
+ if (!old_frame->DetachDocument()) {
// If the Swap() fails, it should be because the frame has been detached
// already. Otherwise the caller will not detach the frame when we return
// false, and the browser and renderer will disagree about the destruction
@@ -128,7 +128,8 @@ bool WebFrame::Swap(WebFrame* frame) {
ToTraceValue(&local_frame));
}
} else {
- ToWebRemoteFrameImpl(frame)->InitializeCoreFrame(*page, owner, name);
+ ToWebRemoteFrameImpl(frame)->InitializeCoreFrame(
+ *page, owner, name, &old_frame->window_agent_factory());
}
Frame* new_frame = ToCoreFrame(*frame);
@@ -168,7 +169,7 @@ WebInsecureRequestPolicy WebFrame::GetInsecureRequestPolicy() const {
return ToCoreFrame(*this)->GetSecurityContext()->GetInsecureRequestPolicy();
}
-std::vector<unsigned> WebFrame::GetInsecureRequestToUpgrade() const {
+WebVector<unsigned> WebFrame::GetInsecureRequestToUpgrade() const {
const SecurityContext::InsecureNavigationsSet& set =
ToCoreFrame(*this)->GetSecurityContext()->InsecureNavigationsToUpgrade();
return SecurityContext::SerializeInsecureNavigationSet(set);
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 528f319b0d7..ded2118ea44 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
@@ -64,7 +64,7 @@
#include "third_party/blink/renderer/core/loader/frame_loader.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/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_request.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_response.h"
@@ -105,7 +105,7 @@ class MHTMLFrameSerializerDelegate final : public FrameSerializer::Delegate {
MHTMLFrameSerializerDelegate(
WebFrameSerializer::MHTMLPartsGenerationDelegate&,
HeapHashSet<WeakMember<const Element>>&);
- ~MHTMLFrameSerializerDelegate() override;
+ ~MHTMLFrameSerializerDelegate() override = default;
bool ShouldIgnoreElement(const Element&) override;
bool ShouldIgnoreAttribute(const Element&, const Attribute&) override;
bool RewriteLink(const Element&, String& rewritten_link) override;
@@ -135,14 +135,6 @@ MHTMLFrameSerializerDelegate::MHTMLFrameSerializerDelegate(
shadow_template_elements_(shadow_template_elements),
popup_overlays_skipped_(false) {}
-MHTMLFrameSerializerDelegate::~MHTMLFrameSerializerDelegate() {
- if (web_delegate_.RemovePopupOverlay()) {
- UMA_HISTOGRAM_BOOLEAN(
- "PageSerialization.MhtmlGeneration.PopupOverlaySkipped",
- popup_overlays_skipped_);
- }
-}
-
bool MHTMLFrameSerializerDelegate::ShouldIgnoreElement(const Element& element) {
if (ShouldIgnoreHiddenElement(element))
return true;
@@ -235,8 +227,11 @@ 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() == html_names::kSrcsetAttr)
+ if (IsHTMLImageElement(element) &&
+ (attribute.LocalName() == html_names::kSrcsetAttr ||
+ attribute.LocalName() == html_names::kSizesAttr)) {
return true;
+ }
// Do not save ping attribute since anyway the ping will be blocked from
// MHTML.
@@ -406,7 +401,7 @@ WebThreadSafeData WebFrameSerializer::GenerateMHTMLHeader(
scoped_refptr<RawData> buffer = RawData::Create();
MHTMLArchive::GenerateMHTMLHeader(
boundary, document->Url(), document->title(),
- document->SuggestedMIMEType(), WTF::Time::Now(), *buffer->MutableData());
+ document->SuggestedMIMEType(), base::Time::Now(), *buffer->MutableData());
return WebThreadSafeData(buffer);
}
diff --git a/chromium/third_party/blink/renderer/core/exported/web_frame_serializer_import_test.cc b/chromium/third_party/blink/renderer/core/exported/web_frame_serializer_import_test.cc
new file mode 100644
index 00000000000..d1e975fdad0
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/exported/web_frame_serializer_import_test.cc
@@ -0,0 +1,68 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/renderer/core/dom/document.h"
+#include "third_party/blink/renderer/core/exported/web_frame_serializer_test_helper.h"
+#include "third_party/blink/renderer/core/html/html_link_element.h"
+#include "third_party/blink/renderer/core/testing/sim/sim_request.h"
+#include "third_party/blink/renderer/core/testing/sim/sim_test.h"
+
+namespace blink {
+
+class WebFrameSerializerImportTest : public SimTest {
+ protected:
+ WebFrameSerializerImportTest() = default;
+
+ void SetUp() override {
+ SimTest::SetUp();
+ WebView().MainFrameWidget()->Resize(WebSize(500, 500));
+ }
+};
+
+TEST_F(WebFrameSerializerImportTest,
+ AddStylesheetFromStyleElementInHtmlImport) {
+ SimRequest main_resource("https://example.com/", "text/html");
+ SimSubresourceRequest import_resource("https://example.com/import.html",
+ "text/html");
+
+ LoadURL("https://example.com/");
+ main_resource.Complete("<link id=link rel=import href=import.html>");
+ import_resource.Complete("<style>div { color: blue; }</style>");
+
+ Document* import_doc =
+ ToHTMLLinkElement(GetDocument().getElementById("link"))->import();
+ ASSERT_TRUE(import_doc);
+ import_doc->GetStyleEngine().StyleSheetsForStyleSheetList(*import_doc);
+
+ String mhtml = WebFrameSerializerTestHelper::GenerateMHTML(&MainFrame());
+
+ // The CSS styles defined in imported HTML should be added.
+ EXPECT_NE(WTF::kNotFound, mhtml.Find("div { color: blue; }"));
+}
+
+TEST_F(WebFrameSerializerImportTest, AddStylesheetFromLinkElementInHtmlImport) {
+ SimRequest main_resource("https://example.com/", "text/html");
+ SimSubresourceRequest import_resource("https://example.com/import.html",
+ "text/html");
+ SimSubresourceRequest import_css("https://example.com/import.css",
+ "text/css");
+
+ LoadURL("https://example.com/");
+ main_resource.Complete("<link id=link rel=import href=import.html>");
+ import_resource.Complete("<link rel=import href=import.css>");
+ import_css.Complete("<style>div { color: red; }</style>");
+
+ Document* import_doc =
+ ToHTMLLinkElement(GetDocument().getElementById("link"))->import();
+ ASSERT_TRUE(import_doc);
+ import_doc->GetStyleEngine().StyleSheetsForStyleSheetList(*import_doc);
+
+ String mhtml = WebFrameSerializerTestHelper::GenerateMHTML(&MainFrame());
+
+ // The CSS styles defined in imported HTML should be added.
+ EXPECT_NE(WTF::kNotFound, mhtml.Find("div { color: red; }"));
+}
+
+} // namespace blink
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 e03d3cc38f4..7dba92896f7 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
@@ -36,40 +36,18 @@
#include "third_party/blink/public/platform/web_url.h"
#include "third_party/blink/public/platform/web_url_loader_mock_factory.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
+#include "third_party/blink/renderer/core/exported/web_frame_serializer_test_helper.h"
#include "third_party/blink/renderer/core/exported/web_view_impl.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/mhtml/mhtml_archive.h"
-#include "third_party/blink/renderer/platform/mhtml/mhtml_parser.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"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
-#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
namespace blink {
namespace {
-class SimpleMHTMLPartsGenerationDelegate
- : public WebFrameSerializer::MHTMLPartsGenerationDelegate {
- public:
- SimpleMHTMLPartsGenerationDelegate() : remove_popup_overlay_(false) {}
-
- void SetRemovePopupOverlay(bool remove_popup_overlay) {
- remove_popup_overlay_ = remove_popup_overlay;
- }
-
- private:
- bool ShouldSkipResource(const WebURL&) final { return false; }
-
- bool UseBinaryEncoding() final { return false; }
- bool RemovePopupOverlay() final { return remove_popup_overlay_; }
- bool UsePageProblemDetectors() final { return false; }
-
- bool remove_popup_overlay_;
-};
-
// Returns the count of match for substring |pattern| in string |str|.
int MatchSubstring(const String& str, const char* pattern, size_t size) {
int matches = 0;
@@ -98,12 +76,12 @@ class WebFrameSerializerSanitizationTest : public testing::Test {
String GenerateMHTMLFromHtml(const String& url, const String& file_name) {
LoadFrame(url, file_name, "text/html");
- return GenerateMHTML(false);
+ return WebFrameSerializerTestHelper::GenerateMHTML(MainFrameImpl());
}
String GenerateMHTMLPartsFromPng(const String& url, const String& file_name) {
LoadFrame(url, file_name, "image/png");
- return GenerateMHTML(true);
+ return WebFrameSerializerTestHelper::GenerateMHTMLParts(MainFrameImpl());
}
void LoadFrame(const String& url,
@@ -112,43 +90,11 @@ class WebFrameSerializerSanitizationTest : public testing::Test {
KURL parsed_url(url);
String file_path("frameserialization/" + file_name);
RegisterMockedFileURLLoad(parsed_url, file_path, mime_type);
- frame_test_helpers::LoadFrame(MainFrameImpl(), url.Utf8().data());
+ frame_test_helpers::LoadFrame(MainFrameImpl(), url.Utf8().c_str());
MainFrameImpl()->GetFrame()->View()->UpdateAllLifecyclePhases(
DocumentLifecycle::LifecycleUpdateReason::kTest);
- }
-
- String GenerateMHTML(const bool only_body_parts) {
- // Boundaries are normally randomly generated but this one is predefined for
- // simplicity and as good as any other. Plus it gets used in almost all the
- // examples in the MHTML spec - RFC 2557.
- const WebString boundary("boundary-example");
- StringBuilder mhtml;
- if (!only_body_parts) {
- WebThreadSafeData header_result = WebFrameSerializer::GenerateMHTMLHeader(
- boundary, MainFrameImpl(), &mhtml_delegate_);
- mhtml.Append(header_result.Data(), header_result.size());
- }
-
- WebThreadSafeData body_result = WebFrameSerializer::GenerateMHTMLParts(
- boundary, MainFrameImpl(), &mhtml_delegate_);
- mhtml.Append(body_result.Data(), body_result.size());
-
- if (!only_body_parts) {
- scoped_refptr<RawData> footer_data = RawData::Create();
- MHTMLArchive::GenerateMHTMLFooterForTesting(boundary,
- *footer_data->MutableData());
- mhtml.Append(footer_data->data(), footer_data->length());
- }
-
- String mhtml_string = mhtml.ToString();
- if (!only_body_parts) {
- // Validate the generated MHTML.
- MHTMLParser parser(SharedBuffer::Create(mhtml_string.Characters8(),
- size_t(mhtml_string.length())));
- EXPECT_FALSE(parser.ParseArchive().IsEmpty())
- << "Generated MHTML is not well formed";
- }
- return mhtml_string;
+ MainFrameImpl()->GetFrame()->GetDocument()->UpdateStyleAndLayoutTree();
+ test::RunPendingTasks();
}
ShadowRoot* SetShadowContent(TreeScope& scope,
@@ -173,26 +119,19 @@ class WebFrameSerializerSanitizationTest : public testing::Test {
return shadow_root;
}
- void SetRemovePopupOverlay(bool remove_popup_overlay) {
- mhtml_delegate_.SetRemovePopupOverlay(remove_popup_overlay);
- }
-
void RegisterMockedFileURLLoad(const KURL& url,
const String& file_path,
const String& mime_type = "image/png") {
url_test_helpers::RegisterMockedURLLoad(
- url, test::CoreTestDataPath(file_path.Utf8().data()), mime_type);
+ url, test::CoreTestDataPath(file_path.Utf8().c_str()), mime_type);
}
WebViewImpl* WebView() { return helper_.GetWebView(); }
WebLocalFrameImpl* MainFrameImpl() { return helper_.LocalMainFrame(); }
- HistogramTester histogram_tester_;
-
private:
frame_test_helpers::WebViewHelper helper_;
- SimpleMHTMLPartsGenerationDelegate mhtml_delegate_;
};
TEST_F(WebFrameSerializerSanitizationTest, RemoveInlineScriptInAttributes) {
@@ -233,10 +172,12 @@ TEST_F(WebFrameSerializerSanitizationTest, RemoveHiddenElements) {
// The hidden form element should be removed.
EXPECT_EQ(WTF::kNotFound, mhtml.Find("<input type=3D\"hidden\""));
+ // The style element should be converted to link element.
+ EXPECT_EQ(WTF::kNotFound, mhtml.Find("<style"));
+
// All other hidden elements should not be removed.
EXPECT_NE(WTF::kNotFound, mhtml.Find("<html"));
EXPECT_NE(WTF::kNotFound, mhtml.Find("<head"));
- EXPECT_NE(WTF::kNotFound, mhtml.Find("<style"));
EXPECT_NE(WTF::kNotFound, mhtml.Find("<title"));
EXPECT_NE(WTF::kNotFound, mhtml.Find("<h1"));
EXPECT_NE(WTF::kNotFound, mhtml.Find("<h2"));
@@ -244,10 +185,9 @@ TEST_F(WebFrameSerializerSanitizationTest, RemoveHiddenElements) {
EXPECT_NE(WTF::kNotFound, mhtml.Find("<option"));
// One for meta in head and another for meta in body.
EXPECT_EQ(2, MatchSubstring(mhtml, "<meta", 5));
- // One for style in head and another for style in body.
- EXPECT_EQ(2, MatchSubstring(mhtml, "<style", 6));
- // One for link in head and another for link in body.
- EXPECT_EQ(2, MatchSubstring(mhtml, "<link", 5));
+ // Two for original link elements: one in head and another in body.
+ // Two for original style elemtns: one in head and another in body.
+ EXPECT_EQ(4, MatchSubstring(mhtml, "<link", 5));
// These visible elements should remain intact.
EXPECT_NE(WTF::kNotFound, mhtml.Find("<p id=3D\"visible_id\""));
@@ -287,8 +227,17 @@ TEST_F(WebFrameSerializerSanitizationTest, ImageLoadedFromSrcsetForHiDPI) {
String mhtml =
GenerateMHTMLFromHtml("http://www.test.com", "img_srcset.html");
- // srcset attribute should be skipped.
+ // srcset and sizes attributes should be skipped.
EXPECT_EQ(WTF::kNotFound, mhtml.Find("srcset="));
+ EXPECT_EQ(WTF::kNotFound, mhtml.Find("sizes="));
+
+ // src attribute with original URL should be preserved.
+ EXPECT_EQ(2,
+ MatchSubstring(mhtml, "src=3D\"http://www.test.com/1x.png\"", 34));
+
+ // The image resource for original URL should be attached.
+ EXPECT_NE(WTF::kNotFound,
+ mhtml.Find("Content-Location: http://www.test.com/1x.png"));
// Width and height attributes should be set when none is present in <img>.
EXPECT_NE(WTF::kNotFound,
@@ -308,8 +257,17 @@ TEST_F(WebFrameSerializerSanitizationTest, ImageLoadedFromSrcForNormalDPI) {
String mhtml =
GenerateMHTMLFromHtml("http://www.test.com", "img_srcset.html");
- // srcset attribute should be skipped.
+ // srcset and sizes attributes should be skipped.
EXPECT_EQ(WTF::kNotFound, mhtml.Find("srcset="));
+ EXPECT_EQ(WTF::kNotFound, mhtml.Find("sizes="));
+
+ // src attribute with original URL should be preserved.
+ EXPECT_EQ(2,
+ MatchSubstring(mhtml, "src=3D\"http://www.test.com/1x.png\"", 34));
+
+ // The image resource for original URL should be attached.
+ EXPECT_NE(WTF::kNotFound,
+ mhtml.Find("Content-Location: http://www.test.com/1x.png"));
// New width and height attributes should not be set.
EXPECT_NE(WTF::kNotFound, mhtml.Find("id=3D\"i1\">"));
@@ -318,31 +276,26 @@ TEST_F(WebFrameSerializerSanitizationTest, ImageLoadedFromSrcForNormalDPI) {
TEST_F(WebFrameSerializerSanitizationTest, RemovePopupOverlayIfRequested) {
WebView()->MainFrameWidget()->Resize(WebSize(500, 500));
- SetRemovePopupOverlay(true);
- String mhtml = GenerateMHTMLFromHtml("http://www.test.com", "popup.html");
+ LoadFrame("http://www.test.com", "popup.html", "text/html");
+ String mhtml =
+ WebFrameSerializerTestHelper::GenerateMHTMLWithPopupOverlayRemoved(
+ MainFrameImpl());
EXPECT_EQ(WTF::kNotFound, mhtml.Find("class=3D\"overlay"));
EXPECT_EQ(WTF::kNotFound, mhtml.Find("class=3D\"modal"));
- histogram_tester_.ExpectUniqueSample(
- "PageSerialization.MhtmlGeneration.PopupOverlaySkipped", true, 1);
}
TEST_F(WebFrameSerializerSanitizationTest, PopupOverlayNotFound) {
WebView()->MainFrameWidget()->Resize(WebSize(500, 500));
- SetRemovePopupOverlay(true);
- String mhtml =
- GenerateMHTMLFromHtml("http://www.test.com", "text_only_page.html");
- histogram_tester_.ExpectUniqueSample(
- "PageSerialization.MhtmlGeneration.PopupOverlaySkipped", false, 1);
+ LoadFrame("http://www.test.com", "text_only_page.html", "text/html");
+ WebFrameSerializerTestHelper::GenerateMHTMLWithPopupOverlayRemoved(
+ MainFrameImpl());
}
TEST_F(WebFrameSerializerSanitizationTest, KeepPopupOverlayIfNotRequested) {
WebView()->MainFrameWidget()->Resize(WebSize(500, 500));
- SetRemovePopupOverlay(false);
String mhtml = GenerateMHTMLFromHtml("http://www.test.com", "popup.html");
EXPECT_NE(WTF::kNotFound, mhtml.Find("class=3D\"overlay"));
EXPECT_NE(WTF::kNotFound, mhtml.Find("class=3D\"modal"));
- histogram_tester_.ExpectTotalCount(
- "PageSerialization.MhtmlGeneration.PopupOverlaySkipped", 0);
}
TEST_F(WebFrameSerializerSanitizationTest, LinkIntegrity) {
@@ -389,7 +342,7 @@ TEST_F(WebFrameSerializerSanitizationTest, ShadowDOM) {
SetShadowContent(*document, "h2", ShadowRootType::kOpen,
"Parent shadow\n<p id=\"h3\">Foo</p>", true);
SetShadowContent(*shadowRoot, "h3", ShadowRootType::kClosed, "Nested shadow");
- String mhtml = GenerateMHTML(false);
+ String mhtml = WebFrameSerializerTestHelper::GenerateMHTML(MainFrameImpl());
// Template with special attribute should be created for each shadow DOM tree.
EXPECT_NE(WTF::kNotFound, mhtml.Find("<template shadowmode=3D\"v0\">"));
@@ -402,4 +355,50 @@ TEST_F(WebFrameSerializerSanitizationTest, ShadowDOM) {
EXPECT_EQ(WTF::kNotFound, mhtml.Find("shadowdelegatesfocus=3D\"bar\">"));
}
+TEST_F(WebFrameSerializerSanitizationTest, StyleElementsWithDynamicCSS) {
+ String mhtml = GenerateMHTMLFromHtml("http://www.test.com",
+ "style_element_with_dynamic_css.html");
+
+ // The dynamically updated CSS rules should be preserved.
+ EXPECT_NE(WTF::kNotFound, mhtml.Find("div { color: blue; }"));
+ EXPECT_NE(WTF::kNotFound, mhtml.Find("p { color: red; }"));
+ EXPECT_EQ(WTF::kNotFound, mhtml.Find("h1 { color: green; }"));
+}
+
+TEST_F(WebFrameSerializerSanitizationTest, PictureElement) {
+ RegisterMockedFileURLLoad(KURL("http://www.test.com/1x.png"),
+ "frameserialization/1x.png");
+ RegisterMockedFileURLLoad(KURL("http://www.test.com/2x.png"),
+ "frameserialization/2x.png");
+
+ WebView()->MainFrameWidget()->Resize(WebSize(500, 500));
+
+ String mhtml = GenerateMHTMLFromHtml("http://www.test.com", "picture.html");
+
+ // srcset attribute should be kept.
+ EXPECT_EQ(2, MatchSubstring(mhtml, "srcset=", 7));
+
+ // 2x.png resource should be added.
+ EXPECT_NE(WTF::kNotFound,
+ mhtml.Find("Content-Location: http://www.test.com/2x.png"));
+ EXPECT_EQ(WTF::kNotFound,
+ mhtml.Find("Content-Location: http://www.test.com/1x.png"));
+}
+
+TEST_F(WebFrameSerializerSanitizationTest, ImageInPluginElement) {
+ RegisterMockedFileURLLoad(KURL("http://www.test.com/1x.png"),
+ "frameserialization/1x.png");
+ RegisterMockedFileURLLoad(KURL("http://www.test.com/2x.png"),
+ "frameserialization/2x.png");
+
+ String mhtml =
+ GenerateMHTMLFromHtml("http://www.test.com", "image_in_plugin.html");
+
+ // Image resources for both object and embed elements should be added.
+ EXPECT_NE(WTF::kNotFound,
+ mhtml.Find("Content-Location: http://www.test.com/1x.png"));
+ EXPECT_NE(WTF::kNotFound,
+ mhtml.Find("Content-Location: http://www.test.com/2x.png"));
+}
+
} // namespace blink
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 74e129b345c..5acb60a6bff 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,7 +77,7 @@ 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(url_test_helpers::ToKURL(url.Utf8().data()),
+ RegisterMockedFileURLLoad(url_test_helpers::ToKURL(url.Utf8().c_str()),
"frameserialization/awesome.png");
}
@@ -85,7 +85,7 @@ class WebFrameSerializerTest : public testing::Test {
const String& file_path,
const String& mime_type = "image/png") {
url_test_helpers::RegisterMockedURLLoad(
- url, test::CoreTestDataPath(file_path.Utf8().data()), mime_type);
+ url, test::CoreTestDataPath(file_path.Utf8().c_str()), mime_type);
}
class SingleLinkRewritingDelegate
@@ -118,7 +118,7 @@ class WebFrameSerializerTest : public testing::Test {
KURL parsed_url(url);
String file_path("frameserialization/" + file_name);
RegisterMockedFileURLLoad(parsed_url, file_path, "text/html");
- frame_test_helpers::LoadFrame(MainFrameImpl(), url.Utf8().data());
+ frame_test_helpers::LoadFrame(MainFrameImpl(), url.Utf8().c_str());
SingleLinkRewritingDelegate delegate(parsed_url, WebString("local"));
SimpleWebFrameSerializerClient serializer_client;
WebFrameSerializer::Serialize(MainFrameImpl(), &serializer_client,
diff --git a/chromium/third_party/blink/renderer/core/exported/web_frame_serializer_test_helper.cc b/chromium/third_party/blink/renderer/core/exported/web_frame_serializer_test_helper.cc
new file mode 100644
index 00000000000..b97e6b77f9b
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/exported/web_frame_serializer_test_helper.cc
@@ -0,0 +1,99 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/exported/web_frame_serializer_test_helper.h"
+
+#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/public/platform/platform.h"
+#include "third_party/blink/public/platform/web_string.h"
+#include "third_party/blink/public/platform/web_url.h"
+#include "third_party/blink/public/web/web_frame_serializer.h"
+#include "third_party/blink/renderer/core/frame/web_local_frame_impl.h"
+#include "third_party/blink/renderer/platform/mhtml/mhtml_archive.h"
+#include "third_party/blink/renderer/platform/mhtml/mhtml_parser.h"
+#include "third_party/blink/renderer/platform/shared_buffer.h"
+#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
+
+namespace blink {
+
+namespace {
+
+class SimpleMHTMLPartsGenerationDelegate
+ : public WebFrameSerializer::MHTMLPartsGenerationDelegate {
+ public:
+ SimpleMHTMLPartsGenerationDelegate() : remove_popup_overlay_(false) {}
+
+ void SetRemovePopupOverlay(bool remove_popup_overlay) {
+ remove_popup_overlay_ = remove_popup_overlay;
+ }
+
+ private:
+ bool ShouldSkipResource(const WebURL&) final { return false; }
+
+ bool UseBinaryEncoding() final { return false; }
+ bool RemovePopupOverlay() final { return remove_popup_overlay_; }
+ bool UsePageProblemDetectors() final { return false; }
+
+ bool remove_popup_overlay_;
+};
+
+String GenerateMHTMLHelper(WebLocalFrameImpl* frame,
+ const bool only_body_parts,
+ const bool remove_popup_overlay) {
+ SimpleMHTMLPartsGenerationDelegate mhtml_delegate;
+ mhtml_delegate.SetRemovePopupOverlay(remove_popup_overlay);
+
+ // Boundaries are normally randomly generated but this one is predefined for
+ // simplicity and as good as any other. Plus it gets used in almost all the
+ // examples in the MHTML spec - RFC 2557.
+ const WebString boundary("boundary-example");
+ StringBuilder mhtml;
+ if (!only_body_parts) {
+ WebThreadSafeData header_result = WebFrameSerializer::GenerateMHTMLHeader(
+ boundary, frame, &mhtml_delegate);
+ mhtml.Append(header_result.Data(), header_result.size());
+ }
+
+ WebThreadSafeData body_result =
+ WebFrameSerializer::GenerateMHTMLParts(boundary, frame, &mhtml_delegate);
+ mhtml.Append(body_result.Data(), body_result.size());
+
+ if (!only_body_parts) {
+ scoped_refptr<RawData> footer_data = RawData::Create();
+ MHTMLArchive::GenerateMHTMLFooterForTesting(boundary,
+ *footer_data->MutableData());
+ mhtml.Append(footer_data->data(), footer_data->length());
+ }
+
+ String mhtml_string = mhtml.ToString();
+ if (!only_body_parts) {
+ // Validate the generated MHTML.
+ MHTMLParser parser(SharedBuffer::Create(mhtml_string.Characters8(),
+ size_t(mhtml_string.length())));
+ EXPECT_FALSE(parser.ParseArchive().IsEmpty())
+ << "Generated MHTML is not well formed";
+ }
+ return mhtml_string;
+}
+
+} // namespace
+
+String WebFrameSerializerTestHelper::GenerateMHTML(WebLocalFrameImpl* frame) {
+ return GenerateMHTMLHelper(frame, false /*remove_popup_overlay*/,
+ false /*remove_popup_overlay*/);
+}
+
+String WebFrameSerializerTestHelper::GenerateMHTMLParts(
+ WebLocalFrameImpl* frame) {
+ return GenerateMHTMLHelper(frame, true /*remove_popup_overlay*/,
+ false /*remove_popup_overlay*/);
+}
+
+String WebFrameSerializerTestHelper::GenerateMHTMLWithPopupOverlayRemoved(
+ WebLocalFrameImpl* frame) {
+ return GenerateMHTMLHelper(frame, false /*remove_popup_overlay*/,
+ true /*remove_popup_overlay*/);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/exported/web_frame_serializer_test_helper.h b/chromium/third_party/blink/renderer/core/exported/web_frame_serializer_test_helper.h
new file mode 100644
index 00000000000..85d051c0e09
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/exported/web_frame_serializer_test_helper.h
@@ -0,0 +1,32 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_EXPORTED_WEB_FRAME_SERIALIZER_TEST_HELPER_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_EXPORTED_WEB_FRAME_SERIALIZER_TEST_HELPER_H_
+
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
+
+namespace blink {
+
+class WebLocalFrameImpl;
+
+class WebFrameSerializerTestHelper {
+ STATIC_ONLY(WebFrameSerializerTestHelper);
+
+ public:
+ // Returns the MHTML serialization of |frame|. Header and footer are included.
+ static String GenerateMHTML(WebLocalFrameImpl*);
+
+ // Returns the body parts of MHTML serialization of |frame|. Header and footer
+ // are excluded.
+ static String GenerateMHTMLParts(WebLocalFrameImpl*);
+
+ // Same as GenerateMHTML(), except that popup overlays are removed.
+ static String GenerateMHTMLWithPopupOverlayRemoved(WebLocalFrameImpl*);
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_EXPORTED_WEB_FRAME_SERIALIZER_TEST_HELPER_H_
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 1b304338b65..d151d4d7c41 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
@@ -40,12 +40,14 @@
#include "cc/input/overscroll_behavior.h"
#include "cc/layers/picture_layer.h"
#include "mojo/public/cpp/bindings/binding.h"
+#include "mojo/public/cpp/bindings/pending_remote.h"
+#include "mojo/public/cpp/bindings/receiver.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/fetch/fetch_api_request.mojom-shared.h"
-#include "third_party/blink/public/mojom/frame/find_in_page.mojom-shared.h"
+#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h"
+#include "third_party/blink/public/mojom/frame/find_in_page.mojom-blink.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_cache.h"
#include "third_party/blink/public/platform/web_coalesced_input_event.h"
@@ -4040,7 +4042,6 @@ TEST_F(WebFrameTest, DivScrollIntoEditableTestZoomToLegibleScaleDisabled) {
web_view_helper.GetWebView()->EnableFakePageScaleAnimationForTesting(true);
- WebRect edit_box_with_text(200, 200, 250, 20);
WebRect edit_box_with_no_text(200, 250, 250, 20);
// Test scrolling the focused node
@@ -4163,9 +4164,6 @@ TEST_F(WebFrameTest, CharacterIndexAtPointWithPinchZoom) {
web_view_helper.GetWebView()->SetPageScaleFactor(2);
web_view_helper.GetWebView()->SetVisualViewportOffset(WebFloatPoint(100, 50));
- WebRect base_rect;
- WebRect extent_rect;
-
WebLocalFrame* main_frame =
web_view_helper.GetWebView()->MainFrame()->ToWebLocalFrame();
@@ -4194,9 +4192,6 @@ TEST_F(WebFrameTest, FirstRectForCharacterRangeWithPinchZoom) {
web_view_helper.GetWebView()->SetPageScaleFactor(scale);
web_view_helper.GetWebView()->SetVisualViewportOffset(visual_offset);
- WebRect base_rect;
- WebRect extent_rect;
-
WebRect rect;
main_frame->FirstRectForCharacterRange(0, 5, rect);
@@ -4809,17 +4804,12 @@ TEST_F(WebFrameTest, ExecuteScriptDuringDidCreateScriptContext) {
class TestFindInPageClient : public mojom::blink::FindInPageClient {
public:
TestFindInPageClient()
- : find_results_are_ready_(false),
- count_(-1),
- active_index_(-1),
- binding_(this) {}
+ : find_results_are_ready_(false), count_(-1), active_index_(-1) {}
~TestFindInPageClient() override = default;
void SetFrame(WebLocalFrameImpl* frame) {
- mojom::blink::FindInPageClientPtr client;
- binding_.Bind(MakeRequest(&client));
- frame->GetFindInPage()->SetClient(std::move(client));
+ frame->GetFindInPage()->SetClient(receiver_.BindNewPipeAndPassRemote());
}
void SetNumberOfMatches(
@@ -4848,7 +4838,7 @@ class TestFindInPageClient : public mojom::blink::FindInPageClient {
bool find_results_are_ready_;
int count_;
int active_index_;
- mojo::Binding<mojom::blink::FindInPageClient> binding_;
+ mojo::Receiver<mojom::blink::FindInPageClient> receiver_{this};
};
TEST_F(WebFrameTest, FindInPageMatchRects) {
@@ -5988,7 +5978,7 @@ TEST_F(WebFrameTest, SmartClipDoesNotCrashPositionReversed) {
}
static int ComputeOffset(LayoutObject* layout_object, int x, int y) {
- return layout_object->PositionForPoint(LayoutPoint(x, y))
+ return layout_object->PositionForPoint(PhysicalOffset(x, y))
.GetPosition()
.ComputeOffsetInContainerNode();
}
@@ -10315,7 +10305,7 @@ TEST_F(WebFrameTest, ImageDocumentLoadResponseEnd) {
ImageResource* resource = img_document->CachedImageResourceDeprecated();
EXPECT_TRUE(resource);
- EXPECT_NE(TimeTicks(), resource->LoadResponseEnd());
+ EXPECT_NE(base::TimeTicks(), resource->LoadResponseEnd());
DocumentLoader* loader = document->Loader();
@@ -10792,6 +10782,7 @@ TEST_F(WebFrameTest, LoadJavascriptURLInNewFrame) {
url_test_helpers::RegisterMockedURLLoad(ToKURL(redirect_url),
test::CoreTestDataPath("foo.html"));
helper.LocalMainFrame()->LoadJavaScriptURL(javascript_url);
+ RunPendingTasks();
// The result of the JS url replaces the existing contents on the
// Document, but the JS-triggered navigation should still occur.
@@ -10799,7 +10790,6 @@ TEST_F(WebFrameTest, LoadJavascriptURLInNewFrame) {
->GetDocument()
->documentElement()
->innerText());
- RunPendingTasks();
EXPECT_EQ(ToKURL(redirect_url),
To<LocalFrame>(helper.GetWebView()->GetPage()->MainFrame())
->GetDocument()
@@ -11102,7 +11092,7 @@ TEST_F(WebFrameTest, MouseOverDifferntNodeClearsTooltip) {
WebFloatPoint(div1_tag->OffsetLeft() + 5, div1_tag->OffsetTop() + 5),
WebFloatPoint(div1_tag->OffsetLeft() + 5, div1_tag->OffsetTop() + 5),
WebPointerProperties::Button::kNoButton, 0, WebInputEvent::kNoModifiers,
- CurrentTimeTicks());
+ base::TimeTicks::Now());
mouse_move_over_link_event.SetFrameScale(1);
document->GetFrame()->GetEventHandler().HandleMouseMoveEvent(
mouse_move_over_link_event, Vector<WebMouseEvent>(),
@@ -11122,7 +11112,7 @@ TEST_F(WebFrameTest, MouseOverDifferntNodeClearsTooltip) {
WebFloatPoint(div2_tag->OffsetLeft() + 5, div2_tag->OffsetTop() + 5),
WebFloatPoint(div2_tag->OffsetLeft() + 5, div2_tag->OffsetTop() + 5),
WebPointerProperties::Button::kNoButton, 0, WebInputEvent::kNoModifiers,
- CurrentTimeTicks());
+ base::TimeTicks::Now());
mouse_move_event.SetFrameScale(1);
document->GetFrame()->GetEventHandler().HandleMouseMoveEvent(
mouse_move_event, Vector<WebMouseEvent>(), Vector<WebMouseEvent>());
@@ -11194,7 +11184,7 @@ TEST_F(WebFrameSimTest, HitTestWithIgnoreClippingAtNegativeOffset) {
HitTestRequest::kActive |
HitTestRequest::kIgnoreClipping;
HitTestLocation location(
- frame_view->ConvertFromRootFrame(LayoutPoint(100, -50)));
+ frame_view->ConvertFromRootFrame(PhysicalOffset(100, -50)));
HitTestResult result(request, location);
frame_view->GetLayoutView()->HitTest(location, result);
@@ -11467,7 +11457,7 @@ TEST_F(WebFrameSimTest, TestScrollFocusedEditableElementIntoView) {
// Now resize the visual viewport so that the input box is no longer in view
// (e.g. a keyboard is overlayed).
- WebView().MainFrameWidget()->ResizeVisualViewport(IntSize(200, 100));
+ WebView().ResizeVisualViewport(IntSize(200, 100));
ASSERT_FALSE(frame_view->GetScrollableArea()->VisibleContentRect().Contains(
inputRect));
@@ -12756,8 +12746,7 @@ class ExternallyHandledPluginDocumentTest
TEST_P(ExternallyHandledPluginDocumentTest, DocumentType) {
bool cross_process = GetParam();
- RuntimeEnabledFeatures::SetMimeHandlerViewInCrossProcessFrameEnabled(
- cross_process);
+ ScopedMimeHandlerViewInCrossProcessFrameForTest scoped_feature(cross_process);
ScopedFakePluginRegistry fake_plugins;
RegisterMockedHttpURLLoadWithMimeType("test.pdf", "application/pdf");
frame_test_helpers::WebViewHelper web_view_helper;
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 5a551772926..12f681b3c84 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
@@ -76,6 +76,16 @@ WebPoint WebHitTestResult::LocalPointWithoutContentBoxOffset() const {
return local_point;
}
+bool WebHitTestResult::ContentBoxContainsPoint() const {
+ LayoutObject* object = private_->Result().GetLayoutObject();
+ DCHECK(object);
+ if (!object->IsBox())
+ return false;
+
+ IntPoint local_point = RoundedIntPoint(private_->Result().LocalPoint());
+ return ToLayoutBox(object)->ComputedCSSContentBoxRect().Contains(local_point);
+}
+
WebElement WebHitTestResult::UrlElement() const {
return WebElement(private_->Result().URLElement());
}
diff --git a/chromium/third_party/blink/renderer/core/exported/web_input_method_controller_impl.cc b/chromium/third_party/blink/renderer/core/exported/web_input_method_controller_impl.cc
index f502778e479..f70eb17b5a3 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_input_method_controller_impl.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_input_method_controller_impl.cc
@@ -122,17 +122,16 @@ bool WebInputMethodControllerImpl::CommitText(
relative_caret_position);
}
- // Select the range to be replaced with the composition later.
- if (!replacement_range.IsNull()) {
- web_frame_->SelectRange(replacement_range,
- WebLocalFrame::kHideSelectionHandle,
- blink::mojom::SelectionMenuBehavior::kHide);
- }
-
// TODO(editing-dev): The use of UpdateStyleAndLayout
// needs to be audited. See http://crbug.com/590369 for more details.
GetFrame()->GetDocument()->UpdateStyleAndLayout();
+ if (!replacement_range.IsNull()) {
+ return GetInputMethodController().ReplaceText(
+ text, PlainTextRange(replacement_range.StartOffset(),
+ replacement_range.EndOffset()));
+ }
+
return GetInputMethodController().CommitText(
text, ImeTextSpanVectorBuilder::Build(ime_text_spans),
relative_caret_position);
diff --git a/chromium/third_party/blink/renderer/core/exported/web_input_method_controller_impl.h b/chromium/third_party/blink/renderer/core/exported/web_input_method_controller_impl.h
index b2e829bd5da..6efd536efde 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_input_method_controller_impl.h
+++ b/chromium/third_party/blink/renderer/core/exported/web_input_method_controller_impl.h
@@ -10,7 +10,7 @@
#include "third_party/blink/public/web/web_input_method_controller.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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
index 0cb27052b18..ffbd4a48cc7 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_layer_test.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_layer_test.cc
@@ -272,6 +272,15 @@ class WebLayerListSimTest : public PaintTestConfigurations, public SimTest {
return Compositor().layer_tree_view().layer_tree_host()->property_trees();
}
+ cc::TransformNode* GetTransformNode(const cc::Layer* layer) {
+ return GetPropertyTrees()->transform_tree.Node(
+ layer->transform_tree_index());
+ }
+
+ cc::EffectNode* GetEffectNode(const cc::Layer* layer) {
+ return GetPropertyTrees()->effect_tree.Node(layer->effect_tree_index());
+ }
+
PaintArtifactCompositor* paint_artifact_compositor() {
return MainFrame().GetFrameView()->GetPaintArtifactCompositorForTesting();
}
@@ -474,20 +483,29 @@ TEST_P(WebLayerListSimTest, LayerSubtreeTransformPropertyChanged) {
// Initially, no layer should have |subtree_property_changed| set.
EXPECT_FALSE(outer_element_layer->subtree_property_changed());
+ EXPECT_FALSE(GetTransformNode(outer_element_layer)->transform_changed);
EXPECT_FALSE(inner_element_layer->subtree_property_changed());
+ EXPECT_FALSE(GetTransformNode(inner_element_layer)->transform_changed);
// Modifying the transform style should set |subtree_property_changed| on
// both layers.
outer_element->setAttribute(html_names::kStyleAttr,
"transform: rotate(10deg)");
UpdateAllLifecyclePhases();
+ // This is still set by the traditional GraphicsLayer::SetTransform().
EXPECT_TRUE(outer_element_layer->subtree_property_changed());
+ // Set by blink::PropertyTreeManager.
+ EXPECT_TRUE(GetTransformNode(outer_element_layer)->transform_changed);
+ // TODO(wangxianzhu): Probably avoid setting this flag on transform change.
EXPECT_TRUE(inner_element_layer->subtree_property_changed());
+ EXPECT_FALSE(GetTransformNode(inner_element_layer)->transform_changed);
// After a frame the |subtree_property_changed| value should be reset.
Compositor().BeginFrame();
EXPECT_FALSE(outer_element_layer->subtree_property_changed());
+ EXPECT_FALSE(GetTransformNode(outer_element_layer)->transform_changed);
EXPECT_FALSE(inner_element_layer->subtree_property_changed());
+ EXPECT_FALSE(GetTransformNode(inner_element_layer)->transform_changed);
}
// When a property tree change occurs that affects layer transform in a simple
@@ -553,6 +571,91 @@ TEST_P(WebLayerListSimTest, DirectTransformPropertyUpdate) {
EXPECT_FALSE(transform_node->transform_changed);
}
+// This test is similar to |DirectTransformPropertyUpdate| but tests that
+// the changed value of a directly updated transform is still set if some other
+// change causes PaintArtifactCompositor to run and do non-direct updates.
+TEST_P(WebLayerListSimTest, DirectTransformPropertyUpdateCausesChange) {
+ // TODO(crbug.com/765003): CAP may make different layerization decisions and
+ // we cannot guarantee that both divs will be composited in this test. When
+ // CAP gets closer to launch, this test should be updated to pass.
+ if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled())
+ return;
+
+ InitializeWithHTML(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ html { overflow: hidden; }
+ #outer {
+ width: 100px;
+ height: 100px;
+ will-change: transform;
+ transform: translate(1px, 2px);
+ }
+ #inner {
+ width: 100px;
+ height: 100px;
+ will-change: transform;
+ background: lightblue;
+ transform: translate(3px, 4px);
+ }
+ </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 outer_transform_tree_index = outer_element_layer->transform_tree_index();
+ auto* outer_transform_node =
+ GetPropertyTrees()->transform_tree.Node(outer_transform_tree_index);
+
+ 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));
+ auto inner_transform_tree_index = inner_element_layer->transform_tree_index();
+ auto* inner_transform_node =
+ GetPropertyTrees()->transform_tree.Node(inner_transform_tree_index);
+
+ // Initially, the transforms should be unchanged.
+ EXPECT_FALSE(outer_transform_node->transform_changed);
+ EXPECT_FALSE(inner_transform_node->transform_changed);
+ EXPECT_FALSE(paint_artifact_compositor()->NeedsUpdate());
+
+ // Modifying the outer transform in a simple way should allow for a direct
+ // update of the outer transform. Modifying the inner transform in a
+ // non-simple way should not allow for a direct update of the inner transform.
+ outer_element->setAttribute(html_names::kStyleAttr,
+ "transform: translate(5px, 6px)");
+ inner_element->setAttribute(html_names::kStyleAttr,
+ "transform: rotate(30deg)");
+ UpdateAllLifecyclePhasesExceptPaint();
+ EXPECT_TRUE(outer_transform_node->transform_changed);
+ EXPECT_FALSE(inner_transform_node->transform_changed);
+ EXPECT_TRUE(paint_artifact_compositor()->NeedsUpdate());
+
+ // After a PaintArtifactCompositor update, which was needed due to the inner
+ // element's transform change, both the inner and outer transform nodes
+ // should be marked as changed to ensure they result in damage.
+ UpdateAllLifecyclePhases();
+ EXPECT_TRUE(outer_transform_node->transform_changed);
+ EXPECT_TRUE(inner_transform_node->transform_changed);
+
+ // After a frame the |transform_changed| values should be reset.
+ Compositor().BeginFrame();
+ EXPECT_FALSE(outer_transform_node->transform_changed);
+ EXPECT_FALSE(inner_transform_node->transform_changed);
+}
+
// This test ensures that the correct transform nodes are created and bits set
// so that the browser controls movement adjustments needed by bottom-fixed
// elements will work.
@@ -719,19 +822,28 @@ TEST_P(WebLayerListSimTest, LayerSubtreeEffectPropertyChanged) {
// Initially, no layer should have |subtree_property_changed| set.
EXPECT_FALSE(outer_element_layer->subtree_property_changed());
+ EXPECT_FALSE(GetEffectNode(outer_element_layer)->effect_changed);
EXPECT_FALSE(inner_element_layer->subtree_property_changed());
+ EXPECT_FALSE(GetEffectNode(inner_element_layer)->effect_changed);
// Modifying the filter style should set |subtree_property_changed| on
// both layers.
outer_element->setAttribute(html_names::kStyleAttr, "filter: blur(20px)");
UpdateAllLifecyclePhases();
+ // TODO(wangxianzhu): Probably avoid setting this flag on transform change.
EXPECT_TRUE(outer_element_layer->subtree_property_changed());
+ // Set by blink::PropertyTreeManager.
+ EXPECT_TRUE(GetEffectNode(outer_element_layer)->effect_changed);
+ // TODO(wangxianzhu): Probably avoid setting this flag on transform change.
EXPECT_TRUE(inner_element_layer->subtree_property_changed());
+ EXPECT_FALSE(GetEffectNode(inner_element_layer)->effect_changed);
// After a frame the |subtree_property_changed| value should be reset.
Compositor().BeginFrame();
EXPECT_FALSE(outer_element_layer->subtree_property_changed());
+ EXPECT_FALSE(GetEffectNode(outer_element_layer)->effect_changed);
EXPECT_FALSE(inner_element_layer->subtree_property_changed());
+ EXPECT_FALSE(GetEffectNode(inner_element_layer)->effect_changed);
}
// This test is similar to |LayerSubtreeTransformPropertyChanged| but for
@@ -853,6 +965,52 @@ TEST_P(WebLayerListSimTest, LayerSubtreeOverflowClipPropertyChanged) {
EXPECT_FALSE(inner_element_layer->subtree_property_changed());
}
+// This test is similar to |LayerSubtreeClipPropertyChanged| but for cases when
+// the clip node itself does not change but the clip node associated with a
+// layer changes.
+TEST_P(WebLayerListSimTest, LayerClipPropertyChanged) {
+ InitializeWithHTML(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ #outer {
+ width: 100px;
+ height: 100px;
+ }
+ #inner {
+ width: 50px;
+ height: 200px;
+ backface-visibility: hidden;
+ background: lightblue;
+ }
+ </style>
+ <div id='outer' style='overflow: hidden;'>
+ <div id='inner'></div>
+ </div>
+ )HTML");
+
+ Compositor().BeginFrame();
+
+ auto* inner_element_layer = ContentLayerAt(ContentLayerCount() - 1);
+ EXPECT_FALSE(inner_element_layer->double_sided());
+
+ // Initially, no layer should have |subtree_property_changed| set.
+ EXPECT_FALSE(inner_element_layer->subtree_property_changed());
+
+ // Removing overflow: hidden on the outer div should set
+ // |subtree_property_changed| on the inner div's cc::Layer.
+ auto* outer_element = GetElementById("outer");
+ outer_element->setAttribute(html_names::kStyleAttr, "");
+ UpdateAllLifecyclePhases();
+
+ inner_element_layer = ContentLayerAt(ContentLayerCount() - 1);
+ EXPECT_FALSE(inner_element_layer->double_sided());
+ EXPECT_TRUE(inner_element_layer->subtree_property_changed());
+
+ // After a frame the |subtree_property_changed| value should be reset.
+ Compositor().BeginFrame();
+ EXPECT_FALSE(inner_element_layer->subtree_property_changed());
+}
+
TEST_P(WebLayerListSimTest, SafeOpaqueBackgroundColorGetsSet) {
// TODO(crbug.com/765003): CAP may make different layerization decisions and
// we cannot guarantee that both divs will be composited in this test. When
@@ -971,4 +1129,37 @@ TEST_P(WebLayerListSimTest, NonDrawableLayersIgnoredForRenderSurfaces) {
EXPECT_FALSE(effect_node->HasRenderSurface());
}
+TEST_P(WebLayerListSimTest, NoRenderSurfaceWithAxisAlignedTransformAnimation) {
+ InitializeWithHTML(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ @keyframes translation {
+ 0% { transform: translate(10px, 11px); }
+ 100% { transform: translate(20px, 21px); }
+ }
+ .animate {
+ animation-name: translation;
+ animation-duration: 1s;
+ width: 100px;
+ height: 100px;
+ overflow: hidden;
+ }
+ .compchild {
+ height: 200px;
+ width: 10px;
+ background: lightblue;
+ will-change: transform;
+ }
+ </style>
+ <div class="animate"><div class="compchild"></div></div>
+ )HTML");
+ Compositor().BeginFrame();
+ // No effect node with kClipAxisAlignment should be created because the
+ // animation is axis-aligned.
+ for (const auto& effect_node : GetPropertyTrees()->effect_tree.nodes()) {
+ EXPECT_NE(cc::RenderSurfaceReason::kClipAxisAlignment,
+ effect_node.render_surface_reason);
+ }
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/exported/web_memory_statistics.cc b/chromium/third_party/blink/renderer/core/exported/web_memory_statistics.cc
index 907463b67d2..2e2004b9f30 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_memory_statistics.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_memory_statistics.cc
@@ -14,8 +14,7 @@ WebMemoryStatistics WebMemoryStatistics::Get() {
statistics.partition_alloc_total_allocated_bytes =
WTF::Partitions::TotalActiveBytes();
statistics.blink_gc_total_allocated_bytes =
- ProcessHeap::TotalAllocatedObjectSize() +
- ProcessHeap::TotalMarkedObjectSize();
+ ProcessHeap::TotalAllocatedObjectSize();
return statistics;
}
diff --git a/chromium/third_party/blink/renderer/core/exported/web_message_port_converter.cc b/chromium/third_party/blink/renderer/core/exported/web_message_port_converter.cc
new file mode 100644
index 00000000000..333760d667f
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/exported/web_message_port_converter.cc
@@ -0,0 +1,24 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/public/web/web_message_port_converter.h"
+
+#include "third_party/blink/public/common/messaging/message_port_channel.h"
+#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_message_port.h"
+#include "third_party/blink/renderer/core/messaging/message_port.h"
+
+namespace blink {
+
+base::Optional<MessagePortChannel>
+WebMessagePortConverter::DisentangleAndExtractMessagePortChannel(
+ v8::Isolate* isolate,
+ v8::Local<v8::Value> value) {
+ MessagePort* port = V8MessagePort::ToImplWithTypeCheck(isolate, value);
+ if (!port || port->IsNeutered())
+ return base::nullopt;
+ return port->Disentangle();
+}
+
+} // 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 128af45522c..acba6e35496 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_node.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_node.cc
@@ -131,12 +131,13 @@ bool WebNode::IsCommentNode() const {
}
bool WebNode::IsFocusable() const {
- if (!private_->IsElementNode())
+ auto* element = DynamicTo<Element>(private_.Get());
+ if (!element)
return false;
if (!private_->GetDocument().HaveRenderBlockingResourcesLoaded())
return false;
private_->GetDocument().UpdateStyleAndLayoutTreeForNode(private_.Get());
- return ToElement(private_.Get())->IsFocusable();
+ return element->IsFocusable();
}
bool WebNode::IsContentEditable() const {
diff --git a/chromium/third_party/blink/renderer/core/exported/web_page_importance_signals.cc b/chromium/third_party/blink/renderer/core/exported/web_page_importance_signals.cc
index 7ab72ec0ec1..079d2223ffc 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_page_importance_signals.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_page_importance_signals.cc
@@ -5,7 +5,6 @@
#include "third_party/blink/public/web/web_page_importance_signals.h"
#include "third_party/blink/public/web/web_view_client.h"
-#include "third_party/blink/renderer/platform/histogram.h"
namespace blink {
@@ -22,11 +21,6 @@ void WebPageImportanceSignals::SetHadFormInteraction() {
}
void WebPageImportanceSignals::OnCommitLoad() {
- DEFINE_STATIC_LOCAL(
- EnumerationHistogram, had_form_interaction_histogram,
- ("PageImportanceSignals.HadFormInteraction.OnCommitLoad", 2));
- had_form_interaction_histogram.Count(had_form_interaction_);
-
Reset();
}
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 9b09c0ef7e1..975d53a6c94 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
@@ -118,7 +118,7 @@ class PagePopupChromeClient final : public EmptyChromeClient {
const String&) override {
#ifndef NDEBUG
fprintf(stderr, "CONSOLE MESSSAGE:%u: %s\n", line_number,
- message.Utf8().data());
+ message.Utf8().c_str());
#endif
}
@@ -162,41 +162,21 @@ class PagePopupChromeClient final : public EmptyChromeClient {
LocalFrame* frame,
cc::EventListenerClass event_class,
cc::EventListenerProperties properties) override {
- DCHECK(frame->IsMainFrame());
- WebWidgetClient* client = popup_->WidgetClient();
- if (WebLayerTreeView* layer_tree_view = popup_->layer_tree_view_) {
- layer_tree_view->SetEventListenerProperties(event_class, properties);
- if (event_class == cc::EventListenerClass::kTouchStartOrMove) {
- client->HasTouchEventHandlers(
- properties != cc::EventListenerProperties::kNone ||
- EventListenerProperties(
- frame, cc::EventListenerClass::kTouchEndOrCancel) !=
- cc::EventListenerProperties::kNone);
- } else if (event_class == cc::EventListenerClass::kTouchEndOrCancel) {
- client->HasTouchEventHandlers(
- properties != cc::EventListenerProperties::kNone ||
- EventListenerProperties(
- frame, cc::EventListenerClass::kTouchStartOrMove) !=
- cc::EventListenerProperties::kNone);
- }
- } else {
- client->HasTouchEventHandlers(true);
- }
+ // WebPagePopup always routes input to main thread (set up in RenderWidget),
+ // so no need to update listener properties.
}
cc::EventListenerProperties EventListenerProperties(
LocalFrame*,
cc::EventListenerClass event_class) const override {
- if (popup_->layer_tree_view_) {
- return popup_->layer_tree_view_->EventListenerProperties(event_class);
- }
+ // WebPagePopup always routes input to main thread (set up in RenderWidget),
+ // so no need to update listener properties.
return cc::EventListenerProperties::kNone;
}
void SetHasScrollEventHandlers(LocalFrame* frame,
bool has_event_handlers) override {
- DCHECK(frame->IsMainFrame());
- if (popup_->layer_tree_view_)
- popup_->layer_tree_view_->SetHaveScrollEventHandlers(has_event_handlers);
+ // WebPagePopup's compositor does not handle compositor thread input (set up
+ // in RenderWidget) so there is no need to signal this.
}
void SetTouchAction(LocalFrame* frame, TouchAction touch_action) override {
@@ -298,8 +278,13 @@ void WebPagePopupImpl::Initialize(WebViewImpl* web_view,
ProvideContextFeaturesTo(*page_, std::make_unique<PagePopupFeaturesClient>());
DEFINE_STATIC_LOCAL(Persistent<LocalFrameClient>, empty_local_frame_client,
(MakeGarbageCollected<EmptyLocalFrameClient>()));
- auto* frame = MakeGarbageCollected<LocalFrame>(empty_local_frame_client,
- *page_, nullptr);
+ // Creating new WindowAgentFactory because page popup content is owned by the
+ // user agent and should be isolated from the main frame.
+ auto* frame =
+ MakeGarbageCollected<LocalFrame>(empty_local_frame_client, *page_,
+ /* FrameOwner* */ nullptr,
+ /* WindowAgentFactory* */ nullptr,
+ /* InterfaceRegistry* */ nullptr);
frame->SetPagePopupOwner(popup_client_->OwnerElement());
frame->SetView(MakeGarbageCollected<LocalFrameView>(*frame));
frame->Init();
@@ -384,7 +369,7 @@ void WebPagePopupImpl::BeginFrame(base::TimeTicks last_frame_time, bool) {
return;
// FIXME: This should use lastFrameTimeMonotonic but doing so
// breaks tests.
- PageWidgetDelegate::Animate(*page_, CurrentTimeTicks());
+ PageWidgetDelegate::Animate(*page_, base::TimeTicks::Now());
}
void WebPagePopupImpl::UpdateLifecycle(LifecycleUpdate requested_update,
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 d01f0838995..720ae274fe0 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
@@ -566,10 +566,9 @@ bool WebPluginContainerImpl::IsRectTopmost(const WebRect& rect) {
if (!frame)
return false;
- IntPoint frame_location = Location();
- HitTestLocation location(LayoutRect(frame_location.X() + rect.x,
- frame_location.Y() + rect.y, rect.width,
- rect.height));
+ IntRect frame_rect = rect;
+ frame_rect.MoveBy(Location());
+ HitTestLocation location((PhysicalRect(frame_rect)));
HitTestResult result = frame->GetEventHandler().HitTestResultAtLocation(
location, HitTestRequest::kReadOnly | HitTestRequest::kActive |
HitTestRequest::kListBased);
@@ -967,8 +966,7 @@ WebTouchEvent WebPluginContainerImpl::TransformTouchEvent(
WebCoalescedInputEvent WebPluginContainerImpl::TransformCoalescedTouchEvent(
const WebCoalescedInputEvent& coalesced_event) {
WebCoalescedInputEvent transformed_event(
- TransformTouchEvent(coalesced_event.Event()),
- std::vector<const WebInputEvent*>(), std::vector<const WebInputEvent*>());
+ TransformTouchEvent(coalesced_event.Event()), {}, {});
for (size_t i = 0; i < coalesced_event.CoalescedEventSize(); ++i) {
transformed_event.AddCoalescedEvent(
TransformTouchEvent(coalesced_event.CoalescedEvent(i)));
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 0819a4fd3d7..1e22b764e32 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
@@ -1421,7 +1421,7 @@ TEST_F(WebPluginContainerTest, ClippedRectsForSubpixelPositionedPlugin) {
}
TEST_F(WebPluginContainerTest, TopmostAfterDetachTest) {
- static WebRect topmost_rect(10, 10, 40, 40);
+ static constexpr WebRect kTopmostRect(10, 10, 40, 40);
// Plugin that checks isRectTopmost in destroy().
class TopmostPlugin : public FakeWebPlugin {
@@ -1429,11 +1429,11 @@ TEST_F(WebPluginContainerTest, TopmostAfterDetachTest) {
explicit TopmostPlugin(const WebPluginParams& params)
: FakeWebPlugin(params) {}
- bool IsRectTopmost() { return Container()->IsRectTopmost(topmost_rect); }
+ bool IsRectTopmost() { return Container()->IsRectTopmost(kTopmostRect); }
void Destroy() override {
// In destroy, IsRectTopmost is no longer valid.
- EXPECT_FALSE(Container()->IsRectTopmost(topmost_rect));
+ EXPECT_FALSE(Container()->IsRectTopmost(kTopmostRect));
FakeWebPlugin::Destroy();
}
@@ -1454,7 +1454,7 @@ TEST_F(WebPluginContainerTest, TopmostAfterDetachTest) {
web_view, WebString::FromUTF8("translated-plugin")));
plugin_container_impl->SetFrameRect(IntRect(0, 0, 300, 300));
- EXPECT_TRUE(plugin_container_impl->IsRectTopmost(topmost_rect));
+ EXPECT_TRUE(plugin_container_impl->IsRectTopmost(kTopmostRect));
TopmostPlugin* test_plugin =
static_cast<TopmostPlugin*>(plugin_container_impl->Plugin());
@@ -1463,7 +1463,7 @@ TEST_F(WebPluginContainerTest, TopmostAfterDetachTest) {
// Cause the plugin's frame to be detached.
web_view_helper.Reset();
- EXPECT_FALSE(plugin_container_impl->IsRectTopmost(topmost_rect));
+ EXPECT_FALSE(plugin_container_impl->IsRectTopmost(kTopmostRect));
}
namespace {
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 e98696f7d6e..d973b15c64a 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
@@ -30,6 +30,8 @@
#include "third_party/blink/renderer/core/fullscreen/fullscreen.h"
#include "third_party/blink/renderer/core/fullscreen/fullscreen_options.h"
#include "third_party/blink/renderer/core/html/html_frame_owner_element.h"
+#include "third_party/blink/renderer/core/html/portal/html_portal_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/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/page/chrome_client.h"
@@ -41,6 +43,7 @@
#include "third_party/blink/renderer/platform/geometry/layout_rect.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
#include "v8/include/v8.h"
namespace blink {
@@ -65,6 +68,13 @@ WebRemoteFrame* WebRemoteFrame::CreateMainFrame(WebView* web_view,
return WebRemoteFrameImpl::CreateMainFrame(web_view, client, opener);
}
+WebRemoteFrame* WebRemoteFrame::CreateForPortal(
+ WebTreeScopeType scope,
+ WebRemoteFrameClient* client,
+ const WebElement& portal_element) {
+ return WebRemoteFrameImpl::CreateForPortal(scope, client, portal_element);
+}
+
WebRemoteFrameImpl* WebRemoteFrameImpl::Create(WebTreeScopeType scope,
WebRemoteFrameClient* client) {
WebRemoteFrameImpl* frame =
@@ -88,7 +98,27 @@ WebRemoteFrameImpl* WebRemoteFrameImpl::CreateMainFrame(
// swapping path and instead directly overwrites the main frame.
// TODO(dcheng): Remove the need for this and strongly enforce this condition
// with a DCHECK.
- frame->InitializeCoreFrame(page, nullptr, g_null_atom);
+ frame->InitializeCoreFrame(
+ page, nullptr, g_null_atom,
+ opener ? &ToCoreFrame(*opener)->window_agent_factory() : nullptr);
+ return frame;
+}
+
+WebRemoteFrameImpl* WebRemoteFrameImpl::CreateForPortal(
+ WebTreeScopeType scope,
+ WebRemoteFrameClient* client,
+ const WebElement& portal_element) {
+ WebRemoteFrameImpl* frame =
+ MakeGarbageCollected<WebRemoteFrameImpl>(scope, client);
+
+ Element* element = portal_element;
+ DCHECK(element->HasTagName(html_names::kPortalTag));
+ DCHECK(RuntimeEnabledFeatures::PortalsEnabled(&element->GetDocument()));
+ HTMLPortalElement* portal = static_cast<HTMLPortalElement*>(element);
+ LocalFrame* host_frame = portal->GetDocument().GetFrame();
+ frame->InitializeCoreFrame(*host_frame->GetPage(), portal, g_null_atom,
+ &host_frame->window_agent_factory());
+
return frame;
}
@@ -159,16 +189,21 @@ WebLocalFrame* WebRemoteFrameImpl::CreateLocalChild(
InsertAfter(child, previous_sibling);
auto* owner = MakeGarbageCollected<RemoteFrameOwner>(
frame_policy, frame_owner_properties, frame_owner_element_type);
- child->InitializeCoreFrame(*GetFrame()->GetPage(), owner, name);
+ child->InitializeCoreFrame(*GetFrame()->GetPage(), owner, name,
+ opener
+ ? &ToCoreFrame(*opener)->window_agent_factory()
+ : &GetFrame()->window_agent_factory());
DCHECK(child->GetFrame());
return child;
}
-void WebRemoteFrameImpl::InitializeCoreFrame(Page& page,
- FrameOwner* owner,
- const AtomicString& name) {
- SetCoreFrame(
- MakeGarbageCollected<RemoteFrame>(frame_client_.Get(), page, owner));
+void WebRemoteFrameImpl::InitializeCoreFrame(
+ Page& page,
+ FrameOwner* owner,
+ const AtomicString& name,
+ WindowAgentFactory* window_agent_factory) {
+ SetCoreFrame(MakeGarbageCollected<RemoteFrame>(frame_client_.Get(), page,
+ owner, window_agent_factory));
GetFrame()->CreateView();
frame_->Tree().SetName(name);
}
@@ -185,7 +220,10 @@ WebRemoteFrame* WebRemoteFrameImpl::CreateRemoteChild(
AppendChild(child);
auto* owner = MakeGarbageCollected<RemoteFrameOwner>(
frame_policy, WebFrameOwnerProperties(), frame_owner_element_type);
- child->InitializeCoreFrame(*GetFrame()->GetPage(), owner, name);
+ child->InitializeCoreFrame(*GetFrame()->GetPage(), owner, name,
+ opener
+ ? &ToCoreFrame(*opener)->window_agent_factory()
+ : &GetFrame()->window_agent_factory());
return child;
}
@@ -235,8 +273,7 @@ void WebRemoteFrameImpl::SetReplicatedOrigin(
void WebRemoteFrameImpl::SetReplicatedSandboxFlags(WebSandboxFlags flags) {
DCHECK(GetFrame());
- GetFrame()->GetSecurityContext()->ResetSandboxFlags();
- GetFrame()->GetSecurityContext()->EnforceSandboxFlags(
+ GetFrame()->GetSecurityContext()->ResetAndEnforceSandboxFlags(
static_cast<SandboxFlags>(flags));
}
@@ -298,7 +335,7 @@ void WebRemoteFrameImpl::SetReplicatedInsecureRequestPolicy(
}
void WebRemoteFrameImpl::SetReplicatedInsecureNavigationsSet(
- const std::vector<unsigned>& set) {
+ const WebVector<unsigned>& set) {
DCHECK(GetFrame());
GetFrame()->GetSecurityContext()->SetInsecureNavigationsSet(set);
}
@@ -398,11 +435,8 @@ void WebRemoteFrameImpl::ScrollRectToVisible(
}
// Schedule the scroll.
- LayoutRect absolute_rect =
- owner_object
- ->LocalToAncestorRect(PhysicalRect(rect_to_scroll),
- owner_object->View())
- .ToLayoutRect();
+ PhysicalRect absolute_rect = owner_object->LocalToAncestorRect(
+ PhysicalRect(rect_to_scroll), owner_object->View());
if (!params.zoom_into_rect ||
!owner_object->GetDocument().GetFrame()->LocalFrameRoot().IsMainFrame()) {
@@ -490,7 +524,7 @@ WebRemoteFrameImpl::WebRemoteFrameImpl(WebTreeScopeType scope,
: WebRemoteFrame(scope),
client_(client),
frame_client_(MakeGarbageCollected<RemoteFrameClientImpl>(this)),
- self_keep_alive_(this) {
+ self_keep_alive_(PERSISTENT_FROM_HERE, this) {
DCHECK(client);
}
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 0b5f67aa4c1..9b2bafddd2f 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
@@ -25,6 +25,7 @@ enum class WebFrameLoadType;
class WebView;
struct WebRect;
struct WebScrollIntoViewParams;
+class WindowAgentFactory;
class CORE_EXPORT WebRemoteFrameImpl final
: public GarbageCollectedFinalized<WebRemoteFrameImpl>,
@@ -34,6 +35,9 @@ class CORE_EXPORT WebRemoteFrameImpl final
static WebRemoteFrameImpl* CreateMainFrame(WebView*,
WebRemoteFrameClient*,
WebFrame* opener = nullptr);
+ static WebRemoteFrameImpl* CreateForPortal(WebTreeScopeType,
+ WebRemoteFrameClient*,
+ const WebElement& portal_element);
WebRemoteFrameImpl(WebTreeScopeType, WebRemoteFrameClient*);
~WebRemoteFrameImpl() override;
@@ -78,8 +82,7 @@ class CORE_EXPORT WebRemoteFrameImpl final
WebContentSecurityPolicySource) override;
void ResetReplicatedContentSecurityPolicy() override;
void SetReplicatedInsecureRequestPolicy(WebInsecureRequestPolicy) override;
- void SetReplicatedInsecureNavigationsSet(
- const std::vector<unsigned>&) override;
+ void SetReplicatedInsecureNavigationsSet(const WebVector<unsigned>&) override;
void ForwardResourceTimingToParent(const WebResourceTimingInfo&) override;
void DispatchLoadEventForFrameOwner() override;
void SetNeedsOcclusionTracking(bool) override;
@@ -99,7 +102,10 @@ class CORE_EXPORT WebRemoteFrameImpl final
WebRect GetCompositingRect() override;
void RenderFallbackContent() const override;
- void InitializeCoreFrame(Page&, FrameOwner*, const AtomicString& name);
+ void InitializeCoreFrame(Page&,
+ FrameOwner*,
+ const AtomicString& name,
+ WindowAgentFactory*);
RemoteFrame* GetFrame() const { return frame_.Get(); }
WebRemoteFrameClient* Client() const { return client_; }
diff --git a/chromium/third_party/blink/renderer/core/exported/web_scoped_page_pauser.cc b/chromium/third_party/blink/renderer/core/exported/web_scoped_page_pauser.cc
new file mode 100644
index 00000000000..8158a90f6a3
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/exported/web_scoped_page_pauser.cc
@@ -0,0 +1,38 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/public/platform/web_scoped_page_pauser.h"
+
+#include "third_party/blink/renderer/core/page/scoped_page_pauser.h"
+
+namespace blink {
+
+namespace {
+
+// Used to defer all page activity in cases where the embedder wishes to run
+// a nested event loop. Using a stack enables nesting of message loop
+// invocations.
+Vector<std::unique_ptr<ScopedPagePauser>>& PagePauserStack() {
+ DEFINE_STATIC_LOCAL(Vector<std::unique_ptr<ScopedPagePauser>>, pauser_stack,
+ ());
+ return pauser_stack;
+}
+
+} // namespace
+
+// static
+std::unique_ptr<WebScopedPagePauser> WebScopedPagePauser::Create() {
+ return std::unique_ptr<WebScopedPagePauser>(new WebScopedPagePauser);
+}
+
+WebScopedPagePauser::WebScopedPagePauser() {
+ PagePauserStack().push_back(std::make_unique<ScopedPagePauser>());
+}
+
+WebScopedPagePauser::~WebScopedPagePauser() {
+ DCHECK_NE(PagePauserStack().size(), 0u);
+ PagePauserStack().pop_back();
+}
+
+} // namespace blink
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 078eb87879e..e04441e2425 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
@@ -71,10 +71,10 @@ void GetFormEncoding(const HTMLFormElement& form, WTF::TextEncoding* encoding) {
// button is returned.
HTMLFormControlElement* ButtonToActivate(const HTMLFormElement& form) {
HTMLFormControlElement* first_submit_button = nullptr;
- for (auto& element : form.ListedElements()) {
- if (!element->IsFormControlElement())
+ for (ListedElement* element : form.ListedElements()) {
+ auto* control = DynamicTo<HTMLFormControlElement>(element);
+ if (!control)
continue;
- HTMLFormControlElement* control = ToHTMLFormControlElement(element);
if (control->IsActivatedSubmit()) {
// There's a button that is already activated for submit, return
// nullptr.
@@ -137,20 +137,19 @@ bool IsInDefaultState(const HTMLFormControlElement& form_element) {
// - More than one text field
HTMLInputElement* FindSuitableSearchInputElement(const HTMLFormElement& form) {
HTMLInputElement* text_element = nullptr;
- for (const auto& item : form.ListedElements()) {
- if (!item->IsFormControlElement())
+ for (ListedElement* item : form.ListedElements()) {
+ auto* control = DynamicTo<HTMLFormControlElement>(item);
+ if (!control)
continue;
- HTMLFormControlElement& control = ToHTMLFormControlElement(*item);
-
- if (control.IsDisabledFormControl() || control.GetName().IsNull())
+ if (control->IsDisabledFormControl() || control->GetName().IsNull())
continue;
- if (!IsInDefaultState(control) || IsHTMLTextAreaElement(control))
+ if (!IsInDefaultState(*control) || IsHTMLTextAreaElement(*control))
return nullptr;
- if (IsHTMLInputElement(control) && control.willValidate()) {
- const HTMLInputElement& input = ToHTMLInputElement(control);
+ if (IsHTMLInputElement(*control) && control->willValidate()) {
+ const HTMLInputElement& input = ToHTMLInputElement(*control);
// Return nothing if a file upload field or a password field are
// found.
@@ -165,7 +164,7 @@ HTMLInputElement* FindSuitableSearchInputElement(const HTMLFormElement& form) {
// searchable.
return nullptr;
}
- text_element = ToHTMLInputElement(&control);
+ text_element = ToHTMLInputElement(control);
}
}
}
@@ -183,16 +182,16 @@ bool BuildSearchString(const HTMLFormElement& form,
const WTF::TextEncoding& encoding,
const HTMLInputElement* text_element) {
bool is_element_found = false;
- for (const auto& item : form.ListedElements()) {
- if (!item->IsFormControlElement())
+ for (ListedElement* item : form.ListedElements()) {
+ auto* control = DynamicTo<HTMLFormControlElement>(item);
+ if (!control)
continue;
- HTMLFormControlElement& control = ToHTMLFormControlElement(*item);
- if (control.IsDisabledFormControl() || control.GetName().IsNull())
+ if (control->IsDisabledFormControl() || control->GetName().IsNull())
continue;
auto* form_data = MakeGarbageCollected<FormData>(encoding);
- control.AppendToFormData(*form_data);
+ control->AppendToFormData(*form_data);
for (const auto& entry : form_data->Entries()) {
if (!encoded_string->IsEmpty())
@@ -201,7 +200,7 @@ bool BuildSearchString(const HTMLFormElement& form,
form_data->Encode(entry->name()),
FormDataEncoder::kNormalizeCRLF);
encoded_string->push_back('=');
- if (&control == text_element) {
+ if (control == text_element) {
encoded_string->Append("{searchTerms}", 13);
is_element_found = true;
} else {
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 8312aab5bdb..962530bb9f7 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
@@ -377,6 +377,18 @@ void WebSettingsImpl::SetTextTrackTextSize(const WebString& size) {
settings_->SetTextTrackTextSize(size);
}
+void WebSettingsImpl::SetTextTrackWindowColor(const WebString& color) {
+ settings_->SetTextTrackWindowColor(color);
+}
+
+void WebSettingsImpl::SetTextTrackWindowPadding(const WebString& padding) {
+ settings_->SetTextTrackWindowPadding(padding);
+}
+
+void WebSettingsImpl::SetTextTrackWindowRadius(const WebString& radius) {
+ settings_->SetTextTrackWindowRadius(radius);
+}
+
void WebSettingsImpl::SetDNSPrefetchingEnabled(bool enabled) {
settings_->SetDNSPrefetchingEnabled(enabled);
}
@@ -624,6 +636,10 @@ void WebSettingsImpl::SetSyncXHRInDocumentsEnabled(bool enabled) {
settings_->SetSyncXHRInDocumentsEnabled(enabled);
}
+void WebSettingsImpl::SetCaretBrowsingEnabled(bool enabled) {
+ settings_->SetCaretBrowsingEnabled(enabled);
+}
+
void WebSettingsImpl::SetCookieEnabled(bool enabled) {
dev_tools_emulator_->SetCookieEnabled(enabled);
}
@@ -755,6 +771,10 @@ void WebSettingsImpl::SetPreferredColorScheme(
settings_->SetPreferredColorScheme(color_scheme);
}
+void WebSettingsImpl::SetForcedColors(ForcedColors forced_colors) {
+ settings_->SetForcedColors(forced_colors);
+}
+
STATIC_ASSERT_ENUM(WebSettings::ImageAnimationPolicy::kAllowed,
kImageAnimationPolicyAllowed);
STATIC_ASSERT_ENUM(WebSettings::ImageAnimationPolicy::kAnimateOnce,
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 6131c110c4e..3f1b4cec787 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
@@ -65,6 +65,7 @@ class CORE_EXPORT WebSettingsImpl final : public WebSettings {
void SetAutoZoomFocusedNodeToLegibleScale(bool) override;
void SetClobberUserAgentInitialScaleQuirk(bool) override;
void SetCookieEnabled(bool) override;
+ void SetCaretBrowsingEnabled(bool) override;
void SetNavigateOnDragDrop(bool) override;
void SetCursiveFontFamily(const WebString&,
UScriptCode = USCRIPT_COMMON) override;
@@ -175,6 +176,9 @@ class CORE_EXPORT WebSettingsImpl final : public WebSettings {
void SetTextTrackTextColor(const WebString&) override;
void SetTextTrackTextShadow(const WebString&) override;
void SetTextTrackTextSize(const WebString&) override;
+ void SetTextTrackWindowColor(const WebString&) override;
+ void SetTextTrackWindowPadding(const WebString&) override;
+ void SetTextTrackWindowRadius(const WebString&) override;
void SetThreadedScrollingEnabled(bool) override;
void SetTouchDragDropEnabled(bool) override;
void SetBarrelButtonForDragEnabled(bool) override;
@@ -216,6 +220,7 @@ class CORE_EXPORT WebSettingsImpl final : public WebSettings {
void SetForceDarkModeEnabled(bool) override;
void SetPreferredColorScheme(PreferredColorScheme) override;
+ void SetForcedColors(ForcedColors) override;
bool RenderVSyncNotificationEnabled() const {
return render_v_sync_notification_enabled_;
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 069b623c6f1..d42b1d926e2 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
@@ -65,7 +65,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/platform/cross_thread_functional.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/loader/fetch/fetch_client_settings_object_snapshot.h"
@@ -76,16 +75,19 @@
#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/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
-WebSharedWorkerImpl::WebSharedWorkerImpl(WebSharedWorkerClient* client)
+WebSharedWorkerImpl::WebSharedWorkerImpl(
+ WebSharedWorkerClient* client,
+ const base::UnguessableToken& appcache_host_id)
: client_(client),
creation_address_space_(mojom::IPAddressSpace::kPublic),
parent_execution_context_task_runners_(
ParentExecutionContextTaskRunners::Create()),
- weak_ptr_factory_(this) {
+ appcache_host_id_(appcache_host_id) {
DCHECK(IsMainThread());
}
@@ -123,13 +125,6 @@ void WebSharedWorkerImpl::TerminateWorkerThread() {
}
}
-std::unique_ptr<WebApplicationCacheHost>
-WebSharedWorkerImpl::CreateApplicationCacheHost(
- WebApplicationCacheHostClient* appcache_host_client) {
- DCHECK(IsMainThread());
- return client_->CreateApplicationCacheHost(appcache_host_client);
-}
-
void WebSharedWorkerImpl::OnShadowPageInitialized() {
DCHECK(IsMainThread());
DCHECK(!main_script_loader_);
@@ -151,8 +146,8 @@ void WebSharedWorkerImpl::OnShadowPageInitialized() {
main_script_loader_->LoadTopLevelScriptAsynchronously(
*shadow_page_->GetDocument(), shadow_page_->GetDocument()->Fetcher(),
script_request_url_, mojom::RequestContextType::SHARED_WORKER,
- network::mojom::FetchRequestMode::kSameOrigin,
- network::mojom::FetchCredentialsMode::kSameOrigin,
+ network::mojom::RequestMode::kSameOrigin,
+ network::mojom::CredentialsMode::kSameOrigin,
Bind(&WebSharedWorkerImpl::DidReceiveScriptLoaderResponse,
WTF::Unretained(this)),
Bind(&WebSharedWorkerImpl::OnScriptLoaderFinished,
@@ -182,10 +177,15 @@ void WebSharedWorkerImpl::CountFeature(WebFeature feature) {
void WebSharedWorkerImpl::DidFetchScript(int64_t app_cache_id) {
DCHECK(IsMainThread());
- client_->SelectAppCacheID(app_cache_id,
- WTF::Bind(&WebSharedWorkerImpl::OnAppCacheSelected,
- weak_ptr_factory_.GetWeakPtr()));
- client_->WorkerScriptLoaded();
+ Document* document = shadow_page_->GetDocument();
+ ApplicationCacheHost* host = document->Loader()->GetApplicationCacheHost();
+ if (host) {
+ host->SelectCacheForSharedWorker(
+ app_cache_id, WTF::Bind(&WebSharedWorkerImpl::OnAppCacheSelected,
+ weak_ptr_factory_.GetWeakPtr()));
+ } else {
+ OnAppCacheSelected();
+ }
}
void WebSharedWorkerImpl::DidFailToFetchClassicScript() {
@@ -259,9 +259,9 @@ void WebSharedWorkerImpl::StartWorkerContext(
// |shadow_page_| must be created after |devtools_worker_token_| because it
// triggers creation of a InspectorNetworkAgent that tries to access the
// token.
- shadow_page_ =
- std::make_unique<WorkerShadowPage>(this, std::move(loader_factory),
- std::move(privacy_preferences));
+ shadow_page_ = std::make_unique<WorkerShadowPage>(
+ this, std::move(loader_factory), std::move(privacy_preferences),
+ appcache_host_id_);
// If we were asked to pause worker context on start and wait for debugger
// then now is a good time to do that.
@@ -353,6 +353,13 @@ void WebSharedWorkerImpl::ContinueStartWorkerContext() {
// fetch (https://crbug.com/824646).
mojom::ScriptType script_type = mojom::ScriptType::kClassic;
+ auto worker_settings = std::make_unique<WorkerSettings>(
+ false /* disable_reading_from_canvas */,
+ false /* strict_mixed_content_checking */,
+ true /* allow_running_of_insecure_content */,
+ false /* strictly_block_blockable_mixed_content */,
+ GenericFontFamilySettings());
+
if (features::IsOffMainThreadSharedWorkerScriptFetchEnabled()) {
// Off-the-main-thread script fetch:
// Some params (e.g., referrer policy, address space, CSP) passed to
@@ -369,8 +376,8 @@ void WebSharedWorkerImpl::ContinueStartWorkerContext() {
document->IsSecureContext(), outside_settings_object->GetHttpsState(),
CreateWorkerClients(), base::nullopt /* response_address_space */,
nullptr /* origin_trial_tokens */, devtools_worker_token_,
- std::make_unique<WorkerSettings>(document->GetFrame()->GetSettings()),
- kV8CacheOptionsDefault, nullptr /* worklet_module_response_map */,
+ std::move(worker_settings), kV8CacheOptionsDefault,
+ nullptr /* worklet_module_response_map */,
std::move(pending_interface_provider_), BeginFrameProviderParams(),
nullptr /* parent_feature_policy */, base::UnguessableToken());
StartWorkerThread(std::move(creation_params), script_request_url_,
@@ -405,8 +412,8 @@ void WebSharedWorkerImpl::ContinueStartWorkerContext() {
document->IsSecureContext(), outside_settings_object->GetHttpsState(),
CreateWorkerClients(), main_script_loader_->ResponseAddressSpace(),
main_script_loader_->OriginTrialTokens(), devtools_worker_token_,
- std::make_unique<WorkerSettings>(document->GetFrame()->GetSettings()),
- kV8CacheOptionsDefault, nullptr /* worklet_module_response_map */,
+ std::move(worker_settings), kV8CacheOptionsDefault,
+ nullptr /* worklet_module_response_map */,
std::move(pending_interface_provider_));
StartWorkerThread(std::move(creation_params), script_response_url,
main_script_loader_->SourceText(),
@@ -493,8 +500,9 @@ scoped_refptr<base::SingleThreadTaskRunner> WebSharedWorkerImpl::GetTaskRunner(
}
std::unique_ptr<WebSharedWorker> WebSharedWorker::Create(
- WebSharedWorkerClient* client) {
- return base::WrapUnique(new WebSharedWorkerImpl(client));
+ WebSharedWorkerClient* client,
+ const base::UnguessableToken& appcache_host_id) {
+ return base::WrapUnique(new WebSharedWorkerImpl(client, appcache_host_id));
}
} // namespace blink
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 9ad14af5559..e7bfc5ec761 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
@@ -40,7 +40,7 @@
#include "services/service_manager/public/mojom/interface_provider.mojom-blink.h"
#include "third_party/blink/public/common/privacy_preferences.h"
#include "third_party/blink/public/mojom/csp/content_security_policy.mojom-blink.h"
-#include "third_party/blink/public/mojom/net/ip_address_space.mojom-shared.h"
+#include "third_party/blink/public/mojom/net/ip_address_space.mojom-blink.h"
#include "third_party/blink/public/mojom/worker/worker_content_settings_proxy.mojom-blink.h"
#include "third_party/blink/public/web/web_shared_worker_client.h"
#include "third_party/blink/renderer/core/core_export.h"
@@ -60,8 +60,6 @@ class SharedURLLoaderFactory;
namespace blink {
class SharedWorkerThread;
-class WebApplicationCacheHost;
-class WebApplicationCacheHostClient;
class WebSharedWorkerClient;
class WebString;
class WebURL;
@@ -76,13 +74,15 @@ class WorkerClassicScriptLoader;
class CORE_EXPORT WebSharedWorkerImpl final : public WebSharedWorker,
public WorkerShadowPage::Client {
public:
- explicit WebSharedWorkerImpl(WebSharedWorkerClient*);
+ WebSharedWorkerImpl(WebSharedWorkerClient*,
+ const base::UnguessableToken& appcache_host_id);
~WebSharedWorkerImpl() override;
// WorkerShadowPage::Client overrides.
- std::unique_ptr<WebApplicationCacheHost> CreateApplicationCacheHost(
- WebApplicationCacheHostClient*) override;
void OnShadowPageInitialized() override;
+ WebLocalFrameClient::AppCacheType GetAppCacheType() override {
+ return WebLocalFrameClient::AppCacheType::kAppCacheForSharedWorker;
+ }
// WebDevToolsAgentImpl::Client overrides.
void ResumeStartup() override;
@@ -169,8 +169,9 @@ class CORE_EXPORT WebSharedWorkerImpl final : public WebSharedWorker,
// document.
Persistent<ParentExecutionContextTaskRunners>
parent_execution_context_task_runners_;
+ const base::UnguessableToken appcache_host_id_;
- base::WeakPtrFactory<WebSharedWorkerImpl> weak_ptr_factory_;
+ base::WeakPtrFactory<WebSharedWorkerImpl> weak_ptr_factory_{this};
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/exported/web_surrounding_text_test.cc b/chromium/third_party/blink/renderer/core/exported/web_surrounding_text_test.cc
index 713231cf8fe..4a087bc0c3f 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_surrounding_text_test.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_surrounding_text_test.cc
@@ -384,9 +384,8 @@ TEST_F(WebSurroundingTextTest, SelectElementAndText) {
EphemeralRange selection = Select(0);
WebSurroundingText surrounding_text(selection, 100);
- EXPECT_STREQ(
- "\xEF\xBF\xBC\n57th Street and Lake Shore Drive\nChicago IL 60637",
- surrounding_text.TextContent().Utf8().data());
+ EXPECT_EQ("\xEF\xBF\xBC\n57th Street and Lake Shore Drive\nChicago IL 60637",
+ surrounding_text.TextContent().Utf8());
EXPECT_EQ(43u, surrounding_text.StartOffsetInTextContent());
EXPECT_EQ(43u, surrounding_text.EndOffsetInTextContent());
}
diff --git a/chromium/third_party/blink/renderer/core/exported/web_user_gesture_indicator.cc b/chromium/third_party/blink/renderer/core/exported/web_user_gesture_indicator.cc
index d45198be7d1..684bb67b6f0 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_user_gesture_indicator.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_user_gesture_indicator.cc
@@ -71,8 +71,4 @@ WebUserGestureToken WebUserGestureIndicator::CurrentUserGestureToken() {
return WebUserGestureToken(UserGestureIndicator::CurrentTokenThreadSafe());
}
-void WebUserGestureIndicator::ExtendTimeout() {
- UserGestureIndicator::SetTimeoutPolicy(UserGestureToken::kOutOfProcess);
-}
-
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/exported/web_user_gesture_token.cc b/chromium/third_party/blink/renderer/core/exported/web_user_gesture_token.cc
index 71909e9cff7..d445f13e091 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_user_gesture_token.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_user_gesture_token.cc
@@ -34,10 +34,6 @@
namespace blink {
-bool WebUserGestureToken::HasGestures() const {
- return !token_.IsNull() && token_->HasGestures();
-}
-
WebUserGestureToken::WebUserGestureToken(
scoped_refptr<UserGestureToken> token) {
token_ = std::move(token);
diff --git a/chromium/third_party/blink/renderer/core/exported/web_user_gesture_token_test.cc b/chromium/third_party/blink/renderer/core/exported/web_user_gesture_token_test.cc
index 5c532fdff29..dfb60c13558 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_user_gesture_token_test.cc
+++ b/chromium/third_party/blink/renderer/core/exported/web_user_gesture_token_test.cc
@@ -39,8 +39,10 @@
namespace blink {
TEST(WebUserGestureTokenTest, Basic) {
+ // UserGestureTokens are meaningless with UAv2.
+ RuntimeEnabledFeatures::SetUserActivationV2Enabled(false);
+
WebUserGestureToken token;
- EXPECT_FALSE(token.HasGestures());
{
WebScopedUserGesture indicator(token);
@@ -55,7 +57,6 @@ TEST(WebUserGestureTokenTest, Basic) {
token = WebUserGestureIndicator::CurrentUserGestureToken();
}
- EXPECT_TRUE(token.HasGestures());
EXPECT_FALSE(WebUserGestureIndicator::IsProcessingUserGesture(nullptr));
{
@@ -65,8 +66,6 @@ TEST(WebUserGestureTokenTest, Basic) {
EXPECT_FALSE(WebUserGestureIndicator::IsProcessingUserGesture(nullptr));
}
- EXPECT_FALSE(token.HasGestures());
-
{
WebScopedUserGesture indicator(token);
EXPECT_FALSE(WebUserGestureIndicator::IsProcessingUserGesture(nullptr));
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 4a9056441d2..414e7de22b0 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
@@ -45,6 +45,7 @@
#include "third_party/blink/public/platform/web_layer_tree_view.h"
#include "third_party/blink/public/platform/web_menu_source_type.h"
#include "third_party/blink/public/platform/web_scroll_into_view_params.h"
+#include "third_party/blink/public/platform/web_text_autosizer_page_info.h"
#include "third_party/blink/public/platform/web_text_input_info.h"
#include "third_party/blink/public/platform/web_url_request.h"
#include "third_party/blink/public/platform/web_vector.h"
@@ -106,7 +107,6 @@
#include "third_party/blink/renderer/core/frame/resize_viewport_anchor.h"
#include "third_party/blink/renderer/core/frame/rotation_viewport_anchor.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/frame/viewport_data.h"
#include "third_party/blink/renderer/core/frame/visual_viewport.h"
#include "third_party/blink/renderer/core/frame/web_frame_widget_base.h"
@@ -152,9 +152,10 @@
#include "third_party/blink/renderer/platform/graphics/image.h"
#include "third_party/blink/renderer/platform/graphics/paint/cull_rect.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_record_builder.h"
-#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/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/keyboard_codes.h"
#include "third_party/blink/renderer/platform/loader/fetch/unique_identifier.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
@@ -204,24 +205,6 @@ const double WebView::kTextSizeMultiplierRatio = 1.2;
const double WebView::kMinTextSizeMultiplier = 0.5;
const double WebView::kMaxTextSizeMultiplier = 3.0;
-// Used to defer all page activity in cases where the embedder wishes to run
-// a nested event loop. Using a stack enables nesting of message loop
-// invocations.
-static Vector<std::unique_ptr<ScopedPagePauser>>& PagePauserStack() {
- DEFINE_STATIC_LOCAL(Vector<std::unique_ptr<ScopedPagePauser>>, pauser_stack,
- ());
- return pauser_stack;
-}
-
-void WebView::WillEnterModalLoop() {
- PagePauserStack().push_back(std::make_unique<ScopedPagePauser>());
-}
-
-void WebView::DidExitModalLoop() {
- DCHECK(PagePauserStack().size());
- PagePauserStack().pop_back();
-}
-
// static
HashSet<WebViewImpl*>& WebViewImpl::AllInstances() {
DEFINE_STATIC_LOCAL(HashSet<WebViewImpl*>, all_instances, ());
@@ -431,7 +414,8 @@ void WebViewImpl::MouseContextMenu(const WebMouseEvent& event) {
WebMouseEvent transformed_event =
TransformWebMouseEvent(MainFrameImpl()->GetFrameView(), event);
transformed_event.menu_source_type = kMenuSourceMouse;
- LayoutPoint position_in_root_frame(transformed_event.PositionInRootFrame());
+ PhysicalOffset position_in_root_frame = PhysicalOffset::FromFloatPointRound(
+ transformed_event.PositionInRootFrame());
// Find the right target frame. See issue 1186900.
HitTestResult result = HitTestResultForRootFramePos(position_in_root_frame);
@@ -1478,9 +1462,7 @@ void WebViewImpl::BeginFrame(base::TimeTicks last_frame_time,
if (!MainFrameImpl())
return;
- if (RuntimeEnabledFeatures::UpdateHoverFromScrollAtBeginFrameEnabled() ||
- RuntimeEnabledFeatures::
- UpdateHoverFromLayoutChangeAtBeginFrameEnabled()) {
+ if (RuntimeEnabledFeatures::UpdateHoverAtBeginFrameEnabled()) {
MainFrameImpl()
->GetFrame()
->GetEventHandler()
@@ -1518,7 +1500,7 @@ void WebViewImpl::DidBeginFrame() {
void WebViewImpl::BeginRafAlignedInput() {
if (MainFrameImpl()) {
- raf_aligned_input_start_time_.emplace(CurrentTimeTicks());
+ raf_aligned_input_start_time_.emplace(base::TimeTicks::Now());
}
}
@@ -1527,14 +1509,14 @@ void WebViewImpl::EndRafAlignedInput() {
DCHECK(raf_aligned_input_start_time_);
MainFrameImpl()->GetFrame()->View()->EnsureUkmAggregator().RecordSample(
LocalFrameUkmAggregator::kHandleInputEvents,
- raf_aligned_input_start_time_.value(), CurrentTimeTicks());
+ raf_aligned_input_start_time_.value(), base::TimeTicks::Now());
}
raf_aligned_input_start_time_.reset();
}
void WebViewImpl::BeginUpdateLayers() {
if (MainFrameImpl())
- update_layers_start_time_.emplace(CurrentTimeTicks());
+ update_layers_start_time_.emplace(base::TimeTicks::Now());
}
void WebViewImpl::EndUpdateLayers() {
@@ -1542,14 +1524,14 @@ void WebViewImpl::EndUpdateLayers() {
DCHECK(update_layers_start_time_);
MainFrameImpl()->GetFrame()->View()->EnsureUkmAggregator().RecordSample(
LocalFrameUkmAggregator::kUpdateLayers,
- update_layers_start_time_.value(), CurrentTimeTicks());
+ update_layers_start_time_.value(), base::TimeTicks::Now());
}
update_layers_start_time_.reset();
}
void WebViewImpl::BeginCommitCompositorFrame() {
if (MainFrameImpl()) {
- commit_compositor_frame_start_time_.emplace(CurrentTimeTicks());
+ commit_compositor_frame_start_time_.emplace(base::TimeTicks::Now());
}
}
@@ -1558,7 +1540,7 @@ void WebViewImpl::EndCommitCompositorFrame() {
if (MainFrameImpl() && commit_compositor_frame_start_time_) {
MainFrameImpl()->GetFrame()->View()->EnsureUkmAggregator().RecordSample(
LocalFrameUkmAggregator::kProxyCommit,
- commit_compositor_frame_start_time_.value(), CurrentTimeTicks());
+ commit_compositor_frame_start_time_.value(), base::TimeTicks::Now());
}
commit_compositor_frame_start_time_.reset();
}
@@ -1578,7 +1560,7 @@ void WebViewImpl::RecordEndOfFrameMetrics(base::TimeTicks frame_begin_time) {
->GetFrame()
->View()
->EnsureUkmAggregator()
- .RecordEndOfFrameMetrics(frame_begin_time, CurrentTimeTicks());
+ .RecordEndOfFrameMetrics(frame_begin_time, base::TimeTicks::Now());
}
void WebViewImpl::UpdateLifecycle(LifecycleUpdate requested_update,
@@ -2029,9 +2011,22 @@ void WebViewImpl::DidAttachLocalMainFrame(WebWidgetClient* client) {
AsWidget().client->SetPageScaleStateAndLimits(
viewport.Scale(), viewport.IsPinchGestureActive(),
MinimumPageScaleFactor(), MaximumPageScaleFactor());
+ // Prevent main frame updates while the main frame is loading until enough
+ // progress is made and BeginMainFrames are explicitly asked for.
+ scoped_defer_main_frame_update_ = AsWidget().client->DeferMainFrameUpdate();
}
}
+void WebViewImpl::DidDetachLocalMainFrame() {
+ // The WebWidgetClient that generated the |scoped_defer_main_frame_update_|
+ // for a local main frame is going away.
+ // TODO(crbug.com/419087): For now, the WebWidgetClient (aka RenderWidget)
+ // is not destroyed, so this comment is not true, but it will be in the
+ // future. All references between |this| and the WebWidgetClient should be
+ // dropped regardless.
+ scoped_defer_main_frame_update_ = nullptr;
+}
+
void WebViewImpl::DidAttachRemoteMainFrame(WebWidgetClient* client) {
DCHECK(does_composite_);
DCHECK(!MainFrameImpl());
@@ -2148,7 +2143,7 @@ bool WebViewImpl::ScrollFocusedEditableElementIntoView() {
kScrollBehaviorInstant);
params.stop_at_main_frame_layout_viewport = true;
layout_object->ScrollRectToVisible(
- LayoutRect(layout_object->AbsoluteBoundingBoxRect()), params);
+ PhysicalRect(layout_object->AbsoluteBoundingBoxRect()), params);
ZoomAndScrollToFocusedEditableElementRect(
main_frame_view->RootFrameToDocument(
@@ -2664,12 +2659,20 @@ void WebViewImpl::UpdatePageDefinedViewportConstraints(
MainFrameImpl()->GetFrameView()->SetNeedsLayout();
}
- if (TextAutosizer* text_autosizer = document->GetTextAutosizer())
- text_autosizer->UpdatePageInfoInAllFrames();
-
UpdateMainFrameLayoutSize();
}
+void WebViewImpl::SetTextAutosizePageInfo(
+ const WebTextAutosizerPageInfo& page_info) {
+ Frame* root_frame = GetPage()->MainFrame();
+ DCHECK(root_frame->IsRemoteFrame());
+ if (page_info == GetPage()->TextAutosizerPageInfo())
+ return;
+
+ GetPage()->SetTextAutosizePageInfo(page_info);
+ TextAutosizer::UpdatePageInfoInAllFrames(root_frame);
+}
+
void WebViewImpl::UpdateMainFrameLayoutSize() {
if (should_auto_resize_ || !MainFrameImpl())
return;
@@ -2770,7 +2773,7 @@ void WebViewImpl::PerformPluginAction(const WebPluginAction& action,
const gfx::Point& location) {
// FIXME: Location is probably in viewport coordinates
HitTestResult result =
- HitTestResultForRootFramePos(LayoutPoint(IntPoint(location)));
+ HitTestResultForRootFramePos(PhysicalOffset(IntPoint(location)));
Node* node = result.InnerNode();
if (!IsHTMLObjectElement(*node) && !IsHTMLEmbedElement(*node))
return;
@@ -2815,8 +2818,8 @@ HitTestResult WebViewImpl::CoreHitTestResultAt(
DocumentLifecycle::AllowThrottlingScope throttling_scope(
MainFrameImpl()->GetFrame()->GetDocument()->Lifecycle());
LocalFrameView* view = MainFrameImpl()->GetFrameView();
- LayoutPoint point_in_root_frame =
- view->ViewportToFrame(LayoutPoint(IntPoint(point_in_viewport)));
+ PhysicalOffset point_in_root_frame =
+ view->ViewportToFrame(PhysicalOffset(IntPoint(point_in_viewport)));
return HitTestResultForRootFramePos(point_in_root_frame);
}
@@ -2872,7 +2875,6 @@ void WebViewImpl::SetDeviceEmulationTransform(
if (transform == device_emulation_transform_)
return;
device_emulation_transform_ = transform;
- GetPage()->GetVisualViewport().SetNeedsPaintPropertyUpdate();
UpdateDeviceEmulationTransform();
}
@@ -2882,11 +2884,14 @@ TransformationMatrix WebViewImpl::GetDeviceEmulationTransform() const {
void WebViewImpl::EnableDeviceEmulation(
const WebDeviceEmulationParams& params) {
- dev_tools_emulator_->EnableDeviceEmulation(params);
+ TransformationMatrix device_emulation_transform =
+ dev_tools_emulator_->EnableDeviceEmulation(params);
+ SetDeviceEmulationTransform(device_emulation_transform);
}
void WebViewImpl::DisableDeviceEmulation() {
dev_tools_emulator_->DisableDeviceEmulation();
+ SetDeviceEmulationTransform(TransformationMatrix());
}
void WebViewImpl::PerformCustomContextMenuAction(unsigned action) {
@@ -2992,7 +2997,6 @@ void WebViewImpl::UpdateBaseBackgroundColor() {
Color color = BaseBackgroundColor();
if (auto* local_frame = DynamicTo<LocalFrame>(AsView().page->MainFrame())) {
LocalFrameView* view = local_frame->View();
- view->SetBaseBackgroundColor(color);
view->UpdateBaseBackgroundColorRecursively(color);
}
}
@@ -3109,11 +3113,21 @@ void WebViewImpl::PageScaleFactorChanged() {
viewport.Scale(), viewport.IsPinchGestureActive(),
MinimumPageScaleFactor(), MaximumPageScaleFactor());
AsView().client->PageScaleFactorChanged(viewport.Scale());
- dev_tools_emulator_->MainFrameScrollOrScaleChanged();
+
+ if (dev_tools_emulator_->HasViewportOverride()) {
+ TransformationMatrix device_emulation_transform =
+ dev_tools_emulator_->MainFrameScrollOrScaleChanged();
+ SetDeviceEmulationTransform(device_emulation_transform);
+ }
}
void WebViewImpl::MainFrameScrollOffsetChanged() {
- dev_tools_emulator_->MainFrameScrollOrScaleChanged();
+ DCHECK(MainFrameImpl());
+ if (dev_tools_emulator_->HasViewportOverride()) {
+ TransformationMatrix device_emulation_transform =
+ dev_tools_emulator_->MainFrameScrollOrScaleChanged();
+ SetDeviceEmulationTransform(device_emulation_transform);
+ }
}
void WebViewImpl::SetBackgroundColorOverride(SkColor color) {
@@ -3161,7 +3175,7 @@ Element* WebViewImpl::FocusedElement() const {
}
HitTestResult WebViewImpl::HitTestResultForRootFramePos(
- const LayoutPoint& pos_in_root_frame) {
+ const PhysicalOffset& pos_in_root_frame) {
auto* main_frame = DynamicTo<LocalFrame>(AsView().page->MainFrame());
if (!main_frame)
return HitTestResult();
@@ -3180,9 +3194,9 @@ WebHitTestResult WebViewImpl::HitTestResultForTap(
if (!main_frame)
return HitTestResult();
- WebGestureEvent tap_event(
- WebInputEvent::kGestureTap, WebInputEvent::kNoModifiers,
- WTF::CurrentTimeTicks(), WebGestureDevice::kTouchscreen);
+ WebGestureEvent tap_event(WebInputEvent::kGestureTap,
+ WebInputEvent::kNoModifiers, base::TimeTicks::Now(),
+ WebGestureDevice::kTouchscreen);
// GestureTap is only ever from a touchscreen.
tap_event.SetPositionInWidget(FloatPoint(IntPoint(tap_point_window_pos)));
tap_event.data.tap.tap_count = 1;
@@ -3252,10 +3266,9 @@ void WebViewImpl::RegisterViewportLayersWithCompositor() {
}
void WebViewImpl::SetRootGraphicsLayer(GraphicsLayer* graphics_layer) {
- if (!layer_tree_view_)
- return;
+ DCHECK(MainFrameImpl());
- // In CAP, setRootLayer is used instead.
+ // In CAP, SetRootLayer() is used instead.
DCHECK(!RuntimeEnabledFeatures::CompositeAfterPaintEnabled());
VisualViewport& visual_viewport = GetPage()->GetVisualViewport();
@@ -3273,29 +3286,26 @@ void WebViewImpl::SetRootGraphicsLayer(GraphicsLayer* graphics_layer) {
root_graphics_layer_ = nullptr;
visual_viewport_container_layer_ = nullptr;
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_main_frame_update_ = layer_tree_view_->DeferMainFrameUpdate();
AsWidget().client->SetRootLayer(nullptr);
AsWidget().client->RegisterViewportLayers(cc::ViewportLayers());
+
+ // When the document in an already-attached main frame is being replaced by
+ // a navigation then SetRootGraphicsLayer(nullptr) will be called. Since we
+ // are navigating, defer BeginMainFrames until the new document is ready for
+ // them.
+ //
+ // TODO(crbug.com/936696): This should not be needed once we always swap
+ // frames when swapping documents.
+ scoped_defer_main_frame_update_ = AsWidget().client->DeferMainFrameUpdate();
}
}
void WebViewImpl::SetRootLayer(scoped_refptr<cc::Layer> layer) {
- if (!layer_tree_view_)
- return;
+ DCHECK(MainFrameImpl());
+ DCHECK(layer);
root_layer_ = std::move(layer);
AsWidget().client->SetRootLayer(root_layer_);
-
- if (!root_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_main_frame_update_ = layer_tree_view_->DeferMainFrameUpdate();
- AsWidget().client->RegisterViewportLayers(cc::ViewportLayers());
- }
}
void WebViewImpl::InvalidateRect(const IntRect& rect) {
@@ -3328,10 +3338,6 @@ void WebViewImpl::SetLayerTreeView(WebLayerTreeView* layer_tree_view,
AsView().page->LayerTreeViewInitialized(*layer_tree_view_, *animation_host_,
nullptr);
- // 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_main_frame_update_ = layer_tree_view_->DeferMainFrameUpdate();
}
void WebViewImpl::ApplyViewportChanges(const ApplyViewportChangesArgs& args) {
@@ -3361,25 +3367,34 @@ void WebViewImpl::ApplyViewportChanges(const ApplyViewportChangesArgs& args) {
UpdateBrowserControlsConstraint(args.browser_controls_constraint);
if (args.scroll_gesture_did_end &&
- RuntimeEnabledFeatures::UpdateHoverFromScrollAtBeginFrameEnabled()) {
+ RuntimeEnabledFeatures::UpdateHoverAtBeginFrameEnabled()) {
MainFrameImpl()->GetFrame()->GetEventHandler().MarkHoverStateDirty();
}
}
-void WebViewImpl::RecordWheelAndTouchScrollingCount(
- bool has_scrolled_by_wheel,
- bool has_scrolled_by_touch) {
+void WebViewImpl::RecordManipulationTypeCounts(cc::ManipulationInfo info) {
if (!MainFrameImpl())
return;
- if (has_scrolled_by_wheel) {
+ if ((info & cc::kManipulationInfoHasScrolledByWheel) ==
+ cc::kManipulationInfoHasScrolledByWheel) {
UseCounter::Count(MainFrameImpl()->GetDocument(),
WebFeature::kScrollByWheel);
}
- if (has_scrolled_by_touch) {
+ if ((info & cc::kManipulationInfoHasScrolledByTouch) ==
+ cc::kManipulationInfoHasScrolledByTouch) {
UseCounter::Count(MainFrameImpl()->GetDocument(),
WebFeature::kScrollByTouch);
}
+ if ((info & cc::kManipulationInfoHasPinchZoomed) ==
+ cc::kManipulationInfoHasPinchZoomed) {
+ UseCounter::Count(MainFrameImpl()->GetDocument(), WebFeature::kPinchZoom);
+ }
+ if ((info & cc::kManipulationInfoHasScrolledByPrecisionTouchPad) ==
+ cc::kManipulationInfoHasScrolledByPrecisionTouchPad) {
+ UseCounter::Count(MainFrameImpl()->GetDocument(),
+ WebFeature::kScrollByPrecisionTouchPad);
+ }
}
Node* WebViewImpl::FindNodeFromScrollableCompositorElementId(
@@ -3433,15 +3448,27 @@ void WebViewImpl::SendScrollEndEventFromImplSide(
}
void WebViewImpl::UpdateDeviceEmulationTransform() {
- if (!visual_viewport_container_layer_)
- return;
+ if (!RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) {
+ // This method may be called before a document lifecycle update runs, and
+ // attaches the |visual_viewport_container_layer_|. In that case, we will
+ // save the new transform and apply it when the container layer is attached.
+ // This is also null when CompositeAfterPaint is enabled.
+ if (visual_viewport_container_layer_) {
+ visual_viewport_container_layer_->SetTransform(
+ device_emulation_transform_);
+ }
+ }
+
+ GetPage()->GetVisualViewport().SetNeedsPaintPropertyUpdate();
- // When the device emulation transform is updated, to avoid incorrect
- // scales and fuzzy raster from the compositor, force all content to
- // pick ideal raster scales.
- visual_viewport_container_layer_->SetTransform(device_emulation_transform_);
- if (layer_tree_view_)
- layer_tree_view_->ForceRecalculateRasterScales();
+ if (MainFrameImpl()) {
+ // When the device emulation transform is updated, to avoid incorrect
+ // scales and fuzzy raster from the compositor, force all content to
+ // pick ideal raster scales.
+ // TODO(wjmaclean): This is only done on the main frame's widget currently,
+ // it should update all local frames.
+ AsWidget().client->ForceRecalculateRasterScales();
+ }
}
PageScheduler* WebViewImpl::Scheduler() const {
@@ -3512,18 +3539,9 @@ int32_t WebViewImpl::AutoplayFlagsForTest() {
return AsView().page->AutoplayFlags();
}
-void WebViewImpl::DeferMainFrameUpdateForTesting() {
- scoped_defer_main_frame_update_ = layer_tree_view_->DeferMainFrameUpdate();
-}
-
-void WebViewImpl::StartDeferringCommits(base::TimeDelta timeout) {
- if (layer_tree_view_)
- layer_tree_view_->StartDeferringCommits(timeout);
-}
-
-void WebViewImpl::StopDeferringCommits(PaintHoldingCommitTrigger trigger) {
- if (layer_tree_view_)
- layer_tree_view_->StopDeferringCommits(trigger);
+void WebViewImpl::StopDeferringMainFrameUpdate() {
+ DCHECK(MainFrameImpl());
+ scoped_defer_main_frame_update_ = nullptr;
}
} // 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 2e7c76cac3b..720ea6fcfb7 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
@@ -93,6 +93,8 @@ class WebSettingsImpl;
class WebViewClient;
class WebWidgetClient;
+struct WebTextAutosizerPageInfo;
+
using PaintHoldingCommitTrigger = cc::PaintHoldingCommitTrigger;
class CORE_EXPORT WebViewImpl final : public WebView,
@@ -160,6 +162,7 @@ class CORE_EXPORT WebViewImpl final : public WebView,
void SetVisualViewportOffset(const WebFloatPoint&) override;
WebFloatPoint VisualViewportOffset() const override;
WebFloatSize VisualViewportSize() const override;
+ void ResizeVisualViewport(const WebSize&) override;
void ResetScrollAndScaleState() override;
void SetIgnoreViewportTagScaleLimits(bool) override;
WebSize ContentsPreferredMinimumSize() override;
@@ -199,6 +202,7 @@ class CORE_EXPORT WebViewImpl final : public WebView,
void ClearBaseBackgroundColorOverride() override;
void SetInsidePortal(bool inside_portal) override;
void PaintContent(cc::PaintCanvas*, const gfx::Rect&) override;
+ void SetTextAutosizePageInfo(const WebTextAutosizerPageInfo&) override;
void DidUpdateFullscreenSize();
@@ -212,7 +216,6 @@ class CORE_EXPORT WebViewImpl final : public WebView,
void SetZoomFactorOverride(float);
void SetCompositorDeviceScaleFactorOverride(float);
- void SetDeviceEmulationTransform(const TransformationMatrix&);
TransformationMatrix GetDeviceEmulationTransform() const;
SkColor BackgroundColor() const;
@@ -395,20 +398,17 @@ class CORE_EXPORT WebViewImpl final : public WebView,
const IntRect& caret_bounds_in_document,
bool zoom_into_legible_scale);
- void StopDeferringMainFrameUpdate() {
- scoped_defer_main_frame_update_.reset();
- }
+ // Allows main frame updates to occur if they were previously blocked. They
+ // are blocked during loading a navigation, to allow Blink to proceed without
+ // being interrupted by useless work until enough progress is made that it
+ // desires composited output to be generated.
+ void StopDeferringMainFrameUpdate();
// This function checks the element ids of ScrollableAreas only and returns
// the equivalent DOM Node if such exists.
Node* FindNodeFromScrollableCompositorElementId(
cc::ElementId element_id) const;
- void DeferMainFrameUpdateForTesting();
-
- void StartDeferringCommits(base::TimeDelta timeout);
- void StopDeferringCommits(PaintHoldingCommitTrigger);
-
private:
FRIEND_TEST_ALL_PREFIXES(WebFrameTest, DivScrollIntoEditableTest);
FRIEND_TEST_ALL_PREFIXES(WebFrameTest,
@@ -426,12 +426,15 @@ class CORE_EXPORT WebViewImpl final : public WebView,
WidgetData& AsWidget() { return as_widget_; }
const WidgetData& AsWidget() const { return as_widget_; }
+ // Called while the main LocalFrame is being detached. The MainFrameImpl() and
+ // WebWidgetClient are still valid until after this method is called.
+ void DidDetachLocalMainFrame();
+
// WebWidget methods:
void SetLayerTreeView(WebLayerTreeView*, cc::AnimationHost*) override;
void Close() override;
WebSize Size() override;
void Resize(const WebSize&) override;
- void ResizeVisualViewport(const WebSize&) override;
void DidEnterFullscreen() override;
void DidExitFullscreen() override;
void SetSuppressFrameRequestsWorkaroundFor704763Only(bool) override;
@@ -454,8 +457,7 @@ class CORE_EXPORT WebViewImpl final : public WebView,
void SetCursorVisibilityState(bool is_visible) override;
void OnFallbackCursorModeToggled(bool is_on) override;
void ApplyViewportChanges(const ApplyViewportChangesArgs& args) override;
- void RecordWheelAndTouchScrollingCount(bool has_scrolled_by_wheel,
- bool has_scrolled_by_touch) override;
+ void RecordManipulationTypeCounts(cc::ManipulationInfo info) override;
void SendOverscrollEventFromImplSide(
const gfx::Vector2dF& overscroll_delta,
cc::ElementId scroll_latched_element_id) override;
@@ -499,13 +501,15 @@ class CORE_EXPORT WebViewImpl final : public WebView,
WebViewImpl* opener);
~WebViewImpl() override;
- HitTestResult HitTestResultForRootFramePos(const LayoutPoint&);
+ HitTestResult HitTestResultForRootFramePos(const PhysicalOffset&);
void ConfigureAutoResizeMode();
void SetIsAcceleratedCompositingActive(bool);
void DoComposite();
void ReallocateRenderer();
+
+ void SetDeviceEmulationTransform(const TransformationMatrix&);
void UpdateDeviceEmulationTransform();
// Helper function: Widens the width of |source| by the specified margins
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 24343bd0019..28c2eaa6b42 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
@@ -510,10 +510,15 @@ TEST_F(WebViewTest, SetBaseBackgroundColorBeforeMainFrame) {
mojo::MakeRequest(&document_interface_broker).PassMessagePipe(), nullptr);
web_frame_client.Bind(frame);
- // We inform the WebView when it has a local main frame attached once the
- // WebFrame it fully set up and the WebWidgetClient is initialized (which is
- // the case by this point).
- web_view->DidAttachLocalMainFrame(&web_widget_client);
+ {
+ // Copy the steps done from WebViewHelper::InitializeWithOpener() to set up
+ // the appropriate pointers!
+ web_view->MainFrameWidget()->SetLayerTreeView(
+ web_widget_client.layer_tree_view(),
+ web_widget_client.animation_host());
+ blink::WebFrameWidget::CreateForMainFrame(&web_widget_client, frame);
+ web_view->DidAttachLocalMainFrame(&web_widget_client);
+ }
// The color should be passed to the compositor.
cc::LayerTreeHost* host = web_widget_client.layer_tree_host();
@@ -591,6 +596,12 @@ TEST_F(WebViewTest, SetBaseBackgroundColorWithColorScheme) {
UpdateAllLifecyclePhases();
EXPECT_EQ(Color::kBlack, frame_view->BaseBackgroundColor());
+ // Don't let dark color-scheme override a transparent background.
+ web_view->SetBaseBackgroundColor(SK_ColorTRANSPARENT);
+ EXPECT_EQ(Color::kTransparent, frame_view->BaseBackgroundColor());
+ web_view->SetBaseBackgroundColor(SK_ColorBLUE);
+ EXPECT_EQ(Color::kBlack, frame_view->BaseBackgroundColor());
+
web_view->SettingsImpl()->SetPreferredColorScheme(
PreferredColorScheme::kLight);
UpdateAllLifecyclePhases();
@@ -1162,7 +1173,7 @@ TEST_F(WebViewTest, FinishComposingTextCursorPositionChange) {
WebRange(), 3, 3);
WebTextInputInfo info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("hello", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("hello", info.value.Utf8());
EXPECT_EQ(3, info.selection_start);
EXPECT_EQ(3, info.selection_end);
EXPECT_EQ(0, info.composition_start);
@@ -1180,7 +1191,7 @@ TEST_F(WebViewTest, FinishComposingTextCursorPositionChange) {
WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans,
WebRange(), 3, 3);
info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("helhellolo", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("helhellolo", info.value.Utf8());
EXPECT_EQ(6, info.selection_start);
EXPECT_EQ(6, info.selection_end);
EXPECT_EQ(3, info.composition_start);
@@ -1213,7 +1224,7 @@ TEST_F(WebViewTest, SetCompositionForNewCaretPositions) {
WebRange(), -5);
WebTextInputInfo info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("helloworld", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("helloworld", info.value.Utf8());
EXPECT_EQ(5, info.selection_start);
EXPECT_EQ(5, info.selection_end);
EXPECT_EQ(-1, info.composition_start);
@@ -1227,7 +1238,7 @@ TEST_F(WebViewTest, SetCompositionForNewCaretPositions) {
WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans,
WebRange(), 0, 0);
info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("helloABCworld", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("helloABCworld", info.value.Utf8());
EXPECT_EQ(5, info.selection_start);
EXPECT_EQ(5, info.selection_end);
EXPECT_EQ(5, info.composition_start);
@@ -1238,7 +1249,7 @@ TEST_F(WebViewTest, SetCompositionForNewCaretPositions) {
WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans,
WebRange(), 3, 3);
info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("helloABCworld", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("helloABCworld", info.value.Utf8());
EXPECT_EQ(8, info.selection_start);
EXPECT_EQ(8, info.selection_end);
EXPECT_EQ(5, info.composition_start);
@@ -1249,7 +1260,7 @@ TEST_F(WebViewTest, SetCompositionForNewCaretPositions) {
WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans,
WebRange(), -2, -2);
info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("helloABCworld", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("helloABCworld", info.value.Utf8());
EXPECT_EQ(3, info.selection_start);
EXPECT_EQ(3, info.selection_end);
EXPECT_EQ(5, info.composition_start);
@@ -1260,7 +1271,7 @@ TEST_F(WebViewTest, SetCompositionForNewCaretPositions) {
WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans,
WebRange(), 5, 5);
info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("helloABCworld", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("helloABCworld", info.value.Utf8());
EXPECT_EQ(10, info.selection_start);
EXPECT_EQ(10, info.selection_end);
EXPECT_EQ(5, info.composition_start);
@@ -1271,7 +1282,7 @@ TEST_F(WebViewTest, SetCompositionForNewCaretPositions) {
WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans,
WebRange(), -5, -5);
info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("helloABCworld", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("helloABCworld", info.value.Utf8());
EXPECT_EQ(0, info.selection_start);
EXPECT_EQ(0, info.selection_end);
EXPECT_EQ(5, info.composition_start);
@@ -1282,7 +1293,7 @@ TEST_F(WebViewTest, SetCompositionForNewCaretPositions) {
WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans,
WebRange(), 8, 8);
info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("helloABCworld", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("helloABCworld", info.value.Utf8());
EXPECT_EQ(13, info.selection_start);
EXPECT_EQ(13, info.selection_end);
EXPECT_EQ(5, info.composition_start);
@@ -1293,7 +1304,7 @@ TEST_F(WebViewTest, SetCompositionForNewCaretPositions) {
WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans,
WebRange(), -100, -100);
info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("helloABCworld", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("helloABCworld", info.value.Utf8());
EXPECT_EQ(0, info.selection_start);
EXPECT_EQ(0, info.selection_end);
EXPECT_EQ(5, info.composition_start);
@@ -1304,7 +1315,7 @@ TEST_F(WebViewTest, SetCompositionForNewCaretPositions) {
WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans,
WebRange(), 100, 100);
info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("helloABCworld", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("helloABCworld", info.value.Utf8());
EXPECT_EQ(13, info.selection_start);
EXPECT_EQ(13, info.selection_end);
EXPECT_EQ(5, info.composition_start);
@@ -1327,7 +1338,7 @@ TEST_F(WebViewTest, SetCompositionWithEmptyText) {
WebRange(), 0);
WebTextInputInfo info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("hello", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("hello", info.value.Utf8());
EXPECT_EQ(5, info.selection_start);
EXPECT_EQ(5, info.selection_end);
EXPECT_EQ(-1, info.composition_start);
@@ -1336,7 +1347,7 @@ TEST_F(WebViewTest, SetCompositionWithEmptyText) {
active_input_method_controller->SetComposition(
WebString::FromUTF8(""), empty_ime_text_spans, WebRange(), 0, 0);
info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("hello", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("hello", info.value.Utf8());
EXPECT_EQ(5, info.selection_start);
EXPECT_EQ(5, info.selection_end);
EXPECT_EQ(-1, info.composition_start);
@@ -1345,7 +1356,7 @@ TEST_F(WebViewTest, SetCompositionWithEmptyText) {
active_input_method_controller->SetComposition(
WebString::FromUTF8(""), empty_ime_text_spans, WebRange(), -2, -2);
info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("hello", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("hello", info.value.Utf8());
EXPECT_EQ(3, info.selection_start);
EXPECT_EQ(3, info.selection_end);
EXPECT_EQ(-1, info.composition_start);
@@ -1368,7 +1379,7 @@ TEST_F(WebViewTest, CommitTextForNewCaretPositions) {
active_input_method_controller->CommitText("ab", empty_ime_text_spans,
WebRange(), -2);
WebTextInputInfo info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("ab", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("ab", info.value.Utf8());
EXPECT_EQ(0, info.selection_start);
EXPECT_EQ(0, info.selection_end);
EXPECT_EQ(-1, info.composition_start);
@@ -1378,7 +1389,7 @@ TEST_F(WebViewTest, CommitTextForNewCaretPositions) {
active_input_method_controller->CommitText("c", empty_ime_text_spans,
WebRange(), 1);
info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("cab", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("cab", info.value.Utf8());
EXPECT_EQ(2, info.selection_start);
EXPECT_EQ(2, info.selection_end);
EXPECT_EQ(-1, info.composition_start);
@@ -1388,7 +1399,7 @@ TEST_F(WebViewTest, CommitTextForNewCaretPositions) {
active_input_method_controller->CommitText("def", empty_ime_text_spans,
WebRange(), -5);
info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("cadefb", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("cadefb", info.value.Utf8());
EXPECT_EQ(0, info.selection_start);
EXPECT_EQ(0, info.selection_end);
EXPECT_EQ(-1, info.composition_start);
@@ -1398,7 +1409,7 @@ TEST_F(WebViewTest, CommitTextForNewCaretPositions) {
active_input_method_controller->CommitText("g", empty_ime_text_spans,
WebRange(), 6);
info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("gcadefb", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("gcadefb", info.value.Utf8());
EXPECT_EQ(7, info.selection_start);
EXPECT_EQ(7, info.selection_end);
EXPECT_EQ(-1, info.composition_start);
@@ -1408,7 +1419,7 @@ TEST_F(WebViewTest, CommitTextForNewCaretPositions) {
active_input_method_controller->CommitText("hi", empty_ime_text_spans,
WebRange(), -100);
info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("gcadefbhi", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("gcadefbhi", info.value.Utf8());
EXPECT_EQ(0, info.selection_start);
EXPECT_EQ(0, info.selection_end);
EXPECT_EQ(-1, info.composition_start);
@@ -1418,7 +1429,7 @@ TEST_F(WebViewTest, CommitTextForNewCaretPositions) {
active_input_method_controller->CommitText("jk", empty_ime_text_spans,
WebRange(), 100);
info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("jkgcadefbhi", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("jkgcadefbhi", info.value.Utf8());
EXPECT_EQ(11, info.selection_start);
EXPECT_EQ(11, info.selection_end);
EXPECT_EQ(-1, info.composition_start);
@@ -1439,7 +1450,7 @@ TEST_F(WebViewTest, CommitTextWhileComposing) {
active_input_method_controller->SetComposition(
WebString::FromUTF8("abc"), empty_ime_text_spans, WebRange(), 0, 0);
WebTextInputInfo info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("abc", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("abc", info.value.Utf8());
EXPECT_EQ(0, info.selection_start);
EXPECT_EQ(0, info.selection_end);
EXPECT_EQ(0, info.composition_start);
@@ -1450,7 +1461,7 @@ TEST_F(WebViewTest, CommitTextWhileComposing) {
active_input_method_controller->CommitText("hello", empty_ime_text_spans,
WebRange(), -2);
info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("hello", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("hello", info.value.Utf8());
EXPECT_EQ(3, info.selection_start);
EXPECT_EQ(3, info.selection_end);
EXPECT_EQ(-1, info.composition_start);
@@ -1459,7 +1470,7 @@ TEST_F(WebViewTest, CommitTextWhileComposing) {
active_input_method_controller->SetComposition(
WebString::FromUTF8("abc"), empty_ime_text_spans, WebRange(), 0, 0);
info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("helabclo", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("helabclo", info.value.Utf8());
EXPECT_EQ(3, info.selection_start);
EXPECT_EQ(3, info.selection_end);
EXPECT_EQ(3, info.composition_start);
@@ -1469,7 +1480,7 @@ TEST_F(WebViewTest, CommitTextWhileComposing) {
active_input_method_controller->CommitText("", empty_ime_text_spans,
WebRange(), 2);
info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("hello", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("hello", info.value.Utf8());
EXPECT_EQ(5, info.selection_start);
EXPECT_EQ(5, info.selection_end);
EXPECT_EQ(-1, info.composition_start);
@@ -1479,7 +1490,7 @@ TEST_F(WebViewTest, CommitTextWhileComposing) {
active_input_method_controller->CommitText("world", empty_ime_text_spans,
WebRange(), -5);
info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("helloworld", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("helloworld", info.value.Utf8());
EXPECT_EQ(5, info.selection_start);
EXPECT_EQ(5, info.selection_end);
EXPECT_EQ(-1, info.composition_start);
@@ -1489,7 +1500,7 @@ TEST_F(WebViewTest, CommitTextWhileComposing) {
active_input_method_controller->CommitText("", empty_ime_text_spans,
WebRange(), 5);
info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("helloworld", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("helloworld", info.value.Utf8());
EXPECT_EQ(10, info.selection_start);
EXPECT_EQ(10, info.selection_end);
EXPECT_EQ(-1, info.composition_start);
@@ -1520,7 +1531,7 @@ TEST_F(WebViewTest, FinishCompositionDoesNotRevealSelection) {
EXPECT_LT(0, offset_height);
WebTextInputInfo info = frame->GetInputMethodController()->TextInputInfo();
- EXPECT_EQ("hello", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("hello", info.value.Utf8());
// Verify that the input field is not scrolled back into the viewport.
frame->FrameWidget()
@@ -1545,8 +1556,7 @@ TEST_F(WebViewTest, InsertNewLinePlacementAfterFinishComposingText) {
frame->SetCompositionFromExistingText(8, 12, empty_ime_text_spans);
WebTextInputInfo info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("0123456789abcdefghijklmnopqrstuvwxyz",
- std::string(info.value.Utf8().data()));
+ EXPECT_EQ("0123456789abcdefghijklmnopqrstuvwxyz", info.value.Utf8());
EXPECT_EQ(4, info.selection_start);
EXPECT_EQ(4, info.selection_end);
EXPECT_EQ(8, info.composition_start);
@@ -1569,8 +1579,7 @@ TEST_F(WebViewTest, InsertNewLinePlacementAfterFinishComposingText) {
EXPECT_EQ(5, info.selection_end);
EXPECT_EQ(-1, info.composition_start);
EXPECT_EQ(-1, info.composition_end);
- EXPECT_EQ("0123\n456789abcdefghijklmnopqrstuvwxyz",
- std::string(info.value.Utf8().data()));
+ EXPECT_EQ("0123\n456789abcdefghijklmnopqrstuvwxyz", info.value.Utf8());
}
TEST_F(WebViewTest, ExtendSelectionAndDelete) {
@@ -1584,12 +1593,12 @@ TEST_F(WebViewTest, ExtendSelectionAndDelete) {
WebInputMethodController* active_input_method_controller =
frame->GetInputMethodController();
WebTextInputInfo info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("01234ijklmnopqrstuvwxyz", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("01234ijklmnopqrstuvwxyz", info.value.Utf8());
EXPECT_EQ(5, info.selection_start);
EXPECT_EQ(5, info.selection_end);
frame->ExtendSelectionAndDelete(10, 0);
info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("ijklmnopqrstuvwxyz", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("ijklmnopqrstuvwxyz", info.value.Utf8());
}
TEST_F(WebViewTest, DeleteSurroundingText) {
@@ -1604,33 +1613,33 @@ TEST_F(WebViewTest, DeleteSurroundingText) {
frame->SetEditableSelectionOffsets(10, 10);
frame->DeleteSurroundingText(5, 8);
WebTextInputInfo info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("01234ijklmnopqrstuvwxyz", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("01234ijklmnopqrstuvwxyz", info.value.Utf8());
EXPECT_EQ(5, info.selection_start);
EXPECT_EQ(5, info.selection_end);
frame->SetEditableSelectionOffsets(5, 10);
frame->DeleteSurroundingText(3, 5);
info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("01ijklmstuvwxyz", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("01ijklmstuvwxyz", info.value.Utf8());
EXPECT_EQ(2, info.selection_start);
EXPECT_EQ(7, info.selection_end);
frame->SetEditableSelectionOffsets(5, 5);
frame->DeleteSurroundingText(10, 0);
info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("lmstuvwxyz", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("lmstuvwxyz", info.value.Utf8());
EXPECT_EQ(0, info.selection_start);
EXPECT_EQ(0, info.selection_end);
frame->DeleteSurroundingText(0, 20);
info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("", info.value.Utf8());
EXPECT_EQ(0, info.selection_start);
EXPECT_EQ(0, info.selection_end);
frame->DeleteSurroundingText(10, 10);
info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("", info.value.Utf8());
EXPECT_EQ(0, info.selection_start);
EXPECT_EQ(0, info.selection_end);
}
@@ -1680,14 +1689,12 @@ TEST_F(WebViewTest, SetCompositionFromExistingTextInTextArea) {
WebString::FromUTF8(new_line_text.c_str()), empty_ime_text_spans,
WebRange(), 0);
WebTextInputInfo info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("0123456789abcdefghijklmnopq\nrstuvwxyz",
- std::string(info.value.Utf8().data()));
+ EXPECT_EQ("0123456789abcdefghijklmnopq\nrstuvwxyz", info.value.Utf8());
frame->SetEditableSelectionOffsets(31, 31);
frame->SetCompositionFromExistingText(30, 34, ime_text_spans);
info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("0123456789abcdefghijklmnopq\nrstuvwxyz",
- std::string(info.value.Utf8().data()));
+ EXPECT_EQ("0123456789abcdefghijklmnopq\nrstuvwxyz", info.value.Utf8());
EXPECT_EQ(31, info.selection_start);
EXPECT_EQ(31, info.selection_end);
EXPECT_EQ(30, info.composition_start);
@@ -1698,8 +1705,7 @@ TEST_F(WebViewTest, SetCompositionFromExistingTextInTextArea) {
WebString::FromUTF8(composition_text.c_str()), empty_ime_text_spans,
WebRange(), 0);
info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("0123456789abcdefghijklmnopq\nrsyoloxyz",
- std::string(info.value.Utf8().data()));
+ EXPECT_EQ("0123456789abcdefghijklmnopq\nrsyoloxyz", info.value.Utf8());
EXPECT_EQ(34, info.selection_start);
EXPECT_EQ(34, info.selection_end);
EXPECT_EQ(-1, info.composition_start);
@@ -1743,7 +1749,7 @@ TEST_F(WebViewTest, SetEditableSelectionOffsetsKeepsComposition) {
empty_ime_text_spans, WebRange(), 5, 5);
WebTextInputInfo info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("hello world", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("hello world", info.value.Utf8());
EXPECT_EQ(11, info.selection_start);
EXPECT_EQ(11, info.selection_end);
EXPECT_EQ(6, info.composition_start);
@@ -1752,7 +1758,7 @@ TEST_F(WebViewTest, SetEditableSelectionOffsetsKeepsComposition) {
WebLocalFrameImpl* frame = web_view->MainFrameImpl();
frame->SetEditableSelectionOffsets(6, 6);
info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("hello world", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("hello world", info.value.Utf8());
EXPECT_EQ(6, info.selection_start);
EXPECT_EQ(6, info.selection_end);
EXPECT_EQ(6, info.composition_start);
@@ -1760,7 +1766,7 @@ TEST_F(WebViewTest, SetEditableSelectionOffsetsKeepsComposition) {
frame->SetEditableSelectionOffsets(8, 8);
info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("hello world", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("hello world", info.value.Utf8());
EXPECT_EQ(8, info.selection_start);
EXPECT_EQ(8, info.selection_end);
EXPECT_EQ(6, info.composition_start);
@@ -1768,7 +1774,7 @@ TEST_F(WebViewTest, SetEditableSelectionOffsetsKeepsComposition) {
frame->SetEditableSelectionOffsets(11, 11);
info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("hello world", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("hello world", info.value.Utf8());
EXPECT_EQ(11, info.selection_start);
EXPECT_EQ(11, info.selection_end);
EXPECT_EQ(6, info.composition_start);
@@ -1776,7 +1782,7 @@ TEST_F(WebViewTest, SetEditableSelectionOffsetsKeepsComposition) {
frame->SetEditableSelectionOffsets(6, 11);
info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("hello world", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("hello world", info.value.Utf8());
EXPECT_EQ(6, info.selection_start);
EXPECT_EQ(11, info.selection_end);
EXPECT_EQ(6, info.composition_start);
@@ -1784,7 +1790,7 @@ TEST_F(WebViewTest, SetEditableSelectionOffsetsKeepsComposition) {
frame->SetEditableSelectionOffsets(2, 2);
info = active_input_method_controller->TextInputInfo();
- EXPECT_EQ("hello world", std::string(info.value.Utf8().data()));
+ EXPECT_EQ("hello world", info.value.Utf8());
EXPECT_EQ(2, info.selection_start);
EXPECT_EQ(2, info.selection_end);
// Composition range should be reset by browser process or keyboard apps.
@@ -2938,9 +2944,9 @@ TEST_F(WebViewTest, LongPressSelection) {
EXPECT_TRUE(
TapElementById(WebInputEvent::kGestureLongPress, onselectstartfalse));
- EXPECT_EQ("", std::string(frame->SelectionAsText().Utf8().data()));
+ EXPECT_EQ("", frame->SelectionAsText().Utf8());
EXPECT_TRUE(TapElementById(WebInputEvent::kGestureLongPress, target));
- EXPECT_EQ("testword", std::string(frame->SelectionAsText().Utf8().data()));
+ EXPECT_EQ("testword", frame->SelectionAsText().Utf8());
}
TEST_F(WebViewTest, FinishComposingTextDoesNotDismissHandles) {
@@ -2962,13 +2968,12 @@ TEST_F(WebViewTest, FinishComposingTextDoesNotDismissHandles) {
EXPECT_TRUE(active_input_method_controller->SetComposition(
"12345", empty_ime_text_spans, WebRange(), 8, 13));
EXPECT_TRUE(frame->GetFrame()->GetInputMethodController().HasComposition());
- EXPECT_EQ("", std::string(frame->SelectionAsText().Utf8().data()));
+ EXPECT_EQ("", frame->SelectionAsText().Utf8());
EXPECT_FALSE(frame->GetFrame()->Selection().IsHandleVisible());
EXPECT_TRUE(frame->GetFrame()->GetInputMethodController().HasComposition());
EXPECT_TRUE(TapElementById(WebInputEvent::kGestureLongPress, target));
- EXPECT_EQ("testword12345",
- std::string(frame->SelectionAsText().Utf8().data()));
+ EXPECT_EQ("testword12345", frame->SelectionAsText().Utf8());
EXPECT_TRUE(frame->GetFrame()->Selection().IsHandleVisible());
EXPECT_TRUE(frame->GetFrame()->GetInputMethodController().HasComposition());
@@ -3105,7 +3110,7 @@ TEST_F(WebViewTest, SelectionOnReadOnlyInput) {
std::string test_word = "This text should be selected.";
WebLocalFrameImpl* frame = web_view->MainFrameImpl();
- EXPECT_EQ(test_word, std::string(frame->SelectionAsText().Utf8().data()));
+ EXPECT_EQ(test_word, frame->SelectionAsText().Utf8());
WebRange range = web_view->MainFrameImpl()
->GetInputMethodController()
@@ -3235,10 +3240,10 @@ class MiddleClickAutoscrollWebWidgetClient
last_cursor_type_ = cursor.type;
}
- int GetLastCursorType() const { return last_cursor_type_; }
+ ui::CursorType GetLastCursorType() const { return last_cursor_type_; }
private:
- int last_cursor_type_ = 0;
+ ui::CursorType last_cursor_type_ = ui::CursorType::kPointer;
};
TEST_F(WebViewTest, MiddleClickAutoscrollCursor) {
@@ -3246,48 +3251,68 @@ TEST_F(WebViewTest, MiddleClickAutoscrollCursor) {
ScopedMiddleClickAutoscrollForTest middle_click_autoscroll(true);
RegisterMockedHttpURLLoad("content-width-1000.html");
- WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(
- base_url_ + "content-width-1000.html", nullptr, nullptr, &client);
- web_view->MainFrameWidget()->Resize(WebSize(100, 100));
- UpdateAllLifecyclePhases();
- RunPendingTasks();
+ // We will be changing the size of the page to test each of the panning
+ // cursor variations. For reference, content-width-1000.html is 1000px wide
+ // and 2000px tall.
+ // 1. 100 x 100 - The page will be scrollable in both x and y directions, so
+ // we expect to see the cursor with arrows in all four directions.
+ // 2. 1010 x 100 - The page will be scrollable in the y direction, but not x,
+ // so we expect to see the cursor with only the vertical arrows.
+ // 3. 100 x 2010 - The page will be scrollable in the x direction, but not y,
+ // so we expect to see the cursor with only the horizontal arrows.
+ struct CursorTests {
+ int resize_width;
+ int resize_height;
+ ui::CursorType expected_cursor;
+ } cursor_tests[] = {{100, 100, MiddlePanningCursor().GetType()},
+ {1010, 100, MiddlePanningVerticalCursor().GetType()},
+ {100, 2010, MiddlePanningHorizontalCursor().GetType()}};
+
+ for (const CursorTests current_test : cursor_tests) {
+ WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(
+ base_url_ + "content-width-1000.html", nullptr, nullptr, &client);
+ web_view->MainFrameWidget()->Resize(
+ WebSize(current_test.resize_width, current_test.resize_height));
+ UpdateAllLifecyclePhases();
+ RunPendingTasks();
- WebMouseEvent mouse_event(WebInputEvent::kMouseDown,
- WebInputEvent::kNoModifiers,
- WebInputEvent::GetStaticTimeStampForTests());
- mouse_event.button = WebMouseEvent::Button::kMiddle;
- mouse_event.SetPositionInWidget(1, 1);
- mouse_event.click_count = 1;
+ WebMouseEvent mouse_event(WebInputEvent::kMouseDown,
+ WebInputEvent::kNoModifiers,
+ WebInputEvent::GetStaticTimeStampForTests());
+ mouse_event.button = WebMouseEvent::Button::kMiddle;
+ mouse_event.SetPositionInWidget(1, 1);
+ mouse_event.click_count = 1;
- // Start middle-click autoscroll.
- web_view->MainFrameWidget()->HandleInputEvent(
- WebCoalescedInputEvent(mouse_event));
- mouse_event.SetType(WebInputEvent::kMouseUp);
- web_view->MainFrameWidget()->HandleInputEvent(
- WebCoalescedInputEvent(mouse_event));
+ // Start middle-click autoscroll.
+ web_view->MainFrameWidget()->HandleInputEvent(
+ WebCoalescedInputEvent(mouse_event));
+ mouse_event.SetType(WebInputEvent::kMouseUp);
+ web_view->MainFrameWidget()->HandleInputEvent(
+ WebCoalescedInputEvent(mouse_event));
- EXPECT_EQ(MiddlePanningCursor().GetType(), client.GetLastCursorType());
+ EXPECT_EQ(current_test.expected_cursor, client.GetLastCursorType());
- LocalFrame* local_frame =
- To<WebLocalFrameImpl>(web_view->MainFrame())->GetFrame();
+ LocalFrame* local_frame =
+ To<WebLocalFrameImpl>(web_view->MainFrame())->GetFrame();
- // Even if a plugin tries to change the cursor type, that should be ignored
- // during middle-click autoscroll.
- web_view->GetChromeClient().SetCursorForPlugin(WebCursorInfo(PointerCursor()),
- local_frame);
- EXPECT_EQ(MiddlePanningCursor().GetType(), client.GetLastCursorType());
+ // Even if a plugin tries to change the cursor type, that should be ignored
+ // during middle-click autoscroll.
+ web_view->GetChromeClient().SetCursorForPlugin(
+ WebCursorInfo(PointerCursor()), local_frame);
+ EXPECT_EQ(current_test.expected_cursor, client.GetLastCursorType());
- // End middle-click autoscroll.
- mouse_event.SetType(WebInputEvent::kMouseDown);
- web_view->MainFrameWidget()->HandleInputEvent(
- WebCoalescedInputEvent(mouse_event));
- mouse_event.SetType(WebInputEvent::kMouseUp);
- web_view->MainFrameWidget()->HandleInputEvent(
- WebCoalescedInputEvent(mouse_event));
+ // End middle-click autoscroll.
+ mouse_event.SetType(WebInputEvent::kMouseDown);
+ web_view->MainFrameWidget()->HandleInputEvent(
+ WebCoalescedInputEvent(mouse_event));
+ mouse_event.SetType(WebInputEvent::kMouseUp);
+ web_view->MainFrameWidget()->HandleInputEvent(
+ WebCoalescedInputEvent(mouse_event));
- web_view->GetChromeClient().SetCursorForPlugin(WebCursorInfo(IBeamCursor()),
- local_frame);
- EXPECT_EQ(IBeamCursor().GetType(), client.GetLastCursorType());
+ web_view->GetChromeClient().SetCursorForPlugin(WebCursorInfo(IBeamCursor()),
+ local_frame);
+ EXPECT_EQ(IBeamCursor().GetType(), client.GetLastCursorType());
+ }
// Explicitly reset to break dependency on locally scoped client.
web_view_helper_.Reset();
@@ -3339,11 +3364,13 @@ class MockAutofillClient : public WebAutofillClient {
}
void UserGestureObserved() override { ++user_gesture_notifications_count_; }
- bool HasFillData(const WebFormControlElement&) const override {
- return has_fill_data_;
+ bool TryToShowTouchToFill(const WebFormControlElement&) override {
+ return can_show_touch_to_fill_;
}
- void SetFillData(bool has_fill_data) { has_fill_data_ = has_fill_data; }
+ void SetCanShowTouchToFill(bool can_show_touch_to_fill) {
+ can_show_touch_to_fill_ = can_show_touch_to_fill;
+ }
void ClearChangeCounts() { text_changes_ = 0; }
@@ -3357,7 +3384,7 @@ class MockAutofillClient : public WebAutofillClient {
int text_changes_ = 0;
int text_changes_from_user_gesture_ = 0;
int user_gesture_notifications_count_ = 0;
- bool has_fill_data_ = false;
+ bool can_show_touch_to_fill_ = false;
};
TEST_F(WebViewTest, LosingFocusDoesNotTriggerAutofillTextChange) {
@@ -3460,8 +3487,8 @@ TEST_F(WebViewTest, FinishComposingTextDoesntTriggerAutofillTextChange) {
web_view->SetInitialFocus(false);
WebDocument document = web_view->MainFrameImpl()->GetDocument();
- HTMLFormControlElement* form =
- ToHTMLFormControlElement(document.GetElementById("sample"));
+ auto* form = To<HTMLFormControlElement>(
+ static_cast<Element*>(document.GetElementById("sample")));
WebInputMethodController* active_input_method_controller =
frame->FrameWidget()->GetActiveWebInputMethodController();
@@ -3507,8 +3534,7 @@ TEST_F(WebViewTest,
frame->SetCompositionFromExistingText(8, 12, empty_ime_text_spans);
WebTextInputInfo info = frame->GetInputMethodController()->TextInputInfo();
- EXPECT_EQ("0123456789abcdefghijklmnopqrstuvwxyz",
- std::string(info.value.Utf8().data()));
+ EXPECT_EQ("0123456789abcdefghijklmnopqrstuvwxyz", info.value.Utf8());
EXPECT_EQ(8, info.composition_start);
EXPECT_EQ(12, info.composition_end);
@@ -3866,7 +3892,7 @@ class TouchEventHandlerWebWidgetClient
: public frame_test_helpers::TestWebWidgetClient {
public:
// WebWidgetClient methods
- void HasTouchEventHandlers(bool state) override {
+ void SetHasTouchEventHandlers(bool state) override {
// Only count the times the state changes.
if (state != has_touch_event_handler_)
has_touch_event_handler_count_[state]++;
@@ -3888,11 +3914,11 @@ class TouchEventHandlerWebWidgetClient
bool has_touch_event_handler_;
};
-// This test verifies that WebWidgetClient::hasTouchEventHandlers is called
+// This test verifies that WebWidgetClient::SetHasTouchEventHandlers 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 web_tests/fast/events/event-handler-count.html.
-TEST_F(WebViewTest, HasTouchEventHandlers) {
+TEST_F(WebViewTest, SetHasTouchEventHandlers) {
TouchEventHandlerWebWidgetClient client;
std::string url = RegisterMockedHttpURLLoad("has_touch_event_handlers.html");
WebViewImpl* web_view_impl =
@@ -4127,7 +4153,7 @@ TEST_F(WebViewTest, FirstUserGestureObservedKeyEvent) {
web_view->MainFrameWidget()->HandleInputEvent(
WebCoalescedInputEvent(key_event));
- EXPECT_EQ(2, client.GetUserGestureNotificationsCount());
+ EXPECT_EQ(1, client.GetUserGestureNotificationsCount());
frame->SetAutofillClient(nullptr);
}
@@ -4335,8 +4361,8 @@ class MojoTestHelper {
MojoTestHelper(const String& test_file,
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_ =
+ web_view_helper.InitializeAndLoad(test_file.Utf8(), &web_frame_client_);
}
~MojoTestHelper() {
@@ -4351,7 +4377,7 @@ class MojoTestHelper {
// Set up our Mock Mojo API.
test_api_.reset(new service_manager::InterfaceProvider::TestApi(
web_frame_client_.GetInterfaceProvider()));
- test_api_->SetBinderForName(WebString(name).Utf8(), callback);
+ test_api_->SetBinderForName(name.Utf8(), callback);
}
WebViewImpl* WebView() const { return web_view_; }
@@ -4660,21 +4686,21 @@ TEST_F(WebViewTest, PasswordFieldCanBeAutofilled) {
RegisterMockedHttpURLLoad("input_field_password.html");
// Pretend client has fill data for all fields it's queried.
MockAutofillClient client;
- client.SetFillData(true);
+ client.SetCanShowTouchToFill(true);
WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(
base_url_ + "input_field_password.html");
WebLocalFrameImpl* frame = web_view->MainFrameImpl();
frame->SetAutofillClient(&client);
// No field is focused.
- EXPECT_FALSE(frame->CanFocusedFieldBeAutofilled());
+ EXPECT_FALSE(frame->TryToShowTouchToFillForFocusedElement());
// Focusing a field should result in treating it autofillable.
web_view->SetInitialFocus(false);
- EXPECT_TRUE(frame->CanFocusedFieldBeAutofilled());
+ EXPECT_TRUE(frame->TryToShowTouchToFillForFocusedElement());
// Pretend that |client| no longer has autofill data available.
- client.SetFillData(false);
- EXPECT_FALSE(frame->CanFocusedFieldBeAutofilled());
+ client.SetCanShowTouchToFill(false);
+ EXPECT_FALSE(frame->TryToShowTouchToFillForFocusedElement());
frame->SetAutofillClient(nullptr);
}
@@ -4828,9 +4854,10 @@ TEST_F(WebViewTest, ForceAndResetViewport) {
// Override applies transform, sets visible rect, and disables
// visual viewport clipping.
- dev_tools_emulator->ForceViewport(WebFloatPoint(50, 55), 2.f);
+ TransformationMatrix matrix =
+ dev_tools_emulator->ForceViewportForTesting(WebFloatPoint(50, 55), 2.f);
expected_matrix.MakeIdentity().Scale(2.f).Translate(-50, -55);
- EXPECT_EQ(expected_matrix, web_view_impl->GetDeviceEmulationTransform());
+ EXPECT_EQ(expected_matrix, matrix);
{
IntRect visible_rect(1, 2, 3, 4);
dev_tools_emulator->OverrideVisibleRect(IntSize(100, 150), &visible_rect);
@@ -4839,9 +4866,10 @@ TEST_F(WebViewTest, ForceAndResetViewport) {
EXPECT_FALSE(visual_viewport->ContainerLayer()->MasksToBounds());
// Setting new override discards previous one.
- dev_tools_emulator->ForceViewport(WebFloatPoint(5.4f, 10.5f), 1.5f);
+ matrix = dev_tools_emulator->ForceViewportForTesting(
+ WebFloatPoint(5.4f, 10.5f), 1.5f);
expected_matrix.MakeIdentity().Scale(1.5f).Translate(-5.4f, -10.5f);
- EXPECT_EQ(expected_matrix, web_view_impl->GetDeviceEmulationTransform());
+ EXPECT_EQ(expected_matrix, matrix);
{
IntRect visible_rect(1, 2, 3, 4);
dev_tools_emulator->OverrideVisibleRect(IntSize(100, 150), &visible_rect);
@@ -4851,9 +4879,9 @@ TEST_F(WebViewTest, ForceAndResetViewport) {
// Clearing override restores original transform, visible rect and
// visual viewport clipping.
- dev_tools_emulator->ResetViewport();
+ matrix = dev_tools_emulator->ResetViewportForTesting();
expected_matrix.MakeIdentity();
- EXPECT_EQ(expected_matrix, web_view_impl->GetDeviceEmulationTransform());
+ EXPECT_EQ(expected_matrix, matrix);
{
IntRect visible_rect(1, 2, 3, 4);
dev_tools_emulator->OverrideVisibleRect(IntSize(), &visible_rect);
@@ -4879,8 +4907,9 @@ TEST_F(WebViewTest, ViewportOverrideIntegratesDeviceMetricsOffsetAndScale) {
EXPECT_EQ(expected_matrix, web_view_impl->GetDeviceEmulationTransform());
// Device metrics offset and scale are applied before viewport override.
- web_view_impl->GetDevToolsEmulator()->ForceViewport(WebFloatPoint(5, 10),
- 1.5f);
+ emulation_params.viewport_offset = WebFloatPoint(5, 10);
+ emulation_params.viewport_scale = 1.5f;
+ web_view_impl->EnableDeviceEmulation(emulation_params);
expected_matrix.MakeIdentity()
.Scale(1.5f)
.Translate(-5, -10)
@@ -4907,7 +4936,11 @@ TEST_F(WebViewTest, ViewportOverrideAdaptsToScaleAndScroll) {
web_view_impl->SetPageScaleFactor(1.5f);
frame_view->LayoutViewport()->SetScrollOffset(
ScrollOffset(100, 150), kProgrammaticScroll, kScrollBehaviorInstant);
- dev_tools_emulator->ForceViewport(WebFloatPoint(50, 55), 2.f);
+
+ WebDeviceEmulationParams emulation_params;
+ emulation_params.viewport_offset = WebFloatPoint(50, 55);
+ emulation_params.viewport_scale = 2.f;
+ web_view_impl->EnableDeviceEmulation(emulation_params);
expected_matrix.MakeIdentity()
.Scale(2.f)
.Translate(-50, -55)
@@ -5219,7 +5252,7 @@ TEST_F(WebViewTest, FirstInputDelayReported) {
ASSERT_NE(nullptr, document);
base::TimeTicks start_time = test_task_runner_->NowTicks();
- test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(70));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(70));
InteractiveDetector* interactive_detector =
GetTestInteractiveDetector(*document);
@@ -5232,7 +5265,7 @@ TEST_F(WebViewTest, FirstInputDelayReported) {
key_event1.dom_key = ui::DomKey::FromCharacter(' ');
key_event1.windows_key_code = VKEY_SPACE;
key_event1.SetTimeStamp(test_task_runner_->NowTicks());
- test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(50));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
web_view->MainFrameWidget()->HandleInputEvent(
WebCoalescedInputEvent(key_event1));
@@ -5247,7 +5280,7 @@ TEST_F(WebViewTest, FirstInputDelayReported) {
WebInputEvent::GetStaticTimeStampForTests());
key_event2.dom_key = ui::DomKey::FromCharacter(' ');
key_event2.windows_key_code = VKEY_SPACE;
- test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(60));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(60));
key_event2.SetTimeStamp(test_task_runner_->NowTicks());
web_view->MainFrameWidget()->HandleInputEvent(
WebCoalescedInputEvent(key_event2));
@@ -5271,7 +5304,7 @@ TEST_F(WebViewTest, LongestInputDelayReported) {
Document* document = main_frame->GetDocument();
ASSERT_NE(nullptr, document);
- test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(70));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(70));
InteractiveDetector* interactive_detector =
GetTestInteractiveDetector(*document);
@@ -5284,11 +5317,11 @@ TEST_F(WebViewTest, LongestInputDelayReported) {
key_event1.dom_key = ui::DomKey::FromCharacter(' ');
key_event1.windows_key_code = VKEY_SPACE;
key_event1.SetTimeStamp(test_task_runner_->NowTicks());
- test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(50));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
web_view->MainFrameWidget()->HandleInputEvent(
WebCoalescedInputEvent(key_event1));
- TimeTicks longest_input_timestamp = test_task_runner_->NowTicks();
+ base::TimeTicks longest_input_timestamp = test_task_runner_->NowTicks();
WebKeyboardEvent key_event2(WebInputEvent::kRawKeyDown,
WebInputEvent::kNoModifiers,
@@ -5296,7 +5329,7 @@ TEST_F(WebViewTest, LongestInputDelayReported) {
key_event2.dom_key = ui::DomKey::FromCharacter(' ');
key_event2.windows_key_code = VKEY_SPACE;
key_event2.SetTimeStamp(longest_input_timestamp);
- test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(100));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(100));
web_view->MainFrameWidget()->HandleInputEvent(
WebCoalescedInputEvent(key_event2));
@@ -5306,7 +5339,7 @@ TEST_F(WebViewTest, LongestInputDelayReported) {
key_event3.dom_key = ui::DomKey::FromCharacter(' ');
key_event3.windows_key_code = VKEY_SPACE;
key_event3.SetTimeStamp(test_task_runner_->NowTicks());
- test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(70));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(70));
web_view->MainFrameWidget()->HandleInputEvent(
WebCoalescedInputEvent(key_event3));
@@ -5318,7 +5351,7 @@ TEST_F(WebViewTest, LongestInputDelayReported) {
}
TEST_F(WebViewTest, InputDelayReported) {
- test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(50));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
WebViewImpl* web_view = web_view_helper_.Initialize();
@@ -5333,7 +5366,7 @@ TEST_F(WebViewTest, InputDelayReported) {
ASSERT_NE(nullptr, document);
GetTestInteractiveDetector(*document);
- test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(70));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(70));
HistogramTester histogram_tester;
WebKeyboardEvent key_event1(WebInputEvent::kRawKeyDown,
@@ -5342,7 +5375,7 @@ TEST_F(WebViewTest, InputDelayReported) {
key_event1.dom_key = ui::DomKey::FromCharacter(' ');
key_event1.windows_key_code = VKEY_SPACE;
key_event1.SetTimeStamp(test_task_runner_->NowTicks());
- test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(50));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
web_view->MainFrameWidget()->HandleInputEvent(
WebCoalescedInputEvent(key_event1));
@@ -5352,7 +5385,7 @@ TEST_F(WebViewTest, InputDelayReported) {
key_event2.dom_key = ui::DomKey::FromCharacter(' ');
key_event2.windows_key_code = VKEY_SPACE;
key_event2.SetTimeStamp(test_task_runner_->NowTicks());
- test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(50));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
web_view->MainFrameWidget()->HandleInputEvent(
WebCoalescedInputEvent(key_event2));
@@ -5362,7 +5395,7 @@ TEST_F(WebViewTest, InputDelayReported) {
key_event3.dom_key = ui::DomKey::FromCharacter(' ');
key_event3.windows_key_code = VKEY_SPACE;
key_event3.SetTimeStamp(test_task_runner_->NowTicks());
- test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(70));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(70));
web_view->MainFrameWidget()->HandleInputEvent(
WebCoalescedInputEvent(key_event3));
@@ -5397,7 +5430,7 @@ TEST_F(WebViewTest, LongestInputDelayPageBackgroundedDuringQueuing) {
Document* document = main_frame->GetDocument();
ASSERT_NE(nullptr, document);
- test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(70));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(70));
InteractiveDetector* interactive_detector =
GetTestInteractiveDetector(*document);
@@ -5409,9 +5442,9 @@ TEST_F(WebViewTest, LongestInputDelayPageBackgroundedDuringQueuing) {
WebInputEvent::GetStaticTimeStampForTests());
key_event1.dom_key = ui::DomKey::FromCharacter(' ');
key_event1.windows_key_code = VKEY_SPACE;
- TimeTicks key_event1_time = test_task_runner_->NowTicks();
+ base::TimeTicks key_event1_time = test_task_runner_->NowTicks();
key_event1.SetTimeStamp(key_event1_time);
- test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(50));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
web_view->MainFrameWidget()->HandleInputEvent(
WebCoalescedInputEvent(key_event1));
@@ -5421,11 +5454,11 @@ TEST_F(WebViewTest, LongestInputDelayPageBackgroundedDuringQueuing) {
key_event2.dom_key = ui::DomKey::FromCharacter(' ');
key_event2.windows_key_code = VKEY_SPACE;
key_event2.SetTimeStamp(test_task_runner_->NowTicks());
- test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(100));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(100));
web_view->SetIsHidden(/*is_hidden=*/true, /*initial_state=*/false);
- test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(100));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(100));
web_view->SetIsHidden(/*is_hidden=*/false, /*initial_state=*/false);
- test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(100));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(100));
// Total input delay is >300ms.
web_view->MainFrameWidget()->HandleInputEvent(
WebCoalescedInputEvent(key_event2));
@@ -5451,7 +5484,7 @@ TEST_F(WebViewTest, LongestInputDelayPageBackgroundedAtNavStart) {
Document* document = main_frame->GetDocument();
ASSERT_NE(nullptr, document);
- test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(70));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(70));
InteractiveDetector* interactive_detector =
GetTestInteractiveDetector(*document);
@@ -5462,7 +5495,7 @@ TEST_F(WebViewTest, LongestInputDelayPageBackgroundedAtNavStart) {
key_event.dom_key = ui::DomKey::FromCharacter(' ');
key_event.windows_key_code = VKEY_SPACE;
key_event.SetTimeStamp(test_task_runner_->NowTicks());
- test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(100));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(100));
web_view->SetIsHidden(/*is_hidden=*/false, /*initial_state=*/false);
web_view->MainFrameWidget()->HandleInputEvent(
WebCoalescedInputEvent(key_event));
@@ -5484,7 +5517,7 @@ TEST_F(WebViewTest, LongestInputDelayPageBackgroundedNotDuringQueuing) {
Document* document = main_frame->GetDocument();
ASSERT_NE(nullptr, document);
- test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(70));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(70));
InteractiveDetector* interactive_detector =
GetTestInteractiveDetector(*document);
@@ -5492,18 +5525,18 @@ TEST_F(WebViewTest, LongestInputDelayPageBackgroundedNotDuringQueuing) {
EXPECT_TRUE(interactive_detector->GetLongestInputDelay().is_zero());
web_view->SetIsHidden(/*is_hidden=*/true, /*initial_state=*/false);
- test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(100));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(100));
web_view->SetIsHidden(/*is_hidden=*/false, /*initial_state=*/false);
- test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(1));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(1));
WebKeyboardEvent key_event(WebInputEvent::kRawKeyDown,
WebInputEvent::kNoModifiers,
WebInputEvent::GetStaticTimeStampForTests());
key_event.dom_key = ui::DomKey::FromCharacter(' ');
key_event.windows_key_code = VKEY_SPACE;
- TimeTicks key_event_time = test_task_runner_->NowTicks();
+ base::TimeTicks key_event_time = test_task_runner_->NowTicks();
key_event.SetTimeStamp(key_event_time);
- test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(50));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
web_view->MainFrameWidget()->HandleInputEvent(
WebCoalescedInputEvent(key_event));
@@ -5533,7 +5566,7 @@ TEST_F(WebViewTest, PointerDownUpFirstInputDelay) {
ASSERT_NE(nullptr, document);
base::TimeTicks start_time = test_task_runner_->NowTicks();
- test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(70));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(70));
InteractiveDetector* interactive_detector =
GetTestInteractiveDetector(*document);
@@ -5545,7 +5578,7 @@ TEST_F(WebViewTest, PointerDownUpFirstInputDelay) {
// Set this to the left button, needed for testing to behave properly.
pointer_down.SetModifiers(WebInputEvent::kLeftButtonDown);
pointer_down.button = WebPointerProperties::Button::kLeft;
- test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(50));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
web_view->MainFrameWidget()->HandleInputEvent(
WebCoalescedInputEvent(pointer_down));
@@ -5557,7 +5590,7 @@ TEST_F(WebViewTest, PointerDownUpFirstInputDelay) {
WebPointerEvent pointer_up(
WebInputEvent::kPointerUp,
WebPointerProperties(1, WebPointerProperties::PointerType::kTouch), 5, 5);
- test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(60));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(60));
pointer_up.SetTimeStamp(test_task_runner_->NowTicks());
web_view->MainFrameWidget()->HandleInputEvent(
WebCoalescedInputEvent(pointer_up));
@@ -5575,7 +5608,7 @@ class MockClockAdvancingWebFrameClient
public:
MockClockAdvancingWebFrameClient(
scoped_refptr<base::TestMockTimeTaskRunner> task_runner,
- TimeDelta event_handling_delay)
+ base::TimeDelta event_handling_delay)
: task_runner_(std::move(task_runner)),
event_handling_delay_(event_handling_delay) {}
// WebLocalFrameClient overrides:
@@ -5588,15 +5621,15 @@ class MockClockAdvancingWebFrameClient
private:
scoped_refptr<base::TestMockTimeTaskRunner> task_runner_;
- TimeDelta event_handling_delay_;
+ base::TimeDelta event_handling_delay_;
};
// Check that the input delay is correctly reported to the document.
TEST_F(WebViewTest, FirstInputDelayExcludesProcessingTime) {
// Page load timing logic depends on the time not being zero.
- test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(1));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(1));
MockClockAdvancingWebFrameClient frame_client(
- test_task_runner_, TimeDelta::FromMilliseconds(6000));
+ test_task_runner_, base::TimeDelta::FromMilliseconds(6000));
WebViewImpl* web_view = web_view_helper_.Initialize(&frame_client);
WebURL base_url = url_test_helpers::ToKURL("http://example.com/");
frame_test_helpers::LoadHTMLString(web_view->MainFrameImpl(),
@@ -5625,12 +5658,13 @@ TEST_F(WebViewTest, FirstInputDelayExcludesProcessingTime) {
key_event.windows_key_code = VKEY_SPACE;
key_event.SetTimeStamp(test_task_runner_->NowTicks());
- test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(5000));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(5000));
web_view->MainFrameWidget()->HandleInputEvent(
WebCoalescedInputEvent(key_event));
- TimeDelta first_input_delay = interactive_detector->GetFirstInputDelay();
+ base::TimeDelta first_input_delay =
+ interactive_detector->GetFirstInputDelay();
EXPECT_EQ(5000, first_input_delay.InMillisecondsF());
web_view_helper_.Reset(); // Remove dependency on locally scoped client.
@@ -5639,9 +5673,9 @@ TEST_F(WebViewTest, FirstInputDelayExcludesProcessingTime) {
// Check that the longest input delay is correctly reported to the document.
TEST_F(WebViewTest, LongestInputDelayExcludesProcessingTime) {
// Page load timing logic depends on the time not being zero.
- test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(1));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(1));
MockClockAdvancingWebFrameClient frame_client(
- test_task_runner_, TimeDelta::FromMilliseconds(6000));
+ test_task_runner_, base::TimeDelta::FromMilliseconds(6000));
WebViewImpl* web_view = web_view_helper_.Initialize(&frame_client);
WebURL base_url = url_test_helpers::ToKURL("http://example.com/");
frame_test_helpers::LoadHTMLString(web_view->MainFrameImpl(),
@@ -5669,12 +5703,13 @@ TEST_F(WebViewTest, LongestInputDelayExcludesProcessingTime) {
key_event.windows_key_code = VKEY_SPACE;
key_event.SetTimeStamp(test_task_runner_->NowTicks());
- test_task_runner_->FastForwardBy(TimeDelta::FromMilliseconds(5000));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(5000));
web_view->MainFrameWidget()->HandleInputEvent(
WebCoalescedInputEvent(key_event));
- TimeDelta longest_input_delay = interactive_detector->GetLongestInputDelay();
+ base::TimeDelta longest_input_delay =
+ interactive_detector->GetLongestInputDelay();
EXPECT_EQ(5000, longest_input_delay.InMillisecondsF());
web_view_helper_.Reset(); // Remove dependency on locally scoped client.
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 1f2993c2605..6b8a4b0780a 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,7 +4,7 @@
#include "third_party/blink/renderer/core/exported/worker_shadow_page.h"
-#include "services/network/public/mojom/referrer_policy.mojom-shared.h"
+#include "services/network/public/mojom/referrer_policy.mojom-blink.h"
#include "third_party/blink/public/mojom/frame/document_interface_broker.mojom-blink.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/core/exported/web_view_impl.h"
@@ -27,7 +27,8 @@ mojo::ScopedMessagePipeHandle CreateStubDocumentInterfaceBrokerHandle() {
WorkerShadowPage::WorkerShadowPage(
Client* client,
scoped_refptr<network::SharedURLLoaderFactory> loader_factory,
- PrivacyPreferences preferences)
+ PrivacyPreferences preferences,
+ const base::UnguessableToken& appcache_host_id)
: client_(client),
web_view_(WebViewImpl::Create(nullptr,
/*is_hidden=*/false,
@@ -43,6 +44,7 @@ WorkerShadowPage::WorkerShadowPage(
WebSandboxFlags::kNone,
FeaturePolicy::FeatureState())),
loader_factory_(std::move(loader_factory)),
+ appcache_host_id_(appcache_host_id),
preferences_(std::move(preferences)) {
DCHECK(IsMainThread());
@@ -64,11 +66,13 @@ void WorkerShadowPage::Initialize(const KURL& script_url) {
// Construct substitute data source. We only need it to have same origin as
// the worker so the loading checks work correctly.
- CString content("");
- main_frame_->GetFrame()->Loader().CommitNavigation(
+ std::string content("");
+ std::unique_ptr<WebNavigationParams> params =
WebNavigationParams::CreateWithHTMLBuffer(
- SharedBuffer::Create(content.data(), content.length()), script_url),
- nullptr /* extra_data */);
+ SharedBuffer::Create(content.c_str(), content.length()), script_url);
+ params->appcache_host_id = appcache_host_id_;
+ main_frame_->GetFrame()->Loader().CommitNavigation(std::move(params),
+ nullptr /* extra_data */);
}
void WorkerShadowPage::DidFinishDocumentLoad() {
@@ -77,14 +81,6 @@ void WorkerShadowPage::DidFinishDocumentLoad() {
client_->OnShadowPageInitialized();
}
-std::unique_ptr<WebApplicationCacheHost>
-WorkerShadowPage::CreateApplicationCacheHost(
- WebDocumentLoader*,
- WebApplicationCacheHostClient* appcache_host_client) {
- DCHECK(IsMainThread());
- return client_->CreateApplicationCacheHost(appcache_host_client);
-}
-
std::unique_ptr<blink::WebURLLoaderFactory>
WorkerShadowPage::CreateURLLoaderFactory() {
DCHECK(IsMainThread());
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 866311fefa6..79c26c4a9da 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
@@ -19,8 +19,6 @@ class SharedURLLoaderFactory;
namespace blink {
-class WebApplicationCacheHost;
-class WebApplicationCacheHostClient;
class WebSettings;
// WorkerShadowPage implements the 'shadow page' concept.
@@ -42,15 +40,12 @@ class CORE_EXPORT WorkerShadowPage : public WebLocalFrameClient {
public:
~Client() override = default;
- // Called when the shadow page is requested to create an application cache
- // host.
- virtual std::unique_ptr<WebApplicationCacheHost> CreateApplicationCacheHost(
- WebApplicationCacheHostClient*) = 0;
-
// Called when Initialize() is completed.
virtual void OnShadowPageInitialized() = 0;
virtual const base::UnguessableToken& GetDevToolsWorkerToken() = 0;
+
+ virtual WebLocalFrameClient::AppCacheType GetAppCacheType() = 0;
};
// If |loader_factory| is non-null, the shadow page will use it when making
@@ -58,7 +53,8 @@ class CORE_EXPORT WorkerShadowPage : public WebLocalFrameClient {
WorkerShadowPage(
Client* client,
scoped_refptr<network::SharedURLLoaderFactory> loader_factory,
- PrivacyPreferences preferences);
+ PrivacyPreferences preferences,
+ const base::UnguessableToken& appcache_host_id);
~WorkerShadowPage() override;
// Initializes this instance and calls Client::OnShadowPageInitialized() when
@@ -66,9 +62,6 @@ class CORE_EXPORT WorkerShadowPage : public WebLocalFrameClient {
void Initialize(const KURL& script_url);
// WebLocalFrameClient overrides.
- std::unique_ptr<WebApplicationCacheHost> CreateApplicationCacheHost(
- WebDocumentLoader*,
- WebApplicationCacheHostClient*) override;
// Note: usually WebLocalFrameClient implementations override
// WebLocalFrameClient to call Close() on the corresponding WebLocalFrame.
// Shadow pages are set up a bit differently and clear the WebLocalFrameClient
@@ -79,6 +72,9 @@ class CORE_EXPORT WorkerShadowPage : public WebLocalFrameClient {
base::UnguessableToken GetDevToolsFrameToken() override;
void WillSendRequest(WebURLRequest&) override;
void BeginNavigation(std::unique_ptr<WebNavigationInfo> info) override;
+ WebLocalFrameClient::AppCacheType GetAppCacheType() override {
+ return client_->GetAppCacheType();
+ }
Document* GetDocument() { return main_frame_->GetFrame()->GetDocument(); }
WebSettings* GetSettings() { return web_view_->GetSettings(); }
@@ -97,6 +93,7 @@ class CORE_EXPORT WorkerShadowPage : public WebLocalFrameClient {
WebView* web_view_;
Persistent<WebLocalFrameImpl> main_frame_;
scoped_refptr<network::SharedURLLoaderFactory> loader_factory_;
+ const base::UnguessableToken appcache_host_id_;
// TODO(crbug.com/862854): Update the values when the browser process changes
// the preferences.
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 9aec8ac93f8..631d4f71465 100644
--- a/chromium/third_party/blink/renderer/core/feature_policy/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/feature_policy/BUILD.gn
@@ -12,6 +12,7 @@ blink_core_sources("feature_policy") {
"feature_policy_helper.h",
"feature_policy_parser.cc",
"feature_policy_parser.h",
+ "feature_policy_parser_delegate.h",
"iframe_policy.h",
"layout_animations_policy.cc",
"layout_animations_policy.h",
diff --git a/chromium/third_party/blink/renderer/core/feature_policy/feature_policy_features.json5 b/chromium/third_party/blink/renderer/core/feature_policy/feature_policy_features.json5
index 7e768dd1e23..e98ceff4967 100644
--- a/chromium/third_party/blink/renderer/core/feature_policy/feature_policy_features.json5
+++ b/chromium/third_party/blink/renderer/core/feature_policy/feature_policy_features.json5
@@ -107,7 +107,6 @@
{
name: "DocumentDomain",
feature_policy_name: "document-domain",
- depends_on: ["ExperimentalProductivityFeatures"],
},
{
name: "DocumentWrite",
@@ -255,10 +254,6 @@
depends_on: ["Serial"],
},
{
- name: "Speaker",
- feature_policy_name: "speaker",
- },
- {
name: "SyncScript",
feature_policy_name: "sync-script",
depends_on: ["ExperimentalProductivityFeatures"],
diff --git a/chromium/third_party/blink/renderer/core/feature_policy/feature_policy_helper.h b/chromium/third_party/blink/renderer/core/feature_policy/feature_policy_helper.h
index 921fb2a0833..f7542617e95 100644
--- a/chromium/third_party/blink/renderer/core/feature_policy/feature_policy_helper.h
+++ b/chromium/third_party/blink/renderer/core/feature_policy/feature_policy_helper.h
@@ -14,7 +14,7 @@ namespace blink {
using FeatureNameMap = HashMap<String, mojom::FeaturePolicyFeature>;
-class ExecutionContext;
+class FeatureContext;
// This method defines the feature names which will be recognized by the parser
// for the Feature-Policy HTTP header and the <iframe> "allow" attribute, as
@@ -24,7 +24,7 @@ const FeatureNameMap& GetDefaultFeatureNameMap();
// Returns true if this feature is currently disabled by an origin trial (it is
// origin trial controlled, and the origin trial is not enabled).
-bool DisabledByOriginTrial(const String&, ExecutionContext*);
+bool DisabledByOriginTrial(const String&, FeatureContext*);
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/feature_policy/feature_policy_parser.cc b/chromium/third_party/blink/renderer/core/feature_policy/feature_policy_parser.cc
index 5bbfc8d5c3e..5260f89ce0b 100644
--- a/chromium/third_party/blink/renderer/core/feature_policy/feature_policy_parser.cc
+++ b/chromium/third_party/blink/renderer/core/feature_policy/feature_policy_parser.cc
@@ -11,9 +11,9 @@
#include "base/metrics/histogram_macros.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/use_counter.h"
#include "third_party/blink/renderer/core/origin_trials/origin_trial_context.h"
#include "third_party/blink/renderer/core/origin_trials/origin_trials.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.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"
@@ -28,9 +28,9 @@ ParsedFeaturePolicy FeaturePolicyParser::ParseHeader(
const String& policy,
scoped_refptr<const SecurityOrigin> origin,
Vector<String>* messages,
- ExecutionContext* execution_context) {
+ FeaturePolicyParserDelegate* delegate) {
return Parse(policy, origin, nullptr, messages, GetDefaultFeatureNameMap(),
- execution_context);
+ delegate);
}
ParsedFeaturePolicy FeaturePolicyParser::ParseAttribute(
@@ -49,7 +49,7 @@ ParsedFeaturePolicy FeaturePolicyParser::Parse(
scoped_refptr<const SecurityOrigin> src_origin,
Vector<String>* messages,
const FeatureNameMap& feature_names,
- ExecutionContext* execution_context) {
+ FeaturePolicyParserDelegate* delegate) {
ParsedFeaturePolicy allowlists;
std::bitset<static_cast<size_t>(mojom::FeaturePolicyFeature::kMaxValue) + 1>
features_specified;
@@ -61,18 +61,16 @@ ParsedFeaturePolicy FeaturePolicyParser::Parse(
Vector<String> policy_items;
// policy_items = [ policy *( "," [ policy ] ) ]
policy.Split(',', policy_items);
- if (policy_items.size() > 1) {
- UseCounter::Count(
- execution_context,
+ if (policy_items.size() > 1 && delegate) {
+ delegate->CountFeaturePolicyUsage(
mojom::WebFeature::kFeaturePolicyCommaSeparatedDeclarations);
}
for (const String& item : policy_items) {
Vector<String> entry_list;
// entry_list = [ entry *( ";" [ entry ] ) ]
item.Split(';', entry_list);
- if (entry_list.size() > 1) {
- UseCounter::Count(
- execution_context,
+ if (entry_list.size() > 1 && delegate) {
+ delegate->CountFeaturePolicyUsage(
mojom::WebFeature::kFeaturePolicySemicolonSeparatedDeclarations);
}
for (const String& entry : entry_list) {
@@ -92,7 +90,7 @@ ParsedFeaturePolicy FeaturePolicyParser::Parse(
continue;
}
- if (DisabledByOriginTrial(feature_name, execution_context)) {
+ if (DisabledByOriginTrial(feature_name, delegate)) {
if (messages) {
messages->push_back("Origin trial controlled feature not enabled: '" +
tokens[0] + "'.");
@@ -110,13 +108,9 @@ ParsedFeaturePolicy FeaturePolicyParser::Parse(
// Count the use of this feature policy.
if (src_origin) {
- Document* document = DynamicTo<Document>(execution_context);
- if (!document || !document->IsParsedFeaturePolicy(feature)) {
+ if (!delegate || !delegate->FeaturePolicyFeatureObserved(feature)) {
UMA_HISTOGRAM_ENUMERATION("Blink.UseCounter.FeaturePolicy.Allow",
feature);
- if (document) {
- document->SetParsedFeaturePolicy(feature);
- }
}
} else {
UMA_HISTOGRAM_ENUMERATION("Blink.UseCounter.FeaturePolicy.Header",
@@ -139,16 +133,20 @@ ParsedFeaturePolicy FeaturePolicyParser::Parse(
feature == mojom::FeaturePolicyFeature::kUnoptimizedLosslessImages ||
feature ==
mojom::FeaturePolicyFeature::kUnoptimizedLosslessImagesStrict) {
- UseCounter::Count(execution_context,
- mojom::WebFeature::kUnoptimizedImagePolicies);
+ if (delegate) {
+ delegate->CountFeaturePolicyUsage(
+ mojom::WebFeature::kUnoptimizedImagePolicies);
+ }
// Don't analyze allowlists for origin trial features.
count_allowlist_type = false;
}
// Detect usage of UnsizedMediaPolicy origin trial
if (feature == mojom::FeaturePolicyFeature::kUnsizedMedia) {
- UseCounter::Count(execution_context,
- mojom::WebFeature::kUnsizedMediaPolicy);
+ if (delegate) {
+ delegate->CountFeaturePolicyUsage(
+ mojom::WebFeature::kUnsizedMediaPolicy);
+ }
// Don't analyze allowlists for origin trial features.
count_allowlist_type = false;
}
@@ -275,7 +273,6 @@ ParsedFeaturePolicy FeaturePolicyParser::Parse(
} else if (target_is_opaque) {
allowlist.opaque_value = value;
} else {
- DCHECK(!target_origin.opaque());
values[target_origin] = value;
}
}
@@ -403,6 +400,13 @@ PolicyValue FeaturePolicyParser::ParseValueForType(
return value;
}
+void FeaturePolicyParser::ParseValueForFuzzer(
+ blink::mojom::PolicyValueType feature_type,
+ const WTF::String& value_string) {
+ bool ok;
+ ParseValueForType(feature_type, value_string, &ok);
+}
+
bool IsFeatureDeclared(mojom::FeaturePolicyFeature feature,
const ParsedFeaturePolicy& policy) {
return std::any_of(policy.begin(), policy.end(),
diff --git a/chromium/third_party/blink/renderer/core/feature_policy/feature_policy_parser.h b/chromium/third_party/blink/renderer/core/feature_policy/feature_policy_parser.h
index 5739397fc6a..7a9725ccce2 100644
--- a/chromium/third_party/blink/renderer/core/feature_policy/feature_policy_parser.h
+++ b/chromium/third_party/blink/renderer/core/feature_policy/feature_policy_parser.h
@@ -16,13 +16,11 @@
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
-// Forward declare for friendship.
-void ParseValueForFuzzer(blink::mojom::PolicyValueType, const WTF::String&);
-
namespace blink {
class Document;
class ExecutionContext;
+class FeaturePolicyParserDelegate;
// These values match the "FeaturePolicyAllowlistType" enum in
// tools/metrics/histograms/enums.xml. Entries should not be renumbered and
@@ -66,7 +64,7 @@ class CORE_EXPORT FeaturePolicyParser {
const String& policy,
scoped_refptr<const SecurityOrigin>,
Vector<String>* messages,
- ExecutionContext* execution_context = nullptr);
+ FeaturePolicyParserDelegate* delegate = nullptr);
// Converts a container policy string into a vector of allowlists, given self
// and src origins provided, one for each feature specified. Unrecognized
@@ -93,10 +91,12 @@ class CORE_EXPORT FeaturePolicyParser {
scoped_refptr<const SecurityOrigin> src_origin,
Vector<String>* messages,
const FeatureNameMap& feature_names,
- ExecutionContext* execution_context = nullptr);
+ FeaturePolicyParserDelegate* delegate = nullptr);
+
+ // Used for LLVM fuzzer test
+ static void ParseValueForFuzzer(mojom::PolicyValueType, const String&);
private:
- friend void ::ParseValueForFuzzer(mojom::PolicyValueType, const String&);
static PolicyValue GetFallbackValueForFeature(
mojom::FeaturePolicyFeature feature);
static PolicyValue ParseValueForType(mojom::PolicyValueType feature_type,
diff --git a/chromium/third_party/blink/renderer/core/feature_policy/feature_policy_parser_delegate.h b/chromium/third_party/blink/renderer/core/feature_policy/feature_policy_parser_delegate.h
new file mode 100644
index 00000000000..3d7cbf11d47
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/feature_policy/feature_policy_parser_delegate.h
@@ -0,0 +1,23 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_FEATURE_POLICY_FEATURE_POLICY_PARSER_DELEGATE_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_FEATURE_POLICY_FEATURE_POLICY_PARSER_DELEGATE_H_
+
+#include "third_party/blink/public/mojom/feature_policy/feature_policy.mojom-blink.h"
+#include "third_party/blink/renderer/core/frame/web_feature.h"
+#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
+
+namespace blink {
+
+class FeaturePolicyParserDelegate : public FeatureContext {
+ public:
+ virtual void CountFeaturePolicyUsage(mojom::WebFeature feature) = 0;
+ virtual bool FeaturePolicyFeatureObserved(
+ mojom::FeaturePolicyFeature feature) = 0;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_FEATURE_POLICY_FEATURE_POLICY_PARSER_DELEGATE_H_
diff --git a/chromium/third_party/blink/renderer/core/feature_policy/feature_policy_value_fuzzer.cc b/chromium/third_party/blink/renderer/core/feature_policy/feature_policy_value_fuzzer.cc
index 7f8e6aa984b..1455636e495 100644
--- a/chromium/third_party/blink/renderer/core/feature_policy/feature_policy_value_fuzzer.cc
+++ b/chromium/third_party/blink/renderer/core/feature_policy/feature_policy_value_fuzzer.cc
@@ -13,19 +13,12 @@
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
-void ParseValueForFuzzer(blink::mojom::PolicyValueType feature_type,
- const WTF::String& value_string) {
- bool ok;
- blink::FeaturePolicyParser::ParseValueForType(feature_type, value_string,
- &ok);
-}
-
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
static blink::BlinkFuzzerTestSupport test_support =
blink::BlinkFuzzerTestSupport();
- ParseValueForFuzzer(blink::mojom::PolicyValueType::kBool,
- WTF::String(data, size));
- ParseValueForFuzzer(blink::mojom::PolicyValueType::kDecDouble,
- WTF::String(data, size));
+ blink::FeaturePolicyParser::ParseValueForFuzzer(
+ blink::mojom::PolicyValueType::kBool, WTF::String(data, size));
+ blink::FeaturePolicyParser::ParseValueForFuzzer(
+ blink::mojom::PolicyValueType::kDecDouble, WTF::String(data, size));
return 0;
}
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
index 3b08064a6b2..53c870bd734 100644
--- 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
@@ -15,10 +15,10 @@ 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(),
+ property.GetPropertyNameString().Utf8().c_str(),
GetNameForFeature(mojom::FeaturePolicyFeature::kLayoutAnimations)
.Utf8()
- .data());
+ .c_str());
}
} // namespace
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
index 3efcff1dcce..d2d5bced360 100644
--- 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
@@ -6,7 +6,7 @@
#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/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.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 f7bd73eeff6..d915fd5f4bf 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
@@ -24,11 +24,13 @@ using testing::UnorderedElementsAre;
class PolicyTest : public testing::Test {
public:
void SetUp() override {
- document_ = MakeGarbageCollected<Document>();
- document_->SetSecurityOrigin(SecurityOrigin::CreateFromString(kSelfOrigin));
- document_->ApplyFeaturePolicyFromHeader(
- "fullscreen *; payment 'self'; midi 'none'; camera 'self' "
- "https://example.com https://example.net");
+ DocumentInit init =
+ DocumentInit::Create()
+ .WithOriginToCommit(SecurityOrigin::CreateFromString(kSelfOrigin))
+ .WithFeaturePolicyHeader(
+ "fullscreen *; payment 'self'; midi 'none'; camera 'self' "
+ "https://example.com https://example.net");
+ document_ = MakeGarbageCollected<Document>(init);
}
DOMFeaturePolicy* GetPolicy() const { return policy_; }
diff --git a/chromium/third_party/blink/renderer/core/fetch/DEPS b/chromium/third_party/blink/renderer/core/fetch/DEPS
index 3c497b001fa..15b3d088781 100644
--- a/chromium/third_party/blink/renderer/core/fetch/DEPS
+++ b/chromium/third_party/blink/renderer/core/fetch/DEPS
@@ -4,4 +4,5 @@ include_rules = [
"+mojo/public/cpp/bindings/binding_set.h",
"+mojo/public/cpp/system/data_pipe.h",
"+mojo/public/cpp/system/simple_watcher.h",
+ "+net/base/request_priority.h",
]
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 ea4e59e2bc3..d4ae6f19f74 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
@@ -295,9 +295,7 @@ void BodyStreamBuffer::OnStateChange() {
}
bool BodyStreamBuffer::HasPendingActivity() const {
- if (loader_)
- return true;
- return UnderlyingSourceBase::HasPendingActivity();
+ return loader_;
}
void BodyStreamBuffer::ContextDestroyed(ExecutionContext* destroyed_context) {
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 ca286e1f5ab..4c79523854a 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
@@ -68,8 +68,7 @@ class BodyStreamBufferTest : public testing::Test {
ADD_FAILURE() << ToCoreString(block.Exception()
->ToString(script_state->GetContext())
.ToLocalChecked())
- .Utf8()
- .data();
+ .Utf8();
block.ReThrow();
}
return r;
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 3bcde6d5ffd..6a04dd9799a 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
@@ -21,6 +21,7 @@
#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/string_utf8_adaptor.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
@@ -333,10 +334,11 @@ class FetchDataLoaderAsFormData final : public FetchDataLoader,
DCHECK(!form_data_);
DCHECK(!multipart_parser_);
- const CString multipart_boundary_utf8 = multipart_boundary_.Utf8();
+ StringUTF8Adaptor multipart_boundary_utf8(multipart_boundary_);
Vector<char> multipart_boundary_vector;
- multipart_boundary_vector.Append(multipart_boundary_utf8.data(),
- multipart_boundary_utf8.length());
+ multipart_boundary_vector.Append(
+ multipart_boundary_utf8.data(),
+ multipart_boundary_utf8.size());
client_ = client;
form_data_ = MakeGarbageCollected<FormData>();
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 7f2db89338a..123a2764a4d 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
@@ -5,7 +5,6 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_FETCH_FETCH_HEADER_LIST_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_FETCH_FETCH_HEADER_LIST_H_
-#include <map>
#include <utility>
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
@@ -20,7 +19,7 @@ class CORE_EXPORT FetchHeaderList final
public:
struct ByteCaseInsensitiveCompare {
bool operator()(const String& lhs, const String& rhs) const {
- return CodePointCompareLessThan(lhs.LowerASCII(), rhs.LowerASCII());
+ return CodeUnitCompareLessThan(lhs.LowerASCII(), rhs.LowerASCII());
}
};
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 098a36938e2..238429f076b 100644
--- a/chromium/third_party/blink/renderer/core/fetch/fetch_manager.cc
+++ b/chromium/third_party/blink/renderer/core/fetch/fetch_manager.cc
@@ -23,7 +23,6 @@
#include "third_party/blink/renderer/core/fileapi/blob.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
#include "third_party/blink/renderer/core/frame/frame.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/subresource_integrity_helper.h"
#include "third_party/blink/renderer/core/loader/threadable_loader.h"
@@ -38,6 +37,7 @@
#include "third_party/blink/renderer/platform/bindings/v8_throw_exception.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
#include "third_party/blink/renderer/platform/heap/persistent.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/loader/cors/cors.h"
#include "third_party/blink/renderer/platform/loader/fetch/buffering_bytes_consumer.h"
#include "third_party/blink/renderer/platform/loader/fetch/bytes_consumer.h"
@@ -61,9 +61,9 @@
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
-using network::mojom::FetchRedirectMode;
-using network::mojom::FetchRequestMode;
using network::mojom::FetchResponseType;
+using network::mojom::RedirectMode;
+using network::mojom::RequestMode;
namespace blink {
@@ -278,13 +278,13 @@ bool FetchManager::Loader::WillFollowRedirect(
const KURL& url,
const ResourceResponse& response) {
const auto redirect_mode = fetch_request_data_->Redirect();
- if (redirect_mode == network::mojom::FetchRedirectMode::kError) {
+ if (redirect_mode == network::mojom::RedirectMode::kError) {
DidFailRedirectCheck();
Dispose();
return false;
}
- if (redirect_mode == network::mojom::FetchRedirectMode::kManual) {
+ if (redirect_mode == network::mojom::RedirectMode::kManual) {
const uint64_t unused = 0;
// There is no need to read the body of redirect response because there is
// no way to read the body of opaque-redirect filtered response's internal
@@ -302,7 +302,7 @@ bool FetchManager::Loader::WillFollowRedirect(
return false;
}
- DCHECK_EQ(redirect_mode, network::mojom::FetchRedirectMode::kFollow);
+ DCHECK_EQ(redirect_mode, network::mojom::RedirectMode::kFollow);
url_list_.push_back(url);
return true;
}
@@ -330,13 +330,13 @@ 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 RequestMode::kNoCors:
tainting = FetchRequestData::kOpaqueTainting;
break;
- case FetchRequestMode::kSameOrigin:
- case FetchRequestMode::kCors:
- case FetchRequestMode::kCorsWithForcedPreflight:
- case FetchRequestMode::kNavigate:
+ case RequestMode::kSameOrigin:
+ case RequestMode::kCors:
+ case RequestMode::kCorsWithForcedPreflight:
+ case RequestMode::kNavigate:
PerformNetworkError("Fetch API cannot load " +
fetch_request_data_->Url().GetString() +
". Redirects to data: URL are allowed only when "
@@ -349,17 +349,17 @@ void FetchManager::Loader::DidReceiveResponse(
// Recompute the tainting if the request was redirected to a different
// origin.
switch (fetch_request_data_->Mode()) {
- case FetchRequestMode::kSameOrigin:
+ case RequestMode::kSameOrigin:
NOTREACHED();
break;
- case FetchRequestMode::kNoCors:
+ case RequestMode::kNoCors:
tainting = FetchRequestData::kOpaqueTainting;
break;
- case FetchRequestMode::kCors:
- case FetchRequestMode::kCorsWithForcedPreflight:
+ case RequestMode::kCors:
+ case RequestMode::kCorsWithForcedPreflight:
tainting = FetchRequestData::kCorsTainting;
break;
- case FetchRequestMode::kNavigate:
+ case RequestMode::kNavigate:
LOG(FATAL);
break;
}
@@ -432,10 +432,10 @@ void FetchManager::Loader::DidReceiveResponse(
DCHECK(!(network_utils::IsRedirectResponseCode(response_http_status_code_) &&
HasNonEmptyLocationHeader(response_data->HeaderList()) &&
- fetch_request_data_->Redirect() != FetchRedirectMode::kManual));
+ fetch_request_data_->Redirect() != RedirectMode::kManual));
if (network_utils::IsRedirectResponseCode(response_http_status_code_) &&
- fetch_request_data_->Redirect() == FetchRedirectMode::kManual) {
+ fetch_request_data_->Redirect() == RedirectMode::kManual) {
tainted_response = response_data->CreateOpaqueRedirectFilteredResponse();
} else {
switch (tainting) {
@@ -545,9 +545,8 @@ void FetchManager::Loader::Start(ExceptionState& exception_state) {
// "- should fetching |request| be blocked as content security returns
// blocked"
- if (!ContentSecurityPolicy::ShouldBypassMainWorld(execution_context_) &&
- !execution_context_->GetContentSecurityPolicy()->AllowConnectToSource(
- fetch_request_data_->Url())) {
+ if (!execution_context_->GetContentSecurityPolicyForWorld()
+ ->AllowConnectToSource(fetch_request_data_->Url())) {
// "A network error."
PerformNetworkError(
"Refused to connect to '" + fetch_request_data_->Url().ElidedString() +
@@ -566,14 +565,14 @@ void FetchManager::Loader::Start(ExceptionState& exception_state) {
->IsSameSchemeHostPort(fetch_request_data_->Origin().get())) ||
(fetch_request_data_->Url().ProtocolIsData() &&
fetch_request_data_->SameOriginDataURLFlag()) ||
- (fetch_request_data_->Mode() == FetchRequestMode::kNavigate)) {
+ (fetch_request_data_->Mode() == RequestMode::kNavigate)) {
// "The result of performing a scheme fetch using request."
PerformSchemeFetch(exception_state);
return;
}
// "- |request|'s mode is |same-origin|"
- if (fetch_request_data_->Mode() == FetchRequestMode::kSameOrigin) {
+ if (fetch_request_data_->Mode() == RequestMode::kSameOrigin) {
// "A network error."
PerformNetworkError("Fetch API cannot load " +
fetch_request_data_->Url().GetString() +
@@ -584,10 +583,10 @@ 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() == RequestMode::kNoCors) {
// "If |request|'s redirect mode is not |follow|, then return a network
// error.
- if (fetch_request_data_->Redirect() != FetchRedirectMode::kFollow) {
+ if (fetch_request_data_->Redirect() != RedirectMode::kFollow) {
PerformNetworkError("Fetch API cannot load " +
fetch_request_data_->Url().GetString() +
". Request mode is \"no-cors\" but the redirect mode "
@@ -693,22 +692,22 @@ void FetchManager::Loader::PerformHTTPFetch(ExceptionState& exception_state) {
fetch_request_data_->ShouldAlsoUseFactoryBoundOriginForCors());
switch (fetch_request_data_->Mode()) {
- case FetchRequestMode::kSameOrigin:
- case FetchRequestMode::kNoCors:
- case FetchRequestMode::kCors:
- case FetchRequestMode::kCorsWithForcedPreflight:
- request.SetFetchRequestMode(fetch_request_data_->Mode());
+ case RequestMode::kSameOrigin:
+ case RequestMode::kNoCors:
+ case RequestMode::kCors:
+ case RequestMode::kCorsWithForcedPreflight:
+ request.SetMode(fetch_request_data_->Mode());
break;
- case FetchRequestMode::kNavigate:
+ case RequestMode::kNavigate:
// NetworkService (i.e. CorsURLLoaderFactory::IsSane) rejects kNavigate
// requests coming from renderers, so using kSameOrigin here.
// TODO(lukasza): Tweak CorsURLLoaderFactory::IsSane to accept kNavigate
// if request_initiator and the target are same-origin.
- request.SetFetchRequestMode(FetchRequestMode::kSameOrigin);
+ request.SetMode(RequestMode::kSameOrigin);
break;
}
- request.SetFetchCredentialsMode(fetch_request_data_->Credentials());
+ request.SetCredentialsMode(fetch_request_data_->Credentials());
for (const auto& header : fetch_request_data_->HeaderList()->List()) {
// 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
@@ -729,14 +728,18 @@ void FetchManager::Loader::PerformHTTPFetch(ExceptionState& exception_state) {
}
}
request.SetCacheMode(fetch_request_data_->CacheMode());
- request.SetFetchRedirectMode(fetch_request_data_->Redirect());
+ request.SetRedirectMode(fetch_request_data_->Redirect());
request.SetFetchImportanceMode(fetch_request_data_->Importance());
request.SetPriority(fetch_request_data_->Priority());
request.SetUseStreamOnResponse(true);
request.SetExternalRequestStateFromRequestorAddressSpace(
execution_context_->GetSecurityContext().AddressSpace());
- request.SetReferrerString(fetch_request_data_->ReferrerString());
- request.SetReferrerPolicy(fetch_request_data_->GetReferrerPolicy());
+ request.SetReferrerString(
+ fetch_request_data_->ReferrerString(),
+ ResourceRequest::SetReferrerStringLocation::kPerformHTTPFetch);
+ request.SetReferrerPolicy(
+ fetch_request_data_->GetReferrerPolicy(),
+ ResourceRequest::SetReferrerPolicyLocation::kPerformHTTPFetch);
request.SetSkipServiceWorker(is_isolated_world_);
@@ -796,8 +799,8 @@ void FetchManager::Loader::PerformDataFetch() {
request.SetRequestContext(fetch_request_data_->Context());
request.SetUseStreamOnResponse(true);
request.SetHttpMethod(fetch_request_data_->Method());
- request.SetFetchCredentialsMode(network::mojom::FetchCredentialsMode::kOmit);
- request.SetFetchRedirectMode(FetchRedirectMode::kError);
+ request.SetCredentialsMode(network::mojom::CredentialsMode::kOmit);
+ request.SetRedirectMode(RedirectMode::kError);
request.SetFetchImportanceMode(fetch_request_data_->Importance());
request.SetPriority(fetch_request_data_->Priority());
// We intentionally skip 'setExternalRequestStateFromRequestorAddressSpace',
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 645bf4f458d..24fa093cd74 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
@@ -4,6 +4,7 @@
#include "third_party/blink/renderer/core/fetch/fetch_request_data.h"
+#include "net/base/request_priority.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_http_body.h"
#include "third_party/blink/public/platform/web_url_request.h"
@@ -19,34 +20,30 @@
#include "third_party/blink/renderer/platform/loader/fetch/resource_request.h"
#include "third_party/blink/renderer/platform/network/http_names.h"
-namespace mojo {
-
-template <>
-struct TypeConverter<::blink::ResourceLoadPriority,
- network::mojom::blink::RequestPriority> {
- static ::blink::ResourceLoadPriority Convert(
- network::mojom::blink::RequestPriority priority) {
- switch (priority) {
- case network::mojom::blink::RequestPriority::kThrottled:
- break;
- case network::mojom::blink::RequestPriority::kIdle:
- return ::blink::ResourceLoadPriority::kVeryLow;
- case network::mojom::blink::RequestPriority::kLowest:
- return ::blink::ResourceLoadPriority::kLow;
- case network::mojom::blink::RequestPriority::kLow:
- return ::blink::ResourceLoadPriority::kMedium;
- case network::mojom::blink::RequestPriority::kMedium:
- return ::blink::ResourceLoadPriority::kHigh;
- case network::mojom::blink::RequestPriority::kHighest:
- return ::blink::ResourceLoadPriority::kVeryHigh;
- }
+namespace {
- NOTREACHED() << priority;
- return blink::ResourceLoadPriority::kUnresolved;
+::blink::ResourceLoadPriority ConvertRequestPriorityToResourceLoadPriority(
+ net::RequestPriority priority) {
+ switch (priority) {
+ case net::RequestPriority::THROTTLED:
+ break;
+ case net::RequestPriority::IDLE:
+ return ::blink::ResourceLoadPriority::kVeryLow;
+ case net::RequestPriority::LOWEST:
+ return ::blink::ResourceLoadPriority::kLow;
+ case net::RequestPriority::LOW:
+ return ::blink::ResourceLoadPriority::kMedium;
+ case net::RequestPriority::MEDIUM:
+ return ::blink::ResourceLoadPriority::kHigh;
+ case net::RequestPriority::HIGHEST:
+ return ::blink::ResourceLoadPriority::kVeryHigh;
}
-};
-} // namespace mojo
+ NOTREACHED() << priority;
+ return blink::ResourceLoadPriority::kUnresolved;
+}
+
+} // namespace
namespace blink {
@@ -123,7 +120,7 @@ FetchRequestData* FetchRequestData::Create(
request->SetKeepalive(fetch_api_request.keepalive);
request->SetIsHistoryNavigation(fetch_api_request.is_history_navigation);
request->SetPriority(
- mojo::ConvertTo<ResourceLoadPriority>(fetch_api_request.priority));
+ ConvertRequestPriorityToResourceLoadPriority(fetch_api_request.priority));
if (fetch_api_request.fetch_window_id)
request->SetWindowId(fetch_api_request.fetch_window_id.value());
return request;
@@ -198,10 +195,10 @@ FetchRequestData::FetchRequestData()
same_origin_data_url_flag_(false),
referrer_string_(Referrer::ClientReferrerString()),
referrer_policy_(network::mojom::ReferrerPolicy::kDefault),
- mode_(network::mojom::FetchRequestMode::kNoCors),
- credentials_(network::mojom::FetchCredentialsMode::kOmit),
+ mode_(network::mojom::RequestMode::kNoCors),
+ credentials_(network::mojom::CredentialsMode::kOmit),
cache_mode_(mojom::FetchCacheMode::kDefault),
- redirect_(network::mojom::FetchRedirectMode::kFollow),
+ redirect_(network::mojom::RedirectMode::kFollow),
importance_(mojom::FetchImportanceMode::kImportanceAuto),
response_tainting_(kBasicTainting),
priority_(ResourceLoadPriority::kUnresolved),
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 3fbba560475..86b6f85feb3 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,7 +9,7 @@
#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/referrer_policy.mojom-blink.h"
#include "services/network/public/mojom/url_loader_factory.mojom-blink.h"
#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h"
#include "third_party/blink/public/platform/web_url_request.h"
@@ -67,22 +67,20 @@ class CORE_EXPORT FetchRequestData final
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) {
+ void SetMode(network::mojom::RequestMode mode) { mode_ = mode; }
+ network::mojom::RequestMode Mode() const { return mode_; }
+ void SetCredentials(network::mojom::CredentialsMode credentials) {
credentials_ = credentials;
}
- network::mojom::FetchCredentialsMode Credentials() const {
- return credentials_;
- }
+ network::mojom::CredentialsMode Credentials() const { return credentials_; }
void SetCacheMode(mojom::FetchCacheMode cache_mode) {
cache_mode_ = cache_mode;
}
mojom::FetchCacheMode CacheMode() const { return cache_mode_; }
- void SetRedirect(network::mojom::FetchRedirectMode redirect) {
+ void SetRedirect(network::mojom::RedirectMode redirect) {
redirect_ = redirect;
}
- network::mojom::FetchRedirectMode Redirect() const { return redirect_; }
+ network::mojom::RedirectMode Redirect() const { return redirect_; }
void SetImportance(mojom::FetchImportanceMode importance) {
importance_ = importance;
}
@@ -138,13 +136,13 @@ class CORE_EXPORT FetchRequestData final
network::mojom::ReferrerPolicy referrer_policy_;
// FIXME: Support m_authenticationFlag;
// FIXME: Support m_synchronousFlag;
- network::mojom::FetchRequestMode mode_;
- network::mojom::FetchCredentialsMode credentials_;
+ network::mojom::RequestMode mode_;
+ network::mojom::CredentialsMode credentials_;
// TODO(yiyix): |cache_mode_| is exposed but does not yet affect fetch
// behavior. We must transfer the mode to the network layer and service
// worker.
mojom::FetchCacheMode cache_mode_;
- network::mojom::FetchRedirectMode redirect_;
+ network::mojom::RedirectMode redirect_;
mojom::FetchImportanceMode importance_;
// FIXME: Support m_useURLCredentialsFlag;
// FIXME: Support m_redirectCount;
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 7bba68b6216..53c95f8e245 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
@@ -89,7 +89,7 @@ FetchResponseData* FetchResponseData::CreateCorsFilteredResponse(
for (const auto& header : header_list_->List()) {
const String& name = header.first;
if (cors::IsCorsSafelistedResponseHeader(name) ||
- (exposed_headers.find(name.Ascii().data()) != exposed_headers.end() &&
+ (exposed_headers.find(name.Ascii()) != exposed_headers.end() &&
!FetchUtils::IsForbiddenResponseHeaderName(name))) {
response->header_list_->Append(name, header.second);
}
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 e2f07660cab..3f2df87f7f1 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
@@ -74,7 +74,7 @@ class CORE_EXPORT FetchResponseData final
// returns |m_buffer|.
BodyStreamBuffer* InternalBuffer() const;
String InternalMIMEType() const;
- Time ResponseTime() const { return response_time_; }
+ base::Time ResponseTime() const { return response_time_; }
String CacheStorageCacheName() const { return cache_storage_cache_name_; }
const WebHTTPHeaderSet& CorsExposedHeaderNames() const {
return cors_exposed_header_names_;
@@ -92,7 +92,9 @@ class CORE_EXPORT FetchResponseData final
status_message_ = status_message;
}
void SetMimeType(const String& type) { mime_type_ = type; }
- void SetResponseTime(Time response_time) { response_time_ = response_time; }
+ void SetResponseTime(base::Time response_time) {
+ response_time_ = response_time;
+ }
void SetCacheStorageCacheName(const String& cache_storage_cache_name) {
cache_storage_cache_name_ = cache_storage_cache_name;
}
@@ -122,7 +124,7 @@ class CORE_EXPORT FetchResponseData final
Member<FetchResponseData> internal_response_;
Member<BodyStreamBuffer> buffer_;
String mime_type_;
- Time response_time_;
+ base::Time response_time_;
String cache_storage_cache_name_;
WebHTTPHeaderSet cors_exposed_header_names_;
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 89aca99785c..512ad7b6943 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
@@ -12,7 +12,6 @@
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/platform/web_http_body.h"
-#include "third_party/blink/public/platform/web_string.h"
#include "third_party/blink/renderer/core/fetch/bytes_consumer_test_util.h"
#include "third_party/blink/renderer/core/html/forms/form_data.h"
#include "third_party/blink/renderer/core/testing/page_test_base.h"
@@ -50,7 +49,7 @@ class SimpleDataPipeGetter : public network::mojom::blink::DataPipeGetter {
// network::mojom::DataPipeGetter implementation:
void Read(mojo::ScopedDataPipeProducerHandle handle,
ReadCallback callback) override {
- bool result = mojo::BlockingCopyFromString(WebString(str_).Utf8(), handle);
+ bool result = mojo::BlockingCopyFromString(str_.Utf8(), handle);
ASSERT_TRUE(result);
std::move(callback).Run(0 /* OK */, str_.length());
}
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 889f063d229..055bfe96b76 100644
--- a/chromium/third_party/blink/renderer/core/fetch/global_fetch.cc
+++ b/chromium/third_party/blink/renderer/core/fetch/global_fetch.cc
@@ -8,11 +8,11 @@
#include "third_party/blink/renderer/core/fetch/request.h"
#include "third_party/blink/renderer/core/fetch/request_init.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.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/workers/worker_global_scope.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/supplementable.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/fetch/multipart_parser.h b/chromium/third_party/blink/renderer/core/fetch/multipart_parser.h
index 8dec658a60b..cedf5e53319 100644
--- a/chromium/third_party/blink/renderer/core/fetch/multipart_parser.h
+++ b/chromium/third_party/blink/renderer/core/fetch/multipart_parser.h
@@ -9,7 +9,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/network/http_header_map.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
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 a05744f77a1..1643916a847 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
@@ -177,10 +177,6 @@ void ReadableStreamBytesConsumer::Trace(blink::Visitor* visitor) {
BytesConsumer::Trace(visitor);
}
-void ReadableStreamBytesConsumer::Dispose() {
- read_handle_ = nullptr;
-}
-
void ReadableStreamBytesConsumer::OnRead(DOMUint8Array* buffer) {
DCHECK(is_reading_);
DCHECK(buffer);
diff --git a/chromium/third_party/blink/renderer/core/fetch/readable_stream_bytes_consumer.h b/chromium/third_party/blink/renderer/core/fetch/readable_stream_bytes_consumer.h
index 9c79c62722a..f62404f8d07 100644
--- a/chromium/third_party/blink/renderer/core/fetch/readable_stream_bytes_consumer.h
+++ b/chromium/third_party/blink/renderer/core/fetch/readable_stream_bytes_consumer.h
@@ -23,7 +23,6 @@ class ScriptState;
// The stream will be immediately locked by the consumer and will never be
// released.
class CORE_EXPORT ReadableStreamBytesConsumer final : public BytesConsumer {
- USING_PRE_FINALIZER(ReadableStreamBytesConsumer, Dispose);
public:
ReadableStreamBytesConsumer(ScriptState*, ReadableStream*, ExceptionState&);
@@ -45,7 +44,6 @@ class CORE_EXPORT ReadableStreamBytesConsumer final : public BytesConsumer {
class OnFulfilled;
class OnRejected;
- void Dispose();
void OnRead(DOMUint8Array*);
void OnReadDone();
void OnRejected();
diff --git a/chromium/third_party/blink/renderer/core/fetch/request.cc b/chromium/third_party/blink/renderer/core/fetch/request.cc
index 3f9e07f85ce..e9ca3805c71 100644
--- a/chromium/third_party/blink/renderer/core/fetch/request.cc
+++ b/chromium/third_party/blink/renderer/core/fetch/request.cc
@@ -5,6 +5,7 @@
#include "third_party/blink/renderer/core/fetch/request.h"
#include "third_party/blink/public/common/blob/blob_utils.h"
+#include "third_party/blink/public/common/loader/request_destination.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/idl_types.h"
@@ -24,12 +25,12 @@
#include "third_party/blink/renderer/core/fetch/request_init.h"
#include "third_party/blink/renderer/core/fileapi/blob.h"
#include "third_party/blink/renderer/core/fileapi/public_url_manager.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/loader/threadable_loader.h"
#include "third_party/blink/renderer/core/url/url_search_params.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/instrumentation/use_counter.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"
@@ -279,8 +280,8 @@ Request* Request::CreateRequestWithRequestOrString(
// "If any of |init|'s members are present, then:"
if (AreAnyMembersPresent(init)) {
// "If |request|'s |mode| is "navigate", then set it to "same-origin".
- if (request->Mode() == network::mojom::FetchRequestMode::kNavigate)
- request->SetMode(network::mojom::FetchRequestMode::kSameOrigin);
+ if (request->Mode() == network::mojom::RequestMode::kNavigate)
+ request->SetMode(network::mojom::RequestMode::kSameOrigin);
// TODO(yhirano): Implement the following substep:
// "Unset |request|'s reload-navigation flag."
@@ -368,16 +369,16 @@ Request* Request::CreateRequestWithRequestOrString(
return nullptr;
}
if (init->mode() == "same-origin") {
- request->SetMode(network::mojom::FetchRequestMode::kSameOrigin);
+ request->SetMode(network::mojom::RequestMode::kSameOrigin);
} else if (init->mode() == "no-cors") {
- request->SetMode(network::mojom::FetchRequestMode::kNoCors);
+ request->SetMode(network::mojom::RequestMode::kNoCors);
} else if (init->mode() == "cors") {
- request->SetMode(network::mojom::FetchRequestMode::kCors);
+ request->SetMode(network::mojom::RequestMode::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::RequestMode::kCors);
}
// This is not yet standardized, but we can assume the following:
@@ -400,11 +401,11 @@ Request* Request::CreateRequestWithRequestOrString(
// "If |credentials| is non-null, set |request|'s credentials mode to
// |credentials|."
- network::mojom::FetchCredentialsMode credentials_mode;
+ network::mojom::CredentialsMode credentials_mode;
if (ParseCredentialsMode(init->credentials(), &credentials_mode)) {
request->SetCredentials(credentials_mode);
} else if (!input_request) {
- request->SetCredentials(network::mojom::FetchCredentialsMode::kSameOrigin);
+ request->SetCredentials(network::mojom::CredentialsMode::kSameOrigin);
}
// "If |init|'s cache member is present, set |request|'s cache mode to it."
@@ -425,7 +426,7 @@ Request* Request::CreateRequestWithRequestOrString(
// If |request|’s cache mode is "only-if-cached" and |request|’s mode is not
// "same-origin", then throw a TypeError.
if (request->CacheMode() == mojom::FetchCacheMode::kOnlyIfCached &&
- request->Mode() != network::mojom::FetchRequestMode::kSameOrigin) {
+ request->Mode() != network::mojom::RequestMode::kSameOrigin) {
exception_state.ThrowTypeError(
"'only-if-cached' can be set only with 'same-origin' mode");
return nullptr;
@@ -434,11 +435,11 @@ Request* Request::CreateRequestWithRequestOrString(
// "If |init|'s redirect member is present, set |request|'s redirect mode
// to it."
if (init->redirect() == "follow") {
- request->SetRedirect(network::mojom::FetchRedirectMode::kFollow);
+ request->SetRedirect(network::mojom::RedirectMode::kFollow);
} else if (init->redirect() == "error") {
- request->SetRedirect(network::mojom::FetchRedirectMode::kError);
+ request->SetRedirect(network::mojom::RedirectMode::kError);
} else if (init->redirect() == "manual") {
- request->SetRedirect(network::mojom::FetchRedirectMode::kManual);
+ request->SetRedirect(network::mojom::RedirectMode::kManual);
}
// "If |init|'s integrity member is present, set |request|'s
@@ -492,7 +493,7 @@ Request* Request::CreateRequestWithRequestOrString(
// "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::RequestMode::kNoCors) {
// "If |r|'s request's method is not a CORS-safelisted method, throw a
// TypeError."
if (!cors::IsCorsSafelistedMethod(r->GetRequest()->Method())) {
@@ -634,19 +635,18 @@ Request* Request::Create(
return MakeGarbageCollected<Request>(script_state, data);
}
-bool Request::ParseCredentialsMode(
- const String& credentials_mode,
- network::mojom::FetchCredentialsMode* result) {
+bool Request::ParseCredentialsMode(const String& credentials_mode,
+ network::mojom::CredentialsMode* result) {
if (credentials_mode == "omit") {
- *result = network::mojom::FetchCredentialsMode::kOmit;
+ *result = network::mojom::CredentialsMode::kOmit;
return true;
}
if (credentials_mode == "same-origin") {
- *result = network::mojom::FetchCredentialsMode::kSameOrigin;
+ *result = network::mojom::CredentialsMode::kSameOrigin;
return true;
}
if (credentials_mode == "include") {
- *result = network::mojom::FetchCredentialsMode::kInclude;
+ *result = network::mojom::CredentialsMode::kInclude;
return true;
}
return false;
@@ -682,7 +682,7 @@ const KURL& Request::url() const {
String Request::destination() const {
// "The destination attribute’s getter must return request’s destination."
- return FetchUtils::GetDestinationFromContext(request_->Context());
+ return GetRequestDestinationFromContext(request_->Context());
}
String Request::referrer() const {
@@ -724,14 +724,14 @@ String Request::mode() const {
// "The mode attribute's getter must return the value corresponding to the
// first matching statement, switching on request's mode:"
switch (request_->Mode()) {
- case network::mojom::FetchRequestMode::kSameOrigin:
+ case network::mojom::RequestMode::kSameOrigin:
return "same-origin";
- case network::mojom::FetchRequestMode::kNoCors:
+ case network::mojom::RequestMode::kNoCors:
return "no-cors";
- case network::mojom::FetchRequestMode::kCors:
- case network::mojom::FetchRequestMode::kCorsWithForcedPreflight:
+ case network::mojom::RequestMode::kCors:
+ case network::mojom::RequestMode::kCorsWithForcedPreflight:
return "cors";
- case network::mojom::FetchRequestMode::kNavigate:
+ case network::mojom::RequestMode::kNavigate:
return "navigate";
}
NOTREACHED();
@@ -743,11 +743,11 @@ String Request::credentials() const {
// to the first matching statement, switching on request's credentials
// mode:"
switch (request_->Credentials()) {
- case network::mojom::FetchCredentialsMode::kOmit:
+ case network::mojom::CredentialsMode::kOmit:
return "omit";
- case network::mojom::FetchCredentialsMode::kSameOrigin:
+ case network::mojom::CredentialsMode::kSameOrigin:
return "same-origin";
- case network::mojom::FetchCredentialsMode::kInclude:
+ case network::mojom::CredentialsMode::kInclude:
return "include";
}
NOTREACHED();
@@ -781,11 +781,11 @@ String Request::cache() const {
String Request::redirect() const {
// "The redirect attribute's getter must return request's redirect mode."
switch (request_->Redirect()) {
- case network::mojom::FetchRedirectMode::kFollow:
+ case network::mojom::RedirectMode::kFollow:
return "follow";
- case network::mojom::FetchRedirectMode::kError:
+ case network::mojom::RedirectMode::kError:
return "error";
- case network::mojom::FetchRedirectMode::kManual:
+ case network::mojom::RedirectMode::kManual:
return "manual";
}
NOTREACHED();
diff --git a/chromium/third_party/blink/renderer/core/fetch/request.h b/chromium/third_party/blink/renderer/core/fetch/request.h
index 9fdd88d662a..0f1cf26349e 100644
--- a/chromium/third_party/blink/renderer/core/fetch/request.h
+++ b/chromium/third_party/blink/renderer/core/fetch/request.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_FETCH_REQUEST_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_FETCH_REQUEST_H_
-#include "services/network/public/mojom/fetch_api.mojom-shared.h"
+#include "services/network/public/mojom/fetch_api.mojom-blink.h"
#include "third_party/blink/public/mojom/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"
@@ -64,7 +64,7 @@ class CORE_EXPORT Request final : public Body {
// Returns false if |credentials_mode| doesn't represent a valid credentials
// mode.
static bool ParseCredentialsMode(const String& credentials_mode,
- network::mojom::FetchCredentialsMode*);
+ network::mojom::CredentialsMode*);
// From Request.idl:
String method() const;
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 1e216e06088..59cd95d8a33 100644
--- a/chromium/third_party/blink/renderer/core/fetch/request_test.cc
+++ b/chromium/third_party/blink/renderer/core/fetch/request_test.cc
@@ -59,13 +59,13 @@ TEST(ServiceWorkerRequestTest, FromAndToFetchAPIRequest) {
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;
- const network::mojom::FetchCredentialsMode kCredentialsMode =
- network::mojom::FetchCredentialsMode::kInclude;
+ const network::mojom::RequestMode kMode =
+ network::mojom::RequestMode::kNavigate;
+ const network::mojom::CredentialsMode kCredentialsMode =
+ network::mojom::CredentialsMode::kInclude;
const auto kCacheMode = mojom::FetchCacheMode::kValidateCache;
- const network::mojom::FetchRedirectMode kRedirectMode =
- network::mojom::FetchRedirectMode::kError;
+ const network::mojom::RedirectMode kRedirectMode =
+ network::mojom::RedirectMode::kError;
fetch_api_request->url = url;
fetch_api_request->method = method;
diff --git a/chromium/third_party/blink/renderer/core/fetch/response.cc b/chromium/third_party/blink/renderer/core/fetch/response.cc
index b33f86b286b..b0c43c6f6fc 100644
--- a/chromium/third_party/blink/renderer/core/fetch/response.cc
+++ b/chromium/third_party/blink/renderer/core/fetch/response.cc
@@ -24,7 +24,6 @@
#include "third_party/blink/renderer/core/fetch/form_data_bytes_consumer.h"
#include "third_party/blink/renderer/core/fetch/response_init.h"
#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/typed_arrays/dom_array_buffer.h"
#include "third_party/blink/renderer/core/typed_arrays/dom_array_buffer_view.h"
@@ -32,6 +31,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/bindings/script_state.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.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/encoded_form_data.h"
@@ -55,7 +55,7 @@ FetchResponseData* FilterResponseData(
case network::mojom::FetchResponseType::kCors: {
WebHTTPHeaderSet header_names;
for (const auto& header : headers)
- header_names.insert(header.Ascii().data());
+ header_names.insert(header.Ascii());
return response->CreateCorsFilteredResponse(header_names);
break;
}
diff --git a/chromium/third_party/blink/renderer/core/fetch/testing/internals_fetch.h b/chromium/third_party/blink/renderer/core/fetch/testing/internals_fetch.h
index ebdeb1aca06..ea59f0db714 100644
--- a/chromium/third_party/blink/renderer/core/fetch/testing/internals_fetch.h
+++ b/chromium/third_party/blink/renderer/core/fetch/testing/internals_fetch.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_FETCH_TESTING_INTERNALS_FETCH_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_FETCH_TESTING_INTERNALS_FETCH_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
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 d1e38a97dde..9f0007b9d33 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
@@ -34,7 +34,7 @@ ScriptPromise WorkerInternalsFetch::getResourcePriority(
ScriptPromiseResolver* resolver =
MakeGarbageCollected<ScriptPromiseResolver>(script_state);
ScriptPromise promise = resolver->Promise();
- KURL resource_url = url_test_helpers::ToKURL(url.Utf8().data());
+ KURL resource_url = url_test_helpers::ToKURL(url.Utf8());
DCHECK(worker_global);
auto callback = WTF::Bind(&WorkerInternalsFetch::ResolveResourcePriority,
diff --git a/chromium/third_party/blink/renderer/core/fetch/testing/worker_internals_fetch.h b/chromium/third_party/blink/renderer/core/fetch/testing/worker_internals_fetch.h
index df884acbb22..e19f4375f1a 100644
--- a/chromium/third_party/blink/renderer/core/fetch/testing/worker_internals_fetch.h
+++ b/chromium/third_party/blink/renderer/core/fetch/testing/worker_internals_fetch.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_FETCH_TESTING_WORKER_INTERNALS_FETCH_H_
#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
diff --git a/chromium/third_party/blink/renderer/core/fileapi/blob.cc b/chromium/third_party/blink/renderer/core/fileapi/blob.cc
index 8880d6f345d..531ccb6574b 100644
--- a/chromium/third_party/blink/renderer/core/fileapi/blob.cc
+++ b/chromium/third_party/blink/renderer/core/fileapi/blob.cc
@@ -39,7 +39,6 @@
#include "third_party/blink/renderer/core/fileapi/blob_property_bag.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/use_counter.h"
#include "third_party/blink/renderer/core/streams/readable_stream_operations.h"
#include "third_party/blink/renderer/core/streams/readable_stream_wrapper.h"
#include "third_party/blink/renderer/core/url/dom_url.h"
@@ -47,6 +46,7 @@
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/blob/blob_registry.h"
#include "third_party/blink/renderer/platform/blob/blob_url.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/fileapi/file.cc b/chromium/third_party/blink/renderer/core/fileapi/file.cc
index bf49b29e867..28bd8a4c339 100644
--- a/chromium/third_party/blink/renderer/core/fileapi/file.cc
+++ b/chromium/third_party/blink/renderer/core/fileapi/file.cc
@@ -30,12 +30,12 @@
#include "third_party/blink/public/platform/file_path_conversion.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/core/fileapi/file_property_bag.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/forms/form_controller.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"
#include "third_party/blink/renderer/platform/file_metadata.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/network/mime/mime_type_registry.h"
#include "third_party/blink/renderer/platform/wtf/date_math.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
@@ -134,7 +134,7 @@ File* File::Create(
if (options->hasLastModified())
last_modified = static_cast<double>(options->lastModified());
else
- last_modified = CurrentTimeMS();
+ last_modified = base::Time::Now().ToDoubleT() * 1000.0;
DCHECK(options->hasEndings());
bool normalize_line_endings_to_native = options->endings() == "native";
if (normalize_line_endings_to_native)
@@ -301,7 +301,7 @@ double File::LastModifiedMS() const {
IsValidFileTime(modification_time_ms))
return modification_time_ms;
- return CurrentTimeMS();
+ return base::Time::Now().ToDoubleT() * 1000.0;
}
int64_t File::lastModified() const {
@@ -310,7 +310,7 @@ int64_t File::lastModified() const {
// The getter should return the current time when the last modification time
// isn't known.
if (!IsValidFileTime(modified_date))
- modified_date = CurrentTimeMS();
+ modified_date = base::Time::Now().ToDoubleT() * 1000.0;
// lastModified returns a number, not a Date instance,
// http://dev.w3.org/2006/webapi/FileAPI/#file-attrs
@@ -323,7 +323,7 @@ double File::lastModifiedDate() const {
// The getter should return the current time when the last modification time
// isn't known.
if (!IsValidFileTime(modified_date))
- modified_date = CurrentTimeMS();
+ modified_date = base::Time::Now().ToDoubleT() * 1000.0;
// lastModifiedDate returns a Date instance,
// http://www.w3.org/TR/FileAPI/#dfn-lastModifiedDate
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 2d52fa1a2d4..2623ec29c47 100644
--- a/chromium/third_party/blink/renderer/core/fileapi/file_reader.cc
+++ b/chromium/third_party/blink/renderer/core/fileapi/file_reader.cc
@@ -31,6 +31,7 @@
#include "third_party/blink/renderer/core/fileapi/file_reader.h"
#include "base/auto_reset.h"
+#include "base/timer/elapsed_timer.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/renderer/bindings/core/v8/string_or_array_buffer.h"
#include "third_party/blink/renderer/core/dom/document.h"
@@ -38,25 +39,24 @@
#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"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/supplementable.h"
#include "third_party/blink/renderer/platform/wtf/deque.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
-#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
namespace blink {
namespace {
-const CString Utf8BlobUUID(Blob* blob) {
+const std::string Utf8BlobUUID(Blob* blob) {
return blob->Uuid().Utf8();
}
-const CString Utf8FilePath(Blob* blob) {
+const std::string Utf8FilePath(Blob* blob) {
return blob->HasBackingFile() ? To<File>(blob)->GetPath().Utf8() : "";
}
@@ -66,7 +66,8 @@ const CString Utf8FilePath(Blob* blob) {
// excessive IPC congestion. We limit this to 100 per thread to throttle the
// requests (the value is arbitrarily chosen).
static const size_t kMaxOutstandingRequestsPerThread = 100;
-static const double kProgressNotificationIntervalMS = 50;
+static const base::TimeDelta kProgressNotificationInterval =
+ base::TimeDelta::FromMilliseconds(50);
class FileReader::ThrottlingController final
: public GarbageCollected<FileReader::ThrottlingController>,
@@ -201,8 +202,7 @@ FileReader::FileReader(ExecutionContext* context)
state_(kEmpty),
loading_state_(kLoadingStateNone),
still_firing_events_(false),
- read_type_(FileReaderLoader::kReadAsBinaryString),
- last_progress_notification_time_ms_(0) {}
+ read_type_(FileReaderLoader::kReadAsBinaryString) {}
FileReader::~FileReader() {
Terminate();
@@ -390,14 +390,13 @@ void FileReader::DidStartLoading() {
void FileReader::DidReceiveData() {
// Fire the progress event at least every 50ms.
- double now = CurrentTimeMS();
- if (!last_progress_notification_time_ms_) {
- last_progress_notification_time_ms_ = now;
- } else if (now - last_progress_notification_time_ms_ >
- kProgressNotificationIntervalMS) {
+ if (!last_progress_notification_time_) {
+ last_progress_notification_time_ = base::ElapsedTimer();
+ } else if (last_progress_notification_time_->Elapsed() >
+ kProgressNotificationInterval) {
base::AutoReset<bool> firing_events(&still_firing_events_, true);
FireEvent(event_type_names::kProgress);
- last_progress_notification_time_ms_ = now;
+ last_progress_notification_time_ = base::ElapsedTimer();
}
}
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 17ed1a4e701..a06639708c0 100644
--- a/chromium/third_party/blink/renderer/core/fileapi/file_reader.h
+++ b/chromium/third_party/blink/renderer/core/fileapi/file_reader.h
@@ -41,6 +41,10 @@
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
+namespace base {
+class ElapsedTimer;
+}
+
namespace blink {
class Blob;
@@ -131,7 +135,7 @@ class CORE_EXPORT FileReader final : public EventTargetWithInlineData,
std::unique_ptr<FileReaderLoader> loader_;
Member<DOMException> error_;
- double last_progress_notification_time_ms_;
+ base::Optional<base::ElapsedTimer> last_progress_notification_time_;
};
} // namespace blink
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 2d6f4196047..c63a32f28bb 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
@@ -47,7 +47,7 @@
#include "third_party/blink/renderer/core/typed_arrays/dom_array_buffer.h"
#include "third_party/blink/renderer/platform/blob/blob_registry.h"
#include "third_party/blink/renderer/platform/blob/blob_url.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_initiator_type_names.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_error.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h"
@@ -76,11 +76,10 @@ FileReaderLoader::FileReaderLoader(
mojo::SimpleWatcher::ArmingPolicy::AUTOMATIC,
task_runner ? task_runner : base::SequencedTaskRunnerHandle::Get()),
binding_(this),
- task_runner_(std::move(task_runner)),
- weak_factory_(this) {
+ task_runner_(std::move(task_runner)) {
// TODO(https://crbug.com/957651): Change this into a DCHECK once we figured
// out where code is passing in a null task runner,
- DCHECK(task_runner_);
+ CHECK(task_runner_);
}
FileReaderLoader::~FileReaderLoader() {
@@ -463,10 +462,10 @@ String FileReaderLoader::ConvertToDataURL() {
builder.Append(";base64,");
Vector<char> out;
- Base64Encode(static_cast<const char*>(raw_data_->Data()),
- static_cast<unsigned>(bytes_loaded_), out);
- out.push_back('\0');
- builder.Append(out.data());
+ Base64Encode(base::make_span(static_cast<const uint8_t*>(raw_data_->Data()),
+ SafeCast<unsigned>(bytes_loaded_)),
+ out);
+ builder.Append(out.data(), out.size());
return builder.ToString();
}
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 f486c798bc1..d460a3f50c9 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
@@ -185,7 +185,7 @@ class CORE_EXPORT FileReaderLoader : public mojom::blink::BlobReaderClient {
scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
- base::WeakPtrFactory<FileReaderLoader> weak_factory_;
+ base::WeakPtrFactory<FileReaderLoader> weak_factory_{this};
};
} // 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 b011ab2af11..f38d4d5c035 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
@@ -39,7 +39,7 @@
#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/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/fileapi/url_file_api.cc b/chromium/third_party/blink/renderer/core/fileapi/url_file_api.cc
index 2a253e03531..9ddcb05354f 100644
--- a/chromium/third_party/blink/renderer/core/fileapi/url_file_api.cc
+++ b/chromium/third_party/blink/renderer/core/fileapi/url_file_api.cc
@@ -7,10 +7,10 @@
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/fileapi/blob.h"
#include "third_party/blink/renderer/core/fileapi/public_url_manager.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/url/dom_url.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/instrumentation/use_counter.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/fileapi/url_file_api.h b/chromium/third_party/blink/renderer/core/fileapi/url_file_api.h
index dcab4f27217..c9b47ad1dda 100644
--- a/chromium/third_party/blink/renderer/core/fileapi/url_file_api.h
+++ b/chromium/third_party/blink/renderer/core/fileapi/url_file_api.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_FILEAPI_URL_FILE_API_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_FILEAPI_URL_FILE_API_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/frame/BUILD.gn b/chromium/third_party/blink/renderer/core/frame/BUILD.gn
index 03647d38e3f..cd9e30c1a9e 100644
--- a/chromium/third_party/blink/renderer/core/frame/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/frame/BUILD.gn
@@ -171,8 +171,8 @@ blink_core_sources("frame") {
"smart_clip.cc",
"smart_clip.h",
"test_report_body.h",
- "use_counter.cc",
- "use_counter.h",
+ "use_counter_helper.cc",
+ "use_counter_helper.h",
"user_activation.cc",
"user_activation.h",
"viewport_data.cc",
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 5d16464ee7f..2a88349022c 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
@@ -12,6 +12,7 @@
#include "third_party/blink/renderer/core/testing/dummy_page_holder.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/runtime_enabled_features_test_helpers.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
namespace blink {
@@ -235,6 +236,10 @@ TEST_F(AdTrackerSimTest, ScriptLoadedWhileExecutingAdScript) {
script.src = "vanilla_script.js";
document.body.appendChild(script);
)SCRIPT");
+
+ // Wait for script to run.
+ base::RunLoop().RunUntilIdle();
+
vanilla_script.Complete("");
EXPECT_TRUE(IsKnownAdScript(&GetDocument(), kAdUrl));
@@ -257,6 +262,9 @@ TEST_F(AdTrackerSimTest, ScriptDetectedByContext) {
document.body.appendChild(frame);
)SCRIPT");
+ // Wait for script to run.
+ base::RunLoop().RunUntilIdle();
+
// The child frame should be an ad subframe.
auto* child_frame =
To<LocalFrame>(GetDocument().GetFrame()->Tree().FirstChild());
@@ -305,6 +313,9 @@ TEST_F(AdTrackerSimTest, AdResourceDetectedByContext) {
document.body.appendChild(frame);
)SCRIPT");
+ // Wait for script to run.
+ base::RunLoop().RunUntilIdle();
+
// The child frame should be an ad subframe.
auto* child_frame =
To<LocalFrame>(GetDocument().GetFrame()->Tree().FirstChild());
@@ -337,6 +348,9 @@ TEST_F(AdTrackerSimTest, InlineAdScriptRunningInNonAdContext) {
document.body.appendChild(frame);
)SCRIPT");
+ // Wait for script to run.
+ base::RunLoop().RunUntilIdle();
+
// Verify that the new frame is an ad frame.
EXPECT_TRUE(To<LocalFrame>(GetDocument().GetFrame()->Tree().FirstChild())
->IsAdSubframe());
@@ -373,6 +387,10 @@ TEST_F(AdTrackerSimTest, ImageLoadedWhileExecutingAdScript) {
image.src = "vanilla_image.jpg";
document.body.appendChild(image);
)SCRIPT");
+
+ // Wait for script to run.
+ base::RunLoop().RunUntilIdle();
+
vanilla_image.Complete("");
EXPECT_TRUE(IsKnownAdScript(&GetDocument(), kAdUrl));
@@ -399,6 +417,10 @@ TEST_F(AdTrackerSimTest, FrameLoadedWhileExecutingAdScript) {
iframe.src = "vanilla_page.html";
document.body.appendChild(iframe);
)SCRIPT");
+
+ // Wait for script to run.
+ base::RunLoop().RunUntilIdle();
+
vanilla_page.Complete("<img src=vanilla_img.jpg></img>");
vanilla_image.Complete("");
@@ -465,6 +487,9 @@ TEST_F(AdTrackerSimTest, SameOriginSubframeFromAdScript) {
document.body.appendChild(iframe);
)SCRIPT");
+ // Wait for script to run.
+ base::RunLoop().RunUntilIdle();
+
iframe_resource.Complete("iframe data");
Frame* subframe = GetDocument().GetFrame()->Tree().FirstChild();
@@ -489,16 +514,19 @@ TEST_F(AdTrackerSimTest, SameOriginDocWrittenSubframeFromAdScript) {
iframeDocument.close();
)SCRIPT");
+ // Wait for script to run.
+ base::RunLoop().RunUntilIdle();
+
Frame* subframe = GetDocument().GetFrame()->Tree().FirstChild();
auto* local_subframe = To<LocalFrame>(subframe);
EXPECT_TRUE(local_subframe->IsAdSubframe());
}
-class AdTrackerDisabledSimTest : public SimTest {
+class AdTrackerDisabledSimTest : public SimTest,
+ private ScopedAdTaggingForTest {
protected:
+ AdTrackerDisabledSimTest() : ScopedAdTaggingForTest(false) {}
void SetUp() override {
- RuntimeEnabledFeatures::SetAdTaggingEnabled(false);
-
SimTest::SetUp();
main_resource_ = std::make_unique<SimRequest>(
"https://example.com/test.html", "text/html");
diff --git a/chromium/third_party/blink/renderer/core/frame/bar_prop.idl b/chromium/third_party/blink/renderer/core/frame/bar_prop.idl
index 6bd3b1c6162..9f6d18ec281 100644
--- a/chromium/third_party/blink/renderer/core/frame/bar_prop.idl
+++ b/chromium/third_party/blink/renderer/core/frame/bar_prop.idl
@@ -28,6 +28,8 @@
// https://html.spec.whatwg.org/C/#barprop
-interface BarProp {
+[
+ Exposed=Window
+] interface BarProp {
readonly attribute boolean visible;
};
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 6ff88e8b7b1..f95aef0f089 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
@@ -147,9 +147,9 @@ class BrowserControlsTest : public testing::Test {
}
private:
+ ScopedTestingPlatformSupport<TestingPlatformSupport> platform_;
std::string base_url_;
frame_test_helpers::WebViewHelper helper_;
- ScopedTestingPlatformSupport<TestingPlatformSupport> platform_;
};
class BrowserControlsSimTest : public SimTest {
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 d5c937ca453..ba49eb0fa8a 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
@@ -27,7 +27,6 @@
#include <memory>
#include <utility>
-#include <vector>
#include "third_party/blink/public/mojom/net/ip_address_space.mojom-blink.h"
#include "third_party/blink/public/platform/platform.h"
@@ -51,10 +50,10 @@
#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/frame/sandbox_flags.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/html_script_element.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/platform/bindings/dom_wrapper_world.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.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"
@@ -158,6 +157,10 @@ ContentSecurityPolicy::ContentSecurityPolicy()
require_trusted_types_(false),
insecure_request_policy_(kLeaveInsecureRequestsAlone) {}
+bool ContentSecurityPolicy::IsBound() {
+ return delegate_;
+}
+
void ContentSecurityPolicy::BindToDelegate(
ContentSecurityPolicyDelegate& delegate) {
// TODO(crbug.com/915954): Add DCHECK(!delegate_). It seems some call sites
@@ -185,10 +188,11 @@ void ContentSecurityPolicy::SetupSelf(const ContentSecurityPolicy& other) {
void ContentSecurityPolicy::ApplyPolicySideEffectsToDelegate() {
DCHECK(delegate_);
- const SecurityOrigin* security_origin = delegate_->GetSecurityOrigin();
- DCHECK(security_origin);
+ const SecurityOrigin* self_origin =
+ delegate_->GetSecurityOrigin()->GetOriginOrPrecursorOriginIfOpaque();
+ DCHECK(self_origin);
- SetupSelf(*security_origin);
+ SetupSelf(*self_origin);
// Set mixed content checking and sandbox flags, then dump all the parsing
// error messages, then poke at histograms.
@@ -345,10 +349,7 @@ void ContentSecurityPolicy::AddPolicyFromHeaderValue(
Member<CSPDirectiveList> policy =
CSPDirectiveList::Create(this, begin, position, type, source);
- if (!policy->AllowEval(nullptr,
- SecurityViolationReportingPolicy::kSuppressReporting,
- kWillNotThrowException, g_empty_string) &&
- disable_eval_error_message_.IsNull()) {
+ if (policy->ShouldDisableEval() && disable_eval_error_message_.IsNull()) {
disable_eval_error_message_ = policy->EvalDisabledErrorMessage();
}
@@ -557,9 +558,7 @@ bool ContentSecurityPolicy::AllowWasmEval(
String ContentSecurityPolicy::EvalDisabledErrorMessage() const {
for (const auto& policy : policies_) {
- if (!policy->AllowEval(nullptr,
- SecurityViolationReportingPolicy::kSuppressReporting,
- kWillNotThrowException, g_empty_string)) {
+ if (policy->ShouldDisableEval()) {
return policy->EvalDisabledErrorMessage();
}
}
@@ -844,10 +843,11 @@ bool ContentSecurityPolicy::IsFrameAncestorsEnforced() const {
}
bool ContentSecurityPolicy::AllowTrustedTypeAssignmentFailure(
- const String& message) const {
+ const String& message,
+ const String& sample) const {
bool allow = true;
for (const auto& policy : policies_) {
- allow &= policy->AllowTrustedTypeAssignmentFailure(message);
+ allow &= policy->AllowTrustedTypeAssignmentFailure(message, sample);
}
return allow;
}
@@ -1615,14 +1615,11 @@ bool ContentSecurityPolicy::IsValidCSPAttr(const String& attr,
WebContentSecurityPolicyList
ContentSecurityPolicy::ExposeForNavigationalChecks() const {
- std::vector<WebContentSecurityPolicy> policies;
+ WebContentSecurityPolicyList list;
for (const auto& policy : policies_) {
- policies.push_back(policy->ExposeForNavigationalChecks());
+ list.policies.emplace_back(policy->ExposeForNavigationalChecks());
}
- WebContentSecurityPolicyList list;
- list.policies = policies;
-
if (self_source_)
list.self_source = self_source_->ExposeForNavigationalChecks();
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 7a2d6bd72ab..cb2b5a4271e 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
@@ -29,7 +29,7 @@
#include <memory>
#include <utility>
-#include "third_party/blink/public/mojom/devtools/console_message.mojom-shared.h"
+#include "third_party/blink/public/mojom/devtools/console_message.mojom-blink.h"
#include "third_party/blink/public/platform/web_content_security_policy_struct.h"
#include "third_party/blink/public/platform/web_insecure_request_policy.h"
#include "third_party/blink/renderer/bindings/core/v8/source_location.h"
@@ -211,6 +211,7 @@ class CORE_EXPORT ContentSecurityPolicy
~ContentSecurityPolicy();
void Trace(blink::Visitor*);
+ bool IsBound();
void BindToDelegate(ContentSecurityPolicyDelegate&);
void SetupSelf(const SecurityOrigin&);
void SetupSelf(const ContentSecurityPolicy&);
@@ -339,7 +340,8 @@ class CORE_EXPORT ContentSecurityPolicy
// Determine whether to enforce the assignment failure. Also handle reporting.
// Returns whether enforcing Trusted Types CSP directives are present.
- bool AllowTrustedTypeAssignmentFailure(const String& message) const;
+ bool AllowTrustedTypeAssignmentFailure(const String& message,
+ const String& sample = String()) const;
void UsesScriptHashAlgorithms(uint8_t content_security_policy_hash_algorithm);
void UsesStyleHashAlgorithms(uint8_t content_security_policy_hash_algorithm);
diff --git a/chromium/third_party/blink/renderer/core/frame/csp/content_security_policy_fuzzer.cc b/chromium/third_party/blink/renderer/core/frame/csp/content_security_policy_fuzzer.cc
index cbb2f652ddc..c296c9565f6 100644
--- a/chromium/third_party/blink/renderer/core/frame/csp/content_security_policy_fuzzer.cc
+++ b/chromium/third_party/blink/renderer/core/frame/csp/content_security_policy_fuzzer.cc
@@ -7,6 +7,7 @@
#include "third_party/blink/renderer/core/testing/dummy_page_holder.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/heap/thread_state.h"
+#include "third_party/blink/renderer/platform/shared_buffer.h"
#include "third_party/blink/renderer/platform/testing/blink_fuzzer_test_support.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
@@ -22,6 +23,14 @@ int LLVMFuzzerInitialize(int* argc, char*** argv) {
// that Oilpan be initialized to access blink::ThreadState::Current.
LEAK_SANITIZER_DISABLED_SCOPE;
g_page_holder = std::make_unique<DummyPageHolder>().release();
+
+ // Set loader sandbox flags and install a new document so the document
+ // has all possible sandbox flags set on the document already when the
+ // CSP is bound.
+ scoped_refptr<SharedBuffer> empty_document_data = SharedBuffer::Create();
+ g_page_holder->GetFrame().Loader().ForceSandboxFlags(WebSandboxFlags::kAll);
+ g_page_holder->GetFrame().ForceSynchronousDocumentInstall(
+ "text/html", empty_document_data);
return 0;
}
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 976e248bab8..6919bd04a51 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
@@ -69,9 +69,10 @@ TEST_F(ContentSecurityPolicyTest, ParseInsecureRequestPolicy) {
kContentSecurityPolicyHeaderSourceHTTP);
EXPECT_EQ(test.expected_policy, csp->GetInsecureRequestPolicy());
- auto* document = MakeGarbageCollected<Document>();
- document->SetSecurityOrigin(secure_origin);
- document->SetURL(secure_url);
+ DocumentInit init = DocumentInit::Create()
+ .WithOriginToCommit(secure_origin)
+ .WithURL(secure_url);
+ auto* document = MakeGarbageCollected<Document>(init);
csp->BindToDelegate(document->GetContentSecurityPolicyDelegate());
EXPECT_EQ(test.expected_policy, document->GetInsecureRequestPolicy());
bool expect_upgrade = test.expected_policy & kUpgradeInsecureRequests;
@@ -238,12 +239,14 @@ TEST_F(ContentSecurityPolicyTest, FrameAncestorsInMeta) {
// delivered in <meta> elements.
TEST_F(ContentSecurityPolicyTest, SandboxInMeta) {
csp->BindToDelegate(execution_context->GetContentSecurityPolicyDelegate());
+ EXPECT_EQ(WebSandboxFlags::kNone, csp->GetSandboxMask());
csp->DidReceiveHeader("sandbox;", kContentSecurityPolicyHeaderTypeEnforce,
kContentSecurityPolicyHeaderSourceMeta);
- EXPECT_FALSE(execution_context->GetSecurityOrigin()->IsOpaque());
+ EXPECT_EQ(WebSandboxFlags::kNone, csp->GetSandboxMask());
+ execution_context->SetSandboxFlags(WebSandboxFlags::kAll);
csp->DidReceiveHeader("sandbox;", kContentSecurityPolicyHeaderTypeEnforce,
kContentSecurityPolicyHeaderSourceHTTP);
- EXPECT_TRUE(execution_context->GetSecurityOrigin()->IsOpaque());
+ EXPECT_EQ(WebSandboxFlags::kAll, csp->GetSandboxMask());
}
// Tests that report-uri directives are discarded from policies
@@ -720,8 +723,8 @@ TEST_F(ContentSecurityPolicyTest, NonceInline) {
WTF::OrdinalNumber context_line;
// We need document for HTMLScriptElement tests.
- auto* document = MakeGarbageCollected<Document>();
- document->SetSecurityOrigin(secure_origin);
+ DocumentInit init = DocumentInit::Create().WithOriginToCommit(secure_origin);
+ auto* document = MakeGarbageCollected<Document>(init);
for (const auto& test : cases) {
SCOPED_TRACE(testing::Message() << "Policy: `" << test.policy
@@ -1598,4 +1601,23 @@ TEST_F(ContentSecurityPolicyTest, EmptyCSPIsNoOp) {
csp->HasPolicyFromSource(kContentSecurityPolicyHeaderSourceHTTP));
}
+TEST_F(ContentSecurityPolicyTest, OpaqueOriginBeforeBind) {
+ const KURL url("https://example.test");
+
+ // Security Origin of execution context might change when sandbox flags
+ // are applied. This shouldn't change the application of the 'self'
+ // determination.
+ secure_origin = secure_origin->DeriveNewOpaqueOrigin();
+ execution_context = CreateExecutionContext();
+ csp->BindToDelegate(execution_context->GetContentSecurityPolicyDelegate());
+ csp->DidReceiveHeader("default-src 'self';",
+ kContentSecurityPolicyHeaderTypeEnforce,
+ kContentSecurityPolicyHeaderSourceMeta);
+ EXPECT_TRUE(
+ csp->AllowRequest(mojom::RequestContextType::SUBRESOURCE, url, String(),
+ IntegrityMetadataSet(), kParserInserted,
+ ResourceRequest::RedirectStatus::kNoRedirect,
+ SecurityViolationReportingPolicy::kSuppressReporting));
+}
+
} // namespace blink
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 d4ebebcb350..ff18a796013 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
@@ -6,7 +6,6 @@
#include <memory>
#include <utility>
-#include <vector>
#include "services/network/public/cpp/features.h"
#include "third_party/blink/renderer/bindings/core/v8/source_location.h"
@@ -15,10 +14,10 @@
#include "third_party/blink/renderer/core/execution_context/security_context.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/use_counter.h"
#include "third_party/blink/renderer/core/html/html_script_element.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/platform/crypto.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/network/content_security_policy_parsers.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/wtf/text/base64.h"
@@ -40,8 +39,7 @@ String GetSha256String(const String& content) {
return "sha256-...";
}
- return "sha256-" + Base64Encode(reinterpret_cast<char*>(digest.data()),
- digest.size(), kBase64DoNotInsertLFs);
+ return "sha256-" + Base64Encode(digest);
}
ContentSecurityPolicyHashAlgorithm ConvertHashAlgorithmToCSPHashAlgorithm(
@@ -162,6 +160,11 @@ CSPDirectiveList* CSPDirectiveList::Create(
->GetText() +
"\".\n";
directives->SetEvalDisabledErrorMessage(message);
+ } else if (directives->trusted_types_) {
+ String message =
+ "Refused to evaluate a string as JavaScript because this document "
+ "requires 'Trusted Type' assignment.";
+ directives->SetEvalDisabledErrorMessage(message);
}
if (directives->IsReportOnly() &&
@@ -180,7 +183,8 @@ void CSPDirectiveList::ReportViolation(
const String& console_message,
const KURL& blocked_url,
ResourceRequest::RedirectStatus redirect_status,
- ContentSecurityPolicy::ViolationType violation_type) const {
+ ContentSecurityPolicy::ViolationType violation_type,
+ const String& sample) const {
String message =
IsReportOnly() ? "[Report Only] " + console_message : console_message;
policy_->LogToConsole(
@@ -191,7 +195,9 @@ void CSPDirectiveList::ReportViolation(
header_type_, violation_type,
std::unique_ptr<SourceLocation>(),
nullptr, // localFrame
- redirect_status);
+ redirect_status,
+ nullptr, // Element*
+ sample);
}
void CSPDirectiveList::ReportViolationWithFrame(
@@ -324,7 +330,8 @@ void CSPDirectiveList::ReportMixedContent(
}
bool CSPDirectiveList::AllowTrustedTypeAssignmentFailure(
- const String& message) const {
+ const String& message,
+ const String& sample) const {
if (!trusted_types_)
return true;
@@ -332,7 +339,7 @@ bool CSPDirectiveList::AllowTrustedTypeAssignmentFailure(
ContentSecurityPolicy::DirectiveType::kTrustedTypes),
ContentSecurityPolicy::DirectiveType::kTrustedTypes, message,
KURL(), RedirectStatus::kFollowedRedirect,
- ContentSecurityPolicy::kTrustedTypesViolation);
+ ContentSecurityPolicy::kTrustedTypesViolation, sample);
return IsReportOnly();
}
@@ -773,6 +780,16 @@ bool CSPDirectiveList::AllowWasmEval(
ContentSecurityPolicy::DirectiveType::kScriptSrc));
}
+bool CSPDirectiveList::ShouldDisableEvalBecauseScriptSrc() const {
+ return !AllowEval(
+ nullptr, SecurityViolationReportingPolicy::kSuppressReporting,
+ ContentSecurityPolicy::kWillNotThrowException, g_empty_string);
+}
+
+bool CSPDirectiveList::ShouldDisableEvalBecauseTrustedTypes() const {
+ return trusted_types_;
+}
+
bool CSPDirectiveList::AllowPluginType(
const String& type,
const String& type_attribute,
@@ -859,8 +876,8 @@ bool CSPDirectiveList::AllowTrustedTypePolicy(const String& policy_name) const {
"Refused to create a TrustedTypePolicy named '%s' because "
"it violates the following Content Security Policy directive: "
"\"%s\".",
- policy_name.Utf8().data(),
- trusted_types_.Get()->GetText().Utf8().data()),
+ policy_name.Utf8().c_str(),
+ trusted_types_.Get()->GetText().Utf8().c_str()),
KURL(), RedirectStatus::kNoRedirect);
return DenyIfEnforcingPolicy();
@@ -1576,31 +1593,26 @@ WebContentSecurityPolicy CSPDirectiveList::ExposeForNavigationalChecks() const {
policy.disposition =
static_cast<mojom::ContentSecurityPolicyType>(header_type_);
policy.source = static_cast<WebContentSecurityPolicySource>(header_source_);
- std::vector<WebContentSecurityPolicyDirective> directives;
for (const auto& directive :
{child_src_, default_src_, form_action_, frame_src_, navigate_to_}) {
if (directive) {
- directives.push_back(WebContentSecurityPolicyDirective{
+ policy.directives.emplace_back(WebContentSecurityPolicyDirective{
directive->DirectiveName(),
directive->ExposeForNavigationalChecks()});
}
}
if (upgrade_insecure_requests_) {
- directives.push_back(WebContentSecurityPolicyDirective{
+ policy.directives.emplace_back(WebContentSecurityPolicyDirective{
blink::WebString("upgrade-insecure-requests"),
WebContentSecurityPolicySourceList()});
}
- policy.directives = directives;
- std::vector<WebString> report_endpoints;
for (const auto& report_endpoint : ReportEndpoints()) {
- report_endpoints.push_back(report_endpoint);
+ policy.report_endpoints.emplace_back(report_endpoint);
}
policy.use_reporting_api = use_reporting_api_;
- policy.report_endpoints = report_endpoints;
-
policy.header = Header();
return policy;
diff --git a/chromium/third_party/blink/renderer/core/frame/csp/csp_directive_list.h b/chromium/third_party/blink/renderer/core/frame/csp/csp_directive_list.h
index 27af666ad57..264b22dab5b 100644
--- a/chromium/third_party/blink/renderer/core/frame/csp/csp_directive_list.h
+++ b/chromium/third_party/blink/renderer/core/frame/csp/csp_directive_list.h
@@ -100,7 +100,8 @@ class CORE_EXPORT CSPDirectiveList
ResourceRequest::RedirectStatus,
SecurityViolationReportingPolicy) const;
- bool AllowTrustedTypeAssignmentFailure(const String& message) const;
+ bool AllowTrustedTypeAssignmentFailure(const String& message,
+ const String& sample) const;
bool StrictMixedContentChecking() const {
return strict_mixed_content_checking_enforced_;
@@ -108,6 +109,12 @@ class CORE_EXPORT CSPDirectiveList
void ReportMixedContent(const KURL& mixed_url,
ResourceRequest::RedirectStatus) const;
+ bool ShouldDisableEval() const {
+ return ShouldDisableEvalBecauseScriptSrc() ||
+ ShouldDisableEvalBecauseTrustedTypes();
+ }
+ bool ShouldDisableEvalBecauseScriptSrc() const;
+ bool ShouldDisableEvalBecauseTrustedTypes() const;
const String& EvalDisabledErrorMessage() const {
return eval_disabled_error_message_;
}
@@ -194,7 +201,8 @@ class CORE_EXPORT CSPDirectiveList
const KURL& blocked_url,
ResourceRequest::RedirectStatus,
ContentSecurityPolicy::ViolationType violation_type =
- ContentSecurityPolicy::kURLViolation) const;
+ ContentSecurityPolicy::kURLViolation,
+ const String& sample = String()) const;
void ReportViolationWithFrame(const String& directive_text,
const ContentSecurityPolicy::DirectiveType,
const String& console_message,
diff --git a/chromium/third_party/blink/renderer/core/frame/csp/csp_directive_list_test.cc b/chromium/third_party/blink/renderer/core/frame/csp/csp_directive_list_test.cc
index 019d3ce3bb0..c9d152575b5 100644
--- a/chromium/third_party/blink/renderer/core/frame/csp/csp_directive_list_test.cc
+++ b/chromium/third_party/blink/renderer/core/frame/csp/csp_directive_list_test.cc
@@ -6,7 +6,6 @@
#include <list>
#include <string>
-#include <vector>
#include "base/test/scoped_feature_list.h"
#include "services/network/public/cpp/features.h"
@@ -665,7 +664,7 @@ TEST_F(CSPDirectiveListTest, SubsumesBasedOnCSPSourcesOnly) {
kContentSecurityPolicyHeaderTypeEnforce);
struct TestCase {
- const std::vector<const char*> policies;
+ const Vector<const char*> policies;
bool expected;
bool expected_first_policy_opposite;
} cases[] = {
@@ -743,7 +742,7 @@ TEST_F(CSPDirectiveListTest, SubsumesBasedOnCSPSourcesOnly) {
TEST_F(CSPDirectiveListTest, SubsumesIfNoneIsPresent) {
struct TestCase {
const char* policy_a;
- const std::vector<const char*> policies_b;
+ const Vector<const char*> policies_b;
bool expected;
} cases[] = {
// `policyA` subsumes any vector of policies.
@@ -844,7 +843,7 @@ TEST_F(CSPDirectiveListTest, SubsumesIfNoneIsPresent) {
TEST_F(CSPDirectiveListTest, SubsumesPluginTypes) {
struct TestCase {
const char* policy_a;
- const std::vector<const char*> policies_b;
+ const Vector<const char*> policies_b;
bool expected;
} cases[] = {
// `policyA` subsumes `policiesB`.
@@ -926,7 +925,7 @@ TEST_F(CSPDirectiveListTest, SubsumesPluginTypes) {
TEST_F(CSPDirectiveListTest, OperativeDirectiveGivenType) {
struct TestCase {
ContentSecurityPolicy::DirectiveType directive;
- std::vector<ContentSecurityPolicy::DirectiveType> fallback_list;
+ Vector<ContentSecurityPolicy::DirectiveType> fallback_list;
} cases[] = {
// Directives with default directive.
{ContentSecurityPolicy::DirectiveType::kChildSrc,
@@ -986,12 +985,12 @@ TEST_F(CSPDirectiveListTest, OperativeDirectiveGivenType) {
EXPECT_FALSE(empty->OperativeDirective(test.directive));
// Add the directive itself as it should be the first one to be returned.
- test.fallback_list.insert(test.fallback_list.begin(), test.directive);
+ test.fallback_list.push_front(test.directive);
// Start the tests with all directives present.
directive_string = all_directives.str();
- while (!test.fallback_list.empty()) {
+ while (!test.fallback_list.IsEmpty()) {
directive_list = CreateList(directive_string.c_str(),
kContentSecurityPolicyHeaderTypeEnforce);
@@ -1032,7 +1031,7 @@ TEST_F(CSPDirectiveListTest, OperativeDirectiveGivenType) {
}
TEST_F(CSPDirectiveListTest, GetSourceVector) {
- const std::vector<const char*> policies = {
+ const Vector<const char*> policies = {
// Policy 1
"default-src https://default-src.com",
// Policy 2
diff --git a/chromium/third_party/blink/renderer/core/frame/csp/csp_source.cc b/chromium/third_party/blink/renderer/core/frame/csp/csp_source.cc
index 6d6a493bf7e..14146af76c4 100644
--- a/chromium/third_party/blink/renderer/core/frame/csp/csp_source.cc
+++ b/chromium/third_party/blink/renderer/core/frame/csp/csp_source.cc
@@ -6,7 +6,7 @@
#include "third_party/blink/public/platform/web_content_security_policy_struct.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/weborigin/known_ports.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
diff --git a/chromium/third_party/blink/renderer/core/frame/csp/csp_source.h b/chromium/third_party/blink/renderer/core/frame/csp/csp_source.h
index b749204b167..23c02f720d7 100644
--- a/chromium/third_party/blink/renderer/core/frame/csp/csp_source.h
+++ b/chromium/third_party/blink/renderer/core/frame/csp/csp_source.h
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_request.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/frame/csp/execution_context_csp_delegate.cc b/chromium/third_party/blink/renderer/core/frame/csp/execution_context_csp_delegate.cc
index e20d974e509..2521361469e 100644
--- a/chromium/third_party/blink/renderer/core/frame/csp/execution_context_csp_delegate.cc
+++ b/chromium/third_party/blink/renderer/core/frame/csp/execution_context_csp_delegate.cc
@@ -14,11 +14,11 @@
#include "third_party/blink/renderer/core/frame/local_frame_client.h"
#include "third_party/blink/renderer/core/frame/report.h"
#include "third_party/blink/renderer/core/frame/reporting_context.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/loader/document_loader.h"
#include "third_party/blink/renderer/core/loader/ping_loader.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/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/network/encoded_form_data.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
@@ -43,7 +43,25 @@ const KURL& ExecutionContextCSPDelegate::Url() const {
}
void ExecutionContextCSPDelegate::SetSandboxFlags(SandboxFlags mask) {
- GetSecurityContext().EnforceSandboxFlags(mask);
+ // Ideally sandbox flags are determined at construction time since
+ // sandbox flags influence the security origin and that influences
+ // the Agent that is assigned for the ExecutionContext. Changing
+ // an ExecutionContext's agent in the middle of an object lifecycle
+ // is not permitted.
+
+ // Since Workers and Worklets don't share agents (each one is unique)
+ // we allow them to apply new sandbox flags on top of the current ones.
+ WorkerOrWorkletGlobalScope* worklet_or_worker =
+ DynamicTo<WorkerOrWorkletGlobalScope>(execution_context_.Get());
+ if (worklet_or_worker) {
+ worklet_or_worker->ApplySandboxFlags(mask);
+ }
+ // Just check that all the sandbox flags that are set by CSP have
+ // already been set on the security context. Meta tags can't set them
+ // and we should have already constructed the document with the correct
+ // sandbox flags from CSP already.
+ WebSandboxFlags flags = GetSecurityContext().GetSandboxFlags();
+ CHECK_EQ(flags | mask, flags);
}
void ExecutionContextCSPDelegate::SetAddressSpace(mojom::IPAddressSpace space) {
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 1176f045c4d..3436ce31d89 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
@@ -6,6 +6,7 @@
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
+#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
@@ -26,12 +27,12 @@ TEST_F(MediaListDirectiveTest, GetIntersect) {
struct TestCase {
const char* policy_b;
- const std::vector<const char*> expected;
+ const Vector<const char*> expected;
} cases[] = {
- {"", std::vector<const char*>()},
- {"text/", std::vector<const char*>()},
- {"text/*", std::vector<const char*>()},
- {"*/plain", std::vector<const char*>()},
+ {"", Vector<const char*>()},
+ {"text/", Vector<const char*>()},
+ {"text/*", Vector<const char*>()},
+ {"*/plain", Vector<const char*>()},
{"text/plain */plain", {"text/plain"}},
{"text/plain application/*", {"text/plain"}},
{"text/plain", {"text/plain"}},
@@ -73,7 +74,7 @@ TEST_F(MediaListDirectiveTest, Subsumes) {
csp.Get());
struct TestCase {
- const std::vector<const char*> policies_b;
+ const Vector<const char*> policies_b;
bool subsumed;
bool subsumed_by_empty_a;
} cases[] = {
@@ -119,7 +120,7 @@ TEST_F(MediaListDirectiveTest, Subsumes) {
true,
true},
// `A` does not subsumes `policiesB`.
- {std::vector<const char*>(), false, false},
+ {Vector<const char*>(), false, false},
{{"application/x-blink-test-plugin"}, false, false},
{{"application/x-shockwave-flash text/plain "
"application/x-blink-test-plugin"},
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 1db6529e2db..83bd3d8d2b1 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
@@ -4,8 +4,6 @@
#include "third_party/blink/renderer/core/frame/csp/source_list_directive.h"
-#include <vector>
-
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
@@ -36,8 +34,9 @@ class SourceListDirectiveTest : public testing::Test {
KURL secure_url("https://example.test/image.png");
scoped_refptr<SecurityOrigin> secure_origin(
SecurityOrigin::Create(secure_url));
- document = MakeGarbageCollected<Document>();
- document->SetSecurityOrigin(secure_origin);
+ DocumentInit init =
+ DocumentInit::Create().WithOriginToCommit(secure_origin);
+ document = MakeGarbageCollected<Document>(init);
csp->BindToDelegate(document->GetContentSecurityPolicyDelegate());
}
@@ -45,8 +44,9 @@ class SourceListDirectiveTest : public testing::Test {
KURL secure_url(origin);
scoped_refptr<SecurityOrigin> secure_origin(
SecurityOrigin::Create(secure_url));
- auto* document = MakeGarbageCollected<Document>();
- document->SetSecurityOrigin(secure_origin);
+ DocumentInit init =
+ DocumentInit::Create().WithOriginToCommit(secure_origin);
+ auto* document = MakeGarbageCollected<Document>(init);
auto* csp = MakeGarbageCollected<ContentSecurityPolicy>();
csp->BindToDelegate(document->GetContentSecurityPolicyDelegate());
return csp;
@@ -351,7 +351,7 @@ TEST_F(SourceListDirectiveTest, Subsumes) {
SourceListDirective required("script-src", required_sources, csp.Get());
struct TestCase {
- std::vector<String> sources_vector;
+ Vector<String> sources_vector;
bool expected;
} cases[] = {
// Non-intersecting source lists give an effective policy of 'none', which
@@ -434,7 +434,7 @@ TEST_F(SourceListDirectiveTest, SubsumesWithSelf) {
csp.Get());
struct TestCase {
- std::vector<const char*> sources_b;
+ Vector<const char*> sources_b;
const char* origin_b;
bool expected;
} cases[] = {
@@ -605,7 +605,7 @@ TEST_F(SourceListDirectiveTest, SubsumesAllowAllInline) {
struct TestCase {
bool is_script_src;
String sources_a;
- std::vector<String> sources_b;
+ Vector<String> sources_b;
bool expected;
} cases[] = {
// `sourcesA` allows all inline behavior.
@@ -714,7 +714,7 @@ TEST_F(SourceListDirectiveTest, SubsumesUnsafeAttributes) {
struct TestCase {
bool is_script_src;
String sources_a;
- std::vector<String> sources_b;
+ Vector<String> sources_b;
bool expected;
} cases[] = {
// A or policiesB contain `unsafe-eval`.
@@ -918,7 +918,7 @@ TEST_F(SourceListDirectiveTest, SubsumesNoncesAndHashes) {
struct TestCase {
bool is_script_src;
String sources_a;
- std::vector<String> sources_b;
+ Vector<String> sources_b;
bool expected;
} cases[] = {
// Check nonces.
@@ -1066,7 +1066,7 @@ TEST_F(SourceListDirectiveTest, SubsumesStrictDynamic) {
struct TestCase {
bool is_script_src;
String sources_a;
- std::vector<String> sources_b;
+ Vector<String> sources_b;
bool expected;
} cases[] = {
// Neither A nor effective policy of list B has `strict-dynamic`.
@@ -1241,7 +1241,7 @@ TEST_F(SourceListDirectiveTest, SubsumesStrictDynamic) {
TEST_F(SourceListDirectiveTest, SubsumesListWildcard) {
struct TestCase {
const char* sources_a;
- std::vector<const char*> sources_b;
+ Vector<const char*> sources_b;
bool expected;
} cases[] = {
// `A` subsumes `policiesB`..
@@ -1272,7 +1272,7 @@ TEST_F(SourceListDirectiveTest, SubsumesListWildcard) {
{"*", "http://a.com ws://b.com ftp://c.com"},
true},
// `A` does not subsume `policiesB`..
- {"*", std::vector<const char*>(), false},
+ {"*", Vector<const char*>(), false},
{"", {"*"}, false},
{"'none'", {"*"}, false},
{"*", {"data:"}, false},
diff --git a/chromium/third_party/blink/renderer/core/frame/dactyloscoper.h b/chromium/third_party/blink/renderer/core/frame/dactyloscoper.h
index d0796ca2753..2f86088579f 100644
--- a/chromium/third_party/blink/renderer/core/frame/dactyloscoper.h
+++ b/chromium/third_party/blink/renderer/core/frame/dactyloscoper.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/frame/web_feature.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/frame/deprecated_schedule_style_recalc_during_layout.h b/chromium/third_party/blink/renderer/core/frame/deprecated_schedule_style_recalc_during_layout.h
index d3ddeb70208..849a3b54e78 100644
--- a/chromium/third_party/blink/renderer/core/frame/deprecated_schedule_style_recalc_during_layout.h
+++ b/chromium/third_party/blink/renderer/core/frame/deprecated_schedule_style_recalc_during_layout.h
@@ -7,7 +7,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/dom/document_lifecycle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
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 bbb1ab1ed2c..3238df84626 100644
--- a/chromium/third_party/blink/renderer/core/frame/deprecation.cc
+++ b/chromium/third_party/blink/renderer/core/frame/deprecation.cc
@@ -5,6 +5,7 @@
#include "third_party/blink/renderer/core/frame/deprecation.h"
#include <bitset>
+#include "build/build_config.h"
#include "services/service_manager/public/cpp/connector.h"
#include "third_party/blink/public/mojom/feature_policy/feature_policy.mojom-blink.h"
#include "third_party/blink/public/mojom/reporting/reporting.mojom-blink.h"
@@ -295,16 +296,6 @@ DeprecationInfo GetDeprecationInfo(WebFeature feature) {
"https://www.chromestatus.com/feature/5669008342777856 for more "
"details."};
- // Blocked `<meta http-equiv="set-cookie" ...>`
- case WebFeature::kMetaSetCookie:
- return {"MetaSetCookie", kM65,
- String::Format(
- "Setting cookies via `<meta http-equiv='Set-Cookie' ...>` no "
- "longer works, as of M65. Consider switching to "
- " `document.cookie = ...`, or to `Set-Cookie` HTTP headers "
- "instead. See %s for more details.",
- "https://www.chromestatus.com/feature/6170540112871424")};
-
// Powerful features on insecure origins (https://goo.gl/rStTGz)
case WebFeature::kGeolocationInsecureOrigin:
case WebFeature::kGeolocationInsecureOriginIframe:
@@ -425,12 +416,6 @@ DeprecationInfo GetDeprecationInfo(WebFeature feature) {
"for more details.",
MilestoneString(kM62))};
- case WebFeature::kChildSrcAllowedWorkerThatScriptSrcBlocked:
- return {"ChildSrcAllowedWorkerThatScriptSrcBlocked", kM60,
- ReplacedWillBeRemoved("The 'child-src' directive",
- "the 'script-src' directive for Workers",
- kM60, "5922594955984896")};
-
case WebFeature::kCanRequestURLHTTPContainingNewline:
return {
"CanRequestURLHTTPContainingNewline", kUnknown,
@@ -528,11 +513,6 @@ DeprecationInfo GetDeprecationInfo(WebFeature feature) {
"Creating a MediaStreamAudioSourceNode on an OfflineAudioContext",
kM71, "5258622686724096")};
- case WebFeature::kRTCDataChannelInitMaxRetransmitTime:
- return {"RTCDataChannelInitMaxRetransmitTime", kM70,
- ReplacedWillBeRemoved("maxRetransmitTime", "maxPacketLifeTime",
- kM70, "5198350873788416")};
-
case WebFeature::kGridRowTrackPercentIndefiniteHeight:
return {"GridRowTrackPercentIndefiniteHeight", kM70,
String::Format("Percentages row tracks and gutters for "
@@ -574,16 +554,6 @@ DeprecationInfo GetDeprecationInfo(WebFeature feature) {
"more details.",
MilestoneString(kM77))};
- case WebFeature::kNoSysexWebMIDIOnInsecureOrigin:
- return {"NoSysexWebMIDIOnInsecureOrigin", kM77,
- String::Format(
- "Web MIDI will be deprecated on insecure origins since %s. "
- "You should consider switching your application to a secure "
- "origin, such as HTTPS. See "
- "https://www.chromestatus.com/feature/5138066234671104 for "
- "more details.",
- MilestoneString(kM77))};
-
case WebFeature::kCustomCursorIntersectsViewport:
return {
"CustomCursorIntersectsViewport", kM75,
@@ -597,6 +567,155 @@ DeprecationInfo GetDeprecationInfo(WebFeature feature) {
ReplacedWillBeRemoved("Atomics.wake", "Atomics.notify", kM76,
"6228189936353280")};
+ case WebFeature::kVRGetDisplays:
+ return {"WebVR", kM79,
+ String::Format("WebVR is deprecated and will be removed as soon "
+ "as %s. Please use WebXR instead. See "
+ "https://www.chromestatus.com/feature/"
+ "4532810371039232 for details.",
+ MilestoneString(kM79))};
+
+ case WebFeature::kCSSValueAppearanceCheckboxForOthersRendered:
+ return {"CSSValueAppearanceCheckboxForOthersRendered", kM79,
+ WillBeRemoved("'-webkit-appearance: checkbox' for elements other "
+ "than input[type=checkbox]",
+ kM79, "5070237827334144")};
+ case WebFeature::kCSSValueAppearanceRadioForOthersRendered:
+ return {"CSSValueAppearanceRadioForOthersRendered", kM79,
+ WillBeRemoved("'-webkit-appearance: radio' for elements other "
+ "than input[type=radio]",
+ kM79, "5070237827334144")};
+ case WebFeature::kCSSValueAppearancePushButtonForOthersRendered:
+ return {
+ "CSSValueAppearancePushButtonForOthersRendered", kM79,
+ WillBeRemoved(
+ "'-webkit-appearance: push-button' for elements other than "
+ "input[type=button], input[type=reset], and input[type=submit]",
+ kM79, "5070237827334144")};
+ case WebFeature::kCSSValueAppearanceSquareButtonForOthersRendered:
+ return {"CSSValueAppearanceSquareButtonForOthersRendered", kM79,
+ WillBeRemoved("'-webkit-appearance: square-button' for elements "
+ "other than input[type=color]",
+ kM79, "5070237827334144")};
+ case WebFeature::kCSSValueAppearanceButtonForAnchor:
+ return {"CSSValueAppearanceSquareButtonForAnchor", kM79,
+ WillBeRemoved("'-webkit-appearance: button' for a", kM79,
+ "5070237827334144")};
+ case WebFeature::kCSSValueAppearanceButtonForSelectRendered:
+ return {
+ "CSSValueAppearanceButtonForSelectRendered", kM79,
+ WillBeRemoved("'-webkit-appearance: button' for drop-down box select",
+ kM79, "5070237827334144")};
+ case WebFeature::kCSSValueAppearanceInnerSpinButtonForOthersRendered:
+ return {"CSSValueAppearanceInnerSpinButtonForOthersRendered", kM79,
+ WillBeRemoved("'-webkit-appearance: inner-spin-button' for "
+ "elements other than :-webkit-inner-spin-button",
+ kM79, "5070237827334144")};
+ case WebFeature::kCSSValueAppearanceListboxForOthersRendered:
+ return {"CSSValueAppearanceListboxForOthersRendered", kM79,
+ WillBeRemoved("'-webkit-appearance: listbox' for "
+ "elements other than listbox select",
+ kM79, "5070237827334144")};
+ case WebFeature::kCSSValueAppearanceMenuListForOthersRendered:
+ return {
+ "CSSValueAppearanceMenuListForOthersRendered", kM79,
+ WillBeRemoved(
+#if defined(OS_ANDROID)
+ "'-webkit-appearance: menulist' for elements other "
+ "than drop-down box select, input[type=color][list], "
+ "input[type=date], "
+ "input[type=datetime-local], input[type=month], "
+ "input[type=time], and input[type=week]",
+#else
+ "'-webkit-appearance: menulist' for elements other "
+ "than select and input[type=color][list]",
+#endif
+ kM79, "5070237827334144")
+ };
+ case WebFeature::kCSSValueAppearanceMenuListButtonForOthersRendered:
+ return {
+ "CSSValueAppearanceMenuListButtonForOthersRendered", kM79,
+ WillBeRemoved(
+#if defined(OS_ANDROID)
+ "'-webkit-appearance: menulist-button' for elements other "
+ "than drop-down box select, input[type=color][list], "
+ "input[type=date], "
+ "input[type=datetime-local], input[type=month], "
+ "input[type=time], and input[type=week]",
+#else
+ "'-webkit-appearance: menulist-button' for elements other "
+ "than select and input[type=color][list]",
+#endif
+ kM79, "5070237827334144")
+ };
+ case WebFeature::kCSSValueAppearanceMeterForOthersRendered:
+ return {"CSSValueAppearanceMeterForOthersRendered", kM79,
+ WillBeRemoved("'-webkit-appearance: meter' for "
+ "elements other than meter",
+ kM79, "5070237827334144")};
+ case WebFeature::kCSSValueAppearanceProgressBarForOthersRendered:
+ return {"CSSValueAppearanceProgressBarForOthersRendered", kM79,
+ WillBeRemoved("'-webkit-appearance: progress-bar' for "
+ "elements other than progress",
+ kM79, "5070237827334144")};
+ case WebFeature::kCSSValueAppearanceSliderHorizontalForOthersRendered:
+ return {"CSSValueAppearanceSliderHorizontalForOthersRendered", kM79,
+ WillBeRemoved("'-webkit-appearance: slider-horizontal' for "
+ "elements other than input[type=range]",
+ kM79, "5070237827334144")};
+ case WebFeature::kCSSValueAppearanceSliderVerticalForOthersRendered:
+ return {"CSSValueAppearanceSliderVerticalForOthersRendered", kM79,
+ WillBeRemoved("'-webkit-appearance: slider-vertical' for "
+ "elements other than input[type=range]",
+ kM79, "5070237827334144")};
+ case WebFeature::kCSSValueAppearanceSliderThumbHorizontalForOthersRendered:
+ return {"CSSValueAppearanceSliderThumbHorizontalForOthersRendered", kM79,
+ WillBeRemoved("'-webkit-appearance: sliderthumb-horizontal' for "
+ "elements other than ::-webkit-slider-thumb and "
+ "::-webkit-media-slider-thumb",
+ kM79, "5070237827334144")};
+ case WebFeature::kCSSValueAppearanceSliderThumbVerticalForOthersRendered:
+ return {"CSSValueAppearanceSliderThumbVerticalForOthersRendered", kM79,
+ WillBeRemoved("'-webkit-appearance: sliderthumb-vertical' for "
+ "elements other than ::-webkit-slider-thumb and "
+ "::-webkit-media-slider-thumb",
+ kM79, "5070237827334144")};
+ case WebFeature::kCSSValueAppearanceSearchFieldForOthersRendered:
+ return {"CSSValueAppearanceSearchFieldForOthersRendered", kM79,
+ WillBeRemoved("'-webkit-appearance: searchfield' for "
+ "elements other than input[type=search]",
+ kM79, "5070237827334144")};
+ case WebFeature::kCSSValueAppearanceSearchCancelForOthers2Rendered:
+ return {
+ "CSSValueAppearanceSearchCancelForOthers2Rendered", kM79,
+ WillBeRemoved("'-webkit-appearance: searchfield-cancel-button' for "
+ "elements other than ::-webkit-clear-button and "
+ "::-webkit-search-cancel-button",
+ kM79, "5070237827334144")};
+ case WebFeature::kCSSValueAppearanceTextFieldForOthersRendered:
+ return {
+ "CSSValueAppearanceTextFieldForOthersRendered", kM79,
+ WillBeRemoved(
+ "'-webkit-appearance: textfield' for "
+#if defined(OS_ANDROID)
+ "elements other than input[type=email], input[type=number], "
+ "input[type=password], input[type=search], input[type=tel], "
+ "input[type=text], input[type=url]",
+#else
+ "elements other than input[type=email], input[type=number], "
+ "input[type=password], input[type=search], input[type=tel], "
+ "input[type=text], input[type=url], input[type=date], "
+ "input[type=datetime-local], input[type=month], "
+ "input[type=time], and input[type=week]",
+#endif
+ kM79, "5070237827334144")
+ };
+ case WebFeature::kCSSValueAppearanceTextAreaForOthersRendered:
+ return {"CSSValueAppearanceTextAreaForOthersRendered", kM79,
+ WillBeRemoved("'-webkit-appearance: textarea' for "
+ "elements other than textarea",
+ kM79, "5070237827334144")};
+
// Features that aren't deprecated don't have a deprecation message.
default:
return {"NotDeprecated", kUnknown, ""};
diff --git a/chromium/third_party/blink/renderer/core/frame/deprecation.h b/chromium/third_party/blink/renderer/core/frame/deprecation.h
index 7c8366762f8..7e65e1c0dc7 100644
--- a/chromium/third_party/blink/renderer/core/frame/deprecation.h
+++ b/chromium/third_party/blink/renderer/core/frame/deprecation.h
@@ -9,7 +9,7 @@
#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/frame/use_counter.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
namespace mojom {
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 419c2da4ca7..609a16f9423 100644
--- a/chromium/third_party/blink/renderer/core/frame/dom_timer.cc
+++ b/chromium/third_party/blink/renderer/core/frame/dom_timer.cc
@@ -37,29 +37,18 @@
namespace blink {
-static const TimeDelta kMaxIntervalForUserGestureForwarding =
- TimeDelta::FromMilliseconds(1000); // One second matches Gecko.
static const int kMaxTimerNestingLevel = 5;
// Chromium uses a minimum timer interval of 4ms. We'd like to go
// lower; however, there are poorly coded websites out there which do
// create CPU-spinning loops. Using 4ms prevents the CPU from
// spinning too busily and provides a balance between CPU spinning and
// the smallest possible interval timer.
-static constexpr TimeDelta kMinimumInterval = TimeDelta::FromMilliseconds(4);
-
-static inline bool ShouldForwardUserGesture(TimeDelta interval,
- int nesting_level) {
- if (RuntimeEnabledFeatures::UserActivationV2Enabled())
- return false;
- return UserGestureIndicator::ProcessingUserGestureThreadSafe() &&
- interval <= kMaxIntervalForUserGestureForwarding &&
- nesting_level ==
- 1; // Gestures should not be forwarded to nested timers.
-}
+static constexpr base::TimeDelta kMinimumInterval =
+ base::TimeDelta::FromMilliseconds(4);
int DOMTimer::Install(ExecutionContext* context,
ScheduledAction* action,
- TimeDelta timeout,
+ base::TimeDelta timeout,
bool single_shot) {
int timeout_id = context->Timers()->InstallNewTimeout(context, action,
timeout, single_shot);
@@ -78,7 +67,7 @@ void DOMTimer::RemoveByID(ExecutionContext* context, int timeout_id) {
DOMTimer::DOMTimer(ExecutionContext* context,
ScheduledAction* action,
- TimeDelta interval,
+ base::TimeDelta interval,
bool single_shot,
int timeout_id)
: ContextLifecycleObserver(context),
@@ -87,14 +76,9 @@ DOMTimer::DOMTimer(ExecutionContext* context,
nesting_level_(context->Timers()->TimerNestingLevel() + 1),
action_(action) {
DCHECK_GT(timeout_id, 0);
- if (ShouldForwardUserGesture(interval, nesting_level_)) {
- // Thread safe because shouldForwardUserGesture will only return true if
- // execution is on the the main thread.
- user_gesture_token_ = UserGestureIndicator::CurrentToken();
- }
- TimeDelta interval_milliseconds =
- std::max(TimeDelta::FromMilliseconds(1), interval);
+ base::TimeDelta interval_milliseconds =
+ std::max(base::TimeDelta::FromMilliseconds(1), interval);
if (interval_milliseconds < kMinimumInterval &&
nesting_level_ >= kMaxTimerNestingLevel)
interval_milliseconds = kMinimumInterval;
@@ -111,18 +95,21 @@ DOMTimer::DOMTimer(ExecutionContext* context,
context, single_shot ? "setTimeout" : "setInterval", this);
}
-DOMTimer::~DOMTimer() {
- if (action_)
- action_->Dispose();
+DOMTimer::~DOMTimer() = default;
+
+void DOMTimer::Dispose() {
+ Stop();
}
void DOMTimer::Stop() {
+ if (!action_)
+ return;
+
const bool is_interval = !RepeatInterval().is_zero();
probe::AsyncTaskCanceledBreakable(
GetExecutionContext(), is_interval ? "clearInterval" : "clearTimeout",
this);
- user_gesture_token_ = nullptr;
// Need to release JS objects potentially protected by ScheduledAction
// because they can form circular references back to the ExecutionContext
// which will cause a memory leak.
@@ -143,7 +130,6 @@ void DOMTimer::Fired() {
DCHECK(!context->IsContextPaused());
// Only the first execution of a multi-shot timer should get an affirmative
// user gesture indicator.
- UserGestureIndicator gesture_indicator(std::move(user_gesture_token_));
TRACE_EVENT1("devtools.timeline", "TimerFire", "data",
inspector_timer_fire_event::Data(context, timeout_id_));
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 58da7f46468..19e9b5b8c58 100644
--- a/chromium/third_party/blink/renderer/core/frame/dom_timer.h
+++ b/chromium/third_party/blink/renderer/core/frame/dom_timer.h
@@ -45,19 +45,20 @@ class CORE_EXPORT DOMTimer final : public GarbageCollectedFinalized<DOMTimer>,
public TimerBase,
public NameClient {
USING_GARBAGE_COLLECTED_MIXIN(DOMTimer);
+ USING_PRE_FINALIZER(DOMTimer, Dispose);
public:
// Creates a new timer owned by the ExecutionContext, starts it and returns
// its ID.
static int Install(ExecutionContext*,
ScheduledAction*,
- TimeDelta timeout,
+ base::TimeDelta timeout,
bool single_shot);
static void RemoveByID(ExecutionContext*, int timeout_id);
DOMTimer(ExecutionContext*,
ScheduledAction*,
- TimeDelta interval,
+ base::TimeDelta interval,
bool single_shot,
int timeout_id);
~DOMTimer() override;
@@ -65,11 +66,12 @@ class CORE_EXPORT DOMTimer final : public GarbageCollectedFinalized<DOMTimer>,
// ContextLifecycleObserver
void ContextDestroyed(ExecutionContext*) override;
- // Eager finalization is needed to promptly stop this Timer object.
+ // Pre finalizer is needed to promptly stop this Timer object.
// Otherwise timer events might fire at an object that's slated for
// destruction (when lazily swept), but some of its members (m_action) may
// already have been finalized & must not be accessed.
- EAGERLY_FINALIZE();
+ void Dispose();
+
void Trace(blink::Visitor*) override;
const char* NameInHeapSnapshot() const override { return "DOMTimer"; }
@@ -85,7 +87,6 @@ class CORE_EXPORT DOMTimer final : public GarbageCollectedFinalized<DOMTimer>,
int timeout_id_;
int nesting_level_;
Member<ScheduledAction> action_;
- scoped_refptr<UserGestureToken> user_gesture_token_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/frame/dom_timer_coordinator.cc b/chromium/third_party/blink/renderer/core/frame/dom_timer_coordinator.cc
index 5d10ef3d8a8..e874cf38958 100644
--- a/chromium/third_party/blink/renderer/core/frame/dom_timer_coordinator.cc
+++ b/chromium/third_party/blink/renderer/core/frame/dom_timer_coordinator.cc
@@ -19,7 +19,7 @@ DOMTimerCoordinator::DOMTimerCoordinator(
int DOMTimerCoordinator::InstallNewTimeout(ExecutionContext* context,
ScheduledAction* action,
- TimeDelta timeout,
+ base::TimeDelta timeout,
bool single_shot) {
// FIXME: DOMTimers depends heavily on ExecutionContext. Decouple them.
DCHECK_EQ(context->Timers(), this);
diff --git a/chromium/third_party/blink/renderer/core/frame/dom_timer_coordinator.h b/chromium/third_party/blink/renderer/core/frame/dom_timer_coordinator.h
index c5597afcfc7..af5011cdd8d 100644
--- a/chromium/third_party/blink/renderer/core/frame/dom_timer_coordinator.h
+++ b/chromium/third_party/blink/renderer/core/frame/dom_timer_coordinator.h
@@ -32,7 +32,7 @@ class DOMTimerCoordinator {
// Creates and installs a new timer. Returns the assigned ID.
int InstallNewTimeout(ExecutionContext*,
ScheduledAction*,
- TimeDelta timeout,
+ base::TimeDelta timeout,
bool single_shot);
// Removes and disposes the timer with the specified ID, if any. This may
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 a2c1a2ee6e0..9f982ed49e4 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
@@ -4,8 +4,6 @@
#include "third_party/blink/renderer/core/frame/dom_timer.h"
-#include <vector>
-
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/bindings/core/v8/idl_types.h"
@@ -17,7 +15,6 @@
#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/core/timing/dom_window_performance.h"
-#include "third_party/blink/renderer/platform/testing/testing_platform_support_with_mock_scheduler.h"
using testing::DoubleNear;
using testing::ElementsAreArray;
@@ -33,26 +30,24 @@ const double kThreshold = 0.006;
class DOMTimerTest : public RenderingTest {
public:
- ScopedTestingPlatformSupport<TestingPlatformSupportWithMockScheduler>
- platform_;
-
// Expected time between each iterator for setInterval(..., 1) or nested
// setTimeout(..., 1) are 1, 1, 1, 1, 4, 4, ... as a minimum clamp of 4ms
// is applied from the 5th iteration onwards.
- const std::vector<Matcher<double>> kExpectedTimings = {
+ const Vector<Matcher<double>> kExpectedTimings = {
DoubleNear(1., kThreshold), DoubleNear(1., kThreshold),
DoubleNear(1., kThreshold), DoubleNear(1., kThreshold),
DoubleNear(4., kThreshold), DoubleNear(4., kThreshold),
};
void SetUp() override {
- platform_->SetAutoAdvanceNowToPendingTasks(true);
+ EnablePlatform();
+ platform()->SetAutoAdvanceNowToPendingTasks(true);
// Advance timer manually as RenderingTest expects the time to be non-zero.
- platform_->AdvanceClockSeconds(1.);
+ platform()->AdvanceClockSeconds(1.);
RenderingTest::SetUp();
auto* window_performance = DOMWindowPerformance::performance(
*GetDocument().GetFrame()->DomWindow());
- auto test_task_runner = platform_->test_task_runner();
+ auto test_task_runner = platform()->test_task_runner();
auto* mock_clock = test_task_runner->GetMockClock();
auto* mock_tick_clock = test_task_runner->GetMockTickClock();
auto now_ticks = test_task_runner->NowTicks();
@@ -91,7 +86,7 @@ class DOMTimerTest : public RenderingTest {
ScriptSourceCode script(script_text);
GetDocument().GetFrame()->GetScriptController().ExecuteScriptInMainWorld(
script, KURL(), SanitizeScriptErrors::kSanitize);
- platform_->RunUntilIdle();
+ platform()->RunUntilIdle();
}
private:
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 a1ec2c965f5..8cf2031cdd5 100644
--- a/chromium/third_party/blink/renderer/core/frame/dom_window.cc
+++ b/chromium/third_party/blink/renderer/core/frame/dom_window.cc
@@ -19,7 +19,6 @@
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/location.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/frame/user_activation.h"
#include "third_party/blink/renderer/core/frame/window_post_message_options.h"
#include "third_party/blink/renderer/core/input/input_device_capabilities.h"
@@ -29,6 +28,7 @@
#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"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
@@ -465,15 +465,26 @@ void DOMWindow::DoPostMessage(scoped_refptr<SerializedScriptValue> message,
if (options->includeUserActivation())
user_activation = UserActivation::CreateSnapshot(source);
+ LocalFrame* source_frame = source->GetFrame();
+
+ bool allow_autoplay = false;
+ if (RuntimeEnabledFeatures::ExperimentalAutoplayDynamicDelegationEnabled(
+ GetExecutionContext()) &&
+ LocalFrame::HasTransientUserActivation(source_frame) &&
+ options->hasAllow()) {
+ Vector<String> policy_entry_list;
+ options->allow().Split(' ', policy_entry_list);
+ allow_autoplay = policy_entry_list.Contains("autoplay");
+ }
+
MessageEvent* event = MessageEvent::Create(
std::move(channels), std::move(message), source_origin, String(), source,
- user_activation, options->transferUserActivation());
+ user_activation, options->transferUserActivation(), allow_autoplay);
// Transfer user activation state in the source's renderer when
// |transferUserActivation| is true.
// TODO(lanwei): we should execute the below code after the post task fires
// (for both local and remote posting messages).
- LocalFrame* source_frame = source->GetFrame();
if (RuntimeEnabledFeatures::UserActivationPostMessageTransferEnabled() &&
options->transferUserActivation() &&
LocalFrame::HasTransientUserActivation(source_frame)) {
diff --git a/chromium/third_party/blink/renderer/core/frame/embedded_content_view.cc b/chromium/third_party/blink/renderer/core/frame/embedded_content_view.cc
index 7c339751f96..666909f6718 100644
--- a/chromium/third_party/blink/renderer/core/frame/embedded_content_view.cc
+++ b/chromium/third_party/blink/renderer/core/frame/embedded_content_view.cc
@@ -29,7 +29,10 @@ IntPoint EmbeddedContentView::Location() const {
LayoutView* owner_layout_view = owner->View();
DCHECK(owner_layout_view);
if (owner_layout_view->HasOverflowClip()) {
- IntSize scroll_offset(owner_layout_view->ScrolledContentOffset());
+ // Floored because the frame_rect in a content view is an IntRect. We may
+ // want to reevaluate that since scroll offsets/layout can be fractional.
+ IntSize scroll_offset(
+ FlooredIntSize(owner_layout_view->ScrolledContentOffset()));
location.SaturatedMove(-scroll_offset.Width(), -scroll_offset.Height());
}
}
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 654049c56f4..ddbbb1c3a5f 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
@@ -30,6 +30,8 @@
#include "third_party/blink/renderer/core/frame/find_in_page.h"
+#include <utility>
+
#include "third_party/blink/public/web/web_document.h"
#include "third_party/blink/public/web/web_local_frame_client.h"
#include "third_party/blink/public/web/web_plugin.h"
@@ -45,15 +47,15 @@ namespace blink {
FindInPage::FindInPage(WebLocalFrameImpl& frame,
InterfaceRegistry* interface_registry)
- : frame_(&frame), binding_(this) {
+ : frame_(&frame) {
// TODO(rakina): Use InterfaceRegistry of |frame| directly rather than passing
// both of them.
if (!interface_registry)
return;
// TODO(crbug.com/800641): Use InterfaceValidator when it works for associated
// interfaces.
- interface_registry->AddAssociatedInterface(
- WTF::BindRepeating(&FindInPage::BindToRequest, WrapWeakPersistent(this)));
+ interface_registry->AddAssociatedInterface(WTF::BindRepeating(
+ &FindInPage::BindToReceiver, WrapWeakPersistent(this)));
}
void FindInPage::Find(int request_id,
@@ -229,8 +231,12 @@ void FindInPage::ActivateNearestFindResult(int request_id,
true /* final_update */);
}
-void FindInPage::SetClient(mojom::blink::FindInPageClientPtr client) {
- client_ = std::move(client);
+void FindInPage::SetClient(
+ mojo::PendingRemote<mojom::blink::FindInPageClient> remote) {
+ // TODO(crbug.com/984878): Having to call reset() to try to bind a remote that
+ // might be bound is questionable behavior and suggests code may be buggy.
+ client_.reset();
+ client_.Bind(std::move(remote));
}
void FindInPage::GetNearestFindResult(const WebFloatPoint& point,
@@ -303,14 +309,14 @@ WebPlugin* FindInPage::GetWebPluginForFind() {
return nullptr;
}
-void FindInPage::BindToRequest(
- mojom::blink::FindInPageAssociatedRequest request) {
- binding_.Bind(std::move(request),
- frame_->GetTaskRunner(blink::TaskType::kInternalDefault));
+void FindInPage::BindToReceiver(
+ mojo::PendingAssociatedReceiver<mojom::blink::FindInPage> receiver) {
+ receiver_.Bind(std::move(receiver),
+ frame_->GetTaskRunner(blink::TaskType::kInternalDefault));
}
void FindInPage::Dispose() {
- binding_.Close();
+ receiver_.reset();
}
void FindInPage::ReportFindInPageMatchCount(int request_id,
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 5ed722614b3..d1cac5d9c93 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
@@ -5,7 +5,10 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_FIND_IN_PAGE_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_FIND_IN_PAGE_H_
-#include "mojo/public/cpp/bindings/associated_binding.h"
+#include "mojo/public/cpp/bindings/associated_receiver.h"
+#include "mojo/public/cpp/bindings/pending_associated_receiver.h"
+#include "mojo/public/cpp/bindings/pending_remote.h"
+#include "mojo/public/cpp/bindings/remote.h"
#include "third_party/blink/public/mojom/frame/find_in_page.mojom-blink.h"
#include "third_party/blink/public/platform/interface_registry.h"
#include "third_party/blink/public/platform/web_common.h"
@@ -57,7 +60,7 @@ class CORE_EXPORT FindInPage final
const String& search_text,
mojom::blink::FindOptionsPtr) final;
- void SetClient(mojom::blink::FindInPageClientPtr) final;
+ void SetClient(mojo::PendingRemote<mojom::blink::FindInPageClient>) final;
void ActivateNearestFindResult(int request_id, const WebFloatPoint&) final;
@@ -88,7 +91,8 @@ class CORE_EXPORT FindInPage final
WebPlugin* GetWebPluginForFind();
- void BindToRequest(mojom::blink::FindInPageAssociatedRequest request);
+ void BindToReceiver(
+ mojo::PendingAssociatedReceiver<mojom::blink::FindInPage> receiver);
void Dispose();
@@ -105,13 +109,13 @@ class CORE_EXPORT FindInPage final
const Member<WebLocalFrameImpl> frame_;
- mojom::blink::FindInPageClientPtr client_;
+ mojo::Remote<mojom::blink::FindInPageClient> client_;
- mojo::AssociatedBinding<mojom::blink::FindInPage> binding_;
+ mojo::AssociatedReceiver<mojom::blink::FindInPage> receiver_{this};
DISALLOW_COPY_AND_ASSIGN(FindInPage);
};
} // namespace blink
-#endif
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_FIND_IN_PAGE_H_
diff --git a/chromium/third_party/blink/renderer/core/frame/frame.cc b/chromium/third_party/blink/renderer/core/frame/frame.cc
index 1f6bcd282df..90948c58df2 100644
--- a/chromium/third_party/blink/renderer/core/frame/frame.cc
+++ b/chromium/third_party/blink/renderer/core/frame/frame.cc
@@ -39,9 +39,9 @@
#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/user_gesture_indicator.h"
+#include "third_party/blink/renderer/core/execution_context/window_agent_factory.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.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_element_base.h"
#include "third_party/blink/renderer/core/input/event_handler.h"
#include "third_party/blink/renderer/core/layout/layout_embedded_content.h"
@@ -49,7 +49,8 @@
#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"
-#include "third_party/blink/renderer/platform/instance_counters.h"
+#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_error.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
@@ -69,6 +70,7 @@ void Frame::Trace(blink::Visitor* visitor) {
visitor->Trace(dom_window_);
visitor->Trace(client_);
visitor->Trace(navigation_rate_limiter_);
+ visitor->Trace(window_agent_factory_);
}
void Frame::Detach(FrameDetachType type) {
@@ -259,23 +261,27 @@ void Frame::UpdateInheritedEffectiveTouchActionIfPossible() {
}
}
-const CString& Frame::ToTraceValue() {
+const std::string& Frame::ToTraceValue() {
// token's ToString() is latin1.
if (!trace_value_)
- trace_value_ = CString(devtools_frame_token_.ToString().c_str());
+ trace_value_ = devtools_frame_token_.ToString();
return trace_value_.value();
}
Frame::Frame(FrameClient* client,
Page& page,
FrameOwner* owner,
- WindowProxyManager* window_proxy_manager)
+ WindowProxyManager* window_proxy_manager,
+ WindowAgentFactory* inheriting_agent_factory)
: tree_node_(this),
page_(&page),
owner_(owner),
client_(client),
window_proxy_manager_(window_proxy_manager),
navigation_rate_limiter_(*this),
+ window_agent_factory_(inheriting_agent_factory
+ ? inheriting_agent_factory
+ : MakeGarbageCollected<WindowAgentFactory>()),
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 58fe978c7ee..d421bcf572d 100644
--- a/chromium/third_party/blink/renderer/core/frame/frame.h
+++ b/chromium/third_party/blink/renderer/core/frame/frame.h
@@ -65,6 +65,7 @@ class Settings;
class WindowProxy;
class WindowProxyManager;
struct FrameLoadRequest;
+class WindowAgentFactory;
enum class FrameDetachType { kRemove, kSwap };
@@ -129,7 +130,7 @@ class CORE_EXPORT Frame : public GarbageCollectedFinalized<Frame> {
// dispatch unload events, abort XHR requests and detach the document.
// Returns true if the frame is ready to receive the next commit, or false
// otherwise.
- virtual bool PrepareForCommit() = 0;
+ virtual bool DetachDocument() = 0;
// LayoutObject for the element that contains this frame.
LayoutEmbeddedContent* OwnerLayoutObject() const;
@@ -205,7 +206,7 @@ class CORE_EXPORT Frame : public GarbageCollectedFinalized<Frame> {
const base::UnguessableToken& GetDevToolsFrameToken() const {
return devtools_frame_token_;
}
- const CString& ToTraceValue();
+ const std::string& ToTraceValue();
// TODO(dcheng): temporary for debugging https://crbug.com/838348.
const base::debug::StackTrace& CreateStackForDebugging() {
@@ -238,8 +239,21 @@ class CORE_EXPORT Frame : public GarbageCollectedFinalized<Frame> {
opener_feature_state_ = state;
}
+ WindowAgentFactory& window_agent_factory() const {
+ return *window_agent_factory_;
+ }
+
protected:
- Frame(FrameClient*, Page&, FrameOwner*, WindowProxyManager*);
+ // |inheriting_agent_factory| should basically be set to the parent frame or
+ // opener's WindowAgentFactory. Pass nullptr if the frame is isolated from
+ // other frames (i.e. if it and its child frames shall never be script
+ // accessible from other frames), and a new WindowAgentFactory will be
+ // created.
+ Frame(FrameClient*,
+ Page&,
+ FrameOwner*,
+ WindowProxyManager*,
+ WindowAgentFactory* inheriting_agent_factory);
// Perform initialization that must happen after the constructor has run so
// that vtables are initialized.
@@ -285,10 +299,12 @@ class CORE_EXPORT Frame : public GarbageCollectedFinalized<Frame> {
// frames.
FeaturePolicy::FeatureState opener_feature_state_;
+ Member<WindowAgentFactory> window_agent_factory_;
+
// TODO(sashab): Investigate if this can be represented with m_lifecycle.
bool is_loading_;
base::UnguessableToken devtools_frame_token_;
- base::Optional<CString> trace_value_;
+ base::Optional<std::string> trace_value_;
base::debug::StackTrace create_stack_;
base::debug::StackTrace detach_stack_;
@@ -314,8 +330,8 @@ DEFINE_COMPARISON_OPERATORS_WITH_REFERENCES(Frame)
// in a TRACE_EVENT_XXX macro. Example:
//
// TRACE_EVENT1("category", "event_name", "frame", ToTraceValue(GetFrame()));
-static inline CString ToTraceValue(Frame* frame) {
- return frame ? frame->ToTraceValue() : CString();
+static inline std::string ToTraceValue(Frame* frame) {
+ return frame ? frame->ToTraceValue() : std::string();
}
} // namespace blink
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 bf284df7c94..720cd843285 100644
--- a/chromium/third_party/blink/renderer/core/frame/frame_console.h
+++ b/chromium/third_party/blink/renderer/core/frame/frame_console.h
@@ -29,7 +29,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_FRAME_CONSOLE_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_FRAME_CONSOLE_H_
-#include "third_party/blink/public/mojom/devtools/console_message.mojom-shared.h"
+#include "third_party/blink/public/mojom/devtools/console_message.mojom-blink.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
diff --git a/chromium/third_party/blink/renderer/core/frame/frame_overlay_test.cc b/chromium/third_party/blink/renderer/core/frame/frame_overlay_test.cc
index a192fd31c5d..180bfb9fef0 100644
--- a/chromium/third_party/blink/renderer/core/frame/frame_overlay_test.cc
+++ b/chromium/third_party/blink/renderer/core/frame/frame_overlay_test.cc
@@ -8,6 +8,7 @@
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/public/web/web_device_emulation_params.h"
#include "third_party/blink/renderer/core/exported/web_view_impl.h"
#include "third_party/blink/renderer/core/frame/frame_test_helpers.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
@@ -113,7 +114,9 @@ TEST_P(FrameOverlayTest, AcceleratedCompositing) {
}
TEST_P(FrameOverlayTest, DeviceEmulationScale) {
- GetWebView()->SetDeviceEmulationTransform(TransformationMatrix().Scale(1.5));
+ WebDeviceEmulationParams params;
+ params.scale = 1.5;
+ GetWebView()->EnableDeviceEmulation(params);
GetWebView()->MainFrameWidget()->UpdateAllLifecyclePhases(
WebWidget::LifecycleUpdateReason::kTest);
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 bbdbbd09203..69df9b1c301 100644
--- a/chromium/third_party/blink/renderer/core/frame/frame_serializer.cc
+++ b/chromium/third_party/blink/renderer/core/frame/frame_serializer.cc
@@ -38,6 +38,7 @@
#include "third_party/blink/renderer/core/css/css_rule_list.h"
#include "third_party/blink/renderer/core/css/css_style_declaration.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_value_list.h"
#include "third_party/blink/renderer/core/css/style_rule.h"
#include "third_party/blink/renderer/core/css/style_sheet_contents.h"
@@ -49,10 +50,14 @@
#include "third_party/blink/renderer/core/html/forms/html_input_element.h"
#include "third_party/blink/renderer/core/html/html_frame_element_base.h"
#include "third_party/blink/renderer/core/html/html_image_element.h"
+#include "third_party/blink/renderer/core/html/html_image_loader.h"
#include "third_party/blink/renderer/core/html/html_link_element.h"
#include "third_party/blink/renderer/core/html/html_meta_element.h"
+#include "third_party/blink/renderer/core/html/html_plugin_element.h"
#include "third_party/blink/renderer/core/html/html_style_element.h"
#include "third_party/blink/renderer/core/html/image_document.h"
+#include "third_party/blink/renderer/core/html/imports/html_import_loader.h"
+#include "third_party/blink/renderer/core/html/imports/html_imports_controller.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/loader/resource/font_resource.h"
@@ -61,14 +66,14 @@
#include "third_party/blink/renderer/core/style/style_image.h"
#include "third_party/blink/renderer/platform/graphics/image.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/mhtml/serialized_resource.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
-#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#include "third_party/blink/renderer/platform/wtf/text/text_encoding.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
+#include "third_party/blink/renderer/platform/wtf/uuid.h"
namespace {
@@ -84,8 +89,8 @@ class SerializerMarkupAccumulator : public MarkupAccumulator {
public:
SerializerMarkupAccumulator(FrameSerializer::Delegate&,
- const Document&,
- HeapVector<Member<const Element>>&);
+ FrameSerializerResourceDelegate&,
+ Document&);
~SerializerMarkupAccumulator() override;
protected:
@@ -101,15 +106,12 @@ class SerializerMarkupAccumulator : public MarkupAccumulator {
void AppendRewrittenAttribute(const Element&,
const String& attribute_name,
const String& attribute_value);
+ void AppendExtraForHeadElement(const Element&);
+ void AppendStylesheets(Document* document, bool style_element_only);
FrameSerializer::Delegate& delegate_;
- Member<const Document> document_;
-
- // FIXME: |FrameSerializer| uses |elements_| for collecting elements in
- // document included into serialized text then extracts image, object, etc.
- // The size of this vector isn't small for large document. It is better to use
- // callback like functionality.
- HeapVector<Member<const Element>>& elements_;
+ FrameSerializerResourceDelegate& resource_delegate_;
+ Member<Document> document_;
// Elements with links rewritten via appendAttribute method.
HeapHashSet<Member<const Element>> elements_with_rewritten_links_;
@@ -117,12 +119,14 @@ class SerializerMarkupAccumulator : public MarkupAccumulator {
SerializerMarkupAccumulator::SerializerMarkupAccumulator(
FrameSerializer::Delegate& delegate,
- const Document& document,
- HeapVector<Member<const Element>>& elements)
- : MarkupAccumulator(kResolveAllURLs),
+ FrameSerializerResourceDelegate& resource_delegate,
+ Document& document)
+ : MarkupAccumulator(kResolveAllURLs,
+ document.IsHTMLDocument() ? SerializationType::kHTML
+ : SerializationType::kXML),
delegate_(delegate),
- document_(&document),
- elements_(elements) {}
+ resource_delegate_(resource_delegate),
+ document_(&document) {}
SerializerMarkupAccumulator::~SerializerMarkupAccumulator() = default;
@@ -149,6 +153,9 @@ bool SerializerMarkupAccumulator::ShouldIgnoreElement(
ToHTMLMetaElement(element).ComputeEncoding().IsValid()) {
return true;
}
+ // This is done in serializing document.StyleSheets.
+ if (IsHTMLStyleElement(element))
+ return true;
return delegate_.ShouldIgnoreElement(element);
}
@@ -156,19 +163,10 @@ AtomicString SerializerMarkupAccumulator::AppendElement(
const Element& element) {
AtomicString prefix = MarkupAccumulator::AppendElement(element);
- // TODO(tiger): Refactor MarkupAccumulator so it is easier to append an
- // element like this, without special cases for XHTML
- if (IsHTMLHeadElement(element)) {
- markup_.Append("<meta http-equiv=\"Content-Type\" content=\"");
- AppendAttributeValue(document_->SuggestedMIMEType());
- markup_.Append("; charset=");
- AppendAttributeValue(document_->characterSet());
- if (document_->IsXHTMLDocument())
- markup_.Append("\" />");
- else
- markup_.Append("\">");
- }
- elements_.push_back(&element);
+ if (IsHTMLHeadElement(element))
+ AppendExtraForHeadElement(element);
+
+ resource_delegate_.AddResourceForElement(*document_, element);
// FIXME: For object (plugins) tags and video tag we could replace them by an
// image of their current contents.
@@ -176,6 +174,64 @@ AtomicString SerializerMarkupAccumulator::AppendElement(
return prefix;
}
+void SerializerMarkupAccumulator::AppendExtraForHeadElement(
+ const Element& element) {
+ DCHECK(IsHTMLHeadElement(element));
+
+ // TODO(tiger): Refactor MarkupAccumulator so it is easier to append an
+ // element like this, without special cases for XHTML
+ markup_.Append("<meta http-equiv=\"Content-Type\" content=\"");
+ AppendAttributeValue(document_->SuggestedMIMEType());
+ markup_.Append("; charset=");
+ AppendAttributeValue(document_->characterSet());
+ if (document_->IsXHTMLDocument())
+ markup_.Append("\" />");
+ else
+ markup_.Append("\">");
+
+ // The CSS rules of a style element can be updated dynamically independent of
+ // the CSS text included in the style element. So we can't use the inline
+ // CSS text defined in the style element. To solve this, we serialize the
+ // working CSS rules in document.stylesheets and wrap them in link elements.
+ AppendStylesheets(document_, true /*style_element_only*/);
+
+ // The stylesheets defined in imported documents are not incorporated into
+ // master document. So we need to scan all of them.
+ if (HTMLImportsController* controller = document_->ImportsController()) {
+ for (wtf_size_t i = 0; i < controller->LoaderCount(); ++i) {
+ if (Document* imported_document =
+ controller->LoaderAt(i)->GetDocument()) {
+ AppendStylesheets(imported_document, false /*style_element_only*/);
+ }
+ }
+ }
+}
+
+void SerializerMarkupAccumulator::AppendStylesheets(Document* document,
+ bool style_element_only) {
+ StyleSheetList& sheets = document->StyleSheets();
+ for (unsigned i = 0; i < sheets.length(); ++i) {
+ StyleSheet* sheet = sheets.item(i);
+ if (!sheet->IsCSSStyleSheet() || sheet->disabled())
+ continue;
+ if (style_element_only && !IsHTMLStyleElement(sheet->ownerNode()))
+ continue;
+
+ StringBuilder pseudo_sheet_url_builder;
+ pseudo_sheet_url_builder.Append("cid:css-");
+ pseudo_sheet_url_builder.Append(WTF::CreateCanonicalUUIDString());
+ pseudo_sheet_url_builder.Append("@mhtml.blink");
+ KURL pseudo_sheet_url = KURL(pseudo_sheet_url_builder.ToString());
+
+ markup_.Append("<link rel=\"stylesheet\" type=\"text/css\" href=\"");
+ markup_.Append(pseudo_sheet_url.GetString());
+ markup_.Append("\" />");
+
+ resource_delegate_.SerializeCSSStyleSheet(
+ static_cast<CSSStyleSheet&>(*sheet), pseudo_sheet_url);
+ }
+}
+
void SerializerMarkupAccumulator::AppendAttribute(const Element& element,
const Attribute& attribute) {
// Check if link rewriting can affect the attribute.
@@ -267,58 +323,24 @@ void FrameSerializer::SerializeFrame(const LocalFrame& frame) {
return;
}
- HeapVector<Member<const Element>> serialized_elements;
+ should_collect_problem_metric_ =
+ delegate_.ShouldCollectProblemMetric() && frame.IsMainFrame();
{
TRACE_EVENT0("page-serialization", "FrameSerializer::serializeFrame HTML");
SCOPED_BLINK_UMA_HISTOGRAM_TIMER(
"PageSerialization.SerializationTime.Html");
- SerializerMarkupAccumulator accumulator(delegate_, document,
- serialized_elements);
+ SerializerMarkupAccumulator accumulator(delegate_, *this, document);
String text =
accumulator.SerializeNodes<EditingStrategy>(document, kIncludeNode);
- CString frame_html =
+ std::string frame_html =
document.Encoding().Encode(text, WTF::kEntitiesForUnencodables);
- resources_->push_back(SerializedResource(
+ // Note that the frame has to be 1st resource.
+ resources_->push_front(SerializedResource(
url, document.SuggestedMIMEType(),
- SharedBuffer::Create(frame_html.data(), frame_html.length())));
+ SharedBuffer::Create(frame_html.c_str(), frame_html.length())));
}
- should_collect_problem_metric_ =
- delegate_.ShouldCollectProblemMetric() && frame.IsMainFrame();
- for (const Element* node : serialized_elements) {
- DCHECK(node);
- const Element& element = *node;
- // We have to process in-line style as it might contain some resources
- // (typically background images).
- if (element.IsStyledElement()) {
- RetrieveResourcesForProperties(element.InlineStyle(), document);
- RetrieveResourcesForProperties(
- const_cast<Element&>(element).PresentationAttributeStyle(), document);
- }
-
- if (const auto* image = ToHTMLImageElementOrNull(element)) {
- KURL image_url =
- document.CompleteURL(image->getAttribute(html_names::kSrcAttr));
- ImageResourceContent* cached_image = image->CachedImage();
- AddImageToResources(cached_image, image_url);
- } else if (const auto* input = ToHTMLInputElementOrNull(element)) {
- if (input->type() == input_type_names::kImage && input->ImageLoader()) {
- KURL image_url = input->Src();
- ImageResourceContent* cached_image = input->ImageLoader()->GetContent();
- AddImageToResources(cached_image, image_url);
- }
- } else if (const auto* link = ToHTMLLinkElementOrNull(element)) {
- if (CSSStyleSheet* sheet = link->sheet()) {
- KURL sheet_url =
- document.CompleteURL(link->getAttribute(html_names::kHrefAttr));
- SerializeCSSStyleSheet(*sheet, sheet_url);
- }
- } else if (const auto* style = ToHTMLStyleElementOrNull(element)) {
- if (CSSStyleSheet* sheet = style->sheet())
- SerializeCSSStyleSheet(*sheet, NullURL());
- }
- }
if (should_collect_problem_metric_) {
// Report detectors through UMA.
// We're having exact 21 buckets for percentage because we want to have 5%
@@ -349,6 +371,56 @@ void FrameSerializer::SerializeFrame(const LocalFrame& frame) {
}
}
+void FrameSerializer::AddResourceForElement(Document& document,
+ const Element& element) {
+ // We have to process in-line style as it might contain some resources
+ // (typically background images).
+ if (element.IsStyledElement()) {
+ RetrieveResourcesForProperties(element.InlineStyle(), document);
+ RetrieveResourcesForProperties(
+ const_cast<Element&>(element).PresentationAttributeStyle(), document);
+ }
+
+ if (const auto* image = ToHTMLImageElementOrNull(element)) {
+ AtomicString image_url_value;
+ const Element* parent = element.parentElement();
+ if (parent && IsHTMLPictureElement(parent)) {
+ // If parent element is <picture>, use ImageSourceURL() to get best fit
+ // image URL from sibling source.
+ image_url_value = image->ImageSourceURL();
+ } else {
+ // Otherwise, it is single <img> element. We should get image url
+ // contained in href attribute. ImageSourceURL() may return a different
+ // URL from srcset attribute.
+ image_url_value = image->getAttribute(html_names::kSrcAttr);
+ }
+ ImageResourceContent* cached_image = image->CachedImage();
+ AddImageToResources(cached_image, document.CompleteURL(image_url_value));
+ } else if (const auto* input = ToHTMLInputElementOrNull(element)) {
+ if (input->type() == input_type_names::kImage && input->ImageLoader()) {
+ KURL image_url = input->Src();
+ ImageResourceContent* cached_image = input->ImageLoader()->GetContent();
+ AddImageToResources(cached_image, image_url);
+ }
+ } else if (const auto* link = ToHTMLLinkElementOrNull(element)) {
+ if (CSSStyleSheet* sheet = link->sheet()) {
+ KURL sheet_url =
+ document.CompleteURL(link->getAttribute(html_names::kHrefAttr));
+ SerializeCSSStyleSheet(*sheet, sheet_url);
+ }
+ } else if (const auto* style = ToHTMLStyleElementOrNull(element)) {
+ if (CSSStyleSheet* sheet = style->sheet())
+ SerializeCSSStyleSheet(*sheet, NullURL());
+ } else if (IsHTMLPlugInElement(element)) {
+ const auto* plugin = ToHTMLPlugInElement(&element);
+ if (plugin->IsImageType() && plugin->ImageLoader()) {
+ KURL image_url = document.CompleteURL(plugin->Url());
+ ImageResourceContent* cached_image = plugin->ImageLoader()->GetContent();
+ AddImageToResources(cached_image, image_url);
+ }
+ }
+}
+
void FrameSerializer::SerializeCSSStyleSheet(CSSStyleSheet& style_sheet,
const KURL& url) {
// If the URL is invalid or if it is a data URL this means that this CSS is
@@ -371,10 +443,10 @@ void FrameSerializer::SerializeCSSStyleSheet(CSSStyleSheet& style_sheet,
TRACE_EVENT2("page-serialization", "FrameSerializer::serializeCSSStyleSheet",
"type", "CSS", "url", url.ElidedString().Utf8());
// Only report UMA metric if this is not a reentrant CSS serialization call.
- TimeTicks css_start_time;
+ base::TimeTicks css_start_time;
if (!is_serializing_css_) {
is_serializing_css_ = true;
- css_start_time = CurrentTimeTicks();
+ css_start_time = base::TimeTicks::Now();
}
// If this CSS is inlined its definition was already serialized with the frame
@@ -399,11 +471,11 @@ void FrameSerializer::SerializeCSSStyleSheet(CSSStyleSheet& style_sheet,
WTF::TextEncoding text_encoding(style_sheet.Contents()->Charset());
DCHECK(text_encoding.IsValid());
String text_string = css_text.ToString();
- CString text = text_encoding.Encode(
+ std::string text = text_encoding.Encode(
text_string, WTF::kCSSEncodedEntitiesForUnencodables);
resources_->push_back(
SerializedResource(url, String("text/css"),
- SharedBuffer::Create(text.data(), text.length())));
+ SharedBuffer::Create(text.c_str(), text.length())));
}
// Sub resources need to be serialized even if the CSS definition doesn't
@@ -411,12 +483,12 @@ void FrameSerializer::SerializeCSSStyleSheet(CSSStyleSheet& style_sheet,
for (unsigned i = 0; i < style_sheet.length(); ++i)
SerializeCSSRule(style_sheet.item(i));
- if (css_start_time != TimeTicks()) {
+ if (css_start_time != base::TimeTicks()) {
is_serializing_css_ = false;
DEFINE_STATIC_LOCAL(CustomCountHistogram, css_histogram,
("PageSerialization.SerializationTime.CSSElement", 0,
maxSerializationTimeUmaMicroseconds, 50));
- css_histogram.CountMicroseconds(CurrentTimeTicks() - css_start_time);
+ css_histogram.CountMicroseconds(base::TimeTicks::Now() - css_start_time);
}
}
@@ -457,6 +529,7 @@ void FrameSerializer::SerializeCSSRule(CSSRule* rule) {
// Rules in which no external resources can be referenced
case CSSRule::kCharsetRule:
case CSSRule::kPageRule:
+ case CSSRule::kPropertyRule:
case CSSRule::kKeyframesRule:
case CSSRule::kKeyframeRule:
case CSSRule::kNamespaceRule:
@@ -497,7 +570,7 @@ void FrameSerializer::AddImageToResources(ImageResourceContent* image,
TRACE_EVENT2("page-serialization", "FrameSerializer::addImageToResources",
"type", "image", "url", url.ElidedString().Utf8());
- base::TimeTicks image_start_time = CurrentTimeTicks();
+ base::TimeTicks image_start_time = base::TimeTicks::Now();
scoped_refptr<const SharedBuffer> data = image->GetImage()->Data();
AddToResources(image->GetResponse().MimeType(),
@@ -509,7 +582,8 @@ void FrameSerializer::AddImageToResources(ImageResourceContent* image,
DEFINE_STATIC_LOCAL(CustomCountHistogram, image_histogram,
("PageSerialization.SerializationTime.ImageElement", 0,
maxSerializationTimeUmaMicroseconds, 50));
- image_histogram.CountMicroseconds(CurrentTimeTicks() - image_start_time);
+ image_histogram.CountMicroseconds(base::TimeTicks::Now() -
+ image_start_time);
}
}
@@ -570,8 +644,8 @@ void FrameSerializer::RetrieveResourcesForCSSValue(const CSSValue& css_value,
String FrameSerializer::MarkOfTheWebDeclaration(const KURL& url) {
StringBuilder builder;
bool emits_minus = false;
- CString orignal_url = url.GetString().Ascii();
- for (const char* string = orignal_url.data(); *string; ++string) {
+ std::string orignal_url = url.GetString().Ascii();
+ for (const char* string = orignal_url.c_str(); *string; ++string) {
const char ch = *string;
if (ch == '-' && emits_minus) {
builder.Append("%2D");
@@ -581,10 +655,10 @@ String FrameSerializer::MarkOfTheWebDeclaration(const KURL& url) {
emits_minus = ch == '-';
builder.Append(ch);
}
- CString escaped_url = builder.ToString().Ascii();
+ std::string escaped_url = builder.ToString().Ascii();
return String::Format("saved from url=(%04d)%s",
static_cast<int>(escaped_url.length()),
- escaped_url.data());
+ escaped_url.c_str());
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/frame/frame_serializer.h b/chromium/third_party/blink/renderer/core/frame/frame_serializer.h
index 28491e7b2ef..ea2406484be 100644
--- a/chromium/third_party/blink/renderer/core/frame/frame_serializer.h
+++ b/chromium/third_party/blink/renderer/core/frame/frame_serializer.h
@@ -56,10 +56,23 @@ class CSSPropertyValueSet;
struct SerializedResource;
+class FrameSerializerResourceDelegate {
+ public:
+ virtual ~FrameSerializerResourceDelegate() = default;
+
+ // Adds the resource needed to serialize an element.
+ virtual void AddResourceForElement(Document&, const Element&) = 0;
+
+ // Serializes the stylesheet back to text and adds it to the resources if
+ // URL is not-empty. It also adds any resources included in that stylesheet
+ // (including any imported stylesheets and their own resources).
+ virtual void SerializeCSSStyleSheet(CSSStyleSheet&, const KURL&) = 0;
+};
+
// This class is used to serialize frame's contents back to text (typically
// HTML). It serializes frame's document and resources such as images and CSS
// stylesheets.
-class CORE_EXPORT FrameSerializer final {
+class CORE_EXPORT FrameSerializer : public FrameSerializerResourceDelegate {
STACK_ALLOCATED();
public:
@@ -123,10 +136,8 @@ class CORE_EXPORT FrameSerializer final {
static String MarkOfTheWebDeclaration(const KURL&);
private:
- // Serializes the stylesheet back to text and adds it to the resources if URL
- // is not-empty. It also adds any resources included in that stylesheet
- // (including any imported stylesheets and their own resources).
- void SerializeCSSStyleSheet(CSSStyleSheet&, const KURL&);
+ void AddResourceForElement(Document&, const Element&) override;
+ void SerializeCSSStyleSheet(CSSStyleSheet&, const KURL&) override;
// Serializes the css rule (including any imported stylesheets), adding
// referenced resources.
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 922200b2da1..9ba3b657096 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
@@ -114,7 +114,7 @@ class FrameSerializerTest : public testing::Test,
void Serialize(const char* url) {
frame_test_helpers::LoadFrame(
helper_.GetWebView()->MainFrameImpl(),
- KURL(base_url_, url).GetString().Utf8().data());
+ KURL(base_url_, url).GetString().Utf8().c_str());
// Sometimes we have iframes created in "onload" handler - wait for them to
// load.
frame_test_helpers::PumpPendingRequestsForFrameToLoad(
@@ -192,6 +192,7 @@ class FrameSerializerTest : public testing::Test,
return skip_urls_.Contains(url);
}
+ ScopedTestingPlatformSupport<TestingPlatformSupport> platform_;
frame_test_helpers::WebViewHelper helper_;
std::string folder_;
KURL base_url_;
@@ -199,7 +200,6 @@ class FrameSerializerTest : public testing::Test,
HashMap<String, String> rewrite_urls_;
Vector<String> skip_urls_;
String rewrite_folder_;
- ScopedTestingPlatformSupport<TestingPlatformSupport> platform_;
};
TEST_F(FrameSerializerTest, HTMLElements) {
@@ -369,7 +369,9 @@ TEST_F(FrameSerializerTest, CSS) {
Serialize("css_test_page.html");
- EXPECT_EQ(16U, GetResources().size());
+ // 16 resoucres added by RegisterURL + 3 resources added due to converting
+ // style elements to link elements.
+ EXPECT_EQ(19U, GetResources().size());
EXPECT_FALSE(IsSerialized("do_not_serialize.png", "image/png"));
EXPECT_FALSE(IsSerialized("included_in_another_frame.css", "text/css"));
diff --git a/chromium/third_party/blink/renderer/core/frame/frame_test.cc b/chromium/third_party/blink/renderer/core/frame/frame_test.cc
index 58ebe05ed71..da406122152 100644
--- a/chromium/third_party/blink/renderer/core/frame/frame_test.cc
+++ b/chromium/third_party/blink/renderer/core/frame/frame_test.cc
@@ -4,12 +4,13 @@
#include "third_party/blink/renderer/core/frame/frame.h"
-#include "base/test/metrics/histogram_tester.h"
+#include "mojo/public/cpp/bindings/remote.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/core/dom/user_gesture_indicator.h"
#include "third_party/blink/renderer/core/loader/document_loader.h"
#include "third_party/blink/renderer/core/testing/document_interface_broker_test_helpers.h"
#include "third_party/blink/renderer/core/testing/page_test_base.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"
namespace blink {
@@ -163,7 +164,7 @@ TEST_F(FrameTest, NavigateSameDomainNoGesture) {
}
TEST_F(FrameTest, UserActivationInterfaceTest) {
- RuntimeEnabledFeatures::SetUserActivationV2Enabled(true);
+ ScopedUserActivationV2ForTest scoped_feature(true);
// Initially both sticky and transient bits are false.
EXPECT_FALSE(GetDocument().GetFrame()->HasBeenActivated());
@@ -186,35 +187,6 @@ TEST_F(FrameTest, UserActivationInterfaceTest) {
LocalFrame::ConsumeTransientUserActivation(GetDocument().GetFrame()));
}
-TEST_F(FrameTest, UserActivationHistograms) {
- RuntimeEnabledFeatures::SetUserActivationV2Enabled(true);
- base::HistogramTester histograms;
-
- LocalFrame::HasTransientUserActivation(GetDocument().GetFrame());
- histograms.ExpectBucketCount("UserActivation.AvailabilityCheck.FrameResult",
- 0, 1);
-
- LocalFrame::ConsumeTransientUserActivation(GetDocument().GetFrame());
- histograms.ExpectBucketCount("UserActivation.Consumption.FrameResult", 0, 1);
-
- LocalFrame::NotifyUserActivation(GetDocument().GetFrame());
-
- LocalFrame::HasTransientUserActivation(GetDocument().GetFrame());
- LocalFrame::HasTransientUserActivation(GetDocument().GetFrame());
- histograms.ExpectBucketCount("UserActivation.AvailabilityCheck.FrameResult",
- 3, 2);
-
- LocalFrame::ConsumeTransientUserActivation(GetDocument().GetFrame());
- histograms.ExpectBucketCount("UserActivation.Consumption.FrameResult", 3, 1);
-
- LocalFrame::ConsumeTransientUserActivation(GetDocument().GetFrame());
- histograms.ExpectBucketCount("UserActivation.Consumption.FrameResult", 0, 2);
-
- histograms.ExpectTotalCount("UserActivation.AvailabilityCheck.FrameResult",
- 3);
- histograms.ExpectTotalCount("UserActivation.Consumption.FrameResult", 3);
-}
-
TEST_F(FrameTest, TestDocumentInterfaceBrokerOverride) {
mojom::blink::DocumentInterfaceBrokerPtr doc;
FrameHostTestDocumentInterfaceBroker frame_interface_broker(
@@ -223,11 +195,11 @@ TEST_F(FrameTest, TestDocumentInterfaceBrokerOverride) {
GetDocument().GetFrame()->SetDocumentInterfaceBrokerForTesting(
doc.PassInterface().PassHandle());
- mojom::blink::FrameHostTestInterfacePtr frame_test;
+ mojo::Remote<mojom::blink::FrameHostTestInterface> frame_test;
GetDocument()
.GetFrame()
->GetDocumentInterfaceBroker()
- .GetFrameHostTestInterface(mojo::MakeRequest(&frame_test));
+ .GetFrameHostTestInterface(frame_test.BindNewPipeAndPassReceiver());
frame_test->GetName(base::BindOnce([](const WTF::String& result) {
EXPECT_EQ(result, kGetNameTestResponse);
}));
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 86accd22be5..19c28fb4ba2 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
@@ -118,6 +118,7 @@ void LoadFrameDontWait(WebLocalFrame* frame, const WebURL& url) {
params->url = url;
params->navigation_timings.navigation_start = base::TimeTicks::Now();
params->navigation_timings.fetch_start = base::TimeTicks::Now();
+ params->is_browser_initiated = true;
FillNavigationParamsResponse(params.get());
impl->CommitNavigation(std::move(params), nullptr /* extra_data */);
}
@@ -315,7 +316,8 @@ WebRemoteFrameImpl* CreateRemoteChild(
return frame;
}
-WebViewHelper::WebViewHelper() : web_view_(nullptr) {}
+WebViewHelper::WebViewHelper()
+ : web_view_(nullptr), platform_(Platform::Current()) {}
WebViewHelper::~WebViewHelper() {
// Close the WebViewImpl before the WebViewClient/WebWidgetClient are
@@ -437,6 +439,10 @@ void WebViewHelper::LoadAhem() {
}
void WebViewHelper::Reset() {
+ DCHECK_EQ(platform_, Platform::Current())
+ << "Platform::Current() should be the same for the life of a test, "
+ "including shutdown.";
+
if (test_web_view_client_)
test_web_view_client_->DestroyChildViews();
if (web_view_) {
@@ -468,6 +474,9 @@ void WebViewHelper::InitializeWebView(TestWebViewClient* web_view_client,
WebView::Create(test_web_view_client_,
/*is_hidden=*/false,
/*compositing_enabled=*/true, opener));
+ // This property must be set at initialization time, it is not supported to be
+ // changed afterward, and does nothing.
+ web_view_->GetSettings()->SetViewportEnabled(viewport_enabled_);
web_view_->GetSettings()->SetJavaScriptEnabled(true);
web_view_->GetSettings()->SetPluginsEnabled(true);
// Enable (mocked) network loads of image URLs, as this simplifies
@@ -486,8 +495,7 @@ int TestWebFrameClient::loads_in_progress_ = 0;
TestWebFrameClient::TestWebFrameClient()
: interface_provider_(new service_manager::InterfaceProvider()),
- effective_connection_type_(WebEffectiveConnectionType::kTypeUnknown),
- weak_factory_(this) {}
+ effective_connection_type_(WebEffectiveConnectionType::kTypeUnknown) {}
void TestWebFrameClient::Bind(WebLocalFrame* frame,
std::unique_ptr<TestWebFrameClient> self_owned) {
@@ -609,9 +617,6 @@ content::LayerTreeView* LayerTreeViewFactory::Initialize(
// Use synchronous compositing so that the MessageLoop becomes idle and the
// test makes progress.
settings.single_thread_proxy_scheduler = false;
- // For web contents, layer transforms should scale up the contents of layers
- // to keep content always crisp when possible.
- settings.layer_transforms_should_scale_layer_contents = true;
// Both BlinkGenPropertyTrees and CompositeAfterPaint should imply layer lists
// in the compositor. Some code across the boundaries makes assumptions based
// on this so ensure tests run using this configuration as well.
@@ -663,9 +668,38 @@ void TestWebWidgetClient::InjectGestureScrollEvent(
ScrollGranularity granularity,
cc::ElementId scrollable_area_element_id,
WebInputEvent::Type injected_type) {
- if (injected_type == WebInputEvent::kGestureScrollUpdate) {
- injected_gesture_scroll_update_count_++;
- }
+ InjectedScrollGestureData data{delta, granularity, scrollable_area_element_id,
+ injected_type};
+ injected_scroll_gesture_data_.push_back(data);
+}
+
+void TestWebWidgetClient::SetHaveScrollEventHandlers(bool have_handlers) {
+ have_scroll_event_handlers_ = have_handlers;
+}
+
+void TestWebWidgetClient::SetEventListenerProperties(
+ cc::EventListenerClass event_class,
+ cc::EventListenerProperties properties) {
+ layer_tree_host()->SetEventListenerProperties(event_class, properties);
+}
+
+cc::EventListenerProperties TestWebWidgetClient::EventListenerProperties(
+ cc::EventListenerClass event_class) const {
+ return layer_tree_host()->event_listener_properties(event_class);
+}
+
+std::unique_ptr<cc::ScopedDeferMainFrameUpdate>
+TestWebWidgetClient::DeferMainFrameUpdate() {
+ return layer_tree_host()->DeferMainFrameUpdate();
+}
+
+void TestWebWidgetClient::StartDeferringCommits(base::TimeDelta timeout) {
+ layer_tree_host()->StartDeferringCommits(timeout);
+}
+
+void TestWebWidgetClient::StopDeferringCommits(
+ cc::PaintHoldingCommitTrigger trigger) {
+ layer_tree_host()->StopDeferringCommits(trigger);
}
void TestWebWidgetClient::RegisterViewportLayers(
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 2e274d6966d..d2a3b913017 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
@@ -43,7 +43,7 @@
#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/mojom/fetch/fetch_api_request.mojom-shared.h"
+#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/scheduler/test/web_fake_thread_scheduler.h"
#include "third_party/blink/public/platform/web_mouse_event.h"
@@ -60,7 +60,7 @@
#include "third_party/blink/renderer/core/scroll/scrollbar_theme.h"
#include "third_party/blink/renderer/core/testing/use_mock_scrollbar_settings.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
#define EXPECT_FLOAT_POINT_EQ(expected, actual) \
@@ -197,13 +197,20 @@ class LayerTreeViewFactory {
std::unique_ptr<content::LayerTreeView> layer_tree_view_;
};
+struct InjectedScrollGestureData {
+ WebFloatSize delta;
+ ScrollGranularity granularity;
+ CompositorElementId scrollable_area_element_id;
+ WebInputEvent::Type type;
+};
+
class TestWebWidgetClient : public WebWidgetClient {
public:
// If no delegate is given, a stub is used.
explicit TestWebWidgetClient(content::LayerTreeViewDelegate* = nullptr);
~TestWebWidgetClient() override = default;
- // WebWidgetClient:
+ // WebWidgetClient implementation.
void ScheduleAnimation() override { animation_scheduled_ = true; }
void SetRootLayer(scoped_refptr<cc::Layer> layer) override;
void RegisterViewportLayers(const cc::ViewportLayers& layOAers) override;
@@ -219,17 +226,32 @@ class TestWebWidgetClient : public WebWidgetClient {
ScrollGranularity granularity,
cc::ElementId scrollable_area_element_id,
WebInputEvent::Type injected_type) override;
+ void SetHaveScrollEventHandlers(bool) override;
+ void SetEventListenerProperties(
+ cc::EventListenerClass event_class,
+ cc::EventListenerProperties properties) override;
+ cc::EventListenerProperties EventListenerProperties(
+ cc::EventListenerClass event_class) const override;
+ std::unique_ptr<cc::ScopedDeferMainFrameUpdate> DeferMainFrameUpdate()
+ override;
+ void StartDeferringCommits(base::TimeDelta timeout) override;
+ void StopDeferringCommits(cc::PaintHoldingCommitTrigger) override;
+ void DidMeaningfulLayout(WebMeaningfulLayout) override;
content::LayerTreeView* layer_tree_view() { return layer_tree_view_; }
cc::LayerTreeHost* layer_tree_host() {
return layer_tree_view_->layer_tree_host();
}
+ const cc::LayerTreeHost* layer_tree_host() const {
+ return layer_tree_view_->layer_tree_host();
+ }
cc::AnimationHost* animation_host() { return animation_host_; }
bool AnimationScheduled() { return animation_scheduled_; }
void ClearAnimationScheduled() { animation_scheduled_ = false; }
- void DidMeaningfulLayout(WebMeaningfulLayout) override;
+ // Returns the last value given to SetHaveScrollEventHandlers().
+ bool HaveScrollEventHandlers() const { return have_scroll_event_handlers_; }
int VisuallyNonEmptyLayoutCount() const {
return visually_non_empty_layout_count_;
@@ -240,19 +262,21 @@ class TestWebWidgetClient : public WebWidgetClient {
int FinishedLoadingLayoutCount() const {
return finished_loading_layout_count_;
}
- int InjectedGestureScrollCount() const {
- return injected_gesture_scroll_update_count_;
+ const Vector<InjectedScrollGestureData>& GetInjectedScrollGestureData()
+ const {
+ return injected_scroll_gesture_data_;
}
private:
content::LayerTreeView* layer_tree_view_ = nullptr;
cc::AnimationHost* animation_host_ = nullptr;
LayerTreeViewFactory layer_tree_view_factory_;
+ Vector<InjectedScrollGestureData> injected_scroll_gesture_data_;
bool animation_scheduled_ = false;
+ bool have_scroll_event_handlers_ = false;
int visually_non_empty_layout_count_ = 0;
int finished_parsing_layout_count_ = 0;
int finished_loading_layout_count_ = 0;
- int injected_gesture_scroll_update_count_ = 0;
};
class TestWebViewClient : public WebViewClient {
@@ -345,14 +369,25 @@ class WebViewHelper {
content::LayerTreeView* GetLayerTreeView() const {
return test_web_widget_client_->layer_tree_view();
}
+ TestWebWidgetClient* GetWebWidgetClient() const {
+ return test_web_widget_client_;
+ }
WebLocalFrameImpl* LocalMainFrame() const;
WebRemoteFrameImpl* RemoteMainFrame() const;
+ void set_viewport_enabled(bool viewport) {
+ DCHECK(!web_view_)
+ << "set_viewport_enabled() should be called before Initialize.";
+ viewport_enabled_ = viewport;
+ }
+
private:
void InitializeWebView(TestWebViewClient*,
class WebView* opener);
+ bool viewport_enabled_ = false;
+
WebViewImpl* web_view_;
UseMockScrollbarSettings mock_scrollbar_settings_;
@@ -361,6 +396,9 @@ class WebViewHelper {
std::unique_ptr<TestWebWidgetClient> owned_test_web_widget_client_;
TestWebWidgetClient* test_web_widget_client_ = nullptr;
+ // The Platform should not change during the lifetime of the test!
+ Platform* const platform_;
+
DISALLOW_COPY_AND_ASSIGN(WebViewHelper);
};
@@ -434,7 +472,7 @@ class TestWebFrameClient : public WebLocalFrameClient {
WebEffectiveConnectionType effective_connection_type_;
Vector<String> console_messages_;
- base::WeakPtrFactory<TestWebFrameClient> weak_factory_;
+ base::WeakPtrFactory<TestWebFrameClient> weak_factory_{this};
};
// Minimal implementation of WebRemoteFrameClient needed for unit tests that
diff --git a/chromium/third_party/blink/renderer/core/frame/frame_view.cc b/chromium/third_party/blink/renderer/core/frame/frame_view.cc
index 0ae6f08f2b4..d19944e57c1 100644
--- a/chromium/third_party/blink/renderer/core/frame/frame_view.cc
+++ b/chromium/third_party/blink/renderer/core/frame/frame_view.cc
@@ -4,6 +4,7 @@
#include "third_party/blink/renderer/core/frame/frame_view.h"
+#include "third_party/blink/renderer/core/display_lock/display_lock_utilities.h"
#include "third_party/blink/renderer/core/frame/frame_client.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/remote_frame.h"
@@ -11,6 +12,7 @@
#include "third_party/blink/renderer/core/intersection_observer/intersection_geometry.h"
#include "third_party/blink/renderer/core/intersection_observer/intersection_observer.h"
#include "third_party/blink/renderer/core/layout/layout_embedded_content.h"
+#include "third_party/blink/renderer/core/page/page.h"
namespace blink {
@@ -33,6 +35,17 @@ bool FrameView::CanThrottleRenderingForPropagation() const {
return !owner && frame.IsCrossOriginSubframe();
}
+bool FrameView::DisplayLockedInParentFrame() {
+ Frame& frame = GetFrame();
+ LayoutEmbeddedContent* owner = frame.OwnerLayoutObject();
+ // We check the inclusive ancestor to determine whether the subtree is locked,
+ // since the contents of the frame are in the subtree of the frame, so they
+ // would be locked if the frame owner is itself locked.
+ return owner && owner->GetNode() &&
+ DisplayLockUtilities::NearestLockedInclusiveAncestor(
+ *owner->GetNode());
+}
+
void FrameView::UpdateViewportIntersection(unsigned flags,
bool needs_occlusion_tracking) {
if (!(flags & IntersectionObservation::kImplicitRootObserversNeedUpdate))
@@ -70,8 +83,19 @@ void FrameView::UpdateViewportIntersection(unsigned flags,
IntersectionGeometry geometry(nullptr, *owner_element, {},
{IntersectionObserver::kMinimumThreshold},
geometry_flags);
- // geometry.IntersectionRect() is in absolute coordinates of the owning
- // document. Map it down to absolute coordinates in the child document.
+ PhysicalRect new_rect_in_parent = geometry.IntersectionRect();
+ if (new_rect_in_parent.size != rect_in_parent_.size ||
+ ((new_rect_in_parent.X() - rect_in_parent_.X()).Abs() +
+ (new_rect_in_parent.Y() - rect_in_parent_.Y()).Abs() >
+ LayoutUnit(kMaxChildFrameScreenRectMovement))) {
+ rect_in_parent_ = new_rect_in_parent;
+ if (Page* page = GetFrame().GetPage()) {
+ rect_in_parent_stable_since_ = page->Animator().Clock().CurrentTime();
+ } else {
+ rect_in_parent_stable_since_ = base::TimeTicks::Now();
+ }
+ }
+
PhysicalRect intersection_rect = owner_layout_object->AncestorToLocalRect(
nullptr, geometry.IntersectionRect());
// Map from the box coordinates of the owner to the inner frame.
@@ -132,7 +156,7 @@ void FrameView::UpdateRenderThrottlingStatus(bool hidden_for_throttling,
bool recurse) {
bool was_throttled = CanThrottleRendering();
hidden_for_throttling_ = hidden_for_throttling;
- subtree_throttled_ = subtree_throttled;
+ subtree_throttled_ = subtree_throttled || DisplayLockedInParentFrame();
bool throttling_did_change = (was_throttled != CanThrottleRendering());
if (throttling_did_change)
RenderThrottlingStatusChanged();
@@ -149,4 +173,16 @@ void FrameView::UpdateRenderThrottlingStatus(bool hidden_for_throttling,
}
}
+bool FrameView::RectInParentIsStable(
+ const base::TimeTicks& event_timestamp) const {
+ if (event_timestamp - rect_in_parent_stable_since_ <
+ base::TimeDelta::FromMilliseconds(kMinScreenRectStableTimeMs)) {
+ return false;
+ }
+ LocalFrameView* parent = ParentFrameView();
+ if (!parent)
+ return true;
+ return parent->RectInParentIsStable(event_timestamp);
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/frame/frame_view.h b/chromium/third_party/blink/renderer/core/frame/frame_view.h
index 2de8435e4ed..d438da4772b 100644
--- a/chromium/third_party/blink/renderer/core/frame/frame_view.h
+++ b/chromium/third_party/blink/renderer/core/frame/frame_view.h
@@ -8,6 +8,7 @@
#include "third_party/blink/public/common/frame/occlusion_state.h"
#include "third_party/blink/public/mojom/frame/lifecycle.mojom-blink.h"
#include "third_party/blink/renderer/core/frame/embedded_content_view.h"
+#include "third_party/blink/renderer/core/layout/geometry/physical_rect.h"
#include "third_party/blink/renderer/platform/wtf/casting.h"
namespace blink {
@@ -52,6 +53,8 @@ class CORE_EXPORT FrameView : public EmbeddedContentView {
bool subtree_throttled,
bool recurse = false);
+ bool RectInParentIsStable(const base::TimeTicks& timestamp) const;
+
protected:
virtual void SetViewportIntersection(const IntRect& viewport_intersection,
FrameOcclusionState occlusion_state) = 0;
@@ -62,7 +65,11 @@ class CORE_EXPORT FrameView : public EmbeddedContentView {
// lifecycle updates for a frame outside the viewport.
void UpdateFrameVisibility(bool);
+ bool DisplayLockedInParentFrame();
+
private:
+ PhysicalRect rect_in_parent_;
+ base::TimeTicks rect_in_parent_stable_since_;
blink::mojom::FrameVisibility frame_visibility_ =
blink::mojom::FrameVisibility::kRenderedInViewport;
bool hidden_for_throttling_;
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 94318fc76bb..c66b4c26227 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
@@ -9,7 +9,7 @@
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/platform/geometry/int_size.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 c2893bede20..726ac9aa872 100644
--- a/chromium/third_party/blink/renderer/core/frame/fullscreen_controller.h
+++ b/chromium/third_party/blink/renderer/core/frame/fullscreen_controller.h
@@ -39,7 +39,7 @@
#include "third_party/blink/renderer/platform/geometry/int_size.h"
#include "third_party/blink/renderer/platform/graphics/color.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/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/frame/history.cc b/chromium/third_party/blink/renderer/core/frame/history.cc
index 519e1bd6f2c..f7d88d1cdbd 100644
--- a/chromium/third_party/blink/renderer/core/frame/history.cc
+++ b/chromium/third_party/blink/renderer/core/frame/history.cc
@@ -31,7 +31,6 @@
#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"
@@ -39,6 +38,7 @@
#include "third_party/blink/renderer/core/page/page.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/instrumentation/use_counter.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/text/string_view.h"
diff --git a/chromium/third_party/blink/renderer/core/frame/history.idl b/chromium/third_party/blink/renderer/core/frame/history.idl
index 182cfa0504c..87f36912142 100644
--- a/chromium/third_party/blink/renderer/core/frame/history.idl
+++ b/chromium/third_party/blink/renderer/core/frame/history.idl
@@ -27,7 +27,9 @@
enum ScrollRestoration {"auto", "manual"};
-interface History {
+[
+ Exposed=Window
+] interface History {
[MeasureAs=HistoryLength, RaisesException] readonly attribute unsigned long length;
[Measure, RaisesException] attribute ScrollRestoration scrollRestoration;
// TODO(foolip): The SerializedScriptValue type should be any.
diff --git a/chromium/third_party/blink/renderer/core/frame/intervention.h b/chromium/third_party/blink/renderer/core/frame/intervention.h
index b9016f124cf..8089995d989 100644
--- a/chromium/third_party/blink/renderer/core/frame/intervention.h
+++ b/chromium/third_party/blink/renderer/core/frame/intervention.h
@@ -7,7 +7,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/frame/layout_subtree_root_list.h b/chromium/third_party/blink/renderer/core/frame/layout_subtree_root_list.h
index 49a8f4efb0b..608edbe5521 100644
--- a/chromium/third_party/blink/renderer/core/frame/layout_subtree_root_list.h
+++ b/chromium/third_party/blink/renderer/core/frame/layout_subtree_root_list.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_LAYOUT_SUBTREE_ROOT_LIST_H_
#include "third_party/blink/renderer/core/layout/depth_ordered_layout_object_list.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
namespace blink {
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 989998baf87..69c1753174d 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
@@ -55,7 +55,6 @@
#include "third_party/blink/renderer/core/dom/events/scoped_event_queue.h"
#include "third_party/blink/renderer/core/dom/frame_request_callback_collection.h"
#include "third_party/blink/renderer/core/dom/scripted_idle_task_controller.h"
-#include "third_party/blink/renderer/core/dom/scripted_task_queue_controller.h"
#include "third_party/blink/renderer/core/dom/sink_document.h"
#include "third_party/blink/renderer/core/dom/user_gesture_indicator.h"
#include "third_party/blink/renderer/core/editing/editor.h"
@@ -93,7 +92,6 @@
#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/create_window.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/scrolling/scrolling_coordinator.h"
#include "third_party/blink/renderer/core/page/scrolling/snap_coordinator.h"
@@ -116,7 +114,8 @@
namespace blink {
// Timeout for link preloads to be used after window.onload
-static constexpr TimeDelta kUnusedPreloadTimeout = TimeDelta::FromSeconds(3);
+static constexpr base::TimeDelta kUnusedPreloadTimeout =
+ base::TimeDelta::FromSeconds(3);
static void UpdateSuddenTerminationStatus(
LocalDOMWindow* dom_window,
@@ -132,14 +131,15 @@ using DOMWindowSet = HeapHashCountedSet<WeakMember<LocalDOMWindow>>;
static DOMWindowSet& WindowsWithUnloadEventListeners() {
DEFINE_STATIC_LOCAL(Persistent<DOMWindowSet>,
- windows_with_unload_event_listeners, (new DOMWindowSet));
+ windows_with_unload_event_listeners,
+ (MakeGarbageCollected<DOMWindowSet>()));
return *windows_with_unload_event_listeners;
}
static DOMWindowSet& WindowsWithBeforeUnloadEventListeners() {
DEFINE_STATIC_LOCAL(Persistent<DOMWindowSet>,
windows_with_before_unload_event_listeners,
- (new DOMWindowSet));
+ (MakeGarbageCollected<DOMWindowSet>()));
return *windows_with_before_unload_event_listeners;
}
@@ -554,27 +554,18 @@ void LocalDOMWindow::SchedulePostMessage(
->PostTask(FROM_HERE,
WTF::Bind(&LocalDOMWindow::DispatchPostMessage,
WrapPersistent(this), WrapPersistent(event),
- WrapRefCounted(UserGestureIndicator::CurrentToken()),
std::move(target), std::move(location)));
probe::AsyncTaskScheduled(document(), "postMessage", event);
}
void LocalDOMWindow::DispatchPostMessage(
MessageEvent* event,
- scoped_refptr<UserGestureToken> token,
scoped_refptr<const SecurityOrigin> intended_target_origin,
std::unique_ptr<SourceLocation> location) {
probe::AsyncTask async_task(document(), event);
if (!IsCurrentlyDisplayedInFrame())
return;
- std::unique_ptr<UserGestureIndicator> gesture_indicator;
- if (!RuntimeEnabledFeatures::UserActivationV2Enabled() && token &&
- token->HasGestures() && document()) {
- gesture_indicator =
- LocalFrame::NotifyUserActivation(document()->GetFrame(), token.get());
- }
-
event->EntangleMessagePorts(document());
DispatchMessageEventWithOriginCheck(intended_target_origin.get(), event,
@@ -993,13 +984,6 @@ ScriptPromise LocalDOMWindow::getComputedAccessibleNode(
return promise;
}
-ScriptedTaskQueueController* LocalDOMWindow::taskQueue() const {
- if (Document* document = this->document()) {
- return ScriptedTaskQueueController::From(*document);
- }
- return nullptr;
-}
-
double LocalDOMWindow::devicePixelRatio() const {
if (!GetFrame())
return 0.0;
@@ -1028,12 +1012,16 @@ void LocalDOMWindow::scrollBy(const ScrollToOptions* scroll_to_options) const {
if (!page)
return;
- 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());
+ float x = 0.0f;
+ float y = 0.0f;
+ if (scroll_to_options->hasLeft()) {
+ x = ScrollableArea::NormalizeNonFiniteScroll(
+ base::saturated_cast<float>(scroll_to_options->left()));
+ }
+ if (scroll_to_options->hasTop()) {
+ y = ScrollableArea::NormalizeNonFiniteScroll(
+ base::saturated_cast<float>(scroll_to_options->top()));
+ }
PaintLayerScrollableArea* viewport = view->LayoutViewport();
FloatPoint current_position = viewport->ScrollPosition();
@@ -1084,23 +1072,25 @@ void LocalDOMWindow::scrollTo(const ScrollToOptions* scroll_to_options) const {
document()->UpdateStyleAndLayout();
}
- double scaled_x = 0.0;
- double scaled_y = 0.0;
+ float scaled_x = 0.0f;
+ float scaled_y = 0.0f;
PaintLayerScrollableArea* viewport = view->LayoutViewport();
ScrollOffset current_offset = viewport->GetScrollOffset();
scaled_x = current_offset.Width();
scaled_y = current_offset.Height();
- if (scroll_to_options->hasLeft())
- scaled_x =
- ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options->left()) *
- GetFrame()->PageZoomFactor();
+ if (scroll_to_options->hasLeft()) {
+ scaled_x = ScrollableArea::NormalizeNonFiniteScroll(
+ base::saturated_cast<float>(scroll_to_options->left())) *
+ GetFrame()->PageZoomFactor();
+ }
- if (scroll_to_options->hasTop())
- scaled_y =
- ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options->top()) *
- GetFrame()->PageZoomFactor();
+ if (scroll_to_options->hasTop()) {
+ scaled_y = ScrollableArea::NormalizeNonFiniteScroll(
+ base::saturated_cast<float>(scroll_to_options->top())) *
+ GetFrame()->PageZoomFactor();
+ }
FloatPoint new_scaled_position =
viewport->ScrollOffsetToPosition(ScrollOffset(scaled_x, scaled_y));
@@ -1229,9 +1219,9 @@ void LocalDOMWindow::cancelPostAnimationFrame(int id) {
}
void LocalDOMWindow::queueMicrotask(V8VoidFunction* callback) {
- Microtask::EnqueueMicrotask(WTF::Bind(
- &V8PersistentCallbackFunction<V8VoidFunction>::InvokeAndReportException,
- WrapPersistent(ToV8PersistentCallbackFunction(callback)), nullptr));
+ Microtask::EnqueueMicrotask(
+ WTF::Bind(&V8VoidFunction::InvokeAndReportException,
+ WrapPersistent(callback), nullptr));
}
int LocalDOMWindow::requestIdleCallback(V8IdleRequestCallback* callback,
@@ -1511,7 +1501,8 @@ DOMWindow* LocalDOMWindow::open(v8::Isolate* isolate,
SecurityPolicy::GenerateReferrer(
active_document->GetReferrerPolicy(), completed_url,
window_features.noreferrer ? Referrer::NoReferrer()
- : active_document->OutgoingReferrer()));
+ : active_document->OutgoingReferrer()),
+ ResourceRequest::SetHttpReferrerLocation::kLocalDomWindow);
frame_request.GetResourceRequest().SetHasUserGesture(
LocalFrame::HasTransientUserActivation(GetFrame()));
@@ -1523,18 +1514,6 @@ DOMWindow* LocalDOMWindow::open(v8::Isolate* isolate,
if (!result.frame)
return nullptr;
- // If the navigation opened a new window, focus is handled during window
- // creation. If the navigation reused an existing frame in a different page,
- // FindOrCreateFrameForNavigation() took care of focus. Most navigations don't
- // refocus when a different frame in the same page is navigated, but
- // window.open() does. Why?
- if (result.frame->GetPage() == GetFrame()->GetPage()) {
- GetFrame()->GetPage()->GetFocusController().SetFocusedFrame(result.frame);
- // Focusing can fire onblur, so check for detach.
- if (!result.frame->GetPage())
- return nullptr;
- }
-
if (!completed_url.IsEmpty() || result.new_window)
result.frame->Navigate(frame_request, WebFrameLoadType::kStandard);
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 548ed670561..c2190f73565 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
@@ -61,7 +61,6 @@ class MessageEvent;
class Modulator;
class Navigator;
class Screen;
-class ScriptedTaskQueueController;
class ScriptPromise;
class ScriptState;
class ScrollToOptions;
@@ -218,8 +217,6 @@ class CORE_EXPORT LocalDOMWindow final : public DOMWindow,
// Acessibility Object Model
ScriptPromise getComputedAccessibleNode(ScriptState*, Element*);
- ScriptedTaskQueueController* taskQueue() const;
-
// WebKit animation extensions
int requestAnimationFrame(V8FrameRequestCallback*);
int webkitRequestAnimationFrame(V8FrameRequestCallback*);
@@ -281,7 +278,6 @@ class CORE_EXPORT LocalDOMWindow final : public DOMWindow,
void DispatchPostMessage(
MessageEvent* event,
- scoped_refptr<UserGestureToken> token,
scoped_refptr<const SecurityOrigin> intended_target_origin,
std::unique_ptr<SourceLocation> location);
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 06f9c9f62dc..1f5407c50ed 100644
--- a/chromium/third_party/blink/renderer/core/frame/local_frame.cc
+++ b/chromium/third_party/blink/renderer/core/frame/local_frame.cc
@@ -37,6 +37,7 @@
#include "services/network/public/cpp/features.h"
#include "services/service_manager/public/cpp/connector.h"
#include "services/service_manager/public/cpp/interface_provider.h"
+#include "third_party/blink/public/common/frame/blocked_navigation_types.h"
#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"
@@ -75,7 +76,6 @@
#include "third_party/blink/renderer/core/frame/report.h"
#include "third_party/blink/renderer/core/frame/reporting_context.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_element_base.h"
#include "third_party/blink/renderer/core/html/html_plugin_element.h"
#include "third_party/blink/renderer/core/html/plugin_document.h"
@@ -83,6 +83,7 @@
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/core/inspector/inspector_task_runner.h"
#include "third_party/blink/renderer/core/inspector/inspector_trace_events.h"
+#include "third_party/blink/renderer/core/intersection_observer/intersection_observer_controller.h"
#include "third_party/blink/renderer/core/layout/hit_test_result.h"
#include "third_party/blink/renderer/core/layout/layout_embedded_content.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
@@ -110,8 +111,9 @@
#include "third_party/blink/renderer/platform/graphics/paint/scoped_paint_chunk_properties.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
#include "third_party/blink/renderer/platform/heap/persistent.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/instrumentation/resource_coordinator/document_resource_coordinator.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#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"
@@ -144,69 +146,9 @@ bool ShouldUseClientLoFiForRequest(
if (!(frame_previews_state & WebURLRequest::kClientLoFiOn))
return false;
- // Even if this frame is using Server Lo-Fi, https:// images won't be
- // handled by Server Lo-Fi since their requests won't be sent to the Data
- // Saver proxy, so use Client Lo-Fi instead.
- if (frame_previews_state & WebURLRequest::kServerLoFiOn)
- return request.Url().ProtocolIs("https");
-
return true;
}
-WeakPersistent<LocalFrame>& UserActivationNotifierFrame() {
- DEFINE_STATIC_LOCAL(WeakPersistent<LocalFrame>,
- user_activation_notifier_frame, (nullptr));
- return user_activation_notifier_frame;
-}
-
-enum class UserActivationFrameResultEnum : int {
- kNullFailure = 0,
- kNullSuccess = 1,
- kSelfFailure = 2,
- kSelfSuccess = 3,
- kAncestorFailure = 4,
- kAncestorSuccess = 5,
- kDescendantFailure = 6,
- kDescendantSuccess = 7,
- kOtherFailure = 8,
- kOtherSuccess = 9,
- kNonMainThreadFailure = 10,
- kNonMainThreadSuccess = 11,
- kMaxValue = kNonMainThreadSuccess
-};
-
-UserActivationFrameResultEnum DetermineActivationResultEnum(
- const LocalFrame* const caller_frame,
- const bool call_succeeded,
- const bool off_main_thread) {
- if (off_main_thread) {
- return call_succeeded
- ? UserActivationFrameResultEnum::kNonMainThreadSuccess
- : UserActivationFrameResultEnum::kNonMainThreadFailure;
- }
-
- LocalFrame* user_activation_notifier_frame = UserActivationNotifierFrame();
-
- if (!caller_frame || !user_activation_notifier_frame) {
- return call_succeeded ? UserActivationFrameResultEnum::kNullSuccess
- : UserActivationFrameResultEnum::kNullFailure;
- }
- if (caller_frame == user_activation_notifier_frame) {
- return call_succeeded ? UserActivationFrameResultEnum::kSelfSuccess
- : UserActivationFrameResultEnum::kSelfFailure;
- }
- if (user_activation_notifier_frame->Tree().IsDescendantOf(caller_frame)) {
- return call_succeeded ? UserActivationFrameResultEnum::kAncestorSuccess
- : UserActivationFrameResultEnum::kAncestorFailure;
- }
- if (caller_frame->Tree().IsDescendantOf(user_activation_notifier_frame)) {
- return call_succeeded ? UserActivationFrameResultEnum::kDescendantSuccess
- : UserActivationFrameResultEnum::kDescendantFailure;
- }
- return call_succeeded ? UserActivationFrameResultEnum::kOtherSuccess
- : UserActivationFrameResultEnum::kOtherFailure;
-}
-
} // namespace
template class CORE_TEMPLATE_EXPORT Supplement<LocalFrame>;
@@ -337,9 +279,6 @@ void LocalFrame::DetachImpl(FrameDetachType type) {
// Starting here, the code must be safe against re-entrancy. Dispatching
// events, et cetera can run Javascript, which can reenter Detach().
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
- if (this == UserActivationNotifierFrame())
- UserActivationNotifierFrame().Clear();
-
frame_color_overlay_.reset();
if (IsLocalRoot()) {
@@ -430,8 +369,8 @@ void LocalFrame::DetachImpl(FrameDetachType type) {
WeakIdentifierMap<LocalFrame>::NotifyObjectDestroyed(this);
}
-bool LocalFrame::PrepareForCommit() {
- return Loader().PrepareForCommit();
+bool LocalFrame::DetachDocument() {
+ return Loader().DetachDocument();
}
void LocalFrame::CheckCompleted() {
@@ -552,9 +491,7 @@ void LocalFrame::DidChangeVisibilityState() {
void LocalFrame::DidFreeze() {
if (GetDocument()) {
- auto* document_resource_coordinator =
- GetDocument()->GetResourceCoordinator();
- if (document_resource_coordinator) {
+ if (GetDocument()->GetResourceCoordinator()) {
// Determine if there is a beforeunload handler by dispatching a
// beforeunload that will *not* launch a user dialog. If
// |proceed| is false then there is a non-empty beforeunload
@@ -562,13 +499,21 @@ void LocalFrame::DidFreeze() {
bool unused_did_allow_navigation = false;
bool proceed = GetDocument()->DispatchBeforeUnloadEvent(
nullptr, false /* is_reload */, unused_did_allow_navigation);
- document_resource_coordinator->SetHasNonEmptyBeforeUnload(!proceed);
+ // Running the beforeunload event may invalidate the
+ // DocumentResourceCoordinator. Because of that, it can't be stored in a
+ // local variable that is reused throughout the method.
+ // https://crbug.com/991380.
+ auto* document_resource_coordinator =
+ GetDocument()->GetResourceCoordinator();
+ if (document_resource_coordinator)
+ document_resource_coordinator->SetHasNonEmptyBeforeUnload(!proceed);
}
GetDocument()->DispatchFreezeEvent();
// TODO(fmeawad): Move the following logic to the page once we have a
// PageResourceCoordinator in Blink. http://crbug.com/838415
- if (document_resource_coordinator) {
+ if (auto* document_resource_coordinator =
+ GetDocument()->GetResourceCoordinator()) {
document_resource_coordinator->SetLifecycleState(
resource_coordinator::mojom::LifecycleState::kFrozen);
}
@@ -577,9 +522,9 @@ void LocalFrame::DidFreeze() {
void LocalFrame::DidResume() {
if (GetDocument()) {
- const TimeTicks resume_event_start = CurrentTimeTicks();
+ const base::TimeTicks resume_event_start = base::TimeTicks::Now();
GetDocument()->DispatchEvent(*Event::Create(event_type_names::kResume));
- const TimeTicks resume_event_end = CurrentTimeTicks();
+ const base::TimeTicks resume_event_end = base::TimeTicks::Now();
DEFINE_STATIC_LOCAL(
CustomCountHistogram, resume_histogram,
("DocumentEventTiming.ResumeDuration", 0, 10000000, 50));
@@ -831,7 +776,7 @@ String LocalFrame::SelectedTextForClipboard() const {
}
PositionWithAffinity LocalFrame::PositionForPoint(
- const LayoutPoint& frame_point) {
+ const PhysicalOffset& frame_point) {
HitTestLocation location(frame_point);
HitTestResult result = GetEventHandler().HitTestResultAtLocation(location);
Node* node = result.InnerNodeOrImageMapImage();
@@ -847,7 +792,8 @@ PositionWithAffinity LocalFrame::PositionForPoint(
return position;
}
-Document* LocalFrame::DocumentAtPoint(const LayoutPoint& point_in_root_frame) {
+Document* LocalFrame::DocumentAtPoint(
+ const PhysicalOffset& point_in_root_frame) {
if (!View())
return nullptr;
@@ -892,11 +838,14 @@ bool LocalFrame::ShouldThrottleRendering() const {
LocalFrame::LocalFrame(LocalFrameClient* client,
Page& page,
FrameOwner* owner,
- InterfaceRegistry* interface_registry)
+ WindowAgentFactory* inheriting_agent_factory,
+ InterfaceRegistry* interface_registry,
+ const base::TickClock* clock)
: Frame(client,
page,
owner,
- MakeGarbageCollected<LocalWindowProxyManager>(*this)),
+ MakeGarbageCollected<LocalWindowProxyManager>(*this),
+ inheriting_agent_factory),
frame_scheduler_(page.GetPageScheduler()->CreateFrameScheduler(
this,
client->GetFrameBlameContext(),
@@ -945,7 +894,7 @@ LocalFrame::LocalFrame(LocalFrameClient* client,
ad_tracker_ = LocalFrameRoot().ad_tracker_;
performance_monitor_ = LocalFrameRoot().performance_monitor_;
}
- idleness_detector_ = MakeGarbageCollected<IdlenessDetector>(this);
+ idleness_detector_ = MakeGarbageCollected<IdlenessDetector>(this, clock);
inspector_task_runner_->InitIsolate(V8PerIsolateData::MainThreadIsolate());
if (ad_tracker_) {
@@ -1076,6 +1025,9 @@ bool LocalFrame::CanNavigate(const Frame& target_frame,
!LocalFrame::HasTransientUserActivation(this)) {
// With only 'allow-top-navigation-by-user-activation' (but not
// 'allow-top-navigation'), top navigation requires a user gesture.
+ Client()->DidBlockNavigation(
+ destination_url, GetDocument()->Url(),
+ blink::NavigationBlockedReason::kRedirectWithNoUserGestureSandbox);
PrintNavigationErrorMessage(
target_frame,
"The frame attempting navigation of the top-level window is "
@@ -1148,7 +1100,9 @@ bool LocalFrame::CanNavigate(const Frame& target_frame,
"but is neither same-origin with its target nor has it received a "
"user gesture. See "
"https://www.chromestatus.com/features/5851021045661696.");
- Client()->DidBlockFramebust(destination_url);
+ Client()->DidBlockNavigation(
+ destination_url, GetDocument()->Url(),
+ blink::NavigationBlockedReason::kRedirectWithNoUserGesture);
} else {
PrintNavigationErrorMessage(target_frame,
"The frame attempting navigation is neither "
@@ -1183,8 +1137,8 @@ ContentCaptureManager* LocalFrame::GetContentCaptureManager() {
if (auto* content_capture_client = Client()->GetWebContentCaptureClient()) {
if (!content_capture_manager_) {
- content_capture_manager_ = MakeGarbageCollected<ContentCaptureManager>(
- *this, content_capture_client->GetNodeHolderType());
+ content_capture_manager_ =
+ MakeGarbageCollected<ContentCaptureManager>(*this);
}
} else if (content_capture_manager_) {
content_capture_manager_->Shutdown();
@@ -1290,23 +1244,38 @@ bool LocalFrame::IsClientLoFiAllowed(const ResourceRequest& request) const {
request, Client()->GetPreviewsStateForFrame());
}
-LocalFrame::LazyLoadImageEnabledState LocalFrame::GetLazyLoadImageEnabledState()
- const {
+LocalFrame::LazyLoadImageSetting LocalFrame::GetLazyLoadImageSetting() const {
DCHECK(GetSettings());
if (!RuntimeEnabledFeatures::LazyImageLoadingEnabled() ||
!GetSettings()->GetLazyLoadEnabled()) {
- return LocalFrame::LazyLoadImageEnabledState::kDisabled;
+ return LocalFrame::LazyLoadImageSetting::kDisabled;
}
if (!RuntimeEnabledFeatures::AutomaticLazyImageLoadingEnabled())
- return LocalFrame::LazyLoadImageEnabledState::kEnabledExplicit;
+ return LocalFrame::LazyLoadImageSetting::kEnabledExplicit;
if (RuntimeEnabledFeatures::
RestrictAutomaticLazyImageLoadingToDataSaverEnabled() &&
!is_save_data_enabled_) {
- return LocalFrame::LazyLoadImageEnabledState::kEnabledExplicit;
+ return LocalFrame::LazyLoadImageSetting::kEnabledExplicit;
+ }
+
+ // Skip automatic lazyload when reloading a page.
+ if (!RuntimeEnabledFeatures::AutoLazyLoadOnReloadsEnabled() &&
+ Loader().GetDocumentLoader() &&
+ IsReloadLoadType(Loader().GetDocumentLoader()->LoadType())) {
+ return LocalFrame::LazyLoadImageSetting::kEnabledExplicit;
}
+
if (Owner() && !Owner()->ShouldLazyLoadChildren())
- return LocalFrame::LazyLoadImageEnabledState::kEnabledExplicit;
- return LocalFrame::LazyLoadImageEnabledState::kEnabledAutomatic;
+ return LocalFrame::LazyLoadImageSetting::kEnabledExplicit;
+ return LocalFrame::LazyLoadImageSetting::kEnabledAutomatic;
+}
+
+bool LocalFrame::ShouldForceDeferScript() const {
+ // Check if enabled by runtime feature (for testing/evaluation) or if enabled
+ // by PreviewsState (for live intervention).
+ return RuntimeEnabledFeatures::ForceDeferScriptInterventionEnabled() ||
+ (Client() && Client()->GetPreviewsStateForFrame() ==
+ WebURLRequest::kDeferAllScriptOn);
}
WebURLLoaderFactory* LocalFrame::GetURLLoaderFactory() {
@@ -1371,6 +1340,16 @@ FrameOcclusionState LocalFrame::GetOcclusionState() const {
return LocalFrameRoot().GetOcclusionState();
}
+bool LocalFrame::NeedsOcclusionTracking() const {
+ if (Document* document = GetDocument()) {
+ if (IntersectionObserverController* controller =
+ document->GetIntersectionObserverController()) {
+ return controller->NeedsOcclusionTracking();
+ }
+ }
+ return false;
+}
+
void LocalFrame::ForceSynchronousDocumentInstall(
const AtomicString& mime_type,
scoped_refptr<SharedBuffer> data) {
@@ -1422,8 +1401,7 @@ bool LocalFrame::IsUsingDataSavingPreview() const {
Client()->GetPreviewsStateForFrame();
// Check for any data saving type of preview.
return previews_state &
- (WebURLRequest::kServerLoFiOn | WebURLRequest::kClientLoFiOn |
- WebURLRequest::kNoScriptOn);
+ (WebURLRequest::kClientLoFiOn | WebURLRequest::kNoScriptOn);
}
bool LocalFrame::IsAdSubframe() const {
@@ -1536,10 +1514,8 @@ const mojom::blink::ReportingServiceProxyPtr& LocalFrame::GetReportingService()
std::unique_ptr<UserGestureIndicator> LocalFrame::NotifyUserActivation(
LocalFrame* frame,
UserGestureToken::Status status) {
- if (frame) {
- UserActivationNotifierFrame() = frame;
+ if (frame)
frame->NotifyUserActivation();
- }
return std::make_unique<UserGestureIndicator>(status);
}
@@ -1548,32 +1524,20 @@ std::unique_ptr<UserGestureIndicator> LocalFrame::NotifyUserActivation(
LocalFrame* frame,
UserGestureToken* token) {
DCHECK(!RuntimeEnabledFeatures::UserActivationV2Enabled());
- if (frame) {
- UserActivationNotifierFrame() = frame;
+ if (frame)
frame->NotifyUserActivation();
- }
return std::make_unique<UserGestureIndicator>(token);
}
// static
bool LocalFrame::HasTransientUserActivation(LocalFrame* frame,
bool check_if_main_thread) {
- bool available;
-
- if (RuntimeEnabledFeatures::UserActivationV2Enabled()) {
- available = frame ? frame->HasTransientUserActivation() : false;
- } else {
- available = check_if_main_thread
- ? UserGestureIndicator::ProcessingUserGestureThreadSafe()
- : UserGestureIndicator::ProcessingUserGesture();
- }
-
- const bool off_main_thread = check_if_main_thread && !IsMainThread();
- UMA_HISTOGRAM_ENUMERATION(
- "UserActivation.AvailabilityCheck.FrameResult",
- DetermineActivationResultEnum(frame, available, off_main_thread));
+ if (RuntimeEnabledFeatures::UserActivationV2Enabled())
+ return frame ? frame->HasTransientUserActivation() : false;
- return available;
+ return check_if_main_thread
+ ? UserGestureIndicator::ProcessingUserGestureThreadSafe()
+ : UserGestureIndicator::ProcessingUserGesture();
}
// static
@@ -1581,25 +1545,12 @@ bool LocalFrame::ConsumeTransientUserActivation(
LocalFrame* frame,
bool check_if_main_thread,
UserActivationUpdateSource update_source) {
- bool consumed;
-
- if (RuntimeEnabledFeatures::UserActivationV2Enabled()) {
- consumed =
- frame ? frame->ConsumeTransientUserActivation(update_source) : false;
- } else {
- consumed = check_if_main_thread
- ? UserGestureIndicator::ConsumeUserGestureThreadSafe()
- : UserGestureIndicator::ConsumeUserGesture();
- }
-
- const bool off_main_thread = check_if_main_thread && !IsMainThread();
- UMA_HISTOGRAM_ENUMERATION(
- "UserActivation.Consumption.FrameResult",
- DetermineActivationResultEnum(frame, consumed, off_main_thread));
- if (!off_main_thread)
- UserActivationNotifierFrame().Clear();
+ if (RuntimeEnabledFeatures::UserActivationV2Enabled())
+ return frame ? frame->ConsumeTransientUserActivation(update_source) : false;
- return consumed;
+ return check_if_main_thread
+ ? UserGestureIndicator::ConsumeUserGestureThreadSafe()
+ : UserGestureIndicator::ConsumeUserGesture();
}
void LocalFrame::NotifyUserActivation() {
@@ -1745,6 +1696,8 @@ void LocalFrame::SetLifecycleState(mojom::FrameLifecycleState state) {
if (old_state != mojom::FrameLifecycleState::kPaused)
DidResume();
}
+ if (Client())
+ Client()->LifecycleStateChanged(state);
}
void LocalFrame::MaybeLogAdClickNavigation() {
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 784ff44bf47..46c9ab9a6f2 100644
--- a/chromium/third_party/blink/renderer/core/frame/local_frame.h
+++ b/chromium/third_party/blink/renderer/core/frame/local_frame.h
@@ -32,6 +32,7 @@
#include <memory>
#include "base/macros.h"
+#include "base/time/default_tick_clock.h"
#include "mojo/public/cpp/bindings/strong_binding_set.h"
#include "third_party/blink/public/common/frame/occlusion_state.h"
#include "third_party/blink/public/mojom/ad_tagging/ad_frame.mojom-blink.h"
@@ -51,7 +52,7 @@
#include "third_party/blink/renderer/core/loader/frame_loader.h"
#include "third_party/blink/renderer/platform/graphics/touch_action.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/instance_counters.h"
+#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h"
#include "third_party/blink/renderer/platform/loader/fetch/client_hints_preferences.h"
#include "third_party/blink/renderer/platform/scheduler/public/frame_scheduler.h"
#include "third_party/blink/renderer/platform/supplementable.h"
@@ -119,10 +120,15 @@ class CORE_EXPORT LocalFrame final : public Frame,
USING_GARBAGE_COLLECTED_MIXIN(LocalFrame);
public:
- LocalFrame(LocalFrameClient*,
- Page&,
- FrameOwner*,
- InterfaceRegistry* = nullptr);
+ // For a description of |inheriting_agent_factory| go see the comment on the
+ // Frame constructor.
+ LocalFrame(
+ LocalFrameClient*,
+ Page&,
+ FrameOwner*,
+ WindowAgentFactory* inheriting_agent_factory,
+ InterfaceRegistry*,
+ const base::TickClock* clock = base::DefaultTickClock::GetInstance());
void Init();
void SetView(LocalFrameView*);
@@ -136,7 +142,7 @@ class CORE_EXPORT LocalFrame final : public Frame,
SecurityContext* GetSecurityContext() const override;
void PrintNavigationErrorMessage(const Frame&, const char* reason);
void PrintNavigationWarning(const String&);
- bool PrepareForCommit() override;
+ bool DetachDocument() override;
void CheckCompleted() override;
void DidChangeVisibilityState() override;
void DidFreeze() override;
@@ -262,8 +268,8 @@ class CORE_EXPORT LocalFrame final : public Frame,
String SelectedTextForClipboard() const;
PositionWithAffinityTemplate<EditingAlgorithm<NodeTraversal>>
- PositionForPoint(const LayoutPoint& frame_point);
- Document* DocumentAtPoint(const LayoutPoint&);
+ PositionForPoint(const PhysicalOffset& frame_point);
+ Document* DocumentAtPoint(const PhysicalOffset&);
void RemoveSpellingMarkersUnderWords(const Vector<String>& words);
@@ -317,13 +323,17 @@ class CORE_EXPORT LocalFrame final : public Frame,
// Returns true if Client Lo-Fi should be used for this request.
bool IsClientLoFiAllowed(const ResourceRequest&) const;
- enum class LazyLoadImageEnabledState {
+ enum class LazyLoadImageSetting {
kDisabled,
kEnabledExplicit,
kEnabledAutomatic
};
// Returns the enabled state of lazyloading of images.
- LazyLoadImageEnabledState GetLazyLoadImageEnabledState() const;
+ LazyLoadImageSetting GetLazyLoadImageSetting() const;
+
+ // Returns true if parser-blocking script should be force-deferred to execute
+ // after parsing completes for this frame.
+ bool ShouldForceDeferScript() const;
// The returned value is a off-heap raw-ptr and should not be stored.
WebURLLoaderFactory* GetURLLoaderFactory();
@@ -346,6 +356,7 @@ class CORE_EXPORT LocalFrame final : public Frame,
return remote_viewport_intersection_;
}
FrameOcclusionState GetOcclusionState() const;
+ bool NeedsOcclusionTracking() const;
// Replaces the initial empty document with a Document suitable for
// |mime_type| and populated with the contents of |data|. Only intended for
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 91d714cd094..f3845a63461 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
@@ -33,6 +33,8 @@
#include <memory>
+#include "mojo/public/cpp/bindings/pending_associated_receiver.h"
+#include "mojo/public/cpp/bindings/pending_associated_remote.h"
#include "third_party/blink/public/common/feature_policy/feature_policy.h"
#include "third_party/blink/public/common/user_agent/user_agent_metadata.h"
#include "third_party/blink/public/mojom/frame/navigation_initiator.mojom-blink.h"
@@ -101,10 +103,7 @@ class ResourceError;
class ResourceRequest;
class ResourceResponse;
class SecurityOrigin;
-class WebApplicationCacheHost;
-class WebApplicationCacheHostClient;
class WebContentCaptureClient;
-class WebCookieJar;
class WebDedicatedWorkerHostFactoryClient;
class WebLayerTreeView;
class WebLocalFrame;
@@ -246,8 +245,8 @@ class CORE_EXPORT LocalFrameClient : public FrameClient {
bool /*is_animated*/) {}
// Reports that visible elements in the frame shifted (bit.ly/lsm-explainer).
- virtual void DidObserveLayoutJank(double jank_fraction,
- bool after_input_or_scroll) {}
+ virtual void DidObserveLayoutShift(double score, bool after_input_or_scroll) {
+ }
// Reports lazy loaded behavior when the frame or image is fully deferred or
// if the frame or image is loaded after being deferred. Called every time the
@@ -291,8 +290,8 @@ class CORE_EXPORT LocalFrameClient : public FrameClient {
// identifies the portal.
virtual std::pair<RemoteFrame*, base::UnguessableToken> CreatePortal(
HTMLPortalElement*,
- mojom::blink::PortalAssociatedRequest,
- mojom::blink::PortalClientAssociatedPtrInfo) = 0;
+ mojo::PendingAssociatedReceiver<mojom::blink::Portal>,
+ mojo::PendingAssociatedRemote<mojom::blink::PortalClient>) = 0;
// Adopts the predecessor |portal|. The HTMLPortalElement must have been
// created by adopting the predecessor in the PortalActivateEvent, and have a
@@ -343,12 +342,10 @@ class CORE_EXPORT LocalFrameClient : public FrameClient {
return false;
}
- virtual WebCookieJar* CookieJar() const = 0;
-
virtual void DidChangeName(const String&) {}
virtual void DidEnforceInsecureRequestPolicy(WebInsecureRequestPolicy) {}
- virtual void DidEnforceInsecureNavigationsSet(const std::vector<unsigned>&) {}
+ virtual void DidEnforceInsecureNavigationsSet(const WebVector<unsigned>&) {}
virtual void DidChangeFramePolicy(Frame* child_frame, const FramePolicy&) {}
@@ -375,10 +372,6 @@ class CORE_EXPORT LocalFrameClient : public FrameClient {
virtual WebContentSettingsClient* GetContentSettingsClient() = 0;
- virtual std::unique_ptr<WebApplicationCacheHost> CreateApplicationCacheHost(
- DocumentLoader*,
- WebApplicationCacheHostClient*) = 0;
-
virtual void DispatchDidChangeManifest() {}
unsigned BackForwardLength() override { return 0; }
@@ -458,7 +451,9 @@ class CORE_EXPORT LocalFrameClient : public FrameClient {
virtual void AnnotatedRegionsChanged() = 0;
- virtual void DidBlockFramebust(const KURL&) {}
+ virtual void DidBlockNavigation(const KURL& blocked_url,
+ const KURL& initiator_urk,
+ blink::NavigationBlockedReason reason) {}
// Called when the corresponding frame should be scrolled in a remote parent
// frame.
@@ -485,6 +480,8 @@ class CORE_EXPORT LocalFrameClient : public FrameClient {
virtual void FrameRectsChanged(const IntRect&) {}
+ virtual void LifecycleStateChanged(mojom::FrameLifecycleState state) {}
+
// Returns true when the contents of plugin are handled externally. This means
// the plugin element will own a content frame but the frame is than used
// externally to load the required handelrs.
@@ -525,6 +522,13 @@ class CORE_EXPORT LocalFrameClient : public FrameClient {
// Returns whether we are associated with a print context who suggests to use
// printing layout.
virtual bool UsePrintingLayout() const { return false; }
+
+ // AppCache ------------------------------------------------------------
+ virtual void UpdateSubresourceFactory(
+ std::unique_ptr<blink::URLLoaderFactoryBundleInfo> info) {}
+ virtual WebLocalFrameClient::AppCacheType GetAppCacheType() {
+ return WebLocalFrameClient::AppCacheType::kAppCacheForNone;
+ }
};
} // namespace blink
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 7bf062ba1c4..2d631832cbe 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
@@ -110,32 +110,6 @@ TEST_F(LocalFrameTest, MaybeAllowPlaceholderImageUsesFramePreviewsState) {
EXPECT_FALSE(page_holder2->GetFrame().IsUsingDataSavingPreview());
}
-TEST_F(LocalFrameTest,
- MaybeAllowPlaceholderImageConditionalOnSchemeForServerLoFi) {
- ResourceRequest request1;
- request1.SetUrl(KURL("https://secure.com"));
- request1.SetPreviewsState(WebURLRequest::kPreviewsUnspecified);
- FetchParameters params1(request1);
- auto page_holder = std::make_unique<DummyPageHolder>(
- IntSize(800, 600), nullptr,
- MakeGarbageCollected<TestLocalFrameClient>(WebURLRequest::kServerLoFiOn |
- WebURLRequest::kClientLoFiOn));
- MaybeAllowImagePlaceholder(page_holder.get(), params1);
- EXPECT_EQ(FetchParameters::kAllowPlaceholder,
- params1.GetImageRequestOptimization());
-
- ResourceRequest request2;
- request2.SetUrl(KURL("http://insecure.com"));
- request2.SetPreviewsState(WebURLRequest::kPreviewsUnspecified);
- FetchParameters params2(request2);
- auto page_holder2 = std::make_unique<DummyPageHolder>(
- IntSize(800, 600), nullptr,
- MakeGarbageCollected<TestLocalFrameClient>(WebURLRequest::kServerLoFiOn |
- WebURLRequest::kClientLoFiOn));
- MaybeAllowImagePlaceholder(page_holder2.get(), params2);
- EXPECT_EQ(FetchParameters::kNone, params2.GetImageRequestOptimization());
-}
-
TEST_F(LocalFrameTest, IsUsingDataSavingPreview) {
EXPECT_TRUE(std::make_unique<DummyPageHolder>(
IntSize(800, 600), nullptr,
@@ -146,12 +120,6 @@ TEST_F(LocalFrameTest, IsUsingDataSavingPreview) {
EXPECT_TRUE(std::make_unique<DummyPageHolder>(
IntSize(800, 600), nullptr,
MakeGarbageCollected<TestLocalFrameClient>(
- WebURLRequest::kServerLoFiOn))
- ->GetFrame()
- .IsUsingDataSavingPreview());
- EXPECT_TRUE(std::make_unique<DummyPageHolder>(
- IntSize(800, 600), nullptr,
- MakeGarbageCollected<TestLocalFrameClient>(
WebURLRequest::kNoScriptOn))
->GetFrame()
.IsUsingDataSavingPreview());
@@ -186,18 +154,18 @@ TEST_F(LocalFrameTest, IsLazyLoadingImageAllowedWithFeatureDisabled) {
ScopedLazyImageLoadingForTest scoped_lazy_image_loading_for_test(false);
auto page_holder = std::make_unique<DummyPageHolder>(
IntSize(800, 600), nullptr, nullptr,
- &EnableLazyLoadAndDisableDataSaverHoldbackInSettings);
- EXPECT_EQ(LocalFrame::LazyLoadImageEnabledState::kDisabled,
- page_holder->GetFrame().GetLazyLoadImageEnabledState());
+ base::BindOnce(&EnableLazyLoadAndDisableDataSaverHoldbackInSettings));
+ EXPECT_EQ(LocalFrame::LazyLoadImageSetting::kDisabled,
+ page_holder->GetFrame().GetLazyLoadImageSetting());
}
TEST_F(LocalFrameTest, IsLazyLoadingImageAllowedWithSettingDisabled) {
ScopedLazyImageLoadingForTest scoped_lazy_image_loading_for_test(false);
auto page_holder = std::make_unique<DummyPageHolder>(
IntSize(800, 600), nullptr, nullptr,
- &DisableLazyLoadAndDisableDataSaverHoldbackInSettings);
- EXPECT_EQ(LocalFrame::LazyLoadImageEnabledState::kDisabled,
- page_holder->GetFrame().GetLazyLoadImageEnabledState());
+ base::BindOnce(&DisableLazyLoadAndDisableDataSaverHoldbackInSettings));
+ EXPECT_EQ(LocalFrame::LazyLoadImageSetting::kDisabled,
+ page_holder->GetFrame().GetLazyLoadImageSetting());
}
TEST_F(LocalFrameTest, IsLazyLoadingImageAllowedWithAutomaticDisabled) {
@@ -206,9 +174,9 @@ TEST_F(LocalFrameTest, IsLazyLoadingImageAllowedWithAutomaticDisabled) {
scoped_automatic_lazy_image_loading_for_test(false);
auto page_holder = std::make_unique<DummyPageHolder>(
IntSize(800, 600), nullptr, nullptr,
- &EnableLazyLoadAndDisableDataSaverHoldbackInSettings);
- EXPECT_EQ(LocalFrame::LazyLoadImageEnabledState::kEnabledExplicit,
- page_holder->GetFrame().GetLazyLoadImageEnabledState());
+ base::BindOnce(&EnableLazyLoadAndDisableDataSaverHoldbackInSettings));
+ EXPECT_EQ(LocalFrame::LazyLoadImageSetting::kEnabledExplicit,
+ page_holder->GetFrame().GetLazyLoadImageSetting());
}
TEST_F(LocalFrameTest, IsLazyLoadingImageAllowedWhenNotRestricted) {
@@ -220,9 +188,9 @@ TEST_F(LocalFrameTest, IsLazyLoadingImageAllowedWhenNotRestricted) {
false);
auto page_holder = std::make_unique<DummyPageHolder>(
IntSize(800, 600), nullptr, nullptr,
- &EnableLazyLoadAndDisableDataSaverHoldbackInSettings);
- EXPECT_EQ(LocalFrame::LazyLoadImageEnabledState::kEnabledAutomatic,
- page_holder->GetFrame().GetLazyLoadImageEnabledState());
+ base::BindOnce(&EnableLazyLoadAndDisableDataSaverHoldbackInSettings));
+ EXPECT_EQ(LocalFrame::LazyLoadImageSetting::kEnabledAutomatic,
+ page_holder->GetFrame().GetLazyLoadImageSetting());
}
TEST_F(LocalFrameTest,
@@ -235,9 +203,9 @@ TEST_F(LocalFrameTest,
GetNetworkStateNotifier().SetSaveDataEnabled(false);
auto page_holder = std::make_unique<DummyPageHolder>(
IntSize(800, 600), nullptr, nullptr,
- &EnableLazyLoadAndDisableDataSaverHoldbackInSettings);
- EXPECT_EQ(LocalFrame::LazyLoadImageEnabledState::kEnabledExplicit,
- page_holder->GetFrame().GetLazyLoadImageEnabledState());
+ base::BindOnce(&EnableLazyLoadAndDisableDataSaverHoldbackInSettings));
+ EXPECT_EQ(LocalFrame::LazyLoadImageSetting::kEnabledExplicit,
+ page_holder->GetFrame().GetLazyLoadImageSetting());
}
TEST_F(LocalFrameTest,
@@ -250,9 +218,9 @@ TEST_F(LocalFrameTest,
GetNetworkStateNotifier().SetSaveDataEnabled(true);
auto page_holder = std::make_unique<DummyPageHolder>(
IntSize(800, 600), nullptr, nullptr,
- &EnableLazyLoadAndEnableDataSaverHoldbackInSettings);
- EXPECT_EQ(LocalFrame::LazyLoadImageEnabledState::kEnabledExplicit,
- page_holder->GetFrame().GetLazyLoadImageEnabledState());
+ base::BindOnce(&EnableLazyLoadAndEnableDataSaverHoldbackInSettings));
+ EXPECT_EQ(LocalFrame::LazyLoadImageSetting::kEnabledExplicit,
+ page_holder->GetFrame().GetLazyLoadImageSetting());
}
TEST_F(LocalFrameTest,
@@ -265,9 +233,9 @@ TEST_F(LocalFrameTest,
GetNetworkStateNotifier().SetSaveDataEnabled(true);
auto page_holder = std::make_unique<DummyPageHolder>(
IntSize(800, 600), nullptr, nullptr,
- &EnableLazyLoadAndDisableDataSaverHoldbackInSettings);
- EXPECT_EQ(LocalFrame::LazyLoadImageEnabledState::kEnabledAutomatic,
- page_holder->GetFrame().GetLazyLoadImageEnabledState());
+ base::BindOnce(&EnableLazyLoadAndDisableDataSaverHoldbackInSettings));
+ EXPECT_EQ(LocalFrame::LazyLoadImageSetting::kEnabledAutomatic,
+ page_holder->GetFrame().GetLazyLoadImageSetting());
}
} // 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 6e039e92871..4c1491886ed 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
@@ -93,7 +93,7 @@ LocalFrameUkmAggregator::LocalFrameUkmAggregator(int64_t source_id,
uma_name.Append(uma_postscript);
if (metric_data.has_uma) {
absolute_record.uma_counter.reset(new CustomCountHistogram(
- uma_name.ToString().Utf8().data(), 0, 10000000, 50));
+ uma_name.ToString().Utf8().c_str(), 0, 10000000, 50));
}
// Percentage records report the ratio of each metric to the primary metric,
@@ -109,7 +109,7 @@ LocalFrameUkmAggregator::LocalFrameUkmAggregator(int64_t source_id,
uma_percentage_name.Append(bucket_substring);
percentage_record.uma_counters_per_bucket.push_back(
std::make_unique<CustomCountHistogram>(
- uma_percentage_name.ToString().Utf8().data(), 0, 10000000, 50));
+ uma_percentage_name.ToString().Utf8().c_str(), 0, 10000000, 50));
}
}
}
@@ -129,7 +129,8 @@ void LocalFrameUkmAggregator::SetTickClockForTesting(
clock_ = clock;
}
-void LocalFrameUkmAggregator::RecordForcedStyleLayoutUMA(TimeDelta& duration) {
+void LocalFrameUkmAggregator::RecordForcedStyleLayoutUMA(
+ base::TimeDelta& duration) {
if (!calls_to_next_forced_style_layout_uma_) {
auto& record = absolute_metric_records_[kForcedStyleAndLayout];
record.uma_counter->CountMicroseconds(duration);
@@ -142,9 +143,9 @@ void LocalFrameUkmAggregator::RecordForcedStyleLayoutUMA(TimeDelta& duration) {
}
void LocalFrameUkmAggregator::RecordSample(size_t metric_index,
- TimeTicks start,
- TimeTicks end) {
- TimeDelta duration = end - start;
+ base::TimeTicks start,
+ base::TimeTicks end) {
+ base::TimeDelta duration = end - start;
// Accumulate for UKM and record the UMA
DCHECK_LT(metric_index, absolute_metric_records_.size());
@@ -169,8 +170,8 @@ void LocalFrameUkmAggregator::RecordSample(size_t metric_index,
}
}
-void LocalFrameUkmAggregator::RecordEndOfFrameMetrics(TimeTicks start,
- TimeTicks end) {
+void LocalFrameUkmAggregator::RecordEndOfFrameMetrics(base::TimeTicks start,
+ base::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.
@@ -182,7 +183,7 @@ void LocalFrameUkmAggregator::RecordEndOfFrameMetrics(TimeTicks start,
}
in_main_frame_update_ = false;
- TimeDelta duration = end - start;
+ base::TimeDelta duration = end - start;
// Record UMA
primary_metric_.uma_counter->CountMicroseconds(duration);
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 0a76cc7ac21..3cb0fd391e1 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
@@ -6,8 +6,8 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_LOCAL_FRAME_UKM_AGGREGATOR_H_
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/histogram.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
@@ -175,10 +175,11 @@ class CORE_EXPORT LocalFrameUkmAggregator
// Modify this array if the UMA ratio metrics should be bucketed in a
// different way.
- static const Vector<TimeDelta>& bucket_thresholds() {
+ static const Vector<base::TimeDelta>& bucket_thresholds() {
// Leaky construction to avoid exit-time destruction.
- static const Vector<TimeDelta>* thresholds = new Vector<TimeDelta>{
- TimeDelta::FromMilliseconds(1), TimeDelta::FromMilliseconds(5)};
+ static const Vector<base::TimeDelta>* thresholds =
+ new Vector<base::TimeDelta>{base::TimeDelta::FromMilliseconds(1),
+ base::TimeDelta::FromMilliseconds(5)};
return *thresholds;
}
@@ -204,7 +205,7 @@ class CORE_EXPORT LocalFrameUkmAggregator
scoped_refptr<LocalFrameUkmAggregator> aggregator_;
const size_t metric_index_;
const base::TickClock* clock_;
- const TimeTicks start_time_;
+ const base::TimeTicks start_time_;
DISALLOW_COPY_AND_ASSIGN(ScopedUkmHierarchicalTimer);
};
@@ -220,12 +221,14 @@ class CORE_EXPORT LocalFrameUkmAggregator
// sub-metrics and generates UMA samples. UKM is only reported when
// BeginMainFrame() returned true. All counters are cleared when this method
// is called.
- void RecordEndOfFrameMetrics(TimeTicks start, TimeTicks end);
+ void RecordEndOfFrameMetrics(base::TimeTicks start, base::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 RecordSample(size_t metric_index,
+ base::TimeTicks start,
+ base::TimeTicks end);
// Mark the beginning of a main frame update.
void BeginMainFrame();
@@ -242,9 +245,9 @@ class CORE_EXPORT LocalFrameUkmAggregator
// Accumulated at each sample, then reset with a call to
// RecordEndOfFrameMetrics.
- TimeDelta interval_duration;
+ base::TimeDelta interval_duration;
- void reset() { interval_duration = TimeDelta(); }
+ void reset() { interval_duration = base::TimeDelta(); }
};
struct MainFramePercentageRecord {
@@ -252,9 +255,9 @@ class CORE_EXPORT LocalFrameUkmAggregator
// Accumulated at each sample, then reset with a call to
// RecordEndOfFrameMetrics.
- TimeDelta interval_duration;
+ base::TimeDelta interval_duration;
- void reset() { interval_duration = TimeDelta(); }
+ void reset() { interval_duration = base::TimeDelta(); }
};
void UpdateEventTimeAndRecordEventIfNeeded();
@@ -263,7 +266,7 @@ class CORE_EXPORT LocalFrameUkmAggregator
unsigned SampleFramesToNextEvent();
// Implements throttling of the ForcedStyleAndLayoutUMA metric.
- void RecordForcedStyleLayoutUMA(TimeDelta& duration);
+ void RecordForcedStyleLayoutUMA(base::TimeDelta& duration);
// To test event sampling. This and all future intervals will be the given
// frame count, until this is called again.
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 16930532541..a9bef6dfc77 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
@@ -36,19 +36,15 @@ class LocalFrameUkmAggregatorTest : public testing::Test {
void ResetAggregator() { aggregator_.reset(); }
std::string GetPrimaryMetricName() {
- return std::string(
- LocalFrameUkmAggregator::primary_metric_name().Utf8().data());
+ return LocalFrameUkmAggregator::primary_metric_name().Utf8();
}
std::string GetMetricName(int index) {
- return std::string(
- LocalFrameUkmAggregator::metrics_data()[index].name.Utf8().data());
+ return LocalFrameUkmAggregator::metrics_data()[index].name.Utf8();
}
std::string GetPercentageMetricName(int index) {
- return std::string(LocalFrameUkmAggregator::metrics_data()[index]
- .name.Utf8()
- .data()) +
+ return LocalFrameUkmAggregator::metrics_data()[index].name.Utf8() +
"Percentage";
}
@@ -104,7 +100,7 @@ TEST_F(LocalFrameUkmAggregatorTest, EmptyEventsNotRecorded) {
return;
// There is no BeginMainFrame, so no metrics get recorded.
- test_task_runner_->FastForwardBy(TimeDelta::FromSeconds(10));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromSeconds(10));
ResetAggregator();
EXPECT_EQ(recorder().sources_count(), 0u);
@@ -128,7 +124,7 @@ TEST_F(LocalFrameUkmAggregatorTest, FirstFrameIsRecorded) {
auto timer =
aggregator().GetScopedTimer(i % LocalFrameUkmAggregator::kCount);
test_task_runner_->FastForwardBy(
- TimeDelta::FromMilliseconds(millisecond_for_step));
+ base::TimeDelta::FromMilliseconds(millisecond_for_step));
}
aggregator().RecordEndOfFrameMetrics(start_time, Now());
@@ -171,10 +167,10 @@ TEST_F(LocalFrameUkmAggregatorTest, EventsRecordedAtIntervals) {
for (int i = 0; i < LocalFrameUkmAggregator::kCount; ++i) {
auto timer = aggregator().GetScopedTimer(i);
test_task_runner_->FastForwardBy(
- TimeDelta::FromMilliseconds(millisecond_per_step));
+ base::TimeDelta::FromMilliseconds(millisecond_per_step));
}
test_task_runner_->FastForwardBy(
- TimeDelta::FromMilliseconds(millisecond_per_step));
+ base::TimeDelta::FromMilliseconds(millisecond_per_step));
aggregator().RecordEndOfFrameMetrics(start_time, Now());
// We should have a sample after the very first step, regardless of the
@@ -190,10 +186,10 @@ TEST_F(LocalFrameUkmAggregatorTest, EventsRecordedAtIntervals) {
for (int i = 0; i < LocalFrameUkmAggregator::kCount; ++i) {
auto timer = aggregator().GetScopedTimer(i);
test_task_runner_->FastForwardBy(
- TimeDelta::FromMilliseconds(millisecond_per_step));
+ base::TimeDelta::FromMilliseconds(millisecond_per_step));
}
test_task_runner_->FastForwardBy(
- TimeDelta::FromMilliseconds(millisecond_per_step));
+ base::TimeDelta::FromMilliseconds(millisecond_per_step));
aggregator().RecordEndOfFrameMetrics(start_time, Now());
VerifyEntries(1u, millisecond_per_frame, millisecond_per_step,
@@ -207,10 +203,10 @@ TEST_F(LocalFrameUkmAggregatorTest, EventsRecordedAtIntervals) {
for (int i = 0; i < LocalFrameUkmAggregator::kCount; ++i) {
auto timer = aggregator().GetScopedTimer(i);
test_task_runner_->FastForwardBy(
- TimeDelta::FromMilliseconds(millisecond_per_step));
+ base::TimeDelta::FromMilliseconds(millisecond_per_step));
}
test_task_runner_->FastForwardBy(
- TimeDelta::FromMilliseconds(millisecond_per_step));
+ base::TimeDelta::FromMilliseconds(millisecond_per_step));
aggregator().RecordEndOfFrameMetrics(start_time, Now());
VerifyEntries(2u, millisecond_per_frame, millisecond_per_step,
@@ -222,10 +218,10 @@ TEST_F(LocalFrameUkmAggregatorTest, EventsRecordedAtIntervals) {
for (int i = 0; i < LocalFrameUkmAggregator::kCount; ++i) {
auto timer = aggregator().GetScopedTimer(i);
test_task_runner_->FastForwardBy(
- TimeDelta::FromMilliseconds(millisecond_per_step));
+ base::TimeDelta::FromMilliseconds(millisecond_per_step));
}
test_task_runner_->FastForwardBy(
- TimeDelta::FromMilliseconds(millisecond_per_step));
+ base::TimeDelta::FromMilliseconds(millisecond_per_step));
aggregator().RecordEndOfFrameMetrics(start_time, Now());
// Should be no more samples.
@@ -238,10 +234,10 @@ TEST_F(LocalFrameUkmAggregatorTest, EventsRecordedAtIntervals) {
for (int i = 0; i < LocalFrameUkmAggregator::kCount; ++i) {
auto timer = aggregator().GetScopedTimer(i);
test_task_runner_->FastForwardBy(
- TimeDelta::FromMilliseconds(millisecond_per_step));
+ base::TimeDelta::FromMilliseconds(millisecond_per_step));
}
test_task_runner_->FastForwardBy(
- TimeDelta::FromMilliseconds(millisecond_per_step));
+ base::TimeDelta::FromMilliseconds(millisecond_per_step));
aggregator().RecordEndOfFrameMetrics(start_time, Now());
// We should have 3 more events, once for the prior interval and 2 for the
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 2f1902003e0..a76239750e5 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
@@ -84,11 +84,11 @@
#include "third_party/blink/renderer/core/intersection_observer/intersection_observer_controller.h"
#include "third_party/blink/renderer/core/layout/adjust_for_absolute_zoom.h"
#include "third_party/blink/renderer/core/layout/geometry/transform_state.h"
-#include "third_party/blink/renderer/core/layout/jank_tracker.h"
#include "third_party/blink/renderer/core/layout/layout_analyzer.h"
#include "third_party/blink/renderer/core/layout/layout_counter.h"
#include "third_party/blink/renderer/core/layout/layout_embedded_content.h"
#include "third_party/blink/renderer/core/layout/layout_embedded_object.h"
+#include "third_party/blink/renderer/core/layout/layout_shift_tracker.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/layout/ng/legacy_layout_tree_walking.h"
#include "third_party/blink/renderer/core/layout/style_retain_scope.h"
@@ -143,7 +143,7 @@
#include "third_party/blink/renderer/platform/graphics/paint/cull_rect.h"
#include "third_party/blink/renderer/platform/graphics/paint/foreign_layer_display_item.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_controller.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/traced_value.h"
#include "third_party/blink/renderer/platform/language.h"
@@ -270,16 +270,17 @@ LocalFrameView::LocalFrameView(LocalFrame& frame, IntRect frame_rect)
intersection_observation_state_(kNotNeeded),
needs_forced_compositing_update_(false),
needs_focus_on_fragment_(false),
+ in_lifecycle_update_(false),
tracked_object_paint_invalidations_(
base::WrapUnique(g_initial_track_all_paint_invalidations
? new Vector<ObjectPaintInvalidation>
: nullptr)),
main_thread_scrolling_reasons_(0),
forced_layout_stack_depth_(0),
- forced_layout_start_time_(TimeTicks()),
+ forced_layout_start_time_(base::TimeTicks()),
paint_frame_count_(0),
unique_id_(NewUniqueObjectId()),
- jank_tracker_(std::make_unique<JankTracker>(this)),
+ layout_shift_tracker_(std::make_unique<LayoutShiftTracker>(this)),
paint_timing_detector_(MakeGarbageCollected<PaintTimingDetector>(this))
#if DCHECK_IS_ON()
,
@@ -396,7 +397,7 @@ void LocalFrameView::Dispose() {
ClearPrintContext();
ukm_aggregator_.reset();
- jank_tracker_->Dispose();
+ layout_shift_tracker_->Dispose();
#if DCHECK_IS_ON()
has_been_disposed_ = true;
@@ -847,12 +848,18 @@ void LocalFrameView::UpdateLayout() {
IntSize new_size(Size());
if (old_size != new_size) {
- SetNeedsLayout();
MarkViewportConstrainedObjectsForLayout(
old_size.Width() != new_size.Width(),
old_size.Height() != new_size.Height());
}
+ if (frame_->IsMainFrame()) {
+ if (auto* text_autosizer = frame_->GetDocument()->GetTextAutosizer()) {
+ if (text_autosizer->HasLayoutInlineSizeChanged())
+ text_autosizer->UpdatePageInfoInAllFrames(frame_);
+ }
+ }
+
if (NeedsLayout()) {
base::AutoReset<bool> suppress(&suppress_adjust_view_size_, true);
UpdateLayout();
@@ -927,7 +934,7 @@ void LocalFrameView::WillStartForcedLayout() {
forced_layout_stack_depth_++;
if (forced_layout_stack_depth_ > 1)
return;
- forced_layout_start_time_ = CurrentTimeTicks();
+ forced_layout_start_time_ = base::TimeTicks::Now();
}
void LocalFrameView::DidFinishForcedLayout() {
@@ -937,7 +944,7 @@ void LocalFrameView::DidFinishForcedLayout() {
LocalFrameUkmAggregator& aggregator = EnsureUkmAggregator();
aggregator.RecordSample(
(size_t)LocalFrameUkmAggregator::kForcedStyleAndLayout,
- forced_layout_start_time_, CurrentTimeTicks());
+ forced_layout_start_time_, base::TimeTicks::Now());
}
}
@@ -983,9 +990,14 @@ FloatSize LocalFrameView::ViewportSizeForViewportUnits() const {
}
FloatSize LocalFrameView::ViewportSizeForMediaQueries() const {
- FloatSize viewport_size(GetLayoutSize());
- if (!frame_->GetDocument() || !frame_->GetDocument()->Printing())
- viewport_size.Scale(1 / GetFrame().PageZoomFactor());
+ FloatSize viewport_size(layout_size_);
+ if (!frame_->GetDocument()->Printing()) {
+ float zoom = GetFrame().PageZoomFactor();
+ viewport_size.SetWidth(
+ AdjustForAbsoluteZoom::AdjustInt(layout_size_.Width(), zoom));
+ viewport_size.SetHeight(
+ AdjustForAbsoluteZoom::AdjustInt(layout_size_.Height(), zoom));
+ }
return viewport_size;
}
@@ -1029,7 +1041,6 @@ void LocalFrameView::ForceUpdateViewportIntersections() {
UpdateViewportIntersectionsForSubtree(
IntersectionObservation::kImplicitRootObserversNeedUpdate |
IntersectionObservation::kIgnoreDelay);
- frame_->Owner()->SetNeedsOcclusionTracking(false);
}
LayoutSVGRoot* LocalFrameView::EmbeddedReplacedContent() const {
@@ -1215,7 +1226,7 @@ void LocalFrameView::ViewportSizeChanged(bool width_changed,
return;
if (frame_->IsMainFrame())
- jank_tracker_->NotifyViewportSizeChanged();
+ layout_shift_tracker_->NotifyViewportSizeChanged();
auto* layout_view = GetLayoutView();
if (layout_view) {
@@ -1244,6 +1255,9 @@ void LocalFrameView::ViewportSizeChanged(bool width_changed,
if (GetFrame().GetDocument() && !IsInPerformLayout())
MarkViewportConstrainedObjectsForLayout(width_changed, height_changed);
+
+ if (GetPaintTimingDetector().Visualizer())
+ GetPaintTimingDetector().Visualizer()->OnViewportChanged();
}
void LocalFrameView::MarkViewportConstrainedObjectsForLayout(
@@ -1513,12 +1527,23 @@ static bool PrepareOrthogonalWritingModeRootForLayout(LayoutObject& root) {
ToLayoutBox(root).IsGridItem() || root.IsTablePart())
return false;
- // Do not pre-layout objects that are fully managed by LayoutNG; it is not
- // necessary and may lead to double layouts. We do need to pre-layout
- // objects whose containing block is a legacy object so that it can
- // properly compute its intrinsic size.
- if (RuntimeEnabledFeatures::LayoutNGEnabled() && IsManagedByLayoutNG(root))
- return false;
+ if (RuntimeEnabledFeatures::LayoutNGEnabled()) {
+ // Do not pre-layout objects that are fully managed by LayoutNG; it is not
+ // necessary and may lead to double layouts. We do need to pre-layout
+ // objects whose containing block is a legacy object so that it can
+ // properly compute its intrinsic size.
+ if (IsManagedByLayoutNG(root))
+ return false;
+
+ // If the root is legacy but has |CachedLayoutResult|, its parent is NG,
+ // which called |RunLegacyLayout()|. This parent not only needs to run
+ // pre-layout, but also clearing |NeedsLayout()| without updating
+ // |CachedLayoutResult| is harmful.
+ if (const auto* box = ToLayoutBoxOrNull(&root)) {
+ if (box->GetCachedLayoutResult())
+ return false;
+ }
+ }
RemoveFloatingObjectsForSubtreeRoot(root);
return true;
@@ -1658,8 +1683,10 @@ bool LocalFrameView::HasOpaqueBackground() const {
}
Color LocalFrameView::BaseBackgroundColor() const {
- if (use_dark_scheme_background_)
+ if (use_dark_scheme_background_ &&
+ base_background_color_ != Color::kTransparent) {
return Color::kBlack;
+ }
return base_background_color_;
}
@@ -1770,7 +1797,7 @@ void LocalFrameView::ScheduleUpdatePluginsIfNecessary() {
DCHECK(!IsInPerformLayout());
if (update_plugins_timer_.IsActive() || part_update_set_.IsEmpty())
return;
- update_plugins_timer_.StartOneShot(TimeDelta(), FROM_HERE);
+ update_plugins_timer_.StartOneShot(base::TimeDelta(), FROM_HERE);
}
void LocalFrameView::PerformPostLayoutTasks() {
@@ -1793,8 +1820,7 @@ void LocalFrameView::PerformPostLayoutTasks() {
// send the right mouse out/over events.
// TODO(lanwei): we should check whether the mouse is inside the frame before
// dirtying the hover state.
- if (RuntimeEnabledFeatures::
- UpdateHoverFromLayoutChangeAtBeginFrameEnabled()) {
+ if (RuntimeEnabledFeatures::UpdateHoverAtBeginFrameEnabled()) {
frame_->LocalFrameRoot().GetEventHandler().MarkHoverStateDirty();
} else {
frame_->GetEventHandler().MayUpdateHoverWhenContentUnderMouseChanged(
@@ -1904,6 +1930,9 @@ void LocalFrameView::DidAttachDocument() {
page->GlobalRootScrollerController().InitializeViewportScrollCallback(
*root_frame_viewport, *frame_->GetDocument());
+
+ // Allow for commits to be deferred because this is a new document.
+ have_deferred_commits_ = false;
}
}
@@ -2061,6 +2090,7 @@ void LocalFrameView::ScheduleVisualUpdateForPaintInvalidationIfNeeded() {
}
void LocalFrameView::NotifyResizeObservers() {
+ TRACE_EVENT0("blink,benchmark", "LocalFrameView::NotifyResizeObservers");
// Controller exists only if ResizeObserver was created.
if (!GetFrame().GetDocument()->GetResizeObserverController())
return;
@@ -2190,11 +2220,19 @@ bool LocalFrameView::UpdateLifecyclePhases(
return Lifecycle().GetState() == target_state;
}
- ForAllNonThrottledLocalFrameViews([](LocalFrameView& frame_view) {
- auto lifecycle_observers = frame_view.lifecycle_observers_;
- for (auto& observer : lifecycle_observers)
- observer->WillStartLifecycleUpdate(frame_view);
- });
+ base::AutoReset<bool> in_lifecycle_scope(&in_lifecycle_update_, true);
+ lifecycle_data_.start_time = base::TimeTicks::Now();
+ ++lifecycle_data_.count;
+
+ {
+ TRACE_EVENT0("blink", "LocalFrameView::WillStartLifecycleUpdate");
+
+ ForAllNonThrottledLocalFrameViews([](LocalFrameView& frame_view) {
+ auto lifecycle_observers = frame_view.lifecycle_observers_;
+ for (auto& observer : lifecycle_observers)
+ observer->WillStartLifecycleUpdate(frame_view);
+ });
+ }
// If we're in PrintBrowser mode, setup a print context.
// TODO(vmpstr): It doesn't seem like we need to do this every lifecycle
@@ -2207,11 +2245,15 @@ bool LocalFrameView::UpdateLifecyclePhases(
// Run the lifecycle updates.
UpdateLifecyclePhasesInternal(target_state);
- ForAllNonThrottledLocalFrameViews([](LocalFrameView& frame_view) {
- auto lifecycle_observers = frame_view.lifecycle_observers_;
- for (auto& observer : lifecycle_observers)
- observer->DidFinishLifecycleUpdate(frame_view);
- });
+ {
+ TRACE_EVENT0("blink", "LocalFrameView::DidFinishLifecycleUpdate");
+
+ ForAllNonThrottledLocalFrameViews([](LocalFrameView& frame_view) {
+ auto lifecycle_observers = frame_view.lifecycle_observers_;
+ for (auto& observer : lifecycle_observers)
+ observer->DidFinishLifecycleUpdate(frame_view);
+ });
+ }
return Lifecycle().GetState() == target_state;
}
@@ -2251,6 +2293,12 @@ void LocalFrameView::UpdateLifecyclePhasesInternal(
return;
}
+ // Now that we have run the lifecycle up to paint, we can reset
+ // |need_paint_phase_after_throttling_| so that the paint phase will
+ // properly see us as being throttled (if that was the only reason we remained
+ // unthrottled), and clear the painted output.
+ need_paint_phase_after_throttling_ = false;
+
DCHECK_EQ(target_state, DocumentLifecycle::kPaintClean);
RunPaintLifecyclePhase();
DCHECK(ShouldThrottleRendering() ||
@@ -2550,7 +2598,15 @@ static void CollectDrawableLayersForLayerListRecursively(
DCHECK(RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled());
if (!layer || layer->Client().ShouldThrottleRendering() ||
- layer->Client().PaintBlockedByDisplayLock()) {
+ layer->Client().IsUnderSVGHiddenContainer()) {
+ return;
+ }
+
+ if (layer->Client().PaintBlockedByDisplayLockIncludingAncestors(
+ DisplayLockContextLifecycleTarget::kSelf)) {
+ // If we skip the layer, then we need to ensure to notify the
+ // display-lock, since we need to force recollect the layers when we commit.
+ layer->Client().NotifyDisplayLockNeedsGraphicsLayerCollection();
return;
}
@@ -2941,7 +2997,7 @@ void LocalFrameView::ForceLayoutForPagination(
// cropping implementation should not do this!
bool horizontal_writing_mode =
layout_view->StyleRef().IsHorizontalWritingMode();
- const LayoutRect& document_rect = LayoutRect(layout_view->DocumentRect());
+ PhysicalRect document_rect(layout_view->DocumentRect());
LayoutUnit doc_logical_width = horizontal_writing_mode
? document_rect.Width()
: document_rect.Height();
@@ -2968,8 +3024,7 @@ void LocalFrameView::ForceLayoutForPagination(
layout_invalidation_reason::kPrintingChanged);
UpdateLayout();
- const LayoutRect& updated_document_rect =
- LayoutRect(layout_view->DocumentRect());
+ PhysicalRect updated_document_rect(layout_view->DocumentRect());
LayoutUnit doc_logical_height = horizontal_writing_mode
? updated_document_rect.Height()
: updated_document_rect.Width();
@@ -2977,8 +3032,8 @@ void LocalFrameView::ForceLayoutForPagination(
? updated_document_rect.Y()
: updated_document_rect.X();
LayoutUnit doc_logical_right = horizontal_writing_mode
- ? updated_document_rect.MaxX()
- : updated_document_rect.MaxY();
+ ? updated_document_rect.Right()
+ : updated_document_rect.Bottom();
LayoutUnit clipped_logical_left;
if (!layout_view->StyleRef().IsLeftToRightDirection()) {
clipped_logical_left =
@@ -3019,22 +3074,15 @@ IntRect LocalFrameView::ConvertToLayoutObject(const LayoutObject& layout_object,
IntPoint LocalFrameView::ConvertFromLayoutObject(
const LayoutObject& layout_object,
const IntPoint& layout_object_point) const {
- return RoundedIntPoint(
- ConvertFromLayoutObject(layout_object, LayoutPoint(layout_object_point)));
+ return RoundedIntPoint(ConvertFromLayoutObject(
+ layout_object, PhysicalOffset(layout_object_point)));
}
IntPoint LocalFrameView::ConvertToLayoutObject(
const LayoutObject& layout_object,
const IntPoint& frame_point) const {
return RoundedIntPoint(
- ConvertToLayoutObject(layout_object, LayoutPoint(frame_point)));
-}
-
-LayoutPoint LocalFrameView::ConvertFromLayoutObject(
- const LayoutObject& layout_object,
- const LayoutPoint& layout_object_point) const {
- return layout_object.LocalToAbsolutePoint(PhysicalOffset(layout_object_point))
- .ToLayoutPoint();
+ ConvertToLayoutObject(layout_object, PhysicalOffset(frame_point)));
}
PhysicalOffset LocalFrameView::ConvertFromLayoutObject(
@@ -3043,13 +3091,6 @@ PhysicalOffset LocalFrameView::ConvertFromLayoutObject(
return layout_object.LocalToAbsolutePoint(layout_object_offset);
}
-LayoutPoint LocalFrameView::ConvertToLayoutObject(
- const LayoutObject& layout_object,
- const LayoutPoint& frame_point) const {
- return LayoutPoint(
- ConvertToLayoutObject(layout_object, FloatPoint(frame_point)));
-}
-
PhysicalOffset LocalFrameView::ConvertToLayoutObject(
const LayoutObject& layout_object,
const PhysicalOffset& frame_offset) const {
@@ -3117,24 +3158,14 @@ FloatPoint LocalFrameView::DocumentToFrame(
return FloatPoint(DocumentToFrame(DoublePoint(point_in_document)));
}
-LayoutPoint LocalFrameView::DocumentToFrame(
- const LayoutPoint& point_in_document) const {
- ScrollableArea* layout_viewport = LayoutViewport();
- if (!layout_viewport)
- return point_in_document;
-
- return point_in_document - LayoutSize(layout_viewport->GetScrollOffset());
-}
-
PhysicalOffset LocalFrameView::DocumentToFrame(
const PhysicalOffset& offset_in_document) const {
- return PhysicalOffset(DocumentToFrame(offset_in_document.ToLayoutPoint()));
-}
+ ScrollableArea* layout_viewport = LayoutViewport();
+ if (!layout_viewport)
+ return offset_in_document;
-LayoutRect LocalFrameView::DocumentToFrame(
- const LayoutRect& rect_in_document) const {
- return LayoutRect(DocumentToFrame(rect_in_document.Location()),
- rect_in_document.Size());
+ return offset_in_document -
+ PhysicalOffset::FromFloatSizeRound(layout_viewport->GetScrollOffset());
}
PhysicalRect LocalFrameView::DocumentToFrame(
@@ -3144,21 +3175,17 @@ PhysicalRect LocalFrameView::DocumentToFrame(
}
IntPoint LocalFrameView::FrameToDocument(const IntPoint& point_in_frame) const {
- return FlooredIntPoint(FrameToDocument(LayoutPoint(point_in_frame)));
+ return FlooredIntPoint(FrameToDocument(PhysicalOffset(point_in_frame)));
}
-LayoutPoint LocalFrameView::FrameToDocument(
- const LayoutPoint& point_in_frame) const {
+PhysicalOffset LocalFrameView::FrameToDocument(
+ const PhysicalOffset& offset_in_frame) const {
ScrollableArea* layout_viewport = LayoutViewport();
if (!layout_viewport)
- return point_in_frame;
-
- return point_in_frame + LayoutSize(layout_viewport->GetScrollOffset());
-}
+ return offset_in_frame;
-PhysicalOffset LocalFrameView::FrameToDocument(
- const PhysicalOffset& offset_in_frame) const {
- return PhysicalOffset(FrameToDocument(offset_in_frame.ToLayoutPoint()));
+ return offset_in_frame +
+ PhysicalOffset::FromFloatSizeRound(layout_viewport->GetScrollOffset());
}
IntRect LocalFrameView::FrameToDocument(const IntRect& rect_in_frame) const {
@@ -3166,12 +3193,6 @@ IntRect LocalFrameView::FrameToDocument(const IntRect& rect_in_frame) const {
rect_in_frame.Size());
}
-LayoutRect LocalFrameView::FrameToDocument(
- const LayoutRect& rect_in_frame) const {
- return LayoutRect(FrameToDocument(rect_in_frame.Location()),
- rect_in_frame.Size());
-}
-
PhysicalRect LocalFrameView::FrameToDocument(
const PhysicalRect& rect_in_frame) const {
return PhysicalRect(FrameToDocument(rect_in_frame.offset),
@@ -3208,24 +3229,6 @@ IntRect LocalFrameView::ConvertFromContainingEmbeddedContentView(
return parent_rect;
}
-LayoutPoint LocalFrameView::ConvertToContainingEmbeddedContentView(
- const LayoutPoint& local_point) const {
- if (LocalFrameView* parent = ParentFrameView()) {
- auto* layout_object = GetLayoutEmbeddedContent();
- if (!layout_object)
- return local_point;
-
- LayoutPoint point(local_point);
-
- // Add borders and padding
- point.Move((layout_object->BorderLeft() + layout_object->PaddingLeft()),
- (layout_object->BorderTop() + layout_object->PaddingTop()));
- return parent->ConvertFromLayoutObject(*layout_object, point);
- }
-
- return local_point;
-}
-
PhysicalOffset LocalFrameView::ConvertToContainingEmbeddedContentView(
const PhysicalOffset& local_offset) const {
if (LocalFrameView* parent = ParentFrameView()) {
@@ -3263,16 +3266,10 @@ FloatPoint LocalFrameView::ConvertToContainingEmbeddedContentView(
return local_point;
}
-LayoutPoint LocalFrameView::ConvertFromContainingEmbeddedContentView(
- const LayoutPoint& parent_point) const {
- return LayoutPoint(
- ConvertFromContainingEmbeddedContentView(DoublePoint(parent_point)));
-}
-
PhysicalOffset LocalFrameView::ConvertFromContainingEmbeddedContentView(
const PhysicalOffset& parent_offset) const {
- return PhysicalOffset(
- ConvertFromContainingEmbeddedContentView(parent_offset.ToLayoutPoint()));
+ return PhysicalOffset::FromFloatPointRound(
+ ConvertFromContainingEmbeddedContentView(FloatPoint(parent_offset)));
}
FloatPoint LocalFrameView::ConvertFromContainingEmbeddedContentView(
@@ -3305,7 +3302,7 @@ DoublePoint LocalFrameView::ConvertFromContainingEmbeddedContentView(
IntPoint LocalFrameView::ConvertToContainingEmbeddedContentView(
const IntPoint& local_point) const {
return RoundedIntPoint(
- ConvertToContainingEmbeddedContentView(LayoutPoint(local_point)));
+ ConvertToContainingEmbeddedContentView(PhysicalOffset(local_point)));
}
void LocalFrameView::SetInitialTracksPaintInvalidationsForTesting(
@@ -3351,6 +3348,10 @@ void LocalFrameView::SetTracksPaintInvalidations(
void LocalFrameView::TrackObjectPaintInvalidation(
const DisplayItemClient& client,
PaintInvalidationReason reason) {
+ TRACE_EVENT_INSTANT2(TRACE_DISABLED_BY_DEFAULT("blink.invalidation"),
+ "InvalidateDisplayItemClient", TRACE_EVENT_SCOPE_GLOBAL,
+ "client", client.DebugName().Utf8(), "reason",
+ PaintInvalidationReasonToString(reason));
if (!tracked_object_paint_invalidations_)
return;
@@ -3544,11 +3545,8 @@ void LocalFrameView::SetLayoutSizeInternal(const IntSize& size) {
return;
layout_size_ = size;
- if (frame_->IsMainFrame() && frame_->GetDocument()) {
- if (TextAutosizer* text_autosizer =
- frame_->GetDocument()->GetTextAutosizer())
- text_autosizer->UpdatePageInfoInAllFrames();
- }
+ if (frame_->IsMainFrame() && frame_->GetDocument())
+ TextAutosizer::UpdatePageInfoInAllFrames(frame_);
SetNeedsLayout();
}
@@ -3580,8 +3578,10 @@ void LocalFrameView::ClipPaintRect(FloatRect* paint_rect) const {
void LocalFrameView::DidChangeScrollOffset() {
GetFrame().Client()->DidChangeScrollOffset();
- if (GetFrame().IsMainFrame())
- GetFrame().GetPage()->GetChromeClient().MainFrameScrollOffsetChanged();
+ if (GetFrame().IsMainFrame()) {
+ GetFrame().GetPage()->GetChromeClient().MainFrameScrollOffsetChanged(
+ GetFrame());
+ }
}
ScrollableArea* LocalFrameView::ScrollableAreaWithElementId(
@@ -3606,11 +3606,11 @@ ScrollableArea* LocalFrameView::ScrollableAreaWithElementId(
}
void LocalFrameView::ScrollRectToVisibleInRemoteParent(
- const LayoutRect& rect_to_scroll,
+ const PhysicalRect& rect_to_scroll,
const WebScrollIntoViewParams& params) {
DCHECK(GetFrame().IsLocalRoot() && !GetFrame().IsMainFrame() &&
safe_to_propagate_scroll_to_parent_);
- LayoutRect new_rect = ConvertToRootFrame(rect_to_scroll);
+ PhysicalRect new_rect = ConvertToRootFrame(rect_to_scroll);
GetFrame().Client()->ScrollRectToVisibleInParentFrame(
WebRect(new_rect.X().ToInt(), new_rect.Y().ToInt(),
new_rect.Width().ToInt(), new_rect.Height().ToInt()),
@@ -3624,9 +3624,9 @@ void LocalFrameView::NotifyFrameRectsChangedIfNeeded() {
}
}
-LayoutPoint LocalFrameView::ViewportToFrame(
- const LayoutPoint& point_in_viewport) const {
- LayoutPoint point_in_root_frame(
+PhysicalOffset LocalFrameView::ViewportToFrame(
+ const PhysicalOffset& point_in_viewport) const {
+ PhysicalOffset point_in_root_frame = PhysicalOffset::FromFloatPointRound(
frame_->GetPage()->GetVisualViewport().ViewportToRootFrame(
FloatPoint(point_in_viewport)));
return ConvertFromRootFrame(point_in_root_frame);
@@ -3649,7 +3649,7 @@ IntRect LocalFrameView::ViewportToFrame(const IntRect& rect_in_viewport) const {
IntPoint LocalFrameView::ViewportToFrame(
const IntPoint& point_in_viewport) const {
- return RoundedIntPoint(ViewportToFrame(LayoutPoint(point_in_viewport)));
+ return RoundedIntPoint(ViewportToFrame(PhysicalOffset(point_in_viewport)));
}
IntRect LocalFrameView::FrameToViewport(const IntRect& rect_in_frame) const {
@@ -3773,17 +3773,7 @@ IntRect LocalFrameView::ConvertToRootFrame(const IntRect& local_rect) const {
}
IntPoint LocalFrameView::ConvertToRootFrame(const IntPoint& local_point) const {
- return RoundedIntPoint(ConvertToRootFrame(LayoutPoint(local_point)));
-}
-
-LayoutPoint LocalFrameView::ConvertToRootFrame(
- const LayoutPoint& local_point) const {
- if (LocalFrameView* parent = ParentFrameView()) {
- LayoutPoint parent_point =
- ConvertToContainingEmbeddedContentView(local_point);
- return parent->ConvertToRootFrame(parent_point);
- }
- return local_point;
+ return RoundedIntPoint(ConvertToRootFrame(PhysicalOffset(local_point)));
}
PhysicalOffset LocalFrameView::ConvertToRootFrame(
@@ -3806,17 +3796,6 @@ FloatPoint LocalFrameView::ConvertToRootFrame(
return local_point;
}
-LayoutRect LocalFrameView::ConvertToRootFrame(
- const LayoutRect& local_rect) const {
- if (LocalFrameView* parent = ParentFrameView()) {
- LayoutPoint parent_point =
- ConvertToContainingEmbeddedContentView(local_rect.Location());
- LayoutRect parent_rect(parent_point, local_rect.Size());
- return parent->ConvertToRootFrame(parent_rect);
- }
- return local_rect;
-}
-
PhysicalRect LocalFrameView::ConvertToRootFrame(
const PhysicalRect& local_rect) const {
if (LocalFrameView* parent = ParentFrameView()) {
@@ -3840,17 +3819,7 @@ IntRect LocalFrameView::ConvertFromRootFrame(
IntPoint LocalFrameView::ConvertFromRootFrame(
const IntPoint& point_in_root_frame) const {
return RoundedIntPoint(
- ConvertFromRootFrame(LayoutPoint(point_in_root_frame)));
-}
-
-LayoutPoint LocalFrameView::ConvertFromRootFrame(
- const LayoutPoint& point_in_root_frame) const {
- if (LocalFrameView* parent = ParentFrameView()) {
- LayoutPoint parent_point =
- parent->ConvertFromRootFrame(point_in_root_frame);
- return ConvertFromContainingEmbeddedContentView(parent_point);
- }
- return point_in_root_frame;
+ ConvertFromRootFrame(PhysicalOffset(point_in_root_frame)));
}
PhysicalOffset LocalFrameView::ConvertFromRootFrame(
@@ -4049,6 +4018,12 @@ void LocalFrameView::RenderThrottlingStatusChanged() {
frame_scheduler->TraceUrlChange(frame_->GetDocument()->Url().GetString());
}
+ // If we have become unthrottled, this is essentially a no-op since we're
+ // going to paint anyway. If we have become throttled, then this will force
+ // one lifecycle update to clear the painted output.
+ if (GetFrame().IsLocalRoot())
+ need_paint_phase_after_throttling_ = true;
+
#if DCHECK_IS_ON()
// Make sure we never have an unthrottled frame inside a throttled one.
LocalFrameView* parent = ParentFrameView();
@@ -4150,8 +4125,10 @@ bool LocalFrameView::ShouldThrottleRendering() const {
bool throttled_for_global_reasons = CanThrottleRendering() &&
frame_->GetDocument() &&
Lifecycle().ThrottlingAllowed();
- if (!throttled_for_global_reasons || needs_forced_compositing_update_)
+ if (!throttled_for_global_reasons || needs_forced_compositing_update_ ||
+ need_paint_phase_after_throttling_) {
return false;
+ }
// Only lifecycle phases up to layout are needed to generate an
// intersection observation.
@@ -4210,23 +4187,26 @@ void LocalFrameView::BeginLifecycleUpdates() {
if (document && base::FeatureList::IsEnabled(
blink::features::kAvoidFlashBetweenNavigation)) {
if (document->DeferredCompositorCommitIsAllowed()) {
- chrome_client.StartDeferringCommits(
- GetCommitDelayForAvoidFlashBetweenNavigation());
+ // Only defer commits once. This method gets called multiple times,
+ // and we do not want to defer a second time if we have already done
+ // so once and resumed commits already.
+ if (!have_deferred_commits_) {
+ chrome_client.StartDeferringCommits(
+ GetFrame(), GetCommitDelayForAvoidFlashBetweenNavigation());
+ have_deferred_commits_ = true;
+ }
+ // We do not StopDeferringCommits in cases where we have already started.
+ // A previously started deferral may not have completed yet, and we do
+ // not want to stop it prematurely.
} else {
chrome_client.StopDeferringCommits(
- cc::PaintHoldingCommitTrigger::kDisallowed);
+ GetFrame(), cc::PaintHoldingCommitTrigger::kDisallowed);
}
} else {
chrome_client.StopDeferringCommits(
- cc::PaintHoldingCommitTrigger::kFeatureDisabled);
+ GetFrame(), cc::PaintHoldingCommitTrigger::kFeatureDisabled);
}
- chrome_client.BeginLifecycleUpdates();
-}
-
-void LocalFrameView::StopDeferringCommits(
- cc::PaintHoldingCommitTrigger trigger) {
- if (GetFrame().GetPage())
- GetFrame().GetPage()->GetChromeClient().StopDeferringCommits(trigger);
+ chrome_client.BeginLifecycleUpdates(GetFrame());
}
void LocalFrameView::SetInitialViewportSize(const IntSize& viewport_size) {
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 de146c2ee04..a879e104e75 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
@@ -46,7 +46,7 @@
#include "third_party/blink/renderer/platform/graphics/paint_invalidation_reason.h"
#include "third_party/blink/renderer/platform/graphics/subtree_paint_property_update_reason.h"
#include "third_party/blink/renderer/platform/timer.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/casting.h"
#include "third_party/skia/include/core/SkColor.h"
@@ -69,13 +69,12 @@ class FragmentAnchor;
class Frame;
class FrameViewAutoSizeInfo;
class JSONObject;
-class JankTracker;
class KURL;
class LayoutAnalyzer;
class LayoutBox;
class LayoutEmbeddedObject;
class LayoutObject;
-class LayoutRect;
+class LayoutShiftTracker;
class LayoutSVGRoot;
class LayoutView;
class LocalFrame;
@@ -104,6 +103,16 @@ typedef uint64_t DOMTimeStamp;
using LayerTreeFlags = unsigned;
using MainThreadScrollingReasons = uint32_t;
+struct LifecycleData {
+ LifecycleData() {}
+ LifecycleData(base::TimeTicks start_time_arg, int count_arg)
+ : start_time(start_time_arg), count(count_arg) {}
+ base::TimeTicks start_time;
+ // The number of lifecycles that have occcurred since the first one,
+ // inclusive, on a given LocalFrameRoot.
+ unsigned count = 0;
+};
+
class CORE_EXPORT LocalFrameView final
: public GarbageCollectedFinalized<LocalFrameView>,
public FrameView {
@@ -359,6 +368,14 @@ class CORE_EXPORT LocalFrameView final
// desired state.
bool UpdateLifecycleToLayoutClean();
+ bool InLifecycleUpdate() { return in_lifecycle_update_; }
+ void SetInLifecycleUpdateForTest(bool val) { in_lifecycle_update_ = val; }
+ void SetLifecycleDataForTesting(const LifecycleData& lifecycle_data) {
+ lifecycle_data_ = lifecycle_data;
+ }
+
+ const LifecycleData& CurrentLifecycleData() const { return lifecycle_data_; }
+
// This for doing work that needs to run synchronously at the end of lifecyle
// updates, but needs to happen outside of the lifecycle code. It's OK to
// schedule another animation frame here, but the layout tree should not be
@@ -399,12 +416,8 @@ class CORE_EXPORT LocalFrameView final
IntRect ConvertToLayoutObject(const LayoutObject&, const IntRect&) const;
IntPoint ConvertFromLayoutObject(const LayoutObject&, const IntPoint&) const;
IntPoint ConvertToLayoutObject(const LayoutObject&, const IntPoint&) const;
- LayoutPoint ConvertFromLayoutObject(const LayoutObject&,
- const LayoutPoint&) const;
PhysicalOffset ConvertFromLayoutObject(const LayoutObject&,
const PhysicalOffset&) const;
- LayoutPoint ConvertToLayoutObject(const LayoutObject&,
- const LayoutPoint&) const;
PhysicalOffset ConvertToLayoutObject(const LayoutObject&,
const PhysicalOffset&) const;
FloatPoint ConvertToLayoutObject(const LayoutObject&,
@@ -496,7 +509,7 @@ class CORE_EXPORT LocalFrameView final
IntPoint FrameToViewport(const IntPoint&) const;
IntPoint ViewportToFrame(const IntPoint&) const;
FloatPoint ViewportToFrame(const FloatPoint&) const;
- LayoutPoint ViewportToFrame(const LayoutPoint&) const;
+ PhysicalOffset ViewportToFrame(const PhysicalOffset&) const;
// FIXME: Some external callers expect to get back a rect that's positioned
// in viewport space, but sized in CSS pixels. This is an artifact of the
@@ -508,19 +521,14 @@ class CORE_EXPORT LocalFrameView final
IntRect FrameToScreen(const IntRect&) const;
// Converts from/to local frame coordinates to the root frame coordinates.
- // TODO(wangxianzhu): Remove LayoutPoint/LayoutRect version after all clients
- // switch to use PhysicalPoint/PhysicalRect.
IntRect ConvertToRootFrame(const IntRect&) const;
IntPoint ConvertToRootFrame(const IntPoint&) const;
- LayoutPoint ConvertToRootFrame(const LayoutPoint&) const;
PhysicalOffset ConvertToRootFrame(const PhysicalOffset&) const;
FloatPoint ConvertToRootFrame(const FloatPoint&) const;
- LayoutRect ConvertToRootFrame(const LayoutRect&) const;
PhysicalRect ConvertToRootFrame(const PhysicalRect&) const;
IntRect ConvertFromRootFrame(const IntRect&) const;
IntPoint ConvertFromRootFrame(const IntPoint&) const;
FloatPoint ConvertFromRootFrame(const FloatPoint&) const;
- LayoutPoint ConvertFromRootFrame(const LayoutPoint&) const;
PhysicalOffset ConvertFromRootFrame(const PhysicalOffset&) const;
IntPoint ConvertSelfToChild(const EmbeddedContentView&,
const IntPoint&) const;
@@ -531,16 +539,12 @@ class CORE_EXPORT LocalFrameView final
IntPoint DocumentToFrame(const IntPoint&) const;
FloatPoint DocumentToFrame(const FloatPoint&) const;
DoublePoint DocumentToFrame(const DoublePoint&) const;
- LayoutPoint DocumentToFrame(const LayoutPoint&) const;
PhysicalOffset DocumentToFrame(const PhysicalOffset&) const;
IntRect DocumentToFrame(const IntRect&) const;
- LayoutRect DocumentToFrame(const LayoutRect&) const;
PhysicalRect DocumentToFrame(const PhysicalRect&) const;
IntPoint FrameToDocument(const IntPoint&) const;
- LayoutPoint FrameToDocument(const LayoutPoint&) const;
PhysicalOffset FrameToDocument(const PhysicalOffset&) const;
IntRect FrameToDocument(const IntRect&) const;
- LayoutRect FrameToDocument(const LayoutRect&) const;
PhysicalRect FrameToDocument(const PhysicalRect&) const;
// Normally a LocalFrameView synchronously paints during full lifecycle
@@ -658,7 +662,7 @@ class CORE_EXPORT LocalFrameView final
// When the frame is a local root and not a main frame, any recursive
// scrolling should continue in the parent process.
- void ScrollRectToVisibleInRemoteParent(const LayoutRect&,
+ void ScrollRectToVisibleInRemoteParent(const PhysicalRect&,
const WebScrollIntoViewParams&);
PaintArtifactCompositor* GetPaintArtifactCompositorForTesting() {
@@ -685,7 +689,7 @@ class CORE_EXPORT LocalFrameView final
cc::AnimationHost* GetCompositorAnimationHost() const;
CompositorAnimationTimeline* GetCompositorAnimationTimeline() const;
- JankTracker& GetJankTracker() { return *jank_tracker_; }
+ LayoutShiftTracker& GetLayoutShiftTracker() { return *layout_shift_tracker_; }
PaintTimingDetector& GetPaintTimingDetector() const {
return *paint_timing_detector_;
}
@@ -750,8 +754,6 @@ class CORE_EXPORT LocalFrameView final
void SetupPrintContext();
void ClearPrintContext();
- void StopDeferringCommits(cc::PaintHoldingCommitTrigger);
-
// Returns whether the lifecycle was succesfully updated to the
// target state.
bool UpdateLifecyclePhases(DocumentLifecycle::LifecycleState target_state,
@@ -772,7 +774,6 @@ class CORE_EXPORT LocalFrameView final
DocumentLifecycle::LifecycleState target_state);
void RunPaintLifecyclePhase();
- void PrePaint();
void PaintTree();
void UpdateStyleAndLayoutIfNeededRecursive();
@@ -792,14 +793,11 @@ class CORE_EXPORT LocalFrameView final
// transforms into account.
IntRect ConvertToContainingEmbeddedContentView(const IntRect&) const;
IntPoint ConvertToContainingEmbeddedContentView(const IntPoint&) const;
- LayoutPoint ConvertToContainingEmbeddedContentView(const LayoutPoint&) const;
PhysicalOffset ConvertToContainingEmbeddedContentView(
const PhysicalOffset&) const;
FloatPoint ConvertToContainingEmbeddedContentView(const FloatPoint&) const;
IntRect ConvertFromContainingEmbeddedContentView(const IntRect&) const;
IntPoint ConvertFromContainingEmbeddedContentView(const IntPoint&) const;
- LayoutPoint ConvertFromContainingEmbeddedContentView(
- const LayoutPoint&) const;
PhysicalOffset ConvertFromContainingEmbeddedContentView(
const PhysicalOffset&) const;
FloatPoint ConvertFromContainingEmbeddedContentView(const FloatPoint&) const;
@@ -954,6 +952,13 @@ class CORE_EXPORT LocalFrameView final
bool needs_forced_compositing_update_;
bool needs_focus_on_fragment_;
+ bool in_lifecycle_update_;
+
+ // True if the frame has deferred commits at least once per document load.
+ // We won't defer again for the same document.
+ bool have_deferred_commits_ = false;
+
+ LifecycleData lifecycle_data_;
IntRect remote_viewport_intersection_;
@@ -979,7 +984,7 @@ class CORE_EXPORT LocalFrameView final
scoped_refptr<LocalFrameUkmAggregator> ukm_aggregator_;
unsigned forced_layout_stack_depth_;
- TimeTicks forced_layout_start_time_;
+ base::TimeTicks forced_layout_start_time_;
Member<PrintContext> print_context_;
@@ -987,11 +992,18 @@ class CORE_EXPORT LocalFrameView final
size_t paint_frame_count_;
UniqueObjectId unique_id_;
- std::unique_ptr<JankTracker> jank_tracker_;
+ std::unique_ptr<LayoutShiftTracker> layout_shift_tracker_;
Member<PaintTimingDetector> paint_timing_detector_;
HeapHashSet<WeakMember<LifecycleNotificationObserver>> lifecycle_observers_;
+ // If set, this indicates that the rendering throttling status for the local
+ // root frame has changed. In this scenario, if we have become unthrottled,
+ // this is a no-op since we run paint anyway. However, if we have become
+ // throttled, this will force the lifecycle to reach the paint phase so that
+ // it can clear the painted output.
+ bool need_paint_phase_after_throttling_ = false;
+
#if DCHECK_IS_ON()
bool is_updating_descendant_dependent_flags_;
#endif
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 774025cebc3..2aeafc0615d 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
@@ -66,8 +66,8 @@ class LocalFrameViewTest : public RenderingTest {
}
void SetUp() override {
- RenderingTest::SetUp();
EnableCompositing();
+ RenderingTest::SetUp();
}
AnimationMockChromeClient& GetAnimationMockChromeClient() const {
@@ -176,6 +176,15 @@ TEST_F(LocalFrameViewTest, UpdateLifecyclePhasesForPrintingDetachedFrame) {
EXPECT_TRUE(child_layout_view->FirstFragment().PaintProperties());
}
+TEST_F(LocalFrameViewTest, CanHaveScrollbarsIfScrollingAttrEqualsNoChanged) {
+ SetBodyInnerHTML("<iframe scrolling='no'></iframe>");
+ EXPECT_FALSE(ChildDocument().View()->CanHaveScrollbars());
+
+ ChildDocument().WillChangeFrameOwnerProperties(0, 0, kScrollbarAlwaysOn,
+ false);
+ EXPECT_TRUE(ChildDocument().View()->CanHaveScrollbars());
+}
+
// Ensure the fragment navigation "scroll into view and focus" behavior doesn't
// activate synchronously while rendering is blocked waiting on a stylesheet.
// See https://crbug.com/851338.
diff --git a/chromium/third_party/blink/renderer/core/frame/location.cc b/chromium/third_party/blink/renderer/core/frame/location.cc
index 26e45438184..2eb0735cfdc 100644
--- a/chromium/third_party/blink/renderer/core/frame/location.cc
+++ b/chromium/third_party/blink/renderer/core/frame/location.cc
@@ -292,11 +292,10 @@ void Location::SetLocation(const String& url,
// execution, there are concerns about the correctness of that statement,
// see http://github.com/whatwg/html/issues/2591.
Document* current_document = current_window->document();
- if (current_document && completed_url.ProtocolIsJavaScript() &&
- !ContentSecurityPolicy::ShouldBypassMainWorld(current_document)) {
+ if (current_document && completed_url.ProtocolIsJavaScript()) {
String script_source = DecodeURLEscapeSequences(
completed_url.GetString(), DecodeURLMode::kUTF8OrIsomorphic);
- if (!current_document->GetContentSecurityPolicy()->AllowInline(
+ if (!current_document->GetContentSecurityPolicyForWorld()->AllowInline(
ContentSecurityPolicy::InlineType::kNavigation,
nullptr /* element */, script_source, String() /* nonce */,
current_document->Url(), OrdinalNumber())) {
diff --git a/chromium/third_party/blink/renderer/core/frame/location.h b/chromium/third_party/blink/renderer/core/frame/location.h
index 29a92b36b54..2b8601a2411 100644
--- a/chromium/third_party/blink/renderer/core/frame/location.h
+++ b/chromium/third_party/blink/renderer/core/frame/location.h
@@ -100,6 +100,8 @@ class CORE_EXPORT Location final : public ScriptWrappable {
// Returns true if the associated Window is the active Window in the frame.
bool IsAttached() const;
+ // Note: SetLocation should be called synchronously from the DOM operation to
+ // ensure we use the correct Javascript world for CSP checks.
enum class SetLocationPolicy { kNormal, kReplaceThisFrame };
void SetLocation(const String&,
LocalDOMWindow* current_window,
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 0a4f0f48c21..942b9226a94 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
@@ -28,12 +28,9 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#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"
#include "third_party/blink/renderer/platform/mhtml/mhtml_archive.h"
#include "third_party/blink/renderer/platform/mhtml/mhtml_parser.h"
#include "third_party/blink/renderer/platform/mhtml/serialized_resource.h"
@@ -41,6 +38,7 @@
#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"
+#include "third_party/blink/renderer/platform/text/date_components.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"
@@ -63,7 +61,7 @@ class MHTMLArchiveTest : public testing::Test {
public:
MHTMLArchiveTest() {
file_path_ = test::CoreTestDataPath("frameserializer/css/");
- mhtml_date_ = WTF::Time::FromJsTime(1520551829000);
+ mhtml_date_ = base::Time::FromJsTime(1520551829000);
mhtml_date_header_ = String::FromUTF8("Thu, 8 Mar 2018 23:30:29 -0000");
}
@@ -184,7 +182,7 @@ class MHTMLArchiveTest : public testing::Test {
Vector<char>& mhtml_data() { return mhtml_data_; }
- WTF::Time mhtml_date() const { return mhtml_date_; }
+ base::Time mhtml_date() const { return mhtml_date_; }
const String& mhtml_date_header() const { return mhtml_date_header_; }
void CheckLoadResult(const KURL url,
@@ -213,7 +211,7 @@ class MHTMLArchiveTest : public testing::Test {
String file_path_;
Vector<SerializedResource> resources_;
Vector<char> mhtml_data_;
- WTF::Time mhtml_date_;
+ base::Time mhtml_date_;
String mhtml_date_header_;
};
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 71a33c48876..047222ac9fb 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
@@ -83,8 +83,8 @@ class MHTMLLoadingTest : public testing::Test {
Page* GetPage() const { return helper_.GetWebView()->GetPage(); }
private:
- frame_test_helpers::WebViewHelper helper_;
ScopedTestingPlatformSupport<TestingPlatformSupport> platform_;
+ frame_test_helpers::WebViewHelper helper_;
};
// Checks that the domain is set to the actual MHTML file, not the URL it was
@@ -102,7 +102,7 @@ TEST_F(MHTMLLoadingTest, CheckDomain) {
EXPECT_EQ(kFileURL, frame->DomWindow()->location()->toString());
const SecurityOrigin* origin = document->GetSecurityOrigin();
- EXPECT_STRNE("localhost", origin->Domain().Ascii().data());
+ EXPECT_NE("localhost", origin->Domain().Ascii());
}
// Checks that full sandboxing protection has been turned on.
diff --git a/chromium/third_party/blink/renderer/core/frame/navigator.cc b/chromium/third_party/blink/renderer/core/frame/navigator.cc
index 45b96233618..bfffaafd466 100644
--- a/chromium/third_party/blink/renderer/core/frame/navigator.cc
+++ b/chromium/third_party/blink/renderer/core/frame/navigator.cc
@@ -29,12 +29,11 @@
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/navigator_id.h"
#include "third_party/blink/renderer/core/frame/settings.h"
-#include "third_party/blink/renderer/core/loader/cookie_jar.h"
#include "third_party/blink/renderer/core/loader/frame_loader.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/instrumentation/memory_pressure_listener.h"
#include "third_party/blink/renderer/platform/language.h"
-#include "third_party/blink/renderer/platform/memory_pressure_listener.h"
namespace blink {
@@ -86,14 +85,14 @@ UserAgentMetadata Navigator::GetUserAgentMetadata() const {
}
bool Navigator::cookieEnabled() const {
- if (!GetFrame())
+ if (!GetFrame() || !GetFrame()->GetDocument())
return false;
Settings* settings = GetFrame()->GetSettings();
if (!settings || !settings->GetCookieEnabled())
return false;
- return CookiesEnabled(GetFrame()->GetDocument());
+ return GetFrame()->GetDocument()->CookiesEnabled();
}
String Navigator::GetAcceptLanguages() {
diff --git a/chromium/third_party/blink/renderer/core/frame/navigator.idl b/chromium/third_party/blink/renderer/core/frame/navigator.idl
index a309bef4f14..f13febb148e 100644
--- a/chromium/third_party/blink/renderer/core/frame/navigator.idl
+++ b/chromium/third_party/blink/renderer/core/frame/navigator.idl
@@ -19,7 +19,9 @@
// https://html.spec.whatwg.org/C/#the-navigator-object
-interface Navigator {
+[
+ Exposed=Window
+] interface Navigator {
// objects implementing this interface also implement the interfaces given below
// TODO(foolip): vendorSub should be on NavigatorID.
diff --git a/chromium/third_party/blink/renderer/core/frame/navigator_device_memory.idl b/chromium/third_party/blink/renderer/core/frame/navigator_device_memory.idl
index 7a8e26b7c2a..76295186c35 100644
--- a/chromium/third_party/blink/renderer/core/frame/navigator_device_memory.idl
+++ b/chromium/third_party/blink/renderer/core/frame/navigator_device_memory.idl
@@ -7,6 +7,6 @@
[
Exposed=(Window, Worker)
] interface mixin NavigatorDeviceMemory {
- [HighEntropy,MeasureAs=NavigatorDeviceMemory,RuntimeEnabled=NavigatorDeviceMemory,SecureContext]
+ [HighEntropy,MeasureAs=NavigatorDeviceMemory,SecureContext]
readonly attribute float deviceMemory;
};
diff --git a/chromium/third_party/blink/renderer/core/frame/opened_frame_tracker.h b/chromium/third_party/blink/renderer/core/frame/opened_frame_tracker.h
index 60c44d6c0bc..f645a9c9813 100644
--- a/chromium/third_party/blink/renderer/core/frame/opened_frame_tracker.h
+++ b/chromium/third_party/blink/renderer/core/frame/opened_frame_tracker.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_OPENED_FRAME_TRACKER_H_
#include "base/macros.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/frame/page_scale_constraints.h b/chromium/third_party/blink/renderer/core/frame/page_scale_constraints.h
index de4f26deb14..301cda40512 100644
--- a/chromium/third_party/blink/renderer/core/frame/page_scale_constraints.h
+++ b/chromium/third_party/blink/renderer/core/frame/page_scale_constraints.h
@@ -33,7 +33,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/geometry/float_size.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.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 d6ceb962614..d80144cba13 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
@@ -40,7 +40,7 @@
#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/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/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 c3c1162118b..746a4f687cf 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
@@ -91,7 +91,6 @@ class V8FunctionExecutor : public PausableScriptExecutor::Executor {
ScopedPersistent<v8::Function> function_;
ScopedPersistent<v8::Value> receiver_;
V8PersistentValueVector<v8::Value> args_;
- scoped_refptr<UserGestureToken> gesture_token_;
};
V8FunctionExecutor::V8FunctionExecutor(v8::Isolate* isolate,
@@ -101,8 +100,7 @@ V8FunctionExecutor::V8FunctionExecutor(v8::Isolate* isolate,
v8::Local<v8::Value> argv[])
: function_(isolate, function),
receiver_(isolate, receiver),
- args_(isolate),
- gesture_token_(UserGestureIndicator::CurrentToken()) {
+ args_(isolate) {
args_.ReserveCapacity(argc);
for (int i = 0; i < argc; ++i)
args_.Append(argv[i]);
@@ -118,11 +116,6 @@ Vector<v8::Local<v8::Value>> V8FunctionExecutor::Execute(LocalFrame* frame) {
for (wtf_size_t i = 0; i < args_size; ++i)
args.push_back(args_.Get(i));
{
- std::unique_ptr<UserGestureIndicator> gesture_indicator;
- if (gesture_token_) {
- gesture_indicator =
- std::make_unique<UserGestureIndicator>(std::move(gesture_token_));
- }
if (V8ScriptRunner::CallFunction(function_.NewLocal(isolate),
frame->GetDocument(),
receiver_.NewLocal(isolate), args.size(),
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 383568ddc4f..5b5c9052847 100644
--- a/chromium/third_party/blink/renderer/core/frame/performance_monitor.cc
+++ b/chromium/third_party/blink/renderer/core/frame/performance_monitor.cc
@@ -17,13 +17,14 @@
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/html/parser/html_document_parser.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
namespace blink {
namespace {
-constexpr auto kLongTaskSubTaskThreshold = TimeDelta::FromMilliseconds(12);
+constexpr auto kLongTaskSubTaskThreshold =
+ base::TimeDelta::FromMilliseconds(12);
} // namespace
void PerformanceMonitor::BypassLongCompileThresholdOnceForTesting() {
@@ -239,7 +240,7 @@ void PerformanceMonitor::Did(const probe::CallFunction& probe) {
String name = user_callback->name ? String(user_callback->name)
: String(user_callback->atomic_name);
String text = String::Format("'%s' handler took %" PRId64 "ms",
- name.Utf8().data(), duration.InMilliseconds());
+ name.Utf8().c_str(), duration.InMilliseconds());
InnerReportGenericViolation(probe.context, handler_type, text, duration,
SourceLocation::FromFunction(probe.function));
}
@@ -256,7 +257,7 @@ void PerformanceMonitor::Did(const probe::V8Compile& probe) {
if (!enabled_ || thresholds_[kLongTask].is_zero())
return;
- TimeDelta v8_compile_duration = probe.Duration();
+ base::TimeDelta v8_compile_duration = probe.Duration();
if (bypass_long_compile_threshold_) {
bypass_long_compile_threshold_ = false;
@@ -267,7 +268,7 @@ void PerformanceMonitor::Did(const probe::V8Compile& probe) {
auto sub_task_attribution = std::make_unique<SubTaskAttribution>(
AtomicString("script-compile"),
- String::Format("%s(%d, %d)", probe.file_name.Utf8().data(), probe.line,
+ String::Format("%s(%d, %d)", probe.file_name.Utf8().c_str(), probe.line,
probe.column),
v8_compile_start_time_, v8_compile_duration);
sub_task_attributions_.push_back(std::move(sub_task_attribution));
@@ -312,9 +313,9 @@ void PerformanceMonitor::WillProcessTask(base::TimeTicks start_time) {
// Reset everything for regular and nested tasks.
script_depth_ = 0;
layout_depth_ = 0;
- per_task_style_and_layout_time_ = TimeDelta();
+ per_task_style_and_layout_time_ = base::TimeDelta();
user_callback_ = nullptr;
- v8_compile_start_time_ = TimeTicks();
+ v8_compile_start_time_ = base::TimeTicks();
sub_task_attributions_.clear();
}
diff --git a/chromium/third_party/blink/renderer/core/frame/performance_monitor.h b/chromium/third_party/blink/renderer/core/frame/performance_monitor.h
index 02fa6767f56..7f1e3a172c4 100644
--- a/chromium/third_party/blink/renderer/core/frame/performance_monitor.h
+++ b/chromium/third_party/blink/renderer/core/frame/performance_monitor.h
@@ -142,12 +142,12 @@ class CORE_EXPORT PerformanceMonitor final
Frame* observer_frame);
bool enabled_ = false;
- TimeDelta per_task_style_and_layout_time_;
+ base::TimeDelta per_task_style_and_layout_time_;
unsigned script_depth_ = 0;
unsigned layout_depth_ = 0;
unsigned user_callback_depth_ = 0;
const void* user_callback_;
- TimeTicks v8_compile_start_time_;
+ base::TimeTicks v8_compile_start_time_;
SubTaskAttribution::EntriesVector sub_task_attributions_;
diff --git a/chromium/third_party/blink/renderer/core/frame/picture_in_picture_controller.h b/chromium/third_party/blink/renderer/core/frame/picture_in_picture_controller.h
index e530afc9683..0f08617bce5 100644
--- a/chromium/third_party/blink/renderer/core/frame/picture_in_picture_controller.h
+++ b/chromium/third_party/blink/renderer/core/frame/picture_in_picture_controller.h
@@ -47,6 +47,7 @@ class CORE_EXPORT PictureInPictureController
kDisabledBySystem,
kDisabledByFeaturePolicy,
kDisabledByAttribute,
+ kInvalidWidthOrHeightOption,
};
// Enter Picture-in-Picture for an element with options if any and resolve
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 de161054e9d..209e34eb913 100644
--- a/chromium/third_party/blink/renderer/core/frame/remote_frame.cc
+++ b/chromium/third_party/blink/renderer/core/frame/remote_frame.cc
@@ -35,11 +35,13 @@ namespace blink {
RemoteFrame::RemoteFrame(RemoteFrameClient* client,
Page& page,
- FrameOwner* owner)
+ FrameOwner* owner,
+ WindowAgentFactory* inheriting_agent_factory)
: Frame(client,
page,
owner,
- MakeGarbageCollected<RemoteWindowProxyManager>(*this)),
+ MakeGarbageCollected<RemoteWindowProxyManager>(*this),
+ inheriting_agent_factory),
security_context_(MakeGarbageCollected<RemoteSecurityContext>()) {
dom_window_ = MakeGarbageCollected<RemoteDOMWindow>(*this);
UpdateInertIfPossible();
@@ -145,7 +147,7 @@ void RemoteFrame::DetachImpl(FrameDetachType type) {
SetCcLayer(nullptr, false, false);
}
-bool RemoteFrame::PrepareForCommit() {
+bool RemoteFrame::DetachDocument() {
DetachChildren();
return !!GetPage();
}
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 fbdb4768f3f..b43e65846c7 100644
--- a/chromium/third_party/blink/renderer/core/frame/remote_frame.h
+++ b/chromium/third_party/blink/renderer/core/frame/remote_frame.h
@@ -24,14 +24,19 @@ struct FrameLoadRequest;
class CORE_EXPORT RemoteFrame final : public Frame {
public:
- RemoteFrame(RemoteFrameClient*, Page&, FrameOwner*);
+ // For a description of |inheriting_agent_factory| go see the comment on the
+ // Frame constructor.
+ RemoteFrame(RemoteFrameClient*,
+ Page&,
+ FrameOwner*,
+ WindowAgentFactory* inheriting_agent_factory);
~RemoteFrame() override;
// Frame overrides:
void Trace(blink::Visitor*) override;
void Navigate(const FrameLoadRequest&, WebFrameLoadType) override;
RemoteSecurityContext* GetSecurityContext() const override;
- bool PrepareForCommit() override;
+ bool DetachDocument() override;
void CheckCompleted() override;
bool ShouldClose() override;
void DidFreeze() override;
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 27022887b96..08124e6e1df 100644
--- a/chromium/third_party/blink/renderer/core/frame/reporting_context.cc
+++ b/chromium/third_party/blink/renderer/core/frame/reporting_context.cc
@@ -15,8 +15,8 @@
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/report.h"
#include "third_party/blink/renderer/core/frame/reporting_observer.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
@@ -156,7 +156,7 @@ void ReportingContext::SendToReportingAPI(Report* report,
const DeprecationReportBody* body =
static_cast<DeprecationReportBody*>(report->body());
base::Optional<base::Time> anticipated_removal =
- WTF::Time::FromDoubleT(body->anticipatedRemoval(is_null));
+ base::Time::FromDoubleT(body->anticipatedRemoval(is_null));
if (is_null)
anticipated_removal = base::nullopt;
GetReportingService()->QueueDeprecationReport(
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 d74be1608f4..37a92dbf142 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
@@ -70,10 +70,10 @@ ScrollableArea& RootFrameViewport::LayoutViewport() const {
return *layout_viewport_;
}
-LayoutRect RootFrameViewport::RootContentsToLayoutViewportContents(
+PhysicalRect RootFrameViewport::RootContentsToLayoutViewportContents(
LocalFrameView& root_frame_view,
- const LayoutRect& rect) const {
- LayoutRect ret(rect);
+ const PhysicalRect& rect) const {
+ PhysicalRect ret = rect;
// If the root LocalFrameView is the layout viewport then coordinates in the
// root LocalFrameView's content space are already in the layout viewport's
@@ -85,7 +85,8 @@ LayoutRect RootFrameViewport::RootContentsToLayoutViewportContents(
// by adding the scroll position.
// TODO(bokan): This will have to be revisited if we ever remove the
// restriction that a root scroller must be exactly screen filling.
- ret.Move(LayoutSize(LayoutViewport().GetScrollOffset()));
+ ret.Move(
+ PhysicalOffset::FromFloatSizeRound(LayoutViewport().GetScrollOffset()));
return ret;
}
@@ -163,8 +164,7 @@ int RootFrameViewport::VerticalScrollbarWidth(
}
void RootFrameViewport::UpdateScrollAnimator() {
- GetScrollAnimator().SetCurrentOffset(
- ToFloatSize(ScrollOffsetFromScrollAnimators()));
+ GetScrollAnimator().SetCurrentOffset(ScrollOffsetFromScrollAnimators());
}
ScrollOffset RootFrameViewport::ScrollOffsetFromScrollAnimators() const {
@@ -179,21 +179,22 @@ IntRect RootFrameViewport::VisibleContentRect(
VisualViewport().VisibleContentRect(scrollbar_inclusion).Size());
}
-LayoutRect RootFrameViewport::VisibleScrollSnapportRect(
+PhysicalRect RootFrameViewport::VisibleScrollSnapportRect(
IncludeScrollbarsInRect scrollbar_inclusion) const {
// The effective viewport is the intersection of the visual viewport with the
// layout viewport.
- LayoutRect frame_rect_in_content = LayoutRect(
- FloatPoint(LayoutViewport().GetScrollOffset()),
- FloatSize(
+ PhysicalRect frame_rect_in_content(
+ PhysicalOffset::FromFloatSizeRound(LayoutViewport().GetScrollOffset()),
+ PhysicalSize(
LayoutViewport().VisibleContentRect(scrollbar_inclusion).Size()));
- LayoutRect visual_rect_in_content = LayoutRect(
- FloatPoint(LayoutViewport().GetScrollOffset() +
- VisualViewport().GetScrollAnimator().CurrentOffset()),
- FloatSize(
+ PhysicalRect visual_rect_in_content(
+ PhysicalOffset::FromFloatSizeRound(
+ LayoutViewport().GetScrollOffset() +
+ VisualViewport().GetScrollAnimator().CurrentOffset()),
+ PhysicalSize(
VisualViewport().VisibleContentRect(scrollbar_inclusion).Size()));
- LayoutRect visible_scroll_snapport =
+ PhysicalRect visible_scroll_snapport =
Intersection(visual_rect_in_content, frame_rect_in_content);
if (!LayoutViewport().GetLayoutBox())
return visible_scroll_snapport;
@@ -282,13 +283,14 @@ ScrollOffset RootFrameViewport::ClampToUserScrollableOffset(
return scroll_offset;
}
-LayoutRect RootFrameViewport::ScrollIntoView(
- const LayoutRect& rect_in_absolute,
+PhysicalRect RootFrameViewport::ScrollIntoView(
+ const PhysicalRect& rect_in_absolute,
const WebScrollIntoViewParams& params) {
- LayoutRect scroll_snapport_rect(VisibleScrollSnapportRect());
+ PhysicalRect scroll_snapport_rect = VisibleScrollSnapportRect();
- LayoutRect rect_in_document = rect_in_absolute;
- rect_in_document.Move(LayoutSize(LayoutViewport().GetScrollOffset()));
+ PhysicalRect rect_in_document = rect_in_absolute;
+ rect_in_document.Move(
+ PhysicalOffset::FromFloatSizeFloor(LayoutViewport().GetScrollOffset()));
ScrollOffset new_scroll_offset =
ClampScrollOffset(ScrollAlignment::GetScrollOffsetToExpose(
@@ -328,7 +330,8 @@ LayoutRect RootFrameViewport::ScrollIntoView(
// Return the newly moved rect to absolute coordinates.
// TODO(szager): PaintLayerScrollableArea::ScrollIntoView clips the return
// value to the visible content rect, but this does not.
- rect_in_document.Move(-LayoutSize(LayoutViewport().GetScrollOffset()));
+ rect_in_document.Move(
+ -PhysicalOffset::FromFloatSizeRound(LayoutViewport().GetScrollOffset()));
return rect_in_document;
}
@@ -476,8 +479,12 @@ GraphicsLayer* RootFrameViewport::LayerForScrollCorner() const {
return LayoutViewport().LayerForScrollCorner();
}
-ScrollResult RootFrameViewport::UserScroll(ScrollGranularity granularity,
- const FloatSize& delta) {
+ScrollResult RootFrameViewport::UserScroll(
+ ScrollGranularity granularity,
+ const FloatSize& delta,
+ ScrollableArea::ScrollCallback on_finish) {
+ base::ScopedClosureRunner run_on_return(std::move(on_finish));
+
// TODO(bokan/ymalik): Once smooth scrolling is permanently enabled we
// should be able to remove this method override and use the base class
// version: ScrollableArea::userScroll.
@@ -525,14 +532,21 @@ ScrollResult RootFrameViewport::UserScroll(ScrollGranularity granularity,
// TODO(bokan): Why do we call userScroll on the animators directly and
// not through the ScrollableAreas?
- ScrollResult visual_result = VisualViewport().GetScrollAnimator().UserScroll(
- granularity, visual_consumed_delta);
-
- if (visual_consumed_delta == pixel_delta)
+ if (visual_consumed_delta == pixel_delta) {
+ ScrollResult visual_result =
+ VisualViewport().GetScrollAnimator().UserScroll(
+ granularity, visual_consumed_delta, run_on_return.Release());
return visual_result;
+ }
+
+ ScrollableArea::ScrollCallback callback = run_on_return.Release();
+ auto all_done = callback ? base::BarrierClosure(2, std::move(callback))
+ : base::RepeatingClosure();
+ ScrollResult visual_result = VisualViewport().GetScrollAnimator().UserScroll(
+ granularity, visual_consumed_delta, all_done);
ScrollResult layout_result = LayoutViewport().GetScrollAnimator().UserScroll(
- granularity, scrollable_axis_delta);
+ granularity, scrollable_axis_delta, all_done);
// Remember to add any delta not used because of !userInputScrollable to the
// unusedScrollDelta in the result.
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 cb8477ff94a..46d8b5eca46 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
@@ -14,7 +14,7 @@
namespace blink {
class LocalFrameView;
-class LayoutRect;
+struct PhysicalRect;
struct WebScrollIntoViewParams;
// ScrollableArea for the root frame's viewport. This class ties together the
@@ -46,9 +46,9 @@ class CORE_EXPORT RootFrameViewport final
// and so the root content is the layout viewport's content but if the page
// sets a custom root scroller via document.rootScroller, another element
// may be the layout viewport.
- LayoutRect RootContentsToLayoutViewportContents(
+ PhysicalRect RootContentsToLayoutViewportContents(
LocalFrameView& root_frame_view,
- const LayoutRect&) const;
+ const PhysicalRect&) const;
void RestoreToAnchor(const ScrollOffset&);
@@ -61,11 +61,11 @@ class CORE_EXPORT RootFrameViewport final
ScrollType,
ScrollBehavior,
ScrollCallback on_finish) override;
- LayoutRect ScrollIntoView(const LayoutRect&,
- const WebScrollIntoViewParams&) override;
+ PhysicalRect ScrollIntoView(const PhysicalRect&,
+ const WebScrollIntoViewParams&) override;
IntRect VisibleContentRect(
IncludeScrollbarsInRect = kExcludeScrollbars) const override;
- LayoutRect VisibleScrollSnapportRect(
+ PhysicalRect VisibleScrollSnapportRect(
IncludeScrollbarsInRect = kExcludeScrollbars) const override;
bool ShouldUseIntegerScrollOffset() const override;
bool IsThrottled() const override {
@@ -102,7 +102,9 @@ class CORE_EXPORT RootFrameViewport final
int VerticalScrollbarWidth(
OverlayScrollbarClipBehavior =
kIgnorePlatformOverlayScrollbarSize) const override;
- ScrollResult UserScroll(ScrollGranularity, const FloatSize&) override;
+ ScrollResult UserScroll(ScrollGranularity,
+ const FloatSize&,
+ ScrollableArea::ScrollCallback on_finish) override;
CompositorElementId GetCompositorElementId() const override;
CompositorElementId GetScrollbarElementId(
ScrollbarOrientation orientation) override;
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 a0be0cc9c5a..29dbeb454d8 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
@@ -13,6 +13,7 @@
#include "third_party/blink/renderer/core/scroll/scroll_types.h"
#include "third_party/blink/renderer/core/scroll/scrollable_area.h"
#include "third_party/blink/renderer/core/scroll/scrollbar_theme_mock.h"
+#include "third_party/blink/renderer/core/testing/core_unit_test_helper.h"
#include "third_party/blink/renderer/platform/geometry/double_rect.h"
#include "third_party/blink/renderer/platform/geometry/layout_rect.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
@@ -145,9 +146,9 @@ class RootLayoutViewportStub : public ScrollableAreaStub {
return ScrollOffset(ContentsSize() - ViewportSize());
}
- LayoutRect DocumentToFrame(const LayoutRect& rect) const {
- LayoutRect ret = rect;
- ret.Move(LayoutSize(-GetScrollOffset()));
+ PhysicalRect DocumentToFrame(const PhysicalRect& rect) const {
+ PhysicalRect ret = rect;
+ ret.Move(-PhysicalOffset::FromFloatSizeRound(GetScrollOffset()));
return ret;
}
@@ -220,14 +221,16 @@ TEST_F(RootFrameViewportTest, UserInputScrollable) {
// Layout viewport shouldn't scroll since it's not horizontally scrollable,
// but visual viewport should.
root_frame_viewport->UserScroll(ScrollGranularity::kScrollByPixel,
- FloatSize(300, 0));
+ FloatSize(300, 0),
+ ScrollableArea::ScrollCallback());
EXPECT_EQ(ScrollOffset(0, 0), layout_viewport->GetScrollOffset());
EXPECT_EQ(ScrollOffset(50, 0), visual_viewport->GetScrollOffset());
EXPECT_EQ(ScrollOffset(50, 0), root_frame_viewport->GetScrollOffset());
// Vertical scrolling should be unaffected.
root_frame_viewport->UserScroll(ScrollGranularity::kScrollByPixel,
- FloatSize(0, 300));
+ FloatSize(0, 300),
+ ScrollableArea::ScrollCallback());
EXPECT_EQ(ScrollOffset(0, 150), layout_viewport->GetScrollOffset());
EXPECT_EQ(ScrollOffset(50, 75), visual_viewport->GetScrollOffset());
EXPECT_EQ(ScrollOffset(50, 225), root_frame_viewport->GetScrollOffset());
@@ -250,14 +253,16 @@ TEST_F(RootFrameViewportTest, UserInputScrollable) {
// Layout viewport shouldn't scroll since it's not vertically scrollable,
// but visual viewport should.
root_frame_viewport->UserScroll(ScrollGranularity::kScrollByPixel,
- FloatSize(0, 300));
+ FloatSize(0, 300),
+ ScrollableArea::ScrollCallback());
EXPECT_EQ(ScrollOffset(0, 0), layout_viewport->GetScrollOffset());
EXPECT_EQ(ScrollOffset(0, 75), visual_viewport->GetScrollOffset());
EXPECT_EQ(ScrollOffset(0, 75), root_frame_viewport->GetScrollOffset());
// Horizontal scrolling should be unaffected.
root_frame_viewport->UserScroll(ScrollGranularity::kScrollByPixel,
- FloatSize(300, 0));
+ FloatSize(300, 0),
+ ScrollableArea::ScrollCallback());
EXPECT_EQ(ScrollOffset(100, 0), layout_viewport->GetScrollOffset());
EXPECT_EQ(ScrollOffset(50, 75), visual_viewport->GetScrollOffset());
EXPECT_EQ(ScrollOffset(150, 75), root_frame_viewport->GetScrollOffset());
@@ -294,7 +299,8 @@ TEST_F(RootFrameViewportTest, TestScrollAnimatorUpdatedBeforeScroll) {
EXPECT_EQ(ScrollOffset(50, 75), root_frame_viewport->GetScrollOffset());
root_frame_viewport->UserScroll(ScrollGranularity::kScrollByPixel,
- FloatSize(-50, 0));
+ FloatSize(-50, 0),
+ ScrollableArea::ScrollCallback());
EXPECT_EQ(ScrollOffset(0, 75), root_frame_viewport->GetScrollOffset());
EXPECT_EQ(ScrollOffset(0, 75), visual_viewport->GetScrollOffset());
@@ -306,7 +312,8 @@ TEST_F(RootFrameViewportTest, TestScrollAnimatorUpdatedBeforeScroll) {
EXPECT_EQ(ScrollOffset(100, 150), root_frame_viewport->GetScrollOffset());
root_frame_viewport->UserScroll(ScrollGranularity::kScrollByPixel,
- FloatSize(-100, 0));
+ FloatSize(-100, 0),
+ ScrollableArea::ScrollCallback());
EXPECT_EQ(ScrollOffset(0, 150), root_frame_viewport->GetScrollOffset());
EXPECT_EQ(ScrollOffset(0, 150), layout_viewport->GetScrollOffset());
}
@@ -328,7 +335,7 @@ TEST_F(RootFrameViewportTest, ScrollIntoView) {
// scaled.
visual_viewport->SetViewportSize(IntSize(100, 100));
root_frame_viewport->ScrollIntoView(
- layout_viewport->DocumentToFrame(LayoutRect(100, 250, 50, 50)),
+ layout_viewport->DocumentToFrame(PhysicalRect(100, 250, 50, 50)),
WebScrollIntoViewParams(ScrollAlignment::kAlignToEdgeIfNeeded,
ScrollAlignment::kAlignToEdgeIfNeeded,
kProgrammaticScroll, true,
@@ -337,7 +344,7 @@ TEST_F(RootFrameViewportTest, ScrollIntoView) {
EXPECT_EQ(ScrollOffset(0, 50), visual_viewport->GetScrollOffset());
root_frame_viewport->ScrollIntoView(
- layout_viewport->DocumentToFrame(LayoutRect(25, 75, 50, 50)),
+ layout_viewport->DocumentToFrame(PhysicalRect(25, 75, 50, 50)),
WebScrollIntoViewParams(ScrollAlignment::kAlignToEdgeIfNeeded,
ScrollAlignment::kAlignToEdgeIfNeeded,
kProgrammaticScroll, true,
@@ -353,7 +360,7 @@ TEST_F(RootFrameViewportTest, ScrollIntoView) {
ScrollableArea::ScrollCallback());
root_frame_viewport->ScrollIntoView(
- layout_viewport->DocumentToFrame(LayoutRect(50, 75, 50, 75)),
+ layout_viewport->DocumentToFrame(PhysicalRect(50, 75, 50, 75)),
WebScrollIntoViewParams(ScrollAlignment::kAlignToEdgeIfNeeded,
ScrollAlignment::kAlignToEdgeIfNeeded,
kProgrammaticScroll, true,
@@ -362,7 +369,7 @@ TEST_F(RootFrameViewportTest, ScrollIntoView) {
EXPECT_EQ(ScrollOffset(50, 75), visual_viewport->GetScrollOffset());
root_frame_viewport->ScrollIntoView(
- layout_viewport->DocumentToFrame(LayoutRect(190, 290, 10, 10)),
+ layout_viewport->DocumentToFrame(PhysicalRect(190, 290, 10, 10)),
WebScrollIntoViewParams(ScrollAlignment::kAlignToEdgeIfNeeded,
ScrollAlignment::kAlignToEdgeIfNeeded,
kProgrammaticScroll, true,
@@ -380,7 +387,7 @@ TEST_F(RootFrameViewportTest, ScrollIntoView) {
kScrollBehaviorInstant, ScrollableArea::ScrollCallback());
root_frame_viewport->ScrollIntoView(
- layout_viewport->DocumentToFrame(LayoutRect(
+ layout_viewport->DocumentToFrame(PhysicalRect(
root_frame_viewport->VisibleContentRect(kExcludeScrollbars))),
WebScrollIntoViewParams(ScrollAlignment::kAlignToEdgeIfNeeded,
ScrollAlignment::kAlignToEdgeIfNeeded,
@@ -390,7 +397,7 @@ TEST_F(RootFrameViewportTest, ScrollIntoView) {
EXPECT_EQ(ScrollOffset(0, 10), visual_viewport->GetScrollOffset());
root_frame_viewport->ScrollIntoView(
- layout_viewport->DocumentToFrame(LayoutRect(
+ layout_viewport->DocumentToFrame(PhysicalRect(
root_frame_viewport->VisibleContentRect(kExcludeScrollbars))),
WebScrollIntoViewParams(ScrollAlignment::kAlignCenterAlways,
ScrollAlignment::kAlignCenterAlways,
@@ -400,7 +407,7 @@ TEST_F(RootFrameViewportTest, ScrollIntoView) {
EXPECT_EQ(ScrollOffset(0, 10), visual_viewport->GetScrollOffset());
root_frame_viewport->ScrollIntoView(
- layout_viewport->DocumentToFrame(LayoutRect(
+ layout_viewport->DocumentToFrame(PhysicalRect(
root_frame_viewport->VisibleContentRect(kExcludeScrollbars))),
WebScrollIntoViewParams(
ScrollAlignment::kAlignTopAlways, ScrollAlignment::kAlignTopAlways,
diff --git a/chromium/third_party/blink/renderer/core/frame/rotation_viewport_anchor.cc b/chromium/third_party/blink/renderer/core/frame/rotation_viewport_anchor.cc
index fa7863d60c8..ce59e84dc12 100644
--- a/chromium/third_party/blink/renderer/core/frame/rotation_viewport_anchor.cc
+++ b/chromium/third_party/blink/renderer/core/frame/rotation_viewport_anchor.cc
@@ -128,7 +128,7 @@ void RotationViewportAnchor::SetAnchor() {
FloatPoint(root_frame_viewport->VisibleContentRect().Location());
anchor_node_.Clear();
- anchor_node_bounds_ = LayoutRect();
+ anchor_node_bounds_ = PhysicalRect();
anchor_in_node_coords_ = FloatSize();
normalized_visual_viewport_offset_ = FloatSize();
@@ -169,9 +169,9 @@ void RotationViewportAnchor::SetAnchor() {
anchor_node_ = node;
anchor_node_bounds_ = root_frame_view_->FrameToDocument(
- LayoutRect(node->GetLayoutObject()->AbsoluteBoundingBoxRect()));
+ PhysicalRect(node->GetLayoutObject()->AbsoluteBoundingBoxRect()));
anchor_in_node_coords_ =
- anchor_point_in_document - FloatPoint(anchor_node_bounds_.Location());
+ anchor_point_in_document - FloatPoint(anchor_node_bounds_.offset);
anchor_in_node_coords_.Scale(1.f / anchor_node_bounds_.Width(),
1.f / anchor_node_bounds_.Height());
}
@@ -242,24 +242,24 @@ FloatPoint RotationViewportAnchor::GetInnerOrigin(
!anchor_node_->GetLayoutObject())
return visual_viewport_in_document_;
- const LayoutRect current_node_bounds = root_frame_view_->FrameToDocument(
- LayoutRect(anchor_node_->GetLayoutObject()->AbsoluteBoundingBoxRect()));
+ const PhysicalRect current_node_bounds = root_frame_view_->FrameToDocument(
+ PhysicalRect(anchor_node_->GetLayoutObject()->AbsoluteBoundingBoxRect()));
if (anchor_node_bounds_ == current_node_bounds)
return visual_viewport_in_document_;
RootFrameViewport* root_frame_viewport =
root_frame_view_->GetRootFrameViewport();
- const LayoutRect current_node_bounds_in_layout_viewport =
+ const PhysicalRect current_node_bounds_in_layout_viewport =
root_frame_viewport->RootContentsToLayoutViewportContents(
*root_frame_view_.Get(), current_node_bounds);
// Compute the new anchor point relative to the node position
FloatSize anchor_offset_from_node(
- current_node_bounds_in_layout_viewport.Size());
+ current_node_bounds_in_layout_viewport.size);
anchor_offset_from_node.Scale(anchor_in_node_coords_.Width(),
anchor_in_node_coords_.Height());
FloatPoint anchor_point =
- FloatPoint(current_node_bounds_in_layout_viewport.Location()) +
+ FloatPoint(current_node_bounds_in_layout_viewport.offset) +
anchor_offset_from_node;
// Compute the new origin point relative to the new anchor point
diff --git a/chromium/third_party/blink/renderer/core/frame/rotation_viewport_anchor.h b/chromium/third_party/blink/renderer/core/frame/rotation_viewport_anchor.h
index 6ee1c7683ca..6eb40056cf8 100644
--- a/chromium/third_party/blink/renderer/core/frame/rotation_viewport_anchor.h
+++ b/chromium/third_party/blink/renderer/core/frame/rotation_viewport_anchor.h
@@ -6,10 +6,9 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_ROTATION_VIEWPORT_ANCHOR_H_
#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/layout/geometry/physical_rect.h"
#include "third_party/blink/renderer/platform/geometry/float_size.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/geometry/layout_rect.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
namespace blink {
@@ -65,7 +64,7 @@ class CORE_EXPORT RotationViewportAnchor {
Member<Node> anchor_node_;
// In Document coordinates.
- LayoutRect anchor_node_bounds_;
+ PhysicalRect anchor_node_bounds_;
FloatSize anchor_in_inner_view_coords_;
FloatSize anchor_in_node_coords_;
diff --git a/chromium/third_party/blink/renderer/core/frame/sandbox_flags.h b/chromium/third_party/blink/renderer/core/frame/sandbox_flags.h
index df8ef0ed7c3..4c5c622ef76 100644
--- a/chromium/third_party/blink/renderer/core/frame/sandbox_flags.h
+++ b/chromium/third_party/blink/renderer/core/frame/sandbox_flags.h
@@ -27,8 +27,6 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_SANDBOX_FLAGS_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_SANDBOX_FLAGS_H_
-#include <vector>
-
#include "third_party/blink/public/common/feature_policy/feature_policy.h"
#include "third_party/blink/public/common/frame/sandbox_flags.h"
#include "third_party/blink/renderer/core/dom/space_split_string.h"
diff --git a/chromium/third_party/blink/renderer/core/frame/settings.h b/chromium/third_party/blink/renderer/core/frame/settings.h
index ccba2309239..5c4091123f8 100644
--- a/chromium/third_party/blink/renderer/core/frame/settings.h
+++ b/chromium/third_party/blink/renderer/core/frame/settings.h
@@ -31,6 +31,7 @@
#include <memory>
#include "base/macros.h"
+#include "third_party/blink/public/common/css/forced_colors.h"
#include "third_party/blink/public/common/css/preferred_color_scheme.h"
#include "third_party/blink/public/common/manifest/web_display_mode.h"
#include "third_party/blink/public/platform/pointer_properties.h"
diff --git a/chromium/third_party/blink/renderer/core/frame/settings.json5 b/chromium/third_party/blink/renderer/core/frame/settings.json5
index 90b072c6f41..6db399bdf88 100644
--- a/chromium/third_party/blink/renderer/core/frame/settings.json5
+++ b/chromium/third_party/blink/renderer/core/frame/settings.json5
@@ -484,6 +484,12 @@
initial: false,
},
+ // The current state of caret browsing mode.
+ {
+ name: "caretBrowsingEnabled",
+ initial: false,
+ },
+
// Font scale factor for accessibility, applied as part of text autosizing.
{
name: "accessibilityFontScaleFactor",
@@ -771,6 +777,18 @@
name: "textTrackTextSize",
type: "String",
},
+ {
+ name: "textTrackWindowColor",
+ type: "String",
+ },
+ {
+ name: "textTrackWindowPadding",
+ type: "String",
+ },
+ {
+ name: "textTrackWindowRadius",
+ type: "String",
+ },
// Margin for title-safe placement of cues with overscan, gives top and bottom margin size as
// percentage of video element height (for horizontal text) into which cues will not be placed.
@@ -902,7 +920,7 @@
},
{
name: "darkModeImagePolicy",
- initial: "DarkModeImagePolicy::kFilterAll",
+ initial: "DarkModeImagePolicy::kFilterNone",
type: "DarkModeImagePolicy",
invalidate: "Paint",
},
@@ -913,9 +931,15 @@
invalidate: "Paint",
},
{
- name: "darkModeTextPolicy",
- initial: "DarkModeTextPolicy::kInvertAll",
- type: "DarkModeTextPolicy",
+ name: "darkModeTextBrightnessThreshold",
+ initial: "256",
+ type: "int",
+ invalidate: "Paint",
+ },
+ {
+ name: "darkModeBackgroundBrightnessThreshold",
+ initial: "0",
+ type: "int",
invalidate: "Paint",
},
{
@@ -947,7 +971,7 @@
//
{
name: "lazyFrameLoadingDistanceThresholdPxUnknown",
- initial: 6000,
+ initial: 4000,
type: "int",
},
{
@@ -981,7 +1005,7 @@
//
{
name: "lazyImageLoadingDistanceThresholdPxUnknown",
- initial: 5000,
+ initial: 3000,
type: "int",
},
{
@@ -1030,5 +1054,13 @@
name: "DontSendKeyEventsToJavascript",
initial: false,
},
+ // Forced colors from the OS/application passed to the renderer for
+ // evaluating the forced-colors media query.
+ {
+ name: "forcedColors",
+ initial: "ForcedColors::kNone",
+ invalidate: "ColorScheme",
+ type: "ForcedColors",
+ },
],
}
diff --git a/chromium/third_party/blink/renderer/core/frame/settings_delegate.h b/chromium/third_party/blink/renderer/core/frame/settings_delegate.h
index 428173cd8c5..26ed4b5ca9e 100644
--- a/chromium/third_party/blink/renderer/core/frame/settings_delegate.h
+++ b/chromium/third_party/blink/renderer/core/frame/settings_delegate.h
@@ -33,7 +33,7 @@
#include <memory>
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 a06219c8bd5..3b3fde2717e 100644
--- a/chromium/third_party/blink/renderer/core/frame/smart_clip.cc
+++ b/chromium/third_party/blink/renderer/core/frame/smart_clip.cc
@@ -161,11 +161,10 @@ Node* SmartClip::FindBestOverlappingNode(Node* root_node,
while (node) {
IntRect node_rect = node->PixelSnappedBoundingBox();
-
- if (node->IsElementNode() &&
+ auto* element = DynamicTo<Element>(node);
+ if (element &&
DeprecatedEqualIgnoringCase(
- ToElement(node)->FastGetAttribute(html_names::kAriaHiddenAttr),
- "true")) {
+ element->FastGetAttribute(html_names::kAriaHiddenAttr), "true")) {
node = NodeTraversal::NextSkippingChildren(*node, root_node);
continue;
}
diff --git a/chromium/third_party/blink/renderer/core/frame/use_counter.cc b/chromium/third_party/blink/renderer/core/frame/use_counter_helper.cc
index b25a8123e4e..b93c2e7f6c6 100644
--- a/chromium/third_party/blink/renderer/core/frame/use_counter.cc
+++ b/chromium/third_party/blink/renderer/core/frame/use_counter_helper.cc
@@ -23,7 +23,7 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "third_party/blink/renderer/core/frame/use_counter.h"
+#include "third_party/blink/renderer/core/frame/use_counter_helper.h"
#include "third_party/blink/public/mojom/use_counter/css_property_id.mojom-blink.h"
#include "third_party/blink/renderer/core/css/css_style_sheet.h"
@@ -38,7 +38,7 @@
#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/inspector/console_message.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/weborigin/scheme_registry.h"
@@ -1237,6 +1237,22 @@ int UseCounterHelper::MapCSSPropertyIdToCSSSampleIdForHistogram(
return 636;
case CSSPropertyID::kColorScheme:
return 637;
+ case CSSPropertyID::kOverflowInline:
+ return 638;
+ case CSSPropertyID::kOverflowBlock:
+ return 639;
+ case CSSPropertyID::kForcedColorAdjust:
+ return 640;
+ case CSSPropertyID::kInherits:
+ return 641;
+ case CSSPropertyID::kInitialValue:
+ return 642;
+ case CSSPropertyID::kSyntax:
+ return 643;
+ case CSSPropertyID::kOverscrollBehaviorInline:
+ return 644;
+ case CSSPropertyID::kOverscrollBehaviorBlock:
+ return 645;
// 1. Add new features above this line (don't change the assigned numbers of
// the existing items).
// 2. Update kMaximumCSSSampleId (defined in
@@ -1244,6 +1260,26 @@ int UseCounterHelper::MapCSSPropertyIdToCSSSampleIdForHistogram(
// value.
// 3. Run the update_use_counter_css.py script in
// chromium/src/tools/metrics/histograms to update the UMA histogram names.
+ case CSSPropertyID::kInternalEffectiveZoom:
+ case CSSPropertyID::kInternalVisitedBackgroundColor:
+ case CSSPropertyID::kInternalVisitedBorderBlockEndColor:
+ case CSSPropertyID::kInternalVisitedBorderBlockStartColor:
+ case CSSPropertyID::kInternalVisitedBorderBottomColor:
+ case CSSPropertyID::kInternalVisitedBorderInlineEndColor:
+ case CSSPropertyID::kInternalVisitedBorderInlineStartColor:
+ case CSSPropertyID::kInternalVisitedBorderLeftColor:
+ case CSSPropertyID::kInternalVisitedBorderRightColor:
+ case CSSPropertyID::kInternalVisitedBorderTopColor:
+ case CSSPropertyID::kInternalVisitedCaretColor:
+ case CSSPropertyID::kInternalVisitedColor:
+ case CSSPropertyID::kInternalVisitedColumnRuleColor:
+ case CSSPropertyID::kInternalVisitedFill:
+ case CSSPropertyID::kInternalVisitedOutlineColor:
+ case CSSPropertyID::kInternalVisitedStroke:
+ case CSSPropertyID::kInternalVisitedTextDecorationColor:
+ case CSSPropertyID::kInternalVisitedTextEmphasisColor:
+ case CSSPropertyID::kInternalVisitedTextFillColor:
+ case CSSPropertyID::kInternalVisitedTextStrokeColor:
case CSSPropertyID::kInvalid:
NOTREACHED();
return 0;
diff --git a/chromium/third_party/blink/renderer/core/frame/use_counter.h b/chromium/third_party/blink/renderer/core/frame/use_counter_helper.h
index 4a948b38ef2..12c769b2ecd 100644
--- a/chromium/third_party/blink/renderer/core/frame/use_counter.h
+++ b/chromium/third_party/blink/renderer/core/frame/use_counter_helper.h
@@ -23,8 +23,8 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_USE_COUNTER_H_
-#define THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_USE_COUNTER_H_
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_USE_COUNTER_HELPER_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_USE_COUNTER_HELPER_H_
#include <bitset>
#include "base/macros.h"
@@ -43,7 +43,6 @@ class DocumentLoader;
class Element;
class EnumerationHistogram;
class LocalFrame;
-class StyleSheetContents;
// Utility class for muting UseCounter, for instance ignoring attributes
// constructed in user-agent shadow DOM. Once constructed, all UseCounting
@@ -137,6 +136,8 @@ class CORE_EXPORT UseCounterHelper final {
void Trace(blink::Visitor*);
private:
+ friend class UseCounterHelperTest;
+
// Notifies that a feature is newly counted to |m_observers|. This shouldn't
// be called when the counter is disabled by |m_muteCount| or when |m_context|
// if kDisabledContext.
@@ -173,4 +174,4 @@ class CORE_EXPORT UseCounterHelper final {
} // namespace blink
-#endif // THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_USE_COUNTER_H_
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_USE_COUNTER_HELPER_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_helper_test.cc
index ca4a76ae6d4..dac117093d8 100644
--- a/chromium/third_party/blink/renderer/core/frame/use_counter_test.cc
+++ b/chromium/third_party/blink/renderer/core/frame/use_counter_helper_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/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_property_names.h"
+#include "third_party/blink/renderer/core/css/properties/css_property.h"
#include "third_party/blink/renderer/core/dom/shadow_root.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"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/testing/dummy_page_holder.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.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/url_test_helpers.h"
@@ -40,6 +42,15 @@ class UseCounterHelperTest : public testing::Test {
Page::InsertOrdinaryPageForTesting(&dummy_->GetPage());
}
+ int ToSampleId(CSSPropertyID property) const {
+ return UseCounterHelper::MapCSSPropertyIdToCSSSampleIdForHistogram(
+ property);
+ }
+
+ bool IsInternal(CSSPropertyID property) const {
+ return CSSProperty::Get(property).IsInternal();
+ }
+
protected:
LocalFrame* GetFrame() { return &dummy_->GetFrame(); }
void SetIsViewSource() { dummy_->GetDocument().SetIsViewSource(true); }
@@ -434,4 +445,35 @@ TEST_F(UseCounterHelperTest, CSSSelectorHostContextInSnapshotProfile) {
EXPECT_TRUE(document.IsUseCounted(feature));
}
+TEST_F(UseCounterHelperTest, UniqueCSSSampleIds) {
+ HashSet<int> ids;
+
+ for (CSSPropertyID property : CSSPropertyIDList()) {
+ if (IsInternal(property))
+ continue;
+ EXPECT_FALSE(ids.Contains(ToSampleId(property)));
+ ids.insert(ToSampleId(property));
+ }
+
+ for (CSSPropertyID property : kCSSPropertyAliasList) {
+ EXPECT_FALSE(ids.Contains(ToSampleId(property)));
+ ids.insert(ToSampleId(property));
+ }
+}
+
+TEST_F(UseCounterHelperTest, MaximumCSSSampleId) {
+ int max_sample_id = 0;
+
+ for (CSSPropertyID property : CSSPropertyIDList()) {
+ if (IsInternal(property))
+ continue;
+ max_sample_id = std::max(max_sample_id, ToSampleId(property));
+ }
+
+ for (CSSPropertyID property : kCSSPropertyAliasList)
+ max_sample_id = std::max(max_sample_id, ToSampleId(property));
+
+ EXPECT_EQ(mojom::blink::kMaximumCSSSampleId, max_sample_id);
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/frame/user_activation.idl b/chromium/third_party/blink/renderer/core/frame/user_activation.idl
index f6a9ea05cb0..fc1e3151b04 100644
--- a/chromium/third_party/blink/renderer/core/frame/user_activation.idl
+++ b/chromium/third_party/blink/renderer/core/frame/user_activation.idl
@@ -3,8 +3,10 @@
// found in the LICENSE file.
// https://github.com/dtapuska/useractivation
-[RuntimeEnabled=UserActivationAPI]
-interface UserActivation {
+[
+ RuntimeEnabled=UserActivationAPI,
+ Exposed=(Window,Worker,AudioWorklet)
+] interface UserActivation {
[Measure] readonly attribute boolean hasBeenActive;
[Measure] readonly attribute boolean isActive;
};
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 ab9f8af54b8..84bf2024d4a 100644
--- a/chromium/third_party/blink/renderer/core/frame/visual_viewport.cc
+++ b/chromium/third_party/blink/renderer/core/frame/visual_viewport.cc
@@ -36,6 +36,7 @@
#include "cc/layers/picture_layer.h"
#include "cc/layers/scrollbar_layer_interface.h"
#include "third_party/blink/public/platform/task_type.h"
+#include "third_party/blink/public/platform/web_scroll_into_view_params.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/local_frame_view.h"
@@ -45,9 +46,11 @@
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/fullscreen/fullscreen.h"
#include "third_party/blink/renderer/core/input/event_handler.h"
-#include "third_party/blink/renderer/core/layout/text_autosizer.h"
+#include "third_party/blink/renderer/core/inspector/identifiers_factory.h"
+#include "third_party/blink/renderer/core/layout/layout_box.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/snap_coordinator.h"
#include "third_party/blink/renderer/core/paint/compositing/paint_layer_compositor.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/core/paint/paint_property_tree_builder.h"
@@ -55,6 +58,7 @@
#include "third_party/blink/renderer/core/scroll/scroll_animator_base.h"
#include "third_party/blink/renderer/core/scroll/scrollbar.h"
#include "third_party/blink/renderer/core/scroll/scrollbar_theme_overlay.h"
+#include "third_party/blink/renderer/core/scroll/smooth_scroll_sequencer.h"
#include "third_party/blink/renderer/platform/geometry/double_rect.h"
#include "third_party/blink/renderer/platform/geometry/float_size.h"
#include "third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.h"
@@ -62,8 +66,9 @@
#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/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
+#include "third_party/blink/renderer/platform/instrumentation/tracing/traced_value.h"
namespace blink {
@@ -364,10 +369,12 @@ void VisualViewport::SetSize(const IntSize& size) {
TRACE_EVENT2("blink", "VisualViewport::setSize", "width", size.Width(),
"height", size.Height());
- bool width_did_change = size.Width() != size_.Width();
size_ = size;
needs_paint_property_update_ = true;
+ TRACE_EVENT_INSTANT1("loading", "viewport", TRACE_EVENT_SCOPE_THREAD, "data",
+ ViewportToTracedValue());
+
if (inner_viewport_container_layer_) {
inner_viewport_container_layer_->SetSize(gfx::Size(size_));
inner_viewport_scroll_layer_->CcLayer()->SetScrollable(
@@ -385,18 +392,6 @@ void VisualViewport::SetSize(const IntSize& size) {
return;
EnqueueResizeEvent();
-
- bool autosizer_needs_updating =
- width_did_change && MainFrame()->GetSettings() &&
- MainFrame()->GetSettings()->TextAutosizingEnabled();
-
- if (autosizer_needs_updating) {
- // This needs to happen after setting the m_size member since it'll be read
- // in the update call.
- if (TextAutosizer* text_autosizer =
- MainFrame()->GetDocument()->GetTextAutosizer())
- text_autosizer->UpdatePageInfoInAllFrames();
- }
}
void VisualViewport::Reset() {
@@ -583,7 +578,10 @@ bool VisualViewport::DidSetScaleOrLocation(float scale,
ClampToBoundaries();
needs_paint_property_update_ = true;
-
+ if (notify_page_scale_factor_changed) {
+ TRACE_EVENT_INSTANT1("loading", "viewport", TRACE_EVENT_SCOPE_THREAD,
+ "data", ViewportToTracedValue());
+ }
return true;
}
@@ -802,6 +800,12 @@ ChromeClient* VisualViewport::GetChromeClient() const {
return &GetPage().GetChromeClient();
}
+SmoothScrollSequencer* VisualViewport::GetSmoothScrollSequencer() const {
+ if (!MainFrame())
+ return nullptr;
+ return &MainFrame()->GetSmoothScrollSequencer();
+}
+
void VisualViewport::SetScrollOffset(const ScrollOffset& offset,
ScrollType scroll_type,
ScrollBehavior scroll_behavior,
@@ -819,6 +823,33 @@ void VisualViewport::SetScrollOffset(const ScrollOffset& offset,
scroll_behavior, std::move(on_finish));
}
+PhysicalRect VisualViewport::ScrollIntoView(
+ const PhysicalRect& rect_in_absolute,
+ const WebScrollIntoViewParams& params) {
+ PhysicalRect scroll_snapport_rect = VisibleScrollSnapportRect();
+
+ ScrollOffset new_scroll_offset =
+ ClampScrollOffset(ScrollAlignment::GetScrollOffsetToExpose(
+ scroll_snapport_rect, rect_in_absolute, params.GetScrollAlignmentX(),
+ params.GetScrollAlignmentY(), GetScrollOffset()));
+
+ if (new_scroll_offset != GetScrollOffset()) {
+ ScrollBehavior behavior = params.GetScrollBehavior();
+ if (params.is_for_scroll_sequence) {
+ DCHECK(params.GetScrollType() == kProgrammaticScroll ||
+ params.GetScrollType() == kUserScroll);
+ if (SmoothScrollSequencer* sequencer = GetSmoothScrollSequencer()) {
+ sequencer->QueueAnimation(this, new_scroll_offset, behavior);
+ }
+ } else {
+ SetScrollOffset(new_scroll_offset, params.GetScrollType(), behavior,
+ ScrollCallback());
+ }
+ }
+
+ return rect_in_absolute;
+}
+
int VisualViewport::ScrollSize(ScrollbarOrientation orientation) const {
IntSize scroll_dimensions =
MaximumScrollOffsetInt() - MinimumScrollOffsetInt();
@@ -1201,4 +1232,37 @@ const ScrollableArea* VisualViewport::GetScrollableAreaForTesting(
return nullptr;
}
+std::unique_ptr<TracedValue> VisualViewport::ViewportToTracedValue() const {
+ auto value = std::make_unique<TracedValue>();
+ IntRect viewport = VisibleContentRect();
+ value->SetInteger("x", clampTo<int>(roundf(viewport.X())));
+ value->SetInteger("y", clampTo<int>(roundf(viewport.Y())));
+ value->SetInteger("width", clampTo<int>(roundf(viewport.Width())));
+ value->SetInteger("height", clampTo<int>(roundf(viewport.Height())));
+ value->SetString("frameID",
+ IdentifiersFactory::FrameId(GetPage().MainFrame()));
+ return value;
+}
+
+void VisualViewport::DisposeImpl() {
+ root_transform_layer_.reset();
+ inner_viewport_container_layer_.reset();
+ overscroll_elasticity_layer_.reset();
+ page_scale_layer_.reset();
+ inner_viewport_scroll_layer_.reset();
+ // scrollbar_layer_group_* are referenced from overlay_scrollbar_*, thus
+ // overlay_scrollbar_* must be destroyed before scrollbar_layer_group_*.
+ overlay_scrollbar_horizontal_.reset();
+ overlay_scrollbar_vertical_.reset();
+ scrollbar_layer_group_horizontal_.reset();
+ scrollbar_layer_group_vertical_.reset();
+ device_emulation_transform_node_.reset();
+ overscroll_elasticity_transform_node_.reset();
+ scale_transform_node_.reset();
+ translation_transform_node_.reset();
+ scroll_node_.reset();
+ horizontal_scrollbar_effect_node_.reset();
+ vertical_scrollbar_effect_node_.reset();
+}
+
} // namespace blink
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 3b01de3d858..91a880829d0 100644
--- a/chromium/third_party/blink/renderer/core/frame/visual_viewport.h
+++ b/chromium/third_party/blink/renderer/core/frame/visual_viewport.h
@@ -62,6 +62,7 @@ class Page;
class PaintArtifactCompositor;
class RootFrameViewport;
class ScrollPaintPropertyNode;
+class TracedValue;
class TransformPaintPropertyNode;
struct PaintPropertyTreeBuilderFragmentContext;
@@ -185,10 +186,13 @@ class CORE_EXPORT VisualViewport final
// ScrollableArea implementation
ChromeClient* GetChromeClient() const override;
+ SmoothScrollSequencer* GetSmoothScrollSequencer() const override;
void SetScrollOffset(const ScrollOffset&,
ScrollType,
ScrollBehavior,
ScrollCallback on_finish) override;
+ PhysicalRect ScrollIntoView(const PhysicalRect&,
+ const WebScrollIntoViewParams&) override;
bool IsThrottled() const override {
// VisualViewport is always in the main frame, so the frame does not get
// throttled.
@@ -273,6 +277,8 @@ class CORE_EXPORT VisualViewport final
void SetNeedsPaintPropertyUpdate() { needs_paint_property_update_ = true; }
bool NeedsPaintPropertyUpdate() const { return needs_paint_property_update_; }
+ void DisposeImpl() override;
+
private:
bool DidSetScaleOrLocation(float scale,
bool is_pinch_gesture_active,
@@ -321,6 +327,8 @@ class CORE_EXPORT VisualViewport final
PaintArtifactCompositor* GetPaintArtifactCompositor() const;
CompositorElementId GetCompositorScrollElementId() const;
+ std::unique_ptr<TracedValue> ViewportToTracedValue() const;
+
// Contracts the given size by the thickness of any visible scrollbars. Does
// not contract the size if the scrollbar is overlay.
IntSize ExcludeScrollbars(const IntSize&) const;
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 66f221f9108..ef250539a4c 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
@@ -9,7 +9,7 @@
#include "cc/layers/picture_layer.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-shared.h"
+#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.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_input_event.h"
@@ -17,6 +17,7 @@
#include "third_party/blink/public/platform/web_url_loader_mock_factory.h"
#include "third_party/blink/public/web/web_ax_context.h"
#include "third_party/blink/public/web/web_context_menu_data.h"
+#include "third_party/blink/public/web/web_device_emulation_params.h"
#include "third_party/blink/public/web/web_document.h"
#include "third_party/blink/public/web/web_local_frame_client.h"
#include "third_party/blink/public/web/web_script_source.h"
@@ -1264,8 +1265,13 @@ TEST_P(VisualViewportTest, ScrollIntoViewFractionalOffset) {
kProgrammaticScroll);
inputBox->scrollIntoViewIfNeeded(false);
- EXPECT_EQ(ScrollOffset(0, 900),
- layout_viewport_scrollable_area->GetScrollOffset());
+ if (RuntimeEnabledFeatures::FractionalScrollOffsetsEnabled()) {
+ EXPECT_EQ(ScrollOffset(0, 900.75),
+ layout_viewport_scrollable_area->GetScrollOffset());
+ } else {
+ EXPECT_EQ(ScrollOffset(0, 900),
+ layout_viewport_scrollable_area->GetScrollOffset());
+ }
EXPECT_EQ(FloatSize(250.25f, 100.25f), visual_viewport.GetScrollOffset());
// Change the fractional part of the frameview to one that would round down.
@@ -1273,8 +1279,13 @@ TEST_P(VisualViewportTest, ScrollIntoViewFractionalOffset) {
kProgrammaticScroll);
inputBox->scrollIntoViewIfNeeded(false);
- EXPECT_EQ(ScrollOffset(0, 900),
- layout_viewport_scrollable_area->GetScrollOffset());
+ if (RuntimeEnabledFeatures::FractionalScrollOffsetsEnabled()) {
+ EXPECT_EQ(ScrollOffset(0, 900.125),
+ layout_viewport_scrollable_area->GetScrollOffset());
+ } else {
+ EXPECT_EQ(ScrollOffset(0, 900),
+ layout_viewport_scrollable_area->GetScrollOffset());
+ }
EXPECT_EQ(FloatSize(250.25f, 100.25f), visual_viewport.GetScrollOffset());
// Repeat both tests above with the visual viewport at a high fractional.
@@ -1283,8 +1294,13 @@ TEST_P(VisualViewportTest, ScrollIntoViewFractionalOffset) {
kProgrammaticScroll);
inputBox->scrollIntoViewIfNeeded(false);
- EXPECT_EQ(ScrollOffset(0, 900),
- layout_viewport_scrollable_area->GetScrollOffset());
+ if (RuntimeEnabledFeatures::FractionalScrollOffsetsEnabled()) {
+ EXPECT_EQ(ScrollOffset(0, 900.75),
+ layout_viewport_scrollable_area->GetScrollOffset());
+ } else {
+ EXPECT_EQ(ScrollOffset(0, 900),
+ layout_viewport_scrollable_area->GetScrollOffset());
+ }
EXPECT_EQ(FloatSize(250.875f, 100.875f), visual_viewport.GetScrollOffset());
// Change the fractional part of the frameview to one that would round down.
@@ -1292,8 +1308,13 @@ TEST_P(VisualViewportTest, ScrollIntoViewFractionalOffset) {
kProgrammaticScroll);
inputBox->scrollIntoViewIfNeeded(false);
- EXPECT_EQ(ScrollOffset(0, 900),
- layout_viewport_scrollable_area->GetScrollOffset());
+ if (RuntimeEnabledFeatures::FractionalScrollOffsetsEnabled()) {
+ EXPECT_EQ(ScrollOffset(0, 900.125),
+ layout_viewport_scrollable_area->GetScrollOffset());
+ } else {
+ EXPECT_EQ(ScrollOffset(0, 900),
+ layout_viewport_scrollable_area->GetScrollOffset());
+ }
EXPECT_EQ(FloatSize(250.875f, 100.875f), visual_viewport.GetScrollOffset());
// Both viewports with a 0.5 fraction.
@@ -1302,8 +1323,13 @@ TEST_P(VisualViewportTest, ScrollIntoViewFractionalOffset) {
kProgrammaticScroll);
inputBox->scrollIntoViewIfNeeded(false);
- EXPECT_EQ(ScrollOffset(0, 900),
- layout_viewport_scrollable_area->GetScrollOffset());
+ if (RuntimeEnabledFeatures::FractionalScrollOffsetsEnabled()) {
+ EXPECT_EQ(ScrollOffset(0, 900.5),
+ layout_viewport_scrollable_area->GetScrollOffset());
+ } else {
+ EXPECT_EQ(ScrollOffset(0, 900),
+ layout_viewport_scrollable_area->GetScrollOffset());
+ }
EXPECT_EQ(FloatSize(250.5f, 100.5f), visual_viewport.GetScrollOffset());
}
@@ -1703,14 +1729,14 @@ TEST_P(VisualViewportTest, ResizeVisualViewportStaysWithinOuterViewport) {
NavigateTo("about:blank");
UpdateAllLifecyclePhases();
- WebView()->MainFrameWidget()->ResizeVisualViewport(IntSize(100, 100));
+ WebView()->ResizeVisualViewport(IntSize(100, 100));
VisualViewport& visual_viewport = GetFrame()->GetPage()->GetVisualViewport();
visual_viewport.Move(ScrollOffset(0, 100));
EXPECT_EQ(100, visual_viewport.GetScrollOffset().Height());
- WebView()->MainFrameWidget()->ResizeVisualViewport(IntSize(100, 200));
+ WebView()->ResizeVisualViewport(IntSize(100, 200));
EXPECT_EQ(0, visual_viewport.GetScrollOffset().Height());
}
@@ -2021,8 +2047,7 @@ TEST_P(VisualViewportTest, WindowDimensionsOnLoad) {
Element* output = GetFrame()->GetDocument()->getElementById("output");
DCHECK(output);
- EXPECT_EQ(std::string("1600x1200"),
- std::string(output->InnerHTMLAsString().Ascii().data()));
+ EXPECT_EQ("1600x1200", output->InnerHTMLAsString());
}
// Similar to above but make sure the initial scale is updated with the content
@@ -2037,8 +2062,7 @@ TEST_P(VisualViewportTest, WindowDimensionsOnLoadWideContent) {
Element* output = GetFrame()->GetDocument()->getElementById("output");
DCHECK(output);
- EXPECT_EQ(std::string("2000x1500"),
- std::string(output->InnerHTMLAsString().Ascii().data()));
+ EXPECT_EQ("2000x1500", output->InnerHTMLAsString());
}
TEST_P(VisualViewportTest, ResizeWithScrollAnchoring) {
@@ -2541,21 +2565,26 @@ TEST_F(VisualViewportSimTest, ScrollingContentsSmallerThanContainer) {
TEST_P(VisualViewportTest, DeviceEmulationTransformNode) {
InitializeWithAndroidSettings();
- TransformationMatrix emulation_transform = TransformationMatrix();
- emulation_transform.Translate(314, 159);
- WebView()->SetDeviceEmulationTransform(emulation_transform);
+ WebDeviceEmulationParams params;
+ params.viewport_offset = WebFloatPoint(314, 159);
+ params.viewport_scale = 1.f;
+ WebView()->EnableDeviceEmulation(params);
WebView()->MainFrameWidget()->Resize(IntSize(400, 400));
NavigateTo("about:blank");
UpdateAllLifecyclePhases();
VisualViewport& visual_viewport = GetFrame()->GetPage()->GetVisualViewport();
- EXPECT_EQ(visual_viewport.GetDeviceEmulationTransformNode()->Translation2D(),
- emulation_transform.To2DTranslation());
+
+ TransformationMatrix expected_transform = TransformationMatrix();
+ expected_transform.Translate(-params.viewport_offset.x,
+ -params.viewport_offset.y);
+ EXPECT_EQ(expected_transform.To2DTranslation(),
+ visual_viewport.GetDeviceEmulationTransformNode()->Translation2D());
// Set an identity device emulation transform and ensure the transform
// paint property node is cleared.
- WebView()->SetDeviceEmulationTransform(TransformationMatrix());
+ WebView()->EnableDeviceEmulation(WebDeviceEmulationParams());
UpdateAllLifecyclePhases();
EXPECT_EQ(visual_viewport.GetDeviceEmulationTransformNode(), nullptr);
}
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 37446f7346d..529c941e531 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
@@ -277,12 +277,12 @@ void WebFrameSerializerImpl::EncodeAndFlushBuffer(
String content = data_buffer_.ToString();
data_buffer_.Clear();
- CString encoded_content =
+ std::string encoded_content =
param->text_encoding.Encode(content, WTF::kEntitiesForUnencodables);
// Send result to the client.
client_->DidSerializeDataForFrame(
- WebVector<char>(encoded_content.data(), encoded_content.length()),
+ WebVector<char>(encoded_content.c_str(), encoded_content.length()),
status);
}
@@ -420,13 +420,13 @@ void WebFrameSerializerImpl::BuildContentForNode(Node* node,
switch (node->getNodeType()) {
case Node::kElementNode:
// Process open tag of element.
- OpenTagToString(ToElement(node), param);
+ OpenTagToString(To<Element>(node), param);
// Walk through the children nodes and process it.
for (Node* child = node->firstChild(); child;
child = child->nextSibling())
BuildContentForNode(child, param);
// Process end tag of element.
- EndTagToString(ToElement(node), param);
+ EndTagToString(To<Element>(node), param);
break;
case Node::kTextNode:
SaveHTMLContentToBuffer(CreateMarkup(node), param);
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 9b28d20b959..a5e3a683dbe 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
@@ -77,7 +77,7 @@ 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))));
+ PhysicalOffset(IntPoint(point_in_root_frame))));
HitTestRequest::HitTestRequestType hit_type =
HitTestRequest::kReadOnly | HitTestRequest::kActive |
(ignore_clipping ? HitTestRequest::kIgnoreClipping : 0);
@@ -216,7 +216,7 @@ void WebFrameWidgetBase::DragSourceEndedAt(
WebMouseEvent fake_mouse_move(
WebInputEvent::kMouseMove, point_in_root_frame, screen_point,
WebPointerProperties::Button::kLeft, 0, WebInputEvent::kNoModifiers,
- CurrentTimeTicks());
+ base::TimeTicks::Now());
fake_mouse_move.SetFrameScale(1);
local_root_->GetFrame()->GetEventHandler().DragSourceEndedAt(
fake_mouse_move, static_cast<DragOperation>(operation));
@@ -452,13 +452,19 @@ WebFrameWidgetBase::EnsureCompositorMutatorDispatcher(
return mutator_dispatcher_;
}
-scoped_refptr<PaintWorkletPaintDispatcher>
-WebFrameWidgetBase::EnsureCompositorPaintDispatcher() {
- if (!paint_dispatcher_) {
+base::WeakPtr<PaintWorkletPaintDispatcher>
+WebFrameWidgetBase::EnsureCompositorPaintDispatcher(
+ scoped_refptr<base::SingleThreadTaskRunner>* paint_task_runner) {
+ // We check paint_task_runner_ not paint_dispatcher_ because the dispatcher is
+ // a base::WeakPtr that should only be used on the compositor thread.
+ if (!paint_task_runner_) {
Client()->SetPaintWorkletLayerPainterClient(
PaintWorkletPaintDispatcher::CreateCompositorThreadPainter(
- paint_dispatcher_));
+ &paint_dispatcher_));
+ paint_task_runner_ = Thread::CompositorThread()->GetTaskRunner();
}
+ DCHECK(paint_task_runner_);
+ *paint_task_runner = paint_task_runner_;
return paint_dispatcher_;
}
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 3cfbd1c9621..8365a2f39b7 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
@@ -65,8 +65,11 @@ class CORE_EXPORT WebFrameWidgetBase
EnsureCompositorMutatorDispatcher(
scoped_refptr<base::SingleThreadTaskRunner>* mutator_task_runner);
- // Creates or returns cached paint dispatcher.
- scoped_refptr<PaintWorkletPaintDispatcher> EnsureCompositorPaintDispatcher();
+ // TODO: consider merge the input and return value to be one parameter.
+ // Creates or returns cached paint dispatcher. The returned WeakPtr must only
+ // be dereferenced on the output |paint_task_runner|.
+ base::WeakPtr<PaintWorkletPaintDispatcher> EnsureCompositorPaintDispatcher(
+ scoped_refptr<base::SingleThreadTaskRunner>* paint_task_runner);
// Sets the root graphics layer. |GraphicsLayer| can be null when detaching
// the root layer.
@@ -201,7 +204,13 @@ class CORE_EXPORT WebFrameWidgetBase
base::WeakPtr<AnimationWorkletMutatorDispatcherImpl> mutator_dispatcher_;
scoped_refptr<base::SingleThreadTaskRunner> mutator_task_runner_;
- scoped_refptr<PaintWorkletPaintDispatcher> paint_dispatcher_;
+ // The |paint_dispatcher_| should only be dereferenced on the
+ // |paint_task_runner_| (in practice this is the compositor thread). We keep a
+ // copy of it here to provide to new PaintWorkletProxyClient objects (which
+ // run on the worklet thread) so that they can talk to the
+ // PaintWorkletPaintDispatcher on the compositor thread.
+ base::WeakPtr<PaintWorkletPaintDispatcher> paint_dispatcher_;
+ scoped_refptr<base::SingleThreadTaskRunner> paint_task_runner_;
friend class WebViewImpl;
};
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 28c5d4ebee9..edb297ffcbe 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
@@ -145,7 +145,7 @@ WebFrameWidget* WebFrameWidget::CreateForChildLocalRoot(
WebFrameWidgetImpl::WebFrameWidgetImpl(WebWidgetClient& client)
: WebFrameWidgetBase(client),
- self_keep_alive_(this) {}
+ self_keep_alive_(PERSISTENT_FROM_HERE, this) {}
WebFrameWidgetImpl::~WebFrameWidgetImpl() = default;
@@ -235,23 +235,6 @@ void WebFrameWidgetImpl::Resize(const WebSize& new_size) {
}
}
-void WebFrameWidgetImpl::ResizeVisualViewport(const WebSize& new_size) {
- if (!LocalRootImpl()) {
- // We should figure out why we get here when there is no local root
- // (https://crbug.com/792345).
- return;
- }
-
- // TODO(alexmos, kenrb): resizing behavior such as this should be changed
- // to use Page messages. This uses the visual viewport size to set size on
- // both the WebViewImpl size and the Page's VisualViewport. If there are
- // multiple OOPIFs on a page, this will currently be set redundantly by
- // each of them. See https://crbug.com/599688.
- View()->MainFrameWidget()->Resize(new_size);
-
- View()->DidUpdateFullscreenSize();
-}
-
void WebFrameWidgetImpl::UpdateMainFrameLayoutSize() {
if (!LocalRootImpl())
return;
@@ -309,7 +292,7 @@ void WebFrameWidgetImpl::DidBeginFrame() {
void WebFrameWidgetImpl::BeginRafAlignedInput() {
if (LocalRootImpl()) {
- raf_aligned_input_start_time_.emplace(CurrentTimeTicks());
+ raf_aligned_input_start_time_.emplace(base::TimeTicks::Now());
}
}
@@ -318,14 +301,14 @@ void WebFrameWidgetImpl::EndRafAlignedInput() {
DCHECK(raf_aligned_input_start_time_);
LocalRootImpl()->GetFrame()->View()->EnsureUkmAggregator().RecordSample(
LocalFrameUkmAggregator::kHandleInputEvents,
- raf_aligned_input_start_time_.value(), CurrentTimeTicks());
+ raf_aligned_input_start_time_.value(), base::TimeTicks::Now());
}
raf_aligned_input_start_time_.reset();
}
void WebFrameWidgetImpl::BeginUpdateLayers() {
if (LocalRootImpl())
- update_layers_start_time_.emplace(CurrentTimeTicks());
+ update_layers_start_time_.emplace(base::TimeTicks::Now());
}
void WebFrameWidgetImpl::EndUpdateLayers() {
@@ -333,14 +316,14 @@ void WebFrameWidgetImpl::EndUpdateLayers() {
DCHECK(update_layers_start_time_);
LocalRootImpl()->GetFrame()->View()->EnsureUkmAggregator().RecordSample(
LocalFrameUkmAggregator::kUpdateLayers,
- update_layers_start_time_.value(), CurrentTimeTicks());
+ update_layers_start_time_.value(), base::TimeTicks::Now());
}
update_layers_start_time_.reset();
}
void WebFrameWidgetImpl::BeginCommitCompositorFrame() {
if (LocalRootImpl()) {
- commit_compositor_frame_start_time_.emplace(CurrentTimeTicks());
+ commit_compositor_frame_start_time_.emplace(base::TimeTicks::Now());
}
}
@@ -350,7 +333,7 @@ void WebFrameWidgetImpl::EndCommitCompositorFrame() {
// timing data.
LocalRootImpl()->GetFrame()->View()->EnsureUkmAggregator().RecordSample(
LocalFrameUkmAggregator::kProxyCommit,
- commit_compositor_frame_start_time_.value(), CurrentTimeTicks());
+ commit_compositor_frame_start_time_.value(), base::TimeTicks::Now());
}
commit_compositor_frame_start_time_.reset();
}
@@ -371,7 +354,7 @@ void WebFrameWidgetImpl::RecordEndOfFrameMetrics(
->GetFrame()
->View()
->EnsureUkmAggregator()
- .RecordEndOfFrameMetrics(frame_begin_time, CurrentTimeTicks());
+ .RecordEndOfFrameMetrics(frame_begin_time, base::TimeTicks::Now());
}
void WebFrameWidgetImpl::UpdateLifecycle(LifecycleUpdate requested_update,
@@ -525,6 +508,8 @@ void WebFrameWidgetImpl::OnFallbackCursorModeToggled(bool is_on) {
NOTREACHED();
}
+void WebFrameWidgetImpl::DidDetachLocalFrameTree() {}
+
WebInputMethodController*
WebFrameWidgetImpl::GetActiveWebInputMethodController() const {
WebLocalFrameImpl* local_frame =
@@ -540,7 +525,7 @@ bool WebFrameWidgetImpl::ScrollFocusedEditableElementIntoView() {
if (!element->GetLayoutObject())
return false;
- LayoutRect rect_to_scroll;
+ PhysicalRect rect_to_scroll;
WebScrollIntoViewParams params;
GetScrollParamsForFocusedEditableElement(*element, rect_to_scroll, params);
element->GetLayoutObject()->ScrollRectToVisible(rect_to_scroll, params);
@@ -696,7 +681,8 @@ void WebFrameWidgetImpl::HandleMouseDown(LocalFrame& main_frame,
// Take capture on a mouse down on a plugin so we can send it mouse events.
// If the hit node is a plugin but a scrollbar is over it don't start mouse
// capture because it will interfere with the scrollbar receiving events.
- LayoutPoint point(event.PositionInWidget().x, event.PositionInWidget().y);
+ PhysicalOffset point(LayoutUnit(event.PositionInWidget().x),
+ LayoutUnit(event.PositionInWidget().y));
if (event.button == WebMouseEvent::Button::kLeft) {
HitTestLocation location(
LocalRootImpl()->GetFrameView()->ConvertFromRootFrame(point));
@@ -752,7 +738,8 @@ void WebFrameWidgetImpl::MouseContextMenu(const WebMouseEvent& event) {
FlooredIntPoint(transformed_event.PositionInRootFrame());
// Find the right target frame. See issue 1186900.
- HitTestResult result = HitTestResultForRootFramePos(position_in_root_frame);
+ HitTestResult result =
+ HitTestResultForRootFramePos(PhysicalOffset(position_in_root_frame));
Frame* target_frame;
if (result.InnerNodeOrImageMapImage())
target_frame = result.InnerNodeOrImageMapImage()->GetDocument().GetFrame();
@@ -997,19 +984,6 @@ void WebFrameWidgetImpl::SetLayerTreeView(WebLayerTreeView* layer_tree_view,
LocalRootImpl()->GetFrame()->View());
}
-void WebFrameWidgetImpl::SetIsAcceleratedCompositingActive(bool active) {
- if (!active)
- return;
- if (is_accelerated_compositing_active_)
- return;
- DCHECK(layer_tree_view_);
-
- TRACE_EVENT0("blink",
- "WebFrameWidgetImpl::SetIsAcceleratedCompositingActive(true)");
- Client()->SetRootLayer(root_layer_);
- is_accelerated_compositing_active_ = true;
-}
-
PaintLayerCompositor* WebFrameWidgetImpl::Compositor() const {
LocalFrame* frame = LocalRootImpl()->GetFrame();
if (!frame || !frame->GetDocument() || !frame->GetDocument()->GetLayoutView())
@@ -1024,13 +998,13 @@ void WebFrameWidgetImpl::SetRootGraphicsLayer(GraphicsLayer* layer) {
}
void WebFrameWidgetImpl::SetRootLayer(scoped_refptr<cc::Layer> layer) {
- root_layer_ = layer;
+ root_layer_ = std::move(layer);
- SetIsAcceleratedCompositingActive(!!layer);
-
- // TODO(danakj): Is this called after Close?? (With a null layer?)
- if (!layer_tree_view_)
+ if (!root_layer_) {
+ // This notifies the WebFrameWidgetImpl that its LocalFrame tree is being
+ // detached.
return;
+ }
// WebFrameWidgetImpl is used for child frames, which always have a
// transparent background color.
@@ -1067,8 +1041,8 @@ HitTestResult WebFrameWidgetImpl::CoreHitTestResultAt(
DocumentLifecycle::AllowThrottlingScope throttling_scope(
LocalRootImpl()->GetFrame()->GetDocument()->Lifecycle());
LocalFrameView* view = LocalRootImpl()->GetFrameView();
- IntPoint point_in_root_frame =
- view->ViewportToFrame(IntPoint(point_in_viewport));
+ PhysicalOffset point_in_root_frame(
+ view->ViewportToFrame(IntPoint(point_in_viewport)));
return HitTestResultForRootFramePos(point_in_root_frame);
}
@@ -1078,10 +1052,10 @@ void WebFrameWidgetImpl::ZoomToFindInPageRect(
}
HitTestResult WebFrameWidgetImpl::HitTestResultForRootFramePos(
- const LayoutPoint& pos_in_root_frame) {
- LayoutPoint doc_point(
+ const PhysicalOffset& pos_in_root_frame) {
+ PhysicalOffset doc_point =
LocalRootImpl()->GetFrame()->View()->ConvertFromRootFrame(
- pos_in_root_frame));
+ pos_in_root_frame);
HitTestLocation location(doc_point);
HitTestResult result =
LocalRootImpl()->GetFrame()->GetEventHandler().HitTestResultAtLocation(
@@ -1108,7 +1082,7 @@ void WebFrameWidgetImpl::DidCreateLocalRootView() {
void WebFrameWidgetImpl::GetScrollParamsForFocusedEditableElement(
const Element& element,
- LayoutRect& rect_to_scroll,
+ PhysicalRect& rect_to_scroll,
WebScrollIntoViewParams& params) {
LocalFrameView& frame_view = *element.GetDocument().View();
IntRect absolute_element_bounds =
@@ -1151,7 +1125,7 @@ void WebFrameWidgetImpl::GetScrollParamsForFocusedEditableElement(
params.relative_caret_bounds = NormalizeRect(
Intersection(absolute_caret_bounds, maximal_rect), maximal_rect);
params.behavior = WebScrollIntoViewParams::kInstant;
- rect_to_scroll = LayoutRect(maximal_rect);
+ rect_to_scroll = PhysicalRect(maximal_rect);
}
} // namespace blink
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 9961a1b0a8c..1d3f32a49d2 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
@@ -76,7 +76,6 @@ class WebFrameWidgetImpl final : public WebFrameWidgetBase,
void Close() override;
WebSize Size() override;
void Resize(const WebSize&) override;
- void ResizeVisualViewport(const WebSize&) override;
void DidEnterFullscreen() override;
void DidExitFullscreen() override;
void SetSuppressFrameRequestsWorkaroundFor704763Only(bool) final;
@@ -114,6 +113,7 @@ class WebFrameWidgetImpl final : public WebFrameWidgetBase,
WebURL GetURLForDebugTrace() override;
// WebFrameWidget implementation.
+ void DidDetachLocalFrameTree() override;
WebInputMethodController* GetActiveWebInputMethodController() const override;
bool ScrollFocusedEditableElementIntoView() override;
@@ -153,9 +153,8 @@ class WebFrameWidgetImpl final : public WebFrameWidgetBase,
// Perform a hit test for a point relative to the root frame of the page.
HitTestResult HitTestResultForRootFramePos(
- const LayoutPoint& pos_in_root_frame);
+ const PhysicalOffset& pos_in_root_frame);
- void SetIsAcceleratedCompositingActive(bool);
void UpdateLayerTreeViewport();
// PageWidgetEventHandler functions
@@ -178,7 +177,7 @@ class WebFrameWidgetImpl final : public WebFrameWidgetBase,
// includes the caret and is with respect to absolute coordinates.
void GetScrollParamsForFocusedEditableElement(
const Element& element,
- LayoutRect& rect_to_scroll,
+ PhysicalRect& rect_to_scroll,
WebScrollIntoViewParams& params);
base::Optional<WebSize> size_;
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 290973c5aea..0a14f7769bd 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
@@ -114,7 +114,7 @@
#include "third_party/blink/public/web/web_console_message.h"
#include "third_party/blink/public/web/web_content_capture_client.h"
#include "third_party/blink/public/web/web_document.h"
-#include "third_party/blink/public/web/web_dom_event.h"
+#include "third_party/blink/public/web/web_dom_message_event.h"
#include "third_party/blink/public/web/web_form_element.h"
#include "third_party/blink/public/web/web_frame_owner_properties.h"
#include "third_party/blink/public/web/web_history_item.h"
@@ -173,7 +173,6 @@
#include "third_party/blink/renderer/core/events/before_print_event.h"
#include "third_party/blink/renderer/core/events/portal_activate_event.h"
#include "third_party/blink/renderer/core/exported/local_frame_client_impl.h"
-#include "third_party/blink/renderer/core/exported/web_associated_url_loader_impl.h"
#include "third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.h"
#include "third_party/blink/renderer/core/exported/web_document_loader_impl.h"
#include "third_party/blink/renderer/core/exported/web_plugin_container_impl.h"
@@ -193,7 +192,6 @@
#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/frame/smart_clip.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/frame/visual_viewport.h"
#include "third_party/blink/renderer/core/frame/web_frame_widget_base.h"
#include "third_party/blink/renderer/core/html/forms/html_form_control_element.h"
@@ -228,6 +226,7 @@
#include "third_party/blink/renderer/core/loader/frame_loader.h"
#include "third_party/blink/renderer/core/loader/history_item.h"
#include "third_party/blink/renderer/core/loader/mixed_content_checker.h"
+#include "third_party/blink/renderer/core/loader/web_associated_url_loader_impl.h"
#include "third_party/blink/renderer/core/messaging/message_port.h"
#include "third_party/blink/renderer/core/page/context_menu_controller.h"
#include "third_party/blink/renderer/core/page/focus_controller.h"
@@ -255,6 +254,7 @@
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.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"
@@ -951,10 +951,12 @@ void WebLocalFrameImpl::SetReferrerForRequest(WebURLRequest& request,
String referrer = referrer_url.IsEmpty()
? GetFrame()->GetDocument()->OutgoingReferrer()
: String(referrer_url.GetString());
- request.ToMutableResourceRequest().SetHttpReferrer(
- SecurityPolicy::GenerateReferrer(
- GetFrame()->GetDocument()->GetReferrerPolicy(), request.Url(),
- referrer));
+ ResourceRequest& resource_request = request.ToMutableResourceRequest();
+ resource_request.SetReferrerPolicy(
+ GetFrame()->GetDocument()->GetReferrerPolicy(),
+ ResourceRequest::SetReferrerPolicyLocation::kWebLocalFrameImpl);
+ resource_request.SetReferrerString(
+ referrer, ResourceRequest::SetReferrerStringLocation::kWebLocalFrameImpl);
}
WebAssociatedURLLoader* WebLocalFrameImpl::CreateAssociatedURLLoader(
@@ -1430,6 +1432,7 @@ void WebLocalFrameImpl::DispatchBeforePrintEvent() {
is_in_printing_ = true;
#endif
+ GetFrame()->GetDocument()->SetPrinting(Document::kBeforePrinting);
DispatchPrintEventRecursively(event_type_names::kBeforeprint);
}
@@ -1555,7 +1558,7 @@ void WebLocalFrameImpl::PageSizeAndMarginsInPixels(int page_index,
WebString WebLocalFrameImpl::PageProperty(const WebString& property_name,
int page_index) {
DCHECK(print_context_);
- return print_context_->PageProperty(GetFrame(), property_name.Utf8().data(),
+ return print_context_->PageProperty(GetFrame(), property_name.Utf8().c_str(),
page_index);
}
@@ -1627,12 +1630,10 @@ WebLocalFrameImpl* WebLocalFrameImpl::CreateMainFrame(
frame->SetOpener(opener);
Page& page = *static_cast<WebViewImpl*>(web_view)->GetPage();
DCHECK(!page.MainFrame());
- frame->InitializeCoreFrame(page, nullptr, name);
- if (RuntimeEnabledFeatures::FeaturePolicyForSandboxEnabled())
- frame->GetFrame()->SetOpenerFeatureState(opener_feature_state);
- // Can't force sandbox flags until there's a core frame.
- frame->GetFrame()->Loader().ForceSandboxFlags(
- static_cast<SandboxFlags>(sandbox_flags));
+ frame->InitializeCoreFrame(
+ page, nullptr, name,
+ opener ? &ToCoreFrame(*opener)->window_agent_factory() : nullptr,
+ sandbox_flags, opener_feature_state);
return frame;
}
@@ -1650,6 +1651,17 @@ WebLocalFrameImpl* WebLocalFrameImpl::CreateProvisional(
Frame* previous_frame = ToCoreFrame(*previous_web_frame);
web_frame->SetParent(previous_web_frame->Parent());
web_frame->SetOpener(previous_web_frame->Opener());
+ WebSandboxFlags sandbox_flags = WebSandboxFlags::kNone;
+ FeaturePolicy::FeatureState feature_state;
+ if (!previous_frame->Owner()) {
+ // Provisional main frames need to force sandbox flags. This is necessary
+ // to inherit sandbox flags when a sandboxed frame does a window.open()
+ // which triggers a cross-process navigation.
+ sandbox_flags = frame_policy.sandbox_flags;
+ // If there is an opener (even disowned), the opener policies must be
+ // inherited the same way as sandbox flag.
+ feature_state = previous_frame->OpenerFeatureState();
+ }
// Note: this *always* temporarily sets a frame owner, even for main frames!
// When a core Frame is created with no owner, it attempts to set itself as
// the main frame of the Page. However, this is a provisional frame, and may
@@ -1661,23 +1673,17 @@ WebLocalFrameImpl* WebLocalFrameImpl::CreateProvisional(
// unscriptable. Once the provisional frame gets properly attached and is
// observable, it will have the real FrameOwner, and any subsequent real
// documents will correctly inherit sandbox flags from the owner.
- web_frame->InitializeCoreFrame(*previous_frame->GetPage(),
- MakeGarbageCollected<DummyFrameOwner>(),
- previous_frame->Tree().GetName());
+ web_frame->InitializeCoreFrame(
+ *previous_frame->GetPage(), MakeGarbageCollected<DummyFrameOwner>(),
+ previous_frame->Tree().GetName(),
+ &ToCoreFrame(*previous_web_frame)->window_agent_factory(), sandbox_flags,
+ feature_state);
LocalFrame* new_frame = web_frame->GetFrame();
new_frame->SetOwner(previous_frame->Owner());
if (auto* remote_frame_owner =
DynamicTo<RemoteFrameOwner>(new_frame->Owner())) {
remote_frame_owner->SetFramePolicy(frame_policy);
- } else if (!new_frame->Owner()) {
- // Provisional main frames need to force sandbox flags. This is necessary
- // to inherit sandbox flags when a sandboxed frame does a window.open()
- // which triggers a cross-process navigation.
- new_frame->Loader().ForceSandboxFlags(frame_policy.sandbox_flags);
- // If there is an opener (even disowned), the opener policies must be
- // inherited the same way as sandbox flag.
- new_frame->SetOpenerFeatureState(previous_frame->OpenerFeatureState());
}
return web_frame;
@@ -1711,7 +1717,7 @@ WebLocalFrameImpl::WebLocalFrameImpl(
interface_registry_(interface_registry),
input_method_controller_(*this),
spell_check_panel_host_client_(nullptr),
- self_keep_alive_(this) {
+ self_keep_alive_(PERSISTENT_FROM_HERE, this) {
DCHECK(client_);
g_frame_count++;
client_->BindToFrame(this);
@@ -1738,12 +1744,21 @@ void WebLocalFrameImpl::SetCoreFrame(LocalFrame* frame) {
frame_ = frame;
}
-void WebLocalFrameImpl::InitializeCoreFrame(Page& page,
- FrameOwner* owner,
- const AtomicString& name) {
+void WebLocalFrameImpl::InitializeCoreFrame(
+ Page& page,
+ FrameOwner* owner,
+ const AtomicString& name,
+ WindowAgentFactory* window_agent_factory,
+ WebSandboxFlags sandbox_flags,
+ const FeaturePolicy::FeatureState& opener_feature_state) {
SetCoreFrame(MakeGarbageCollected<LocalFrame>(local_frame_client_.Get(), page,
- owner, interface_registry_));
+ owner, window_agent_factory,
+ interface_registry_));
frame_->Tree().SetName(name);
+ if (RuntimeEnabledFeatures::FeaturePolicyForSandboxEnabled())
+ frame_->SetOpenerFeatureState(opener_feature_state);
+ frame_->Loader().ForceSandboxFlags(sandbox_flags);
+
// We must call init() after frame_ is assigned because it is referenced
// during init().
frame_->Init();
@@ -1791,7 +1806,8 @@ LocalFrame* WebLocalFrameImpl::CreateChildFrame(
return nullptr;
webframe_child->InitializeCoreFrame(*GetFrame()->GetPage(), owner_element,
- name);
+ name,
+ &GetFrame()->window_agent_factory());
DCHECK(webframe_child->Parent());
return webframe_child->GetFrame();
@@ -1799,21 +1815,18 @@ LocalFrame* WebLocalFrameImpl::CreateChildFrame(
std::pair<RemoteFrame*, base::UnguessableToken> WebLocalFrameImpl::CreatePortal(
HTMLPortalElement* portal,
- mojom::blink::PortalAssociatedRequest request,
- mojom::blink::PortalClientAssociatedPtrInfo client) {
- auto pair = client_->CreatePortal(request.PassHandle(), client.PassHandle());
- WebRemoteFrameImpl* portal_frame = ToWebRemoteFrameImpl(pair.first);
- portal_frame->InitializeCoreFrame(*GetFrame()->GetPage(), portal,
- g_null_atom);
- return std::pair<RemoteFrame*, base::UnguessableToken>(
- portal_frame->GetFrame(), pair.second);
+ mojo::PendingAssociatedReceiver<mojom::blink::Portal> portal_receiver,
+ mojo::PendingAssociatedRemote<mojom::blink::PortalClient> portal_client) {
+ WebRemoteFrame* portal_frame;
+ base::UnguessableToken portal_token;
+ std::tie(portal_frame, portal_token) = client_->CreatePortal(
+ portal_receiver.PassHandle(), portal_client.PassHandle(), portal);
+ return {ToWebRemoteFrameImpl(portal_frame)->GetFrame(), portal_token};
}
RemoteFrame* WebLocalFrameImpl::AdoptPortal(HTMLPortalElement* portal) {
WebRemoteFrameImpl* portal_frame =
- ToWebRemoteFrameImpl(client_->AdoptPortal(portal->GetToken()));
- portal_frame->InitializeCoreFrame(*GetFrame()->GetPage(), portal,
- g_null_atom);
+ ToWebRemoteFrameImpl(client_->AdoptPortal(portal->GetToken(), portal));
return portal_frame->GetFrame();
}
@@ -2023,8 +2036,8 @@ void WebLocalFrameImpl::CommitNavigation(
DCHECK(!navigation_params->url.ProtocolIs("javascript"));
if (GetTextFinder())
GetTextFinder()->ClearActiveFindMatch();
- GetFrame()->Loader().CommitNavigation(
- std::move(navigation_params), std::move(extra_data));
+ GetFrame()->Loader().CommitNavigation(std::move(navigation_params),
+ std::move(extra_data));
}
blink::mojom::CommitResult WebLocalFrameImpl::CommitSameDocumentNavigation(
@@ -2148,13 +2161,17 @@ void WebLocalFrameImpl::NotifyUserActivation() {
LocalFrame::NotifyUserActivation(GetFrame(), UserGestureToken::kNewGesture);
}
-void WebLocalFrameImpl::BlinkFeatureUsageReport(const std::set<int>& features) {
+void WebLocalFrameImpl::BlinkFeatureUsageReport(
+ const std::set<blink::mojom::WebFeature>& features) {
DCHECK(!features.empty());
// Assimilate all features used/performed by the browser into UseCounter.
- for (int feature : features) {
- UseCounter::Count(GetFrame()->GetDocument(),
- static_cast<WebFeature>(feature));
- }
+ for (const auto& feature : features)
+ UseCounter::Count(GetFrame()->GetDocument(), feature);
+}
+
+void WebLocalFrameImpl::BlinkFeatureUsageReport(
+ blink::mojom::WebFeature feature) {
+ UseCounter::Count(GetFrame()->GetDocument(), feature);
}
void WebLocalFrameImpl::MixedContentFound(
@@ -2223,7 +2240,7 @@ void WebLocalFrameImpl::DidCallIsSearchProviderInstalled() {
void WebLocalFrameImpl::DispatchMessageEventWithOriginCheck(
const WebSecurityOrigin& intended_target_origin,
- const WebDOMEvent& event,
+ const WebDOMMessageEvent& event,
bool has_user_gesture) {
DCHECK(!event.IsNull());
@@ -2237,15 +2254,27 @@ void WebLocalFrameImpl::DispatchMessageEventWithOriginCheck(
UserGestureIndicator::SetWasForwardedCrossProcess();
}
- // Transfer user activation state in the target's renderer when
- // |transferUserActivation| is true.
MessageEvent* msg_event = static_cast<MessageEvent*>((Event*)event);
Frame* source_frame = nullptr;
if (msg_event->source() && msg_event->source()->ToDOMWindow())
source_frame = msg_event->source()->ToDOMWindow()->GetFrame();
- if (RuntimeEnabledFeatures::UserActivationPostMessageTransferEnabled() &&
- msg_event->transferUserActivation()) {
+
+ // Transfer user activation state in the target's renderer when
+ // |transferUserActivation| is true.
+ //
+ // Also do the same as an ad-hoc solution to allow the origin trial of dynamic
+ // delegation of autoplay capability through postMessages. Note that we
+ // skipped updating the user activation states in all other copies of the
+ // frame tree in this case because this is a temporary hack.
+ //
+ // TODO(mustaq): Remove the ad-hoc solution when the API shape is
+ // ready. crbug.com/985914
+ if ((RuntimeEnabledFeatures::UserActivationPostMessageTransferEnabled() &&
+ msg_event->transferUserActivation()) ||
+ msg_event->allowAutoplay()) {
GetFrame()->TransferUserActivationFrom(source_frame);
+ if (msg_event->allowAutoplay())
+ UseCounter::Count(GetDocument(), WebFeature::kAutoplayDynamicDelegation);
}
GetFrame()->DomWindow()->DispatchMessageEventWithOriginCheck(
@@ -2258,6 +2287,9 @@ WebNode WebLocalFrameImpl::ContextMenuNode() const {
}
void WebLocalFrameImpl::WillBeDetached() {
+ // The |frame_widget_| can be null for frames in non-composited WebViews.
+ if (IsLocalRoot() && frame_widget_)
+ frame_widget_->DidDetachLocalFrameTree();
if (dev_tools_agent_)
dev_tools_agent_->WillBeDestroyed();
if (find_in_page_)
@@ -2311,7 +2343,7 @@ void WebLocalFrameImpl::SaveImageAt(const WebPoint& pos_in_viewport) {
if (!node || !(IsHTMLCanvasElement(*node) || IsHTMLImageElement(*node)))
return;
- String url = ToElement(*node).ImageSourceURL();
+ String url = To<Element>(*node).ImageSourceURL();
if (!KURL(NullURL(), url).ProtocolIsData())
return;
@@ -2473,15 +2505,15 @@ void WebLocalFrameImpl::AdvanceFocusInForm(WebFocusType focus_type) {
next_element->focus();
}
-bool WebLocalFrameImpl::CanFocusedFieldBeAutofilled() const {
+bool WebLocalFrameImpl::TryToShowTouchToFillForFocusedElement() {
+ if (!autofill_client_)
+ return false;
+
DCHECK(GetFrame()->GetDocument());
auto* focused_form_control_element = ToHTMLFormControlElementOrNull(
GetFrame()->GetDocument()->FocusedElement());
-
- if (!focused_form_control_element)
- return false;
-
- return autofill_client_->HasFillData(focused_form_control_element);
+ return focused_form_control_element &&
+ autofill_client_->TryToShowTouchToFill(focused_form_control_element);
}
void WebLocalFrameImpl::PerformMediaPlayerAction(
@@ -2521,6 +2553,7 @@ void WebLocalFrameImpl::PerformMediaPlayerAction(
PictureInPictureController::From(node->GetDocument())
.ExitPictureInPicture(ToHTMLVideoElement(media_element), nullptr);
}
+
break;
}
}
@@ -2545,9 +2578,9 @@ void WebLocalFrameImpl::OnPortalActivated(
PortalActivateEvent* event = PortalActivateEvent::Create(
frame_.Get(), portal_token,
- mojom::blink::PortalAssociatedPtr(mojom::blink::PortalAssociatedPtrInfo(
- std::move(portal_pipe), mojom::blink::Portal::Version_)),
- mojom::blink::PortalClientAssociatedRequest(
+ mojo::PendingAssociatedRemote<mojom::blink::Portal>(
+ std::move(portal_pipe), mojom::blink::Portal::Version_),
+ mojo::PendingAssociatedReceiver<mojom::blink::PortalClient>(
std::move(portal_client_pipe)),
std::move(blink_data.message), ports, std::move(callback));
@@ -2558,6 +2591,17 @@ void WebLocalFrameImpl::OnPortalActivated(
if (debugger)
debugger->ExternalAsyncTaskFinished(blink_data.sender_stack_trace_id);
event->DetachPortalIfNotAdopted();
+
+ // After dispatching the portalactivate event, we check to see if we need to
+ // cleanup the portal hosting the predecessor. If the portal was created,
+ // but wasn't inserted or activated, we destroy it.
+ HTMLPortalElement* portal_element =
+ DocumentPortals::From(*(GetFrame()->GetDocument()))
+ .GetPortal(portal_token);
+ if (portal_element && !portal_element->isConnected() &&
+ !portal_element->IsActivating()) {
+ portal_element->ConsumePortal();
+ }
}
void WebLocalFrameImpl::ForwardMessageFromHost(
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 96a8b2d9375..df0c843043e 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
@@ -35,6 +35,8 @@
#include <set>
#include "base/single_thread_task_runner.h"
+#include "mojo/public/cpp/bindings/pending_associated_receiver.h"
+#include "mojo/public/cpp/bindings/pending_associated_remote.h"
#include "third_party/blink/public/mojom/ad_tagging/ad_frame.mojom-blink.h"
#include "third_party/blink/public/mojom/devtools/devtools_agent.mojom-blink.h"
#include "third_party/blink/public/mojom/frame/find_in_page.mojom-blink.h"
@@ -80,6 +82,7 @@ class WebViewImpl;
enum class WebFrameLoadType;
struct WebContentSecurityPolicyViolation;
struct WebPrintParams;
+class WindowAgentFactory;
template <typename T>
class WebVector;
@@ -233,7 +236,7 @@ class CORE_EXPORT WebLocalFrameImpl final
void DispatchMessageEventWithOriginCheck(
const WebSecurityOrigin& intended_target_origin,
- const WebDOMEvent&,
+ const WebDOMMessageEvent&,
bool has_user_gesture) override;
WebRect GetSelectionBoundsRectForTesting() const override;
@@ -265,7 +268,9 @@ class CORE_EXPORT WebLocalFrameImpl final
bool IsLoading() const override;
bool IsNavigationScheduledWithin(double interval) const override;
void NotifyUserActivation() override;
- void BlinkFeatureUsageReport(const std::set<int>& features) override;
+ void BlinkFeatureUsageReport(
+ const std::set<blink::mojom::WebFeature>& features) override;
+ void BlinkFeatureUsageReport(blink::mojom::WebFeature feature) override;
void MixedContentFound(const WebURL& main_resource_url,
const WebURL& mixed_content_url,
mojom::RequestContextType,
@@ -299,7 +304,7 @@ class CORE_EXPORT WebLocalFrameImpl final
WebString& clip_html,
WebRect& clip_rect) override;
void AdvanceFocusInForm(WebFocusType) override;
- bool CanFocusedFieldBeAutofilled() const override;
+ bool TryToShowTouchToFillForFocusedElement() override;
void PerformMediaPlayerAction(const WebPoint&,
const WebMediaPlayerAction&) override;
void OnPortalActivated(const base::UnguessableToken& portal_token,
@@ -342,7 +347,14 @@ class CORE_EXPORT WebLocalFrameImpl final
void WasHidden() override;
void WasShown() override;
- void InitializeCoreFrame(Page&, FrameOwner*, const AtomicString& name);
+ void InitializeCoreFrame(
+ Page&,
+ FrameOwner*,
+ const AtomicString& name,
+ WindowAgentFactory*,
+ WebSandboxFlags sandbox_flags = WebSandboxFlags::kNone,
+ const FeaturePolicy::FeatureState& opener_feature_state =
+ FeaturePolicy::FeatureState());
LocalFrame* GetFrame() const { return frame_.Get(); }
void WillBeDetached();
@@ -372,8 +384,8 @@ class CORE_EXPORT WebLocalFrameImpl final
HTMLFrameOwnerElement*);
std::pair<RemoteFrame*, base::UnguessableToken> CreatePortal(
HTMLPortalElement*,
- mojom::blink::PortalAssociatedRequest,
- mojom::blink::PortalClientAssociatedPtrInfo);
+ mojo::PendingAssociatedReceiver<mojom::blink::Portal>,
+ mojo::PendingAssociatedRemote<mojom::blink::PortalClient>);
RemoteFrame* AdoptPortal(HTMLPortalElement*);
void DidChangeContentsSize(const IntSize&);
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 62a4bcf60e5..1c38e3ce342 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
@@ -11,8 +11,9 @@ namespace blink {
WebViewFrameWidget::WebViewFrameWidget(WebWidgetClient& client,
WebViewImpl& web_view)
- : WebFrameWidgetBase(client), web_view_(&web_view), self_keep_alive_(this) {
-}
+ : WebFrameWidgetBase(client),
+ web_view_(&web_view),
+ self_keep_alive_(PERSISTENT_FROM_HERE, this) {}
WebViewFrameWidget::~WebViewFrameWidget() = default;
@@ -35,10 +36,6 @@ void WebViewFrameWidget::Resize(const WebSize& size) {
web_view_->Resize(size);
}
-void WebViewFrameWidget::ResizeVisualViewport(const WebSize& size) {
- web_view_->ResizeVisualViewport(size);
-}
-
void WebViewFrameWidget::DidEnterFullscreen() {
web_view_->DidEnterFullscreen();
}
@@ -125,11 +122,9 @@ void WebViewFrameWidget::ApplyViewportChanges(
web_view_->ApplyViewportChanges(args);
}
-void WebViewFrameWidget::RecordWheelAndTouchScrollingCount(
- bool has_scrolled_by_wheel,
- bool has_scrolled_by_touch) {
- web_view_->RecordWheelAndTouchScrollingCount(has_scrolled_by_wheel,
- has_scrolled_by_touch);
+void WebViewFrameWidget::RecordManipulationTypeCounts(
+ cc::ManipulationInfo info) {
+ web_view_->RecordManipulationTypeCounts(info);
}
void WebViewFrameWidget::SendOverscrollEventFromImplSide(
const gfx::Vector2dF& overscroll_delta,
@@ -163,6 +158,10 @@ WebURL WebViewFrameWidget::GetURLForDebugTrace() {
return web_view_->GetURLForDebugTrace();
}
+void WebViewFrameWidget::DidDetachLocalFrameTree() {
+ web_view_->DidDetachLocalMainFrame();
+}
+
WebInputMethodController*
WebViewFrameWidget::GetActiveWebInputMethodController() const {
return web_view_->GetActiveWebInputMethodController();
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 91e49fa8c38..c8320344e4d 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
@@ -44,7 +44,6 @@ class CORE_EXPORT WebViewFrameWidget : public WebFrameWidgetBase {
void Close() override;
WebSize Size() override;
void Resize(const WebSize&) override;
- void ResizeVisualViewport(const WebSize&) override;
void DidEnterFullscreen() override;
void DidExitFullscreen() override;
void SetSuppressFrameRequestsWorkaroundFor704763Only(bool) final;
@@ -67,8 +66,7 @@ class CORE_EXPORT WebViewFrameWidget : public WebFrameWidgetBase {
void SetCursorVisibilityState(bool is_visible) override;
void OnFallbackCursorModeToggled(bool is_on) override;
void ApplyViewportChanges(const ApplyViewportChangesArgs&) override;
- void RecordWheelAndTouchScrollingCount(bool has_scrolled_by_wheel,
- bool has_scrolled_by_touch) override;
+ void RecordManipulationTypeCounts(cc::ManipulationInfo info) override;
void SendOverscrollEventFromImplSide(
const gfx::Vector2dF& overscroll_delta,
cc::ElementId scroll_latched_element_id) override;
@@ -81,6 +79,7 @@ class CORE_EXPORT WebViewFrameWidget : public WebFrameWidgetBase {
WebURL GetURLForDebugTrace() override;
// WebFrameWidget overrides:
+ void DidDetachLocalFrameTree() override;
WebInputMethodController* GetActiveWebInputMethodController() const override;
bool ScrollFocusedEditableElementIntoView() override;
WebHitTestResult HitTestResultAt(const gfx::Point&) override;
diff --git a/chromium/third_party/blink/renderer/core/frame/window.idl b/chromium/third_party/blink/renderer/core/frame/window.idl
index f72784866e9..b5c9a7b6d37 100644
--- a/chromium/third_party/blink/renderer/core/frame/window.idl
+++ b/chromium/third_party/blink/renderer/core/frame/window.idl
@@ -120,8 +120,6 @@
[HighEntropy, Measure, NewObject] MediaQueryList matchMedia(DOMString query);
[SameObject, Replaceable] readonly attribute Screen screen;
- [RuntimeEnabled=WorkerTaskQueue, SameObject, Replaceable] readonly attribute ScriptedTaskQueueController TaskQueue;
-
// browsing context
void moveTo(long x, long y);
void moveBy(long x, long y);
diff --git a/chromium/third_party/blink/renderer/core/frame/window_event_handlers.h b/chromium/third_party/blink/renderer/core/frame/window_event_handlers.h
index 07ab42dc0f3..d9f5e87640d 100644
--- a/chromium/third_party/blink/renderer/core/frame/window_event_handlers.h
+++ b/chromium/third_party/blink/renderer/core/frame/window_event_handlers.h
@@ -31,7 +31,7 @@
#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"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/frame/window_or_worker_global_scope.cc b/chromium/third_party/blink/renderer/core/frame/window_or_worker_global_scope.cc
index 128ec1aed49..51e3b0f07f5 100644
--- a/chromium/third_party/blink/renderer/core/frame/window_or_worker_global_scope.cc
+++ b/chromium/third_party/blink/renderer/core/frame/window_or_worker_global_scope.cc
@@ -146,7 +146,7 @@ int WindowOrWorkerGlobalScope::setTimeout(
ScheduledAction* action = ScheduledAction::Create(
script_state, execution_context, handler, arguments);
return DOMTimer::Install(execution_context, action,
- TimeDelta::FromMilliseconds(timeout), true);
+ base::TimeDelta::FromMilliseconds(timeout), true);
}
int WindowOrWorkerGlobalScope::setTimeout(
@@ -189,7 +189,7 @@ int WindowOrWorkerGlobalScope::setTimeoutFromString(
ScheduledAction* action =
ScheduledAction::Create(script_state, execution_context, handler);
return DOMTimer::Install(execution_context, action,
- TimeDelta::FromMilliseconds(timeout), true);
+ base::TimeDelta::FromMilliseconds(timeout), true);
}
int WindowOrWorkerGlobalScope::setInterval(
@@ -204,7 +204,7 @@ int WindowOrWorkerGlobalScope::setInterval(
ScheduledAction* action = ScheduledAction::Create(
script_state, execution_context, handler, arguments);
return DOMTimer::Install(execution_context, action,
- TimeDelta::FromMilliseconds(timeout), false);
+ base::TimeDelta::FromMilliseconds(timeout), false);
}
int WindowOrWorkerGlobalScope::setInterval(
@@ -242,7 +242,7 @@ int WindowOrWorkerGlobalScope::setIntervalFromString(
ScheduledAction* action =
ScheduledAction::Create(script_state, execution_context, handler);
return DOMTimer::Install(execution_context, action,
- TimeDelta::FromMilliseconds(timeout), false);
+ base::TimeDelta::FromMilliseconds(timeout), false);
}
void WindowOrWorkerGlobalScope::clearTimeout(EventTarget& event_target,
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
index 0cb1db28ad2..e3e7a41adaf 100644
--- 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
@@ -34,7 +34,7 @@
#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/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
diff --git a/chromium/third_party/blink/renderer/core/frame/window_post_message_options.idl b/chromium/third_party/blink/renderer/core/frame/window_post_message_options.idl
index e078ea3a2f5..b82c6f7b74c 100644
--- a/chromium/third_party/blink/renderer/core/frame/window_post_message_options.idl
+++ b/chromium/third_party/blink/renderer/core/frame/window_post_message_options.idl
@@ -9,4 +9,6 @@ dictionary WindowPostMessageOptions : PostMessageOptions {
[RuntimeEnabled =
UserActivationPostMessageTransfer] boolean transferUserActivation =
false;
+ [OriginTrialEnabled =
+ ExperimentalAutoplayDynamicDelegation] DOMString allow = "";
};
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 a0ef80020ae..cb64f05fd67 100644
--- a/chromium/third_party/blink/renderer/core/fullscreen/document_fullscreen.h
+++ b/chromium/third_party/blink/renderer/core/fullscreen/document_fullscreen.h
@@ -29,7 +29,7 @@
#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
#include "third_party/blink/renderer/core/dom/events/event_target.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
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 7fd715191b6..5bfa0516ee0 100644
--- a/chromium/third_party/blink/renderer/core/fullscreen/element_fullscreen.cc
+++ b/chromium/third_party/blink/renderer/core/fullscreen/element_fullscreen.cc
@@ -4,8 +4,8 @@
#include "third_party/blink/renderer/core/fullscreen/element_fullscreen.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/fullscreen/fullscreen.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
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 512bb78e0b2..ecca49b003d 100644
--- a/chromium/third_party/blink/renderer/core/fullscreen/element_fullscreen.h
+++ b/chromium/third_party/blink/renderer/core/fullscreen/element_fullscreen.h
@@ -9,7 +9,7 @@
#include "third_party/blink/renderer/core/dom/events/event_target.h"
#include "third_party/blink/renderer/core/fullscreen/fullscreen_options.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
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 3db7742deb5..5cb191948c2 100644
--- a/chromium/third_party/blink/renderer/core/fullscreen/fullscreen.cc
+++ b/chromium/third_party/blink/renderer/core/fullscreen/fullscreen.cc
@@ -43,7 +43,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/frame/settings.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/frame/visual_viewport.h"
#include "third_party/blink/renderer/core/fullscreen/fullscreen_options.h"
#include "third_party/blink/renderer/core/fullscreen/scoped_allow_fullscreen.h"
@@ -55,6 +54,7 @@
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/svg/svg_svg_element.h"
#include "third_party/blink/renderer/platform/bindings/microtask.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/fullscreen/scoped_allow_fullscreen.h b/chromium/third_party/blink/renderer/core/fullscreen/scoped_allow_fullscreen.h
index 950b3841cef..541054b6b39 100644
--- a/chromium/third_party/blink/renderer/core/fullscreen/scoped_allow_fullscreen.h
+++ b/chromium/third_party/blink/renderer/core/fullscreen/scoped_allow_fullscreen.h
@@ -8,7 +8,7 @@
#include "base/macros.h"
#include "base/optional.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 4160cb255b7..6686db7f41a 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
@@ -17,7 +17,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/paint/paint_layer_scrollable_area.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/geometry/int_size.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
@@ -305,7 +306,12 @@ void AnchorElementMetrics::MaybeReportViewportMetricsOnLoad(
if (anchor_elements_metrics.IsEmpty())
return;
- sender->SendAnchorMetricsVectorToBrowser(std::move(anchor_elements_metrics));
+ LocalFrame* local_frame = document.GetFrame();
+ LocalFrameView* root_frame_view = local_frame->LocalFrameRoot().View();
+ IntRect viewport = root_frame_view->LayoutViewport()->VisibleContentRect();
+
+ sender->SendAnchorMetricsVectorToBrowser(std::move(anchor_elements_metrics),
+ viewport.Size());
}
mojom::blink::AnchorElementMetricsPtr AnchorElementMetrics::CreateMetricsPtr()
diff --git a/chromium/third_party/blink/renderer/core/html/anchor_element_metrics.h b/chromium/third_party/blink/renderer/core/html/anchor_element_metrics.h
index cc4bb5fbe37..778f218a497 100644
--- a/chromium/third_party/blink/renderer/core/html/anchor_element_metrics.h
+++ b/chromium/third_party/blink/renderer/core/html/anchor_element_metrics.h
@@ -9,7 +9,7 @@
#include "third_party/blink/public/mojom/loader/navigation_predictor.mojom-blink.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 b723f10bf97..ac565b661c0 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
@@ -11,6 +11,7 @@
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/html/anchor_element_metrics.h"
#include "third_party/blink/renderer/core/html/html_anchor_element.h"
+#include "ui/gfx/geometry/mojo/geometry.mojom-shared.h"
namespace blink {
@@ -67,11 +68,13 @@ void AnchorElementMetricsSender::SendClickedAnchorMetricsToBrowser(
}
void AnchorElementMetricsSender::SendAnchorMetricsVectorToBrowser(
- Vector<mojom::blink::AnchorElementMetricsPtr> metrics) {
+ Vector<mojom::blink::AnchorElementMetricsPtr> metrics,
+ const IntSize& viewport_size) {
if (!AssociateInterface())
return;
- metrics_host_->ReportAnchorElementMetricsOnLoad(std::move(metrics));
+ metrics_host_->ReportAnchorElementMetricsOnLoad(std::move(metrics),
+ viewport_size);
has_onload_report_sent_ = true;
anchor_elements_.clear();
}
diff --git a/chromium/third_party/blink/renderer/core/html/anchor_element_metrics_sender.h b/chromium/third_party/blink/renderer/core/html/anchor_element_metrics_sender.h
index ecb3ba208ab..70cd4623335 100644
--- a/chromium/third_party/blink/renderer/core/html/anchor_element_metrics_sender.h
+++ b/chromium/third_party/blink/renderer/core/html/anchor_element_metrics_sender.h
@@ -9,6 +9,7 @@
#include "third_party/blink/public/mojom/loader/navigation_predictor.mojom-blink.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
+#include "third_party/blink/renderer/platform/geometry/int_size.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/supplementable.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
@@ -52,7 +53,8 @@ class CORE_EXPORT AnchorElementMetricsSender final
// Sends metrics of visible anchor elements to the browser.
void SendAnchorMetricsVectorToBrowser(
- Vector<mojom::blink::AnchorElementMetricsPtr> metrics);
+ Vector<mojom::blink::AnchorElementMetricsPtr> metrics,
+ const IntSize& viewport_size);
// Adds an anchor element to |anchor_elements_|.
void AddAnchorElement(HTMLAnchorElement& element);
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 08baf7904fd..0c2745c6923 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
@@ -15,16 +15,16 @@
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/fileapi/blob.h"
#include "third_party/blink/renderer/core/html/canvas/canvas_rendering_context.h"
-#include "third_party/blink/renderer/platform/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/graphics/image_data_buffer.h"
#include "third_party/blink/renderer/platform/graphics/skia/skia_utils.h"
#include "third_party/blink/renderer/platform/heap/heap.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/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/scheduler/public/thread_scheduler.h"
#include "third_party/blink/renderer/platform/scheduler/public/worker_pool.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.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"
@@ -34,10 +34,10 @@ namespace blink {
namespace {
// small slack period between deadline and current time for safety
-constexpr TimeDelta kCreateBlobSlackBeforeDeadline =
- TimeDelta::FromMilliseconds(1);
-constexpr TimeDelta kEncodeRowSlackBeforeDeadline =
- TimeDelta::FromMicroseconds(100);
+constexpr base::TimeDelta kCreateBlobSlackBeforeDeadline =
+ base::TimeDelta::FromMilliseconds(1);
+constexpr base::TimeDelta kEncodeRowSlackBeforeDeadline =
+ base::TimeDelta::FromMicroseconds(100);
/* The value is based on user statistics on Nov 2017. */
#if (defined(OS_LINUX) || defined(OS_MACOSX) || defined(OS_WIN))
@@ -59,18 +59,19 @@ const double kIdleTaskCompleteTimeoutDelayMs = 5700.0;
const double kIdleTaskCompleteTimeoutDelayMs = 9000.0;
#endif
-bool IsCreateBlobDeadlineNearOrPassed(TimeTicks deadline) {
- return CurrentTimeTicks() >= deadline - kCreateBlobSlackBeforeDeadline;
+bool IsCreateBlobDeadlineNearOrPassed(base::TimeTicks deadline) {
+ return base::TimeTicks::Now() >= deadline - kCreateBlobSlackBeforeDeadline;
}
-bool IsEncodeRowDeadlineNearOrPassed(TimeTicks deadline, size_t image_width) {
+bool IsEncodeRowDeadlineNearOrPassed(base::TimeTicks deadline,
+ size_t image_width) {
// Rough estimate of the row encoding time in micro seconds. We will consider
// a slack time later to not pass the idle task deadline.
int row_encode_time_us = 1000 * (kIdleTaskCompleteTimeoutDelayMs / 4000.0) *
(image_width / 4000.0);
- TimeDelta row_encode_time_delta =
- TimeDelta::FromMicroseconds(row_encode_time_us);
- return CurrentTimeTicks() >=
+ base::TimeDelta row_encode_time_delta =
+ base::TimeDelta::FromMicroseconds(row_encode_time_us);
+ return base::TimeTicks::Now() >=
deadline - row_encode_time_delta - kEncodeRowSlackBeforeDeadline;
}
@@ -80,29 +81,30 @@ void RecordIdleTaskStatusHistogram(
}
void RecordInitiateEncodingTimeHistogram(ImageEncodingMimeType mime_type,
- TimeDelta elapsed_time) {
+ base::TimeDelta elapsed_time) {
+ // TODO(crbug.com/983261) Change this to use UmaHistogramMicrosecondsTimes.
if (mime_type == kMimeTypePng) {
- UmaHistogramMicrosecondsTimes(
+ UmaHistogramMicrosecondsTimesUnderTenMilliseconds(
"Blink.Canvas.ToBlob.InitiateEncodingDelay.PNG", elapsed_time);
} else if (mime_type == kMimeTypeJpeg) {
- UmaHistogramMicrosecondsTimes(
+ UmaHistogramMicrosecondsTimesUnderTenMilliseconds(
"Blink.Canvas.ToBlob.InitiateEncodingDelay.JPEG", elapsed_time);
}
}
void RecordCompleteEncodingTimeHistogram(ImageEncodingMimeType mime_type,
- TimeDelta elapsed_time) {
+ base::TimeDelta elapsed_time) {
if (mime_type == kMimeTypePng) {
- UmaHistogramMicrosecondsTimes(
+ UmaHistogramMicrosecondsTimesUnderTenMilliseconds(
"Blink.Canvas.ToBlob.CompleteEncodingDelay.PNG", elapsed_time);
} else if (mime_type == kMimeTypeJpeg) {
- UmaHistogramMicrosecondsTimes(
+ UmaHistogramMicrosecondsTimesUnderTenMilliseconds(
"Blink.Canvas.ToBlob.CompleteEncodingDelay.JPEG", elapsed_time);
}
}
void RecordScaledDurationHistogram(ImageEncodingMimeType mime_type,
- TimeDelta elapsed_time,
+ base::TimeDelta elapsed_time,
float width,
float height) {
float sqrt_pixels = std::sqrt(width) * std::sqrt(height);
@@ -127,13 +129,22 @@ void RecordScaledDurationHistogram(ImageEncodingMimeType mime_type,
}
}
+SkColorType GetColorTypeForConversion(SkColorType color_type) {
+ if (color_type == kRGBA_8888_SkColorType ||
+ color_type == kBGRA_8888_SkColorType) {
+ return color_type;
+ }
+
+ return kN32_SkColorType;
+}
+
} // anonymous namespace
CanvasAsyncBlobCreator::CanvasAsyncBlobCreator(
scoped_refptr<StaticBitmapImage> image,
const ImageEncodeOptions* options,
ToBlobFunctionType function_type,
- TimeTicks start_time,
+ base::TimeTicks start_time,
ExecutionContext* context,
ScriptPromiseResolver* resolver)
: CanvasAsyncBlobCreator(image,
@@ -149,7 +160,7 @@ CanvasAsyncBlobCreator::CanvasAsyncBlobCreator(
const ImageEncodeOptions* options,
ToBlobFunctionType function_type,
V8BlobCallback* callback,
- TimeTicks start_time,
+ base::TimeTicks start_time,
ExecutionContext* context,
ScriptPromiseResolver* resolver)
: fail_encoder_initialization_for_test_(false),
@@ -160,7 +171,7 @@ CanvasAsyncBlobCreator::CanvasAsyncBlobCreator(
function_type_(function_type),
start_time_(start_time),
static_bitmap_image_loaded_(false),
- callback_(ToV8PersistentCallbackFunction(callback)),
+ callback_(callback),
script_promise_resolver_(resolver) {
DCHECK(image);
@@ -189,7 +200,9 @@ CanvasAsyncBlobCreator::CanvasAsyncBlobCreator(
// covnert to the requested color space and pixel format.
if (function_type_ != kHTMLCanvasConvertToBlobPromise) {
if (skia_image->colorSpace()) {
- image_ = image_->ConvertToColorSpace(SkColorSpace::MakeSRGB());
+ image_ = image_->ConvertToColorSpace(
+ SkColorSpace::MakeSRGB(),
+ GetColorTypeForConversion(skia_image->colorType()));
skia_image = image_->PaintImageForCurrentFrame().GetSkImage();
}
@@ -210,7 +223,8 @@ CanvasAsyncBlobCreator::CanvasAsyncBlobCreator(
DCHECK(skia_image->colorSpace());
}
- SkColorType target_color_type = kN32_SkColorType;
+ SkColorType target_color_type =
+ GetColorTypeForConversion(skia_image->colorType());
if (encode_options_->pixelFormat() == kRGBA16ImagePixelFormatName)
target_color_type = kRGBA_F16_SkColorType;
// We can do color space and color type conversion together.
@@ -342,19 +356,19 @@ void CanvasAsyncBlobCreator::ScheduleAsyncBlobCreation(const double& quality) {
}
void CanvasAsyncBlobCreator::ScheduleInitiateEncoding(double quality) {
- schedule_idle_task_start_time_ = WTF::CurrentTimeTicks();
+ schedule_idle_task_start_time_ = base::TimeTicks::Now();
ThreadScheduler::Current()->PostIdleTask(
FROM_HERE, WTF::Bind(&CanvasAsyncBlobCreator::InitiateEncoding,
WrapPersistent(this), quality));
}
void CanvasAsyncBlobCreator::InitiateEncoding(double quality,
- TimeTicks deadline) {
+ base::TimeTicks deadline) {
if (idle_task_status_ == kIdleTaskSwitchedToImmediateTask) {
return;
}
RecordInitiateEncodingTimeHistogram(
- mime_type_, WTF::CurrentTimeTicks() - schedule_idle_task_start_time_);
+ mime_type_, base::TimeTicks::Now() - schedule_idle_task_start_time_);
DCHECK(idle_task_status_ == kIdleTaskNotStarted);
idle_task_status_ = kIdleTaskStarted;
@@ -365,11 +379,11 @@ void CanvasAsyncBlobCreator::InitiateEncoding(double quality,
}
// Re-use this time variable to collect data on complete encoding delay
- schedule_idle_task_start_time_ = WTF::CurrentTimeTicks();
+ schedule_idle_task_start_time_ = base::TimeTicks::Now();
IdleEncodeRows(deadline);
}
-void CanvasAsyncBlobCreator::IdleEncodeRows(TimeTicks deadline) {
+void CanvasAsyncBlobCreator::IdleEncodeRows(base::TimeTicks deadline) {
if (idle_task_status_ == kIdleTaskSwitchedToImmediateTask) {
return;
}
@@ -392,8 +406,8 @@ void CanvasAsyncBlobCreator::IdleEncodeRows(TimeTicks deadline) {
num_rows_completed_ = src_data_.height();
idle_task_status_ = kIdleTaskCompleted;
- TimeDelta elapsed_time =
- WTF::CurrentTimeTicks() - schedule_idle_task_start_time_;
+ base::TimeDelta elapsed_time =
+ base::TimeTicks::Now() - schedule_idle_task_start_time_;
RecordCompleteEncodingTimeHistogram(mime_type_, elapsed_time);
if (IsCreateBlobDeadlineNearOrPassed(deadline)) {
context_->GetTaskRunner(TaskType::kCanvasBlobSerialization)
@@ -438,8 +452,7 @@ void CanvasAsyncBlobCreator::CreateBlobAndReturnResult() {
if (function_type_ == kHTMLCanvasToBlobCallback) {
context_->GetTaskRunner(TaskType::kCanvasBlobSerialization)
->PostTask(FROM_HERE,
- WTF::Bind(&V8PersistentCallbackFunction<
- V8BlobCallback>::InvokeAndReportException,
+ WTF::Bind(&V8BlobCallback::InvokeAndReportException,
WrapPersistent(callback_.Get()), nullptr,
WrapPersistent(result_blob)));
} else {
@@ -451,7 +464,7 @@ void CanvasAsyncBlobCreator::CreateBlobAndReturnResult() {
}
RecordScaledDurationHistogram(mime_type_,
- WTF::CurrentTimeTicks() - start_time_,
+ base::TimeTicks::Now() - start_time_,
image_->width(), image_->height());
// Avoid unwanted retention, see dispose().
Dispose();
@@ -465,8 +478,7 @@ void CanvasAsyncBlobCreator::CreateNullAndReturnResult() {
context_->GetTaskRunner(TaskType::kCanvasBlobSerialization)
->PostTask(
FROM_HERE,
- WTF::Bind(&V8PersistentCallbackFunction<
- V8BlobCallback>::InvokeAndReportException,
+ WTF::Bind(&V8BlobCallback::InvokeAndReportException,
WrapPersistent(callback_.Get()), nullptr, nullptr));
} else {
context_->GetTaskRunner(TaskType::kCanvasBlobSerialization)
@@ -585,7 +597,7 @@ void CanvasAsyncBlobCreator::PostDelayedTaskToCurrentThread(
double delay_ms) {
context_->GetTaskRunner(TaskType::kCanvasBlobSerialization)
->PostDelayedTask(location, std::move(task),
- TimeDelta::FromMillisecondsD(delay_ms));
+ base::TimeDelta::FromMillisecondsD(delay_ms));
}
void CanvasAsyncBlobCreator::Trace(Visitor* visitor) {
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 615d58f5e43..e90ba9abe82 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
@@ -59,14 +59,14 @@ class CORE_EXPORT CanvasAsyncBlobCreator
CanvasAsyncBlobCreator(scoped_refptr<StaticBitmapImage>,
const ImageEncodeOptions* options,
ToBlobFunctionType function_type,
- TimeTicks start_time,
+ base::TimeTicks start_time,
ExecutionContext*,
ScriptPromiseResolver*);
CanvasAsyncBlobCreator(scoped_refptr<StaticBitmapImage>,
const ImageEncodeOptions*,
ToBlobFunctionType,
V8BlobCallback*,
- TimeTicks start_time,
+ base::TimeTicks start_time,
ExecutionContext*,
ScriptPromiseResolver* = nullptr);
virtual ~CanvasAsyncBlobCreator();
@@ -90,7 +90,7 @@ class CORE_EXPORT CanvasAsyncBlobCreator
ImageEncodingMimeType);
// Methods are virtual for unit testing
virtual void ScheduleInitiateEncoding(double quality);
- virtual void IdleEncodeRows(TimeTicks deadline);
+ virtual void IdleEncodeRows(base::TimeTicks deadline);
virtual void PostDelayedTaskToCurrentThread(const base::Location&,
base::OnceClosure,
double delay_ms);
@@ -98,7 +98,7 @@ class CORE_EXPORT CanvasAsyncBlobCreator
virtual void CreateBlobAndReturnResult();
virtual void CreateNullAndReturnResult();
- void InitiateEncoding(double quality, TimeTicks deadline);
+ void InitiateEncoding(double quality, base::TimeTicks deadline);
protected:
IdleTaskStatus idle_task_status_;
@@ -123,20 +123,15 @@ class CORE_EXPORT CanvasAsyncBlobCreator
sk_sp<SkData> png_data_helper_;
// Chrome metrics use
- TimeTicks start_time_;
- TimeTicks schedule_idle_task_start_time_;
+ base::TimeTicks start_time_;
+ base::TimeTicks schedule_idle_task_start_time_;
bool static_bitmap_image_loaded_;
// Used when CanvasAsyncBlobCreator runs on main thread only
scoped_refptr<base::SingleThreadTaskRunner> parent_frame_task_runner_;
// Used for HTMLCanvasElement only
- //
- // Note: CanvasAsyncBlobCreator is never held by other objects. As soon as
- // an instance gets created, ScheduleAsyncBlobCreation is invoked, and then
- // the instance is only held by a task runner (via PostTask). Thus the
- // instance has only limited lifetime. Hence, Persistent here is okay.
- Member<V8PersistentCallbackFunction<V8BlobCallback>> callback_;
+ Member<V8BlobCallback> callback_;
// Used for OffscreenCanvas only
Member<ScriptPromiseResolver> script_promise_resolver_;
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 88fa1db3887..4b0d87733bb 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
@@ -31,7 +31,7 @@ class MockCanvasAsyncBlobCreator : public CanvasAsyncBlobCreator {
CanvasAsyncBlobCreator::GetImageEncodeOptionsForMimeType(mime_type),
kHTMLCanvasToBlobCallback,
nullptr,
- TimeTicks(),
+ base::TimeTicks(),
document,
nullptr) {
if (fail_encoder_initialization)
@@ -102,10 +102,10 @@ class MockCanvasAsyncBlobCreatorWithoutComplete
Thread::Current()->GetTaskRunner()->PostTask(
FROM_HERE,
WTF::Bind(&MockCanvasAsyncBlobCreatorWithoutComplete::InitiateEncoding,
- WrapPersistent(this), quality, TimeTicks::Max()));
+ WrapPersistent(this), quality, base::TimeTicks::Max()));
}
- void IdleEncodeRows(TimeTicks deadline) override {
+ void IdleEncodeRows(base::TimeTicks deadline) override {
// Deliberately make idleEncodeRows do nothing so that idle task never
// completes
}
@@ -292,7 +292,7 @@ TEST_F(CanvasAsyncBlobCreatorTest, ColorManagedConvertToBlob) {
source_bitmap_image, options,
CanvasAsyncBlobCreator::ToBlobFunctionType::
kHTMLCanvasConvertToBlobPromise,
- TimeTicks(), &GetDocument(), nullptr);
+ base::TimeTicks(), &GetDocument(), nullptr);
ASSERT_TRUE(async_blob_creator->EncodeImageForConvertToBlobTest());
sk_sp<SkData> sk_data = SkData::MakeWithCopy(
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 228a7da6ff2..da84ab47e1c 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
@@ -8,10 +8,11 @@
#include "third_party/blink/renderer/core/css/parser/css_parser.h"
#include "third_party/blink/renderer/core/css/resolver/style_resolver.h"
#include "third_party/blink/renderer/core/dom/document.h"
+#include "third_party/blink/renderer/core/html/canvas/html_canvas_element.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/platform/fonts/font_cache.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
-#include "third_party/blink/renderer/platform/memory_pressure_listener.h"
+#include "third_party/blink/renderer/platform/instrumentation/memory_pressure_listener.h"
namespace {
@@ -56,7 +57,8 @@ unsigned CanvasFontCache::HardMaxFonts() {
: CanvasFontCacheHardMaxFonts);
}
-bool CanvasFontCache::GetFontUsingDefaultStyle(const String& font_string,
+bool CanvasFontCache::GetFontUsingDefaultStyle(HTMLCanvasElement& element,
+ const String& font_string,
Font& resolved_font) {
HashMap<String, Font>::iterator i =
fonts_resolved_using_default_style_.find(font_string);
@@ -74,7 +76,8 @@ bool CanvasFontCache::GetFontUsingDefaultStyle(const String& font_string,
scoped_refptr<ComputedStyle> font_style =
ComputedStyle::Clone(*default_font_style_.get());
- document_->EnsureStyleResolver().ComputeFont(font_style.get(), *parsed_style);
+ document_->EnsureStyleResolver().ComputeFont(element, font_style.get(),
+ *parsed_style);
fonts_resolved_using_default_style_.insert(font_string,
font_style->GetFont());
resolved_font = fonts_resolved_using_default_style_.find(font_string)->value;
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 2e41d95b53a..c74201898b1 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
@@ -20,6 +20,7 @@ namespace blink {
class ComputedStyle;
class Document;
class FontCachePurgePreventer;
+class HTMLCanvasElement;
class CORE_EXPORT CanvasFontCache final
: public GarbageCollectedFinalized<CanvasFontCache>,
@@ -39,7 +40,9 @@ class CORE_EXPORT CanvasFontCache final
unsigned HardMaxFonts();
void WillUseCurrentFont() { SchedulePruningIfNeeded(); }
- bool GetFontUsingDefaultStyle(const String&, Font&);
+ bool GetFontUsingDefaultStyle(HTMLCanvasElement& canvas,
+ const String&,
+ Font&);
// TaskObserver implementation
void DidProcessTask(const base::PendingTask&) override;
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 858c10aebff..022cdb0f018 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
@@ -152,7 +152,7 @@ class CORE_EXPORT CanvasRenderingContext : public ScriptWrappable,
virtual void StyleDidChange(const ComputedStyle* old_style,
const ComputedStyle& new_style) {}
virtual HitTestCanvasResult* GetControlAndIdIfHitRegionExists(
- const LayoutPoint& location) {
+ const PhysicalOffset& location) {
NOTREACHED();
return MakeGarbageCollected<HitTestCanvasResult>(String(), nullptr);
}
diff --git a/chromium/third_party/blink/renderer/core/html/canvas/canvas_rendering_context_factory.h b/chromium/third_party/blink/renderer/core/html/canvas/canvas_rendering_context_factory.h
index 5a56e7a2492..dff8ab7ce2e 100644
--- a/chromium/third_party/blink/renderer/core/html/canvas/canvas_rendering_context_factory.h
+++ b/chromium/third_party/blink/renderer/core/html/canvas/canvas_rendering_context_factory.h
@@ -11,7 +11,7 @@
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/html/canvas/canvas_context_creation_attributes_core.h"
#include "third_party/blink/renderer/core/html/canvas/canvas_rendering_context.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 06c83654c09..cc1248185ab 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
@@ -12,23 +12,23 @@
#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/heap/heap.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/skia/include/core/SkSurface.h"
namespace blink {
-CanvasRenderingContextHost::CanvasRenderingContextHost() = default;
+CanvasRenderingContextHost::CanvasRenderingContextHost(HostType host_type)
+ : host_type_(host_type) {}
-void CanvasRenderingContextHost::RecordCanvasSizeToUMA(const IntSize& size,
- HostType hostType) {
+void CanvasRenderingContextHost::RecordCanvasSizeToUMA(const IntSize& size) {
if (did_record_canvas_size_to_uma_)
return;
did_record_canvas_size_to_uma_ = true;
- if (hostType == kCanvasHost) {
+ if (host_type_ == kCanvasHost) {
UMA_HISTOGRAM_CUSTOM_COUNTS("Blink.Canvas.SqrtNumberOfPixels",
std::sqrt(size.Area()), 1, 5000, 100);
- } else if (hostType == kOffscreenCanvasHost) {
+ } else if (host_type_ == kOffscreenCanvasHost) {
UMA_HISTOGRAM_CUSTOM_COUNTS("Blink.OffscreenCanvas.SqrtNumberOfPixels",
std::sqrt(size.Area()), 1, 5000, 100);
} else {
@@ -96,23 +96,33 @@ CanvasRenderingContextHost::GetOrCreateCanvasResourceProviderImpl(
if (Is3d()) {
CanvasResourceProvider::ResourceUsage usage;
if (SharedGpuContext::IsGpuCompositingEnabled()) {
- if (LowLatencyEnabled())
- usage = CanvasResourceProvider::kAcceleratedDirect3DResourceUsage;
- else
- usage = CanvasResourceProvider::kAcceleratedCompositedResourceUsage;
+ if (LowLatencyEnabled()) {
+ usage = CanvasResourceProvider::ResourceUsage::
+ kAcceleratedDirect3DResourceUsage;
+ } else {
+ usage = CanvasResourceProvider::ResourceUsage::
+ kAcceleratedCompositedResourceUsage;
+ }
} else {
- usage = CanvasResourceProvider::kSoftwareCompositedResourceUsage;
+ usage = CanvasResourceProvider::ResourceUsage::
+ kSoftwareCompositedResourceUsage;
}
- const CanvasResourceProvider::PresentationMode presentation_mode =
- RuntimeEnabledFeatures::WebGLImageChromiumEnabled()
- ? CanvasResourceProvider::kAllowImageChromiumPresentationMode
- : CanvasResourceProvider::kDefaultPresentationMode;
+ CanvasResourceProvider::PresentationMode presentation_mode;
+ if (RuntimeEnabledFeatures::WebGLSwapChainEnabled()) {
+ presentation_mode =
+ CanvasResourceProvider::kAllowSwapChainPresentationMode;
+ } else if (RuntimeEnabledFeatures::WebGLImageChromiumEnabled()) {
+ presentation_mode =
+ CanvasResourceProvider::kAllowImageChromiumPresentationMode;
+ } else {
+ presentation_mode = CanvasResourceProvider::kDefaultPresentationMode;
+ }
const bool is_origin_top_left =
!SharedGpuContext::IsGpuCompositingEnabled();
- ReplaceResourceProvider(CanvasResourceProvider::Create(
+ ReplaceResourceProvider(CanvasResourceProvider::CreateForCanvas(
Size(), usage, SharedGpuContext::ContextProviderWrapper(),
0 /* msaa_sample_count */, ColorParams(), presentation_mode,
std::move(dispatcher), is_origin_top_left));
@@ -123,12 +133,16 @@ CanvasRenderingContextHost::GetOrCreateCanvasResourceProviderImpl(
CanvasResourceProvider::ResourceUsage usage;
if (want_acceleration) {
- if (LowLatencyEnabled())
- usage = CanvasResourceProvider::kAcceleratedDirect2DResourceUsage;
- else
- usage = CanvasResourceProvider::kAcceleratedCompositedResourceUsage;
+ if (LowLatencyEnabled()) {
+ usage = CanvasResourceProvider::ResourceUsage::
+ kAcceleratedDirect2DResourceUsage;
+ } else {
+ usage = CanvasResourceProvider::ResourceUsage::
+ kAcceleratedCompositedResourceUsage;
+ }
} else {
- usage = CanvasResourceProvider::kSoftwareCompositedResourceUsage;
+ usage = CanvasResourceProvider::ResourceUsage::
+ kSoftwareCompositedResourceUsage;
}
const CanvasResourceProvider::PresentationMode presentation_mode =
@@ -140,7 +154,7 @@ CanvasRenderingContextHost::GetOrCreateCanvasResourceProviderImpl(
const bool is_origin_top_left =
!want_acceleration || LowLatencyEnabled();
- ReplaceResourceProvider(CanvasResourceProvider::Create(
+ ReplaceResourceProvider(CanvasResourceProvider::CreateForCanvas(
Size(), usage, SharedGpuContext::ContextProviderWrapper(),
GetMSAASampleCountFor2dContext(), ColorParams(), presentation_mode,
std::move(dispatcher), is_origin_top_left));
@@ -201,7 +215,7 @@ ScriptPromise CanvasRenderingContextHost::convertToBlob(
return ScriptPromise();
}
- TimeTicks start_time = WTF::CurrentTimeTicks();
+ base::TimeTicks start_time = base::TimeTicks::Now();
scoped_refptr<StaticBitmapImage> image_bitmap =
RenderingContext()->GetImage(kPreferNoAcceleration);
if (image_bitmap) {
@@ -223,4 +237,8 @@ ScriptPromise CanvasRenderingContextHost::convertToBlob(
return ScriptPromise();
}
+bool CanvasRenderingContextHost::IsOffscreenCanvas() const {
+ return host_type_ == kOffscreenCanvasHost;
+}
+
} // namespace blink
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 daea7c9aed5..d90f1979efa 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
@@ -32,14 +32,15 @@ class CORE_EXPORT CanvasRenderingContextHost : public CanvasResourceHost,
public CanvasImageSource,
public GarbageCollectedMixin {
public:
- CanvasRenderingContextHost();
-
enum HostType {
+ kNone,
kCanvasHost,
kOffscreenCanvasHost,
};
+ CanvasRenderingContextHost(HostType host_type);
+
+ void RecordCanvasSizeToUMA(const IntSize&);
- void RecordCanvasSizeToUMA(const IntSize&, HostType);
virtual void DetachContext() = 0;
virtual void DidDraw(const FloatRect& rect) = 0;
@@ -98,6 +99,9 @@ class CORE_EXPORT CanvasRenderingContextHost : public CanvasResourceHost,
const ImageEncodeOptions*,
ExceptionState&) const;
+ // blink::CanvasImageSource
+ bool IsOffscreenCanvas() const override;
+
protected:
~CanvasRenderingContextHost() override {}
@@ -105,6 +109,7 @@ class CORE_EXPORT CanvasRenderingContextHost : public CanvasResourceHost,
bool did_fail_to_create_resource_provider_ = false;
bool did_record_canvas_size_to_uma_ = false;
+ HostType host_type_ = kNone;
};
} // namespace blink
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 e18b337318a..4e6688aa229 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
@@ -52,7 +52,6 @@
#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/html/canvas/canvas_async_blob_creator.h"
#include "third_party/blink/renderer/core/html/canvas/canvas_context_creation_attributes_core.h"
#include "third_party/blink/renderer/core/html/canvas/canvas_draw_listener.h"
@@ -85,6 +84,7 @@
#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/image-encoders/image_encoder_utils.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "v8/include/v8.h"
@@ -127,6 +127,8 @@ HTMLCanvasElement::HTMLCanvasElement(Document& document)
: HTMLElement(kCanvasTag, document),
ContextLifecycleObserver(&document),
PageVisibilityObserver(document.GetPage()),
+ CanvasRenderingContextHost(
+ CanvasRenderingContextHost::HostType::kCanvasHost),
size_(kDefaultCanvasWidth, kDefaultCanvasHeight),
context_creation_was_blocked_(false),
ignore_reset_(false),
@@ -137,7 +139,6 @@ HTMLCanvasElement::HTMLCanvasElement(Document& document)
gpu_readback_invoked_in_current_frame_(false),
gpu_readback_successive_frames_(0) {
UseCounter::Count(document, WebFeature::kHTMLCanvasElement);
-
GetDocument().IncrementNumberOfCanvases();
}
@@ -152,8 +153,10 @@ HTMLCanvasElement::~HTMLCanvasElement() {
void HTMLCanvasElement::Dispose() {
if (PlaceholderFrame()) {
ReleasePlaceholderFrame();
- UnregisterPlaceholder();
}
+ // It's possible that the placeholder frame has been disposed but its ID still
+ // exists. Make sure that it gets unregistered here
+ UnregisterPlaceholder();
// We need to drop frame dispatcher, to prevent mojo calls from completing.
frame_dispatcher_ = nullptr;
@@ -318,6 +321,12 @@ CanvasRenderingContext* HTMLCanvasElement::GetCanvasRenderingContextInternal(
if (!context_)
return nullptr;
+ // Since the |context_| is created, free the transparent image,
+ // |transparent_image_| created for this canvas if it exists.
+ if (transparent_image_.get()) {
+ transparent_image_.reset();
+ }
+
context_creation_was_blocked_ = false;
probe::DidCreateCanvasContext(&GetDocument());
@@ -407,8 +416,7 @@ void HTMLCanvasElement::DidDraw() {
void HTMLCanvasElement::FinalizeFrame() {
TRACE_EVENT0("blink", "HTMLCanvasElement::FinalizeFrame");
- RecordCanvasSizeToUMA(size_,
- CanvasRenderingContextHost::HostType::kCanvasHost);
+ RecordCanvasSizeToUMA(size_);
// FinalizeFrame indicates the end of a script task that may have rendered
// into the canvas, now is a good time to unlock cache entries.
@@ -441,10 +449,13 @@ void HTMLCanvasElement::FinalizeFrame() {
if (LowLatencyEnabled() && !dirty_rect_.IsEmpty()) {
if (GetOrCreateCanvasResourceProvider(kPreferAcceleration)) {
+ const bool webgl_overlay_enabled =
+ RuntimeEnabledFeatures::WebGLImageChromiumEnabled() ||
+ RuntimeEnabledFeatures::WebGLSwapChainEnabled();
// TryEnableSingleBuffering() the first time we FinalizeFrame().
if (!ResourceProvider()->IsSingleBuffered()) {
ResourceProvider()->TryEnableSingleBuffering();
- if (Is3d() && RuntimeEnabledFeatures::WebGLImageChromiumEnabled())
+ if (Is3d() && webgl_overlay_enabled)
context_->ProvideBackBufferToResourceProvider();
}
@@ -452,11 +463,11 @@ void HTMLCanvasElement::FinalizeFrame() {
canvas2d_bridge_->FlushRecording();
} else {
DCHECK(Is3d());
- if (!RuntimeEnabledFeatures::WebGLImageChromiumEnabled())
+ if (!webgl_overlay_enabled)
context_->PaintRenderingResultsToCanvas(kBackBuffer);
}
- const base::TimeTicks start_time = WTF::CurrentTimeTicks();
+ const base::TimeTicks start_time = base::TimeTicks::Now();
const scoped_refptr<CanvasResource> canvas_resource =
ResourceProvider()->ProduceCanvasResource();
const FloatRect src_rect(0, 0, Size().Width(), Size().Height());
@@ -764,6 +775,34 @@ void HTMLCanvasElement::PaintInternal(GraphicsContext& context,
context_->PaintRenderingResultsToCanvas(kFrontBuffer);
if (HasResourceProvider()) {
if (!context.ContextDisabled()) {
+ // For 2D Canvas, there are two ways of render Canvas for printing:
+ // display list or image snapshot. Display list allows better PDF printing
+ // and we prefer this method.
+ // Here are the requirements for display list to be used:
+ // 1. We must have had a full repaint of the Canvas after beginprint
+ // event has been fired. Otherwise, we don't have a PaintRecord.
+ // 2. CSS property 'image-rendering' must not be 'pixelated'.
+
+ // display list rendering: we replay the last full PaintRecord, if Canvas
+ // has been redraw since beginprint happened.
+ if (IsPrinting() && !Is3d() && canvas2d_bridge_) {
+ canvas2d_bridge_->FlushRecording();
+ if (canvas2d_bridge_->getLastRecord()) {
+ const ComputedStyle* style = GetComputedStyle();
+ if (style && style->ImageRendering() != EImageRendering::kPixelated) {
+ context.Canvas()->save();
+ context.Canvas()->translate(r.X(), r.Y());
+ context.Canvas()->scale(r.Width() / Size().Width(),
+ r.Height() / Size().Height());
+ context.Canvas()->drawPicture(canvas2d_bridge_->getLastRecord());
+ context.Canvas()->restore();
+ UMA_HISTOGRAM_BOOLEAN("Blink.Canvas.2DPrintingAsVector", true);
+ return;
+ }
+ }
+ UMA_HISTOGRAM_BOOLEAN("Blink.Canvas.2DPrintingAsVector", false);
+ }
+ // or image snapshot rendering: grab a snapshot and raster it.
SkBlendMode composite_operator =
!context_ || context_->CreationAttributes().alpha
? SkBlendMode::kSrcOver
@@ -792,9 +831,8 @@ void HTMLCanvasElement::PaintInternal(GraphicsContext& context,
context_->MarkLayerComposited();
}
-bool HTMLCanvasElement::IsAnimated2d() const {
- return Is2d() && canvas2d_bridge_ &&
- canvas2d_bridge_->WasDrawnToAfterSnapshot();
+bool HTMLCanvasElement::IsPrinting() const {
+ return GetDocument().BeforePrintingOrPrinting();
}
void HTMLCanvasElement::SetSurfaceSize(const IntSize& size) {
@@ -938,16 +976,13 @@ void HTMLCanvasElement::toBlob(V8BlobCallback* callback,
// If the canvas element's bitmap has no pixels
GetDocument()
.GetTaskRunner(TaskType::kCanvasBlobSerialization)
- ->PostTask(
- FROM_HERE,
- WTF::Bind(&V8PersistentCallbackFunction<
- V8BlobCallback>::InvokeAndReportException,
- WrapPersistent(ToV8PersistentCallbackFunction(callback)),
- nullptr, nullptr));
+ ->PostTask(FROM_HERE,
+ WTF::Bind(&V8BlobCallback::InvokeAndReportException,
+ WrapPersistent(callback), nullptr, nullptr));
return;
}
- TimeTicks start_time = WTF::CurrentTimeTicks();
+ base::TimeTicks start_time = base::TimeTicks::Now();
double quality = kUndefinedQualityValue;
if (!quality_argument.IsEmpty()) {
v8::Local<v8::Value> v8_value = quality_argument.V8Value();
@@ -976,12 +1011,9 @@ void HTMLCanvasElement::toBlob(V8BlobCallback* callback,
} else {
GetDocument()
.GetTaskRunner(TaskType::kCanvasBlobSerialization)
- ->PostTask(
- FROM_HERE,
- WTF::Bind(&V8PersistentCallbackFunction<
- V8BlobCallback>::InvokeAndReportException,
- WrapPersistent(ToV8PersistentCallbackFunction(callback)),
- nullptr, nullptr));
+ ->PostTask(FROM_HERE,
+ WTF::Bind(&V8BlobCallback::InvokeAndReportException,
+ WrapPersistent(callback), nullptr, nullptr));
}
}
@@ -1023,6 +1055,11 @@ bool HTMLCanvasElement::ShouldAccelerate(AccelerationCriteria criteria) const {
if (context_ && !Is2d())
return false;
+ // The command line flag --disable-accelerated-2d-canvas toggles this option
+ if (!RuntimeEnabledFeatures::Accelerated2dCanvasEnabled()) {
+ return false;
+ }
+
// The following is necessary for handling the special case of canvases in
// the dev tools overlay, which run in a process that supports accelerated
// 2d canvas but in a special compositing context that does not.
@@ -1086,9 +1123,6 @@ HTMLCanvasElement::CreateAccelerated2dBuffer() {
if (!surface->IsValid())
return nullptr;
- if (MemoryPressureListenerRegistry::IsLowEndDevice())
- surface->DisableDeferral(kDisableDeferralReasonLowEndDevice);
-
return surface;
}
@@ -1154,11 +1188,6 @@ void HTMLCanvasElement::Trace(Visitor* visitor) {
HTMLElement::Trace(visitor);
}
-void HTMLCanvasElement::DisableDeferral(DisableDeferralReason reason) {
- if (canvas2d_bridge_)
- canvas2d_bridge_->DisableDeferral(reason);
-}
-
Canvas2DLayerBridge* HTMLCanvasElement::GetOrCreateCanvas2DLayerBridge() {
DCHECK(Is2d());
if (!canvas2d_bridge_ && !did_fail_to_create_resource_provider_) {
@@ -1249,7 +1278,7 @@ scoped_refptr<Image> HTMLCanvasElement::GetSourceImageForCanvas(
}
if (!context_) {
- scoped_refptr<Image> result = CreateTransparentImage(Size());
+ scoped_refptr<Image> result = GetTransparentImage();
*status = result ? kNormalSourceImageStatus : kInvalidSourceImageStatus;
return result;
}
@@ -1258,7 +1287,7 @@ scoped_refptr<Image> HTMLCanvasElement::GetSourceImageForCanvas(
*status = kNormalSourceImageStatus;
scoped_refptr<Image> result = context_->GetImage(hint);
if (!result)
- result = CreateTransparentImage(Size());
+ result = GetTransparentImage();
*status = result ? kNormalSourceImageStatus : kInvalidSourceImageStatus;
return result;
}
@@ -1274,7 +1303,7 @@ scoped_refptr<Image> HTMLCanvasElement::GetSourceImageForCanvas(
if (ResourceProvider())
image = ResourceProvider()->Snapshot();
else
- image = CreateTransparentImage(Size());
+ image = GetTransparentImage();
} else {
if (canvas_heuristic_parameters::kDisableAccelerationToAvoidReadbacks &&
!RuntimeEnabledFeatures::Canvas2dFixedRenderingModeEnabled() &&
@@ -1285,7 +1314,7 @@ scoped_refptr<Image> HTMLCanvasElement::GetSourceImageForCanvas(
}
image = RenderingContext()->GetImage(hint);
if (!image)
- image = CreateTransparentImage(Size());
+ image = GetTransparentImage();
}
if (image)
@@ -1409,7 +1438,7 @@ bool HTMLCanvasElement::IsSupportedInteractiveCanvasFallback(
}
HitTestCanvasResult* HTMLCanvasElement::GetControlAndIdIfHitRegionExists(
- const LayoutPoint& location) {
+ const PhysicalOffset& location) {
if (Is2d())
return context_->GetControlAndIdIfHitRegionExists(location);
return MakeGarbageCollected<HitTestCanvasResult>(String(), nullptr);
@@ -1551,6 +1580,12 @@ bool HTMLCanvasElement::HasImageBitmapContext() const {
return (type == CanvasRenderingContext::kContextImageBitmap);
}
+scoped_refptr<Image> HTMLCanvasElement::GetTransparentImage() {
+ if (!transparent_image_ || transparent_image_.get()->Size() != Size())
+ transparent_image_ = CreateTransparentImage(Size());
+ return transparent_image_;
+}
+
cc::Layer* HTMLCanvasElement::ContentsCcLayer() const {
if (surface_layer_bridge_)
return surface_layer_bridge_->GetCcLayer();
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 161f84bf55b..675071b3e9b 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
@@ -49,6 +49,7 @@
#include "third_party/blink/renderer/platform/graphics/canvas_resource_provider.h"
#include "third_party/blink/renderer/platform/graphics/graphics_types.h"
#include "third_party/blink/renderer/platform/graphics/graphics_types_3d.h"
+#include "third_party/blink/renderer/platform/graphics/image.h"
#include "third_party/blink/renderer/platform/graphics/offscreen_canvas_placeholder.h"
#include "third_party/blink/renderer/platform/graphics/surface_layer_bridge.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
@@ -69,7 +70,6 @@ class CanvasRenderingContextFactory;
class GraphicsContext;
class HitTestCanvasResult;
class HTMLCanvasElement;
-class Image;
class ImageBitmapOptions;
class IntSize;
@@ -159,8 +159,6 @@ class CORE_EXPORT HTMLCanvasElement final
const PhysicalRect&,
bool flatten_composited_layers);
- void DisableDeferral(DisableDeferralReason);
-
CanvasRenderingContext* RenderingContext() const override {
return context_.Get();
}
@@ -168,8 +166,6 @@ class CORE_EXPORT HTMLCanvasElement final
bool OriginClean() const override;
void SetOriginTainted() override { origin_clean_ = false; }
- bool IsAnimated2d() const;
-
Canvas2DLayerBridge* GetCanvas2DLayerBridge() {
return canvas2d_bridge_.get();
}
@@ -227,6 +223,7 @@ class CORE_EXPORT HTMLCanvasElement final
bool LowLatencyEnabled() const override { return !!frame_dispatcher_; }
CanvasResourceProvider* GetOrCreateCanvasResourceProvider(
AccelerationHint hint) override;
+ bool IsPrinting() const override;
void DisableAcceleration(std::unique_ptr<Canvas2DLayerBridge>
unaccelerated_bridge_used_for_testing = nullptr);
@@ -259,7 +256,7 @@ class CORE_EXPORT HTMLCanvasElement final
// For Canvas HitRegions
bool IsSupportedInteractiveCanvasFallback(const Element&);
- HitTestCanvasResult* GetControlAndIdIfHitRegionExists(const LayoutPoint&);
+ HitTestCanvasResult* GetControlAndIdIfHitRegionExists(const PhysicalOffset&);
String GetIdFromControl(const Element*);
// For OffscreenCanvas that controls this html canvas element
@@ -356,6 +353,9 @@ class CORE_EXPORT HTMLCanvasElement final
// ImageBitmapRenderingContextBase.
bool HasImageBitmapContext() const;
+ // Returns the transparent image resource for this canvas.
+ scoped_refptr<Image> GetTransparentImage();
+
CanvasRenderingContext* GetCanvasRenderingContextInternal(
const String&,
const CanvasContextCreationAttributesCore&);
@@ -406,6 +406,7 @@ class CORE_EXPORT HTMLCanvasElement final
mutable bool gpu_readback_invoked_in_current_frame_;
int gpu_readback_successive_frames_;
+ scoped_refptr<Image> transparent_image_ = nullptr;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/canvas/html_canvas_element.idl b/chromium/third_party/blink/renderer/core/html/canvas/html_canvas_element.idl
index 52b74257efe..34926c8807e 100644
--- a/chromium/third_party/blink/renderer/core/html/canvas/html_canvas_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/canvas/html_canvas_element.idl
@@ -24,9 +24,11 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-// https://html.spec.whatwg.org/C/#the-canvas-element
-[HTMLConstructor]
-interface HTMLCanvasElement : HTMLElement
+// https://html.spec.whatwg.org/multipage/canvas.html#htmlcanvaselement
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLCanvasElement : HTMLElement
{
// Note: Due to dependecies on modules, getContext is defined in a partial
// interface in html_canvas_element_module.idl
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 34790e46fa2..c6d0da77ce5 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
@@ -6,11 +6,11 @@
#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/imagebitmap/image_bitmap.h"
#include "third_party/blink/renderer/core/layout/layout_object.h"
#include "third_party/blink/renderer/core/loader/image_loader.h"
#include "third_party/blink/renderer/core/svg/graphics/svg_image_for_container.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/canvas/text_metrics.idl b/chromium/third_party/blink/renderer/core/html/canvas/text_metrics.idl
index 367d5d533de..a3b85136499 100644
--- a/chromium/third_party/blink/renderer/core/html/canvas/text_metrics.idl
+++ b/chromium/third_party/blink/renderer/core/html/canvas/text_metrics.idl
@@ -25,19 +25,19 @@
// https://html.spec.whatwg.org/C/#textmetrics
-// TODO(foolip): Exposed=(Window,Worker)
+[Exposed=(Window,Worker)]
interface TextMetrics {
// x-direction
readonly attribute double width; // advance width
[RuntimeEnabled=ExtendedTextMetrics] readonly attribute FrozenArray<double> advances;
- [RuntimeEnabled=ExtendedTextMetrics] readonly attribute double actualBoundingBoxLeft;
- [RuntimeEnabled=ExtendedTextMetrics] readonly attribute double actualBoundingBoxRight;
+ readonly attribute double actualBoundingBoxLeft;
+ readonly attribute double actualBoundingBoxRight;
// y-direction
[RuntimeEnabled=ExtendedTextMetrics] readonly attribute double fontBoundingBoxAscent;
[RuntimeEnabled=ExtendedTextMetrics] readonly attribute double fontBoundingBoxDescent;
- [RuntimeEnabled=ExtendedTextMetrics] readonly attribute double actualBoundingBoxAscent;
- [RuntimeEnabled=ExtendedTextMetrics] readonly attribute double actualBoundingBoxDescent;
+ readonly attribute double actualBoundingBoxAscent;
+ readonly attribute double actualBoundingBoxDescent;
[RuntimeEnabled=ExtendedTextMetrics] readonly attribute double emHeightAscent;
[RuntimeEnabled=ExtendedTextMetrics] readonly attribute double emHeightDescent;
[RuntimeEnabled=ExtendedTextMetrics] Baselines getBaselines();
diff --git a/chromium/third_party/blink/renderer/core/html/custom/ce_reactions_scope.h b/chromium/third_party/blink/renderer/core/html/custom/ce_reactions_scope.h
index 650d010c4b1..c3bf1ee0507 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/ce_reactions_scope.h
+++ b/chromium/third_party/blink/renderer/core/html/custom/ce_reactions_scope.h
@@ -8,7 +8,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
namespace blink {
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 ccf22bf4f98..172a3dc7eb8 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
@@ -9,7 +9,7 @@
#include "third_party/blink/renderer/core/dom/create_element_flags.h"
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/platform/text/character.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/ascii_ctype.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
diff --git a/chromium/third_party/blink/renderer/core/html/custom/custom_element_definition_builder.h b/chromium/third_party/blink/renderer/core/html/custom/custom_element_definition_builder.h
index eab6ef04d00..6a61667fac6 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/custom_element_definition_builder.h
+++ b/chromium/third_party/blink/renderer/core/html/custom/custom_element_definition_builder.h
@@ -9,7 +9,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/css/css_style_sheet.h"
#include "third_party/blink/renderer/core/html/custom/custom_element_definition.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 59e781b4945..ba8b0301f0a 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
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/dom/element.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_table_deleted_value_type.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
diff --git a/chromium/third_party/blink/renderer/core/html/custom/custom_element_reaction_factory.h b/chromium/third_party/blink/renderer/core/html/custom/custom_element_reaction_factory.h
index edb0e1cbfb2..177bcd7e207 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/custom_element_reaction_factory.h
+++ b/chromium/third_party/blink/renderer/core/html/custom/custom_element_reaction_factory.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_HTML_CUSTOM_CUSTOM_ELEMENT_REACTION_FACTORY_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_CUSTOM_CUSTOM_ELEMENT_REACTION_FACTORY_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
namespace blink {
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 b0d1320dc90..4f3c7506adf 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
@@ -5,7 +5,6 @@
#include "third_party/blink/renderer/core/html/custom/custom_element_reaction_queue.h"
#include <initializer_list>
-#include <vector>
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/core/html/custom/custom_element_reaction.h"
#include "third_party/blink/renderer/core/html/custom/custom_element_reaction_test_helpers.h"
@@ -16,7 +15,7 @@
namespace blink {
TEST(CustomElementReactionQueueTest, invokeReactions_one) {
- std::vector<char> log;
+ Vector<char> log;
CustomElementReactionQueue* queue =
MakeGarbageCollected<CustomElementReactionQueue>();
HeapVector<Member<Command>>* commands =
@@ -25,12 +24,12 @@ TEST(CustomElementReactionQueueTest, invokeReactions_one) {
queue->Add(*MakeGarbageCollected<TestReaction>(commands));
Element* test_element = CreateElement(AtomicString("my-element"));
queue->InvokeReactions(*test_element);
- EXPECT_EQ(log, std::vector<char>({'a'}))
+ EXPECT_EQ(log, Vector<char>({'a'}))
<< "the reaction should have been invoked";
}
TEST(CustomElementReactionQueueTest, invokeReactions_many) {
- std::vector<char> log;
+ Vector<char> log;
CustomElementReactionQueue* queue =
MakeGarbageCollected<CustomElementReactionQueue>();
{
@@ -53,12 +52,12 @@ TEST(CustomElementReactionQueueTest, invokeReactions_many) {
}
Element* test_element = CreateElement(AtomicString("my-element"));
queue->InvokeReactions(*test_element);
- EXPECT_EQ(log, std::vector<char>({'a', 'b', 'c'}))
+ EXPECT_EQ(log, Vector<char>({'a', 'b', 'c'}))
<< "the reaction should have been invoked";
}
TEST(CustomElementReactionQueueTest, invokeReactions_recursive) {
- std::vector<char> log;
+ Vector<char> log;
CustomElementReactionQueue* queue =
MakeGarbageCollected<CustomElementReactionQueue>();
@@ -87,12 +86,12 @@ TEST(CustomElementReactionQueueTest, invokeReactions_recursive) {
queue->Add(*first);
Element* test_element = CreateElement(AtomicString("my-element"));
queue->InvokeReactions(*test_element);
- EXPECT_EQ(log, std::vector<char>({'a', 'b', 'c'}))
+ EXPECT_EQ(log, Vector<char>({'a', 'b', 'c'}))
<< "the reactions should have been invoked";
}
TEST(CustomElementReactionQueueTest, clear_duringInvoke) {
- std::vector<char> log;
+ Vector<char> log;
CustomElementReactionQueue* queue =
MakeGarbageCollected<CustomElementReactionQueue>();
@@ -119,7 +118,7 @@ TEST(CustomElementReactionQueueTest, clear_duringInvoke) {
Element* test_element = CreateElement(AtomicString("my-element"));
queue->InvokeReactions(*test_element);
- EXPECT_EQ(log, std::vector<char>({'a'}))
+ EXPECT_EQ(log, Vector<char>({'a'}))
<< "only 'a' should be logged; the second log should have been cleared";
}
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 b46132e7054..7bfb1712cfe 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
@@ -5,7 +5,6 @@
#include "third_party/blink/renderer/core/html/custom/custom_element_reaction_stack.h"
#include <initializer_list>
-#include <vector>
#include "base/macros.h"
#include "testing/gtest/include/gtest/gtest.h"
@@ -17,7 +16,7 @@
namespace blink {
TEST(CustomElementReactionStackTest, one) {
- std::vector<char> log;
+ Vector<char> log;
CustomElementReactionStack* stack =
MakeGarbageCollected<CustomElementReactionStack>();
@@ -29,12 +28,12 @@ TEST(CustomElementReactionStackTest, one) {
*MakeGarbageCollected<TestReaction>(commands));
stack->PopInvokingReactions();
- EXPECT_EQ(log, std::vector<char>({'a'}))
+ EXPECT_EQ(log, Vector<char>({'a'}))
<< "popping the reaction stack should run reactions";
}
TEST(CustomElementReactionStackTest, multipleElements) {
- std::vector<char> log;
+ Vector<char> log;
CustomElementReactionStack* stack =
MakeGarbageCollected<CustomElementReactionStack>();
@@ -55,12 +54,12 @@ TEST(CustomElementReactionStackTest, multipleElements) {
}
stack->PopInvokingReactions();
- EXPECT_EQ(log, std::vector<char>({'a', 'b'}))
+ EXPECT_EQ(log, Vector<char>({'a', 'b'}))
<< "reactions should run in the order the elements queued";
}
TEST(CustomElementReactionStackTest, popTopEmpty) {
- std::vector<char> log;
+ Vector<char> log;
CustomElementReactionStack* stack =
MakeGarbageCollected<CustomElementReactionStack>();
@@ -73,12 +72,12 @@ TEST(CustomElementReactionStackTest, popTopEmpty) {
stack->Push();
stack->PopInvokingReactions();
- EXPECT_EQ(log, std::vector<char>())
+ EXPECT_EQ(log, Vector<char>())
<< "popping the empty top-of-stack should not run any reactions";
}
TEST(CustomElementReactionStackTest, popTop) {
- std::vector<char> log;
+ Vector<char> log;
CustomElementReactionStack* stack =
MakeGarbageCollected<CustomElementReactionStack>();
@@ -100,12 +99,12 @@ TEST(CustomElementReactionStackTest, popTop) {
}
stack->PopInvokingReactions();
- EXPECT_EQ(log, std::vector<char>({'b'}))
+ EXPECT_EQ(log, Vector<char>({'b'}))
<< "popping the top-of-stack should only run top-of-stack reactions";
}
TEST(CustomElementReactionStackTest, requeueingDoesNotReorderElements) {
- std::vector<char> log;
+ Vector<char> log;
Element& element = *CreateElement("a");
@@ -135,12 +134,12 @@ TEST(CustomElementReactionStackTest, requeueingDoesNotReorderElements) {
}
stack->PopInvokingReactions();
- EXPECT_EQ(log, std::vector<char>({'a', 'b', 'z'}))
+ EXPECT_EQ(log, Vector<char>({'a', 'b', 'z'}))
<< "reactions should run together in the order elements were queued";
}
TEST(CustomElementReactionStackTest, oneReactionQueuePerElement) {
- std::vector<char> log;
+ Vector<char> log;
Element& element = *CreateElement("a");
@@ -178,12 +177,12 @@ TEST(CustomElementReactionStackTest, oneReactionQueuePerElement) {
}
stack->PopInvokingReactions();
- EXPECT_EQ(log, std::vector<char>({'y', 'a', 'b'}))
+ EXPECT_EQ(log, Vector<char>({'y', 'a', 'b'}))
<< "reactions should run together in the order elements were queued";
log.clear();
stack->PopInvokingReactions();
- EXPECT_EQ(log, std::vector<char>({'z'})) << "reactions should be run once";
+ EXPECT_EQ(log, Vector<char>({'z'})) << "reactions should be run once";
}
class EnqueueToStack : public Command {
@@ -212,7 +211,7 @@ class EnqueueToStack : public Command {
};
TEST(CustomElementReactionStackTest, enqueueFromReaction) {
- std::vector<char> log;
+ Vector<char> log;
Element& element = *CreateElement("a");
@@ -232,9 +231,9 @@ TEST(CustomElementReactionStackTest, enqueueFromReaction) {
}
stack->PopInvokingReactions();
- EXPECT_EQ(log, std::vector<char>({'a'})) << "enqueued reaction from another "
- "reaction should run in the same "
- "invoke";
+ EXPECT_EQ(log, Vector<char>({'a'})) << "enqueued reaction from another "
+ "reaction should run in the same "
+ "invoke";
}
} // namespace blink
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 a746fe3dbb8..b240c4d2503 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
@@ -9,7 +9,6 @@
#include <initializer_list>
#include <memory>
-#include <vector>
#include "base/macros.h"
#include "testing/gtest/include/gtest/gtest.h"
@@ -60,13 +59,13 @@ class Unreached : public Command {
class Log : public Command {
public:
- Log(char what, std::vector<char>& where) : what_(what), where_(where) {}
+ Log(char what, Vector<char>& where) : what_(what), where_(where) {}
~Log() override = default;
void Run(Element&) override { where_.push_back(what_); }
private:
char what_;
- std::vector<char>& where_;
+ Vector<char>& where_;
DISALLOW_COPY_AND_ASSIGN(Log);
};
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 d6fae1df0cb..d440e2a250f 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
@@ -17,7 +17,6 @@
#include "third_party/blink/renderer/core/dom/element_traversal.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/custom/ce_reactions_scope.h"
#include "third_party/blink/renderer/core/html/custom/custom_element.h"
#include "third_party/blink/renderer/core/html/custom/custom_element_definition.h"
@@ -29,7 +28,8 @@
#include "third_party/blink/renderer/core/html_element_type_helpers.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -37,11 +37,10 @@ namespace {
void CollectUpgradeCandidateInNode(Node& root,
HeapVector<Member<Element>>& candidates) {
- if (root.IsElementNode()) {
- Element& root_element = ToElement(root);
- if (root_element.GetCustomElementState() == CustomElementState::kUndefined)
+ if (auto* root_element = DynamicTo<Element>(root)) {
+ if (root_element->GetCustomElementState() == CustomElementState::kUndefined)
candidates.push_back(root_element);
- if (auto* shadow_root = root_element.GetShadowRoot()) {
+ if (auto* shadow_root = root_element->GetShadowRoot()) {
if (shadow_root->GetType() != ShadowRootType::kUserAgent)
CollectUpgradeCandidateInNode(*shadow_root, candidates);
}
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 ce51bc44a34..986991b7968 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
@@ -4,6 +4,7 @@
// https://html.spec.whatwg.org/C/custom-elements.html#customelementregistry
+[Exposed=Window]
interface CustomElementRegistry {
[CallWith=ScriptState, CEReactions, CustomElementCallbacks, RaisesException, MeasureAs=CustomElementRegistryDefine] void define(DOMString name, CustomElementConstructor constructor, optional ElementDefinitionOptions options);
any get(DOMString name);
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 6f5062b63a8..af5cc4358fe 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
@@ -20,7 +20,6 @@
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
#include <utility>
-#include <vector>
namespace blink {
@@ -171,7 +170,7 @@ class CreateElement {
AtomicString namespace_uri_;
AtomicString local_name_;
AtomicString is_value_;
- std::vector<std::pair<QualifiedName, AtomicString>> attributes_;
+ Vector<std::pair<QualifiedName, AtomicString>> attributes_;
};
} // namespace blink
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 0e045400c20..f383846bb03 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
@@ -65,8 +65,9 @@ void CustomElementUpgradeSorter::Visit(HeapVector<Member<Element>>* result,
const ChildSet::iterator& it) {
if (it == children.end())
return;
- if (it->Get()->IsElementNode() && elements_->Contains(ToElement(*it)))
- result->push_back(ToElement(*it));
+ auto* element = DynamicTo<Element>(it->Get());
+ if (element && elements_->Contains(element))
+ result->push_back(*element);
Sorted(result, *it);
children.erase(it);
}
@@ -86,8 +87,8 @@ void CustomElementUpgradeSorter::Sorted(HeapVector<Member<Element>>* result,
// TODO(dominicc): When custom elements are used in UA shadow
// roots, expand this to include UA shadow roots.
- ShadowRoot* shadow_root =
- parent->IsElementNode() ? ToElement(parent)->AuthorShadowRoot() : nullptr;
+ auto* element = DynamicTo<Element>(parent);
+ ShadowRoot* shadow_root = element ? element->AuthorShadowRoot() : nullptr;
if (shadow_root)
Visit(result, *children, children->find(shadow_root));
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 4e10b8db5ee..7f977b897a1 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
@@ -32,13 +32,13 @@
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/element.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/custom/v0_custom_element_microtask_run_queue.h"
#include "third_party/blink/renderer/core/html/custom/v0_custom_element_observer.h"
#include "third_party/blink/renderer/core/html/custom/v0_custom_element_scheduler.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/mathml_names.h"
#include "third_party/blink/renderer/core/svg_names.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element.h b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element.h
index 1693319db99..3fffa8901fd 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element.h
+++ b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element.h
@@ -33,7 +33,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/html/custom/v0_custom_element_definition.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
diff --git a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_descriptor_hash.h b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_descriptor_hash.h
index 64fb2863b5a..103ffc488a3 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_descriptor_hash.h
+++ b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_descriptor_hash.h
@@ -32,7 +32,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_CUSTOM_V0_CUSTOM_ELEMENT_DESCRIPTOR_HASH_H_
#include "third_party/blink/renderer/core/html/custom/v0_custom_element_descriptor.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.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/atomic_string_hash.h"
diff --git a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_exception.h b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_exception.h
index aa75b5d7d70..2727385ca95 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_exception.h
+++ b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_exception.h
@@ -31,7 +31,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_HTML_CUSTOM_V0_CUSTOM_ELEMENT_EXCEPTION_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_CUSTOM_V0_CUSTOM_ELEMENT_EXCEPTION_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
diff --git a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_microtask_import_step.cc b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_microtask_import_step.cc
index 43450d1c31b..f4025118dc0 100644
--- a/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_microtask_import_step.cc
+++ b/chromium/third_party/blink/renderer/core/html/custom/v0_custom_element_microtask_import_step.cc
@@ -80,7 +80,7 @@ void V0CustomElementMicrotaskImportStep::Trace(Visitor* visitor) {
void V0CustomElementMicrotaskImportStep::Show(unsigned indent) {
fprintf(stderr, "%*sImport(wait=%d sync=%d, url=%s)\n", indent, "",
ShouldWaitForImport(), import_ && import_->IsSync(),
- import_ ? import_->Url().GetString().Utf8().data() : "null");
+ import_ ? import_->Url().GetString().Utf8().c_str() : "null");
queue_->Show(indent + 1);
}
#endif
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 9b96204dafb..cbc1372e12a 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
@@ -33,12 +33,12 @@
#include "third_party/blink/renderer/bindings/core/v8/v0_custom_element_constructor_builder.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/use_counter.h"
#include "third_party/blink/renderer/core/html/custom/custom_element_registry.h"
#include "third_party/blink/renderer/core/html/custom/v0_custom_element_exception.h"
#include "third_party/blink/renderer/core/html/custom/v0_custom_element_registration_context.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/svg_names.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
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 c1d194df773..12c2b7d0e2b 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
@@ -32,11 +32,11 @@
#include "third_party/blink/renderer/core/html/forms/base_checkable_input_type.h"
#include "third_party/blink/renderer/core/events/keyboard_event.h"
-#include "third_party/blink/renderer/core/frame/use_counter.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/html_input_element.h"
#include "third_party/blink/renderer/core/html_names.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
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 8d4cdb426a4..54f77cc1461 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
@@ -109,7 +109,8 @@ String BaseTemporalInputType::RangeUnderflowText(const Decimal& minimum) const {
}
Decimal BaseTemporalInputType::DefaultValueForStepUp() const {
- return Decimal::FromDouble(ConvertToLocalTime(CurrentTimeMS()));
+ return Decimal::FromDouble(
+ ConvertToLocalTime(base::Time::Now().ToDoubleT() * 1000.0));
}
bool BaseTemporalInputType::IsSteppable() const {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/base_temporal_input_type.h b/chromium/third_party/blink/renderer/core/html/forms/base_temporal_input_type.h
index c48bf308795..a142ad16a70 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/base_temporal_input_type.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/base_temporal_input_type.h
@@ -33,7 +33,7 @@
#include "third_party/blink/renderer/core/html/forms/date_time_edit_element.h"
#include "third_party/blink/renderer/core/html/forms/input_type.h"
-#include "third_party/blink/renderer/platform/date_components.h"
+#include "third_party/blink/renderer/platform/text/date_components.h"
namespace blink {
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 207e4c835cf..b70daab459f 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
@@ -42,8 +42,8 @@ ClearButtonElement::ClearButtonElement(Document& document,
setAttribute(kIdAttr, shadow_element_names::ClearButton());
}
-void ClearButtonElement::DetachLayoutTree(const AttachContext& context) {
- HTMLDivElement::DetachLayoutTree(context);
+void ClearButtonElement::DetachLayoutTree(bool performing_reattach) {
+ HTMLDivElement::DetachLayoutTree(performing_reattach);
}
void ClearButtonElement::DefaultEventHandler(Event& event) {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/clear_button_element.h b/chromium/third_party/blink/renderer/core/html/forms/clear_button_element.h
index f92cdf97073..1afa8214130 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/clear_button_element.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/clear_button_element.h
@@ -48,7 +48,7 @@ class ClearButtonElement final : public HTMLDivElement {
void Trace(Visitor*) override;
private:
- void DetachLayoutTree(const AttachContext& = AttachContext()) override;
+ void DetachLayoutTree(bool performing_reattach) override;
bool IsMouseFocusable() const override { return false; }
void DefaultEventHandler(Event&) override;
bool IsClearButtonElement() const override;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/color_chooser_popup_ui_controller.cc b/chromium/third_party/blink/renderer/core/html/forms/color_chooser_popup_ui_controller.cc
index 3187c0b507a..f81ad933734 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/color_chooser_popup_ui_controller.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/color_chooser_popup_ui_controller.cc
@@ -65,7 +65,8 @@ void ColorChooserPopupUIController::Trace(Visitor* visitor) {
}
void ColorChooserPopupUIController::OpenUI() {
- if (client_->ShouldShowSuggestions())
+ if (client_->ShouldShowSuggestions() ||
+ RuntimeEnabledFeatures::FormControlsRefreshEnabled())
OpenPopup();
else
OpenColorChooser();
@@ -81,6 +82,45 @@ AXObject* ColorChooserPopupUIController::RootAXObject() {
}
void ColorChooserPopupUIController::WriteDocument(SharedBuffer* data) {
+ if (client_->ShouldShowSuggestions()) {
+ WriteColorSuggestionPickerDocument(data);
+ } else {
+ WriteColorPickerDocument(data);
+ }
+}
+
+void ColorChooserPopupUIController::WriteColorPickerDocument(
+ SharedBuffer* data) {
+ DCHECK(RuntimeEnabledFeatures::FormControlsRefreshEnabled());
+
+ IntRect anchor_rect_in_screen = chrome_client_->ViewportToScreen(
+ client_->ElementRectRelativeToViewport(), frame_->View());
+
+ PagePopupClient::AddString(
+ "<!DOCTYPE html><head><meta charset='UTF-8'><style>\n", data);
+ data->Append(Platform::Current()->GetDataResource("pickerCommon.css"));
+ data->Append(Platform::Current()->GetDataResource("color_picker.css"));
+ PagePopupClient::AddString(
+ "</style></head><body>\n"
+ "<div id='main'>Loading...</div><script>\n"
+ "window.dialogArguments = {\n",
+ data);
+ PagePopupClient::AddProperty("selectedColor",
+ client_->CurrentColor().Serialized(), data);
+ AddProperty("anchorRectInScreen", anchor_rect_in_screen, data);
+ AddProperty("zoomFactor", ZoomFactor(), data);
+ AddProperty("shouldShowColorSuggestionPicker", false, data);
+ PagePopupClient::AddString("};\n", data);
+ data->Append(Platform::Current()->GetDataResource("pickerCommon.js"));
+ data->Append(Platform::Current()->GetDataResource("color_picker.js"));
+ data->Append(Platform::Current()->GetDataResource("color_picker_common.js"));
+ PagePopupClient::AddString("</script></body>\n", data);
+}
+
+void ColorChooserPopupUIController::WriteColorSuggestionPickerDocument(
+ SharedBuffer* data) {
+ DCHECK(client_->ShouldShowSuggestions());
+
Vector<String> suggestion_values;
for (auto& suggestion : client_->Suggestions())
suggestion_values.push_back(Color(suggestion->color).Serialized());
@@ -92,20 +132,35 @@ void ColorChooserPopupUIController::WriteDocument(SharedBuffer* data) {
data->Append(Platform::Current()->GetDataResource("pickerCommon.css"));
data->Append(
Platform::Current()->GetDataResource("colorSuggestionPicker.css"));
+ if (RuntimeEnabledFeatures::FormControlsRefreshEnabled()) {
+ data->Append(Platform::Current()->GetDataResource("color_picker.css"));
+ }
PagePopupClient::AddString(
- "</style></head><body><div id=main>Loading...</div><script>\n"
+ "</style></head><body>\n"
+ "<div id='main'>Loading...</div><script>\n"
"window.dialogArguments = {\n",
data);
PagePopupClient::AddProperty("values", suggestion_values, data);
PagePopupClient::AddProperty(
"otherColorLabel",
GetLocale().QueryString(WebLocalizedString::kOtherColorLabel), data);
+ if (RuntimeEnabledFeatures::FormControlsRefreshEnabled()) {
+ PagePopupClient::AddProperty("selectedColor",
+ client_->CurrentColor().Serialized(), data);
+ }
AddProperty("anchorRectInScreen", anchor_rect_in_screen, data);
AddProperty("zoomFactor", ZoomFactor(), data);
+ AddProperty("shouldShowColorSuggestionPicker", true, data);
+ AddProperty("isFormControlsRefreshEnabled",
+ RuntimeEnabledFeatures::FormControlsRefreshEnabled(), data);
PagePopupClient::AddString("};\n", data);
data->Append(Platform::Current()->GetDataResource("pickerCommon.js"));
data->Append(
Platform::Current()->GetDataResource("colorSuggestionPicker.js"));
+ if (RuntimeEnabledFeatures::FormControlsRefreshEnabled()) {
+ data->Append(Platform::Current()->GetDataResource("color_picker.js"));
+ }
+ data->Append(Platform::Current()->GetDataResource("color_picker_common.js"));
PagePopupClient::AddString("</script></body>\n", data);
}
@@ -120,8 +175,10 @@ void ColorChooserPopupUIController::SetValueAndClosePopup(
DCHECK(client_);
if (num_value == kColorPickerPopupActionSetValue)
SetValue(string_value);
- if (num_value == kColorPickerPopupActionChooseOtherColor)
+ if (num_value == kColorPickerPopupActionChooseOtherColor) {
+ DCHECK(!RuntimeEnabledFeatures::FormControlsRefreshEnabled());
OpenColorChooser();
+ }
CancelPopup();
}
diff --git a/chromium/third_party/blink/renderer/core/html/forms/color_chooser_popup_ui_controller.h b/chromium/third_party/blink/renderer/core/html/forms/color_chooser_popup_ui_controller.h
index 26b8153378a..989446bbbb4 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/color_chooser_popup_ui_controller.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/color_chooser_popup_ui_controller.h
@@ -69,6 +69,9 @@ class CORE_EXPORT ColorChooserPopupUIController final
void OpenPopup();
void Dispose();
+ void WriteColorPickerDocument(SharedBuffer*);
+ void WriteColorSuggestionPickerDocument(SharedBuffer*);
+
Member<ChromeClient> chrome_client_;
PagePopup* popup_;
Locale& locale_;
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 99d106eb319..e750e7387d6 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
@@ -36,7 +36,6 @@
#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/local_frame_view.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/frame/web_feature.h"
#include "third_party/blink/renderer/core/html/forms/color_chooser.h"
#include "third_party/blink/renderer/core/html/forms/html_data_list_element.h"
@@ -50,6 +49,7 @@
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/graphics/color.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
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 999f22433f2..6f22f11f4ad 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
@@ -36,7 +36,7 @@
#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/platform/date_components.h"
+#include "third_party/blink/renderer/platform/text/date_components.h"
#include "third_party/blink/renderer/platform/text/platform_locale.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/date_time_chooser.h b/chromium/third_party/blink/renderer/core/html/forms/date_time_chooser.h
index 59c3199c6e4..c6c5e749c1b 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/date_time_chooser.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/date_time_chooser.h
@@ -36,7 +36,7 @@
#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/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
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 f87435b68da..8b37c16592a 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
@@ -38,8 +38,8 @@
#include "third_party/blink/renderer/core/layout/layout_theme.h"
#include "third_party/blink/renderer/core/page/chrome_client.h"
#include "third_party/blink/renderer/core/page/page_popup.h"
-#include "third_party/blink/renderer/platform/date_components.h"
#include "third_party/blink/renderer/platform/language.h"
+#include "third_party/blink/renderer/platform/text/date_components.h"
#include "third_party/blink/renderer/platform/text/platform_locale.h"
namespace blink {
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 f280ef926b6..251a4be296c 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
@@ -29,7 +29,6 @@
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/text.h"
#include "third_party/blink/renderer/core/events/mouse_event.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/forms/date_time_field_elements.h"
#include "third_party/blink/renderer/core/html/forms/date_time_fields_state.h"
#include "third_party/blink/renderer/core/html/shadow/shadow_element_names.h"
@@ -38,6 +37,7 @@
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/fonts/font_cache.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/text/date_time_format.h"
#include "third_party/blink/renderer/platform/text/platform_locale.h"
#include "third_party/blink/renderer/platform/wtf/date_math.h"
@@ -548,8 +548,8 @@ void DateTimeEditElement::Trace(Visitor* visitor) {
}
inline Element* DateTimeEditElement::FieldsWrapperElement() const {
- DCHECK(firstChild());
- return ToElementOrDie(firstChild());
+ CHECK(!firstChild() || IsA<Element>(firstChild()));
+ return To<Element>(firstChild());
}
void DateTimeEditElement::AddField(DateTimeFieldElement* field) {
@@ -580,9 +580,9 @@ scoped_refptr<ComputedStyle> DateTimeEditElement::CustomStyleForLayoutObject() {
float width = 0;
for (Node* child = FieldsWrapperElement()->firstChild(); child;
child = child->nextSibling()) {
- if (!child->IsElementNode())
+ auto* child_element = DynamicTo<Element>(child);
+ if (!child_element)
continue;
- Element* child_element = ToElement(child);
if (child_element->IsDateTimeFieldElement()) {
// We need to pass the ComputedStyle of this element because child
// elements can't resolve inherited style at this timing.
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 05cf99d3ce2..4cf46d4a15f 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
@@ -30,8 +30,8 @@
#include "third_party/blink/public/platform/web_focus_type.h"
#include "third_party/blink/renderer/core/html/forms/date_time_field_element.h"
#include "third_party/blink/renderer/core/html/forms/step_range.h"
-#include "third_party/blink/renderer/platform/date_components.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/text/date_components.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 ae5485f2ca7..1c0b62e1edd 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
@@ -26,7 +26,7 @@
#include "third_party/blink/renderer/core/html/forms/date_time_field_elements.h"
#include "third_party/blink/renderer/core/html/forms/date_time_fields_state.h"
-#include "third_party/blink/renderer/platform/date_components.h"
+#include "third_party/blink/renderer/platform/text/date_components.h"
#include "third_party/blink/renderer/platform/text/platform_locale.h"
#include "third_party/blink/renderer/platform/wtf/date_math.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
@@ -664,7 +664,8 @@ DateTimeYearFieldElement::DateTimeYearFieldElement(
static int CurrentFullYear() {
DateComponents date;
- date.SetMillisecondsSinceEpochForMonth(ConvertToLocalTime(CurrentTimeMS()));
+ date.SetMillisecondsSinceEpochForMonth(
+ ConvertToLocalTime(base::Time::Now().ToDoubleT() * 1000.0));
return date.FullYear();
}
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 ce097fe4cb5..f5ad133294d 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
@@ -29,7 +29,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/html/forms/date_time_numeric_field_element.h"
#include "third_party/blink/renderer/core/html/forms/date_time_symbolic_field_element.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/date_time_fields_state.h b/chromium/third_party/blink/renderer/core/html/forms/date_time_fields_state.h
index 36020b2a3ed..e9762a6f294 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/date_time_fields_state.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/date_time_fields_state.h
@@ -26,7 +26,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_HTML_FORMS_DATE_TIME_FIELDS_STATE_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_FORMS_DATE_TIME_FIELDS_STATE_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 0f12fd7b870..b0bcc91e08d 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
@@ -36,7 +36,7 @@
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/input_type_names.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
-#include "third_party/blink/renderer/platform/date_components.h"
+#include "third_party/blink/renderer/platform/text/date_components.h"
#include "third_party/blink/renderer/platform/text/platform_locale.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
diff --git a/chromium/third_party/blink/renderer/core/html/forms/date_time_numeric_field_element.h b/chromium/third_party/blink/renderer/core/html/forms/date_time_numeric_field_element.h
index a661fce1ffc..83edb4e3147 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/date_time_numeric_field_element.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/date_time_numeric_field_element.h
@@ -29,7 +29,7 @@
#include "base/macros.h"
#include "third_party/blink/public/platform/web_focus_type.h"
#include "third_party/blink/renderer/core/html/forms/date_time_field_element.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
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 699cd73b648..fd9a06fcb95 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
@@ -82,7 +82,7 @@ String EmailInputType::ConvertEmailAddressToASCII(const ScriptRegexp& regexp,
// Leak |idna| at the end.
UErrorCode error_code = U_ZERO_ERROR;
- static icu::IDNA* idna =
+ static const icu::IDNA* const idna =
icu::IDNA::createUTS46Instance(kIdnaConversionOption, error_code);
DCHECK(idna);
icu::IDNAInfo idna_info;
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 142944f614f..0221f293701 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
@@ -33,7 +33,7 @@
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
-#include "ui/base/ime/mojo/ime_types.mojom-shared.h"
+#include "ui/base/ime/mojo/ime_types.mojom-blink.h"
namespace blink {
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 91ecc914be4..8d0e81e6ca8 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
@@ -123,7 +123,7 @@ void ExternalPopupMenu::Show() {
synthetic_event_ = std::make_unique<WebMouseEvent>();
*synthetic_event_ = *static_cast<const WebMouseEvent*>(current_event);
synthetic_event_->SetType(WebInputEvent::kMouseUp);
- dispatch_event_timer_.StartOneShot(TimeDelta(), FROM_HERE);
+ dispatch_event_timer_.StartOneShot(base::TimeDelta(), FROM_HERE);
// FIXME: show() is asynchronous. If preparing a popup is slow and a
// user released the mouse button before showing the popup, mouseup and
// click events are correctly dispatched. Dispatching the synthetic
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 de158f586b7..b1fda914bc0 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
@@ -182,7 +182,7 @@ TEST_F(ExternalPopupMenuTest, DidAcceptIndex) {
static_cast<ExternalPopupMenu*>(select->Popup());
client->DidAcceptIndex(2);
EXPECT_FALSE(select->PopupIsVisible());
- ASSERT_STREQ("2", menu_list->GetText().Utf8().data());
+ ASSERT_EQ("2", menu_list->GetText().Utf8());
EXPECT_EQ(2, select->selectedIndex());
}
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 1042c13f531..fc4d926f749 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
@@ -36,7 +36,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/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
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 21d8638323c..50e65c47290 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
@@ -29,7 +29,6 @@
#include "third_party/blink/renderer/core/events/keyboard_event.h"
#include "third_party/blink/renderer/core/fileapi/file.h"
#include "third_party/blink/renderer/core/fileapi/file_list.h"
-#include "third_party/blink/renderer/core/frame/use_counter.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/html_input_element.h"
@@ -42,6 +41,7 @@
#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/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.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/wtf/text/string_builder.h"
@@ -323,16 +323,20 @@ void FileInputType::CreateShadowSubtree() {
void FileInputType::DisabledAttributeChanged() {
DCHECK(IsShadowHost(GetElement()));
+ CHECK(!GetElement().UserAgentShadowRoot()->firstChild() ||
+ IsA<Element>(GetElement().UserAgentShadowRoot()->firstChild()));
if (Element* button =
- ToElementOrDie(GetElement().UserAgentShadowRoot()->firstChild()))
+ To<Element>(GetElement().UserAgentShadowRoot()->firstChild()))
button->SetBooleanAttribute(kDisabledAttr,
GetElement().IsDisabledFormControl());
}
void FileInputType::MultipleAttributeChanged() {
DCHECK(IsShadowHost(GetElement()));
+ CHECK(!GetElement().UserAgentShadowRoot()->firstChild() ||
+ IsA<Element>(GetElement().UserAgentShadowRoot()->firstChild()));
if (Element* button =
- ToElementOrDie(GetElement().UserAgentShadowRoot()->firstChild()))
+ To<Element>(GetElement().UserAgentShadowRoot()->firstChild()))
button->setAttribute(
kValueAttr,
AtomicString(GetLocale().QueryString(
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 485a82a4931..82907076088 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
@@ -53,7 +53,7 @@ inline HTMLFormElement* OwnerFormForState(const ListedElement& control) {
}
const AtomicString& ControlType(const ListedElement& control) {
- if (auto* control_element = ToHTMLFormControlElementOrNull(control))
+ if (auto* control_element = DynamicTo<HTMLFormControlElement>(control))
return control_element->type();
return To<ElementInternals>(control).Target().localName();
}
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 0ac1e411a1b..4a5201871f1 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
@@ -26,7 +26,7 @@
#include <memory>
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string_hash.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
diff --git a/chromium/third_party/blink/renderer/core/html/forms/form_controller_test.cc b/chromium/third_party/blink/renderer/core/html/forms/form_controller_test.cc
index 5bf1e877ec9..ed04ac881c0 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/form_controller_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/form_controller_test.cc
@@ -20,7 +20,7 @@ TEST(DocumentStateTest, ToStateVectorConnected) {
Element* html = doc.CreateRawElement(html_names::kHTMLTag);
doc.appendChild(html);
Node* body = html->appendChild(doc.CreateRawElement(html_names::kBodyTag));
- ToElement(body)->SetInnerHTMLFromString("<select form='ff'></select>");
+ To<Element>(body)->SetInnerHTMLFromString("<select form='ff'></select>");
DocumentState* document_state = doc.GetFormController().FormElementsState();
Vector<String> state1 = document_state->ToStateVector();
// <signature>, <control-size>, <form-key>, <name>, <type>, <data-size(0)>
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 260db7620a1..bd44cb04a40 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
@@ -33,10 +33,10 @@
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/fileapi/blob.h"
#include "third_party/blink/renderer/core/fileapi/file.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/forms/form_controller.h"
#include "third_party/blink/renderer/core/html/forms/html_form_element.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/network/form_data_encoder.h"
#include "third_party/blink/renderer/platform/wtf/text/line_ending.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
@@ -226,7 +226,7 @@ void FormData::AppendFromElement(const String& name, const String& value) {
MakeGarbageCollected<Entry>(Normalize(name), Normalize(value)));
}
-CString FormData::Encode(const String& string) const {
+std::string FormData::Encode(const String& string) const {
return encoding_.Encode(string, WTF::kEntitiesForUnencodables);
}
@@ -307,8 +307,8 @@ scoped_refptr<EncodedFormData> FormData::EncodeMultiPartFormData() {
entry->GetBlob()->GetBlobDataHandle());
}
} else {
- CString encoded_value = Encode(entry->Value());
- form_data->AppendData(encoded_value.data(), encoded_value.length());
+ std::string encoded_value = Encode(entry->Value());
+ form_data->AppendData(encoded_value.c_str(), encoded_value.length());
}
form_data->AppendData("\r\n", 2);
}
@@ -359,7 +359,7 @@ File* FormData::Entry::GetFile() const {
String filename = filename_;
if (filename.IsNull())
filename = "blob";
- return File::Create(filename, CurrentTimeMS(),
+ return File::Create(filename, base::Time::Now().ToDoubleT() * 1000.0,
GetBlob()->GetBlobDataHandle());
}
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 48670d9371a..5e9eb525234 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
@@ -84,7 +84,7 @@ class CORE_EXPORT FormData final
// Internal functions.
const WTF::TextEncoding& Encoding() const { return encoding_; }
- CString Encode(const String& key) const;
+ std::string Encode(const String& key) const;
class Entry;
const HeapVector<Member<const Entry>>& Entries() const { return entries_; }
size_t size() const { return entries_.size(); }
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 773f9cffca9..1ae3d941602 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
@@ -31,13 +31,13 @@
#include "third_party/blink/renderer/core/html/forms/hidden_input_type.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/frame/web_feature.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/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/platform/instrumentation/use_counter.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_button_element.idl b/chromium/third_party/blink/renderer/core/html/forms/html_button_element.idl
index e872816f766..9f41e83a751 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_button_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_button_element.idl
@@ -19,8 +19,10 @@
*/
// https://html.spec.whatwg.org/C/#the-button-element
-[HTMLConstructor]
-interface HTMLButtonElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLButtonElement : HTMLElement {
[CEReactions, Reflect] attribute boolean autofocus;
[CEReactions, Reflect] attribute boolean disabled;
[ImplementedAs=formOwner] readonly attribute HTMLFormElement? form;
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 c58ae1d4a65..c5497815d61 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
@@ -33,9 +33,9 @@
#include "third_party/blink/renderer/core/dom/id_target_observer_registry.h"
#include "third_party/blink/renderer/core/dom/node_lists_node_data.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/forms/html_data_list_options_collection.h"
#include "third_party/blink/renderer/core/html_names.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_data_list_element.idl b/chromium/third_party/blink/renderer/core/html/forms/html_data_list_element.idl
index 84358a8a9a4..29c77147b21 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_data_list_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_data_list_element.idl
@@ -29,7 +29,9 @@
*/
// https://html.spec.whatwg.org/C/#the-datalist-element
-[HTMLConstructor]
-interface HTMLDataListElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLDataListElement : HTMLElement {
readonly attribute HTMLCollection options;
};
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 0380724f9f7..2dca9969f6c 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
@@ -49,8 +49,8 @@ bool HTMLFieldSetElement::MatchesValidityPseudoClasses() const {
bool HTMLFieldSetElement::IsValidElement() {
for (Element* element : *elements()) {
- if (element->IsFormControlElement()) {
- if (!ToHTMLFormControlElement(element)->IsNotCandidateOrValid())
+ if (auto* html_form_element = DynamicTo<HTMLFormControlElement>(element)) {
+ if (!html_form_element->IsNotCandidateOrValid())
return false;
} else if (auto* html_element = DynamicTo<HTMLElement>(element)) {
if (html_element->IsFormAssociatedCustomElement() &&
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_field_set_element.idl b/chromium/third_party/blink/renderer/core/html/forms/html_field_set_element.idl
index 66adce58164..f9b20c2cd4a 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_field_set_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_field_set_element.idl
@@ -18,8 +18,10 @@
*/
// https://html.spec.whatwg.org/C/#the-fieldset-element
-[HTMLConstructor]
-interface HTMLFieldSetElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLFieldSetElement : HTMLElement {
[CEReactions, Reflect] attribute boolean disabled;
[ImplementedAs=formOwner] readonly attribute HTMLFormElement? form;
[CEReactions, Reflect] attribute DOMString name;
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 f9a83fb6615..c9b2036c563 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
@@ -29,13 +29,13 @@
#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/events/event_dispatch_forbidden_scope.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/forms/html_form_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"
#include "third_party/blink/renderer/core/layout/layout_object.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
@@ -402,4 +402,11 @@ void HTMLFormControlElement::AssociateWith(HTMLFormElement* form) {
AssociateByParser(form);
}
+int32_t HTMLFormControlElement::GetAxId() const {
+ if (AXObjectCache* cache = GetDocument().ExistingAXObjectCache())
+ return cache->GetAXID(const_cast<HTMLFormControlElement*>(this));
+
+ return 0;
+}
+
} // namespace blink
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 30fd4ef490e..df09c1983db 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
@@ -31,6 +31,7 @@
#include "third_party/blink/renderer/core/html/forms/form_associated.h"
#include "third_party/blink/renderer/core/html/forms/listed_element.h"
#include "third_party/blink/renderer/core/html/html_element.h"
+#include "third_party/blink/renderer/platform/wtf/casting.h"
namespace blink {
@@ -129,6 +130,8 @@ class CORE_EXPORT HTMLFormControlElement : public HTMLElement,
return unique_renderer_form_control_id_;
}
+ int32_t GetAxId() const;
+
protected:
HTMLFormControlElement(const QualifiedName& tag_name, Document&);
@@ -174,12 +177,17 @@ inline bool IsHTMLFormControlElement(const Element& element) {
}
DEFINE_HTMLELEMENT_TYPE_CASTS_WITH_FUNCTION(HTMLFormControlElement);
-DEFINE_TYPE_CASTS(HTMLFormControlElement,
- ListedElement,
- control,
- control->IsFormControlElement(),
- control.IsFormControlElement());
+template <>
+struct DowncastTraits<HTMLFormControlElement> {
+ static bool AllowFrom(const Node& node) {
+ auto* element = DynamicTo<Element>(node);
+ return element && element->IsFormControlElement();
+ }
+ static bool AllowFrom(const ListedElement& control) {
+ return control.IsFormControlElement();
+ }
+};
} // namespace blink
#endif
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 2183ac63f65..9d555103171 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
@@ -134,8 +134,8 @@ TEST_F(HTMLFormControlElementTest, DoNotUpdateLayoutDuringDOMMutation) {
// dangerous. This test ensures ShowValidationMessage() is NOT called in
// appendChild(). crbug.com/756408
GetDocument().documentElement()->SetInnerHTMLFromString("<select></select>");
- HTMLFormControlElement* const select =
- ToHTMLFormControlElement(GetDocument().QuerySelector("select"));
+ auto* const select =
+ To<HTMLFormControlElement>(GetDocument().QuerySelector("select"));
auto* const optgroup =
GetDocument().CreateRawElement(html_names::kOptgroupTag);
auto* validation_client =
@@ -153,12 +153,12 @@ TEST_F(HTMLFormControlElementTest, DoNotUpdateLayoutDuringDOMMutation) {
TEST_F(HTMLFormControlElementTest, UniqueRendererFormControlId) {
SetHtmlInnerHTML("<body><input id=input1><input id=input2></body>");
- auto* form_control1 = ToHTMLFormControlElement(GetElementById("input1"));
+ auto* form_control1 = To<HTMLFormControlElement>(GetElementById("input1"));
unsigned first_id = form_control1->UniqueRendererFormControlId();
- auto* form_control2 = ToHTMLFormControlElement(GetElementById("input2"));
+ auto* form_control2 = To<HTMLFormControlElement>(GetElementById("input2"));
EXPECT_EQ(first_id + 1, form_control2->UniqueRendererFormControlId());
SetHtmlInnerHTML("<body><select id=select1></body>");
- auto* form_control3 = ToHTMLFormControlElement(GetElementById("select1"));
+ auto* form_control3 = To<HTMLFormControlElement>(GetElementById("select1"));
EXPECT_EQ(first_id + 2, form_control3->UniqueRendererFormControlId());
}
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 f28ce14b7c1..10d02d0bbfd 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
@@ -25,10 +25,10 @@
#include "third_party/blink/renderer/core/html/forms/html_form_controls_collection.h"
#include "third_party/blink/renderer/bindings/core/v8/radio_node_list_or_element.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/forms/html_form_element.h"
#include "third_party/blink/renderer/core/html/html_image_element.h"
#include "third_party/blink/renderer/core/html_names.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_form_controls_collection.idl b/chromium/third_party/blink/renderer/core/html/forms/html_form_controls_collection.idl
index 8a084bed2f1..6842382d342 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_form_controls_collection.idl
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_form_controls_collection.idl
@@ -21,6 +21,7 @@
// https://html.spec.whatwg.org/C/#the-htmlformcontrolscollection-interface
+[Exposed=Window]
interface HTMLFormControlsCollection : HTMLCollection {
// inherits length and item()
[ImplementedAs=namedGetter] getter (RadioNodeList or Element)? namedItem(DOMString name); // shadows inherited namedItem()
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 4c2e4611b9b..340695dcb78 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
@@ -45,7 +45,6 @@
#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/remote_frame.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/element_internals.h"
#include "third_party/blink/renderer/core/html/forms/form_controller.h"
@@ -66,6 +65,7 @@
#include "third_party/blink/renderer/core/loader/mixed_content_checker.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
namespace blink {
@@ -192,10 +192,10 @@ void HTMLFormElement::SubmitImplicitly(Event& event,
bool from_implicit_submission_trigger) {
int submission_trigger_count = 0;
bool seen_default_button = false;
- for (const auto& element : ListedElements()) {
- if (!element->IsFormControlElement())
+ for (ListedElement* element : ListedElements()) {
+ auto* control = DynamicTo<HTMLFormControlElement>(element);
+ if (!control)
continue;
- HTMLFormControlElement* control = ToHTMLFormControlElement(element);
if (!seen_default_button && control->CanBeSuccessfulSubmitButton()) {
if (from_implicit_submission_trigger)
seen_default_button = true;
@@ -283,13 +283,13 @@ void HTMLFormElement::PrepareForSubmission(
}
// https://github.com/whatwg/html/issues/2253
- for (const auto& element : ListedElements()) {
- if (element->IsFormControlElement() &&
- ToHTMLFormControlElement(element)->BlocksFormSubmission()) {
+ for (ListedElement* element : ListedElements()) {
+ auto* form_control_element = DynamicTo<HTMLFormControlElement>(element);
+ if (form_control_element && form_control_element->BlocksFormSubmission()) {
UseCounter::Count(GetDocument(),
WebFeature::kFormSubmittedWithUnclosedFormControl);
if (RuntimeEnabledFeatures::UnclosedFormControlIsInvalidEnabled()) {
- String tag_name = ToHTMLFormControlElement(element)->tagName();
+ String tag_name = To<HTMLFormControlElement>(element)->tagName();
GetDocument().AddConsoleMessage(ConsoleMessage::Create(
mojom::ConsoleMessageSource::kSecurity,
mojom::ConsoleMessageLevel::kError,
@@ -307,23 +307,25 @@ void HTMLFormElement::PrepareForSubmission(
}
}
- bool skip_validation = !GetDocument().GetPage() || NoValidate();
- if (submit_button && submit_button->FormNoValidate())
- skip_validation = true;
-
- UseCounter::Count(GetDocument(), WebFeature::kFormSubmissionStarted);
- // Interactive validation must be done before dispatching the submit event.
- if (!skip_validation && !ValidateInteractively())
- return;
-
bool should_submit;
{
base::AutoReset<bool> submit_event_handler_scope(&in_user_js_submit_event_,
true);
- frame->Client()->DispatchWillSendSubmitEvent(this);
- should_submit =
- DispatchEvent(*Event::CreateCancelableBubble(
- event_type_names::kSubmit)) == DispatchEventResult::kNotCanceled;
+
+ bool skip_validation = !GetDocument().GetPage() || NoValidate();
+ if (submit_button && submit_button->FormNoValidate())
+ skip_validation = true;
+
+ UseCounter::Count(GetDocument(), WebFeature::kFormSubmissionStarted);
+ // Interactive validation must be done before dispatching the submit event.
+ if (!skip_validation && !ValidateInteractively()) {
+ should_submit = false;
+ } else {
+ frame->Client()->DispatchWillSendSubmitEvent(this);
+ should_submit =
+ DispatchEvent(*Event::CreateCancelableBubble(
+ event_type_names::kSubmit)) == DispatchEventResult::kNotCanceled;
+ }
}
if (should_submit) {
planned_navigation_ = nullptr;
@@ -423,11 +425,10 @@ void HTMLFormElement::Submit(Event* event,
// event handler might add a submit button. We search for a submit
// button again.
// TODO(tkent): Do we really need to activate such submit button?
- for (const auto& listed_element : ListedElements()) {
- if (!listed_element->IsFormControlElement())
+ for (ListedElement* listed_element : ListedElements()) {
+ auto* control = DynamicTo<HTMLFormControlElement>(listed_element);
+ if (!control)
continue;
- HTMLFormControlElement* control =
- ToHTMLFormControlElement(listed_element);
DCHECK(!control->IsActivatedSubmit());
if (control->IsSuccessfulSubmitButton()) {
submit_button = control;
@@ -541,9 +542,9 @@ void HTMLFormElement::reset() {
// Copy the element list because |reset()| implementation can update DOM
// structure.
ListedElement::List elements(ListedElements());
- for (const auto& element : elements) {
- if (element->IsFormControlElement()) {
- ToHTMLFormControlElement(element)->Reset();
+ for (ListedElement* element : elements) {
+ if (auto* html_form_element = DynamicTo<HTMLFormControlElement>(element)) {
+ html_form_element->Reset();
} else if (element->IsElementInternals()) {
CustomElement::EnqueueFormResetCallback(element->ToHTMLElement());
}
@@ -718,10 +719,10 @@ void HTMLFormElement::setMethod(const AtomicString& value) {
}
HTMLFormControlElement* HTMLFormElement::FindDefaultButton() const {
- for (const auto& element : ListedElements()) {
- if (!element->IsFormControlElement())
+ for (ListedElement* element : ListedElements()) {
+ auto* control = DynamicTo<HTMLFormControlElement>(element);
+ if (!control)
continue;
- HTMLFormControlElement* control = ToHTMLFormControlElement(element);
if (control->CanBeSuccessfulSubmitButton())
return control;
}
@@ -739,17 +740,16 @@ bool HTMLFormElement::CheckInvalidControlsAndCollectUnhandled(
const ListedElement::List& listed_elements = ListedElements();
HeapVector<Member<ListedElement>> elements;
elements.ReserveCapacity(listed_elements.size());
- for (const auto& element : listed_elements)
+ for (ListedElement* element : listed_elements)
elements.push_back(element);
int invalid_controls_count = 0;
- for (const auto& element : elements) {
+ for (ListedElement* element : elements) {
if (element->Form() != this)
continue;
// TOOD(tkent): Virtualize checkValidity().
bool should_check_validity = false;
- if (element->IsFormControlElement()) {
- should_check_validity =
- ToHTMLFormControlElement(element)->IsSubmittableElement();
+ if (auto* html_form_element = DynamicTo<HTMLFormControlElement>(element)) {
+ should_check_validity = html_form_element->IsSubmittableElement();
} else if (element->IsElementInternals()) {
should_check_validity = true;
}
@@ -781,8 +781,8 @@ Element* HTMLFormElement::ElementFromPastNamesMap(
SECURITY_DCHECK(ListedElements().Find(ToHTMLObjectElement(element)) !=
kNotFound);
} else {
- SECURITY_DCHECK(ListedElements().Find(ToHTMLFormControlElement(element)) !=
- kNotFound);
+ SECURITY_DCHECK(ListedElements().Find(
+ To<HTMLFormControlElement>(element)) != kNotFound);
}
#endif
return element;
@@ -879,12 +879,13 @@ void HTMLFormElement::AnonymousNamedGetter(
}
void HTMLFormElement::InvalidateDefaultButtonStyle() const {
- for (const auto& control : ListedElements()) {
- if (!control->IsFormControlElement())
+ for (ListedElement* control : ListedElements()) {
+ auto* html_form_control = DynamicTo<HTMLFormControlElement>(control);
+ if (!html_form_control)
continue;
- if (ToHTMLFormControlElement(control)->CanBeSuccessfulSubmitButton()) {
- ToHTMLFormControlElement(control)->PseudoStateChanged(
- CSSSelector::kPseudoDefault);
+
+ if (html_form_control->CanBeSuccessfulSubmitButton()) {
+ html_form_control->PseudoStateChanged(CSSSelector::kPseudoDefault);
}
}
}
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_form_element.idl b/chromium/third_party/blink/renderer/core/html/forms/html_form_element.idl
index 91d58dafd97..9d7b63602d5 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_form_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_form_element.idl
@@ -21,6 +21,7 @@
// https://html.spec.whatwg.org/C/#the-form-element
[
+ Exposed=Window,
HTMLConstructor,
OverrideBuiltins
] interface HTMLFormElement : HTMLElement {
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 5d894e51d71..974f1a6c9dc 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
@@ -51,7 +51,6 @@
#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_view.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/forms/color_chooser.h"
#include "third_party/blink/renderer/core/html/forms/date_time_chooser.h"
#include "third_party/blink/renderer/core/html/forms/file_input_type.h"
@@ -74,6 +73,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/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/language.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/text/platform_locale.h"
@@ -901,8 +901,8 @@ void HTMLInputElement::AttachLayoutTree(AttachContext& context) {
input_type_->CountUsage();
}
-void HTMLInputElement::DetachLayoutTree(const AttachContext& context) {
- TextControlElement::DetachLayoutTree(context);
+void HTMLInputElement::DetachLayoutTree(bool performing_reattach) {
+ TextControlElement::DetachLayoutTree(performing_reattach);
needs_to_update_view_value_ = true;
input_type_view_->ClosePopupView();
}
@@ -1652,8 +1652,7 @@ bool HTMLInputElement::HasValidDataListOptions() const {
return false;
HTMLDataListOptionsCollection* options = data_list->options();
for (unsigned i = 0; HTMLOptionElement* option = options->Item(i); ++i) {
- if (!option->value().IsEmpty() && !option->IsDisabledFormControl() &&
- IsValidValue(option->value()))
+ if (!option->value().IsEmpty() && !option->IsDisabledFormControl())
return true;
}
return false;
@@ -1687,9 +1686,7 @@ HTMLInputElement::FilteredDataListOptions() const {
option->label().FoldCase().Find(value) == kNotFound)
continue;
}
- // TODO(tkent): Should allow invalid strings. crbug.com/607097.
- if (option->value().IsEmpty() || option->IsDisabledFormControl() ||
- !IsValidValue(option->value()))
+ if (option->value().IsEmpty() || option->IsDisabledFormControl())
continue;
filtered.push_back(option);
}
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 0329d621bb8..33e922552ea 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
@@ -193,7 +193,7 @@ class CORE_EXPORT HTMLInputElement
bool LayoutObjectIsNeeded(const ComputedStyle&) const final;
LayoutObject* CreateLayoutObject(const ComputedStyle&, LegacyLayout) override;
- void DetachLayoutTree(const AttachContext& = AttachContext()) final;
+ void DetachLayoutTree(bool performing_reattach) final;
void UpdateFocusAppearanceWithOptions(SelectionBehaviorOnFocus,
const FocusOptions*) final;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_input_element.idl b/chromium/third_party/blink/renderer/core/html/forms/html_input_element.idl
index 0d9b7a2cab5..31b6b8e8535 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_input_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_input_element.idl
@@ -19,11 +19,12 @@
* Boston, MA 02110-1301, USA.
*/
-// https://html.spec.whatwg.org/C/#the-input-element
+// https://html.spec.whatwg.org/multipage/input.html#htmlinputelement
enum SelectionMode { "select", "start", "end", "preserve" };
[
+ Exposed=Window,
HTMLConstructor,
ActiveScriptWrappable
] interface HTMLInputElement : HTMLElement {
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 4e1e6eed38b..f1c4ab8999e 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
@@ -32,13 +32,13 @@
#include "third_party/blink/renderer/core/editing/visible_selection.h"
#include "third_party/blink/renderer/core/events/mouse_event.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/html/custom/element_internals.h"
#include "third_party/blink/renderer/core/html/forms/html_form_control_element.h"
#include "third_party/blink/renderer/core/html/forms/listed_element.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_object.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
@@ -71,7 +71,7 @@ HTMLElement* HTMLLabelElement::control() const {
return nullptr;
if (Element* element = GetTreeScope().getElementById(control_id)) {
- if (auto* html_element = ToHTMLElementOrNull(*element)) {
+ if (auto* html_element = DynamicTo<HTMLElement>(*element)) {
if (html_element->IsLabelable()) {
if (!html_element->IsFormControlElement()) {
UseCounter::Count(
@@ -96,10 +96,10 @@ HTMLFormElement* HTMLLabelElement::form() const {
return nullptr;
}
-void HTMLLabelElement::SetActive(bool down) {
- if (down != IsActive()) {
+void HTMLLabelElement::SetActive(bool active) {
+ if (active != IsActive()) {
// Update our status first.
- HTMLElement::SetActive(down);
+ HTMLElement::SetActive(active);
}
// Also update our corresponding control.
@@ -108,10 +108,10 @@ void HTMLLabelElement::SetActive(bool down) {
control_element->SetActive(IsActive());
}
-void HTMLLabelElement::SetHovered(bool over) {
- if (over != IsHovered()) {
+void HTMLLabelElement::SetHovered(bool hovered) {
+ if (hovered != IsHovered()) {
// Update our status first.
- HTMLElement::SetHovered(over);
+ HTMLElement::SetHovered(hovered);
}
// Also update our corresponding control.
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 126f9268d6d..3e4fc40bea2 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
@@ -47,8 +47,8 @@ class CORE_EXPORT HTMLLabelElement final : public HTMLElement {
void AccessKeyAction(bool send_mouse_events) override;
// Overridden to update the hover/active state of the corresponding control.
- void SetActive(bool = true) override;
- void SetHovered(bool = true) override;
+ void SetActive(bool active) override;
+ void SetHovered(bool hovered) override;
// Overridden to either click() or focus() the corresponding control.
void DefaultEventHandler(Event&) override;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_label_element.idl b/chromium/third_party/blink/renderer/core/html/forms/html_label_element.idl
index 39f1eba52d1..24d8fca6daf 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_label_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_label_element.idl
@@ -19,8 +19,10 @@
*/
// https://html.spec.whatwg.org/C/#the-label-element
-[HTMLConstructor]
-interface HTMLLabelElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLLabelElement : HTMLElement {
readonly attribute HTMLFormElement? form;
[CEReactions, Reflect=for] attribute DOMString htmlFor;
readonly attribute HTMLElement? control;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_legend_element.idl b/chromium/third_party/blink/renderer/core/html/forms/html_legend_element.idl
index b20b50e1e1d..6b0a63b4b6c 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_legend_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_legend_element.idl
@@ -19,8 +19,10 @@
*/
// https://html.spec.whatwg.org/C/#the-legend-element
-[HTMLConstructor]
-interface HTMLLegendElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLLegendElement : HTMLElement {
readonly attribute HTMLFormElement? form;
// obsolete members
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_opt_group_element.idl b/chromium/third_party/blink/renderer/core/html/forms/html_opt_group_element.idl
index 60ede697ced..a4c96c36b9c 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_opt_group_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_opt_group_element.idl
@@ -18,8 +18,10 @@
*/
// https://html.spec.whatwg.org/C/#the-optgroup-element
-[HTMLConstructor]
-interface HTMLOptGroupElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLOptGroupElement : HTMLElement {
[CEReactions, Reflect] attribute boolean disabled;
[CEReactions, Reflect] attribute DOMString label;
};
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 85281f9b1de..a79c57ebb02 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
@@ -354,7 +354,8 @@ String HTMLOptionElement::CollectOptionInnerText() const {
if (node->IsTextNode())
text.Append(node->nodeValue());
// Text nodes inside script elements are not part of the option text.
- if (node->IsElementNode() && ToElement(node)->IsScriptElement())
+ auto* element = DynamicTo<Element>(node);
+ if (element && element->IsScriptElement())
node = NodeTraversal::NextSkippingChildren(*node, this);
else
node = NodeTraversal::Next(*node, this);
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_option_element.idl b/chromium/third_party/blink/renderer/core/html/forms/html_option_element.idl
index 638e3af2f62..fd2eb010c43 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_option_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_option_element.idl
@@ -21,6 +21,7 @@
// https://html.spec.whatwg.org/C/#the-option-element
[
+ Exposed=Window,
HTMLConstructor,
NamedConstructor=Option(optional DOMString data = null,
optional DOMString value = null,
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_options_collection.idl b/chromium/third_party/blink/renderer/core/html/forms/html_options_collection.idl
index a78ff412282..7fecb92f34b 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_options_collection.idl
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_options_collection.idl
@@ -21,6 +21,7 @@
// https://html.spec.whatwg.org/C/#the-htmloptionscollection-interface
+[Exposed=Window]
interface HTMLOptionsCollection : HTMLCollection {
// Inherits item() and namedItem()
[CEReactions, RaisesException=Setter] attribute unsigned long length; // shadows inherited length
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_output_element.idl b/chromium/third_party/blink/renderer/core/html/forms/html_output_element.idl
index 50a38fbba1b..369394a6cad 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_output_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_output_element.idl
@@ -24,8 +24,10 @@
*/
// https://html.spec.whatwg.org/C/#the-output-element
-[HTMLConstructor]
-interface HTMLOutputElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLOutputElement : HTMLElement {
[PutForwards=value] readonly attribute DOMTokenList htmlFor;
[ImplementedAs=formOwner] readonly attribute HTMLFormElement? form;
[CEReactions, Reflect] attribute DOMString name;
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 9dd6702a1fd..869f8a063c3 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
@@ -106,6 +106,9 @@ HTMLSelectElement::~HTMLSelectElement() = default;
// static
bool HTMLSelectElement::CanAssignToSelectSlot(const Node& node) {
+ // Even if options/optgroups are not rendered as children of LayoutMenuList,
+ // we still need to add them to the flat tree through slotting since we need
+ // their ComputedStyle for popup rendering.
return node.HasTagName(kOptionTag) || node.HasTagName(kOptgroupTag) ||
node.HasTagName(kHrTag);
}
@@ -915,7 +918,7 @@ void HTMLSelectElement::ScrollToOptionTask() {
GetDocument().UpdateStyleAndLayout();
if (!GetLayoutObject() || !GetLayoutObject()->IsListBox())
return;
- LayoutRect bounds = option->BoundingBoxForScrollIntoView();
+ PhysicalRect bounds = option->BoundingBoxForScrollIntoView();
ToLayoutListBox(GetLayoutObject())->ScrollToRect(bounds);
}
@@ -2019,8 +2022,8 @@ void HTMLSelectElement::AttachLayoutTree(AttachContext& context) {
}
}
-void HTMLSelectElement::DetachLayoutTree(const AttachContext& context) {
- HTMLFormControlElementWithState::DetachLayoutTree(context);
+void HTMLSelectElement::DetachLayoutTree(bool performing_reattach) {
+ HTMLFormControlElementWithState::DetachLayoutTree(performing_reattach);
if (popup_)
popup_->DisconnectClient();
popup_is_visible_ = false;
@@ -2062,7 +2065,7 @@ class HTMLSelectElement::PopupUpdater : public MutationObserver::Delegate {
return;
for (const auto& record : records) {
if (record->type() == "attributes") {
- const Element& element = *ToElement(record->target());
+ const auto& element = *To<Element>(record->target());
if (record->oldValue() == element.getAttribute(record->attributeName()))
continue;
} else if (record->type() == "characterData") {
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 8c20767c2ad..7c9ddcc6557 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
@@ -205,7 +205,7 @@ class CORE_EXPORT HTMLSelectElement final
LayoutObject* CreateLayoutObject(const ComputedStyle&, LegacyLayout) override;
void DidRecalcStyle(const StyleRecalcChange) override;
void AttachLayoutTree(AttachContext&) override;
- void DetachLayoutTree(const AttachContext& = AttachContext()) override;
+ void DetachLayoutTree(bool performing_reattach = false) override;
void AppendToFormData(FormData&) override;
void DidAddUserAgentShadowRoot(ShadowRoot&) override;
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_select_element.idl b/chromium/third_party/blink/renderer/core/html/forms/html_select_element.idl
index 4e43cd41875..feaf76f3fff 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_select_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_select_element.idl
@@ -20,8 +20,10 @@
*/
// https://html.spec.whatwg.org/C/#the-select-element
-[HTMLConstructor]
-interface HTMLSelectElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLSelectElement : HTMLElement {
[CEReactions, ImplementedAs=IDLExposedAutofillValue] attribute DOMString autocomplete;
[CEReactions, Reflect] attribute boolean autofocus;
[CEReactions, Reflect] attribute boolean disabled;
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 ad6bd3530aa..1c85388124a 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
@@ -387,8 +387,8 @@ TEST_F(HTMLSelectElementTest, DefaultToolTip) {
">Placeholder</option><optgroup><option>o2</option></optgroup></select>");
HTMLSelectElement* select =
ToHTMLSelectElement(GetDocument().body()->firstChild());
- Element* option = ToElement(select->firstChild());
- Element* optgroup = ToElement(option->nextSibling());
+ auto* option = To<Element>(select->firstChild());
+ auto* optgroup = To<Element>(option->nextSibling());
EXPECT_EQ(String(), select->DefaultToolTip())
<< "defaultToolTip for SELECT without FORM and without required "
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 bc9729484df..bf8c8877454 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
@@ -37,7 +37,6 @@
#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"
#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/text_control_inner_elements.h"
@@ -49,6 +48,7 @@
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/text/platform_locale.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
diff --git a/chromium/third_party/blink/renderer/core/html/forms/html_text_area_element.idl b/chromium/third_party/blink/renderer/core/html/forms/html_text_area_element.idl
index c06bd0d9021..4e1376f6602 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/html_text_area_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/forms/html_text_area_element.idl
@@ -20,8 +20,10 @@
*/
// https://html.spec.whatwg.org/C/#the-textarea-element
-[HTMLConstructor]
-interface HTMLTextAreaElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLTextAreaElement : HTMLElement {
[CEReactions, ImplementedAs=IDLExposedAutofillValue] attribute DOMString autocomplete;
[CEReactions, Reflect] attribute boolean autofocus;
[CEReactions] attribute unsigned long cols;
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 b6842278493..ec9b2091966 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
@@ -972,7 +972,7 @@ void InputType::AddWarningToConsole(const char* message_format,
mojom::ConsoleMessageSource::kRendering,
mojom::ConsoleMessageLevel::kWarning,
String::Format(message_format,
- JSONValue::QuoteString(value).Utf8().data())));
+ JSONValue::QuoteString(value).Utf8().c_str())));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/forms/input_type_view.h b/chromium/third_party/blink/renderer/core/html/forms/input_type_view.h
index 0c13fd7a983..9da2af7624a 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/input_type_view.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/input_type_view.h
@@ -39,7 +39,7 @@
#include "third_party/blink/renderer/core/dom/events/event_dispatcher.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/text/text_direction.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
namespace blink {
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 879e5dd4048..ee187f76b0c 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
@@ -669,11 +669,11 @@ bool ListedElement::IsElementInternals() const {
}
ListedElement* ListedElement::From(Element& element) {
- auto* html_element = ToHTMLElementOrNull(element);
+ auto* html_element = DynamicTo<HTMLElement>(element);
if (!html_element)
return nullptr;
- if (html_element->IsFormControlElement())
- return ToHTMLFormControlElement(&element);
+ if (auto* form_control_element = DynamicTo<HTMLFormControlElement>(element))
+ return form_control_element;
if (html_element->IsFormAssociatedCustomElement())
return &element.EnsureElementInternals();
if (auto* object = ToHTMLObjectElementOrNull(html_element))
@@ -682,8 +682,8 @@ ListedElement* ListedElement::From(Element& element) {
}
const HTMLElement& ListedElement::ToHTMLElement() const {
- if (IsFormControlElement())
- return ToHTMLFormControlElement(*this);
+ if (auto* form_control_element = DynamicTo<HTMLFormControlElement>(this))
+ return *form_control_element;
if (IsElementInternals())
return To<ElementInternals>(*this).Target();
return ToHTMLObjectElementFromListedElement(*this);
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 32b4dc89474..50c9fc611eb 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
@@ -35,7 +35,7 @@
#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/platform/date_components.h"
+#include "third_party/blink/renderer/platform/text/date_components.h"
#include "third_party/blink/renderer/platform/text/platform_locale.h"
#include "third_party/blink/renderer/platform/wtf/date_math.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
@@ -76,7 +76,8 @@ String MonthInputType::SerializeWithMilliseconds(double value) const {
Decimal MonthInputType::DefaultValueForStepUp() const {
DateComponents date;
- date.SetMillisecondsSinceEpochForMonth(ConvertToLocalTime(CurrentTimeMS()));
+ date.SetMillisecondsSinceEpochForMonth(
+ ConvertToLocalTime(base::Time::Now().ToDoubleT() * 1000.0));
double months = date.MonthsSinceEpoch();
DCHECK(std::isfinite(months));
return Decimal::FromDouble(months);
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 ac76a2c8c35..b9b75086e30 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
@@ -48,8 +48,8 @@
#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/style/computed_style.h"
-#include "third_party/blink/renderer/platform/date_components.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/text/date_components.h"
#include "third_party/blink/renderer/platform/text/date_time_format.h"
#include "third_party/blink/renderer/platform/text/platform_locale.h"
#include "third_party/blink/renderer/platform/wtf/date_math.h"
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 202bb99ff7d..f9bb44662e8 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
@@ -69,10 +69,12 @@ TEST(PasswordInputTypeTest, DidEditFieldEvent) {
// in a secure context.
TEST(PasswordInputTypeTest, DidEditFieldEventNotSentFromSecureContext) {
auto page_holder = std::make_unique<DummyPageHolder>(IntSize(2000, 2000));
+ page_holder->GetFrame().Loader().CommitNavigation(
+ WebNavigationParams::CreateWithHTMLBuffer(SharedBuffer::Create(),
+ KURL("https://example.test")),
+ nullptr /* extra_data */);
+ blink::test::RunPendingTasks();
MockInsecureInputService mock_service(page_holder->GetFrame());
- page_holder->GetDocument().SetURL(KURL("https://example.test"));
- page_holder->GetDocument().SetSecurityOrigin(
- SecurityOrigin::Create(KURL("https://example.test")));
page_holder->GetDocument().SetSecureContextStateForTesting(
SecureContextState::kSecure);
page_holder->GetDocument().body()->SetInnerHTMLFromString(
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 ce1173e773f..6f3673ebd37 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
@@ -133,9 +133,9 @@ void PickerIndicatorElement::ClosePopup() {
chooser_->EndChooser();
}
-void PickerIndicatorElement::DetachLayoutTree(const AttachContext& context) {
+void PickerIndicatorElement::DetachLayoutTree(bool performing_reattach) {
ClosePopup();
- HTMLDivElement::DetachLayoutTree(context);
+ HTMLDivElement::DetachLayoutTree(performing_reattach);
}
AXObject* PickerIndicatorElement::PopupRootAXObject() const {
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 7055f0dac10..df33806c889 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
@@ -76,7 +76,7 @@ class PickerIndicatorElement final : public HTMLDivElement,
private:
LayoutObject* CreateLayoutObject(const ComputedStyle&, LegacyLayout) override;
void DefaultEventHandler(Event&) override;
- void DetachLayoutTree(const AttachContext& = AttachContext()) override;
+ void DetachLayoutTree(bool performing_reattach) override;
bool IsPickerIndicatorElement() const override;
InsertionNotificationRequest InsertedInto(ContainerNode&) override;
void DidNotifySubtreeInsertionsToDocument() override;
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 3b9b713079c..06b43bef4fd 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
@@ -40,7 +40,6 @@
#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/events/mouse_event.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/forms/html_data_list_element.h"
#include "third_party/blink/renderer/core/html/forms/html_data_list_options_collection.h"
#include "third_party/blink/renderer/core/html/forms/html_input_element.h"
@@ -55,6 +54,7 @@
#include "third_party/blink/renderer/core/layout/layout_slider.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/forms/resources/calendarPicker.js b/chromium/third_party/blink/renderer/core/html/forms/resources/calendarPicker.js
index 9d50db7efba..f79a5cee0d9 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/resources/calendarPicker.js
+++ b/chromium/third_party/blink/renderer/core/html/forms/resources/calendarPicker.js
@@ -108,11 +108,14 @@ function formatJapaneseImperialEra(year, month) {
{era: 'long'});
}
// Produce the era for day 16 because it's almost the midpoint of a month.
- let day16string = japaneseEraFormatter.format(new Date(year, month, 16));
- let nenIndex = day16string.indexOf('\u5e74');
+ // 275760-09-13 is the last valid date in ECMAScript. We apply day 7 in that
+ // case because it's the midpoint between 09-01 and 09-13.
+ let sampleDay = year == 275760 && month == 8 ? 7 : 16;
+ let sampleDayString = japaneseEraFormatter.format(new Date(year, month, sampleDay));
+ let nenIndex = sampleDayString.indexOf('\u5e74');
if (nenIndex == -1)
return '';
- let yearPart = day16string.substring(0, nenIndex + 1);
+ let yearPart = sampleDayString.substring(0, nenIndex + 1);
// We don't show an imperial era if it is greater than 99 because of space
// limitation.
@@ -356,7 +359,7 @@ Day.prototype.format = function() {
return Day.formatter.format(this.startDate());
};
-// See platform/date_components.h.
+// See platform/text/date_components.h.
Day.Minimum = Day.createFromValue(-62135596800000.0);
Day.Maximum = Day.createFromValue(8640000000000000.0);
@@ -391,7 +394,7 @@ function Week(year, week) {
Week.ISOStringRegExp = /^(\d+)-[wW](\d+)$/;
-// See platform/date_components.h.
+// See platform/text/date_components.h.
Week.Minimum = new Week(1, 1);
Week.Maximum = new Week(275760, 37);
@@ -613,7 +616,7 @@ function Month(year, month) {
Month.ISOStringRegExp = /^(\d+)-(\d+)$/;
-// See platform/date_components.h.
+// See platform/text/date_components.h.
Month.Minimum = new Month(1, 0);
Month.Maximum = new Month(275760, 8);
diff --git a/chromium/third_party/blink/renderer/core/html/forms/resources/colorSuggestionPicker.css b/chromium/third_party/blink/renderer/core/html/forms/resources/colorSuggestionPicker.css
index eda7bbbc068..9a3e42df60f 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/resources/colorSuggestionPicker.css
+++ b/chromium/third_party/blink/renderer/core/html/forms/resources/colorSuggestionPicker.css
@@ -31,7 +31,7 @@ body {
overflow: hidden;
}
-#main {
+.color-suggestion-picker-main {
background-color: white;
border: solid 1px #8899aa;
box-shadow: inset 2px 2px 2px white,
diff --git a/chromium/third_party/blink/renderer/core/html/forms/resources/colorSuggestionPicker.js b/chromium/third_party/blink/renderer/core/html/forms/resources/colorSuggestionPicker.js
index aa2477f1381..15c60eb08ec 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/resources/colorSuggestionPicker.js
+++ b/chromium/third_party/blink/renderer/core/html/forms/resources/colorSuggestionPicker.js
@@ -24,37 +24,25 @@
* DAMAGE.
*/
-var global = {argumentsReceived: false, params: null};
-/**
- * @param {Event} event
- */
-function handleMessage(event) {
- initialize(JSON.parse(event.data));
- global.argumentsReceived = true;
+function initializeColorSuggestionPicker() {
+ new ColorSuggestionPicker(main, global.params);
}
/**
* @param {!Object} args
+ * @return {?string} An error message, or null if the argument has no errors.
*/
-function initialize(args) {
- global.params = args;
- var main = $('main');
- main.innerHTML = '';
- var errorString = validateArguments(args);
- if (errorString) {
- main.textContent = 'Internal error: ' + errorString;
- resizeWindow(main.offsetWidth, main.offsetHeight);
- } else
- new ColorPicker(main, args);
+function validateColorSuggestionPickerArguments(args) {
+ if (!args.shouldShowColorSuggestionPicker)
+ return 'Should not be showing the color suggestion picker.'
+ if (!args.values)
+ return 'No values.';
+ if (!args.otherColorLabel)
+ return 'No otherColorLabel.';
+ return null;
}
-// The DefaultColorPalette is used when the list of values are empty.
-var DefaultColorPalette = [
- '#000000', '#404040', '#808080', '#c0c0c0', '#ffffff', '#980000', '#ff0000', '#ff9900', '#ffff00', '#00ff00',
- '#00ffff', '#4a86e8', '#0000ff', '#9900ff', '#ff00ff'
-];
-
function handleArgumentsTimeout() {
if (global.argumentsReceived)
return;
@@ -62,19 +50,7 @@ function handleArgumentsTimeout() {
initialize(args);
}
-/**
- * @param {!Object} args
- * @return {?string} An error message, or null if the argument has no errors.
- */
-function validateArguments(args) {
- if (!args.values)
- return 'No values.';
- if (!args.otherColorLabel)
- return 'No otherColorLabel.';
- return null;
-}
-
-function ColorPicker(element, config) {
+function ColorSuggestionPicker(element, config) {
Picker.call(this, element, config);
this._config = config;
if (this._config.values.length === 0)
@@ -85,14 +61,14 @@ function ColorPicker(element, config) {
this._element.addEventListener('mousemove', this._handleMouseMove.bind(this));
this._element.addEventListener('mousedown', this._handleMouseDown.bind(this));
}
-ColorPicker.prototype = Object.create(Picker.prototype);
+ColorSuggestionPicker.prototype = Object.create(Picker.prototype);
var SwatchBorderBoxWidth = 24; // keep in sync with CSS
var SwatchBorderBoxHeight = 24; // keep in sync with CSS
var SwatchesPerRow = 5;
var SwatchesMaxRow = 4;
-ColorPicker.prototype._layout = function() {
+ColorSuggestionPicker.prototype._layout = function() {
var container = createElement('div', 'color-swatch-container');
container.addEventListener('click', this._handleSwatchClick.bind(this), false);
for (var i = 0; i < this._config.values.length; ++i) {
@@ -110,7 +86,7 @@ ColorPicker.prototype._layout = function() {
container.style.maxHeight = (SwatchBorderBoxHeight * SwatchesMaxRow) + 'px';
this._element.appendChild(container);
var otherButton = createElement('button', 'other-color', this._config.otherColorLabel);
- otherButton.addEventListener('click', this.chooseOtherColor.bind(this), false);
+ otherButton.addEventListener('click', this._onOtherButtonClick.bind(this), false);
this._element.appendChild(otherButton);
this._container = container;
this._otherButton = otherButton;
@@ -119,23 +95,39 @@ ColorPicker.prototype._layout = function() {
resizeWindow(elementWidth, elementHeight);
};
-ColorPicker.prototype.selectColorAtIndex = function(index) {
+ColorSuggestionPicker.prototype._onOtherButtonClick = function() {
+ if (global.params.isFormControlsRefreshEnabled) {
+ var main = $('main');
+ main.innerHTML = '';
+ main.classList.remove('color-suggestion-picker-main');
+ main.classList.add('color-picker-main');
+ // Replace document.body with a deep clone to drop all event listeners.
+ var oldBody = document.body;
+ var newBody = oldBody.cloneNode(true);
+ oldBody.parentElement.replaceChild(newBody, oldBody);
+ initializeColorPicker();
+ } else {
+ this.chooseOtherColor();
+ }
+}
+
+ColorSuggestionPicker.prototype.selectColorAtIndex = function(index) {
index = Math.max(Math.min(this._container.childNodes.length - 1, index), 0);
this._container.childNodes[index].focus();
};
-ColorPicker.prototype._handleMouseMove = function(event) {
+ColorSuggestionPicker.prototype._handleMouseMove = function(event) {
if (event.target.classList.contains('color-swatch'))
event.target.focus();
};
-ColorPicker.prototype._handleMouseDown = function(event) {
+ColorSuggestionPicker.prototype._handleMouseDown = function(event) {
// Prevent blur.
if (event.target.classList.contains('color-swatch'))
event.preventDefault();
};
-ColorPicker.prototype._handleKeyDown = function(event) {
+ColorSuggestionPicker.prototype._handleKeyDown = function(event) {
var key = event.key;
if (key === 'Escape')
this.handleCancel();
@@ -172,14 +164,7 @@ ColorPicker.prototype._handleKeyDown = function(event) {
event.preventDefault();
};
-ColorPicker.prototype._handleSwatchClick = function(event) {
+ColorSuggestionPicker.prototype._handleSwatchClick = function(event) {
if (event.target.classList.contains('color-swatch'))
this.submitValue(event.target.dataset.value);
};
-
-if (window.dialogArguments) {
- initialize(dialogArguments);
-} else {
- window.addEventListener('message', handleMessage, false);
- window.setTimeout(handleArgumentsTimeout, 1000);
-}
diff --git a/chromium/third_party/blink/renderer/core/html/forms/resources/color_picker.css b/chromium/third_party/blink/renderer/core/html/forms/resources/color_picker.css
new file mode 100644
index 00000000000..12325853617
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/html/forms/resources/color_picker.css
@@ -0,0 +1,99 @@
+/* Copyright (C) 2019 The Chromium Authors. All rights reserved.
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+body {
+ font-family: "Segoe UI", system-ui, Roboto, Ubuntu, sans-serif;
+}
+
+color-picker {
+ background: #FFFFFF;
+ display: flex;
+ flex-direction: column;
+ height: 304px;
+ width: 232px;
+}
+
+visual-color-picker {
+ height: 59%;
+}
+
+manual-color-picker {
+ height: 28%;
+}
+
+color-value-container {
+ display: flex;
+ flex-direction: row;
+ height: 32px;
+ margin-left: 10%;
+ margin-top: 2%;
+ width: 171px;
+}
+
+input {
+ background: #FFFFFF;
+ border: 1px solid #CECECE;
+ border-radius: 2px;
+ box-sizing: border-box;
+ font-family: inherit;
+ font-size: 14px;
+ text-align: center;
+}
+
+format-toggler {
+ border-radius: 2px;
+ display: block;
+ height: 24px;
+ margin-left: 10%;
+ margin-top: 2%;
+ width: 200px;
+}
+
+format-toggler:hover {
+ background-color: #F7F7F7;
+}
+
+format-label {
+ border-radius: 2px;
+ display: flex;
+ flex-direction: row;
+ font-family: inherit;
+ font-size: 12px;
+ height: 24px;
+ width: 172px;
+}
+
+channel-label {
+ align-items: center;
+ display: flex;
+ flex-direction: row;
+ height: 24px;
+ justify-content: center;
+ width: 172px;
+}
+
+submission-controls {
+ align-items: center;
+ border-top: 1px solid #CECECE;
+ display: flex;
+ flex-direction: row;
+ height: 13%;
+}
+
+#submission-controls-padding {
+ height: 100%;
+ width: 84%;
+}
+
+submission-button {
+ padding: 3%;
+ text-align: center;
+ width: 8%;
+}
+
+submission-button:hover {
+ background-color: #F3F3F3;
+ border-radius: 2px;
+} \ No newline at end of file
diff --git a/chromium/third_party/blink/renderer/core/html/forms/resources/color_picker.js b/chromium/third_party/blink/renderer/core/html/forms/resources/color_picker.js
new file mode 100644
index 00000000000..4bebefacfa0
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/html/forms/resources/color_picker.js
@@ -0,0 +1,437 @@
+// Copyright (C) 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+/**
+ * @fileoverview Color picker used by <input type='color' />
+ */
+
+/**
+ * @param {!Object} args
+ */
+function initializeColorPicker() {
+ if (global.params.selectedColor === undefined) {
+ global.params.selectedColor = DefaultColor;
+ }
+ const colorPicker = new ColorPicker(new Color(global.params.selectedColor));
+ main.append(colorPicker);
+ const width = colorPicker.offsetWidth;
+ const height = colorPicker.offsetHeight;
+ resizeWindow(width, height);
+}
+
+/**
+ * @param {!Object} args
+ * @return {?string} An error message, or null if the argument has no errors.
+ */
+function validateColorPickerArguments(args) {
+ if (args.shouldShowColorSuggestionPicker)
+ return 'Should be showing the color suggestion picker.'
+ if (!args.selectedColor)
+ return 'No selectedColor.';
+ return null;
+}
+
+/**
+ * Supported color channels.
+ * @enum {number}
+ */
+const ColorChannel = {
+ UNDEFINED: 0,
+ HEX: 1,
+ R: 2,
+ G: 3,
+ B: 4,
+ H: 5,
+ S: 6,
+ L: 7,
+};
+
+/**
+ * Supported color formats.
+ * @enum {number}
+ */
+const ColorFormat = {
+ UNDEFINED: 0,
+ HEX: 1,
+ RGB: 2,
+ HSL: 3,
+};
+
+/**
+ * Color: Helper class to get color values in different color formats.
+ */
+class Color {
+ /**
+ * @param {string|!ColorFormat} colorStringOrFormat
+ * @param {...number} colorValues ignored if colorStringOrFormat is a string
+ */
+ constructor(colorStringOrFormat, ...colorValues) {
+ if (typeof colorStringOrFormat === 'string') {
+ colorStringOrFormat = colorStringOrFormat.toLowerCase();
+ if (colorStringOrFormat.startsWith('#')) {
+ this.hexValue_ = colorStringOrFormat.substr(1);
+ }
+ // TODO(crbug.com/982087): Add support for RGB
+ // TODO(crbug.com/982088): Add support for HSL
+ } else {
+ switch(colorStringOrFormat) {
+ case ColorFormat.HEX:
+ this.hexValue_ = colorValues[0];
+ break;
+ // TODO(crbug.com/982087): Add support for RGB
+ // TODO(crbug.com/982088): Add support for HSL
+ }
+ }
+ }
+
+ /**
+ * @param {!Color} other
+ */
+ equals(other) {
+ return (this.hexValue_ === other.hexValue_);
+ }
+
+ get hexValue() {
+ return this.hexValue_;
+ }
+
+ asHex() {
+ return '#' + this.hexValue_;
+ }
+}
+
+/**
+ * ColorPicker: Custom element providing a color picker implementation.
+ * A color picker is comprised of three main parts: a visual color
+ * picker to allow visual selection of colors, a manual color
+ * picker to allow numeric selection of colors, and submission
+ * controls to save/discard new color selections.
+ */
+class ColorPicker extends HTMLElement {
+ /**
+ * @param {!Color} initialColor
+ */
+ constructor(initialColor) {
+ super();
+
+ this.selectedColor_ = initialColor;
+
+ this.visualColorPicker_ = new VisualColorPicker(initialColor);
+ this.manualColorPicker_ = new ManualColorPicker(initialColor);
+ this.submissionControls_ =
+ new SubmissionControls(this.onSubmitButtonClick_,
+ this.onCancelButtonClick_);
+ this.append(this.visualColorPicker_,
+ this.manualColorPicker_,
+ this.submissionControls_);
+
+ this.manualColorPicker_
+ .addEventListener('manual-color-change', this.onManualColorChange_);
+ }
+
+ get selectedColor() {
+ return this.selectedColor_;
+ }
+
+ /**
+ * @param {!Color} newColor
+ */
+ set selectedColor(newColor) {
+ this.selectedColor_ = newColor;
+ }
+
+ /**
+ * @param {!Event} event
+ */
+ onManualColorChange_ = (event) => {
+ var newColor = event.detail.color;
+ if (!this.selectedColor.equals(newColor)) {
+ this.selectedColor = newColor;
+ this.visualColorPicker_.setSelectedColor(newColor);
+ }
+ }
+
+ onSubmitButtonClick_ = () => {
+ const selectedValue = this.selectedColor_.asHex();
+ window.setTimeout(function() {
+ window.pagePopupController.setValueAndClosePopup(0, selectedValue);
+ }, 100);
+ }
+
+ onCancelButtonClick_ = () => {
+ window.pagePopupController.closePopup();
+ }
+}
+window.customElements.define('color-picker', ColorPicker);
+
+/**
+ * VisualColorPicker: Provides functionality to see the selected color and
+ * select a different color visually.
+ * TODO(crbug.com/983311): Allow colors to be selected from within the visual
+ * color picker.
+ */
+class VisualColorPicker extends HTMLElement {
+ /**
+ * @param {!Color} initialColor
+ */
+ constructor(initialColor) {
+ super();
+
+ this.setSelectedColor(initialColor);
+ }
+
+ /**
+ * @param {!Color} newColor
+ */
+ setSelectedColor(newColor) {
+ this.style.backgroundColor = newColor.asHex();
+ }
+}
+window.customElements.define('visual-color-picker', VisualColorPicker);
+
+/**
+ * ManualColorPicker: Provides functionality to change the selected color by
+ * manipulating its numeric values.
+ */
+class ManualColorPicker extends HTMLElement {
+ /**
+ * @param {!Color} initialColor
+ */
+ constructor(initialColor) {
+ super();
+
+ this.colorValueContainers_ = [
+ new ColorValueContainer(ColorFormat.HEX,
+ initialColor)
+ // TODO(crbug.com/982087): Add support for RGB
+ // TODO(crbug.com/982088): Add support for HSL
+ ];
+ this.formatToggler_ = new FormatToggler();
+ this.append(...this.colorValueContainers_, this.formatToggler_);
+ }
+}
+window.customElements.define('manual-color-picker', ManualColorPicker);
+
+/**
+ * ColorValueContainer: Maintains a set of channel values that make up a given
+ * color format, and tracks value changes.
+ */
+class ColorValueContainer extends HTMLElement {
+ /**
+ * @param {!ColorFormat} colorFormat
+ * @param {!Color} initialColor
+ */
+ constructor(colorFormat, initialColor) {
+ super();
+
+ this.colorFormat_ = colorFormat;
+ this.channelValueContainers_ = [];
+ if (this.colorFormat_ === ColorFormat.HEX) {
+ const hexValueContainer =
+ new ChannelValueContainer(ColorChannel.HEX,
+ initialColor);
+ this.channelValueContainers_.push(hexValueContainer);
+ }
+ this.append(...this.channelValueContainers_);
+
+ this.channelValueContainers_.forEach((channelValueContainer) =>
+ channelValueContainer.addEventListener('input',
+ this.onChannelValueChange_));
+ }
+
+ get color() {
+ return new Color(this.colorFormat_,
+ ...this.channelValueContainers_.map((channelValueContainer) =>
+ channelValueContainer.channelValue));
+ }
+
+ onChannelValueChange_ = () => {
+ this.dispatchEvent(new CustomEvent('manual-color-change', {
+ bubbles: true,
+ detail: {
+ color: this.color
+ }
+ }));
+ }
+}
+window.customElements.define('color-value-container', ColorValueContainer);
+
+/**
+ * ChannelValueContainer: Maintains and displays the numeric value
+ * for a given color channel.
+ */
+class ChannelValueContainer extends HTMLInputElement {
+ /**
+ * @param {!ColorChannel} colorChannel
+ * @param {!Color} initialColor
+ */
+ constructor(colorChannel, initialColor) {
+ super();
+
+ this.setAttribute('type', 'text');
+ this.colorChannel_ = colorChannel;
+ switch(colorChannel) {
+ case ColorChannel.HEX:
+ this.setAttribute('maxlength', '7');
+ break;
+ // TODO(crbug.com/982087): Add support for RGB
+ // TODO(crbug.com/982088): Add support for HSL
+ }
+ this.setValue(initialColor);
+
+ this.addEventListener('input', this.onValueChange_);
+ }
+
+ get channelValue() {
+ return this.channelValue_;
+ }
+
+ /**
+ * @param {!Color} color
+ */
+ setValue(color) {
+ switch(this.colorChannel_) {
+ case ColorChannel.HEX:
+ this.channelValue_ = color.hexValue;
+ this.value = '#' + this.channelValue_;
+ break;
+ // TODO(crbug.com/982087): Add support for RGB
+ // TODO(crbug.com/982088): Add support for HSL
+ }
+ }
+
+ onValueChange_ = () => {
+ // Set this.channelValue_ based on the element's new value.
+ let value = this.value;
+ if (value) {
+ switch(this.colorChannel_) {
+ case ColorChannel.HEX:
+ if (value.startsWith('#')) {
+ value = value.substr(1);
+ if (value.match(/^[0-9a-fA-F]+$/)) {
+ // Ex. 'FFFFFF' => this.channelValue_ == 'FFFFFF'
+ // Ex. 'FF' => this.channelValue_ == '0000FF'
+ this.channelValue_ = ('000000' + value).slice(-6);
+ }
+ }
+ break;
+ // TODO(crbug.com/982087): Add support for RGB
+ // TODO(crbug.com/982088): Add support for HSL
+ }
+ }
+ }
+}
+window.customElements.define('channel-value-container',
+ ChannelValueContainer,
+ { extends: 'input' });
+
+/**
+ * FormatToggler: Button that powers switching between different color formats.
+ */
+class FormatToggler extends HTMLElement {
+ constructor() {
+ super();
+
+ this.colorFormatLabels_ = [
+ new FormatLabel(ColorFormat.HEX)
+ // TODO(crbug.com/982087): Add support for RGB
+ // TODO(crbug.com/982088): Add support for HSL
+ ];
+ this.append(...this.colorFormatLabels_);
+ }
+}
+window.customElements.define('format-toggler', FormatToggler);
+
+/**
+ * FormatLabel: Label for a given color format.
+ */
+class FormatLabel extends HTMLElement {
+ /**
+ * @param {!ColorFormat} colorFormat
+ */
+ constructor(colorFormat) {
+ super();
+
+ if (colorFormat === ColorFormat.HEX) {
+ this.hexChannelLabel_ = new ChannelLabel(ColorChannel.HEX);
+ this.append(this.hexChannelLabel_);
+ }
+ // TODO(crbug.com/982087): Add support for RGB
+ // TODO(crbug.com/982088): Add support for HSL
+ }
+}
+window.customElements.define('format-label', FormatLabel);
+
+/**
+ * ChannelLabel: Label for a color channel, to be used within a FormatLabel.
+ */
+class ChannelLabel extends HTMLElement {
+ /**
+ * @param {!ColorChannel} colorChannel
+ */
+ constructor(colorChannel) {
+ super();
+
+ if (colorChannel === ColorChannel.HEX) {
+ this.textContent = 'HEX';
+ }
+ // TODO(crbug.com/982087): Add support for RGB
+ // TODO(crbug.com/982088): Add support for HSL
+ }
+}
+window.customElements.define('channel-label', ChannelLabel);
+
+/**
+ * SubmissionControls: Provides functionality to submit or discard a change.
+ */
+class SubmissionControls extends HTMLElement {
+ /**
+ * @param {function} submitCallback executed if the submit button is clicked
+ * @param {function} cancelCallback executed if the cancel button is clicked
+ */
+ constructor(submitCallback, cancelCallback) {
+ super();
+
+ const padding = document.createElement('span');
+ padding.setAttribute('id', 'submission-controls-padding');
+ this.append(padding);
+
+ this.submitButton_ = new SubmissionButton(submitCallback,
+ '<svg width="14" height="10" viewBox="0 0 14 10" fill="none" ' +
+ 'xmlns="http://www.w3.org/2000/svg"><path d="M13.3516 ' +
+ '1.35156L5 9.71094L0.648438 5.35156L1.35156 4.64844L5 ' +
+ '8.28906L12.6484 0.648438L13.3516 1.35156Z" fill="black"/></svg>'
+ );
+ this.cancelButton_ = new SubmissionButton(cancelCallback,
+ '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" ' +
+ 'xmlns="http://www.w3.org/2000/svg"><path d="M7.71094 7L13.1016 ' +
+ '12.3984L12.3984 13.1016L7 7.71094L1.60156 13.1016L0.898438 ' +
+ '12.3984L6.28906 7L0.898438 1.60156L1.60156 0.898438L7 ' +
+ '6.28906L12.3984 0.898438L13.1016 1.60156L7.71094 7Z" ' +
+ 'fill="black"/></svg>'
+ );
+ this.append(this.submitButton_, this.cancelButton_);
+ }
+}
+window.customElements.define('submission-controls', SubmissionControls);
+
+/**
+ * SubmissionButton: Button with a custom look that can be clicked for
+ * a submission action.
+ */
+class SubmissionButton extends HTMLElement {
+ /**
+ * @param {function} clickCallback executed when the button is clicked
+ * @param {string} htmlString custom look for the button
+ */
+ constructor(clickCallback, htmlString) {
+ super();
+
+ this.setAttribute('tabIndex', '0');
+ this.innerHTML = htmlString;
+
+ this.addEventListener('click', clickCallback);
+ }
+}
+window.customElements.define('submission-button', SubmissionButton); \ No newline at end of file
diff --git a/chromium/third_party/blink/renderer/core/html/forms/resources/color_picker_common.js b/chromium/third_party/blink/renderer/core/html/forms/resources/color_picker_common.js
new file mode 100644
index 00000000000..ba1120a22f5
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/html/forms/resources/color_picker_common.js
@@ -0,0 +1,73 @@
+// Copyright (C) 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+var global = {argumentsReceived: false, params: null};
+
+// DefaultColor is used by ColorPicker when selectedColor is not provided.
+var DefaultColor = '#000000';
+
+// DefaultColorPalette is used by ColorSuggestionPicker when the list of values
+// is empty.
+var DefaultColorPalette = [
+ '#000000', '#404040', '#808080', '#c0c0c0', '#ffffff', '#980000', '#ff0000',
+ '#ff9900', '#ffff00', '#00ff00', '#00ffff', '#4a86e8', '#0000ff', '#9900ff',
+ '#ff00ff'
+];
+
+/**
+ * @param {Event} event
+ */
+function handleMessage(event) {
+ initialize(JSON.parse(event.data));
+ global.argumentsReceived = true;
+}
+
+if (window.dialogArguments) {
+ initialize(dialogArguments);
+} else {
+ window.addEventListener('message', handleMessage, false);
+ window.setTimeout(handleArgumentsTimeout, 1000);
+}
+
+/**
+ * @param {!Object} args
+ */
+function initialize(args) {
+ global.params = args;
+ var main = $('main');
+ main.innerHTML = '';
+ var errorString;
+ if (global.params.shouldShowColorSuggestionPicker) {
+ main.classList.add('color-suggestion-picker-main');
+ errorString = validateColorSuggestionPickerArguments(args);
+ } else {
+ main.classList.add('color-picker-main');
+ errorString = validateColorPickerArguments(args);
+ }
+ if (errorString) {
+ main.textContent = 'Internal error: ' + errorString;
+ resizeWindow(main.offsetWidth, main.offsetHeight);
+ } else {
+ if (global.params.shouldShowColorSuggestionPicker) {
+ initializeColorSuggestionPicker();
+ } else {
+ initializeColorPicker();
+ }
+ }
+}
+
+function handleArgumentsTimeout() {
+ if (global.argumentsReceived)
+ return;
+ // When an argument timeout happens, we do not have enough information to
+ // determine whether to show the color picker or color suggestion picker.
+ // In this case, we just choose to show the color suggestion picker.
+ var args = {
+ values: DefaultColorPalette,
+ otherColorLabel: 'Other...',
+ shouldShowColorSuggestionPicker: true,
+ selectedColor: DefaultColor,
+ };
+ initialize(args);
+} \ No newline at end of file
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 2e99f77d57b..2403a75d86b 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
@@ -17,6 +17,7 @@
opacity: 0;
position: absolute;
will-change: opacity, transform;
+ word-break: break-word;
}
#container.shown-initially {
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 edcf51cc978..3236fa974cb 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
@@ -115,7 +115,7 @@ void SearchInputType::StartSearchEventTimer() {
// After typing the first key, we wait 500ms.
// After the second key, 400ms, then 300, then 200 from then on.
unsigned step = std::min(length, 4u) - 1;
- TimeDelta timeout = TimeDelta::FromMilliseconds(500 - 100 * step);
+ base::TimeDelta timeout = base::TimeDelta::FromMilliseconds(500 - 100 * step);
search_event_timer_.StartOneShot(timeout, FROM_HERE);
}
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 a97ced5e7cc..bf029591f52 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
@@ -69,6 +69,13 @@ void SliderThumbElement::SetPositionFromValue() {
if (GetLayoutObject()) {
GetLayoutObject()->SetNeedsLayoutAndFullPaintInvalidation(
layout_invalidation_reason::kSliderValueChanged);
+ if (RuntimeEnabledFeatures::FormControlsRefreshEnabled()) {
+ HTMLInputElement* input(HostInput());
+ if (input && input->GetLayoutObject()) {
+ // the slider track selected value needs to be updated.
+ input->GetLayoutObject()->SetShouldDoFullPaintInvalidation();
+ }
+ }
}
}
@@ -160,10 +167,7 @@ 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()) {
- GetLayoutObject()->SetNeedsLayoutAndFullPaintInvalidation(
- layout_invalidation_reason::kSliderValueChanged);
- }
+ SetPositionFromValue();
}
void SliderThumbElement::StartDragging() {
@@ -258,14 +262,14 @@ bool SliderThumbElement::WillRespondToMouseClickEvents() {
return HTMLDivElement::WillRespondToMouseClickEvents();
}
-void SliderThumbElement::DetachLayoutTree(const AttachContext& context) {
+void SliderThumbElement::DetachLayoutTree(bool performing_reattach) {
if (in_drag_mode_) {
if (LocalFrame* frame = GetDocument().GetFrame()) {
frame->GetEventHandler().ReleasePointerCapture(
PointerEventFactory::kMouseId, this);
}
}
- HTMLDivElement::DetachLayoutTree(context);
+ HTMLDivElement::DetachLayoutTree(performing_reattach);
}
HTMLInputElement* SliderThumbElement::HostInput() const {
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 a487b992238..878816148bb 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
@@ -53,7 +53,7 @@ class SliderThumbElement final : public HTMLDivElement {
void DefaultEventHandler(Event&) override;
bool WillRespondToMouseMoveEvents() override;
bool WillRespondToMouseClickEvents() override;
- void DetachLayoutTree(const AttachContext& = AttachContext()) override;
+ void DetachLayoutTree(bool performing_reattach) override;
const AtomicString& ShadowPseudoId() const override;
HTMLInputElement* HostInput() const;
void SetPositionFromPoint(const LayoutPoint&);
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 8715d0e8c82..c64aee9cc72 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
@@ -58,9 +58,9 @@ SpinButtonElement::SpinButtonElement(Document& document,
setAttribute(kIdAttr, shadow_element_names::SpinButton());
}
-void SpinButtonElement::DetachLayoutTree(const AttachContext& context) {
+void SpinButtonElement::DetachLayoutTree(bool performing_reattach) {
ReleaseCapture(kEventDispatchDisallowed);
- HTMLDivElement::DetachLayoutTree(context);
+ HTMLDivElement::DetachLayoutTree(performing_reattach);
}
void SpinButtonElement::DefaultEventHandler(Event& event) {
@@ -236,10 +236,10 @@ void SpinButtonElement::RepeatingTimerFired(TimerBase*) {
Step(up_down_state_ == kUp ? 1 : -1);
}
-void SpinButtonElement::SetHovered(bool flag) {
- if (!flag)
+void SpinButtonElement::SetHovered(bool hovered) {
+ if (!hovered)
up_down_state_ = kIndeterminate;
- HTMLDivElement::SetHovered(flag);
+ HTMLDivElement::SetHovered(hovered);
}
bool SpinButtonElement::ShouldRespondToMouseEvents() {
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 5f0c939490d..fdbe80f8b26 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
@@ -78,7 +78,7 @@ class CORE_EXPORT SpinButtonElement final : public HTMLDivElement,
void Trace(Visitor*) override;
private:
- void DetachLayoutTree(const AttachContext&) override;
+ void DetachLayoutTree(bool performing_reattach) override;
bool IsSpinButtonElement() const override { return true; }
bool IsDisabledFormControl() const override {
return OwnerShadowHost() && OwnerShadowHost()->IsDisabledFormControl();
@@ -91,7 +91,7 @@ class CORE_EXPORT SpinButtonElement final : public HTMLDivElement,
void StartRepeatingTimer();
void StopRepeatingTimer();
void RepeatingTimerFired(TimerBase*);
- void SetHovered(bool = true) override;
+ void SetHovered(bool hovered) override;
bool ShouldRespondToMouseEvents();
bool IsMouseFocusable() const override { return false; }
@@ -102,16 +102,11 @@ class CORE_EXPORT SpinButtonElement final : public HTMLDivElement,
TaskRunnerTimer<SpinButtonElement> repeating_timer_;
};
-DEFINE_TYPE_CASTS(SpinButtonElement,
- Node,
- node,
- ToElement(node)->IsSpinButtonElement(),
- ToElement(node).IsSpinButtonElement());
-
template <>
struct DowncastTraits<SpinButtonElement> {
static bool AllowFrom(const Node& node) {
- return ToElement(node).IsSpinButtonElement();
+ auto* element = DynamicTo<Element>(node);
+ return element && element->IsSpinButtonElement();
}
};
diff --git a/chromium/third_party/blink/renderer/core/html/forms/step_range.h b/chromium/third_party/blink/renderer/core/html/forms/step_range.h
index b62c182a00d..796a496c438 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/step_range.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/step_range.h
@@ -22,7 +22,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_FORMS_STEP_RANGE_H_
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/decimal.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
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 77ca2c9b416..6379e8e70e3 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
@@ -32,11 +32,11 @@
#include "third_party/blink/renderer/core/html/forms/submit_input_type.h"
#include "third_party/blink/renderer/core/dom/events/event.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/html/forms/html_form_element.h"
#include "third_party/blink/renderer/core/html/forms/html_input_element.h"
#include "third_party/blink/renderer/core/input_type_names.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/text/platform_locale.h"
namespace blink {
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 908e990884f..f45bbabeac0 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
@@ -30,8 +30,8 @@
#include "third_party/blink/renderer/core/html/forms/telephone_input_type.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/input_type_names.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
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 955b5511d0d..b6ac38b3b2e 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
@@ -45,7 +45,6 @@
#include "third_party/blink/renderer/core/editing/text_affinity.h"
#include "third_party/blink/renderer/core/editing/visible_position.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/html/forms/text_control_inner_elements.h"
#include "third_party/blink/renderer/core/html/html_br_element.h"
#include "third_party/blink/renderer/core/html/html_div_element.h"
@@ -59,6 +58,7 @@
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
namespace blink {
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 97833d5673e..47c266d0474 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
@@ -234,7 +234,8 @@ class CORE_EXPORT TextControlElement : public HTMLFormControlElementWithState {
};
inline bool IsTextControl(const Node& node) {
- return node.IsElementNode() && ToElement(node).IsTextControl();
+ auto* element = DynamicTo<Element>(node);
+ return element && element->IsTextControl();
}
inline bool IsTextControl(const Node* node) {
return node && IsTextControl(*node);
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 acd7a0182bf..439e5b8ce6a 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
@@ -145,7 +145,7 @@ TextControlInnerEditorElement::CreateInnerEditorStyle() const {
text_block_style->SetUnicodeBidi(start_style.GetUnicodeBidi());
text_block_style->SetUserSelect(EUserSelect::kText);
text_block_style->SetUserModify(
- ToHTMLFormControlElement(host)->IsDisabledOrReadOnly()
+ To<HTMLFormControlElement>(host)->IsDisabledOrReadOnly()
? EUserModify::kReadOnly
: EUserModify::kReadWritePlaintextOnly);
text_block_style->SetDisplay(EDisplay::kBlock);
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 eaabf37e771..5f75f6f3269 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
@@ -37,7 +37,7 @@
#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/inspector/console_message.h"
-#include "third_party/blink/renderer/platform/date_components.h"
+#include "third_party/blink/renderer/platform/text/date_components.h"
#include "third_party/blink/renderer/platform/text/platform_locale.h"
#include "third_party/blink/renderer/platform/wtf/date_math.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
@@ -65,7 +65,8 @@ const AtomicString& TimeInputType::FormControlType() const {
Decimal TimeInputType::DefaultValueForStepUp() const {
DateComponents date;
- date.SetMillisecondsSinceMidnight(ConvertToLocalTime(CurrentTimeMS()));
+ date.SetMillisecondsSinceMidnight(
+ ConvertToLocalTime(base::Time::Now().ToDoubleT() * 1000.0));
double milliseconds = date.MillisecondsSinceEpoch();
DCHECK(std::isfinite(milliseconds));
return Decimal::FromDouble(milliseconds);
diff --git a/chromium/third_party/blink/renderer/core/html/forms/type_ahead.cc b/chromium/third_party/blink/renderer/core/html/forms/type_ahead.cc
index 1327ff78854..d1593e080c7 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/type_ahead.cc
+++ b/chromium/third_party/blink/renderer/core/html/forms/type_ahead.cc
@@ -37,7 +37,7 @@ namespace blink {
TypeAhead::TypeAhead(TypeAheadDataSource* data_source)
: data_source_(data_source), repeating_char_(0) {}
-constexpr TimeDelta kTypeAheadTimeout = TimeDelta::FromSecondsD(1);
+constexpr base::TimeDelta kTypeAheadTimeout = base::TimeDelta::FromSecondsD(1);
static String StripLeadingWhiteSpace(const String& string) {
unsigned length = string.length();
@@ -123,7 +123,7 @@ int TypeAhead::HandleEvent(const KeyboardEvent& event,
bool TypeAhead::HasActiveSession(const KeyboardEvent& event) {
if (!last_type_time_)
return false;
- TimeDelta delta = event.PlatformTimeStamp() - *last_type_time_;
+ base::TimeDelta delta = event.PlatformTimeStamp() - *last_type_time_;
return delta <= kTypeAheadTimeout;
}
diff --git a/chromium/third_party/blink/renderer/core/html/forms/type_ahead.h b/chromium/third_party/blink/renderer/core/html/forms/type_ahead.h
index 033d37ea432..cefa090bc85 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/type_ahead.h
+++ b/chromium/third_party/blink/renderer/core/html/forms/type_ahead.h
@@ -28,7 +28,7 @@
#include "base/optional.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.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/time.h"
@@ -67,7 +67,7 @@ class CORE_EXPORT TypeAhead {
private:
TypeAheadDataSource* data_source_;
// platform timestamp of last keyboard event in seconds
- base::Optional<TimeTicks> last_type_time_;
+ base::Optional<base::TimeTicks> last_type_time_;
UChar repeating_char_;
StringBuilder buffer_;
};
diff --git a/chromium/third_party/blink/renderer/core/html/forms/validity_state.idl b/chromium/third_party/blink/renderer/core/html/forms/validity_state.idl
index 5c5d868e350..b5c520470a9 100644
--- a/chromium/third_party/blink/renderer/core/html/forms/validity_state.idl
+++ b/chromium/third_party/blink/renderer/core/html/forms/validity_state.idl
@@ -22,6 +22,7 @@
// https://html.spec.whatwg.org/C/#validitystate
+[Exposed=Window]
interface ValidityState {
readonly attribute boolean valueMissing;
readonly attribute boolean typeMismatch;
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 c78dbcdd313..c6567554f0b 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
@@ -35,7 +35,7 @@
#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/platform/date_components.h"
+#include "third_party/blink/renderer/platform/text/date_components.h"
#include "third_party/blink/renderer/platform/text/platform_locale.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
diff --git a/chromium/third_party/blink/renderer/core/html/html_all_collection.idl b/chromium/third_party/blink/renderer/core/html/html_all_collection.idl
index 76d31705bb2..6a007bfeadf 100644
--- a/chromium/third_party/blink/renderer/core/html/html_all_collection.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_all_collection.idl
@@ -27,6 +27,7 @@
// https://html.spec.whatwg.org/C/#the-htmlallcollection-interface
[
+ Exposed=Window,
Custom=LegacyCallAsFunction,
LegacyUnenumerableNamedProperties
] interface 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 d57c5bc0ebd..b609ff94f66 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
@@ -37,7 +37,6 @@
#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"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/anchor_element_metrics.h"
#include "third_party/blink/renderer/core/html/anchor_element_metrics_sender.h"
#include "third_party/blink/renderer/core/html/html_image_element.h"
@@ -51,12 +50,54 @@
#include "third_party/blink/renderer/core/trustedtypes/trusted_types_util.h"
#include "third_party/blink/renderer/core/trustedtypes/trusted_url.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/weborigin/security_policy.h"
namespace blink {
+namespace {
+
+// Note: Here it covers download originated from clicking on <a download> link
+// that results in direct download. Features in this method can also be logged
+// from browser for download due to navigations to non-web-renderable content.
+bool ShouldInterveneDownloadByFramePolicy(LocalFrame* frame) {
+ bool should_intervene_download = false;
+ Document& document = *(frame->GetDocument());
+ UseCounter::Count(document, WebFeature::kDownloadPrePolicyCheck);
+ bool has_gesture = LocalFrame::HasTransientUserActivation(frame);
+ if (!has_gesture) {
+ UseCounter::Count(document, WebFeature::kDownloadWithoutUserGesture);
+ }
+ if (frame->IsAdSubframe()) {
+ UseCounter::Count(document, WebFeature::kDownloadInAdFrame);
+ if (!has_gesture) {
+ UseCounter::Count(document,
+ WebFeature::kDownloadInAdFrameWithoutUserGesture);
+ if (base::FeatureList::IsEnabled(
+ blink::features::
+ kBlockingDownloadsInAdFrameWithoutUserActivation))
+ should_intervene_download = true;
+ }
+ }
+ if (document.IsSandboxed(WebSandboxFlags::kDownloads)) {
+ UseCounter::Count(document, WebFeature::kDownloadInSandbox);
+ if (!has_gesture) {
+ UseCounter::Count(document,
+ WebFeature::kDownloadInSandboxWithoutUserGesture);
+ if (RuntimeEnabledFeatures::
+ BlockingDownloadsInSandboxWithoutUserActivationEnabled())
+ should_intervene_download = true;
+ }
+ }
+ if (!should_intervene_download)
+ UseCounter::Count(document, WebFeature::kDownloadPostPolicyCheck);
+ return should_intervene_download;
+}
+
+} // namespace
+
using namespace html_names;
HTMLAnchorElement::HTMLAnchorElement(Document& document)
@@ -170,11 +211,11 @@ bool HTMLAnchorElement::HasActivationBehavior() const {
return true;
}
-void HTMLAnchorElement::SetActive(bool down) {
+void HTMLAnchorElement::SetActive(bool active) {
if (HasEditableStyle(*this))
return;
- ContainerNode::SetActive(down);
+ HTMLElement::SetActive(active);
}
const AttrNameToTrustedType& HTMLAnchorElement::GetCheckedAttributeTypes()
@@ -381,7 +422,8 @@ void HTMLAnchorElement::HandleClick(Event& event) {
!HasRel(kRelationNoReferrer)) {
UseCounter::Count(GetDocument(),
WebFeature::kHTMLAnchorElementReferrerPolicyAttribute);
- request.SetReferrerPolicy(policy);
+ request.SetReferrerPolicy(
+ policy, ResourceRequest::SetReferrerPolicyLocation::kAnchorElement);
}
// Ignore the download attribute if we either can't read the content, or
@@ -389,33 +431,8 @@ void HTMLAnchorElement::HandleClick(Event& event) {
if (hasAttribute(kDownloadAttr) &&
NavigationPolicyFromEvent(&event) != kNavigationPolicyDownload &&
GetDocument().GetSecurityOrigin()->CanReadContent(completed_url)) {
- UseCounter::Count(GetDocument(), WebFeature::kDownloadPrePolicyCheck);
- bool has_gesture = LocalFrame::HasTransientUserActivation(frame);
- if (frame->IsAdSubframe()) {
- // Note: Here it covers download originated from clicking on <a download>
- // link that results in direct download. These two features can also be
- // logged from browser for download due to navigations to
- // non-web-renderable content.
- UseCounter::Count(GetDocument(),
- has_gesture
- ? WebFeature::kDownloadInAdFrameWithUserGesture
- : WebFeature::kDownloadInAdFrameWithoutUserGesture);
- if (!has_gesture &&
- base::FeatureList::IsEnabled(
- blink::features::
- kBlockingDownloadsInAdFrameWithoutUserActivation))
- return;
- }
- if (GetDocument().IsSandboxed(WebSandboxFlags::kDownloads)) {
- if (!has_gesture) {
- UseCounter::Count(GetDocument(),
- WebFeature::kDownloadInSandboxWithoutUserGesture);
- if (RuntimeEnabledFeatures::
- BlockingDownloadsInSandboxWithoutUserActivationEnabled())
- return;
- }
- }
- UseCounter::Count(GetDocument(), WebFeature::kDownloadPostPolicyCheck);
+ if (ShouldInterveneDownloadByFramePolicy(frame))
+ return;
request.SetSuggestedFilename(
static_cast<String>(FastGetAttribute(kDownloadAttr)));
request.SetRequestContext(mojom::RequestContextType::DOWNLOAD);
@@ -426,6 +443,7 @@ void HTMLAnchorElement::HandleClick(Event& event) {
}
request.SetRequestContext(mojom::RequestContextType::HYPERLINK);
+ request.SetHasUserGesture(LocalFrame::HasTransientUserActivation(frame));
const AtomicString& target = getAttribute(kTargetAttr);
FrameLoadRequest frame_request(&GetDocument(), request);
frame_request.SetNavigationPolicy(NavigationPolicyFromEvent(&event));
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 25b4cc9d71b..fd135eee8a5 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
@@ -113,7 +113,7 @@ class CORE_EXPORT HTMLAnchorElement : public HTMLElement, public DOMURLUtils {
bool IsKeyboardFocusable() const override;
void DefaultEventHandler(Event&) final;
bool HasActivationBehavior() const override;
- void SetActive(bool = true) final;
+ void SetActive(bool active) final;
void AccessKeyAction(bool send_mouse_events) final;
bool IsURLAttribute(const Attribute&) const final;
bool HasLegalLinkAttribute(const QualifiedName&) const final;
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 bc7dc363aa3..6520bacb61e 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
@@ -19,8 +19,10 @@
*/
// https://html.spec.whatwg.org/C/#the-a-element
-[HTMLConstructor]
-interface HTMLAnchorElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLAnchorElement : HTMLElement {
[CEReactions, Reflect] attribute DOMString target;
[CEReactions, Reflect] attribute DOMString download;
[CEReactions, Reflect] attribute USVString ping;
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 b8a62567c20..3df9f0aff0a 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
@@ -86,15 +86,15 @@ void HTMLAreaElement::InvalidateCachedPath() {
path_ = nullptr;
}
-bool HTMLAreaElement::PointInArea(const LayoutPoint& location,
+bool HTMLAreaElement::PointInArea(const PhysicalOffset& location,
const LayoutObject* container_object) const {
return GetPath(container_object).Contains(FloatPoint(location));
}
-LayoutRect HTMLAreaElement::ComputeAbsoluteRect(
+PhysicalRect HTMLAreaElement::ComputeAbsoluteRect(
const LayoutObject* container_object) const {
if (!container_object)
- return LayoutRect();
+ return PhysicalRect();
// FIXME: This doesn't work correctly with transforms.
PhysicalOffset abs_pos = container_object->LocalToAbsolutePoint(
@@ -102,7 +102,7 @@ LayoutRect HTMLAreaElement::ComputeAbsoluteRect(
Path path = GetPath(container_object);
path.Translate(FloatSize(abs_pos));
- return EnclosingLayoutRect(path.BoundingRect());
+ return PhysicalRect::EnclosingRect(path.BoundingRect());
}
Path HTMLAreaElement::GetPath(const LayoutObject* container_object) const {
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 6dece5190db..2e6f36cc14a 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
@@ -27,7 +27,7 @@
#include "third_party/blink/public/platform/web_focus_type.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/html/html_anchor_element.h"
-#include "third_party/blink/renderer/platform/geometry/layout_rect.h"
+#include "third_party/blink/renderer/core/layout/geometry/physical_rect.h"
namespace blink {
@@ -49,9 +49,9 @@ class CORE_EXPORT HTMLAreaElement final : public HTMLAnchorElement {
// specified container object, e.g. the rectangle of the default shape will
// be the border box rect of the container object, and effective zoom factor
// of the container object will be applied on non-default shape.
- bool PointInArea(const LayoutPoint&,
+ bool PointInArea(const PhysicalOffset&,
const LayoutObject* container_object) const;
- LayoutRect ComputeAbsoluteRect(const LayoutObject* container_object) const;
+ PhysicalRect ComputeAbsoluteRect(const LayoutObject* container_object) const;
Path GetPath(const LayoutObject* container_object) const;
// The parent map's image.
diff --git a/chromium/third_party/blink/renderer/core/html/html_area_element.idl b/chromium/third_party/blink/renderer/core/html/html_area_element.idl
index a6d1728ce17..e213527f286 100644
--- a/chromium/third_party/blink/renderer/core/html/html_area_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_area_element.idl
@@ -19,8 +19,10 @@
*/
// https://html.spec.whatwg.org/C/#the-area-element
-[HTMLConstructor]
-interface HTMLAreaElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLAreaElement : HTMLElement {
[CEReactions, Reflect] attribute DOMString alt;
[CEReactions, Reflect] attribute DOMString coords;
[CEReactions, Reflect] attribute DOMString download;
diff --git a/chromium/third_party/blink/renderer/core/html/html_base_element.idl b/chromium/third_party/blink/renderer/core/html/html_base_element.idl
index 5d6fec7e085..40e2384c977 100644
--- a/chromium/third_party/blink/renderer/core/html/html_base_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_base_element.idl
@@ -18,8 +18,10 @@
*/
// https://html.spec.whatwg.org/C/#the-base-element
-[HTMLConstructor]
-interface HTMLBaseElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLBaseElement : HTMLElement {
[CEReactions, RaisesException=Setter] attribute URLString href;
[CEReactions, Reflect] attribute DOMString target;
};
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 f47282d2faa..12508098102 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
@@ -33,10 +33,10 @@
#include "third_party/blink/renderer/core/dom/attribute.h"
#include "third_party/blink/renderer/core/editing/editing_utilities.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/html/html_frame_element_base.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/platform/instrumentation/use_counter.h"
namespace blink {
@@ -65,7 +65,8 @@ void HTMLBodyElement::CollectStyleForPresentationAttribute(
CSSImageValue* image_value =
CSSImageValue::Create(url, GetDocument().CompleteURL(url),
Referrer(GetDocument().OutgoingReferrer(),
- GetDocument().GetReferrerPolicy()));
+ GetDocument().GetReferrerPolicy()),
+ OriginClean::kTrue);
image_value->SetInitiator(localName());
style->SetProperty(
CSSPropertyValue(GetCSSPropertyBackgroundImage(), *image_value));
diff --git a/chromium/third_party/blink/renderer/core/html/html_body_element.idl b/chromium/third_party/blink/renderer/core/html/html_body_element.idl
index c616fb17f90..53a8f4be820 100644
--- a/chromium/third_party/blink/renderer/core/html/html_body_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_body_element.idl
@@ -19,8 +19,10 @@
*/
// https://html.spec.whatwg.org/C/#the-body-element
-[HTMLConstructor]
-interface HTMLBodyElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLBodyElement : HTMLElement {
// obsolete members
// https://html.spec.whatwg.org/C/#HTMLBodyElement-partial
[CEReactions, Reflect] attribute [TreatNullAs=EmptyString] DOMString text;
diff --git a/chromium/third_party/blink/renderer/core/html/html_br_element.idl b/chromium/third_party/blink/renderer/core/html/html_br_element.idl
index 22ebfae8953..2751dd6a3da 100644
--- a/chromium/third_party/blink/renderer/core/html/html_br_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_br_element.idl
@@ -18,8 +18,10 @@
*/
// https://html.spec.whatwg.org/C/#the-br-element
-[HTMLConstructor]
-interface HTMLBRElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLBRElement : HTMLElement {
// obsolete members
// https://html.spec.whatwg.org/C/#HTMLBRElement-partial
[CEReactions, Reflect] attribute DOMString clear;
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 b8685a291a2..4088f9f5a68 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
@@ -31,9 +31,9 @@
#include "third_party/blink/renderer/core/dom/qualified_name.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/dom/shadow_root_v0.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/html_content_element.h b/chromium/third_party/blink/renderer/core/html/html_content_element.h
index ecc7ead996e..83db8015a5f 100644
--- a/chromium/third_party/blink/renderer/core/html/html_content_element.h
+++ b/chromium/third_party/blink/renderer/core/html/html_content_element.h
@@ -88,9 +88,10 @@ inline bool HTMLContentElement::CanSelectNode(
return true;
if (!IsSelectValid())
return false;
- if (!siblings[nth]->IsElementNode())
+ auto* element = DynamicTo<Element>(siblings[nth].Get());
+ if (!element)
return false;
- return MatchSelector(*ToElement(siblings[nth]));
+ return MatchSelector(*element);
}
} // namespace blink
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 9a53b1ab1ee..12219a7cbdc 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
@@ -4,7 +4,7 @@
#include "third_party/blink/renderer/core/html/html_data_element.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/html_data_element.idl b/chromium/third_party/blink/renderer/core/html/html_data_element.idl
index 3006a5c5bf6..6afc98787d7 100644
--- a/chromium/third_party/blink/renderer/core/html/html_data_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_data_element.idl
@@ -4,7 +4,9 @@
// https://html.spec.whatwg.org/C/#the-data-element
-[HTMLConstructor]
-interface HTMLDataElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLDataElement : HTMLElement {
[CEReactions, Reflect] attribute DOMString value;
}; \ No newline at end of file
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 c4ef49e76b8..4fdb5112b30 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
@@ -27,7 +27,6 @@
#include "third_party/blink/renderer/core/dom/events/event.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/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/html_div_element.h"
#include "third_party/blink/renderer/core/html/html_slot_element.h"
#include "third_party/blink/renderer/core/html/html_summary_element.h"
@@ -38,6 +37,7 @@
#include "third_party/blink/renderer/core/layout/layout_object_factory.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/text/platform_locale.h"
namespace blink {
@@ -102,7 +102,7 @@ Element* HTMLDetailsElement::FindMainSummary() const {
HTMLSlotElement* slot = To<HTMLSlotElement>(element);
DCHECK(slot->firstChild());
CHECK(IsHTMLSummaryElement(*slot->firstChild()));
- return ToElement(slot->firstChild());
+ return To<Element>(slot->firstChild());
}
void HTMLDetailsElement::ParseAttribute(
diff --git a/chromium/third_party/blink/renderer/core/html/html_details_element.idl b/chromium/third_party/blink/renderer/core/html/html_details_element.idl
index 70eb7308ace..20036a92617 100644
--- a/chromium/third_party/blink/renderer/core/html/html_details_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_details_element.idl
@@ -18,7 +18,9 @@
*/
// https://html.spec.whatwg.org/C/#the-details-element
-[HTMLConstructor]
-interface HTMLDetailsElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLDetailsElement : HTMLElement {
[CEReactions, Reflect] attribute boolean open;
};
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 5f1414d0867..e1697bd25d8 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
@@ -30,11 +30,11 @@
#include "third_party/blink/renderer/core/dom/flat_tree_traversal.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/use_counter.h"
#include "third_party/blink/renderer/core/fullscreen/fullscreen.h"
#include "third_party/blink/renderer/core/html/forms/html_form_control_element.h"
#include "third_party/blink/renderer/core/html/html_frame_owner_element.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
@@ -54,11 +54,10 @@ static void SetFocusForDialog(HTMLDialogElement* dialog) {
? FlatTreeTraversal::NextSkippingChildren(*node, dialog)
: FlatTreeTraversal::Next(*node, dialog);
- if (!node->IsElementNode())
+ auto* element = DynamicTo<Element>(node);
+ if (!element)
continue;
- Element* element = ToElement(node);
- if (element->IsFormControlElement()) {
- HTMLFormControlElement* control = ToHTMLFormControlElement(node);
+ if (auto* control = DynamicTo<HTMLFormControlElement>(node)) {
if (control->IsAutofocusable() && control->IsFocusable()) {
control->focus();
return;
diff --git a/chromium/third_party/blink/renderer/core/html/html_dialog_element.idl b/chromium/third_party/blink/renderer/core/html/html_dialog_element.idl
index 2a695087404..3137ce1fad8 100644
--- a/chromium/third_party/blink/renderer/core/html/html_dialog_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_dialog_element.idl
@@ -24,8 +24,10 @@
*/
// https://html.spec.whatwg.org/C/#the-dialog-element
-[HTMLConstructor]
-interface HTMLDialogElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLDialogElement : HTMLElement {
[CEReactions, Reflect] attribute boolean open;
attribute DOMString returnValue;
[CEReactions] void show();
diff --git a/chromium/third_party/blink/renderer/core/html/html_dimension.h b/chromium/third_party/blink/renderer/core/html/html_dimension.h
index ba44b61d045..2a3bf96070d 100644
--- a/chromium/third_party/blink/renderer/core/html/html_dimension.h
+++ b/chromium/third_party/blink/renderer/core/html/html_dimension.h
@@ -32,7 +32,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_HTML_DIMENSION_H_
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
diff --git a/chromium/third_party/blink/renderer/core/html/html_directory_element.idl b/chromium/third_party/blink/renderer/core/html/html_directory_element.idl
index 58b0922b2fd..fe91d06eb03 100644
--- a/chromium/third_party/blink/renderer/core/html/html_directory_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_directory_element.idl
@@ -18,7 +18,9 @@
*/
// https://html.spec.whatwg.org/C/#htmldirectoryelement
-[HTMLConstructor]
-interface HTMLDirectoryElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLDirectoryElement : HTMLElement {
[CEReactions, Reflect] attribute boolean compact;
};
diff --git a/chromium/third_party/blink/renderer/core/html/html_div_element.idl b/chromium/third_party/blink/renderer/core/html/html_div_element.idl
index 04a0751b44f..3ae69647321 100644
--- a/chromium/third_party/blink/renderer/core/html/html_div_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_div_element.idl
@@ -18,8 +18,10 @@
*/
// https://html.spec.whatwg.org/C/#the-div-element
-[HTMLConstructor]
-interface HTMLDivElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLDivElement : HTMLElement {
// obsolete members
// https://html.spec.whatwg.org/C/#HTMLDivElement-partial
[CEReactions, Reflect] attribute DOMString align;
diff --git a/chromium/third_party/blink/renderer/core/html/html_dlist_element.idl b/chromium/third_party/blink/renderer/core/html/html_dlist_element.idl
index ef594e14ec2..bf5e720cfe3 100644
--- a/chromium/third_party/blink/renderer/core/html/html_dlist_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_dlist_element.idl
@@ -18,8 +18,10 @@
*/
// https://html.spec.whatwg.org/C/#the-dl-element
-[HTMLConstructor]
-interface HTMLDListElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLDListElement : HTMLElement {
// obsolete members
// https://html.spec.whatwg.org/C/#HTMLDListElement-partial
[CEReactions, Reflect] attribute boolean compact;
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 fd65513f592..3db77e5071a 100644
--- a/chromium/third_party/blink/renderer/core/html/html_document.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_document.cc
@@ -81,7 +81,8 @@ Document* HTMLDocument::CloneDocumentWithoutChildren() const {
DocumentInit::Create()
.WithContextDocument(ContextDocument())
.WithURL(Url())
- .WithRegistrationContext(RegistrationContext()));
+ .WithRegistrationContext(RegistrationContext())
+ .WithOriginToCommit(GetSecurityOrigin()->IsolatedCopy()));
}
// --------------------------------------------------------------------------
diff --git a/chromium/third_party/blink/renderer/core/html/html_document.idl b/chromium/third_party/blink/renderer/core/html/html_document.idl
index 938136e4fe8..24f6db850d2 100644
--- a/chromium/third_party/blink/renderer/core/html/html_document.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_document.idl
@@ -22,6 +22,6 @@
// writable, configurable, non-enumerable property named HTMLDocument
// whose value is the Document interface object."
// https://html.spec.whatwg.org/C/#the-window-object
-
+[Exposed=Window]
interface HTMLDocument : Document {
};
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 f85f8a20b07..b6b0f3e7a45 100644
--- a/chromium/third_party/blink/renderer/core/html/html_element.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_element.cc
@@ -52,7 +52,6 @@
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.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"
#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"
@@ -76,12 +75,12 @@
#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/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/language.h"
#include "third_party/blink/renderer/platform/text/bidi_resolver.h"
#include "third_party/blink/renderer/platform/text/bidi_text_run.h"
#include "third_party/blink/renderer/platform/text/text_run_iterator.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
-#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
namespace blink {
@@ -127,10 +126,10 @@ bool IsEditable(const Node& node) {
return true;
if (IsSVGSVGElement(node))
return true;
- if (node.IsElementNode() &&
- ToElement(node).HasTagName(mathml_names::kMathTag))
+ auto* element = DynamicTo<Element>(node);
+ if (element && element->HasTagName(mathml_names::kMathTag))
return true;
- return !node.IsElementNode() && node.parentNode()->IsHTMLElement();
+ return !element && node.parentNode()->IsHTMLElement();
}
const WebFeature kNoWebFeature = static_cast<WebFeature>(0);
@@ -1044,19 +1043,19 @@ TextDirection HTMLElement::Directionality() const {
Node* node = FlatTreeTraversal::FirstChild(*this);
while (node) {
// Skip bdi, script, style and text form controls.
+ auto* element = DynamicTo<Element>(node);
if (DeprecatedEqualIgnoringCase(node->nodeName(), "bdi") ||
IsHTMLScriptElement(*node) || IsHTMLStyleElement(*node) ||
- (node->IsElementNode() && ToElement(node)->IsTextControl()) ||
- (node->IsElementNode() &&
- ToElement(node)->ShadowPseudoId() == "-webkit-input-placeholder")) {
+ (element && element->IsTextControl()) ||
+ (element && element->ShadowPseudoId() == "-webkit-input-placeholder")) {
node = FlatTreeTraversal::NextSkippingChildren(*node, this);
continue;
}
// Skip elements with valid dir attribute
- if (node->IsElementNode()) {
+ if (auto* element_node = DynamicTo<Element>(node)) {
AtomicString dir_attribute_value =
- ToElement(node)->FastGetAttribute(kDirAttr);
+ element_node->FastGetAttribute(kDirAttr);
if (IsValidDirAttribute(dir_attribute_value)) {
node = FlatTreeTraversal::NextSkippingChildren(*node, this);
continue;
@@ -1545,6 +1544,6 @@ void HTMLElement::FinishParsingChildren() {
void dumpInnerHTML(blink::HTMLElement*);
void dumpInnerHTML(blink::HTMLElement* element) {
- printf("%s\n", element->InnerHTMLAsString().Ascii().data());
+ printf("%s\n", element->InnerHTMLAsString().Ascii().c_str());
}
#endif
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 2b858287be3..c6adefece61 100644
--- a/chromium/third_party/blink/renderer/core/html/html_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_element.idl
@@ -19,8 +19,10 @@
*/
// https://html.spec.whatwg.org/C/#htmlelement
-[HTMLConstructor]
-interface HTMLElement : Element {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLElement : Element {
// metadata attributes
[CEReactions, Reflect] attribute DOMString title;
[CEReactions, Reflect] attribute DOMString lang;
diff --git a/chromium/third_party/blink/renderer/core/html/html_embed_element.idl b/chromium/third_party/blink/renderer/core/html/html_embed_element.idl
index 1e698b5e0e9..800a6bc7075 100644
--- a/chromium/third_party/blink/renderer/core/html/html_embed_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_embed_element.idl
@@ -22,6 +22,7 @@
// TODO(yukishiino): HTMLEmbedElement should not have [OverrideBuiltins].
[
+ Exposed=Window,
OverrideBuiltins,
ActiveScriptWrappable,
HTMLConstructor
diff --git a/chromium/third_party/blink/renderer/core/html/html_font_element.idl b/chromium/third_party/blink/renderer/core/html/html_font_element.idl
index 8ff4ec16a67..b4f6d99e93b 100644
--- a/chromium/third_party/blink/renderer/core/html/html_font_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_font_element.idl
@@ -18,8 +18,10 @@
*/
// https://html.spec.whatwg.org/C/#htmlfontelement
-[HTMLConstructor]
-interface HTMLFontElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLFontElement : HTMLElement {
[CEReactions, Reflect] attribute [TreatNullAs=EmptyString] DOMString color;
[CEReactions, Reflect] attribute DOMString face;
[CEReactions, Reflect] attribute DOMString size;
diff --git a/chromium/third_party/blink/renderer/core/html/html_frame_element.idl b/chromium/third_party/blink/renderer/core/html/html_frame_element.idl
index 0248a354bc4..5a52b7844bd 100644
--- a/chromium/third_party/blink/renderer/core/html/html_frame_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_frame_element.idl
@@ -20,8 +20,10 @@
// https://html.spec.whatwg.org/C/#htmlframeelement
-[HTMLConstructor]
-interface HTMLFrameElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLFrameElement : HTMLElement {
[CEReactions, Reflect] attribute DOMString name;
[CEReactions, Reflect] attribute DOMString scrolling;
[CEReactions, Reflect, URL, RaisesException=Setter] attribute URLString src;
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 61c95203f5e..d6cafcab6c0 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
@@ -16,10 +16,12 @@ class HTMLFrameElementTest : public testing::Test {};
// Frame elements do not have any container-policy related attributes, but the
// fullscreen feature should be unconditionally disabled.
TEST_F(HTMLFrameElementTest, DefaultContainerPolicy) {
- auto* document = MakeGarbageCollected<Document>();
const KURL document_url("http://example.com");
- document->SetURL(document_url);
- document->UpdateSecurityOrigin(SecurityOrigin::Create(document_url));
+ DocumentInit init =
+ DocumentInit::Create()
+ .WithInitiatorOrigin(SecurityOrigin::Create(document_url))
+ .WithURL(document_url);
+ auto* document = MakeGarbageCollected<Document>(init);
auto* frame_element = MakeGarbageCollected<HTMLFrameElement>(*document);
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 1b2e72efde8..7400dca2334 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
@@ -20,7 +20,7 @@
#include "third_party/blink/renderer/core/html/html_frame_owner_element.h"
-#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-shared.h"
+#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h"
#include "third_party/blink/renderer/core/accessibility/ax_object_cache.h"
#include "third_party/blink/renderer/core/css/style_change_reason.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
@@ -132,6 +132,11 @@ bool ShouldLazilyLoadFrame(const Document& document,
return false;
}
+ // Skip automatic lazyload when reloading a page.
+ if (!RuntimeEnabledFeatures::AutoLazyLoadOnReloadsEnabled() &&
+ document.Loader() && IsReloadLoadType(document.Loader()->LoadType())) {
+ return false;
+ }
return true;
}
@@ -362,8 +367,7 @@ void HTMLFrameOwnerElement::SetEmbeddedContentView(
GetDocument().GetRootScrollerController().DidUpdateIFrameFrameView(*this);
- LayoutEmbeddedContent* layout_embedded_content =
- ToLayoutEmbeddedContent(GetLayoutObject());
+ LayoutEmbeddedContent* layout_embedded_content = GetLayoutEmbeddedContent();
if (!layout_embedded_content)
return;
@@ -391,8 +395,7 @@ EmbeddedContentView* HTMLFrameOwnerElement::ReleaseEmbeddedContentView() {
return nullptr;
if (embedded_content_view_->IsAttached())
embedded_content_view_->DetachFromLayout();
- LayoutEmbeddedContent* layout_embedded_content =
- ToLayoutEmbeddedContent(GetLayoutObject());
+ LayoutEmbeddedContent* layout_embedded_content = GetLayoutEmbeddedContent();
if (layout_embedded_content) {
if (AXObjectCache* cache = GetDocument().ExistingAXObjectCache())
cache->ChildrenChanged(layout_embedded_content);
@@ -421,7 +424,9 @@ bool HTMLFrameOwnerElement::LoadOrRedirectSubframe(
KURL url_to_request = url.IsNull() ? BlankURL() : url;
ResourceRequest request(url_to_request);
- request.SetReferrerPolicy(ReferrerPolicyAttribute());
+ request.SetReferrerPolicy(ReferrerPolicyAttribute(),
+ ResourceRequest::SetReferrerPolicyLocation::
+ kFrameOwnerLoadOrRedirectSubframe);
if (ContentFrame()) {
// TODO(sclittle): Support lazily loading frame navigations.
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 0561d7ec389..dd2967f705a 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
@@ -31,11 +31,11 @@
#include "third_party/blink/renderer/core/events/mouse_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/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/html_collection.h"
#include "third_party/blink/renderer/core/html/html_frame_element.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/layout/layout_frame_set.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/html_frame_set_element.idl b/chromium/third_party/blink/renderer/core/html/html_frame_set_element.idl
index 6a6733ed149..2b8e2b112b6 100644
--- a/chromium/third_party/blink/renderer/core/html/html_frame_set_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_frame_set_element.idl
@@ -22,6 +22,7 @@
// FIXME: HTMLFrameSetElement should not have [OverrideBuiltins].
[
+ Exposed=Window,
HTMLConstructor,
OverrideBuiltins
] interface HTMLFrameSetElement : HTMLElement {
diff --git a/chromium/third_party/blink/renderer/core/html/html_head_element.idl b/chromium/third_party/blink/renderer/core/html/html_head_element.idl
index 34b7b3c5f16..f19f5010e98 100644
--- a/chromium/third_party/blink/renderer/core/html/html_head_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_head_element.idl
@@ -18,6 +18,8 @@
*/
// https://html.spec.whatwg.org/C/#the-head-element
-[HTMLConstructor]
-interface HTMLHeadElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLHeadElement : HTMLElement {
};
diff --git a/chromium/third_party/blink/renderer/core/html/html_heading_element.idl b/chromium/third_party/blink/renderer/core/html/html_heading_element.idl
index 8b7fe5d2971..b4e427daf8b 100644
--- a/chromium/third_party/blink/renderer/core/html/html_heading_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_heading_element.idl
@@ -18,8 +18,10 @@
*/
// https://html.spec.whatwg.org/C/#the-h1,-h2,-h3,-h4,-h5,-and-h6-elements
-[HTMLConstructor]
-interface HTMLHeadingElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLHeadingElement : HTMLElement {
// obsolete members
// https://html.spec.whatwg.org/C/#HTMLHeadingElement-partial
[CEReactions, Reflect] attribute DOMString align;
diff --git a/chromium/third_party/blink/renderer/core/html/html_hr_element.idl b/chromium/third_party/blink/renderer/core/html/html_hr_element.idl
index dda79b168d5..515383183c5 100644
--- a/chromium/third_party/blink/renderer/core/html/html_hr_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_hr_element.idl
@@ -18,8 +18,10 @@
*/
// https://html.spec.whatwg.org/C/#the-hr-element
-[HTMLConstructor]
-interface HTMLHRElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLHRElement : HTMLElement {
// obsolete members
// https://html.spec.whatwg.org/C/#HTMLHRElement-partial
[CEReactions, Reflect] attribute DOMString align;
diff --git a/chromium/third_party/blink/renderer/core/html/html_html_element.idl b/chromium/third_party/blink/renderer/core/html/html_html_element.idl
index 5683c27746e..cd5f7112def 100644
--- a/chromium/third_party/blink/renderer/core/html/html_html_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_html_element.idl
@@ -18,8 +18,10 @@
*/
// https://html.spec.whatwg.org/C/#the-html-element
-[HTMLConstructor]
-interface HTMLHtmlElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLHtmlElement : HTMLElement {
// obsolete members
// https://html.spec.whatwg.org/C/#HTMLHtmlElement-partial
[CEReactions, Reflect] attribute DOMString version;
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 3c64ce86223..81677263fcc 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
@@ -33,12 +33,12 @@
#include "third_party/blink/renderer/core/feature_policy/iframe_policy.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
#include "third_party/blink/renderer/core/frame/sandbox_flags.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/html_document.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/core/layout/layout_iframe.h"
#include "third_party/blink/renderer/core/loader/document_loader.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
namespace blink {
@@ -300,7 +300,7 @@ ParsedFeaturePolicy HTMLIFrameElement::ConstructContainerPolicy(
messages->push_back(String::Format(
"Allow and Sandbox attributes both mention '%s'. Allow will take "
"precedence.",
- GetNameForFeature(pair.second).Utf8().data()));
+ GetNameForFeature(pair.second).Utf8().c_str()));
}
}
}
diff --git a/chromium/third_party/blink/renderer/core/html/html_iframe_element.idl b/chromium/third_party/blink/renderer/core/html/html_iframe_element.idl
index 9532b1d53f5..026dd50e070 100644
--- a/chromium/third_party/blink/renderer/core/html/html_iframe_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_iframe_element.idl
@@ -18,13 +18,15 @@
* Boston, MA 02110-1301, USA.
*/
-// https://html.spec.whatwg.org/C/#the-iframe-element
+// https://html.spec.whatwg.org/multipage/iframe-embed-object.html#htmliframeelement
// The `HTMLString` and `URLString` references below are from Trusted Types:
// https://github.com/WICG/trusted-types/, which is still WIP.
// https://crbug.com/739170.
-[HTMLConstructor]
-interface HTMLIFrameElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLIFrameElement : HTMLElement {
[CEReactions, Reflect, URL, RaisesException=Setter] attribute URLString src;
[CEReactions, Reflect, RaisesException=Setter] attribute HTMLString srcdoc;
[CEReactions, Reflect] attribute DOMString name;
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 bfe5e63e8c6..16932628abc 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
@@ -22,11 +22,12 @@ class HTMLIFrameElementTest : public testing::Test {
}
void SetUp() final {
- document_ = MakeGarbageCollected<Document>();
const KURL document_url("http://example.com");
- document_->SetURL(document_url);
- document_->UpdateSecurityOrigin(SecurityOrigin::Create(document_url));
-
+ DocumentInit init =
+ DocumentInit::Create()
+ .WithOriginToCommit(SecurityOrigin::Create(document_url))
+ .WithURL(document_url);
+ document_ = MakeGarbageCollected<Document>(init);
frame_element_ = MakeGarbageCollected<HTMLIFrameElement>(*document_);
}
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 c5f40e724f4..7cb5e8474bc 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
@@ -435,12 +435,14 @@ Node::InsertionNotificationRequest HTMLImageElement::InsertedInto(
ResetFormOwner();
if (listener_)
GetDocument().GetMediaQueryMatcher().AddViewportListener(listener_);
- Node* parent = parentNode();
- if (parent && IsHTMLPictureElement(*parent))
- ToHTMLPictureElement(parent)->AddListenerToSourceChildren();
+ bool was_added_to_picture_parent = false;
+ if (auto* picture_parent = ToHTMLPictureElementOrNull(parentNode())) {
+ picture_parent->AddListenerToSourceChildren();
+ was_added_to_picture_parent = picture_parent == insertion_point;
+ }
bool image_was_modified = false;
- if (GetDocument().IsActive()) {
+ if (GetDocument().IsActive() && was_added_to_picture_parent) {
ImageCandidate candidate = FindBestFitImageFromPictureParent();
if (!candidate.IsEmpty()) {
SetBestFitURLAndDPRFromImageCandidate(candidate);
@@ -448,8 +450,8 @@ Node::InsertionNotificationRequest HTMLImageElement::InsertedInto(
}
}
- if (image_was_modified ||
- GetImageLoader().ShouldUpdateOnInsertedInto(insertion_point)) {
+ if (image_was_modified || GetImageLoader().ShouldUpdateOnInsertedInto(
+ insertion_point, referrer_policy_)) {
GetImageLoader().UpdateFromElement(ImageLoader::kUpdateNormal,
referrer_policy_);
}
@@ -462,9 +464,8 @@ void HTMLImageElement::RemovedFrom(ContainerNode& insertion_point) {
ResetFormOwner();
if (listener_) {
GetDocument().GetMediaQueryMatcher().RemoveViewportListener(listener_);
- Node* parent = parentNode();
- if (parent && IsHTMLPictureElement(*parent))
- ToHTMLPictureElement(parent)->RemoveListenerFromSourceChildren();
+ if (auto* picture_parent = ToHTMLPictureElementOrNull(parentNode()))
+ picture_parent->RemoveListenerFromSourceChildren();
}
HTMLElement::RemovedFrom(insertion_point);
}
@@ -757,32 +758,7 @@ void HTMLImageElement::SelectSourceURL(
GetImageLoader().UpdateFromElement(behavior, referrer_policy_);
}
- ImageResourceContent* image_content = GetImageLoader().GetContent();
- // Images such as data: uri's can return immediately and may already have
- // errored out.
- bool image_has_loaded = image_content && !image_content->IsLoading() &&
- !image_content->ErrorOccurred();
- bool image_still_loading =
- !image_has_loaded && GetImageLoader().HasPendingActivity() &&
- !GetImageLoader().HasPendingError() && !ImageSourceURL().IsEmpty();
- bool image_has_image = image_content && image_content->HasImage();
- bool image_is_document = GetImageLoader().IsLoadingImageDocument() &&
- image_content && !image_content->ErrorOccurred();
-
- // Icky special case for deferred images:
- // A deferred image is not loading, does have pending activity, does not
- // have an error, but it does have an ImageResourceContent associated
- // with it, so imageHasLoaded will be true even though the image hasn't
- // actually loaded. Fixing the definition of imageHasLoaded isn't
- // sufficient, because a deferred image does have pending activity, does not
- // have a pending error, and does have a source URL, so if imageHasLoaded
- // was correct, imageStillLoading would become wrong.
- //
- // Instead of dealing with that, there's a separate check that the
- // ImageResourceContent has non-null image data associated with it, which
- // isn't folded into imageHasLoaded above.
- if ((image_has_loaded && image_has_image) || image_still_loading ||
- image_is_document)
+ if (GetImageLoader().ImageIsPotentiallyAvailable())
EnsurePrimaryContent();
else
EnsureCollapsedOrFallbackContent();
diff --git a/chromium/third_party/blink/renderer/core/html/html_image_element.idl b/chromium/third_party/blink/renderer/core/html/html_image_element.idl
index 4d332ec87df..a572a173d07 100644
--- a/chromium/third_party/blink/renderer/core/html/html_image_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_image_element.idl
@@ -21,6 +21,7 @@
// https://html.spec.whatwg.org/C/#the-img-element
[
+ Exposed=Window,
ActiveScriptWrappable,
ConstructorCallWith=Document,
HTMLConstructor,
diff --git a/chromium/third_party/blink/renderer/core/html/html_image_fallback_helper.h b/chromium/third_party/blink/renderer/core/html/html_image_fallback_helper.h
index 1ffbf91173f..8d7df65657f 100644
--- a/chromium/third_party/blink/renderer/core/html/html_image_fallback_helper.h
+++ b/chromium/third_party/blink/renderer/core/html/html_image_fallback_helper.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_HTML_IMAGE_FALLBACK_HELPER_H_
#include "base/memory/scoped_refptr.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/html_li_element.idl b/chromium/third_party/blink/renderer/core/html/html_li_element.idl
index 134b750b71e..c605235432c 100644
--- a/chromium/third_party/blink/renderer/core/html/html_li_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_li_element.idl
@@ -18,8 +18,10 @@
*/
// https://html.spec.whatwg.org/C/#the-li-element
-[HTMLConstructor]
-interface HTMLLIElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLLIElement : HTMLElement {
[CEReactions, Reflect] attribute long value;
// obsolete members
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 52bea7869e4..51e5ba2a301 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
@@ -36,7 +36,6 @@
#include "third_party/blink/renderer/core/dom/events/event.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/use_counter.h"
#include "third_party/blink/renderer/core/html/cross_origin_attribute.h"
#include "third_party/blink/renderer/core/html/imports/link_import.h"
#include "third_party/blink/renderer/core/html/link_manifest.h"
@@ -45,6 +44,7 @@
#include "third_party/blink/renderer/core/loader/link_loader.h"
#include "third_party/blink/renderer/core/origin_trials/origin_trial_context.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/weborigin/security_policy.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
@@ -192,9 +192,6 @@ LinkResource* HTMLLinkElement::LinkResourceToProcess() {
(Href().Protocol() == "chrome" ||
Href().Protocol() == "chrome-extension");
if (!imports_enabled) {
- // Ensure the origin trial context is created, as the enabled check will
- // return false if the context doesn't exist yet.
- OriginTrialContext::FromOrCreate(&GetDocument());
imports_enabled =
RuntimeEnabledFeatures::HTMLImportsEnabled(&GetDocument());
}
@@ -302,10 +299,16 @@ bool HTMLLinkElement::StyleSheetIsLoading() const {
}
void HTMLLinkElement::LinkLoaded() {
+ if (rel_attribute_.IsLinkPrefetch()) {
+ UseCounter::Count(GetDocument(), WebFeature::kLinkPrefetchLoadEvent);
+ }
DispatchEvent(*Event::Create(event_type_names::kLoad));
}
void HTMLLinkElement::LinkLoadingErrored() {
+ if (rel_attribute_.IsLinkPrefetch()) {
+ UseCounter::Count(GetDocument(), WebFeature::kLinkPrefetchErrorEvent);
+ }
DispatchEvent(*Event::Create(event_type_names::kError));
}
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 e812054231f..c284176534c 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
@@ -20,8 +20,10 @@
*/
// https://html.spec.whatwg.org/C/#the-link-element
-[HTMLConstructor]
-interface HTMLLinkElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLLinkElement : HTMLElement {
// FIXME: The disabled attribute has been removed from the spec:
// https://www.w3.org/Bugs/Public/show_bug.cgi?id=14703
[Reflect, Measure] attribute boolean disabled;
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 1a99834b30e..85c56a5dc56 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
@@ -24,12 +24,12 @@
#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/node_lists_node_data.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/html_area_element.h"
#include "third_party/blink/renderer/core/html/html_collection.h"
#include "third_party/blink/renderer/core/html/html_image_element.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/layout/hit_test_result.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
@@ -43,7 +43,7 @@ HTMLMapElement::HTMLMapElement(Document& document)
HTMLMapElement::~HTMLMapElement() = default;
HTMLAreaElement* HTMLMapElement::AreaForPoint(
- const LayoutPoint& location,
+ const PhysicalOffset& location,
const LayoutObject* container_object) {
HTMLAreaElement* default_area = nullptr;
for (HTMLAreaElement& area :
diff --git a/chromium/third_party/blink/renderer/core/html/html_map_element.h b/chromium/third_party/blink/renderer/core/html/html_map_element.h
index 76ab08447a6..56e936d36e1 100644
--- a/chromium/third_party/blink/renderer/core/html/html_map_element.h
+++ b/chromium/third_party/blink/renderer/core/html/html_map_element.h
@@ -29,6 +29,7 @@
namespace blink {
class HTMLImageElement;
+struct PhysicalOffset;
class CORE_EXPORT HTMLMapElement final : public HTMLElement {
DEFINE_WRAPPERTYPEINFO();
@@ -39,7 +40,7 @@ class CORE_EXPORT HTMLMapElement final : public HTMLElement {
const AtomicString& GetName() const { return name_; }
- HTMLAreaElement* AreaForPoint(const LayoutPoint&,
+ HTMLAreaElement* AreaForPoint(const PhysicalOffset&,
const LayoutObject* container_object);
HTMLImageElement* ImageElement();
diff --git a/chromium/third_party/blink/renderer/core/html/html_map_element.idl b/chromium/third_party/blink/renderer/core/html/html_map_element.idl
index 847c2e3cb4b..9c8fe9fd601 100644
--- a/chromium/third_party/blink/renderer/core/html/html_map_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_map_element.idl
@@ -19,8 +19,10 @@
*/
// https://html.spec.whatwg.org/C/#the-map-element
-[HTMLConstructor]
-interface HTMLMapElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLMapElement : HTMLElement {
[CEReactions, Reflect] attribute DOMString name;
readonly attribute HTMLCollection areas;
};
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 838cd6aac5e..8ee12e81ad7 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
@@ -40,7 +40,6 @@
#include "third_party/blink/renderer/core/dom/frame_request_callback_collection.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/html_div_element.h"
#include "third_party/blink/renderer/core/html/html_slot_element.h"
#include "third_party/blink/renderer/core/html/html_style_element.h"
@@ -48,6 +47,7 @@
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/html_marquee_element.idl b/chromium/third_party/blink/renderer/core/html/html_marquee_element.idl
index d88032355b0..54e6d4db43d 100644
--- a/chromium/third_party/blink/renderer/core/html/html_marquee_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_marquee_element.idl
@@ -18,8 +18,10 @@
*/
// https://html.spec.whatwg.org/C/#htmlmarqueeelement
-[HTMLConstructor]
-interface HTMLMarqueeElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLMarqueeElement : HTMLElement {
[Reflect] attribute DOMString behavior;
[Reflect] attribute DOMString bgColor;
[Reflect] attribute DOMString direction;
diff --git a/chromium/third_party/blink/renderer/core/html/html_menu_element.idl b/chromium/third_party/blink/renderer/core/html/html_menu_element.idl
index 74c8a6076eb..40c701c30e7 100644
--- a/chromium/third_party/blink/renderer/core/html/html_menu_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_menu_element.idl
@@ -18,8 +18,10 @@
*/
// https://html.spec.whatwg.org/C/#the-menu-element
-[HTMLConstructor]
-interface HTMLMenuElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLMenuElement : HTMLElement {
// obsolete members
// https://html.spec.whatwg.org/C/#HTMLMenuElement-partial
[CEReactions, Reflect] attribute boolean compact;
diff --git a/chromium/third_party/blink/renderer/core/html/html_meta_element.idl b/chromium/third_party/blink/renderer/core/html/html_meta_element.idl
index 437193f9386..09148a8fe84 100644
--- a/chromium/third_party/blink/renderer/core/html/html_meta_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_meta_element.idl
@@ -18,8 +18,10 @@
*/
// https://html.spec.whatwg.org/C/#the-meta-element
-[HTMLConstructor]
-interface HTMLMetaElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLMetaElement : HTMLElement {
[CEReactions, Reflect] attribute DOMString name;
[CEReactions, Reflect=http_equiv] attribute DOMString httpEquiv;
[CEReactions, Reflect] attribute DOMString content;
diff --git a/chromium/third_party/blink/renderer/core/html/html_meta_element_test.cc b/chromium/third_party/blink/renderer/core/html/html_meta_element_test.cc
index 97d9bf780f5..c1731470a63 100644
--- a/chromium/third_party/blink/renderer/core/html/html_meta_element_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/html_meta_element_test.cc
@@ -18,18 +18,23 @@
#include "third_party/blink/renderer/core/testing/page_test_base.h"
#include "third_party/blink/renderer/platform/heap/heap.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 HTMLMetaElementTest : public PageTestBase {
+class HTMLMetaElementTest : public PageTestBase,
+ private ScopedDisplayCutoutAPIForTest,
+ private ScopedMetaColorSchemeForTest,
+ private ScopedMediaQueryPrefersColorSchemeForTest,
+ private ScopedCSSColorSchemeForTest {
public:
+ HTMLMetaElementTest()
+ : ScopedDisplayCutoutAPIForTest(true),
+ ScopedMetaColorSchemeForTest(true),
+ ScopedMediaQueryPrefersColorSchemeForTest(true),
+ ScopedCSSColorSchemeForTest(true) {}
void SetUp() override {
PageTestBase::SetUp();
-
- RuntimeEnabledFeatures::SetDisplayCutoutAPIEnabled(true);
- RuntimeEnabledFeatures::SetMetaColorSchemeEnabled(true);
- RuntimeEnabledFeatures::SetMediaQueryPrefersColorSchemeEnabled(true);
- RuntimeEnabledFeatures::SetCSSColorSchemeEnabled(true);
GetDocument().GetSettings()->SetViewportMetaEnabled(true);
}
@@ -164,7 +169,7 @@ TEST_F(HTMLMetaElementTest, ColorSchemeProcessing_RemoveContentAttribute) {
GetDocument().getElementById("meta")->removeAttribute(
html_names::kContentAttr);
- ExpectComputedColorScheme("auto");
+ ExpectComputedColorScheme("normal");
}
TEST_F(HTMLMetaElementTest, ColorSchemeProcessing_RemoveNameAttribute) {
@@ -176,17 +181,17 @@ TEST_F(HTMLMetaElementTest, ColorSchemeProcessing_RemoveNameAttribute) {
GetDocument().getElementById("meta")->removeAttribute(html_names::kNameAttr);
- ExpectComputedColorScheme("auto");
+ ExpectComputedColorScheme("normal");
}
TEST_F(HTMLMetaElementTest, ColorSchemeParsing) {
GetDocument().head()->AppendChild(CreateColorSchemeMeta(""));
SetColorScheme("");
- ExpectComputedColorScheme("auto");
+ ExpectComputedColorScheme("normal");
- SetColorScheme("auto");
- ExpectComputedColorScheme("auto");
+ SetColorScheme("normal");
+ ExpectComputedColorScheme("normal");
SetColorScheme("light");
ExpectComputedColorScheme("light");
@@ -201,19 +206,19 @@ TEST_F(HTMLMetaElementTest, ColorSchemeParsing) {
ExpectComputedColorScheme("BLUE light");
SetColorScheme("light,dark");
- ExpectComputedColorScheme("auto");
+ ExpectComputedColorScheme("normal");
SetColorScheme("light,");
- ExpectComputedColorScheme("auto");
+ ExpectComputedColorScheme("normal");
SetColorScheme(",light");
- ExpectComputedColorScheme("auto");
+ ExpectComputedColorScheme("normal");
SetColorScheme(", light");
- ExpectComputedColorScheme("auto");
+ ExpectComputedColorScheme("normal");
SetColorScheme("light, dark");
- ExpectComputedColorScheme("auto");
+ ExpectComputedColorScheme("normal");
}
TEST_F(HTMLMetaElementTest, ColorSchemeForcedDarkeningAndMQ) {
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 e3b2ebb364a..60d727ef253 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
@@ -22,7 +22,6 @@
#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/use_counter.h"
#include "third_party/blink/renderer/core/html/html_div_element.h"
#include "third_party/blink/renderer/core/html/html_slot_element.h"
#include "third_party/blink/renderer/core/html/parser/html_parser_idioms.h"
@@ -30,6 +29,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/html_meter_element.idl b/chromium/third_party/blink/renderer/core/html/html_meter_element.idl
index ad4c7d15e40..14e99617f3a 100644
--- a/chromium/third_party/blink/renderer/core/html/html_meter_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_meter_element.idl
@@ -18,8 +18,10 @@
*/
// https://html.spec.whatwg.org/C/#the-meter-element
-[HTMLConstructor]
-interface HTMLMeterElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLMeterElement : HTMLElement {
[CEReactions] attribute double value;
[CEReactions] attribute double min;
[CEReactions] attribute double max;
diff --git a/chromium/third_party/blink/renderer/core/html/html_mod_element.idl b/chromium/third_party/blink/renderer/core/html/html_mod_element.idl
index 0ed79d98c2c..472717bd778 100644
--- a/chromium/third_party/blink/renderer/core/html/html_mod_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_mod_element.idl
@@ -19,8 +19,10 @@
// https://html.spec.whatwg.org/C/#the-ins-element
// https://html.spec.whatwg.org/C/#the-del-element
-[HTMLConstructor]
-interface HTMLModElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLModElement : HTMLElement {
[CEReactions, Reflect, URL] attribute DOMString cite;
[CEReactions, Reflect] attribute DOMString dateTime;
};
diff --git a/chromium/third_party/blink/renderer/core/html/html_object_element.idl b/chromium/third_party/blink/renderer/core/html/html_object_element.idl
index bca66e96be7..1279fd485b0 100644
--- a/chromium/third_party/blink/renderer/core/html/html_object_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_object_element.idl
@@ -22,6 +22,7 @@
// TODO(yukishiino): HTMLObjectElement should not have [OverrideBuiltins].
[
+ Exposed=Window,
OverrideBuiltins,
ActiveScriptWrappable,
HTMLConstructor
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 bbddd1b173c..3299964b046 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
@@ -24,11 +24,11 @@
#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"
#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/layout/layout_list_item.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/html_olist_element.idl b/chromium/third_party/blink/renderer/core/html/html_olist_element.idl
index b47d8670701..bc6ab7133db 100644
--- a/chromium/third_party/blink/renderer/core/html/html_olist_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_olist_element.idl
@@ -18,8 +18,10 @@
*/
// https://html.spec.whatwg.org/C/#the-ol-element
-[HTMLConstructor]
-interface HTMLOListElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLOListElement : HTMLElement {
[CEReactions, Reflect] attribute boolean reversed;
[CEReactions] attribute long start;
[CEReactions, Reflect] attribute DOMString type;
diff --git a/chromium/third_party/blink/renderer/core/html/html_paragraph_element.idl b/chromium/third_party/blink/renderer/core/html/html_paragraph_element.idl
index 773d976b196..804adcc4d95 100644
--- a/chromium/third_party/blink/renderer/core/html/html_paragraph_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_paragraph_element.idl
@@ -18,8 +18,10 @@
*/
// https://html.spec.whatwg.org/C/#the-p-element
-[HTMLConstructor]
-interface HTMLParagraphElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLParagraphElement : HTMLElement {
// obsolete members
// https://html.spec.whatwg.org/C/#HTMLParagraphElement-partial
[CEReactions, Reflect] attribute DOMString align;
diff --git a/chromium/third_party/blink/renderer/core/html/html_param_element.idl b/chromium/third_party/blink/renderer/core/html/html_param_element.idl
index 1359fe70e84..5ed4a3a6a02 100644
--- a/chromium/third_party/blink/renderer/core/html/html_param_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_param_element.idl
@@ -18,8 +18,10 @@
*/
// https://html.spec.whatwg.org/C/#the-param-element
-[HTMLConstructor]
-interface HTMLParamElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLParamElement : HTMLElement {
[CEReactions, Reflect] attribute DOMString name;
[CEReactions, Reflect] attribute DOMString value;
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 5e54d9b9ad7..adc93e3d852 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
@@ -5,11 +5,11 @@
#include "third_party/blink/renderer/core/html/html_picture_element.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/html_image_element.h"
#include "third_party/blink/renderer/core/html/html_source_element.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/loader/image_loader.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/html_picture_element.idl b/chromium/third_party/blink/renderer/core/html/html_picture_element.idl
index 4dced65725a..c09e2fc3bc1 100644
--- a/chromium/third_party/blink/renderer/core/html/html_picture_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_picture_element.idl
@@ -3,6 +3,8 @@
// found in the LICENSE file.
// https://html.spec.whatwg.org/C/#the-picture-element
-[HTMLConstructor]
-interface HTMLPictureElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLPictureElement : HTMLElement {
};
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 1a6a9ec3b56..ee414199faa 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
@@ -51,7 +51,7 @@
#include "third_party/blink/renderer/core/page/plugin_data.h"
#include "third_party/blink/renderer/core/page/scrolling/scrolling_coordinator.h"
#include "third_party/blink/renderer/platform/bindings/v8_per_isolate_data.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_request.h"
#include "third_party/blink/renderer/platform/network/mime/mime_type_from_url.h"
#include "third_party/blink/renderer/platform/network/mime/mime_type_registry.h"
@@ -64,14 +64,6 @@ using namespace html_names;
namespace {
-// Used for histograms, do not change the order.
-enum PluginRequestObjectResult {
- kPluginRequestObjectResultFailure = 0,
- kPluginRequestObjectResultSuccess = 1,
- // Keep at the end.
- kPluginRequestObjectResultMax
-};
-
String GetMIMETypeFromURL(const KURL& url) {
String filename = url.LastPathComponent();
int extension_pos = filename.ReverseFind('.');
@@ -164,57 +156,6 @@ void HTMLPlugInElement::SetFocused(bool focused, WebFocusType focus_type) {
HTMLFrameOwnerElement::SetFocused(focused, focus_type);
}
-bool HTMLPlugInElement::RequestObjectInternal(
- const PluginParameters& plugin_params) {
- if (url_.IsEmpty() && service_type_.IsEmpty())
- return false;
-
- if (ProtocolIsJavaScript(url_))
- return false;
-
- KURL completed_url =
- url_.IsEmpty() ? KURL() : GetDocument().CompleteURL(url_);
- if (!AllowedToLoadObject(completed_url, service_type_))
- return false;
-
- ObjectContentType object_type = GetObjectContentType();
- bool handled_externally =
- object_type == ObjectContentType::kExternalPlugin &&
- AllowedToLoadPlugin(completed_url, service_type_) &&
- GetDocument().GetFrame()->Client()->IsPluginHandledExternally(
- *this, completed_url,
- service_type_.IsEmpty() ? GetMIMETypeFromURL(completed_url)
- : service_type_);
- if (handled_externally)
- ResetInstance();
- if (object_type == ObjectContentType::kFrame ||
- object_type == ObjectContentType::kImage || handled_externally) {
- if (ContentFrame() && ContentFrame()->IsRemoteFrame()) {
- // During lazy reattaching, the plugin element loses EmbeddedContentView.
- // Since the ContentFrame() is not torn down the options here are to
- // either re-create a new RemoteFrameView or reuse the old one. The former
- // approach requires CommitNavigation for OOPF to be sent back here in
- // the parent process. It is easier to just reuse the current FrameView
- // instead until plugin element issue are properly resolved (for context
- // see https://crbug.com/781880).
- DCHECK(!OwnedEmbeddedContentView());
- SetEmbeddedContentView(ContentFrame()->View());
- DCHECK(OwnedEmbeddedContentView());
- }
- // If the plugin element already contains a subframe,
- // loadOrRedirectSubframe will re-use it. Otherwise, it will create a
- // new frame and set it as the LayoutEmbeddedContent's EmbeddedContentView,
- // causing what was previously in the EmbeddedContentView to be torn down.
- return LoadOrRedirectSubframe(completed_url, GetNameAttribute(), true);
- }
-
- // If an object's content can't be handled and it has no fallback, let
- // it be handled as a plugin to show the broken plugin icon.
- bool use_fallback =
- object_type == ObjectContentType::kNone && HasFallbackContent();
- return LoadPlugin(completed_url, service_type_, plugin_params, use_fallback);
-}
-
bool HTMLPlugInElement::CanProcessDrag() const {
return PluginEmbeddedContentView() &&
PluginEmbeddedContentView()->CanProcessDrag();
@@ -294,10 +235,8 @@ void HTMLPlugInElement::AttachLayoutTree(AttachContext& context) {
}
void HTMLPlugInElement::IntrinsicSizingInfoChanged() {
- if (auto* layout_object = GetLayoutObject()) {
- layout_object->SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
- layout_invalidation_reason::kUnknown);
- }
+ if (auto* embedded_object = GetLayoutEmbeddedObject())
+ embedded_object->IntrinsicSizeChanged();
}
void HTMLPlugInElement::UpdatePlugin() {
@@ -335,7 +274,7 @@ ParsedFeaturePolicy HTMLPlugInElement::ConstructContainerPolicy(
return container_policy;
}
-void HTMLPlugInElement::DetachLayoutTree(const AttachContext& context) {
+void HTMLPlugInElement::DetachLayoutTree(bool performing_reattach) {
// Update the EmbeddedContentView the next time we attach (detaching destroys
// the plugin).
// FIXME: None of this "needsPluginUpdate" related code looks right.
@@ -347,7 +286,7 @@ void HTMLPlugInElement::DetachLayoutTree(const AttachContext& context) {
GetDocument().DecrementLoadEventDelayCount();
}
- bool keep_plugin = context.performing_reattach && !dispose_view_;
+ bool keep_plugin = performing_reattach && !dispose_view_;
// Only try to persist a plugin we actually own.
WebPluginContainerImpl* plugin = OwnedPlugin();
@@ -370,12 +309,12 @@ void HTMLPlugInElement::DetachLayoutTree(const AttachContext& context) {
// state. But only if we're reattaching. Otherwise we need to throw it away,
// since there's no telling what's going to happen next, and it wouldn't be
// safe to keep it.
- if (!context.performing_reattach)
+ if (!performing_reattach)
SetDisposeView();
ResetInstance();
- HTMLFrameOwnerElement::DetachLayoutTree(context);
+ HTMLFrameOwnerElement::DetachLayoutTree(performing_reattach);
}
LayoutObject* HTMLPlugInElement::CreateLayoutObject(const ComputedStyle& style,
@@ -602,11 +541,9 @@ bool HTMLPlugInElement::IsImageType() const {
}
LayoutEmbeddedObject* HTMLPlugInElement::GetLayoutEmbeddedObject() const {
- // HTMLObjectElement and HTMLEmbedElement may return arbitrary layoutObjects
+ // HTMLObjectElement and HTMLEmbedElement may return arbitrary LayoutObjects
// when using fallback content.
- if (!GetLayoutObject() || !GetLayoutObject()->IsEmbeddedObject())
- return nullptr;
- return ToLayoutEmbeddedObject(GetLayoutObject());
+ return ToLayoutEmbeddedObjectOrNull(GetLayoutObject());
}
// We don't use url_, as it may not be the final URL that the object loads,
@@ -619,15 +556,53 @@ bool HTMLPlugInElement::AllowedToLoadFrameURL(const String& url) {
}
bool HTMLPlugInElement::RequestObject(const PluginParameters& plugin_params) {
- bool result = RequestObjectInternal(plugin_params);
+ if (url_.IsEmpty() && service_type_.IsEmpty())
+ return false;
+
+ if (ProtocolIsJavaScript(url_))
+ return false;
+
+ KURL completed_url =
+ url_.IsEmpty() ? KURL() : GetDocument().CompleteURL(url_);
+ if (!AllowedToLoadObject(completed_url, service_type_))
+ return false;
- DEFINE_STATIC_LOCAL(
- EnumerationHistogram, result_histogram,
- ("Plugin.RequestObjectResult", kPluginRequestObjectResultMax));
- result_histogram.Count(result ? kPluginRequestObjectResultSuccess
- : kPluginRequestObjectResultFailure);
+ ObjectContentType object_type = GetObjectContentType();
+ bool handled_externally =
+ object_type == ObjectContentType::kExternalPlugin &&
+ AllowedToLoadPlugin(completed_url, service_type_) &&
+ GetDocument().GetFrame()->Client()->IsPluginHandledExternally(
+ *this, completed_url,
+ service_type_.IsEmpty() ? GetMIMETypeFromURL(completed_url)
+ : service_type_);
+ if (handled_externally)
+ ResetInstance();
+ if (object_type == ObjectContentType::kFrame ||
+ object_type == ObjectContentType::kImage || handled_externally) {
+ if (ContentFrame() && ContentFrame()->IsRemoteFrame()) {
+ // During lazy reattaching, the plugin element loses EmbeddedContentView.
+ // Since the ContentFrame() is not torn down the options here are to
+ // either re-create a new RemoteFrameView or reuse the old one. The former
+ // approach requires CommitNavigation for OOPF to be sent back here in
+ // the parent process. It is easier to just reuse the current FrameView
+ // instead until plugin element issue are properly resolved (for context
+ // see https://crbug.com/781880).
+ DCHECK(!OwnedEmbeddedContentView());
+ SetEmbeddedContentView(ContentFrame()->View());
+ DCHECK(OwnedEmbeddedContentView());
+ }
+ // If the plugin element already contains a subframe,
+ // loadOrRedirectSubframe will re-use it. Otherwise, it will create a
+ // new frame and set it as the LayoutEmbeddedContent's EmbeddedContentView,
+ // causing what was previously in the EmbeddedContentView to be torn down.
+ return LoadOrRedirectSubframe(completed_url, GetNameAttribute(), true);
+ }
- return result;
+ // If an object's content can't be handled and it has no fallback, let
+ // it be handled as a plugin to show the broken plugin icon.
+ bool use_fallback =
+ object_type == ObjectContentType::kNone && HasFallbackContent();
+ return LoadPlugin(completed_url, service_type_, plugin_params, use_fallback);
}
bool HTMLPlugInElement::LoadPlugin(const KURL& 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 043e91ad661..053689c9a5b 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
@@ -103,6 +103,9 @@ class CORE_EXPORT HTMLPlugInElement
ParsedFeaturePolicy ConstructContainerPolicy(
Vector<String>* /* messages */) const override;
+ bool IsImageType() const;
+ HTMLImageLoader* ImageLoader() const { return image_loader_.Get(); }
+
protected:
HTMLPlugInElement(const QualifiedName& tag_name,
Document&,
@@ -127,7 +130,6 @@ class CORE_EXPORT HTMLPlugInElement
// if necessary.
virtual LayoutEmbeddedContent* LayoutEmbeddedContentForJSBindings() const;
- bool IsImageType() const;
LayoutEmbeddedObject* GetLayoutEmbeddedObject() const;
bool AllowedToLoadFrameURL(const String& url);
bool RequestObject(const PluginParameters& plugin_params);
@@ -165,7 +167,7 @@ class CORE_EXPORT HTMLPlugInElement
bool CanStartSelection() const override;
bool WillRespondToMouseClickEvents() final;
void DefaultEventHandler(Event&) final;
- void DetachLayoutTree(const AttachContext& = AttachContext()) final;
+ void DetachLayoutTree(bool performing_reattach) final;
void FinishParsingChildren() final;
// Element overrides:
@@ -210,8 +212,6 @@ class CORE_EXPORT HTMLPlugInElement
void SetPersistedPlugin(WebPluginContainerImpl*);
- bool RequestObjectInternal(const PluginParameters& plugin_params);
-
void UpdateServiceTypeIfEmpty();
v8::Global<v8::Object> plugin_wrapper_;
diff --git a/chromium/third_party/blink/renderer/core/html/html_pre_element.idl b/chromium/third_party/blink/renderer/core/html/html_pre_element.idl
index 3d527fff83f..80ba78786c3 100644
--- a/chromium/third_party/blink/renderer/core/html/html_pre_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_pre_element.idl
@@ -19,8 +19,10 @@
*/
// https://html.spec.whatwg.org/C/#the-pre-element
-[HTMLConstructor]
-interface HTMLPreElement : HTMLElement {
+[
+ HTMLConstructor,
+ Exposed=Window
+] interface HTMLPreElement : HTMLElement {
// obsolete members
// https://html.spec.whatwg.org/C/#HTMLPreElement-partial
[CEReactions, Reflect] attribute long width;
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 de7993816ae..d8ef15e4f6a 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
@@ -21,13 +21,13 @@
#include "third_party/blink/renderer/core/html/html_progress_element.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/parser/html_parser_idioms.h"
#include "third_party/blink/renderer/core/html/shadow/progress_shadow_element.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/layout/layout_progress.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/html_progress_element.idl b/chromium/third_party/blink/renderer/core/html/html_progress_element.idl
index 6cb8ed6ad29..4c2c66df002 100644
--- a/chromium/third_party/blink/renderer/core/html/html_progress_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_progress_element.idl
@@ -18,8 +18,10 @@
*/
// https://html.spec.whatwg.org/C/#the-progress-element
-[HTMLConstructor]
-interface HTMLProgressElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLProgressElement : HTMLElement {
[CEReactions] attribute double value;
[CEReactions] attribute double max;
readonly attribute double position;
diff --git a/chromium/third_party/blink/renderer/core/html/html_quote_element.idl b/chromium/third_party/blink/renderer/core/html/html_quote_element.idl
index 26ebbc806f2..7b6e62dd6af 100644
--- a/chromium/third_party/blink/renderer/core/html/html_quote_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_quote_element.idl
@@ -19,7 +19,9 @@
// https://html.spec.whatwg.org/C/#the-blockquote-element
// https://html.spec.whatwg.org/C/#the-q-element
-[HTMLConstructor]
-interface HTMLQuoteElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLQuoteElement : HTMLElement {
[CEReactions, Reflect, URL] attribute DOMString cite;
};
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 b667f998234..0807c984bc8 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
@@ -32,13 +32,13 @@
#include "third_party/blink/renderer/core/dom/events/event.h"
#include "third_party/blink/renderer/core/dom/text.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#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"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
namespace blink {
@@ -158,10 +158,6 @@ bool HTMLScriptElement::async() const {
return FastHasAttribute(kAsyncAttr) || loader_->IsNonBlocking();
}
-KURL HTMLScriptElement::Src() const {
- return GetDocument().CompleteURL(SourceAttributeValue());
-}
-
String HTMLScriptElement::SourceAttributeValue() const {
return getAttribute(kSrcAttr).GetString();
}
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 2a8c31bb711..ca7f9f5f44c 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
@@ -52,8 +52,6 @@ class CORE_EXPORT HTMLScriptElement final : public HTMLElement,
void setInnerText(const StringOrTrustedScript&, ExceptionState&) override;
void setTextContent(const StringOrTrustedScript&, ExceptionState&) override;
- KURL Src() const;
-
void setAsync(bool);
bool async() const;
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 475f551689b..2d6feee429a 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
@@ -18,8 +18,10 @@
*/
// https://html.spec.whatwg.org/C/#the-script-element
-[HTMLConstructor]
-interface HTMLScriptElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLScriptElement : HTMLElement {
[CEReactions, Reflect, URL, RaisesException=Setter] attribute ScriptURLString src;
[CEReactions, Reflect] attribute DOMString type;
[CEReactions, Reflect] attribute boolean noModule;
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 3fd64f61a9b..cdb30fb3b49 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
@@ -32,9 +32,9 @@
#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/use_counter.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
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 2a5fbd25634..0aacd6c65c7 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
@@ -30,8 +30,6 @@
#include "third_party/blink/renderer/core/html/html_slot_element.h"
-#include <array>
-
#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"
@@ -43,12 +41,12 @@
#include "third_party/blink/renderer/core/dom/slot_assignment.h"
#include "third_party/blink/renderer/core/dom/text.h"
#include "third_party/blink/renderer/core/dom/whitespace_attacher.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/assigned_nodes_options.h"
#include "third_party/blink/renderer/core/html_names.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/platform/bindings/microtask.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
@@ -157,8 +155,8 @@ const HeapVector<Member<Node>> HTMLSlotElement::AssignedNodesForBinding(
const HeapVector<Member<Element>> HTMLSlotElement::AssignedElements() {
HeapVector<Member<Element>> elements;
for (auto& node : AssignedNodes()) {
- if (Element* element = ToElementOrNull(node))
- elements.push_back(element);
+ if (auto* element = DynamicTo<Element>(node.Get()))
+ elements.push_back(*element);
}
return elements;
}
@@ -167,8 +165,8 @@ const HeapVector<Member<Element>> HTMLSlotElement::AssignedElementsForBinding(
const AssignedNodesOptions* options) {
HeapVector<Member<Element>> elements;
for (auto& node : AssignedNodesForBinding(options)) {
- if (Element* element = ToElementOrNull(node))
- elements.push_back(element);
+ if (auto* element = DynamicTo<Element>(node.Get()))
+ elements.push_back(*element);
}
return elements;
}
@@ -184,15 +182,11 @@ void HTMLSlotElement::assign(HeapVector<Member<Node>> nodes) {
void HTMLSlotElement::AppendAssignedNode(Node& host_child) {
DCHECK(host_child.IsSlotable());
- if (!RuntimeEnabledFeatures::FastFlatTreeTraversalEnabled())
- assigned_nodes_index_.insert(&host_child, assigned_nodes_.size());
assigned_nodes_.push_back(&host_child);
}
void HTMLSlotElement::ClearAssignedNodes() {
assigned_nodes_.clear();
- if (!RuntimeEnabledFeatures::FastFlatTreeTraversalEnabled())
- assigned_nodes_index_.clear();
}
void HTMLSlotElement::ClearAssignedNodesAndFlatTreeChildren() {
@@ -249,32 +243,6 @@ void HTMLSlotElement::DispatchSlotChangeEvent() {
DispatchScopedEvent(*event);
}
-Node* HTMLSlotElement::AssignedNodeNextTo(const Node& node) const {
- DCHECK(!RuntimeEnabledFeatures::FastFlatTreeTraversalEnabled());
- DCHECK(SupportsAssignment());
- ContainingShadowRoot()->GetSlotAssignment().RecalcAssignment();
-
- auto it = assigned_nodes_index_.find(&node);
- DCHECK(it != assigned_nodes_index_.end());
- unsigned index = it->value;
- if (index + 1 == assigned_nodes_.size())
- return nullptr;
- return assigned_nodes_[index + 1].Get();
-}
-
-Node* HTMLSlotElement::AssignedNodePreviousTo(const Node& node) const {
- DCHECK(!RuntimeEnabledFeatures::FastFlatTreeTraversalEnabled());
- DCHECK(SupportsAssignment());
- ContainingShadowRoot()->GetSlotAssignment().RecalcAssignment();
-
- auto it = assigned_nodes_index_.find(&node);
- DCHECK(it != assigned_nodes_index_.end());
- unsigned index = it->value;
- if (index == 0)
- return nullptr;
- return assigned_nodes_[index - 1].Get();
-}
-
AtomicString HTMLSlotElement::GetName() const {
return NormalizeSlotName(FastGetAttribute(kNameAttr));
}
@@ -283,7 +251,15 @@ void HTMLSlotElement::AttachLayoutTree(AttachContext& context) {
HTMLElement::AttachLayoutTree(context);
if (SupportsAssignment()) {
+ LayoutObject* layout_object = GetLayoutObject();
AttachContext children_context(context);
+ const ComputedStyle* style = GetComputedStyle();
+ if (layout_object || !style || style->IsEnsuredInDisplayNone()) {
+ children_context.previous_in_flow = nullptr;
+ children_context.parent = layout_object;
+ children_context.next_sibling = nullptr;
+ children_context.next_sibling_valid = true;
+ }
for (auto& node : AssignedNodes())
node->AttachLayoutTree(children_context);
@@ -292,25 +268,23 @@ void HTMLSlotElement::AttachLayoutTree(AttachContext& context) {
}
}
-void HTMLSlotElement::DetachLayoutTree(const AttachContext& context) {
+void HTMLSlotElement::DetachLayoutTree(bool performing_reattach) {
if (SupportsAssignment()) {
const HeapVector<Member<Node>>& flat_tree_children = assigned_nodes_;
for (auto& node : flat_tree_children)
- node->DetachLayoutTree(context);
+ node->DetachLayoutTree(performing_reattach);
}
- HTMLElement::DetachLayoutTree(context);
+ HTMLElement::DetachLayoutTree(performing_reattach);
}
void HTMLSlotElement::RebuildDistributedChildrenLayoutTrees(
WhitespaceAttacher& whitespace_attacher) {
- if (!SupportsAssignment())
- return;
-
- const HeapVector<Member<Node>>& assigned_nodes = AssignedNodes();
+ DCHECK(SupportsAssignment());
// This loop traverses the nodes from right to left for the same reason as the
// one described in ContainerNode::RebuildChildrenLayoutTrees().
- for (auto it = assigned_nodes.rbegin(); it != assigned_nodes.rend(); ++it) {
+ for (auto it = flat_tree_children_.rbegin(); it != flat_tree_children_.rend();
+ ++it) {
RebuildLayoutTreeForChild(*it, whitespace_attacher);
}
}
@@ -412,8 +386,8 @@ void HTMLSlotElement::DidRecalcStyle(const StyleRecalcChange change) {
for (auto& node : assigned_nodes_) {
if (!change.TraverseChild(*node))
continue;
- if (node->IsElementNode())
- ToElement(node)->RecalcStyle(change);
+ if (auto* element = DynamicTo<Element>(node.Get()))
+ element->RecalcStyle(change);
else if (auto* text_node = DynamicTo<Text>(node.Get()))
text_node->RecalcTextStyle(change);
}
@@ -423,14 +397,15 @@ void HTMLSlotElement::NotifySlottedNodesOfFlatTreeChangeByDynamicProgramming(
const HeapVector<Member<Node>>& old_slotted,
const HeapVector<Member<Node>>& new_slotted) {
// Use dynamic programming to minimize the number of nodes being reattached.
- using LCSTable = std::array<std::array<wtf_size_t, kLCSTableSizeLimit>,
- kLCSTableSizeLimit>;
+ using LCSTable =
+ Vector<LCSArray<wtf_size_t, kLCSTableSizeLimit>, kLCSTableSizeLimit>;
using Backtrack = std::pair<wtf_size_t, wtf_size_t>;
using BacktrackTable =
- std::array<std::array<Backtrack, kLCSTableSizeLimit>, kLCSTableSizeLimit>;
+ Vector<LCSArray<Backtrack, kLCSTableSizeLimit>, kLCSTableSizeLimit>;
- DEFINE_STATIC_LOCAL(LCSTable*, lcs_table, (new LCSTable));
- DEFINE_STATIC_LOCAL(BacktrackTable*, backtrack_table, (new BacktrackTable));
+ DEFINE_STATIC_LOCAL(LCSTable*, lcs_table, (new LCSTable(kLCSTableSizeLimit)));
+ DEFINE_STATIC_LOCAL(BacktrackTable*, backtrack_table,
+ (new BacktrackTable(kLCSTableSizeLimit)));
FillLongestCommonSubsequenceDynamicProgrammingTable(
old_slotted, new_slotted, *lcs_table, *backtrack_table);
@@ -556,21 +531,12 @@ bool HTMLSlotElement::HasAssignedNodesSlow() const {
return assignment.FindHostChildBySlotName(GetName());
}
-bool HTMLSlotElement::FindHostChildWithSameSlotName() const {
- ShadowRoot* root = ContainingShadowRoot();
- DCHECK(root);
- DCHECK(root->IsV1());
- SlotAssignment& assignment = root->GetSlotAssignment();
- return assignment.FindHostChildBySlotName(GetName());
-}
-
int HTMLSlotElement::tabIndex() const {
return Element::tabIndex();
}
void HTMLSlotElement::Trace(Visitor* visitor) {
visitor->Trace(assigned_nodes_);
- visitor->Trace(assigned_nodes_index_);
visitor->Trace(flat_tree_children_);
visitor->Trace(assigned_nodes_candidates_);
HTMLElement::Trace(visitor);
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 3a2fc851b9b..0821db41441 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
@@ -73,13 +73,12 @@ class CORE_EXPORT HTMLSlotElement final : public HTMLElement {
void WillRecalcAssignedNodes() { ClearAssignedNodes(); }
void DidRecalcAssignedNodes() {
- if (RuntimeEnabledFeatures::FastFlatTreeTraversalEnabled())
- UpdateFlatTreeNodeDataForAssignedNodes();
+ UpdateFlatTreeNodeDataForAssignedNodes();
RecalcFlatTreeChildren();
}
void AttachLayoutTree(AttachContext&) final;
- void DetachLayoutTree(const AttachContext& = AttachContext()) final;
+ void DetachLayoutTree(bool performing_reattach) final;
void RebuildDistributedChildrenLayoutTrees(WhitespaceAttacher&);
void AttributeChanged(const AttributeModificationParams&) final;
@@ -91,7 +90,6 @@ class CORE_EXPORT HTMLSlotElement final : public HTMLElement {
// shadow host. This method should be used only when |assigned_nodes_| is
// dirty. e.g. To detect a slotchange event in DOM mutations.
bool HasAssignedNodesSlow() const;
- bool FindHostChildWithSameSlotName() const;
bool SupportsAssignment() const { return IsInV1ShadowTree(); }
@@ -143,7 +141,6 @@ class CORE_EXPORT HTMLSlotElement final : public HTMLElement {
void ClearAssignedNodesAndFlatTreeChildren();
HeapVector<Member<Node>> assigned_nodes_;
- HeapHashMap<Member<const Node>, unsigned> assigned_nodes_index_;
HeapVector<Member<Node>> flat_tree_children_;
bool slotchange_event_enqueued_ = false;
@@ -151,6 +148,14 @@ class CORE_EXPORT HTMLSlotElement final : public HTMLElement {
// For imperative Shadow DOM distribution APIs
HeapHashSet<Member<Node>> assigned_nodes_candidates_;
+ template <typename T, wtf_size_t S>
+ struct LCSArray {
+ LCSArray() : values(S) {}
+ T& operator[](wtf_size_t i) { return values[i]; }
+ wtf_size_t size() { return values.size(); }
+ Vector<T, S> values;
+ };
+
// TODO(hayato): Move this to more appropriate directory (e.g. platform/wtf)
// if there are more than one usages.
template <typename Container, typename LCSTable, typename BacktrackTable>
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 d501b022101..bb8898cb9ed 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
@@ -4,8 +4,6 @@
#include "third_party/blink/renderer/core/html/html_slot_element.h"
-#include <array>
-
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/core/css/style_engine.h"
#include "third_party/blink/renderer/core/dom/node_computed_style.h"
@@ -16,21 +14,22 @@ namespace blink {
namespace {
constexpr int kTableSize = 16;
-using Seq = std::vector<char>;
+using Seq = Vector<char>;
using Backtrack = std::pair<size_t, size_t>;
}
class HTMLSlotElementTest : public testing::Test {
protected:
- HTMLSlotElementTest() = default;
+ HTMLSlotElementTest()
+ : lcs_table_(kTableSize), backtrack_table_(kTableSize) {}
Seq LongestCommonSubsequence(const Seq& seq1, const Seq& seq2);
- std::array<std::array<size_t, kTableSize>, kTableSize> lcs_table_;
- std::array<std::array<Backtrack, kTableSize>, kTableSize> backtrack_table_;
+ Vector<HTMLSlotElement::LCSArray<size_t, kTableSize>, kTableSize> lcs_table_;
+ Vector<HTMLSlotElement::LCSArray<Backtrack, kTableSize>, kTableSize>
+ backtrack_table_;
};
-std::vector<char> HTMLSlotElementTest::LongestCommonSubsequence(
- const Seq& seq1,
- const Seq& seq2) {
+Vector<char> HTMLSlotElementTest::LongestCommonSubsequence(const Seq& seq1,
+ const Seq& seq2) {
HTMLSlotElement::FillLongestCommonSubsequenceDynamicProgrammingTable(
seq1, seq2, lcs_table_, backtrack_table_);
Seq lcs;
@@ -157,16 +156,16 @@ TEST_F(HTMLSlotElementReattachTest, RecalcAssignedNodeStyleForReattach) {
shadow_root.SetInnerHTMLFromString(
R"HTML(<span><slot /></span>)HTML");
- Element& shadow_span = *ToElement(shadow_root.firstChild());
+ auto* shadow_span = To<Element>(shadow_root.firstChild());
GetDocument().View()->UpdateAllLifecyclePhases(
DocumentLifecycle::LifecycleUpdateReason::kTest);
- shadow_span.setAttribute(html_names::kStyleAttr, "display:block");
+ shadow_span->setAttribute(html_names::kStyleAttr, "display:block");
GetDocument().Lifecycle().AdvanceTo(DocumentLifecycle::kInStyleRecalc);
GetDocument().GetStyleEngine().RecalcStyle({});
- EXPECT_TRUE(shadow_span.GetComputedStyle());
+ EXPECT_TRUE(shadow_span->GetComputedStyle());
EXPECT_TRUE(span.GetComputedStyle());
}
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 4ba9bf6f7b9..ef77c39bcf3 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
@@ -100,20 +100,22 @@ Node::InsertionNotificationRequest HTMLSourceElement::InsertedInto(
Element* parent = parentElement();
if (auto* media = ToHTMLMediaElementOrNull(parent))
media->SourceWasAdded(this);
- if (auto* picture = ToHTMLPictureElementOrNull(parent))
- picture->SourceOrMediaChanged();
+ if (parent == insertion_point && IsHTMLPictureElement(parent))
+ ToHTMLPictureElement(parent)->SourceOrMediaChanged();
return kInsertionDone;
}
void HTMLSourceElement::RemovedFrom(ContainerNode& removal_root) {
Element* parent = parentElement();
- if (!parent && removal_root.IsElementNode())
- parent = ToElement(&removal_root);
+ bool was_removed_from_parent = !parent;
+ if (was_removed_from_parent)
+ parent = DynamicTo<Element>(&removal_root);
if (auto* media = ToHTMLMediaElementOrNull(parent))
media->SourceWasRemoved(this);
if (auto* picture = ToHTMLPictureElementOrNull(parent)) {
RemoveMediaQueryListListener();
- picture->SourceOrMediaChanged();
+ if (was_removed_from_parent)
+ picture->SourceOrMediaChanged();
}
HTMLElement::RemovedFrom(removal_root);
}
diff --git a/chromium/third_party/blink/renderer/core/html/html_source_element.idl b/chromium/third_party/blink/renderer/core/html/html_source_element.idl
index acf73961713..6ab643a2928 100644
--- a/chromium/third_party/blink/renderer/core/html/html_source_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_source_element.idl
@@ -24,8 +24,10 @@
*/
// https://html.spec.whatwg.org/C/#the-source-element
-[HTMLConstructor]
-interface HTMLSourceElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLSourceElement : HTMLElement {
[CEReactions, Reflect, URL, RaisesException=Setter] attribute URLString src;
[CEReactions] attribute DOMString type;
diff --git a/chromium/third_party/blink/renderer/core/html/html_span_element.idl b/chromium/third_party/blink/renderer/core/html/html_span_element.idl
index 6fcc37d7d83..1cb60a27d40 100644
--- a/chromium/third_party/blink/renderer/core/html/html_span_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_span_element.idl
@@ -24,6 +24,8 @@
*/
// https://html.spec.whatwg.org/C/#the-span-element
-[HTMLConstructor]
-interface HTMLSpanElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLSpanElement : HTMLElement {
};
diff --git a/chromium/third_party/blink/renderer/core/html/html_style_element.idl b/chromium/third_party/blink/renderer/core/html/html_style_element.idl
index f213490016c..5370a3608ba 100644
--- a/chromium/third_party/blink/renderer/core/html/html_style_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_style_element.idl
@@ -19,8 +19,10 @@
*/
// https://html.spec.whatwg.org/C/#the-style-element
-[HTMLConstructor]
-interface HTMLStyleElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLStyleElement : HTMLElement {
// TODO(foolip): The disabled attribute has been removed from the spec:
// https://www.w3.org/Bugs/Public/show_bug.cgi?id=14703
[Measure] attribute boolean disabled;
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 75b2d11151f..9ac4c1b500c 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
@@ -87,9 +87,9 @@ bool HTMLSummaryElement::IsMainSummary() const {
}
static bool IsClickableControl(Node* node) {
- if (!node->IsElementNode())
+ auto* element = DynamicTo<Element>(node);
+ if (!element)
return false;
- Element* element = ToElement(node);
if (element->IsFormControlElement())
return true;
Element* host = element->OwnerShadowHost();
diff --git a/chromium/third_party/blink/renderer/core/html/html_table_caption_element.idl b/chromium/third_party/blink/renderer/core/html/html_table_caption_element.idl
index 030d38491f8..386b675e323 100644
--- a/chromium/third_party/blink/renderer/core/html/html_table_caption_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_table_caption_element.idl
@@ -19,8 +19,10 @@
*/
// https://html.spec.whatwg.org/C/#the-caption-element
-[HTMLConstructor]
-interface HTMLTableCaptionElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLTableCaptionElement : HTMLElement {
// obsolete members
// https://html.spec.whatwg.org/C/#HTMLTableCaptionElement-partial
[CEReactions, Reflect] attribute DOMString align;
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 3071fb2e99e..90855ac2d2a 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
@@ -28,12 +28,12 @@
#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"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/html_table_element.h"
#include "third_party/blink/renderer/core/html/parser/html_parser_idioms.h"
#include "third_party/blink/renderer/core/html/table_constants.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/layout/layout_table_cell.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/html_table_cell_element.idl b/chromium/third_party/blink/renderer/core/html/html_table_cell_element.idl
index 29d6d5a58b9..d29dce0339d 100644
--- a/chromium/third_party/blink/renderer/core/html/html_table_cell_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_table_cell_element.idl
@@ -19,8 +19,10 @@
*/
// https://html.spec.whatwg.org/C/#attributes-common-to-td-and-th-elements
-[HTMLConstructor]
-interface HTMLTableCellElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLTableCellElement : HTMLElement {
[CEReactions] attribute unsigned long colSpan;
[CEReactions] attribute unsigned long rowSpan;
// TODO(foolip): headers should be a [PutForwards=value] readonly attribute
diff --git a/chromium/third_party/blink/renderer/core/html/html_table_col_element.idl b/chromium/third_party/blink/renderer/core/html/html_table_col_element.idl
index 42afbc16087..32295d37d80 100644
--- a/chromium/third_party/blink/renderer/core/html/html_table_col_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_table_col_element.idl
@@ -20,8 +20,10 @@
// https://html.spec.whatwg.org/C/#the-colgroup-element
// https://html.spec.whatwg.org/C/#the-col-element
-[HTMLConstructor]
-interface HTMLTableColElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLTableColElement : HTMLElement {
[CEReactions] attribute unsigned long span;
// obsolete attributes
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 ab1dbc2a5b9..6f718881568 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,6 +28,7 @@
#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_numeric_literal_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"
@@ -35,7 +36,6 @@
#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/node_lists_node_data.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/html_table_caption_element.h"
#include "third_party/blink/renderer/core/html/html_table_cell_element.h"
#include "third_party/blink/renderer/core/html/html_table_row_element.h"
@@ -45,6 +45,7 @@
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/weborigin/referrer.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
@@ -329,7 +330,8 @@ void HTMLTableElement::CollectStyleForPresentationAttribute(
CSSImageValue* image_value =
CSSImageValue::Create(url, GetDocument().CompleteURL(url),
Referrer(GetDocument().OutgoingReferrer(),
- GetDocument().GetReferrerPolicy()));
+ GetDocument().GetReferrerPolicy()),
+ OriginClean::kTrue);
style->SetProperty(
CSSPropertyValue(GetCSSPropertyBackgroundImage(), *image_value));
}
@@ -531,18 +533,18 @@ CSSPropertyValueSet* HTMLTableElement::CreateSharedCellStyle() {
*CSSInheritedValue::Create());
break;
case kSolidBorders:
- style->SetProperty(
- CSSPropertyID::kBorderWidth,
- *CSSPrimitiveValue::Create(1, CSSPrimitiveValue::UnitType::kPixels));
+ style->SetProperty(CSSPropertyID::kBorderWidth,
+ *CSSNumericLiteralValue::Create(
+ 1, CSSPrimitiveValue::UnitType::kPixels));
style->SetProperty(CSSPropertyID::kBorderStyle,
*CSSIdentifierValue::Create(CSSValueID::kSolid));
style->SetProperty(CSSPropertyID::kBorderColor,
*CSSInheritedValue::Create());
break;
case kInsetBorders:
- style->SetProperty(
- CSSPropertyID::kBorderWidth,
- *CSSPrimitiveValue::Create(1, CSSPrimitiveValue::UnitType::kPixels));
+ style->SetProperty(CSSPropertyID::kBorderWidth,
+ *CSSNumericLiteralValue::Create(
+ 1, CSSPrimitiveValue::UnitType::kPixels));
style->SetProperty(CSSPropertyID::kBorderStyle,
*CSSIdentifierValue::Create(CSSValueID::kInset));
style->SetProperty(CSSPropertyID::kBorderColor,
@@ -556,7 +558,7 @@ CSSPropertyValueSet* HTMLTableElement::CreateSharedCellStyle() {
if (padding_)
style->SetProperty(CSSPropertyID::kPadding,
- *CSSPrimitiveValue::Create(
+ *CSSNumericLiteralValue::Create(
padding_, CSSPrimitiveValue::UnitType::kPixels));
return style;
diff --git a/chromium/third_party/blink/renderer/core/html/html_table_element.idl b/chromium/third_party/blink/renderer/core/html/html_table_element.idl
index a057d4de071..9d773aa1200 100644
--- a/chromium/third_party/blink/renderer/core/html/html_table_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_table_element.idl
@@ -19,8 +19,10 @@
*/
// https://html.spec.whatwg.org/C/#the-table-element
-[HTMLConstructor]
-interface HTMLTableElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLTableElement : HTMLElement {
[CEReactions, RaisesException=Setter] attribute HTMLTableCaptionElement? caption;
[CEReactions] HTMLTableCaptionElement createCaption();
[CEReactions] void deleteCaption();
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 fabea0f9126..c5c813d81c3 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
@@ -30,10 +30,10 @@
#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"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/html_table_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/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/weborigin/referrer.h"
namespace blink {
@@ -63,7 +63,8 @@ void HTMLTablePartElement::CollectStyleForPresentationAttribute(
CSSImageValue* image_value =
CSSImageValue::Create(url, GetDocument().CompleteURL(url),
Referrer(GetDocument().OutgoingReferrer(),
- GetDocument().GetReferrerPolicy()));
+ GetDocument().GetReferrerPolicy()),
+ OriginClean::kTrue);
style->SetProperty(
CSSPropertyValue(GetCSSPropertyBackgroundImage(), *image_value));
}
diff --git a/chromium/third_party/blink/renderer/core/html/html_table_row_element.idl b/chromium/third_party/blink/renderer/core/html/html_table_row_element.idl
index 9965d481b0f..50afa319e5a 100644
--- a/chromium/third_party/blink/renderer/core/html/html_table_row_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_table_row_element.idl
@@ -19,8 +19,10 @@
*/
// https://html.spec.whatwg.org/C/#the-tr-element
-[HTMLConstructor]
-interface HTMLTableRowElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLTableRowElement : HTMLElement {
readonly attribute long rowIndex;
readonly attribute long sectionRowIndex;
readonly attribute HTMLCollection cells;
diff --git a/chromium/third_party/blink/renderer/core/html/html_table_section_element.idl b/chromium/third_party/blink/renderer/core/html/html_table_section_element.idl
index b95a4946258..4859cd27b87 100644
--- a/chromium/third_party/blink/renderer/core/html/html_table_section_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_table_section_element.idl
@@ -21,8 +21,10 @@
// https://html.spec.whatwg.org/C/#the-tbody-element
// https://html.spec.whatwg.org/C/#the-thead-element
// https://html.spec.whatwg.org/C/#the-tfoot-element
-[HTMLConstructor]
-interface HTMLTableSectionElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLTableSectionElement : HTMLElement {
readonly attribute HTMLCollection rows;
[CEReactions, RaisesException] HTMLElement insertRow(optional long index = -1);
[CEReactions, RaisesException] void deleteRow(long index);
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 ebd0ebf819c..2e7570d63d7 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
@@ -33,7 +33,7 @@
#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/template_content_document_fragment.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/html_template_element.idl b/chromium/third_party/blink/renderer/core/html/html_template_element.idl
index 2d8fdfbb4d4..ebfd32c39ac 100644
--- a/chromium/third_party/blink/renderer/core/html/html_template_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_template_element.idl
@@ -29,7 +29,9 @@
*/
// https://html.spec.whatwg.org/C/#the-template-element
-[HTMLConstructor]
-interface HTMLTemplateElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLTemplateElement : HTMLElement {
readonly attribute DocumentFragment content;
};
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 fed6cf8bf11..7ff049ea866 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
@@ -4,7 +4,7 @@
#include "third_party/blink/renderer/core/html/html_time_element.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/html_time_element.idl b/chromium/third_party/blink/renderer/core/html/html_time_element.idl
index 3f6e0c95ac8..d0fd76bd3a1 100644
--- a/chromium/third_party/blink/renderer/core/html/html_time_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_time_element.idl
@@ -4,7 +4,9 @@
// https://html.spec.whatwg.org/C/#the-time-element
-[HTMLConstructor]
-interface HTMLTimeElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLTimeElement : HTMLElement {
[CEReactions, Reflect] attribute DOMString dateTime;
}; \ No newline at end of file
diff --git a/chromium/third_party/blink/renderer/core/html/html_title_element.idl b/chromium/third_party/blink/renderer/core/html/html_title_element.idl
index c28e9c0d61e..191b831cd10 100644
--- a/chromium/third_party/blink/renderer/core/html/html_title_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_title_element.idl
@@ -18,7 +18,9 @@
*/
// https://html.spec.whatwg.org/C/#the-title-element
-[HTMLConstructor]
-interface HTMLTitleElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLTitleElement : HTMLElement {
[CEReactions] attribute DOMString text;
};
diff --git a/chromium/third_party/blink/renderer/core/html/html_ulist_element.idl b/chromium/third_party/blink/renderer/core/html/html_ulist_element.idl
index 7a0f2cd45c8..3a16e709fd4 100644
--- a/chromium/third_party/blink/renderer/core/html/html_ulist_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/html_ulist_element.idl
@@ -18,8 +18,10 @@
*/
// https://html.spec.whatwg.org/C/#the-ul-element
-[HTMLConstructor]
-interface HTMLUListElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLUListElement : HTMLElement {
// obsolete members
// https://html.spec.whatwg.org/C/#HTMLUListElement-partial
[CEReactions, Reflect] attribute boolean compact;
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 1f07036c8ac..e45fe09be9e 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
@@ -52,7 +52,7 @@ const char kXSSDetected[] = "Token contains a reflected XSS vector";
HTMLViewSourceDocument::HTMLViewSourceDocument(const DocumentInit& initializer,
const String& mime_type)
- : HTMLDocument(initializer), type_(mime_type) {
+ : HTMLDocument(initializer, kViewSourceDocumentClass), type_(mime_type) {
SetIsViewSource(true);
// FIXME: Why do view-source pages need to load in quirks mode?
@@ -289,7 +289,7 @@ int HTMLViewSourceDocument::AddRange(const String& source,
}
AddText(text, class_name);
if (!class_name.IsEmpty() && current_ != tbody_)
- current_ = ToElement(current_->parentNode());
+ current_ = To<Element>(current_->parentNode());
return end;
}
@@ -337,7 +337,7 @@ int HTMLViewSourceDocument::AddSrcset(const String& source,
AtomicString link(tmp[0]);
current_ = AddLink(link, false);
AddText(srclist[i], "html-attribute-value");
- current_ = ToElement(current_->parentNode());
+ current_ = To<Element>(current_->parentNode());
} else {
AddText(srclist[i], "html-attribute-value");
}
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 97ffda683e2..021425cae74 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
@@ -75,9 +75,6 @@ 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/image_document.cc b/chromium/third_party/blink/renderer/core/html/image_document.cc
index 22a86c31076..6947540ca6a 100644
--- a/chromium/third_party/blink/renderer/core/html/image_document.cc
+++ b/chromium/third_party/blink/renderer/core/html/image_document.cc
@@ -36,7 +36,6 @@
#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/frame/visual_viewport.h"
#include "third_party/blink/renderer/core/html/html_body_element.h"
#include "third_party/blink/renderer/core/html/html_div_element.h"
@@ -55,6 +54,7 @@
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/wtf/casting.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
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 62a71b0b070..23d0f6a24c8 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
@@ -236,16 +236,26 @@ TEST_F(ImageDocumentTest, MAYBE(ImageCenteredAtDeviceScaleFactor)) {
GetDocument().ImageClicked(15, 27);
ScrollOffset offset =
GetDocument().GetFrame()->View()->LayoutViewport()->GetScrollOffset();
- EXPECT_EQ(22, offset.Width());
- EXPECT_EQ(42, offset.Height());
+ if (RuntimeEnabledFeatures::FractionalScrollOffsetsEnabled()) {
+ EXPECT_EQ(22.5f, offset.Width());
+ EXPECT_EQ(42, offset.Height());
+ } else {
+ EXPECT_EQ(22, offset.Width());
+ EXPECT_EQ(42, offset.Height());
+ }
GetDocument().ImageClicked(20, 20);
GetDocument().ImageClicked(12, 15);
offset =
GetDocument().GetFrame()->View()->LayoutViewport()->GetScrollOffset();
- EXPECT_EQ(11, offset.Width());
- EXPECT_EQ(22, offset.Height());
+ if (RuntimeEnabledFeatures::FractionalScrollOffsetsEnabled()) {
+ EXPECT_EQ(11.25f, offset.Width());
+ EXPECT_EQ(22.5f, offset.Height());
+ } else {
+ EXPECT_EQ(11, offset.Width());
+ EXPECT_EQ(22, offset.Height());
+ }
}
class ImageDocumentViewportTest : public SimTest {
diff --git a/chromium/third_party/blink/renderer/core/html/imports/html_import.h b/chromium/third_party/blink/renderer/core/html/imports/html_import.h
index e112e64aa18..45078adb4ed 100644
--- a/chromium/third_party/blink/renderer/core/html/imports/html_import.h
+++ b/chromium/third_party/blink/renderer/core/html/imports/html_import.h
@@ -33,7 +33,7 @@
#include "third_party/blink/renderer/core/html/imports/html_import_state.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/tree_node.h"
namespace blink {
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 6b2c0fd8c57..063eff44f11 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
@@ -151,7 +151,7 @@ void HTMLImportLoader::NotifyParserStopped() {
parser->RemoveClient(this);
}
-void HTMLImportLoader::DidRemoveAllPendingStylesheet() {
+void HTMLImportLoader::DidRemoveAllPendingStylesheets() {
if (state_ == kStateParsed)
SetState(FinishLoading());
}
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 fa38f1addd2..3034cc534d9 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
@@ -83,9 +83,8 @@ class HTMLImportLoader final
bool ShouldBlockScriptExecution() const;
// Tells the loader that all of the import's stylesheets finished
- // loading.
- // Called by Document::didRemoveAllPendingStylesheet.
- void DidRemoveAllPendingStylesheet();
+ // loading. Called by Document::DidRemoveAllPendingStylesheets.
+ void DidRemoveAllPendingStylesheets();
V0CustomElementSyncMicrotaskQueue* MicrotaskQueue() const;
diff --git a/chromium/third_party/blink/renderer/core/html/imports/html_import_state.h b/chromium/third_party/blink/renderer/core/html/imports/html_import_state.h
index c193d4cd125..1bfc893ee13 100644
--- a/chromium/third_party/blink/renderer/core/html/imports/html_import_state.h
+++ b/chromium/third_party/blink/renderer/core/html/imports/html_import_state.h
@@ -31,7 +31,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_HTML_IMPORTS_HTML_IMPORT_STATE_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_IMPORTS_HTML_IMPORT_STATE_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
namespace blink {
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 e468beaa6a9..d88f5f79f8d 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
@@ -55,7 +55,7 @@ void HTMLImportTreeRoot::ScheduleRecalcState() {
DCHECK(document_);
if (recalc_timer_.IsActive() || !document_->IsActive())
return;
- recalc_timer_.StartOneShot(TimeDelta(), FROM_HERE);
+ recalc_timer_.StartOneShot(base::TimeDelta(), FROM_HERE);
}
HTMLImportChild* HTMLImportTreeRoot::Add(HTMLImportChild* child) {
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 d880eb0c47a..da8f64464c6 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
@@ -31,12 +31,12 @@
#include "third_party/blink/renderer/core/html/imports/html_imports_controller.h"
#include "third_party/blink/renderer/core/dom/document.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/imports/html_import_child.h"
#include "third_party/blink/renderer/core/html/imports/html_import_child_client.h"
#include "third_party/blink/renderer/core/html/imports/html_import_loader.h"
#include "third_party/blink/renderer/core/html/imports/html_import_tree_root.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
namespace blink {
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 75fe52d3f69..ddb6933ec8b 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
@@ -34,7 +34,7 @@
#include "third_party/blink/renderer/core/dom/document.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/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
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 c5fc72d461e..f907e0f9f69 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,7 +30,7 @@
#include "third_party/blink/renderer/core/html/imports/link_import.h"
-#include "services/network/public/mojom/referrer_policy.mojom-shared.h"
+#include "services/network/public/mojom/referrer_policy.mojom-blink.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"
@@ -76,7 +76,8 @@ void LinkImport::Process() {
ResourceRequest resource_request(GetDocument().CompleteURL(url));
network::mojom::ReferrerPolicy referrer_policy = owner_->GetReferrerPolicy();
- resource_request.SetReferrerPolicy(referrer_policy);
+ resource_request.SetReferrerPolicy(
+ referrer_policy, ResourceRequest::SetReferrerPolicyLocation::kLinkImport);
ResourceLoaderOptions options;
options.initiator_info.name = owner_->localName();
diff --git a/chromium/third_party/blink/renderer/core/html/imports/link_import.h b/chromium/third_party/blink/renderer/core/html/imports/link_import.h
index e6586e1aa77..b6f1b8fcbc2 100644
--- a/chromium/third_party/blink/renderer/core/html/imports/link_import.h
+++ b/chromium/third_party/blink/renderer/core/html/imports/link_import.h
@@ -34,7 +34,7 @@
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/core/html/imports/html_import_child_client.h"
#include "third_party/blink/renderer/core/html/link_resource.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 647028a380f..17a280cf27e 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
@@ -25,6 +25,7 @@
#include "third_party/blink/renderer/platform/geometry/length.h"
#include "third_party/blink/renderer/platform/heap/visitor.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/weborigin/security_origin.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
@@ -71,8 +72,7 @@ int GetLazyFrameLoadingViewportDistanceThresholdPx(const Document& document) {
if (!settings)
return 0;
- DCHECK(document.GetFrame() && document.GetFrame()->Client());
- switch (document.GetFrame()->Client()->GetEffectiveConnectionType()) {
+ switch (GetNetworkStateNotifier().EffectiveType()) {
case WebEffectiveConnectionType::kTypeUnknown:
return settings->GetLazyFrameLoadingDistanceThresholdPxUnknown();
case WebEffectiveConnectionType::kTypeOffline:
@@ -164,10 +164,7 @@ void LazyLoadFrameObserver::LoadImmediately() {
UMA_HISTOGRAM_ENUMERATION(
"Blink.LazyLoad.CrossOriginFrames.LoadStartedAfterBeingDeferred",
- element_->GetDocument()
- .GetFrame()
- ->Client()
- ->GetEffectiveConnectionType());
+ GetNetworkStateNotifier().EffectiveType());
element_->GetDocument().GetFrame()->Client()->DidObserveLazyLoadBehavior(
WebLocalFrameClient::LazyLoadBehavior::kLazyLoadedFrame);
}
@@ -225,7 +222,7 @@ void LazyLoadFrameObserver::RecordMetricsOnVisibilityChanged(
return;
DCHECK(time_when_first_visible_.is_null());
- time_when_first_visible_ = CurrentTimeTicks();
+ time_when_first_visible_ = base::TimeTicks::Now();
RecordVisibilityMetricsIfLoadedAndVisible();
visibility_metrics_observer_->disconnect();
@@ -237,8 +234,6 @@ void LazyLoadFrameObserver::RecordMetricsOnVisibilityChanged(
if (!element_->GetDocument().GetFrame())
return;
- DCHECK(element_->GetDocument().GetFrame()->Client());
-
// On slow networks, iframes might not finish loading by the time the user
// leaves the page, so the visible load time metrics samples won't represent
// the slowest frames. To remedy this, record how often below the fold
@@ -253,26 +248,20 @@ void LazyLoadFrameObserver::RecordMetricsOnVisibilityChanged(
// WebEffectiveConnectionType.
UMA_HISTOGRAM_ENUMERATION(
"Blink.VisibleBeforeLoaded.LazyLoadEligibleFrames.BelowTheFold",
- element_->GetDocument()
- .GetFrame()
- ->Client()
- ->GetEffectiveConnectionType());
+ GetNetworkStateNotifier().EffectiveType());
}
if (was_recorded_as_deferred_) {
UMA_HISTOGRAM_ENUMERATION(
"Blink.LazyLoad.CrossOriginFrames.VisibleAfterBeingDeferred",
- element_->GetDocument()
- .GetFrame()
- ->Client()
- ->GetEffectiveConnectionType());
+ GetNetworkStateNotifier().EffectiveType());
}
}
void LazyLoadFrameObserver::RecordMetricsOnLoadFinished() {
if (!time_when_first_load_finished_.is_null())
return;
- time_when_first_load_finished_ = CurrentTimeTicks();
+ time_when_first_load_finished_ = base::TimeTicks::Now();
RecordVisibilityMetricsIfLoadedAndVisible();
}
@@ -285,15 +274,12 @@ void LazyLoadFrameObserver::RecordVisibilityMetricsIfLoadedAndVisible() {
DCHECK(has_above_the_fold_been_set_);
- TimeDelta visible_load_delay =
+ base::TimeDelta visible_load_delay =
time_when_first_load_finished_ - time_when_first_visible_;
- if (visible_load_delay < TimeDelta())
- visible_load_delay = TimeDelta();
+ if (visible_load_delay < base::TimeDelta())
+ visible_load_delay = base::TimeDelta();
- switch (element_->GetDocument()
- .GetFrame()
- ->Client()
- ->GetEffectiveConnectionType()) {
+ switch (GetNetworkStateNotifier().EffectiveType()) {
case WebEffectiveConnectionType::kTypeSlow2G:
if (is_initially_above_the_fold_) {
UMA_HISTOGRAM_MEDIUM_TIMES(
@@ -358,10 +344,7 @@ void LazyLoadFrameObserver::RecordInitialDeferralAction(
DCHECK(element_->GetDocument().GetFrame());
DCHECK(element_->GetDocument().GetFrame()->Client());
- switch (element_->GetDocument()
- .GetFrame()
- ->Client()
- ->GetEffectiveConnectionType()) {
+ switch (GetNetworkStateNotifier().EffectiveType()) {
case WebEffectiveConnectionType::kTypeUnknown:
UMA_HISTOGRAM_ENUMERATION(
"Blink.LazyLoad.CrossOriginFrames.InitialDeferralAction.Unknown",
diff --git a/chromium/third_party/blink/renderer/core/html/lazy_load_frame_observer.h b/chromium/third_party/blink/renderer/core/html/lazy_load_frame_observer.h
index 5aef9962946..7562d75b2ff 100644
--- a/chromium/third_party/blink/renderer/core/html/lazy_load_frame_observer.h
+++ b/chromium/third_party/blink/renderer/core/html/lazy_load_frame_observer.h
@@ -88,9 +88,9 @@ class LazyLoadFrameObserver
bool has_above_the_fold_been_set_ = false;
// Set when the frame first becomes visible (i.e. appears in the viewport).
- TimeTicks time_when_first_visible_;
+ base::TimeTicks time_when_first_visible_;
// Set when the first load event is dispatched for the frame.
- TimeTicks time_when_first_load_finished_;
+ base::TimeTicks time_when_first_load_finished_;
// Keeps track of whether the frame was initially recorded as having been
// deferred, so that the appropriate histograms can be recorded if the frame
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 b97f5654c6c..73da6322fec 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
@@ -14,6 +14,7 @@
#include "third_party/blink/renderer/core/exported/web_view_impl.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/web_local_frame_impl.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/core/testing/sim/sim_compositor.h"
@@ -102,8 +103,10 @@ class LazyLoadFramesParamsTest
LazyFrameVisibleLoadTimeFeatureStatus::kEnabled) {}
void SetUp() override {
- WebFrameClient().SetEffectiveConnectionTypeForTesting(
- std::get<WebEffectiveConnectionType>(GetParam()));
+ GetNetworkStateNotifier().SetNetworkConnectionInfoOverride(
+ true /*on_line*/, kWebConnectionTypeWifi,
+ std::get<WebEffectiveConnectionType>(GetParam()),
+ 1000 /*http_rtt_msec*/, 100 /*max_bandwidth_mbps*/);
SimTest::SetUp();
WebView().MainFrameWidget()->Resize(
@@ -1134,23 +1137,25 @@ class LazyLoadFramesTest : public SimTest {
static constexpr int kLoadingDistanceThresholdPx = 1000;
void SetUp() override {
- GetNetworkStateNotifier().SetSaveDataEnabled(false);
- WebFrameClient().SetEffectiveConnectionTypeForTesting(
- WebEffectiveConnectionType::kTypeUnknown);
+ GetNetworkStateNotifier().SetSaveDataEnabledOverride(false);
+ GetNetworkStateNotifier().SetNetworkConnectionInfoOverride(
+ true /*on_line*/, kWebConnectionTypeWifi,
+ WebEffectiveConnectionType::kType4G, 1000 /*http_rtt_msec*/,
+ 100 /*max_bandwidth_mbps*/);
SimTest::SetUp();
WebView().MainFrameWidget()->Resize(
WebSize(kViewportWidth, kViewportHeight));
Settings& settings = WebView().GetPage()->GetSettings();
- settings.SetLazyFrameLoadingDistanceThresholdPxUnknown(
+ settings.SetLazyFrameLoadingDistanceThresholdPx4G(
kLoadingDistanceThresholdPx);
settings.SetLazyLoadEnabled(true);
settings.SetDataSaverHoldbackWebApi(false);
}
void TearDown() override {
- GetNetworkStateNotifier().SetSaveDataEnabled(false);
+ GetNetworkStateNotifier().SetSaveDataEnabledOverride(false);
SimTest::TearDown();
}
@@ -1224,6 +1229,65 @@ class LazyLoadFramesTest : public SimTest {
EXPECT_TRUE(ConsoleMessages().Contains("child frame element onload"));
}
+
+ void TestLazyLoadUsedInPageReload(const char* iframe_attributes,
+ bool is_deferral_expected_on_reload) {
+ HistogramTester histogram_tester;
+ ConsoleMessages().clear();
+
+ SimRequest main_resource("https://example.com/", "text/html");
+ MainFrame().StartReload(WebFrameLoadType::kReload);
+
+ 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' %s
+ style='width: 400px; height: 400px;'
+ onload='console.log("child frame element onload");'></iframe>
+ </body>)HTML",
+ LazyLoadFramesTest::kViewportHeight +
+ LazyLoadFramesTest::kLoadingDistanceThresholdPx + 100,
+ iframe_attributes));
+
+ if (is_deferral_expected_on_reload) {
+ // The body's load event should have already fired.
+ EXPECT_TRUE(ConsoleMessages().Contains("main body onload"));
+ EXPECT_FALSE(ConsoleMessages().Contains("child frame element onload"));
+
+ GetDocument().View()->LayoutViewport()->SetScrollOffset(
+ ScrollOffset(0, 150), kProgrammaticScroll);
+
+ SimRequest child_frame_resource("https://crossorigin.com/subframe.html",
+ "text/html");
+ Compositor().BeginFrame();
+ test::RunPendingTasks();
+ child_frame_resource.Complete("");
+ test::RunPendingTasks();
+
+ // Scroll down near the child frame to cause the child frame to start
+ // loading.
+ GetDocument().View()->LayoutViewport()->SetScrollOffset(
+ ScrollOffset(0, LazyLoadFramesTest::kViewportHeight +
+ LazyLoadFramesTest::kLoadingDistanceThresholdPx),
+ kProgrammaticScroll);
+
+ Compositor().BeginFrame();
+ test::RunPendingTasks();
+
+ histogram_tester.ExpectTotalCount(
+ "Blink.VisibleLoadTime.LazyLoadEligibleFrames.BelowTheFold.4G", 1);
+ } else {
+ SimRequest child_frame_resource("https://crossorigin.com/subframe.html",
+ "text/html");
+ Compositor().BeginFrame();
+ test::RunPendingTasks();
+ child_frame_resource.Complete("");
+ }
+ test::RunPendingTasks();
+ EXPECT_TRUE(ConsoleMessages().Contains("main body onload"));
+ EXPECT_TRUE(ConsoleMessages().Contains("child frame element onload"));
+ }
};
TEST_F(LazyLoadFramesTest, LazyLoadWhenDisabledAndAttrLazy) {
@@ -1324,7 +1388,7 @@ TEST_F(LazyLoadFramesTest, LazyLoadWhenAutomaticRestrictedAndAttrEager) {
scoped_restrict_automatic_lazy_frame_loading_to_data_saver_for_test_(
true);
- GetNetworkStateNotifier().SetSaveDataEnabled(true);
+ GetNetworkStateNotifier().SetSaveDataEnabledOverride(true);
TestCrossOriginFrameIsImmediatelyLoaded("loading='eager'");
EXPECT_FALSE(GetDocument().IsUseCounted(
WebFeature::kLazyLoadFrameLoadingAttributeLazy));
@@ -1374,7 +1438,7 @@ TEST_F(LazyLoadFramesTest, LazyLoadWhenDataSaverEnabledHoldbackAndRestricted) {
scoped_restrict_automatic_lazy_frame_loading_to_data_saver_for_test_(
true);
- GetNetworkStateNotifier().SetSaveDataEnabled(true);
+ GetNetworkStateNotifier().SetSaveDataEnabledOverride(true);
WebView().GetPage()->GetSettings().SetDataSaverHoldbackWebApi(true);
TestCrossOriginFrameIsImmediatelyLoaded("");
}
@@ -1387,8 +1451,76 @@ TEST_F(LazyLoadFramesTest, LazyLoadWhenDataSaverEnabledAndRestricted) {
scoped_restrict_automatic_lazy_frame_loading_to_data_saver_for_test_(
true);
- GetNetworkStateNotifier().SetSaveDataEnabled(true);
+ GetNetworkStateNotifier().SetSaveDataEnabledOverride(true);
+ TestCrossOriginFrameIsLazilyLoaded("");
+}
+
+// Frames with loading=lazy should be deferred irrespective of disable
+// lazyload-on reload feature state.
+TEST_F(LazyLoadFramesTest, NoAutoLazyLoadOnReload_DeferredForAttributeLazy) {
+ ScopedLazyFrameLoadingForTest scoped_lazy_frame_loading_for_test(true);
+ ScopedAutomaticLazyFrameLoadingForTest
+ scoped_automatic_lazy_frame_loading_for_test(true);
+ ScopedRestrictAutomaticLazyFrameLoadingToDataSaverForTest
+ scoped_restrict_automatic_lazy_frame_loading_to_data_saver_for_test(
+ false);
+ ScopedAutoLazyLoadOnReloadsForTest scoped_auto_lazy_load_on_reloads_for_test(
+ false);
+ ScopedLazyFrameVisibleLoadTimeMetricsForTest
+ scoped_lazy_frame_visible_load_time_metrics_for_test(true);
+
+ TestCrossOriginFrameIsLazilyLoaded("loading='lazy'");
+ TestLazyLoadUsedInPageReload("loading='lazy'", true);
+}
+
+// Frames with loading=lazy should be deferred irrespective of disable
+// lazyload-on reload feature state.
+TEST_F(LazyLoadFramesTest, AutoLazyLoadOnReload_DeferredForAttributeLazy) {
+ ScopedLazyFrameLoadingForTest scoped_lazy_frame_loading_for_test(true);
+ ScopedAutomaticLazyFrameLoadingForTest
+ scoped_automatic_lazy_frame_loading_for_test(true);
+ ScopedRestrictAutomaticLazyFrameLoadingToDataSaverForTest
+ scoped_restrict_automatic_lazy_frame_loading_to_data_saver_for_test(
+ false);
+ ScopedAutoLazyLoadOnReloadsForTest scoped_auto_lazy_load_on_reloads_for_test(
+ true);
+ ScopedLazyFrameVisibleLoadTimeMetricsForTest
+ scoped_lazy_frame_visible_load_time_metrics_for_test(true);
+
+ TestCrossOriginFrameIsLazilyLoaded("loading='lazy'");
+ TestLazyLoadUsedInPageReload("loading='lazy'", true);
+}
+
+TEST_F(LazyLoadFramesTest, NoAutoLazyLoadOnReload_NotDeferredForAttributeAuto) {
+ ScopedLazyFrameLoadingForTest scoped_lazy_frame_loading_for_test(true);
+ ScopedAutomaticLazyFrameLoadingForTest
+ scoped_automatic_lazy_frame_loading_for_test(true);
+ ScopedRestrictAutomaticLazyFrameLoadingToDataSaverForTest
+ scoped_restrict_automatic_lazy_frame_loading_to_data_saver_for_test(
+ false);
+ ScopedAutoLazyLoadOnReloadsForTest scoped_auto_lazy_load_on_reloads_for_test(
+ false);
+ ScopedLazyFrameVisibleLoadTimeMetricsForTest
+ scoped_lazy_frame_visible_load_time_metrics_for_test(true);
+
+ TestCrossOriginFrameIsLazilyLoaded("");
+ TestLazyLoadUsedInPageReload("", false);
+}
+
+TEST_F(LazyLoadFramesTest, AutoLazyLoadOnReload_DeferredForAttributeAuto) {
+ ScopedLazyFrameLoadingForTest scoped_lazy_frame_loading_for_test(true);
+ ScopedAutomaticLazyFrameLoadingForTest
+ scoped_automatic_lazy_frame_loading_for_test(true);
+ ScopedRestrictAutomaticLazyFrameLoadingToDataSaverForTest
+ scoped_restrict_automatic_lazy_frame_loading_to_data_saver_for_test(
+ false);
+ ScopedAutoLazyLoadOnReloadsForTest scoped_auto_lazy_load_on_reloads_for_test(
+ true);
+ ScopedLazyFrameVisibleLoadTimeMetricsForTest
+ scoped_lazy_frame_visible_load_time_metrics_for_test(true);
+
TestCrossOriginFrameIsLazilyLoaded("");
+ TestLazyLoadUsedInPageReload("", true);
}
} // namespace
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 176bec37771..a2e500bc590 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
@@ -11,9 +11,9 @@
#include "third_party/blink/public/platform/web_effective_connection_type.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/flat_tree_traversal.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_client.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/html/html_image_element.h"
#include "third_party/blink/renderer/core/html_element_type_helpers.h"
@@ -22,6 +22,7 @@
#include "third_party/blink/renderer/core/intersection_observer/intersection_observer_entry.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
+#include "third_party/blink/renderer/platform/network/network_state_notifier.h"
namespace blink {
@@ -32,8 +33,7 @@ int GetLazyImageLoadingViewportDistanceThresholdPx(const Document& document) {
if (!settings)
return 0;
- DCHECK(document.GetFrame() && document.GetFrame()->Client());
- switch (document.GetFrame()->Client()->GetEffectiveConnectionType()) {
+ switch (GetNetworkStateNotifier().EffectiveType()) {
case WebEffectiveConnectionType::kTypeUnknown:
return settings->GetLazyImageLoadingDistanceThresholdPxUnknown();
case WebEffectiveConnectionType::kTypeOffline:
@@ -57,6 +57,24 @@ Document* GetRootDocumentOrNull(Element* element) {
return nullptr;
}
+// Returns if the element or its ancestors are invisible, due to their style or
+// attribute or due to themselves not connected to the main document tree.
+bool IsElementInInvisibleSubTree(const Element& element) {
+ if (!element.isConnected())
+ return true;
+ for (Node& ancestor : FlatTreeTraversal::InclusiveAncestorsOf(element)) {
+ auto* ancestor_element = DynamicTo<Element>(ancestor);
+ if (!ancestor_element)
+ continue;
+ const ComputedStyle* style = ancestor_element->EnsureComputedStyle();
+ if (style && (style->Visibility() != EVisibility::kVisible ||
+ style->Display() == EDisplay::kNone)) {
+ return true;
+ }
+ }
+ return false;
+}
+
} // namespace
void LazyLoadImageObserver::StartMonitoring(Element* element,
@@ -139,10 +157,26 @@ void LazyLoadImageObserver::LoadIfNearViewport(
DCHECK(!entries.IsEmpty());
for (auto entry : entries) {
+ Element* element = entry->target();
+ HTMLImageElement* image_element = ToHTMLImageElementOrNull(element);
+ if (!entry->isIntersecting() && image_element) {
+ // Fully load the invisible image elements. The elements can be invisible
+ // by style such as display:none, visibility: hidden, or hidden via
+ // attribute, etc. Style might also not be calculated if the ancestors
+ // were invisible.
+ const ComputedStyle* style = entry->target()->GetComputedStyle();
+ if (!style || style->Visibility() != EVisibility::kVisible ||
+ style->Display() == EDisplay::kNone) {
+ // Check that style was null because it was not computed since the
+ // element was in an invisible subtree.
+ DCHECK(style || IsElementInInvisibleSubTree(*element));
+ image_element->LoadDeferredImage();
+ lazy_load_intersection_observer_->unobserve(element);
+ }
+ }
if (!entry->isIntersecting())
continue;
- Element* element = entry->target();
- if (auto* image_element = ToHTMLImageElementOrNull(element))
+ if (image_element)
image_element->LoadDeferredImage();
// Load the background image if the element has one deferred.
@@ -185,16 +219,13 @@ void LazyLoadImageObserver::OnLoadFinished(HTMLImageElement* image_element) {
visible_load_time_metrics.record_visibility_metrics = false;
visibility_metrics_observer_->unobserve(image_element);
- TimeDelta visible_load_delay;
+ base::TimeDelta visible_load_delay;
if (!visible_load_time_metrics.time_when_first_visible.is_null()) {
- visible_load_delay =
- CurrentTimeTicks() - visible_load_time_metrics.time_when_first_visible;
+ visible_load_delay = base::TimeTicks::Now() -
+ visible_load_time_metrics.time_when_first_visible;
}
- switch (image_element->GetDocument()
- .GetFrame()
- ->Client()
- ->GetEffectiveConnectionType()) {
+ switch (GetNetworkStateNotifier().EffectiveType()) {
case WebEffectiveConnectionType::kTypeSlow2G:
if (visible_load_time_metrics.is_initially_intersecting) {
UMA_HISTOGRAM_MEDIUM_TIMES(
@@ -266,7 +297,8 @@ void LazyLoadImageObserver::OnVisibilityChanged(
}
if (entry->isIntersecting()) {
DCHECK(visible_load_time_metrics.time_when_first_visible.is_null());
- visible_load_time_metrics.time_when_first_visible = CurrentTimeTicks();
+ visible_load_time_metrics.time_when_first_visible =
+ base::TimeTicks::Now();
if (visible_load_time_metrics.record_visibility_metrics &&
image_element->GetDocument().GetFrame()) {
@@ -282,17 +314,11 @@ void LazyLoadImageObserver::OnVisibilityChanged(
if (visible_load_time_metrics.is_initially_intersecting) {
UMA_HISTOGRAM_ENUMERATION(
"Blink.VisibleBeforeLoaded.LazyLoadImages.AboveTheFold",
- image_element->GetDocument()
- .GetFrame()
- ->Client()
- ->GetEffectiveConnectionType());
+ GetNetworkStateNotifier().EffectiveType());
} else {
UMA_HISTOGRAM_ENUMERATION(
"Blink.VisibleBeforeLoaded.LazyLoadImages.BelowTheFold",
- image_element->GetDocument()
- .GetFrame()
- ->Client()
- ->GetEffectiveConnectionType());
+ GetNetworkStateNotifier().EffectiveType());
}
}
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 1db9fd3ec5f..946b4821b75 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
@@ -36,7 +36,7 @@ class LazyLoadImageObserver final
bool record_visibility_metrics = false;
// Set when the image first becomes visible (i.e. appears in the viewport).
- TimeTicks time_when_first_visible;
+ base::TimeTicks time_when_first_visible;
};
LazyLoadImageObserver();
diff --git a/chromium/third_party/blink/renderer/core/html/lazy_load_image_observer_test.cc b/chromium/third_party/blink/renderer/core/html/lazy_load_image_observer_test.cc
index 74b7bbd18a9..096a501994e 100644
--- a/chromium/third_party/blink/renderer/core/html/lazy_load_image_observer_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/lazy_load_image_observer_test.cc
@@ -12,6 +12,7 @@
#include "third_party/blink/renderer/core/dom/pseudo_element.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/web_local_frame_impl.h"
#include "third_party/blink/renderer/core/html/html_element.h"
#include "third_party/blink/renderer/core/html/html_iframe_element.h"
#include "third_party/blink/renderer/core/html_names.h"
@@ -27,6 +28,7 @@
#include "third_party/blink/renderer/platform/loader/fetch/resource_request.h"
#include "third_party/blink/renderer/platform/network/http_header_map.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"
@@ -350,11 +352,11 @@ class ScopedDataSaverSetting {
explicit ScopedDataSaverSetting(bool is_data_saver_enabled)
: was_data_saver_previously_enabled_(
GetNetworkStateNotifier().SaveDataEnabled()) {
- GetNetworkStateNotifier().SetSaveDataEnabled(is_data_saver_enabled);
+ GetNetworkStateNotifier().SetSaveDataEnabledOverride(is_data_saver_enabled);
}
~ScopedDataSaverSetting() {
- GetNetworkStateNotifier().SetSaveDataEnabled(
+ GetNetworkStateNotifier().SetSaveDataEnabledOverride(
was_data_saver_previously_enabled_);
}
@@ -417,8 +419,10 @@ class LazyLoadImagesParamsTest : public SimTest,
kEnabledAutomaticMetadataFetchDisabled) {}
void SetUp() override {
- WebFrameClient().SetEffectiveConnectionTypeForTesting(
- std::get<WebEffectiveConnectionType>(GetParam()));
+ GetNetworkStateNotifier().SetNetworkConnectionInfoOverride(
+ true /*on_line*/, kWebConnectionTypeWifi,
+ std::get<WebEffectiveConnectionType>(GetParam()),
+ 1000 /*http_rtt_msec*/, 100 /*max_bandwidth_mbps*/);
SimTest::SetUp();
WebView().MainFrameWidget()->Resize(
@@ -828,17 +832,18 @@ class LazyLoadAutomaticImagesTest : public SimTest {
false) {}
void SetUp() override {
- WebFrameClient().SetEffectiveConnectionTypeForTesting(
- WebEffectiveConnectionType::kTypeUnknown);
-
+ GetNetworkStateNotifier().SetNetworkConnectionInfoOverride(
+ true /*on_line*/, kWebConnectionTypeWifi,
+ WebEffectiveConnectionType::kType4G, 1000 /*http_rtt_msec*/,
+ 100 /*max_bandwidth_mbps*/);
SimTest::SetUp();
WebView().MainFrameWidget()->Resize(
WebSize(kViewportWidth, kViewportHeight));
Settings& settings = WebView().GetPage()->GetSettings();
- settings.SetLazyImageLoadingDistanceThresholdPxUnknown(
+ settings.SetLazyImageLoadingDistanceThresholdPx4G(
kLoadingDistanceThreshold);
- settings.SetLazyFrameLoadingDistanceThresholdPxUnknown(
+ settings.SetLazyFrameLoadingDistanceThresholdPx4G(
kLoadingDistanceThreshold);
settings.SetLazyLoadEnabled(
RuntimeEnabledFeatures::LazyImageLoadingEnabled());
@@ -955,6 +960,8 @@ class LazyLoadAutomaticImagesTest : public SimTest {
scoped_restrict_automatic_lazy_image_loading_to_data_saver_for_test_;
ScopedLazyImageLoadingMetadataFetchForTest
scoped_lazy_image_loading_metadata_fetch_for_test_ = true;
+ ScopedLazyImageVisibleLoadTimeMetricsForTest
+ scoped_lazy_image_visible_load_time_metrics_for_test_ = true;
};
TEST_F(LazyLoadAutomaticImagesTest, AttributeChangedFromLazyToEager) {
@@ -1305,6 +1312,77 @@ TEST_F(LazyLoadAutomaticImagesTest, ImageInsideLazyLoadedFrame) {
EXPECT_TRUE(ConsoleMessages().Contains("unset onload"));
}
+TEST_F(LazyLoadAutomaticImagesTest, LazyLoadDisabledOnReload) {
+ ScopedLazyImageLoadingMetadataFetchForTest
+ scoped_lazy_image_loading_metadata_fetch_for_test = false;
+ String main_resource_html = String::Format(
+ R"HTML(
+ <body onload='console.log("main body onload");'>
+ <div style='height: %dpx;'></div>
+ <img src='https://example.com/image.png'
+ width='50px' height='50px'
+ onload='console.log("auto image onload");' />
+ <img src='https://example.com/image_lazy.png' loading='lazy'
+ width='50px' height='50px'
+ onload='console.log("auto image onload");' />
+ </body>)HTML",
+ LazyLoadAutomaticImagesTest::kViewportHeight +
+ LazyLoadAutomaticImagesTest::kLoadingDistanceThreshold + 100);
+
+ {
+ HistogramTester histogram_tester;
+ SimRequest main_resource("https://example.com/", "text/html");
+ LoadURL("https://example.com/");
+
+ main_resource.Complete(main_resource_html);
+ Compositor().BeginFrame();
+ test::RunPendingTasks();
+
+ // Scrolling down should trigger the fetch both the images, and record
+ // visible load time metrics.
+ SimSubresourceRequest auto_image("https://example.com/image.png",
+ "image/png");
+ SimSubresourceRequest lazy_image("https://example.com/image_lazy.png",
+ "image/png");
+ GetDocument().View()->LayoutViewport()->SetScrollOffset(
+ ScrollOffset(0, LazyLoadAutomaticImagesTest::kLoadingDistanceThreshold +
+ LazyLoadAutomaticImagesTest::kViewportHeight),
+ kProgrammaticScroll);
+ Compositor().BeginFrame();
+ auto_image.Complete(ReadTestImage());
+ lazy_image.Complete(ReadTestImage());
+ test::RunPendingTasks();
+ histogram_tester.ExpectTotalCount(
+ "Blink.VisibleLoadTime.LazyLoadImages.BelowTheFold.4G", 2);
+ }
+
+ // Reloading the page should load the image with loading=auto, but still defer
+ // the image with loading=lazy.
+ {
+ HistogramTester histogram_tester;
+ SimRequest main_resource("https://example.com/", "text/html");
+ SimSubresourceRequest auto_image("https://example.com/image.png",
+ "image/png");
+ MainFrame().StartReload(WebFrameLoadType::kReload);
+ main_resource.Complete(main_resource_html);
+ auto_image.Complete(ReadTestImage());
+
+ // Scrolling down should trigger the fetch deferred image, and record
+ // visible load time metrics for both images.
+ GetDocument().View()->LayoutViewport()->SetScrollOffset(
+ ScrollOffset(0, LazyLoadAutomaticImagesTest::kLoadingDistanceThreshold +
+ LazyLoadAutomaticImagesTest::kViewportHeight),
+ kProgrammaticScroll);
+ SimSubresourceRequest lazy_image("https://example.com/image_lazy.png",
+ "image/png");
+ Compositor().BeginFrame();
+ lazy_image.Complete(ReadTestImage());
+ test::RunPendingTasks();
+ histogram_tester.ExpectTotalCount(
+ "Blink.VisibleLoadTime.LazyLoadImages.BelowTheFold.4G", 2);
+ }
+}
+
} // namespace
} // namespace blink
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 187e960a2f7..30f002d1723 100644
--- a/chromium/third_party/blink/renderer/core/html/link_manifest.h
+++ b/chromium/third_party/blink/renderer/core/html/link_manifest.h
@@ -7,7 +7,7 @@
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/core/html/link_resource.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/link_rel_attribute.h b/chromium/third_party/blink/renderer/core/html/link_rel_attribute.h
index fdb6aeb8f48..709dceacc25 100644
--- a/chromium/third_party/blink/renderer/core/html/link_rel_attribute.h
+++ b/chromium/third_party/blink/renderer/core/html/link_rel_attribute.h
@@ -34,7 +34,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/dom/icon_url.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/link_rel_attribute_test.cc b/chromium/third_party/blink/renderer/core/html/link_rel_attribute_test.cc
index a62fca01834..acb04e6a58d 100644
--- a/chromium/third_party/blink/renderer/core/html/link_rel_attribute_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/link_rel_attribute_test.cc
@@ -31,7 +31,6 @@
#include "third_party/blink/renderer/core/html/link_rel_attribute.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
namespace blink {
@@ -45,7 +44,7 @@ static inline void TestLinkRelAttribute(const String& value,
bool is_import = false,
bool is_preconnect = false,
bool is_canonical = false) {
- SCOPED_TRACE(value.Utf8().data());
+ SCOPED_TRACE(value.Utf8());
LinkRelAttribute link_rel_attribute(value);
ASSERT_EQ(is_style_sheet, link_rel_attribute.IsStyleSheet());
ASSERT_EQ(icon_type, link_rel_attribute.GetIconType());
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 e9be1accc17..b802bd64a93 100644
--- a/chromium/third_party/blink/renderer/core/html/link_style.cc
+++ b/chromium/third_party/blink/renderer/core/html/link_style.cc
@@ -4,7 +4,7 @@
#include "third_party/blink/renderer/core/html/link_style.h"
-#include "services/network/public/mojom/referrer_policy.mojom-shared.h"
+#include "services/network/public/mojom/referrer_policy.mojom-blink.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"
@@ -18,7 +18,7 @@
#include "third_party/blink/renderer/core/loader/resource/css_style_sheet_resource.h"
#include "third_party/blink/renderer/core/loader/subresource_integrity_helper.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h"
#include "third_party/blink/renderer/platform/loader/subresource_integrity.h"
#include "third_party/blink/renderer/platform/network/mime/content_type.h"
@@ -69,9 +69,10 @@ void LinkStyle::NotifyFinished(Resource* resource) {
CSSStyleSheetResource* cached_style_sheet = ToCSSStyleSheetResource(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(kIntegrityAttr).IsEmpty() &&
- !cached_style_sheet->IntegrityMetadata().IsEmpty()) {
+ if ((!cached_style_sheet->ErrorOccurred() &&
+ !owner_->FastGetAttribute(kIntegrityAttr).IsEmpty() &&
+ !cached_style_sheet->IntegrityMetadata().IsEmpty()) ||
+ resource->IsLinkPreload()) {
ResourceIntegrityDisposition disposition =
cached_style_sheet->IntegrityDisposition();
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 f6920652706..74ea6a159e4 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
@@ -12,25 +12,23 @@
#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/settings.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/media/autoplay_policy.h"
#include "third_party/blink/renderer/core/html/media/html_media_element.h"
#include "third_party/blink/renderer/core/intersection_observer/intersection_observer.h"
#include "third_party/blink/renderer/core/intersection_observer/intersection_observer_entry.h"
#include "third_party/blink/renderer/core/page/page.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/network/network_state_notifier.h"
namespace blink {
namespace {
-constexpr TimeDelta kMaxOffscreenDurationUma = TimeDelta::FromHours(1);
+constexpr base::TimeDelta kMaxOffscreenDurationUma =
+ base::TimeDelta::FromHours(1);
constexpr int32_t kOffscreenDurationUmaBucketCount = 50;
-constexpr TimeDelta kMaxWaitTimeUma = TimeDelta::FromSeconds(30);
-constexpr int32_t kWaitTimeBucketCount = 50;
-
// Returns a int64_t with the following structure:
// 0b0001 set if there is a user gesture on the stack.
// 0b0010 set if there was a user gesture on the page.
@@ -58,20 +56,11 @@ AutoplayUmaHelper::AutoplayUmaHelper(HTMLMediaElement* element)
muted_video_play_method_intersection_observer_(nullptr),
is_visible_(false),
muted_video_offscreen_duration_intersection_observer_(nullptr) {
- element->addEventListener(event_type_names::kLoadstart, this, false);
}
AutoplayUmaHelper::~AutoplayUmaHelper() = default;
-void AutoplayUmaHelper::OnLoadStarted() {
- if (element_->GetLoadType() == WebMediaPlayer::kLoadTypeURL)
- load_start_time_ = CurrentTimeTicks();
-}
-
void AutoplayUmaHelper::OnAutoplayInitiated(AutoplaySource source) {
- base::Optional<TimeDelta> autoplay_wait_time;
- if (!load_start_time_.is_null())
- autoplay_wait_time = CurrentTimeTicks() - load_start_time_;
DEFINE_STATIC_LOCAL(EnumerationHistogram, video_histogram,
("Media.Video.Autoplay",
static_cast<int>(AutoplaySource::kNumberOfUmaSources)));
@@ -86,7 +75,7 @@ void AutoplayUmaHelper::OnAutoplayInitiated(AutoplaySource source) {
("Media.Video.Autoplay.Muted.Blocked", kAutoplayBlockedReasonMax));
// Autoplay already initiated
- if (sources_.count(source))
+ if (sources_.Contains(source))
return;
sources_.insert(source);
@@ -96,34 +85,8 @@ void AutoplayUmaHelper::OnAutoplayInitiated(AutoplaySource source) {
video_histogram.Count(static_cast<int>(source));
if (element_->muted())
muted_video_histogram.Count(static_cast<int>(source));
- if (autoplay_wait_time.has_value()) {
- if (source == AutoplaySource::kAttribute) {
- UMA_HISTOGRAM_CUSTOM_TIMES("Media.Video.Autoplay.Attribute.WaitTime",
- *autoplay_wait_time,
- TimeDelta::FromMilliseconds(1),
- kMaxWaitTimeUma, kWaitTimeBucketCount);
- } else if (source == AutoplaySource::kMethod) {
- UMA_HISTOGRAM_CUSTOM_TIMES("Media.Video.Autoplay.PlayMethod.WaitTime",
- *autoplay_wait_time,
- TimeDelta::FromMilliseconds(1),
- kMaxWaitTimeUma, kWaitTimeBucketCount);
- }
- }
} else {
audio_histogram.Count(static_cast<int>(source));
- if (autoplay_wait_time.has_value()) {
- if (source == AutoplaySource::kAttribute) {
- UMA_HISTOGRAM_CUSTOM_TIMES("Media.Audio.Autoplay.Attribute.WaitTime",
- *autoplay_wait_time,
- TimeDelta::FromMilliseconds(1),
- kMaxWaitTimeUma, kWaitTimeBucketCount);
- } else if (source == AutoplaySource::kMethod) {
- UMA_HISTOGRAM_CUSTOM_TIMES("Media.Audio.Autoplay.PlayMethod.WaitTime",
- *autoplay_wait_time,
- TimeDelta::FromMilliseconds(1),
- kMaxWaitTimeUma, kWaitTimeBucketCount);
- }
- }
}
// Record dual source.
@@ -206,7 +169,7 @@ void AutoplayUmaHelper::RecordAutoplayUnmuteStatus(
if (sources_.size() ==
static_cast<size_t>(AutoplaySource::kNumberOfSources)) {
source = static_cast<int>(AutoplaySource::kDualSource);
- } else if (sources_.count(AutoplaySource::kMethod)) {
+ } else if (sources_.Contains(AutoplaySource::kMethod)) {
source = static_cast<int>(AutoplaySource::kAttribute);
}
@@ -252,9 +215,9 @@ void AutoplayUmaHelper::OnIntersectionChangedForMutedVideoOffscreenDuration(
if (is_visible) {
muted_video_autoplay_offscreen_duration_ +=
- CurrentTimeTicks() - muted_video_autoplay_offscreen_start_time_;
+ base::TimeTicks::Now() - muted_video_autoplay_offscreen_start_time_;
} else {
- muted_video_autoplay_offscreen_start_time_ = CurrentTimeTicks();
+ muted_video_autoplay_offscreen_start_time_ = base::TimeTicks::Now();
}
is_visible_ = is_visible;
@@ -262,9 +225,7 @@ void AutoplayUmaHelper::OnIntersectionChangedForMutedVideoOffscreenDuration(
void AutoplayUmaHelper::Invoke(ExecutionContext* execution_context,
Event* event) {
- if (event->type() == event_type_names::kLoadstart)
- OnLoadStarted();
- else if (event->type() == event_type_names::kPlaying)
+ if (event->type() == event_type_names::kPlaying)
HandlePlayingEvent();
else if (event->type() == event_type_names::kPause)
HandlePauseEvent();
@@ -293,7 +254,7 @@ void AutoplayUmaHelper::HandleContextDestroyed() {
}
void AutoplayUmaHelper::MaybeStartRecordingMutedVideoPlayMethodBecomeVisible() {
- if (!sources_.count(AutoplaySource::kMethod) ||
+ if (!sources_.Contains(AutoplaySource::kMethod) ||
!element_->IsHTMLVideoElement() || !element_->muted())
return;
@@ -323,11 +284,11 @@ void AutoplayUmaHelper::MaybeStopRecordingMutedVideoPlayMethodBecomeVisible(
void AutoplayUmaHelper::MaybeStartRecordingMutedVideoOffscreenDuration() {
if (!element_->IsHTMLVideoElement() || !element_->muted() ||
- !sources_.count(AutoplaySource::kMethod))
+ !sources_.Contains(AutoplaySource::kMethod))
return;
// Start recording muted video playing offscreen duration.
- muted_video_autoplay_offscreen_start_time_ = CurrentTimeTicks();
+ muted_video_autoplay_offscreen_start_time_ = base::TimeTicks::Now();
is_visible_ = false;
muted_video_offscreen_duration_intersection_observer_ =
IntersectionObserver::Create(
@@ -348,19 +309,20 @@ void AutoplayUmaHelper::MaybeStopRecordingMutedVideoOffscreenDuration() {
if (!is_visible_) {
muted_video_autoplay_offscreen_duration_ +=
- CurrentTimeTicks() - muted_video_autoplay_offscreen_start_time_;
+ base::TimeTicks::Now() - muted_video_autoplay_offscreen_start_time_;
}
- DCHECK(sources_.count(AutoplaySource::kMethod));
+ DCHECK(sources_.Contains(AutoplaySource::kMethod));
UMA_HISTOGRAM_CUSTOM_TIMES(
"Media.Video.Autoplay.Muted.PlayMethod.OffscreenDuration",
- muted_video_autoplay_offscreen_duration_, TimeDelta::FromMilliseconds(1),
- kMaxOffscreenDurationUma, kOffscreenDurationUmaBucketCount);
+ muted_video_autoplay_offscreen_duration_,
+ base::TimeDelta::FromMilliseconds(1), kMaxOffscreenDurationUma,
+ kOffscreenDurationUmaBucketCount);
muted_video_offscreen_duration_intersection_observer_->disconnect();
muted_video_offscreen_duration_intersection_observer_ = nullptr;
- muted_video_autoplay_offscreen_duration_ = TimeDelta();
+ muted_video_autoplay_offscreen_duration_ = base::TimeDelta();
MaybeUnregisterMediaElementPauseListener();
MaybeUnregisterContextDestroyedObserver();
}
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 fdce3cc81f1..ab96edd7542 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
@@ -12,8 +12,6 @@
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
-#include <set>
-
namespace blink {
// These values are used for histograms. Do not reorder.
@@ -70,7 +68,7 @@ class CORE_EXPORT AutoplayUmaHelper : public NativeEventListener,
bool IsVisible() const { return is_visible_; }
- bool HasSource() const { return !sources_.empty(); }
+ bool HasSource() const { return !sources_.IsEmpty(); }
void Invoke(ExecutionContext*, Event*) override;
@@ -103,7 +101,7 @@ class CORE_EXPORT AutoplayUmaHelper : public NativeEventListener,
bool ShouldListenToContextDestroyed() const;
// The autoplay sources.
- std::set<AutoplaySource> sources_;
+ HashSet<AutoplaySource> sources_;
// The media element this UMA helper is attached to. |element| owns |this|.
Member<HTMLMediaElement> element_;
@@ -120,10 +118,10 @@ class CORE_EXPORT AutoplayUmaHelper : public NativeEventListener,
// The recording stops whenever the playback pauses or the page is unloaded.
// The starting time of autoplaying muted video.
- TimeTicks muted_video_autoplay_offscreen_start_time_;
+ base::TimeTicks muted_video_autoplay_offscreen_start_time_;
// The duration an autoplaying muted video has been in offscreen.
- TimeDelta muted_video_autoplay_offscreen_duration_;
+ base::TimeDelta muted_video_autoplay_offscreen_duration_;
// Whether an autoplaying muted video is visible.
bool is_visible_;
@@ -133,8 +131,6 @@ class CORE_EXPORT AutoplayUmaHelper : public NativeEventListener,
// for recording as long as this observer is non-null.
Member<IntersectionObserver>
muted_video_offscreen_duration_intersection_observer_;
-
- TimeTicks load_start_time_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/media/html_audio_element.idl b/chromium/third_party/blink/renderer/core/html/media/html_audio_element.idl
index f2eb3fa62d3..698f97b673a 100644
--- a/chromium/third_party/blink/renderer/core/html/media/html_audio_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/media/html_audio_element.idl
@@ -26,6 +26,7 @@
// https://html.spec.whatwg.org/C/#the-audio-element
[
+ Exposed=Window,
HTMLConstructor,
NamedConstructor=Audio(optional DOMString src),
ConstructorCallWith=Document
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 684c38f4fa3..637245eb50f 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
@@ -32,6 +32,7 @@
#include "base/auto_reset.h"
#include "base/debug/crash_logging.h"
#include "base/memory/ptr_util.h"
+#include "base/time/time.h"
#include "media/base/logging_override_if_enabled.h"
#include "third_party/blink/public/platform/modules/remoteplayback/web_remote_playback_client.h"
#include "third_party/blink/public/platform/platform.h"
@@ -61,7 +62,6 @@
#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/fullscreen/fullscreen.h"
#include "third_party/blink/renderer/core/html/html_source_element.h"
#include "third_party/blink/renderer/core/html/media/autoplay_policy.h"
@@ -97,7 +97,8 @@
#include "third_party/blink/renderer/platform/bindings/microtask.h"
#include "third_party/blink/renderer/platform/graphics/graphics_layer.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/mediastream/media_stream_descriptor.h"
#include "third_party/blink/renderer/platform/network/mime/content_type.h"
#include "third_party/blink/renderer/platform/network/mime/mime_type_from_url.h"
@@ -107,8 +108,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/math_extras.h"
-#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
-#include "third_party/blink/renderer/platform/wtf/time.h"
#ifndef LOG_MEDIA_EVENTS
// Default to not logging events because so many are generated they can
@@ -163,6 +162,9 @@ enum class PlayPromiseRejectReason {
kCount,
};
+static const base::TimeDelta kStalledNotificationInterval =
+ base::TimeDelta::FromSeconds(3);
+
// Limits the range of media playback rate.
const double kMinRate = 0.0625;
const double kMaxRate = 16.0;
@@ -385,7 +387,7 @@ MIMETypeRegistry::SupportsType HTMLMediaElement::GetSupportsType(
base::debug::AllocateCrashKeyString("media_content_type",
base::debug::CrashKeySize::Size256);
base::debug::ScopedCrashKeyString scoped_crash_key(
- content_type_crash_key, content_type.Raw().Utf8().data());
+ content_type_crash_key, content_type.Raw().Utf8().c_str());
String type = content_type.GetType().DeprecatedLower();
// The codecs string is not lower-cased because MP4 values are case sensitive
@@ -479,7 +481,6 @@ HTMLMediaElement::HTMLMediaElement(const QualifiedName& tag_name,
ready_state_maximum_(kHaveNothing),
volume_(1.0f),
last_seek_time_(0),
- previous_progress_time_(std::numeric_limits<double>::max()),
duration_(std::numeric_limits<double>::quiet_NaN()),
last_time_update_event_media_time_(
std::numeric_limits<double>::quiet_NaN()),
@@ -713,7 +714,7 @@ void HTMLMediaElement::DidNotifySubtreeInsertionsToDocument() {
void HTMLMediaElement::RemovedFrom(ContainerNode& insertion_point) {
DVLOG(3) << "removedFrom(" << (void*)this << ", " << insertion_point << ")";
- removed_from_document_timer_.StartOneShot(TimeDelta(), FROM_HERE);
+ removed_from_document_timer_.StartOneShot(base::TimeDelta(), FROM_HERE);
HTMLElement::RemovedFrom(insertion_point);
}
@@ -736,14 +737,14 @@ void HTMLMediaElement::ScheduleTextTrackResourceLoad() {
pending_action_flags_ |= kLoadTextTrackResource;
if (!load_timer_.IsActive())
- load_timer_.StartOneShot(TimeDelta(), FROM_HERE);
+ load_timer_.StartOneShot(base::TimeDelta(), FROM_HERE);
}
void HTMLMediaElement::ScheduleNextSourceChild() {
// Schedule the timer to try the next <source> element WITHOUT resetting state
// ala invokeLoadAlgorithm.
pending_action_flags_ |= kLoadMediaResource;
- load_timer_.StartOneShot(TimeDelta(), FROM_HERE);
+ load_timer_.StartOneShot(base::TimeDelta(), FROM_HERE);
}
void HTMLMediaElement::ScheduleEvent(const AtomicString& event_name) {
@@ -1329,7 +1330,7 @@ void HTMLMediaElement::DeferLoad() {
ChangeNetworkStateFromLoadingToIdle();
// 3. Queue a task to set the element's delaying-the-load-event
// flag to false. This stops delaying the load event.
- deferred_load_timer_.StartOneShot(TimeDelta(), FROM_HERE);
+ deferred_load_timer_.StartOneShot(base::TimeDelta(), FROM_HERE);
// 4. Wait for the task to be run.
deferred_load_state_ = kWaitingForStopDelayingLoadEventTask;
// Continued in executeDeferredLoad().
@@ -1503,9 +1504,9 @@ void HTMLMediaElement::StartProgressEventTimer() {
if (progress_event_timer_.IsActive())
return;
- previous_progress_time_ = WTF::CurrentTime();
+ previous_progress_time_ = base::ElapsedTimer();
// 350ms is not magic, it is in the spec!
- progress_event_timer_.StartRepeating(TimeDelta::FromMilliseconds(350),
+ progress_event_timer_.StartRepeating(base::TimeDelta::FromMilliseconds(350),
FROM_HERE);
}
@@ -1911,16 +1912,18 @@ void HTMLMediaElement::ProgressEventTimerFired(TimerBase*) {
if (MediaShouldBeOpaque())
return;
- double time = WTF::CurrentTime();
- double timedelta = time - previous_progress_time_;
+ DCHECK(previous_progress_time_);
if (GetWebMediaPlayer() && GetWebMediaPlayer()->DidLoadingProgress()) {
ScheduleEvent(event_type_names::kProgress);
- previous_progress_time_ = time;
+ previous_progress_time_ = base::ElapsedTimer();
sent_stalled_event_ = false;
if (GetLayoutObject())
GetLayoutObject()->UpdateFromElement();
- } else if (!media_source_ && timedelta > 3.0 && !sent_stalled_event_) {
+ } else if (!media_source_ &&
+ previous_progress_time_->Elapsed() >
+ kStalledNotificationInterval &&
+ !sent_stalled_event_) {
// Note the !media_source_ condition above. The 'stalled' event is not
// fired when using MSE. MSE's resource is considered 'local' (we don't
// manage the donwload - the app does), so the HTML5 spec text around
@@ -2051,13 +2054,13 @@ void HTMLMediaElement::Seek(double time) {
// the new playback position. ... If there are no ranges given in the seekable
// attribute then set the seeking IDL attribute to false and abort these
// steps.
- TimeRanges* seekable_ranges = seekable();
+ WebTimeRanges seekable_ranges = SeekableInternal();
- if (!seekable_ranges->length()) {
+ if (seekable_ranges.empty()) {
seeking_ = false;
return;
}
- time = seekable_ranges->Nearest(time, now);
+ time = seekable_ranges.Nearest(time, now);
if (playing_ && last_seek_time_ < now)
AddPlayedRange(last_seek_time_, now);
@@ -2114,9 +2117,9 @@ bool HTMLMediaElement::seeking() const {
// corresponds to the start time of the first range in the seekable attribute’s
// TimeRanges object, if any, or the current playback position otherwise.
double HTMLMediaElement::EarliestPossiblePosition() const {
- TimeRanges* seekable_ranges = seekable();
- if (seekable_ranges && seekable_ranges->length() > 0)
- return seekable_ranges->start(0, ASSERT_NO_EXCEPTION);
+ WebTimeRanges seekable_ranges = SeekableInternal();
+ if (!seekable_ranges.empty())
+ return seekable_ranges.front().start;
return CurrentPlaybackPosition();
}
@@ -2586,7 +2589,14 @@ void HTMLMediaElement::setVolume(double vol, ExceptionState& exception_state) {
if (volume_ == vol)
return;
- if (vol < 0.0f || vol > 1.0f) {
+ if (RuntimeEnabledFeatures::MediaElementVolumeGreaterThanOneEnabled()) {
+ if (vol < 0.0f) {
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kIndexSizeError,
+ ExceptionMessages::IndexExceedsMinimumBound("volume", vol, 0.0));
+ return;
+ }
+ } else if (vol < 0.0f || vol > 1.0f) {
exception_state.ThrowDOMException(
DOMExceptionCode::kIndexSizeError,
ExceptionMessages::IndexOutsideRange(
@@ -2656,14 +2666,14 @@ double HTMLMediaElement::EffectiveMediaVolume() const {
// The spec says to fire periodic timeupdate events (those sent while playing)
// every "15 to 250ms", we choose the slowest frequency
-static const TimeDelta kMaxTimeupdateEventFrequency =
- TimeDelta::FromMilliseconds(250);
+static const base::TimeDelta kMaxTimeupdateEventFrequency =
+ base::TimeDelta::FromMilliseconds(250);
void HTMLMediaElement::StartPlaybackProgressTimer() {
if (playback_progress_timer_.IsActive())
return;
- previous_progress_time_ = WTF::CurrentTime();
+ previous_progress_time_ = base::ElapsedTimer();
playback_progress_timer_.StartRepeating(kMaxTimeupdateEventFrequency,
FROM_HERE);
}
@@ -2736,7 +2746,7 @@ void HTMLMediaElement::AudioTrackChanged(AudioTrack* track) {
media_source_->OnTrackChanged(track);
if (!audio_tracks_timer_.IsActive())
- audio_tracks_timer_.StartOneShot(TimeDelta(), FROM_HERE);
+ audio_tracks_timer_.StartOneShot(base::TimeDelta(), FROM_HERE);
}
void HTMLMediaElement::AudioTracksTimerFired(TimerBase*) {
@@ -3340,14 +3350,18 @@ void HTMLMediaElement::SizeChanged() {
GetLayoutObject()->UpdateFromElement();
}
-TimeRanges* HTMLMediaElement::buffered() const {
+WebTimeRanges HTMLMediaElement::BufferedInternal() const {
if (media_source_)
- return media_source_->Buffered();
+ return media_source_->BufferedInternal();
if (!GetWebMediaPlayer())
- return MakeGarbageCollected<TimeRanges>();
+ return {};
+
+ return GetWebMediaPlayer()->Buffered();
+}
- return MakeGarbageCollected<TimeRanges>(GetWebMediaPlayer()->Buffered());
+TimeRanges* HTMLMediaElement::buffered() const {
+ return MakeGarbageCollected<TimeRanges>(BufferedInternal());
}
TimeRanges* HTMLMediaElement::played() {
@@ -3363,14 +3377,18 @@ TimeRanges* HTMLMediaElement::played() {
return played_time_ranges_->Copy();
}
-TimeRanges* HTMLMediaElement::seekable() const {
+WebTimeRanges HTMLMediaElement::SeekableInternal() const {
if (!GetWebMediaPlayer())
- return MakeGarbageCollected<TimeRanges>();
+ return {};
if (media_source_)
- return media_source_->Seekable();
+ return media_source_->SeekableInternal();
- return MakeGarbageCollected<TimeRanges>(GetWebMediaPlayer()->Seekable());
+ return GetWebMediaPlayer()->Seekable();
+}
+
+TimeRanges* HTMLMediaElement::seekable() const {
+ return MakeGarbageCollected<TimeRanges>(SeekableInternal());
}
bool HTMLMediaElement::PotentiallyPlaying() const {
@@ -3415,8 +3433,8 @@ bool HTMLMediaElement::EndedPlayback(LoopCondition loop_condition) const {
bool HTMLMediaElement::StoppedDueToErrors() const {
if (ready_state_ >= kHaveMetadata && error_) {
- TimeRanges* seekable_ranges = seekable();
- if (!seekable_ranges->Contain(currentTime()))
+ WebTimeRanges seekable_ranges = SeekableInternal();
+ if (!seekable_ranges.Contain(currentTime()))
return true;
}
@@ -4103,13 +4121,13 @@ void HTMLMediaElement::DefaultEventHandler(Event& event) {
}
void HTMLMediaElement::AudioSourceProviderImpl::Wrap(
- WebAudioSourceProvider* provider) {
+ scoped_refptr<WebAudioSourceProviderImpl> provider) {
MutexLocker locker(provide_input_lock);
if (web_audio_source_provider_ && provider != web_audio_source_provider_)
web_audio_source_provider_->SetClient(nullptr);
- web_audio_source_provider_ = provider;
+ web_audio_source_provider_ = std::move(provider);
if (web_audio_source_provider_)
web_audio_source_provider_->SetClient(client_.Get());
}
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 f4e4a0e757a..ea0853391dd 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
@@ -32,6 +32,7 @@
#include "base/optional.h"
#include "third_party/blink/public/platform/web_audio_source_provider_client.h"
#include "third_party/blink/public/platform/web_media_player_client.h"
+#include "third_party/blink/public/platform/webaudiosourceprovider_impl.h"
#include "third_party/blink/renderer/bindings/core/v8/active_script_wrappable.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
#include "third_party/blink/renderer/core/core_export.h"
@@ -77,7 +78,6 @@ class TextTrackList;
class TimeRanges;
class VideoTrack;
class VideoTrackList;
-class WebAudioSourceProvider;
class WebInbandTextTrack;
class WebRemotePlaybackClient;
@@ -160,6 +160,7 @@ class CORE_EXPORT HTMLMediaElement
String EffectivePreload() const;
WebMediaPlayer::Preload EffectivePreloadType() const;
+ WebTimeRanges BufferedInternal() const;
TimeRanges* buffered() const;
void load();
String canPlayType(const String& mime_type) const;
@@ -186,6 +187,7 @@ class CORE_EXPORT HTMLMediaElement
void setPlaybackRate(double, ExceptionState& = ASSERT_NO_EXCEPTION);
void UpdatePlaybackRate();
TimeRanges* played();
+ WebTimeRanges SeekableInternal() const;
TimeRanges* seekable() const;
bool ended() const;
bool Autoplay() const;
@@ -577,7 +579,7 @@ class CORE_EXPORT HTMLMediaElement
double volume_;
double last_seek_time_;
- double previous_progress_time_;
+ base::Optional<base::ElapsedTimer> previous_progress_time_;
// Cached duration to suppress duplicate events if duration unchanged.
double duration_;
@@ -707,12 +709,11 @@ class CORE_EXPORT HTMLMediaElement
DISALLOW_NEW();
public:
- AudioSourceProviderImpl() : web_audio_source_provider_(nullptr) {}
-
+ AudioSourceProviderImpl() = default;
~AudioSourceProviderImpl() override = default;
// Wraps the given WebAudioSourceProvider.
- void Wrap(WebAudioSourceProvider*);
+ void Wrap(scoped_refptr<WebAudioSourceProviderImpl>);
// AudioSourceProvider
void SetClient(AudioSourceProviderClient*) override;
@@ -721,7 +722,7 @@ class CORE_EXPORT HTMLMediaElement
void Trace(Visitor*);
private:
- WebAudioSourceProvider* web_audio_source_provider_;
+ scoped_refptr<WebAudioSourceProviderImpl> web_audio_source_provider_;
Member<AudioClientImpl> client_;
Mutex provide_input_lock;
};
diff --git a/chromium/third_party/blink/renderer/core/html/media/html_media_element.idl b/chromium/third_party/blink/renderer/core/html/media/html_media_element.idl
index f0e61660b2f..af5987856d7 100644
--- a/chromium/third_party/blink/renderer/core/html/media/html_media_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/media/html_media_element.idl
@@ -26,7 +26,9 @@
// https://html.spec.whatwg.org/C/#media-elements
enum CanPlayTypeResult { "" /* empty string */, "maybe", "probably" };
+
[
+ Exposed=Window,
ActiveScriptWrappable
] interface HTMLMediaElement : HTMLElement {
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 6d0c8f6e6a3..61b7cdeb8a7 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
@@ -22,7 +22,6 @@
#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/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/wtf/time.h"
@@ -212,7 +211,7 @@ TEST_F(HTMLMediaElementEventListenersTest,
Persistent<MediaCustomControlsFullscreenDetector> detector =
FullscreenDetector();
- std::vector<blink::WebFullscreenVideoStatus> observed_results;
+ Vector<blink::WebFullscreenVideoStatus> observed_results;
ON_CALL(*WebMediaPlayer(), SetIsEffectivelyFullscreen(_))
.WillByDefault(testing::Invoke(
@@ -244,20 +243,17 @@ class HTMLMediaElementWithMockSchedulerTest
: public HTMLMediaElementEventListenersTest {
protected:
void SetUp() override {
+ EnablePlatform();
// We want total control over when to advance the clock. This also allows
- // us to call platform_->RunUntilIdle() to run all pending tasks without
+ // us to call platform()->RunUntilIdle() to run all pending tasks without
// fear of looping forever.
- platform_->SetAutoAdvanceNowToPendingTasks(false);
+ platform()->SetAutoAdvanceNowToPendingTasks(false);
// DocumentParserTiming has DCHECKS to make sure time > 0.0.
- platform_->AdvanceClockSeconds(1);
+ platform()->AdvanceClockSeconds(1);
HTMLMediaElementEventListenersTest::SetUp();
}
-
- // MockSchdulere to control scheduling of task_timer_;
- ScopedTestingPlatformSupport<TestingPlatformSupportWithMockScheduler>
- platform_;
};
TEST_F(HTMLMediaElementWithMockSchedulerTest, OneTimeupdatePerSeek) {
@@ -267,7 +263,7 @@ TEST_F(HTMLMediaElementWithMockSchedulerTest, OneTimeupdatePerSeek) {
// Set a src to trigger WebMediaPlayer creation.
Video()->SetSrc("http://example.com");
- platform_->RunUntilIdle();
+ platform()->RunUntilIdle();
ASSERT_NE(WebMediaPlayer(), nullptr);
auto* timeupdate_handler = MakeGarbageCollected<MockEventListener>();
@@ -285,17 +281,17 @@ 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, Invoke(_, _)).Times(4);
- platform_->RunForPeriodSeconds(1);
+ platform()->RunForPeriodSeconds(1);
// If media playback time is fixed, periodic timeupdate's should not continue
// to fire.
WebMediaPlayer()->SetAutoAdvanceCurrentTime(false);
EXPECT_CALL(*timeupdate_handler, Invoke(_, _)).Times(0);
- platform_->RunForPeriodSeconds(1);
+ platform()->RunForPeriodSeconds(1);
EXPECT_CALL(*timeupdate_handler, Invoke(_, _)).Times(1);
Video()->pause();
- platform_->RunUntilIdle();
+ platform()->RunUntilIdle();
// Seek to some time in the past. A completed seek while paused should trigger
// a *single* timeupdate.
@@ -307,7 +303,7 @@ TEST_F(HTMLMediaElementWithMockSchedulerTest, OneTimeupdatePerSeek) {
WebMediaPlayer()->FinishSeek();
// Give the scheduled timeupdate a chance to fire.
- platform_->RunUntilIdle();
+ platform()->RunUntilIdle();
}
TEST_F(HTMLMediaElementWithMockSchedulerTest, PeriodicTimeupdateAfterSeek) {
@@ -317,7 +313,7 @@ TEST_F(HTMLMediaElementWithMockSchedulerTest, PeriodicTimeupdateAfterSeek) {
// Set a src to trigger WebMediaPlayer creation.
Video()->SetSrc("http://example.com");
- platform_->RunUntilIdle();
+ platform()->RunUntilIdle();
EXPECT_NE(WebMediaPlayer(), nullptr);
auto* timeupdate_handler = MakeGarbageCollected<MockEventListener>();
@@ -335,15 +331,15 @@ TEST_F(HTMLMediaElementWithMockSchedulerTest, PeriodicTimeupdateAfterSeek) {
// Advance a full periodic timeupdate interval (250 ms) and expect a single
// timeupdate.
EXPECT_CALL(*timeupdate_handler, Invoke(_, _)).Times(1);
- platform_->RunForPeriodSeconds(.250);
+ platform()->RunForPeriodSeconds(.250);
// The event is scheduled, but needs one more scheduler cycle to fire.
- platform_->RunUntilIdle();
+ platform()->RunUntilIdle();
// Now advance 125 ms to reach the middle of the periodic timeupdate interval.
// no additional timeupdate should trigger.
EXPECT_CALL(*timeupdate_handler, Invoke(_, _)).Times(0);
- platform_->RunForPeriodSeconds(.125);
- platform_->RunUntilIdle();
+ 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.
@@ -355,7 +351,7 @@ TEST_F(HTMLMediaElementWithMockSchedulerTest, PeriodicTimeupdateAfterSeek) {
// Expect another timeupdate after FinishSeek due to
// seeking -> begin scrubbing -> pause -> timeupdate.
EXPECT_CALL(*timeupdate_handler, Invoke(_, _)).Times(1);
- platform_->RunUntilIdle();
+ platform()->RunUntilIdle();
// Advancing the remainder of the last periodic timeupdate interval should be
// insufficient to trigger a new timeupdate event because the seek's
@@ -363,21 +359,21 @@ TEST_F(HTMLMediaElementWithMockSchedulerTest, PeriodicTimeupdateAfterSeek) {
// exactly every 250ms from the last timeupdate, and the seek's timeupdate
// should reset that 250ms ms countdown.
EXPECT_CALL(*timeupdate_handler, Invoke(_, _)).Times(0);
- platform_->RunForPeriodSeconds(.125);
- platform_->RunUntilIdle();
+ 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, Invoke(_, _)).Times(1);
- platform_->RunForPeriodSeconds(.125);
- platform_->RunUntilIdle();
+ 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, Invoke(_, _)).Times(1);
- platform_->RunForPeriodSeconds(.250);
- platform_->RunUntilIdle();
+ platform()->RunForPeriodSeconds(.250);
+ platform()->RunUntilIdle();
}
} // namespace blink
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 f38e4f1565a..5e161688368 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
@@ -4,6 +4,7 @@
#include "third_party/blink/renderer/core/html/media/html_media_element.h"
+#include "base/test/gtest_util.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/mojom/autoplay/autoplay.mojom-blink.h"
@@ -12,6 +13,7 @@
#include "third_party/blink/renderer/core/html/media/html_audio_element.h"
#include "third_party/blink/renderer/core/html/media/html_video_element.h"
#include "third_party/blink/renderer/core/html/media/media_error.h"
+#include "third_party/blink/renderer/core/html/time_ranges.h"
#include "third_party/blink/renderer/core/html/track/audio_track_list.h"
#include "third_party/blink/renderer/core/html/track/video_track_list.h"
#include "third_party/blink/renderer/core/loader/empty_clients.h"
@@ -19,7 +21,9 @@
#include "third_party/blink/renderer/platform/heap/heap.h"
#include "third_party/blink/renderer/platform/network/network_state_notifier.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/wtf/vector.h"
using ::testing::AnyNumber;
using ::testing::Return;
@@ -89,8 +93,7 @@ class HTMLMediaElementTest : public testing::TestWithParam<MediaTestParam> {
dummy_page_holder_ = std::make_unique<DummyPageHolder>(
IntSize(), nullptr,
MakeGarbageCollected<WebMediaStubLocalFrameClient>(
- std::move(mock_media_player)),
- nullptr);
+ std::move(mock_media_player)));
if (GetParam() == MediaTestParam::kAudio) {
media_ = MakeGarbageCollected<HTMLAudioElement>(
@@ -315,7 +318,7 @@ TEST_P(HTMLMediaElementTest, AutoplayInitiated_DocumentActivation_Low_Gesture) {
// - Policy: DocumentUserActivation (aka. unified autoplay)
// - MEI: low;
// - Frame received user gesture.
- RuntimeEnabledFeatures::SetMediaEngagementBypassAutoplayPoliciesEnabled(true);
+ ScopedMediaEngagementBypassAutoplayPoliciesForTest scoped_feature(true);
Media()->GetDocument().GetSettings()->SetAutoplayPolicy(
AutoplayPolicy::Type::kDocumentUserActivationRequired);
LocalFrame::NotifyUserActivation(Media()->GetDocument().GetFrame());
@@ -331,7 +334,7 @@ TEST_P(HTMLMediaElementTest,
// - Policy: DocumentUserActivation (aka. unified autoplay)
// - MEI: high;
// - Frame received user gesture.
- RuntimeEnabledFeatures::SetMediaEngagementBypassAutoplayPoliciesEnabled(true);
+ ScopedMediaEngagementBypassAutoplayPoliciesForTest scoped_feature(true);
Media()->GetDocument().GetSettings()->SetAutoplayPolicy(
AutoplayPolicy::Type::kDocumentUserActivationRequired);
SimulateHighMediaEngagement();
@@ -348,7 +351,7 @@ TEST_P(HTMLMediaElementTest,
// - Policy: DocumentUserActivation (aka. unified autoplay)
// - MEI: high;
// - Frame did not receive user gesture.
- RuntimeEnabledFeatures::SetMediaEngagementBypassAutoplayPoliciesEnabled(true);
+ ScopedMediaEngagementBypassAutoplayPoliciesForTest scoped_feature(true);
Media()->GetDocument().GetSettings()->SetAutoplayPolicy(
AutoplayPolicy::Type::kDocumentUserActivationRequired);
SimulateHighMediaEngagement();
@@ -488,4 +491,33 @@ TEST_P(HTMLMediaElementTest, ContextPaused) {
EXPECT_TRUE(Media()->paused());
}
+TEST_P(HTMLMediaElementTest, GcMarkingNoAllocWebTimeRanges) {
+ auto* thread_state = ThreadState::Current();
+ ThreadState::NoAllocationScope no_allocation_scope(thread_state);
+ EXPECT_FALSE(thread_state->IsAllocationAllowed());
+ // Use of TimeRanges is not allowed during GC marking (crbug.com/970150)
+ EXPECT_DCHECK_DEATH(MakeGarbageCollected<TimeRanges>(0, 0));
+ // Instead of using TimeRanges, WebTimeRanges can be used without GC
+ Vector<WebTimeRanges> ranges;
+ ranges.emplace_back();
+ ranges[0].emplace_back(0, 0);
+}
+
+// Reproduce crbug.com/970150
+TEST_P(HTMLMediaElementTest, GcMarkingNoAllocHasActivity) {
+ Media()->SetSrc(SrcSchemeToURL(TestURLScheme::kHttp));
+ Media()->Play();
+
+ test::RunPendingTasks();
+ SetReadyState(HTMLMediaElement::kHaveFutureData);
+ SetError(MakeGarbageCollected<MediaError>(MediaError::kMediaErrDecode, ""));
+
+ EXPECT_FALSE(Media()->paused());
+
+ auto* thread_state = ThreadState::Current();
+ ThreadState::NoAllocationScope no_allocation_scope(thread_state);
+ EXPECT_FALSE(thread_state->IsAllocationAllowed());
+ Media()->HasPendingActivity();
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/media/html_media_source.h b/chromium/third_party/blink/renderer/core/html/media/html_media_source.h
index 1ec61e12d18..a759c7b8def 100644
--- a/chromium/third_party/blink/renderer/core/html/media/html_media_source.h
+++ b/chromium/third_party/blink/renderer/core/html/media/html_media_source.h
@@ -32,6 +32,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_MEDIA_HTML_MEDIA_SOURCE_H_
#include <memory>
+#include "third_party/blink/public/platform/web_time_range.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/fileapi/url_registry.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
@@ -66,6 +67,16 @@ class CORE_EXPORT HTMLMediaSource : public URLRegistrable,
virtual void Close() = 0;
virtual bool IsClosed() const = 0;
virtual double duration() const = 0;
+
+ // 'Internal' in these methods doesn't mean private, it means that they are
+ // internal to chromium and are not exposed to JavaScript.
+
+ // The JavaScript exposed version of this is Buffered.
+ virtual WebTimeRanges BufferedInternal() const = 0;
+
+ // The JavaScript exposed version of this is Seekable.
+ virtual WebTimeRanges SeekableInternal() const = 0;
+
virtual TimeRanges* Buffered() const = 0;
virtual TimeRanges* Seekable() const = 0;
virtual void OnTrackChanged(TrackBase*) = 0;
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 7c47efac7db..608280125f3 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
@@ -39,7 +39,6 @@
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/picture_in_picture_controller.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/fullscreen/fullscreen.h"
#include "third_party/blink/renderer/core/fullscreen/fullscreen_options.h"
#include "third_party/blink/renderer/core/html/media/media_custom_controls_fullscreen_detector.h"
@@ -58,7 +57,8 @@
#include "third_party/blink/renderer/platform/graphics/canvas_resource_provider.h"
#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/instrumentation/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/web_test_support.h"
@@ -387,7 +387,7 @@ bool HTMLVideoElement::IsPersistent() const {
}
void HTMLVideoElement::UpdateDisplayState() {
- if (PosterImageURL().IsEmpty())
+ if (PosterImageURL().IsEmpty() || HasAvailableVideoFrame())
SetDisplayMode(kVideo);
else if (GetDisplayMode() < kPoster)
SetDisplayMode(kPoster);
@@ -516,13 +516,9 @@ bool HTMLVideoElement::PrepareVideoFrameForWebGL(
}
bool HTMLVideoElement::HasAvailableVideoFrame() const {
- if (!GetWebMediaPlayer())
- return false;
-
- // The ready state maximum is used here instead of the current ready state
- // since a frame is still available during a seek.
- return GetWebMediaPlayer()->HasVideo() &&
- ready_state_maximum_ >= kHaveCurrentData;
+ if (auto* wmp = GetWebMediaPlayer())
+ return wmp->HasAvailableVideoFrame();
+ return false;
}
void HTMLVideoElement::webkitEnterFullscreen() {
@@ -643,11 +639,13 @@ scoped_refptr<Image> HTMLVideoElement::GetSourceImageForCanvas(
}
IntSize intrinsic_size(videoWidth(), videoHeight());
- // FIXME: Not sure if we dhould we be doing anything with the AccelerationHint
+ // TODO(fserb): this should not be default software.
+ // FIXME: Not sure if we should we be doing anything with the AccelerationHint
// argument here? Currently we use unacceleration mode.
std::unique_ptr<CanvasResourceProvider> resource_provider =
CanvasResourceProvider::Create(
- intrinsic_size, CanvasResourceProvider::kSoftwareResourceUsage,
+ intrinsic_size,
+ CanvasResourceProvider::ResourceUsage::kSoftwareResourceUsage,
nullptr, // context_provider_wrapper
0, // msaa_sample_count
CanvasColorParams(), CanvasResourceProvider::kDefaultPresentationMode,
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 bd710023d50..b0211dd1095 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
@@ -197,8 +197,10 @@ class CORE_EXPORT HTMLVideoElement final : public HTMLMediaElement,
void SetIsEffectivelyFullscreen(blink::WebFullscreenVideoStatus);
void SetImageForTest(ImageResourceContent* content) {
- DCHECK(image_loader_);
+ if (!image_loader_)
+ image_loader_ = MakeGarbageCollected<HTMLImageLoader>(this);
image_loader_->SetImageForTest(content);
+ SetDisplayMode(kPoster);
}
VideoWakeLock* wake_lock_for_tests() const { return wake_lock_; }
diff --git a/chromium/third_party/blink/renderer/core/html/media/html_video_element.idl b/chromium/third_party/blink/renderer/core/html/media/html_video_element.idl
index 06bbed436d7..8e6cab0e084 100644
--- a/chromium/third_party/blink/renderer/core/html/media/html_video_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/media/html_video_element.idl
@@ -23,9 +23,10 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-// https://html.spec.whatwg.org/C/#the-video-element
+// https://html.spec.whatwg.org/multipage/media.html#htmlvideoelement
[
+ Exposed=Window,
HTMLConstructor,
ActiveScriptWrappable
] interface HTMLVideoElement : HTMLMediaElement {
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 d5a1f3d1825..954f311ad05 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
@@ -20,12 +20,15 @@
#include "third_party/blink/renderer/platform/testing/empty_web_media_player.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
+using testing::_;
+
namespace blink {
class HTMLVideoElementMockMediaPlayer : public EmptyWebMediaPlayer {
public:
MOCK_METHOD1(SetIsEffectivelyFullscreen, void(WebFullscreenVideoStatus));
MOCK_METHOD1(OnDisplayTypeChanged, void(WebMediaPlayer::DisplayType));
+ MOCK_CONST_METHOD0(HasAvailableVideoFrame, bool());
};
class HTMLVideoElementTest : public PageTestBase {
@@ -71,6 +74,7 @@ TEST_F(HTMLVideoElementTest, PictureInPictureInterstitialAndTextContainer) {
video()->UpdateTextTrackDisplay();
// Simulate entering Picture-in-Picture.
+ EXPECT_CALL(*MockWebMediaPlayer(), OnDisplayTypeChanged(_));
video()->OnEnteredPictureInPicture();
// Simulate that text track are displayed again.
@@ -90,6 +94,10 @@ TEST_F(HTMLVideoElementTest, PictureInPictureInterstitial_Reattach) {
video()->SetSrc("http://example.com/foo.mp4");
test::RunPendingTasks();
+ EXPECT_CALL(*MockWebMediaPlayer(), OnDisplayTypeChanged(_));
+ EXPECT_CALL(*MockWebMediaPlayer(), HasAvailableVideoFrame())
+ .WillRepeatedly(testing::Return(true));
+
// Simulate entering Picture-in-Picture.
video()->OnEnteredPictureInPicture();
@@ -100,6 +108,10 @@ TEST_F(HTMLVideoElementTest, PictureInPictureInterstitial_Reattach) {
}
TEST_F(HTMLVideoElementTest, EffectivelyFullscreen_DisplayType) {
+ video()->SetSrc("http://example.com/foo.mp4");
+ test::RunPendingTasks();
+ UpdateAllLifecyclePhasesForTest();
+
EXPECT_EQ(WebMediaPlayer::DisplayType::kInline, video()->DisplayType());
// Vector of data to use for tests. First value is to be set when calling
@@ -107,7 +119,7 @@ TEST_F(HTMLVideoElementTest, EffectivelyFullscreen_DisplayType) {
// This is testing all possible values of WebFullscreenVideoStatus and then
// sets the value back to a value that should put the DisplayType back to
// inline.
- std::vector<std::pair<WebFullscreenVideoStatus, WebMediaPlayer::DisplayType>>
+ Vector<std::pair<WebFullscreenVideoStatus, WebMediaPlayer::DisplayType>>
tests = {
{WebFullscreenVideoStatus::kNotEffectivelyFullscreen,
WebMediaPlayer::DisplayType::kInline},
@@ -125,6 +137,7 @@ TEST_F(HTMLVideoElementTest, EffectivelyFullscreen_DisplayType) {
video()->SetIsEffectivelyFullscreen(test.first);
EXPECT_EQ(test.second, video()->DisplayType());
+ testing::Mock::VerifyAndClearExpectations(MockWebMediaPlayer());
}
}
@@ -156,4 +169,16 @@ TEST_F(HTMLVideoElementTest, ChangeLayerNeedsCompositingUpdate) {
EXPECT_FALSE(paint_layer->NeedsCompositingInputsUpdate());
}
+TEST_F(HTMLVideoElementTest, HasAvailableVideoFrameChecksWMP) {
+ video()->SetSrc("http://example.com/foo.mp4");
+ test::RunPendingTasks();
+ UpdateAllLifecyclePhasesForTest();
+
+ EXPECT_CALL(*MockWebMediaPlayer(), HasAvailableVideoFrame())
+ .WillOnce(testing::Return(false))
+ .WillOnce(testing::Return(true));
+ EXPECT_FALSE(video()->HasAvailableVideoFrame());
+ EXPECT_TRUE(video()->HasAvailableVideoFrame());
+}
+
} // namespace blink
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 c7ad8c313f7..78f797a93ce 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
@@ -19,7 +19,8 @@ using blink::WebFullscreenVideoStatus;
namespace {
-constexpr TimeDelta kCheckFullscreenInterval = TimeDelta::FromSeconds(1);
+constexpr base::TimeDelta kCheckFullscreenInterval =
+ base::TimeDelta::FromSeconds(1);
constexpr float kMostlyFillViewportThresholdOfOccupationProportion = 0.85f;
constexpr float kMostlyFillViewportThresholdOfVisibleProportion = 0.75f;
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 8751b11288c..cb5658e5b7e 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
@@ -36,7 +36,6 @@
#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/html/html_body_element.h"
#include "third_party/blink/renderer/core/html/html_head_element.h"
#include "third_party/blink/renderer/core/html/html_html_element.h"
@@ -49,6 +48,7 @@
#include "third_party/blink/renderer/core/loader/frame_loader.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/keyboard_codes.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/media/media_error.idl b/chromium/third_party/blink/renderer/core/html/media/media_error.idl
index fbf1a237e17..7bdfc0b8ca8 100644
--- a/chromium/third_party/blink/renderer/core/html/media/media_error.idl
+++ b/chromium/third_party/blink/renderer/core/html/media/media_error.idl
@@ -25,6 +25,7 @@
// https://html.spec.whatwg.org/C/#error-codes
+[Exposed=Window]
interface MediaError {
const unsigned short MEDIA_ERR_ABORTED = 1;
const unsigned short MEDIA_ERR_NETWORK = 2;
diff --git a/chromium/third_party/blink/renderer/core/html/media/media_fragment_uri_parser.cc b/chromium/third_party/blink/renderer/core/html/media/media_fragment_uri_parser.cc
index 1bdbeef0a03..efb81e3e2bb 100644
--- a/chromium/third_party/blink/renderer/core/html/media/media_fragment_uri_parser.cc
+++ b/chromium/third_party/blink/renderer/core/html/media/media_fragment_uri_parser.cc
@@ -128,15 +128,15 @@ void MediaFragmentURIParser::ParseFragments() {
// UTF-8. If either name or value are not valid UTF-8 strings, then
// remove the name-value pair from the list.
bool valid_utf8 = true;
- CString utf8_name;
+ std::string utf8_name;
if (!name.IsEmpty()) {
utf8_name = name.Utf8(kStrictUTF8Conversion);
- valid_utf8 = !utf8_name.IsNull();
+ valid_utf8 = !utf8_name.empty();
}
- CString utf8_value;
+ std::string utf8_value;
if (valid_utf8 && !value.IsEmpty()) {
utf8_value = value.Utf8(kStrictUTF8Conversion);
- valid_utf8 = !utf8_value.IsNull();
+ valid_utf8 = !utf8_value.empty();
}
if (valid_utf8)
diff --git a/chromium/third_party/blink/renderer/core/html/media/media_fragment_uri_parser.h b/chromium/third_party/blink/renderer/core/html/media/media_fragment_uri_parser.h
index 795626021c8..3e965309c00 100644
--- a/chromium/third_party/blink/renderer/core/html/media/media_fragment_uri_parser.h
+++ b/chromium/third_party/blink/renderer/core/html/media/media_fragment_uri_parser.h
@@ -27,8 +27,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_MEDIA_MEDIA_FRAGMENT_URI_PARSER_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/text/cstring.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
@@ -68,7 +67,7 @@ class MediaFragmentURIParser final {
TimeFormat time_format_;
double start_time_;
double end_time_;
- Vector<std::pair<CString, CString>> fragments_;
+ Vector<std::pair<std::string, std::string>> fragments_;
};
} // namespace blink
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 580ef9d1b13..fabd7e4e736 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
@@ -14,10 +14,11 @@
namespace {
-constexpr TimeDelta kStyleChangeTransitionDuration =
- TimeDelta::FromMilliseconds(200);
-constexpr TimeDelta kHiddenAnimationDuration = TimeDelta::FromMilliseconds(300);
-constexpr TimeDelta kShowToastDuration = TimeDelta::FromSeconds(5);
+constexpr base::TimeDelta kStyleChangeTransitionDuration =
+ base::TimeDelta::FromMilliseconds(200);
+constexpr base::TimeDelta kHiddenAnimationDuration =
+ base::TimeDelta::FromMilliseconds(300);
+constexpr base::TimeDelta kShowToastDuration = base::TimeDelta::FromSeconds(5);
} // namespace
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 17a3f6f8a68..5159cdf2528 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
@@ -20,10 +20,10 @@
namespace {
-constexpr TimeDelta kPictureInPictureStyleChangeTransitionDuration =
- TimeDelta::FromMilliseconds(200);
-constexpr TimeDelta kPictureInPictureHiddenAnimationSeconds =
- TimeDelta::FromMilliseconds(300);
+constexpr base::TimeDelta kPictureInPictureStyleChangeTransitionDuration =
+ base::TimeDelta::FromMilliseconds(200);
+constexpr base::TimeDelta kPictureInPictureHiddenAnimationSeconds =
+ base::TimeDelta::FromMilliseconds(300);
} // namespace
diff --git a/chromium/third_party/blink/renderer/core/html/media/video_auto_fullscreen_test.cc b/chromium/third_party/blink/renderer/core/html/media/video_auto_fullscreen_test.cc
index 749e6a68982..c8505727c13 100644
--- a/chromium/third_party/blink/renderer/core/html/media/video_auto_fullscreen_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/media/video_auto_fullscreen_test.cc
@@ -14,6 +14,7 @@
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/testing/wait_for_event.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"
namespace blink {
@@ -52,11 +53,11 @@ class VideoAutoFullscreenFrameClient
WebWidget* web_widget_;
};
-class VideoAutoFullscreen : public testing::Test {
+class VideoAutoFullscreen : public testing::Test,
+ private ScopedVideoAutoFullscreenForTest {
public:
+ VideoAutoFullscreen() : ScopedVideoAutoFullscreenForTest(true) {}
void SetUp() override {
- RuntimeEnabledFeatures::SetVideoAutoFullscreenEnabled(true);
-
web_view_helper_.Initialize(&web_frame_client_);
GetWebView()->GetSettings()->SetAutoplayPolicy(
WebSettings::AutoplayPolicy::kUserGestureRequired);
diff --git a/chromium/third_party/blink/renderer/core/html/media/video_wake_lock_test.cc b/chromium/third_party/blink/renderer/core/html/media/video_wake_lock_test.cc
index b89b83cf246..448ca9a8ddb 100644
--- a/chromium/third_party/blink/renderer/core/html/media/video_wake_lock_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/media/video_wake_lock_test.cc
@@ -4,6 +4,9 @@
#include "third_party/blink/renderer/core/html/media/video_wake_lock.h"
+#include "mojo/public/cpp/bindings/pending_receiver.h"
+#include "mojo/public/cpp/bindings/pending_remote.h"
+#include "mojo/public/cpp/bindings/receiver.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/mojom/picture_in_picture/picture_in_picture.mojom-blink.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
@@ -25,8 +28,8 @@ class VideoWakeLockPictureInPictureSession
: public mojom::blink::PictureInPictureSession {
public:
explicit VideoWakeLockPictureInPictureSession(
- mojo::InterfaceRequest<mojom::blink::PictureInPictureSession> request)
- : binding_(this, std::move(request)) {}
+ mojo::PendingReceiver<mojom::blink::PictureInPictureSession> receiver)
+ : receiver_(this, std::move(receiver)) {}
~VideoWakeLockPictureInPictureSession() override = default;
void Stop(StopCallback callback) final { std::move(callback).Run(); }
@@ -38,7 +41,7 @@ class VideoWakeLockPictureInPictureSession
bool show_mute_button) final {}
private:
- mojo::Binding<mojom::blink::PictureInPictureSession> binding_;
+ mojo::Receiver<mojom::blink::PictureInPictureSession> receiver_;
};
// The VideoWakeLockPictureInPictureService implements the PictureInPicture
@@ -47,30 +50,31 @@ class VideoWakeLockPictureInPictureSession
class VideoWakeLockPictureInPictureService
: public mojom::blink::PictureInPictureService {
public:
- VideoWakeLockPictureInPictureService() : binding_(this) {}
+ VideoWakeLockPictureInPictureService() : receiver_(this) {}
~VideoWakeLockPictureInPictureService() override = default;
void Bind(mojo::ScopedMessagePipeHandle handle) {
- binding_.Bind(
- mojom::blink::PictureInPictureServiceRequest(std::move(handle)));
+ receiver_.Bind(mojo::PendingReceiver<mojom::blink::PictureInPictureService>(
+ std::move(handle)));
}
- void StartSession(uint32_t,
- const base::Optional<viz::SurfaceId>&,
- const blink::WebSize&,
- bool,
- bool,
- mojom::blink::PictureInPictureSessionObserverPtr,
- StartSessionCallback callback) final {
- mojom::blink::PictureInPictureSessionPtr session_ptr;
+ void StartSession(
+ uint32_t,
+ const base::Optional<viz::SurfaceId>&,
+ const blink::WebSize&,
+ bool,
+ bool,
+ mojo::PendingRemote<mojom::blink::PictureInPictureSessionObserver>,
+ StartSessionCallback callback) final {
+ mojo::PendingRemote<mojom::blink::PictureInPictureSession> session_remote;
session_.reset(new VideoWakeLockPictureInPictureSession(
- mojo::MakeRequest(&session_ptr)));
+ session_remote.InitWithNewPipeAndPassReceiver()));
- std::move(callback).Run(std::move(session_ptr), WebSize());
+ std::move(callback).Run(std::move(session_remote), WebSize());
}
private:
- mojo::Binding<mojom::blink::PictureInPictureService> binding_;
+ mojo::Receiver<mojom::blink::PictureInPictureService> receiver_;
std::unique_ptr<VideoWakeLockPictureInPictureSession> session_;
};
diff --git a/chromium/third_party/blink/renderer/core/html/parser/atomic_html_token.cc b/chromium/third_party/blink/renderer/core/html/parser/atomic_html_token.cc
index 419fbf3ffd4..8adbebafa82 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/atomic_html_token.cc
+++ b/chromium/third_party/blink/renderer/core/html/parser/atomic_html_token.cc
@@ -47,11 +47,11 @@ void AtomicHTMLToken::Show() const {
printf(" selfclosing");
FALLTHROUGH;
case HTMLToken::DOCTYPE:
- printf(" name \"%s\"", name_.GetString().Utf8().data());
+ printf(" name \"%s\"", name_.GetString().Utf8().c_str());
break;
case HTMLToken::kComment:
case HTMLToken::kCharacter:
- printf(" data \"%s\"", data_.Utf8().data());
+ printf(" data \"%s\"", data_.Utf8().c_str());
break;
default:
break;
diff --git a/chromium/third_party/blink/renderer/core/html/parser/atomic_html_token.h b/chromium/third_party/blink/renderer/core/html/parser/atomic_html_token.h
index 6e091f6948e..6c1dcaa54c6 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/atomic_html_token.h
+++ b/chromium/third_party/blink/renderer/core/html/parser/atomic_html_token.h
@@ -33,7 +33,7 @@
#include "third_party/blink/renderer/core/html/parser/compact_html_token.h"
#include "third_party/blink/renderer/core/html/parser/html_token.h"
#include "third_party/blink/renderer/core/html_element_lookup_trie.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/parser/background_html_input_stream.h b/chromium/third_party/blink/renderer/core/html/parser/background_html_input_stream.h
index a32e032d386..4e04ad139fe 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/background_html_input_stream.h
+++ b/chromium/third_party/blink/renderer/core/html/parser/background_html_input_stream.h
@@ -28,7 +28,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/platform/text/segmented_string.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
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 1eaf3d4583c..3d765b580ab 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
@@ -34,9 +34,9 @@
#include "third_party/blink/renderer/core/html/parser/text_resource_decoder.h"
#include "third_party/blink/renderer/core/html/parser/xss_auditor.h"
#include "third_party/blink/renderer/core/html_names.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/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.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"
@@ -101,8 +101,7 @@ BackgroundHTMLParser::BackgroundHTMLParser(
loading_task_runner_(std::move(loading_task_runner)),
pending_csp_meta_token_index_(
HTMLDocumentParser::TokenizedChunk::kNoPendingToken),
- starting_script_(false),
- weak_factory_(this) {}
+ starting_script_(false) {}
BackgroundHTMLParser::~BackgroundHTMLParser() = default;
diff --git a/chromium/third_party/blink/renderer/core/html/parser/background_html_parser.h b/chromium/third_party/blink/renderer/core/html/parser/background_html_parser.h
index 76b01e43458..5b4fc4debbe 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/background_html_parser.h
+++ b/chromium/third_party/blink/renderer/core/html/parser/background_html_parser.h
@@ -133,7 +133,7 @@ class BackgroundHTMLParser {
bool starting_script_;
- base::WeakPtrFactory<BackgroundHTMLParser> weak_factory_;
+ base::WeakPtrFactory<BackgroundHTMLParser> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(BackgroundHTMLParser);
};
diff --git a/chromium/third_party/blink/renderer/core/html/parser/compact_html_token.h b/chromium/third_party/blink/renderer/core/html/parser/compact_html_token.h
index ccb3c6f6c70..c24072f3c79 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/compact_html_token.h
+++ b/chromium/third_party/blink/renderer/core/html/parser/compact_html_token.h
@@ -27,7 +27,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_PARSER_COMPACT_HTML_TOKEN_H_
#include "third_party/blink/renderer/core/html/parser/html_token.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/text_position.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
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 f0be9372801..eb5b85853bd 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
@@ -39,7 +39,6 @@
#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/html/custom/ce_reactions_scope.h"
#include "third_party/blink/renderer/core/html/custom/custom_element.h"
#include "third_party/blink/renderer/core/html/custom/custom_element_definition.h"
@@ -65,6 +64,7 @@
#include "third_party/blink/renderer/platform/bindings/microtask.h"
#include "third_party/blink/renderer/platform/bindings/v8_per_isolate_data.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/text/text_break_iterator.h"
namespace blink {
@@ -124,12 +124,10 @@ static inline void ExecuteInsertTask(HTMLConstructionSiteTask& task) {
DCHECK_EQ(task.operation, HTMLConstructionSiteTask::kInsert);
Insert(task);
-
- if (task.child->IsElementNode()) {
- Element& child = ToElement(*task.child);
- child.BeginParsingChildren();
+ if (auto* child = DynamicTo<Element>(task.child.Get())) {
+ child->BeginParsingChildren();
if (task.self_closing)
- child.FinishParsingChildren();
+ child->FinishParsingChildren();
}
}
@@ -295,8 +293,9 @@ void HTMLConstructionSite::QueueTask(const HTMLConstructionSiteTask& task) {
void HTMLConstructionSite::AttachLater(ContainerNode* parent,
Node* child,
bool self_closing) {
- DCHECK(ScriptingContentIsAllowed(parser_content_policy_) ||
- !child->IsElementNode() || !ToElement(child)->IsScriptElement());
+ auto* element = DynamicTo<Element>(child);
+ DCHECK(ScriptingContentIsAllowed(parser_content_policy_) || !element ||
+ !element->IsScriptElement());
DCHECK(PluginContentIsAllowed(parser_content_policy_) ||
!IsHTMLPlugInElement(child));
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 5cce22fd2e4..7c259b82a2a 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
@@ -30,6 +30,8 @@
#include "base/auto_reset.h"
#include "base/numerics/safe_conversions.h"
+#include "third_party/blink/public/common/features.h"
+#include "third_party/blink/public/mojom/appcache/appcache.mojom-blink.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_loading_behavior_flag.h"
@@ -54,16 +56,17 @@
#include "third_party/blink/renderer/core/script/html_parser_script_runner.h"
#include "third_party/blink/renderer/platform/bindings/runtime_call_stats.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/heap/handle.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
+#include "third_party/blink/renderer/platform/scheduler/public/cooperative_scheduling_manager.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/shared_buffer.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
namespace blink {
@@ -151,9 +154,8 @@ HTMLDocumentParser::HTMLDocumentParser(Document& document,
pump_speculations_session_nesting_level_(0),
is_parsing_at_line_number_(false),
tried_loading_link_headers_(false),
- added_pending_stylesheet_in_body_(false),
- is_waiting_for_stylesheets_(false),
- weak_factory_(this) {
+ added_pending_parser_blocking_stylesheet_(false),
+ is_waiting_for_stylesheets_(false) {
DCHECK(ShouldUseThreading() || (token_ && tokenizer_));
// Threading is not allowed in prefetch mode.
DCHECK(!document.IsPrefetchOnly() || !ShouldUseThreading());
@@ -254,6 +256,9 @@ void HTMLDocumentParser::PrepareToStopParsing() {
if (IsDetached())
return;
+ if (script_runner_)
+ script_runner_->RecordMetricsAtParseEnd();
+
AttemptToRunDeferredScriptsAndEnd();
}
@@ -315,6 +320,8 @@ void HTMLDocumentParser::EnqueueTokenizedChunk(
TRACE_EVENT0("blink", "HTMLDocumentParser::EnqueueTokenizedChunk");
DCHECK(chunk);
+ DCHECK(GetDocument());
+
if (!IsParsing())
return;
@@ -346,13 +353,20 @@ void HTMLDocumentParser::EnqueueTokenizedChunk(
}
if (preloader_) {
- bool appcache_initialized = GetDocument()->documentElement();
- if (!appcache_initialized) {
- appcache_queueing_start_time_ = CurrentTimeTicks();
+ bool appcache_fetched = false;
+ if (GetDocument()->Loader()) {
+ appcache_fetched = (GetDocument()->Loader()->GetResponse().AppCacheID() !=
+ mojom::blink::kAppCacheNoCacheId);
}
+ bool appcache_initialized = GetDocument()->documentElement();
// Delay sending some requests if meta tag based CSP is present or
- // if AppCache was not yet initialized.
- if (pending_csp_meta_token_ || !appcache_initialized) {
+ // if AppCache was used to fetch the HTML but was not yet initialized for
+ // this document.
+ if (pending_csp_meta_token_ ||
+ ((!base::FeatureList::IsEnabled(
+ blink::features::kVerifyHTMLFetchedFromAppCacheBeforeDelay) ||
+ appcache_fetched) &&
+ !appcache_initialized)) {
PreloadRequestStream link_rel_preloads;
for (auto& request : chunk->preloads) {
// Link rel preloads don't need to wait for AppCache but they
@@ -1071,6 +1085,10 @@ void HTMLDocumentParser::NotifyScriptLoaded(PendingScript* pending_script) {
DCHECK(script_runner_);
DCHECK(!IsExecutingScript());
+ scheduler::CooperativeSchedulingManager::AllowedStackScope
+ whitelisted_stack_scope(
+ scheduler::CooperativeSchedulingManager::Instance());
+
if (IsStopped()) {
return;
}
@@ -1102,27 +1120,27 @@ void HTMLDocumentParser::ExecuteScriptsWaitingForResources() {
ResumeParsingAfterPause();
}
-void HTMLDocumentParser::DidAddPendingStylesheetInBody() {
+void HTMLDocumentParser::DidAddPendingParserBlockingStylesheet() {
// In-body CSS doesn't block painting. The parser needs to pause so that
// the DOM doesn't include any elements that may depend on the CSS for style.
// The stylesheet can be added and removed during the parsing of a single
// token so don't actually set the bit to block parsing here, just track
// the state of the added sheet in case it does persist beyond a single
// token.
- added_pending_stylesheet_in_body_ = true;
+ added_pending_parser_blocking_stylesheet_ = true;
}
-void HTMLDocumentParser::DidLoadAllBodyStylesheets() {
+void HTMLDocumentParser::DidLoadAllPendingParserBlockingStylesheets() {
// Just toggle the stylesheet flag here (mostly for synchronous sheets).
// The document will also call into executeScriptsWaitingForResources
// which is when the parser will re-start, otherwise it will attempt to
// resume twice which could cause state machine issues.
- added_pending_stylesheet_in_body_ = false;
+ added_pending_parser_blocking_stylesheet_ = false;
}
void HTMLDocumentParser::CheckIfBodyStylesheetAdded() {
- if (added_pending_stylesheet_in_body_) {
- added_pending_stylesheet_in_body_ = false;
+ if (added_pending_parser_blocking_stylesheet_) {
+ added_pending_parser_blocking_stylesheet_ = false;
is_waiting_for_stylesheets_ = true;
}
}
@@ -1215,23 +1233,8 @@ void HTMLDocumentParser::SetDecoder(
void HTMLDocumentParser::DocumentElementAvailable() {
TRACE_EVENT0("blink,loading", "HTMLDocumentParser::DocumentElementAvailable");
- TimeDelta delta;
- if (!appcache_queueing_start_time_.is_null()) {
- delta = CurrentTimeTicks() - appcache_queueing_start_time_;
- }
- UMA_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES(
- "WebCore.HTMLDocumentParser.PreloadScannerAppCacheDelayTime", delta,
- base::TimeDelta::FromMicroseconds(1),
- base::TimeDelta::FromMilliseconds(1000), 50);
Document* document = GetDocument();
DCHECK(document);
- LocalFrame* frame = document->GetFrame();
- if (frame && frame->IsMainFrame()) {
- UMA_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES(
- "WebCore.HTMLDocumentParser.PreloadScannerAppCacheDelayTime.MainFrame",
- delta, base::TimeDelta::FromMicroseconds(1),
- base::TimeDelta::FromMilliseconds(1000), 50);
- }
DCHECK(document->documentElement());
Element* documentElement = GetDocument()->documentElement();
if (documentElement->hasAttribute(u"\u26A1") ||
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 df11f78d301..35f40b4440a 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
@@ -159,8 +159,8 @@ class CORE_EXPORT HTMLDocumentParser : public ScriptableDocumentParser,
bool IsWaitingForScripts() const final;
bool IsExecutingScript() const final;
void ExecuteScriptsWaitingForResources() final;
- void DidAddPendingStylesheetInBody() final;
- void DidLoadAllBodyStylesheets() final;
+ void DidAddPendingParserBlockingStylesheet() final;
+ void DidLoadAllPendingParserBlockingStylesheets() final;
void CheckIfBodyStylesheetAdded();
void DocumentElementAvailable() override;
@@ -248,7 +248,6 @@ class CORE_EXPORT HTMLDocumentParser : public ScriptableDocumentParser,
base::WeakPtr<BackgroundHTMLParser> background_parser_;
Member<HTMLResourcePreloader> preloader_;
PreloadRequestStream queued_preloads_;
- TimeTicks appcache_queueing_start_time_;
// If this is non-null, then there is a meta CSP token somewhere in the
// speculation buffer. Preloads will be deferred until a token matching this
@@ -268,10 +267,10 @@ class CORE_EXPORT HTMLDocumentParser : public ScriptableDocumentParser,
unsigned pump_speculations_session_nesting_level_;
bool is_parsing_at_line_number_;
bool tried_loading_link_headers_;
- bool added_pending_stylesheet_in_body_;
+ bool added_pending_parser_blocking_stylesheet_;
bool is_waiting_for_stylesheets_;
- base::WeakPtrFactory<HTMLDocumentParser> weak_factory_;
+ base::WeakPtrFactory<HTMLDocumentParser> weak_factory_{this};
};
} // namespace blink
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 87d6b262b20..5132af65b49 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
@@ -165,8 +165,9 @@ void HTMLElementStack::PopAll() {
stack_depth_ = 0;
while (top_) {
Node& node = *TopNode();
- if (node.IsElementNode()) {
- ToElement(node).FinishParsingChildren();
+ auto* element = DynamicTo<Element>(node);
+ if (element) {
+ element->FinishParsingChildren();
if (auto* select = ToHTMLSelectElementOrNull(node))
select->SetBlocksFormSubmission(true);
}
@@ -470,7 +471,7 @@ bool HTMLElementStack::HasTemplateInHTMLScope() const {
Element* HTMLElementStack::HtmlElement() const {
DCHECK(root_node_);
- return ToElement(root_node_);
+ return To<Element>(root_node_.Get());
}
Element* HTMLElementStack::HeadElement() const {
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_entity_parser.h b/chromium/third_party/blink/renderer/core/html/parser/html_entity_parser.h
index 814fccb6a36..4f936a8497a 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_entity_parser.h
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_entity_parser.h
@@ -29,7 +29,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/text/segmented_string.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_entity_search.h b/chromium/third_party/blink/renderer/core/html/parser/html_entity_search.h
index 3a54bd060d7..163e58b3a23 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_entity_search.h
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_entity_search.h
@@ -26,7 +26,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_HTML_PARSER_HTML_ENTITY_SEARCH_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_PARSER_HTML_ENTITY_SEARCH_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_entity_table.h b/chromium/third_party/blink/renderer/core/html/parser/html_entity_table.h
index fe936790956..7f8c1d7678f 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_entity_table.h
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_entity_table.h
@@ -26,7 +26,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_HTML_PARSER_HTML_ENTITY_TABLE_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_PARSER_HTML_ENTITY_TABLE_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_input_stream.h b/chromium/third_party/blink/renderer/core/html/parser/html_input_stream.h
index e0c6415d838..9539cceaa7f 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_input_stream.h
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_input_stream.h
@@ -29,7 +29,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/html/parser/input_stream_preprocessor.h"
#include "third_party/blink/renderer/platform/text/segmented_string.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_parser_options.h b/chromium/third_party/blink/renderer/core/html/parser/html_parser_options.h
index 8a469a2e4f1..50011d16d10 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_parser_options.h
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_parser_options.h
@@ -27,7 +27,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_PARSER_HTML_PARSER_OPTIONS_H_
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 c8fbb188736..156092ec66d 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
@@ -37,13 +37,12 @@ namespace blink {
SpeculationsPumpSession::SpeculationsPumpSession(unsigned& nesting_level)
: NestingLevelIncrementer(nesting_level),
- start_time_(CurrentTime()),
processed_element_tokens_(0) {}
SpeculationsPumpSession::~SpeculationsPumpSession() = default;
-inline double SpeculationsPumpSession::ElapsedTime() const {
- return CurrentTime() - start_time_;
+inline base::TimeDelta SpeculationsPumpSession::ElapsedTime() const {
+ return start_time_.Elapsed();
}
void SpeculationsPumpSession::AddedElementTokens(size_t count) {
@@ -103,7 +102,8 @@ inline bool HTMLParserScheduler::ShouldYield(
if (ThreadScheduler::Current()->ShouldYieldForHighPriorityWork())
return true;
- const double kParserTimeLimit = 0.5;
+ const base::TimeDelta kParserTimeLimit =
+ base::TimeDelta::FromMilliseconds(500);
if (session.ElapsedTime() > kParserTimeLimit)
return true;
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 612dd39fe7c..d947fcd22ef 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
@@ -29,9 +29,10 @@
#include "base/macros.h"
#include "base/memory/scoped_refptr.h"
#include "base/single_thread_task_runner.h"
+#include "base/timer/elapsed_timer.h"
#include "third_party/blink/renderer/core/html/parser/nesting_level_incrementer.h"
#include "third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -44,12 +45,12 @@ class SpeculationsPumpSession : public NestingLevelIncrementer {
SpeculationsPumpSession(unsigned& nesting_level);
~SpeculationsPumpSession();
- double ElapsedTime() const;
+ base::TimeDelta ElapsedTime() const;
void AddedElementTokens(size_t count);
size_t ProcessedElementTokens() const { return processed_element_tokens_; }
private:
- double start_time_;
+ base::ElapsedTimer start_time_;
size_t processed_element_tokens_;
};
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 c6dde7a6f82..87a0f2736c7 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,7 +29,7 @@
#include <memory>
#include "base/optional.h"
-#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-shared.h"
+#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h"
#include "third_party/blink/public/mojom/script/script_type.mojom-blink.h"
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
#include "third_party/blink/renderer/core/css/css_property_name.h"
@@ -58,7 +58,7 @@
#include "third_party/blink/renderer/core/loader/subresource_integrity_helper.h"
#include "third_party/blink/renderer/core/origin_trials/origin_trials.h"
#include "third_party/blink/renderer/core/script/script_loader.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/loader/fetch/integrity_metadata.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource.h"
@@ -299,54 +299,53 @@ class TokenPreloadScanner::StartTagScanner {
document_parameters.lazyload_policy_enforced) {
effective_loading_attr_value = LoadingAttrValue::kAuto;
}
- bool is_lazy_load_image_enabled = false;
- switch (effective_loading_attr_value) {
- case LoadingAttrValue::kEager:
- is_lazy_load_image_enabled = false;
- break;
- case LoadingAttrValue::kLazy:
- is_lazy_load_image_enabled =
- document_parameters.lazy_load_image_enabled_state !=
- LocalFrame::LazyLoadImageEnabledState::kDisabled;
- break;
- case LoadingAttrValue::kAuto:
- if ((width_attr_dimension_type_ ==
- HTMLImageElement::LazyLoadDimensionType::kAbsoluteSmall &&
- height_attr_dimension_type_ ==
- HTMLImageElement::LazyLoadDimensionType::kAbsoluteSmall) ||
- inline_style_dimensions_type_ ==
- HTMLImageElement::LazyLoadDimensionType::kAbsoluteSmall) {
+ if (type == ResourceType::kImage) {
+ bool is_lazy_load_image_enabled = false;
+ switch (effective_loading_attr_value) {
+ case LoadingAttrValue::kEager:
is_lazy_load_image_enabled = false;
- } else {
+ break;
+ case LoadingAttrValue::kLazy:
is_lazy_load_image_enabled =
- document_parameters.lazy_load_image_enabled_state ==
- LocalFrame::LazyLoadImageEnabledState::kEnabledAutomatic;
- }
- break;
- }
- // Do not preload if lazyload is possible but metadata fetch is disabled.
- if (is_lazy_load_image_enabled &&
- !RuntimeEnabledFeatures::LazyImageLoadingMetadataFetchEnabled()) {
- return nullptr;
- }
- // LazyLoad: Do not preload if absolute dimensions are mentioned in width
- // and height attributes or in the inline style, and the dimensions are not
- // small enough.
- if (is_lazy_load_image_enabled &&
- ((width_attr_dimension_type_ ==
- HTMLImageElement::LazyLoadDimensionType::kAbsoluteNotSmall &&
- height_attr_dimension_type_ ==
- HTMLImageElement::LazyLoadDimensionType::kAbsoluteNotSmall) ||
- inline_style_dimensions_type_ ==
- HTMLImageElement::LazyLoadDimensionType::kAbsoluteNotSmall)) {
- return nullptr;
+ document_parameters.lazy_load_image_setting !=
+ LocalFrame::LazyLoadImageSetting::kDisabled;
+ break;
+ case LoadingAttrValue::kAuto:
+ if ((width_attr_dimension_type_ ==
+ HTMLImageElement::LazyLoadDimensionType::kAbsoluteSmall &&
+ height_attr_dimension_type_ ==
+ HTMLImageElement::LazyLoadDimensionType::kAbsoluteSmall) ||
+ inline_style_dimensions_type_ ==
+ HTMLImageElement::LazyLoadDimensionType::kAbsoluteSmall) {
+ is_lazy_load_image_enabled = false;
+ } else {
+ is_lazy_load_image_enabled =
+ document_parameters.lazy_load_image_setting ==
+ LocalFrame::LazyLoadImageSetting::kEnabledAutomatic;
+ }
+ break;
+ }
+ // Do not preload if lazyload is possible but metadata fetch is disabled.
+ if (is_lazy_load_image_enabled &&
+ !RuntimeEnabledFeatures::LazyImageLoadingMetadataFetchEnabled()) {
+ return nullptr;
+ }
+ // LazyLoad: Do not preload if absolute dimensions are mentioned in width
+ // and height attributes or in the inline style, and the dimensions are
+ // not small enough.
+ if (is_lazy_load_image_enabled &&
+ ((width_attr_dimension_type_ ==
+ HTMLImageElement::LazyLoadDimensionType::kAbsoluteNotSmall &&
+ height_attr_dimension_type_ ==
+ HTMLImageElement::LazyLoadDimensionType::kAbsoluteNotSmall) ||
+ inline_style_dimensions_type_ ==
+ HTMLImageElement::LazyLoadDimensionType::kAbsoluteNotSmall)) {
+ return nullptr;
+ }
+ request->SetIsLazyLoadImageEnabled(is_lazy_load_image_enabled);
}
- request->SetIsLazyLoadImageEnabled(is_lazy_load_image_enabled);
- // 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_, kLinkTag))
- request->SetIntegrityMetadata(integrity_metadata_);
+ request->SetIntegrityMetadata(integrity_metadata_);
if (scanner_type_ == ScannerType::kInsertion)
request->SetFromInsertionScanner(true);
@@ -1092,11 +1091,10 @@ CachedDocumentParameters::CachedDocumentParameters(Document* document) {
integrity_features = SubresourceIntegrityHelper::GetFeatures(document);
lazyload_policy_enforced = document->IsLazyLoadPolicyEnforced();
if (document->Loader() && document->Loader()->GetFrame()) {
- lazy_load_image_enabled_state =
- document->Loader()->GetFrame()->GetLazyLoadImageEnabledState();
+ lazy_load_image_setting =
+ document->Loader()->GetFrame()->GetLazyLoadImageSetting();
} else {
- lazy_load_image_enabled_state =
- LocalFrame::LazyLoadImageEnabledState::kDisabled;
+ lazy_load_image_setting = LocalFrame::LazyLoadImageSetting::kDisabled;
}
}
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 90c3cfc8d43..d621de64499 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
@@ -56,12 +56,6 @@ struct CORE_EXPORT CachedDocumentParameters {
USING_FAST_MALLOC(CachedDocumentParameters);
public:
- enum class LazyLoadImageEnabledState {
- kDisabled,
- kEnabledExplicit,
- kEnabledAutomatic
- };
-
explicit CachedDocumentParameters(Document*);
CachedDocumentParameters() = default;
@@ -72,7 +66,7 @@ struct CORE_EXPORT CachedDocumentParameters {
network::mojom::ReferrerPolicy referrer_policy;
SubresourceIntegrity::IntegrityFeatures integrity_features;
bool lazyload_policy_enforced;
- LocalFrame::LazyLoadImageEnabledState lazy_load_image_enabled_state;
+ LocalFrame::LazyLoadImageSetting lazy_load_image_setting;
};
class TokenPreloadScanner {
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 5fb686fe97b..fa4f9a9215a 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
@@ -71,7 +71,7 @@ int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
TokenPreloadScanner::ScannerType::kMainDocument);
TextResourceDecoderForFuzzing decoder(fuzzed_data);
- CString bytes = fuzzed_data.ConsumeRemainingBytes();
+ std::string bytes = fuzzed_data.ConsumeRemainingBytes();
String decoded_bytes = decoder.Decode(bytes.data(), bytes.length());
scanner->AppendToEnd(decoded_bytes);
bool has_csp_meta_tag_unused = false;
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 4d31917c429..7c14c44530f 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
@@ -59,8 +59,8 @@ struct ReferrerPolicyTestCase {
struct CorsTestCase {
const char* base_url;
const char* input_html;
- network::mojom::FetchRequestMode request_mode;
- network::mojom::FetchCredentialsMode credentials_mode;
+ network::mojom::RequestMode request_mode;
+ network::mojom::CredentialsMode credentials_mode;
};
struct CSPTestCase {
@@ -160,15 +160,14 @@ class HTMLMockHTMLResourcePreloader : public ResourcePreloader {
void CorsRequestVerification(
Document* document,
- network::mojom::FetchRequestMode request_mode,
- network::mojom::FetchCredentialsMode credentials_mode) {
+ network::mojom::RequestMode request_mode,
+ network::mojom::CredentialsMode credentials_mode) {
ASSERT_TRUE(preload_request_.get());
Resource* resource = preload_request_->Start(document);
ASSERT_TRUE(resource);
- EXPECT_EQ(request_mode,
- resource->GetResourceRequest().GetFetchRequestMode());
+ EXPECT_EQ(request_mode, resource->GetResourceRequest().GetMode());
EXPECT_EQ(credentials_mode,
- resource->GetResourceRequest().GetFetchCredentialsMode());
+ resource->GetResourceRequest().GetCredentialsMode());
}
void NonceRequestVerification(const char* nonce) {
@@ -246,8 +245,7 @@ class HTMLPreloadScannerTest : public PageTestBase {
KURL document_url = KURL("http://whatever.test/");
if (use_secure_document_url)
document_url = KURL("https://whatever.test/");
- GetDocument().SetURL(document_url);
- GetDocument().SetSecurityOrigin(SecurityOrigin::Create(document_url));
+ NavigateTo(document_url);
GetDocument().GetSettings()->SetViewportEnabled(viewport_state ==
kViewportEnabled);
GetDocument().GetSettings()->SetViewportMetaEnabled(viewport_state ==
@@ -912,27 +910,27 @@ TEST_F(HTMLPreloadScannerTest, testReferrerPolicy) {
TEST_F(HTMLPreloadScannerTest, testCors) {
CorsTestCase test_cases[] = {
{"http://example.test", "<script src='/script'></script>",
- network::mojom::FetchRequestMode::kNoCors,
- network::mojom::FetchCredentialsMode::kInclude},
+ network::mojom::RequestMode::kNoCors,
+ network::mojom::CredentialsMode::kInclude},
{"http://example.test", "<script crossorigin src='/script'></script>",
- network::mojom::FetchRequestMode::kCors,
- network::mojom::FetchCredentialsMode::kSameOrigin},
+ network::mojom::RequestMode::kCors,
+ network::mojom::CredentialsMode::kSameOrigin},
{"http://example.test",
"<script crossorigin=use-credentials src='/script'></script>",
- network::mojom::FetchRequestMode::kCors,
- network::mojom::FetchCredentialsMode::kInclude},
+ network::mojom::RequestMode::kCors,
+ network::mojom::CredentialsMode::kInclude},
{"http://example.test", "<script type='module' src='/script'></script>",
- network::mojom::FetchRequestMode::kCors,
- network::mojom::FetchCredentialsMode::kSameOrigin},
+ network::mojom::RequestMode::kCors,
+ network::mojom::CredentialsMode::kSameOrigin},
{"http://example.test",
"<script type='module' crossorigin='anonymous' src='/script'></script>",
- network::mojom::FetchRequestMode::kCors,
- network::mojom::FetchCredentialsMode::kSameOrigin},
+ network::mojom::RequestMode::kCors,
+ network::mojom::CredentialsMode::kSameOrigin},
{"http://example.test",
"<script type='module' crossorigin='use-credentials' "
"src='/script'></script>",
- network::mojom::FetchRequestMode::kCors,
- network::mojom::FetchCredentialsMode::kInclude},
+ network::mojom::RequestMode::kCors,
+ network::mojom::CredentialsMode::kInclude},
};
for (const auto& test_case : test_cases) {
@@ -1237,6 +1235,7 @@ TEST_F(HTMLPreloadScannerTest, LazyLoadImage_DisabledForSmallImages) {
}
TEST_F(HTMLPreloadScannerTest, LazyLoadImage_FeatureDisabledWithAttribute) {
+ ScopedLazyImageLoadingForTest scoped_lazy_image_loading_for_test(false);
GetDocument().GetSettings()->SetLazyLoadEnabled(true);
RunSetUp(kViewportEnabled);
LazyLoadImageTestCase test_cases[] = {
@@ -1275,6 +1274,8 @@ TEST_F(HTMLPreloadScannerTest,
ScopedLazyImageLoadingForTest scoped_lazy_image_loading_for_test(true);
ScopedLazyImageLoadingMetadataFetchForTest
scoped_lazy_image_loading_metadata_fetch_for_test(true);
+ ScopedAutomaticLazyImageLoadingForTest
+ scoped_automatic_lazy_image_loading_for_test(false);
GetDocument().GetSettings()->SetLazyLoadEnabled(true);
RunSetUp(kViewportEnabled);
LazyLoadImageTestCase test_cases[] = {
@@ -1334,6 +1335,8 @@ TEST_F(HTMLPreloadScannerTest,
ScopedLazyImageLoadingForTest scoped_lazy_image_loading_for_test(true);
ScopedLazyImageLoadingMetadataFetchForTest
scoped_lazy_image_loading_metadata_fetch_for_test(true);
+ ScopedAutomaticLazyImageLoadingForTest
+ scoped_automatic_lazy_image_loading_for_test(false);
GetDocument().GetSettings()->SetLazyLoadEnabled(true);
RunSetUp(kViewportEnabled);
PreloadScannerTestCase test_cases[] = {
@@ -1393,7 +1396,6 @@ TEST_F(HTMLPreloadScannerTest, LazyLoadImage_DisableMetadataFetch) {
{true, true, "eager", true, false},
};
for (const auto& test_case : test_cases) {
- ScopedLazyImageLoadingForTest scoped_lazy_image_loading_for_test(true);
ScopedLazyImageLoadingMetadataFetchForTest
scoped_lazy_image_loading_metadata_fetch_for_test(
test_case.metadata_fetch_feature_enabled);
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 4e16dc0c425..cfd414d4e47 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
@@ -26,6 +26,10 @@
#include "third_party/blink/renderer/core/html/parser/html_resource_preloader.h"
#include <memory>
+
+#include "base/feature_list.h"
+#include "base/metrics/field_trial_params.h"
+#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_prescient_networking.h"
#include "third_party/blink/renderer/core/dom/document.h"
@@ -63,6 +67,10 @@ void HTMLResourcePreloader::Preload(std::unique_ptr<PreloadRequest> preload) {
PreconnectHost(preload.get());
return;
}
+
+ if (!AllowPreloadRequest(preload.get())) {
+ return;
+ }
// TODO(yoichio): Should preload if document is imported.
if (!document_->Loader())
return;
@@ -70,4 +78,62 @@ void HTMLResourcePreloader::Preload(std::unique_ptr<PreloadRequest> preload) {
preload->Start(document_);
}
+bool HTMLResourcePreloader::AllowPreloadRequest(PreloadRequest* preload) const {
+ if (!base::FeatureList::IsEnabled(features::kLightweightNoStatePrefetch))
+ return true;
+
+ if (!document_->IsPrefetchOnly())
+ return true;
+
+ // Don't fetch any other resources when in the HTML only arm of the
+ // experiment.
+ if (GetFieldTrialParamByFeatureAsBool(features::kLightweightNoStatePrefetch,
+ "html_only", false)) {
+ return false;
+ }
+
+ switch (preload->Importance()) {
+ case mojom::FetchImportanceMode::kImportanceHigh:
+ return true;
+ case mojom::FetchImportanceMode::kImportanceLow:
+ case mojom::FetchImportanceMode::kImportanceAuto:
+ break;
+ }
+
+ // When running lightweight prefetch, always skip image resources. Other
+ // resources are either classified into CSS (always fetched when not in the
+ // HTML only arm), JS (skip_script param), or other.
+ switch (preload->GetResourceType()) {
+ case ResourceType::kFont:
+ case ResourceType::kRaw:
+ case ResourceType::kSVGDocument:
+ case ResourceType::kXSLStyleSheet:
+ case ResourceType::kLinkPrefetch:
+ case ResourceType::kTextTrack:
+ case ResourceType::kImportResource:
+ case ResourceType::kAudio:
+ case ResourceType::kVideo:
+ case ResourceType::kManifest:
+ case ResourceType::kMock:
+ return !GetFieldTrialParamByFeatureAsBool(
+ features::kLightweightNoStatePrefetch, "skip_other", false);
+ case ResourceType::kImage:
+ return false;
+ case ResourceType::kCSSStyleSheet:
+ return true;
+ case ResourceType::kScript:
+ // We might skip all script.
+ if (GetFieldTrialParamByFeatureAsBool(
+ features::kLightweightNoStatePrefetch, "skip_script", false)) {
+ return false;
+ }
+
+ // Otherwise, we might skip async/deferred script.
+ return !GetFieldTrialParamByFeatureAsBool(
+ features::kLightweightNoStatePrefetch, "skip_async_script",
+ false) ||
+ preload->DeferOption() == FetchParameters::DeferOption::kNoDefer;
+ }
+}
+
} // namespace blink
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 f16100465c2..67cd7e546ec 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
@@ -53,6 +53,10 @@ class CORE_EXPORT HTMLResourcePreloader
void Preload(std::unique_ptr<PreloadRequest>) override;
private:
+ // Whether the request is allowed based on whether the doc is prefetch only
+ // and resource priority/type of |preload|.
+ bool AllowPreloadRequest(PreloadRequest* preload) const;
+
Member<Document> document_;
DISALLOW_COPY_AND_ASSIGN(HTMLResourcePreloader);
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_source_tracker.h b/chromium/third_party/blink/renderer/core/html/parser/html_source_tracker.h
index 50799bd95b2..1e87b08935e 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_source_tracker.h
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_source_tracker.h
@@ -29,7 +29,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/html/parser/html_token.h"
#include "third_party/blink/renderer/platform/text/segmented_string.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_srcset_parser.cc b/chromium/third_party/blink/renderer/core/html/parser/html_srcset_parser.cc
index 7c15d1033ae..69704027bfe 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_srcset_parser.cc
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_srcset_parser.cc
@@ -35,9 +35,9 @@
#include "third_party/blink/renderer/core/dom/document.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/use_counter.h"
#include "third_party/blink/renderer/core/html/parser/html_parser_idioms.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/json/json_values.h"
#include "third_party/blink/renderer/platform/loader/fetch/memory_cache.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_srcset_parser.h b/chromium/third_party/blink/renderer/core/html/parser/html_srcset_parser.h
index c694b066395..1270664c288 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_srcset_parser.h
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_srcset_parser.h
@@ -33,7 +33,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_PARSER_HTML_SRCSET_PARSER_H_
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/string_view.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
diff --git a/chromium/third_party/blink/renderer/core/html/parser/html_srcset_parser_test.cc b/chromium/third_party/blink/renderer/core/html/parser/html_srcset_parser_test.cc
index a94eb2e5c43..cc3aed6a9fe 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/html_srcset_parser_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/parser/html_srcset_parser_test.cc
@@ -169,7 +169,7 @@ TEST(HTMLSrcsetParserTest, Basic) {
test.srcset_input);
ASSERT_EQ(test.output_density, candidate.Density());
ASSERT_EQ(test.output_resource_width, candidate.GetResourceWidth());
- ASSERT_STREQ(test.output_url, candidate.ToString().Ascii().data());
+ ASSERT_EQ(test.output_url, candidate.ToString().Ascii());
}
}
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 e300375f122..d81933a4b70 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
@@ -64,7 +64,7 @@ class HTMLStackItem : public GarbageCollectedFinalized<HTMLStackItem> {
namespace_uri_(namespace_uri),
is_document_fragment_node_(false) {}
- Element* GetElement() const { return ToElement(node_.Get()); }
+ Element* GetElement() const { return To<Element>(node_.Get()); }
ContainerNode* GetNode() const { return node_.Get(); }
bool IsDocumentFragmentNode() const { return is_document_fragment_node_; }
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 2d3956ccfad..e27ad677177 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
@@ -32,7 +32,6 @@
#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_traversal.h"
-#include "third_party/blink/renderer/core/frame/use_counter.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/html_template_element.h"
@@ -52,6 +51,7 @@
#include "third_party/blink/renderer/platform/bindings/runtime_call_stats.h"
#include "third_party/blink/renderer/platform/bindings/v8_per_isolate_data.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/text/platform_locale.h"
#include "third_party/blink/renderer/platform/wtf/text/character_names.h"
@@ -2443,7 +2443,7 @@ void HTMLTreeBuilder::ProcessEndOfFile(AtomicHTMLToken* token) {
}
Element* el = tree_.OpenElements()->Top();
if (IsHTMLTextAreaElement(el))
- ToHTMLFormControlElement(el)->SetBlocksFormSubmission(true);
+ To<HTMLFormControlElement>(el)->SetBlocksFormSubmission(true);
tree_.OpenElements()->Pop();
DCHECK_NE(original_insertion_mode_, kTextMode);
SetInsertionMode(original_insertion_mode_);
diff --git a/chromium/third_party/blink/renderer/core/html/parser/input_stream_preprocessor.h b/chromium/third_party/blink/renderer/core/html/parser/input_stream_preprocessor.h
index 43a147f4ca2..29f5f9e5715 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/input_stream_preprocessor.h
+++ b/chromium/third_party/blink/renderer/core/html/parser/input_stream_preprocessor.h
@@ -30,7 +30,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/platform/text/segmented_string.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 83022796aeb..c9b3308bc3b 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
@@ -39,9 +39,14 @@ Resource* PreloadRequest::Start(Document* document) {
DCHECK(!url.ProtocolIsData());
ResourceRequest resource_request(url);
- resource_request.SetReferrerPolicy(referrer_policy_);
- if (referrer_source_ == kBaseUrlIsReferrer)
- resource_request.SetReferrerString(base_url_.StrippedForUseAsReferrer());
+ resource_request.SetReferrerPolicy(
+ referrer_policy_,
+ ResourceRequest::SetReferrerPolicyLocation::kPreloadRequestStart);
+ if (referrer_source_ == kBaseUrlIsReferrer) {
+ resource_request.SetReferrerString(
+ base_url_.StrippedForUseAsReferrer(),
+ ResourceRequest::SetReferrerStringLocation::kPreloadRequestStart);
+ }
resource_request.SetRequestContext(
ResourceFetcher::DetermineRequestContext(resource_type_, is_image_set_));
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 4894623aeb9..ad64c70ccf8 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,7 +8,7 @@
#include <memory>
#include "base/memory/ptr_util.h"
-#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-shared.h"
+#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.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/core/script/script.h"
@@ -18,7 +18,7 @@
#include "third_party/blink/renderer/platform/loader/fetch/integrity_metadata.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
#include "third_party/blink/renderer/platform/weborigin/security_policy.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/text_position.h"
namespace blink {
@@ -72,6 +72,8 @@ class CORE_EXPORT PreloadRequest {
Resource* Start(Document*);
void SetDefer(FetchParameters::DeferOption defer) { defer_ = defer; }
+ FetchParameters::DeferOption DeferOption() const { return defer_; }
+
void SetCharset(const String& charset) { charset_ = charset; }
void SetCrossOrigin(CrossOriginAttributeValue cross_origin) {
cross_origin_ = cross_origin;
diff --git a/chromium/third_party/blink/renderer/core/html/parser/pump_session.h b/chromium/third_party/blink/renderer/core/html/parser/pump_session.h
index 9fc3ec080f8..1c12ef922ac 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/pump_session.h
+++ b/chromium/third_party/blink/renderer/core/html/parser/pump_session.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_PARSER_PUMP_SESSION_H_
#include "third_party/blink/renderer/core/html/parser/nesting_level_incrementer.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/parser/text_resource_decoder_fuzzer.cc b/chromium/third_party/blink/renderer/core/html/parser/text_resource_decoder_fuzzer.cc
index 95139539220..344c455d589 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/text_resource_decoder_fuzzer.cc
+++ b/chromium/third_party/blink/renderer/core/html/parser/text_resource_decoder_fuzzer.cc
@@ -14,7 +14,7 @@ int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
static BlinkFuzzerTestSupport test_support = BlinkFuzzerTestSupport();
FuzzedDataProvider fuzzed_data(data, size);
TextResourceDecoderForFuzzing decoder(fuzzed_data);
- CString bytes = fuzzed_data.ConsumeRemainingBytes();
+ std::string bytes = fuzzed_data.ConsumeRemainingBytes();
decoder.Decode(bytes.data(), bytes.length());
decoder.Flush();
return 0;
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 dc66b5d01c8..3f8e39e424a 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
@@ -31,7 +31,6 @@
#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/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/html_param_element.h"
#include "third_party/blink/renderer/core/html/link_rel_attribute.h"
#include "third_party/blink/renderer/core/html/parser/html_document_parser.h"
@@ -44,6 +43,7 @@
#include "third_party/blink/renderer/core/loader/mixed_content_checker.h"
#include "third_party/blink/renderer/core/svg_names.h"
#include "third_party/blink/renderer/core/xlink_names.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/network/encoded_form_data.h"
#include "third_party/blink/renderer/platform/text/decode_escape_sequences.h"
#include "third_party/blink/renderer/platform/wtf/text/ascii_ctype.h"
diff --git a/chromium/third_party/blink/renderer/core/html/parser/xss_auditor.h b/chromium/third_party/blink/renderer/core/html/parser/xss_auditor.h
index 17c831f7633..022dbba1d6e 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/xss_auditor.h
+++ b/chromium/third_party/blink/renderer/core/html/parser/xss_auditor.h
@@ -33,7 +33,7 @@
#include "third_party/blink/renderer/platform/network/http_parsers.h"
#include "third_party/blink/renderer/platform/text/suffix_tree.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/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/text_encoding.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/parser/xss_auditor_delegate.cc b/chromium/third_party/blink/renderer/core/html/parser/xss_auditor_delegate.cc
index e5c87dd806a..dcd28b883bc 100644
--- a/chromium/third_party/blink/renderer/core/html/parser/xss_auditor_delegate.cc
+++ b/chromium/third_party/blink/renderer/core/html/parser/xss_auditor_delegate.cc
@@ -28,16 +28,17 @@
#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_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/loader/document_loader.h"
#include "third_party/blink/renderer/core/loader/frame_loader.h"
#include "third_party/blink/renderer/core/loader/ping_loader.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/json/json_values.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_error.h"
#include "third_party/blink/renderer/platform/network/encoded_form_data.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
+#include "third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h"
namespace blink {
@@ -94,7 +95,8 @@ scoped_refptr<EncodedFormData> XSSAuditorDelegate::GenerateViolationReport(
auto report_object = std::make_unique<JSONObject>();
report_object->SetObject("xss-report", std::move(report_details));
- return EncodedFormData::Create(report_object->ToJSONString().Utf8().data());
+ return EncodedFormData::Create(
+ StringUTF8Adaptor(report_object->ToJSONString()));
}
void XSSAuditorDelegate::DidBlockScript(const XSSInfo& xss_info) {
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 ab95ea8be14..8762ec57e16 100644
--- a/chromium/third_party/blink/renderer/core/html/plugin_document.cc
+++ b/chromium/third_party/blink/renderer/core/html/plugin_document.cc
@@ -34,7 +34,6 @@
#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/local_frame_view.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/html_body_element.h"
#include "third_party/blink/renderer/core/html/html_embed_element.h"
#include "third_party/blink/renderer/core/html/html_html_element.h"
@@ -45,6 +44,7 @@
#include "third_party/blink/renderer/core/loader/frame_loader.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/scheduler/public/scheduling_policy.h"
namespace blink {
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 bf97a2d4bd7..babc1411ae0 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
@@ -6,6 +6,7 @@
#include <utility>
#include "services/service_manager/public/cpp/interface_provider.h"
+#include "third_party/blink/public/mojom/referrer.mojom-blink.h"
#include "third_party/blink/renderer/bindings/core/v8/script_event_listener.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
@@ -36,7 +37,9 @@
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
+#include "third_party/blink/renderer/platform/weborigin/referrer.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"
namespace blink {
@@ -44,12 +47,20 @@ namespace blink {
HTMLPortalElement::HTMLPortalElement(
Document& document,
const base::UnguessableToken& portal_token,
- mojom::blink::PortalAssociatedPtr portal_ptr,
- mojom::blink::PortalClientAssociatedRequest portal_client_request)
+ mojo::AssociatedRemote<mojom::blink::Portal> remote_portal,
+ mojo::PendingAssociatedReceiver<mojom::blink::PortalClient>
+ portal_client_receiver)
: HTMLFrameOwnerElement(html_names::kPortalTag, document),
portal_token_(portal_token),
- portal_ptr_(std::move(portal_ptr)),
- portal_client_binding_(this, std::move(portal_client_request)) {}
+ remote_portal_(std::move(remote_portal)),
+ portal_client_receiver_(this, std::move(portal_client_receiver)) {
+ if (remote_portal_) {
+ // If the portal element hosts a predecessor from activation, it can be
+ // activated before being inserted into the DOM, and we need to keep track
+ // of it from creation.
+ DocumentPortals::From(GetDocument()).OnPortalInserted(this);
+ }
+}
HTMLPortalElement::~HTMLPortalElement() {}
@@ -58,9 +69,18 @@ void HTMLPortalElement::Trace(Visitor* visitor) {
visitor->Trace(portal_frame_);
}
+void HTMLPortalElement::ConsumePortal() {
+ if (portal_token_) {
+ DocumentPortals::From(GetDocument()).OnPortalRemoved(this);
+ portal_token_ = base::UnguessableToken();
+ }
+ remote_portal_.reset();
+ portal_client_receiver_.reset();
+}
+
void HTMLPortalElement::Navigate() {
KURL url = GetNonEmptyURLAttribute(html_names::kSrcAttr);
- if (!portal_ptr_ || url.IsEmpty())
+ if (!remote_portal_ || url.IsEmpty())
return;
if (!url.ProtocolIsInHTTPFamily()) {
@@ -71,16 +91,15 @@ void HTMLPortalElement::Navigate() {
return;
}
- portal_ptr_->Navigate(url);
-}
+ auto referrer_policy_to_use = ReferrerPolicyAttribute();
+ if (referrer_policy_to_use == network::mojom::ReferrerPolicy::kDefault)
+ referrer_policy_to_use = GetDocument().GetReferrerPolicy();
+ Referrer referrer = SecurityPolicy::GenerateReferrer(
+ referrer_policy_to_use, url, GetDocument().OutgoingReferrer());
+ auto mojo_referrer = mojom::blink::Referrer::New(
+ KURL(NullURL(), referrer.referrer), referrer.referrer_policy);
-void HTMLPortalElement::ConsumePortal() {
- if (portal_token_) {
- DocumentPortals::From(GetDocument()).OnPortalRemoved(this);
- portal_token_ = base::UnguessableToken();
- }
- portal_ptr_.reset();
- portal_client_binding_.Close();
+ remote_portal_->Navigate(url, std::move(mojo_referrer));
}
namespace {
@@ -147,7 +166,7 @@ ScriptPromise HTMLPortalElement::activate(ScriptState* script_state,
ExceptionState::kExecutionContext,
"HTMLPortalElement", "activate");
- if (!portal_ptr_) {
+ if (!remote_portal_) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidStateError,
"The HTMLPortalElement is not associated with a portal context.");
@@ -189,12 +208,12 @@ ScriptPromise HTMLPortalElement::activate(ScriptState* script_state,
// We also pass the ownership of the PortalPtr, which guarantees that the
// PortalPtr stays alive until the callback is called.
is_activating_ = true;
- auto* raw_portal_ptr = portal_ptr_.get();
- raw_portal_ptr->Activate(
+ auto* raw_remote_portal = remote_portal_.get();
+ raw_remote_portal->Activate(
std::move(data),
WTF::Bind(
[](HTMLPortalElement* portal,
- mojom::blink::PortalAssociatedPtr portal_ptr,
+ mojo::AssociatedRemote<mojom::blink::Portal>,
ScriptPromiseResolver* resolver, bool was_adopted) {
if (was_adopted)
portal->GetDocument().GetPage()->SetInsidePortal(true);
@@ -202,7 +221,7 @@ ScriptPromise HTMLPortalElement::activate(ScriptState* script_state,
portal->is_activating_ = false;
portal->ConsumePortal();
},
- WrapPersistent(this), std::move(portal_ptr_),
+ WrapPersistent(this), std::move(remote_portal_),
WrapPersistent(resolver)));
return promise;
}
@@ -223,7 +242,7 @@ void HTMLPortalElement::postMessage(ScriptState* script_state,
const ScriptValue& message,
const WindowPostMessageOptions* options,
ExceptionState& exception_state) {
- if (!portal_ptr_ || is_activating_) {
+ if (!remote_portal_ || is_activating_) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidStateError,
"The HTMLPortalElement is not associated with a portal context");
@@ -242,8 +261,8 @@ void HTMLPortalElement::postMessage(ScriptState* script_state,
if (exception_state.HadException())
return;
- portal_ptr_->PostMessageToGuest(std::move(transferable_message),
- target_origin);
+ remote_portal_->PostMessageToGuest(std::move(transferable_message),
+ target_origin);
}
EventListener* HTMLPortalElement::onmessage() {
@@ -266,7 +285,7 @@ void HTMLPortalElement::ForwardMessageFromGuest(
BlinkTransferableMessage message,
const scoped_refptr<const SecurityOrigin>& source_origin,
const scoped_refptr<const SecurityOrigin>& target_origin) {
- if (!portal_ptr_)
+ if (!remote_portal_)
return;
PortalPostMessageHelper::CreateAndDispatchMessageEvent(
@@ -274,7 +293,7 @@ void HTMLPortalElement::ForwardMessageFromGuest(
}
void HTMLPortalElement::DispatchLoadEvent() {
- if (!portal_ptr_)
+ if (!remote_portal_)
return;
DispatchLoad();
@@ -298,20 +317,20 @@ HTMLPortalElement::InsertionNotificationRequest HTMLPortalElement::InsertedInto(
return result;
}
- if (portal_ptr_) {
+ if (remote_portal_) {
// The interface is already bound if the HTMLPortalElement is adopting the
// predecessor.
portal_frame_ = GetDocument().GetFrame()->Client()->AdoptPortal(this);
- portal_ptr_.set_connection_error_handler(
+ remote_portal_.set_disconnect_handler(
WTF::Bind(&HTMLPortalElement::ConsumePortal, WrapWeakPersistent(this)));
- DocumentPortals::From(GetDocument()).OnPortalInserted(this);
} else {
- mojom::blink::PortalClientAssociatedPtr client;
- portal_client_binding_.Bind(mojo::MakeRequest(&client));
+ mojo::PendingAssociatedRemote<mojom::blink::PortalClient> client;
+ portal_client_receiver_.Bind(client.InitWithNewEndpointAndPassReceiver());
std::tie(portal_frame_, portal_token_) =
GetDocument().GetFrame()->Client()->CreatePortal(
- this, mojo::MakeRequest(&portal_ptr_), client.PassInterface());
- portal_ptr_.set_connection_error_handler(
+ this, remote_portal_.BindNewEndpointAndPassReceiver(),
+ std::move(client));
+ remote_portal_.set_disconnect_handler(
WTF::Bind(&HTMLPortalElement::ConsumePortal, WrapWeakPersistent(this)));
DocumentPortals::From(GetDocument()).OnPortalInserted(this);
Navigate();
@@ -344,6 +363,16 @@ void HTMLPortalElement::ParseAttribute(
return;
}
+ if (params.name == html_names::kReferrerpolicyAttr) {
+ referrer_policy_ = network::mojom::ReferrerPolicy::kDefault;
+ if (!params.new_value.IsNull()) {
+ SecurityPolicy::ReferrerPolicyFromString(
+ params.new_value, kDoNotSupportReferrerPolicyLegacyKeywords,
+ &referrer_policy_);
+ }
+ return;
+ }
+
struct {
const QualifiedName& name;
const AtomicString& event_name;
@@ -366,6 +395,11 @@ LayoutObject* HTMLPortalElement::CreateLayoutObject(const ComputedStyle& style,
return new LayoutIFrame(this);
}
+void HTMLPortalElement::DisconnectContentFrame() {
+ HTMLFrameOwnerElement::DisconnectContentFrame();
+ ConsumePortal();
+}
+
void HTMLPortalElement::AttachLayoutTree(AttachContext& context) {
HTMLFrameOwnerElement::AttachLayoutTree(context);
@@ -373,4 +407,8 @@ void HTMLPortalElement::AttachLayoutTree(AttachContext& context) {
SetEmbeddedContentView(ContentFrame()->View());
}
+network::mojom::ReferrerPolicy HTMLPortalElement::ReferrerPolicyAttribute() {
+ return referrer_policy_;
+}
+
} // namespace blink
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 296f102267d..32fb107579b 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
@@ -6,7 +6,9 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_PORTAL_HTML_PORTAL_ELEMENT_H_
#include "base/unguessable_token.h"
-#include "mojo/public/cpp/bindings/associated_binding.h"
+#include "mojo/public/cpp/bindings/associated_receiver.h"
+#include "mojo/public/cpp/bindings/associated_remote.h"
+#include "mojo/public/cpp/bindings/pending_associated_receiver.h"
#include "third_party/blink/public/mojom/portal/portal.mojom-blink.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
#include "third_party/blink/renderer/core/core_export.h"
@@ -33,9 +35,9 @@ class CORE_EXPORT HTMLPortalElement : public HTMLFrameOwnerElement,
explicit HTMLPortalElement(
Document& document,
const base::UnguessableToken& portal_token = base::UnguessableToken(),
- mojom::blink::PortalAssociatedPtr portal_ptr = nullptr,
- mojom::blink::PortalClientAssociatedRequest portal_client_request =
- nullptr);
+ mojo::AssociatedRemote<mojom::blink::Portal> remote_portal = {},
+ mojo::PendingAssociatedReceiver<mojom::blink::PortalClient>
+ portal_client_receiver = {});
~HTMLPortalElement() override;
// ScriptWrappable overrides.
@@ -72,15 +74,15 @@ class CORE_EXPORT HTMLPortalElement : public HTMLFrameOwnerElement,
bool IsActivating() { return is_activating_; }
- private:
- // Navigates the portal to |url_|.
- void Navigate();
-
// Consumes the portal interface. When a Portal is activated, or if the
// renderer receives a connection error, this function will gracefully
// terminate the portal interface.
void ConsumePortal();
+ private:
+ // Navigates the portal to |url_|.
+ void Navigate();
+
// Node overrides
InsertionNotificationRequest InsertedInto(ContainerNode&) override;
void RemovedFrom(ContainerNode&) override;
@@ -91,10 +93,12 @@ class CORE_EXPORT HTMLPortalElement : public HTMLFrameOwnerElement,
LayoutObject* CreateLayoutObject(const ComputedStyle&, LegacyLayout) override;
// HTMLFrameOwnerElement overrides
+ void DisconnectContentFrame() override;
ParsedFeaturePolicy ConstructContainerPolicy(Vector<String>*) const override {
return ParsedFeaturePolicy();
}
void AttachLayoutTree(AttachContext& context) override;
+ network::mojom::ReferrerPolicy ReferrerPolicyAttribute() override;
// Uniquely identifies the portal, this token is used by the browser process
// to reference this portal when communicating with the renderer.
@@ -106,8 +110,11 @@ class CORE_EXPORT HTMLPortalElement : public HTMLFrameOwnerElement,
// right before the promise returned by activate() is resolved or rejected.
bool is_activating_ = false;
- mojom::blink::PortalAssociatedPtr portal_ptr_;
- mojo::AssociatedBinding<mojom::blink::PortalClient> portal_client_binding_;
+ network::mojom::ReferrerPolicy referrer_policy_ =
+ network::mojom::ReferrerPolicy::kDefault;
+
+ mojo::AssociatedRemote<mojom::blink::Portal> remote_portal_;
+ mojo::AssociatedReceiver<mojom::blink::PortalClient> portal_client_receiver_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/portal/html_portal_element.idl b/chromium/third_party/blink/renderer/core/html/portal/html_portal_element.idl
index cb1b02fc1ff..b71a0ab9e6f 100644
--- a/chromium/third_party/blink/renderer/core/html/portal/html_portal_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/portal/html_portal_element.idl
@@ -7,6 +7,8 @@
[Exposed=Window, HTMLConstructor, RuntimeEnabled=Portals]
interface HTMLPortalElement : HTMLElement {
[CEReactions, Reflect, URL, RaisesException=Setter] attribute URLString src;
+ [CEReactions, Reflect, ReflectOnly=("","no-referrer","origin","no-referrer-when-downgrade","origin-when-cross-origin","unsafe-url"), ReflectMissing="", ReflectInvalid=""] attribute DOMString referrerPolicy;
+
[CallWith=ScriptState] Promise<void> activate(optional PortalActivateOptions options);
[CallWith=ScriptState, RaisesException] void postMessage(any message, DOMString targetOrigin,
optional sequence<object> transfer = []);
diff --git a/chromium/third_party/blink/renderer/core/html/portal/portal_post_message_helper.h b/chromium/third_party/blink/renderer/core/html/portal/portal_post_message_helper.h
index 8a6a24782f5..9eac28b500b 100644
--- a/chromium/third_party/blink/renderer/core/html/portal/portal_post_message_helper.h
+++ b/chromium/third_party/blink/renderer/core/html/portal/portal_post_message_helper.h
@@ -7,7 +7,7 @@
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/resources/controls_refresh.css b/chromium/third_party/blink/renderer/core/html/resources/controls_refresh.css
new file mode 100644
index 00000000000..2cbfb1f20db
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/html/resources/controls_refresh.css
@@ -0,0 +1,81 @@
+/* Copyright 2019 The Chromium Authors. All rights reserved.
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+/* These styles adjust the default styling for HTML elements as defined in
+ * core/html/resources/html.css in order to provide an updated style when
+ * using the refreshed controls UI.
+ */
+
+input,
+select,
+textarea {
+ background-color: #ffffff;
+ border-color: #cecece;
+}
+
+input:hover,
+select:hover,
+textarea:hover {
+ border-color: #9d9d9d;
+}
+
+input:disabled,
+select:disabled,
+textarea:disabled {
+ background-color: #ffffff;
+ border-color: #c5c5c5;
+}
+
+input[type="button" i],
+input[type="submit" i],
+input[type="reset" i],
+input[type="color" i],
+input[type="file" i]::-webkit-file-upload-button,
+button {
+ background-color: #efefef;
+ border-color: #cecece;
+}
+
+input[type="button" i]:disabled,
+input[type="submit" i]:disabled,
+input[type="reset" i]:disabled,
+input[type="color" i]:disabled,
+input[type="file" i]:disabled::-webkit-file-upload-button,
+button:disabled {
+ border-color: #c5c5c5;
+}
+
+input[type="range" i] {
+ color: #101010;
+}
+
+input[type="range" i]:disabled {
+ color: #c5c5c5;
+}
+
+meter::-webkit-meter-bar {
+ background: #efefef;
+ border-width: 1px;
+ border-style: solid;
+ border-color: #cecece;
+ border-radius: 2px;
+ box-sizing: border-box;
+ padding: 1px;
+}
+
+meter::-webkit-meter-optimum-value {
+ background: #107c10;
+ border-radius: 1px 0px 0px 1px;
+}
+
+meter::-webkit-meter-suboptimum-value {
+ background: #ffb900;
+ border-radius: 1px 0px 0px 1px;
+}
+
+meter::-webkit-meter-even-less-good-value {
+ background: #d83b01;
+ border-radius: 1px 0px 0px 1px;
+}
diff --git a/chromium/third_party/blink/renderer/core/html/resources/forced_colors.css b/chromium/third_party/blink/renderer/core/html/resources/forced_colors.css
new file mode 100644
index 00000000000..c04c9386e07
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/html/resources/forced_colors.css
@@ -0,0 +1,145 @@
+/* Copyright 2019 The Chromium Authors. All rights reserved.
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+/* These forced colors mode styles override the default styling for HTML
+ * elements as defined in core/html/resources/html.css when forced colors mode
+ * is enabled.
+ */
+
+@media forced-colors {
+ body {
+ background-color: Window;
+ color: WindowText;
+ }
+
+ :focus {
+ outline-color: Highlight;
+ }
+
+ a:link,
+ a:-webkit-any-link:active {
+ color: LinkText;
+ }
+
+ a:visited {
+ color: VisitedText;
+ }
+
+ fieldset {
+ border-color: WindowText;
+ }
+
+ ::placeholder {
+ color: GrayText;
+ }
+
+ input,
+ textarea {
+ background: Window;
+ border-color: ButtonText;
+ color: WindowText;
+ }
+
+ input:hover,
+ textarea:hover,
+ input[type="file"]:hover::-webkit-file-upload-button,
+ input:focus,
+ textarea:focus {
+ border-color: Highlight;
+ }
+
+ input[type="text"]:disabled,
+ input[type="password"]:disabled,
+ input[type="email"]:disabled,
+ input[type="number"]:disabled,
+ input[type="tel"]:disabled,
+ input[type="url"]:disabled,
+ input[type="search"]:disabled,
+ input[type="date"]:disabled,
+ input[type="month"]:disabled,
+ input[type="week"]:disabled,
+ input[type="time"]:disabled,
+ input[type="datetime-local"]:disabled,
+ textarea:disabled {
+ background-color: ButtonFace;
+ border-color: GrayText;
+ color: GrayText;
+ }
+
+ input::-webkit-calendar-picker-indicator {
+ background-color: ButtonFace;
+ color: ButtonText;
+ }
+
+ input[type="color"]:disabled {
+ border-color: GrayText;
+ }
+
+ button,
+ input[type="button"],
+ input[type="submit"],
+ input[type="reset"],
+ input[type="file"]::-webkit-file-upload-button {
+ border-color: ButtonText;
+ background: ButtonFace;
+ color: ButtonText;
+ }
+
+ button:hover,
+ input[type="button"]:hover,
+ input[type="submit"]:hover,
+ input[type="reset"]:hover,
+ button:focus,
+ input[type="button"]:focus,
+ input[type="submit"]:focus,
+ input[type="reset"]:focus {
+ border-color: Highlight;
+ }
+
+ button:disabled,
+ input[type="button"]:disabled,
+ input[type="submit"]:disabled,
+ input[type="reset"]:disabled {
+ border-color: GrayText;
+ color: GrayText;
+ }
+
+ select {
+ background: Window;
+ border-color: WindowText;
+ color: WindowText;
+ }
+
+ select:hover {
+ border-color: Highlight;
+ }
+
+ select:focus {
+ border-color: Highlight;
+ }
+
+ select:disabled {
+ border-color: GrayText;
+ color: GrayText;
+ }
+
+ progress::-webkit-progress-bar {
+ background: ButtonFace;
+ }
+
+ progress::-webkit-progress-value {
+ background: Highlight;
+ }
+
+ meter::-webkit-meter-bar {
+ background: ButtonFace;
+ }
+
+ meter::-webkit-meter-even-less-good-value,
+ meter::-webkit-meter-optimum-value,
+ meter::-webkit-meter-suboptimal-value {
+ background: Highlight;
+ }
+}
diff --git a/chromium/third_party/blink/renderer/core/html/resources/html.css b/chromium/third_party/blink/renderer/core/html/resources/html.css
index 791cfeff8e5..5c5b6501fe4 100644
--- a/chromium/third_party/blink/renderer/core/html/resources/html.css
+++ b/chromium/third_party/blink/renderer/core/html/resources/html.css
@@ -678,6 +678,9 @@ datalist {
area {
display: inline;
+}
+
+area:-webkit-any-link {
cursor: pointer;
}
@@ -1013,7 +1016,7 @@ nobr {
/* states */
:-internal-spatial-navigation-interest {
- outline: auto 1px -webkit-focus-ring-color;
+ outline: auto 1px -webkit-focus-ring-color !important;
box-shadow: none !important
}
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 d395dc2165e..97728d05dde 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
@@ -34,7 +34,7 @@ TEST_F(ProgressShadowElementTest, LayoutObjectIsNeeded) {
ToHTMLProgressElement(GetDocument().getElementById("prog"));
ASSERT_TRUE(progress);
- Element* shadow_element = ToElement(progress->GetShadowRoot()->firstChild());
+ auto* shadow_element = To<Element>(progress->GetShadowRoot()->firstChild());
ASSERT_TRUE(shadow_element);
GetDocument().View()->UpdateAllLifecyclePhases(
diff --git a/chromium/third_party/blink/renderer/core/html/text_document.cc b/chromium/third_party/blink/renderer/core/html/text_document.cc
index 26cd7ce9f9a..7b7db8d0963 100644
--- a/chromium/third_party/blink/renderer/core/html/text_document.cc
+++ b/chromium/third_party/blink/renderer/core/html/text_document.cc
@@ -24,9 +24,9 @@
#include "third_party/blink/renderer/core/html/text_document.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/parser/text_document_parser.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/time_ranges.cc b/chromium/third_party/blink/renderer/core/html/time_ranges.cc
index 66416222ee1..c1febee8331 100644
--- a/chromium/third_party/blink/renderer/core/html/time_ranges.cc
+++ b/chromium/third_party/blink/renderer/core/html/time_ranges.cc
@@ -25,8 +25,6 @@
#include "third_party/blink/renderer/core/html/time_ranges.h"
-#include <math.h>
-
#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/heap/heap.h"
@@ -44,36 +42,7 @@ TimeRanges::TimeRanges(const blink::WebTimeRanges& web_ranges) {
}
TimeRanges* TimeRanges::Copy() const {
- auto* new_session = MakeGarbageCollected<TimeRanges>();
-
- wtf_size_t size = ranges_.size();
- for (wtf_size_t i = 0; i < size; i++)
- new_session->Add(ranges_[i].start_, ranges_[i].end_);
-
- return new_session;
-}
-
-void TimeRanges::Invert() {
- auto* inverted = MakeGarbageCollected<TimeRanges>();
- double pos_inf = std::numeric_limits<double>::infinity();
- double neg_inf = -std::numeric_limits<double>::infinity();
-
- if (!ranges_.size()) {
- inverted->Add(neg_inf, pos_inf);
- } else {
- double start = ranges_.front().start_;
- if (start != neg_inf)
- inverted->Add(neg_inf, start);
-
- for (wtf_size_t index = 0; index + 1 < ranges_.size(); ++index)
- inverted->Add(ranges_[index].end_, ranges_[index + 1].start_);
-
- double end = ranges_.back().end_;
- if (end != pos_inf)
- inverted->Add(end, pos_inf);
- }
-
- ranges_.swap(inverted->ranges_);
+ return MakeGarbageCollected<TimeRanges>(ranges_);
}
void TimeRanges::IntersectWith(const TimeRanges* other) {
@@ -82,23 +51,12 @@ void TimeRanges::IntersectWith(const TimeRanges* other) {
if (other == this)
return;
- TimeRanges* inverted_other = other->Copy();
- inverted_other->Invert();
-
- Invert();
- UnionWith(inverted_other);
- Invert();
+ ranges_.IntersectWith(other->ranges_);
}
void TimeRanges::UnionWith(const TimeRanges* other) {
DCHECK(other);
- TimeRanges* unioned = Copy();
- for (wtf_size_t index = 0; index < other->ranges_.size(); ++index) {
- const Range& range = other->ranges_[index];
- unioned->Add(range.start_, range.end_);
- }
-
- ranges_.swap(unioned->ranges_);
+ ranges_.UnionWith(other->ranges_);
}
double TimeRanges::start(unsigned index,
@@ -109,7 +67,7 @@ double TimeRanges::start(unsigned index,
ExceptionMessages::IndexExceedsMaximumBound("index", index, length()));
return 0;
}
- return ranges_[index].start_;
+ return ranges_.Data()[index].start;
}
double TimeRanges::end(unsigned index, ExceptionState& exception_state) const {
@@ -119,94 +77,20 @@ double TimeRanges::end(unsigned index, ExceptionState& exception_state) const {
ExceptionMessages::IndexExceedsMaximumBound("index", index, length()));
return 0;
}
- return ranges_[index].end_;
+ return ranges_.Data()[index].end;
}
void TimeRanges::Add(double start, double end) {
- DCHECK_LE(start, end);
- unsigned overlapping_arc_index;
- Range added_range(start, end);
-
- // For each present range check if we need to:
- // - merge with the added range, in case we are overlapping or contiguous
- // - Need to insert in place, we we are completely, not overlapping and not
- // contiguous in between two ranges.
- //
- // TODO: Given that we assume that ranges are correctly ordered, this could be
- // optimized.
-
- for (overlapping_arc_index = 0; overlapping_arc_index < ranges_.size();
- overlapping_arc_index++) {
- if (added_range.IsOverlappingRange(ranges_[overlapping_arc_index]) ||
- added_range.IsContiguousWithRange(ranges_[overlapping_arc_index])) {
- // We need to merge the addedRange and that range.
- added_range = added_range.UnionWithOverlappingOrContiguousRange(
- ranges_[overlapping_arc_index]);
- ranges_.EraseAt(overlapping_arc_index);
- overlapping_arc_index--;
- } else {
- // Check the case for which there is no more to do
- if (!overlapping_arc_index) {
- if (added_range.IsBeforeRange(ranges_[0])) {
- // First index, and we are completely before that range (and not
- // contiguous, nor overlapping). We just need to be inserted here.
- break;
- }
- } else {
- if (ranges_[overlapping_arc_index - 1].IsBeforeRange(added_range) &&
- added_range.IsBeforeRange(ranges_[overlapping_arc_index])) {
- // We are exactly after the current previous range, and before the
- // current range, while not overlapping with none of them. Insert
- // here.
- break;
- }
- }
- }
- }
-
- // Now that we are sure we don't overlap with any range, just add it.
- ranges_.insert(overlapping_arc_index, added_range);
+ ranges_.Add(start, end);
}
bool TimeRanges::Contain(double time) const {
- for (unsigned n = 0; n < length(); n++) {
- if (time >= start(n, IGNORE_EXCEPTION_FOR_TESTING) &&
- time <= end(n, IGNORE_EXCEPTION_FOR_TESTING))
- return true;
- }
- return false;
+ return ranges_.Contain(time);
}
double TimeRanges::Nearest(double new_playback_position,
double current_playback_position) const {
- unsigned count = length();
- double best_match = 0;
- double best_delta = std::numeric_limits<double>::infinity();
- for (unsigned ndx = 0; ndx < count; ndx++) {
- double start_time = start(ndx, IGNORE_EXCEPTION_FOR_TESTING);
- double end_time = end(ndx, IGNORE_EXCEPTION_FOR_TESTING);
- if (new_playback_position >= start_time &&
- new_playback_position <= end_time)
- return new_playback_position;
-
- double delta, match;
- if (new_playback_position < start_time) {
- delta = start_time - new_playback_position;
- match = start_time;
- } else {
- delta = new_playback_position - end_time;
- match = end_time;
- }
-
- if (delta < best_delta ||
- (delta == best_delta &&
- std::abs(current_playback_position - match) <
- std::abs(current_playback_position - best_match))) {
- best_delta = delta;
- best_match = match;
- }
- }
- return best_match;
+ return ranges_.Nearest(new_playback_position, current_playback_position);
}
} // namespace blink
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 50ac7b59407..96683445826 100644
--- a/chromium/third_party/blink/renderer/core/html/time_ranges.h
+++ b/chromium/third_party/blink/renderer/core/html/time_ranges.h
@@ -30,10 +30,7 @@
#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"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
-#include "third_party/blink/renderer/platform/wtf/vector.h"
-
-#include <algorithm>
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -43,47 +40,6 @@ class CORE_EXPORT TimeRanges final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
- // We consider all the Ranges to be semi-bounded as follow: [start, end[
- struct Range {
- DISALLOW_NEW();
-
- public:
- Range() = default;
- Range(double start, double end) {
- start_ = start;
- end_ = end;
- }
- double start_;
- double end_;
-
- inline bool isPointInRange(double point) const {
- return start_ <= point && point < end_;
- }
-
- inline bool IsOverlappingRange(const Range& range) const {
- return isPointInRange(range.start_) || isPointInRange(range.end_) ||
- range.isPointInRange(start_);
- }
-
- inline bool IsContiguousWithRange(const Range& range) const {
- return range.start_ == end_ || range.end_ == start_;
- }
-
- inline Range UnionWithOverlappingOrContiguousRange(
- const Range& range) const {
- Range ret;
-
- ret.start_ = std::min(start_, range.start_);
- ret.end_ = std::max(end_, range.end_);
-
- return ret;
- }
-
- inline bool IsBeforeRange(const Range& range) const {
- return range.start_ >= end_;
- }
- };
-
TimeRanges() = default;
TimeRanges(double start, double end);
TimeRanges(const WebTimeRanges&);
@@ -92,7 +48,7 @@ class CORE_EXPORT TimeRanges final : public ScriptWrappable {
void IntersectWith(const TimeRanges*);
void UnionWith(const TimeRanges*);
- unsigned length() const { return ranges_.size(); }
+ unsigned length() const { return static_cast<unsigned>(ranges_.size()); }
double start(unsigned index, ExceptionState&) const;
double end(unsigned index, ExceptionState&) const;
@@ -104,9 +60,7 @@ class CORE_EXPORT TimeRanges final : public ScriptWrappable {
double current_playback_position) const;
private:
- void Invert();
-
- Vector<Range> ranges_;
+ WebTimeRanges ranges_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/html/time_ranges.idl b/chromium/third_party/blink/renderer/core/html/time_ranges.idl
index f153bee3dd6..1f2aa210e2f 100644
--- a/chromium/third_party/blink/renderer/core/html/time_ranges.idl
+++ b/chromium/third_party/blink/renderer/core/html/time_ranges.idl
@@ -25,6 +25,7 @@
// https://html.spec.whatwg.org/C/#time-ranges
+[Exposed=Window]
interface TimeRanges {
readonly attribute unsigned long length;
[RaisesException] double start(unsigned long index);
diff --git a/chromium/third_party/blink/renderer/core/html/track/automatic_track_selection.h b/chromium/third_party/blink/renderer/core/html/track/automatic_track_selection.h
index f5381e4f8d0..5d02a626468 100644
--- a/chromium/third_party/blink/renderer/core/html/track/automatic_track_selection.h
+++ b/chromium/third_party/blink/renderer/core/html/track/automatic_track_selection.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/html/track/text_track_kind_user_preference.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 52747a14a1b..66efed10dea 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
@@ -163,7 +163,7 @@ void HTMLTrackElement::ScheduleLoad() {
// 4. Run the remainder of these steps in parallel, allowing whatever caused
// these steps to run to continue.
- load_timer_.StartOneShot(TimeDelta(), FROM_HERE);
+ load_timer_.StartOneShot(base::TimeDelta(), FROM_HERE);
// 5. Top: Await a stable state. The synchronous section consists of the
// following steps. (The steps in the synchronous section are marked with [X])
diff --git a/chromium/third_party/blink/renderer/core/html/track/html_track_element.idl b/chromium/third_party/blink/renderer/core/html/track/html_track_element.idl
index 79bd122a7b8..a6d32960e94 100644
--- a/chromium/third_party/blink/renderer/core/html/track/html_track_element.idl
+++ b/chromium/third_party/blink/renderer/core/html/track/html_track_element.idl
@@ -25,8 +25,10 @@
// https://html.spec.whatwg.org/C/#the-track-element
-[HTMLConstructor]
-interface HTMLTrackElement : HTMLElement {
+[
+ Exposed=Window,
+ HTMLConstructor
+] interface HTMLTrackElement : HTMLElement {
[CEReactions] attribute DOMString kind;
[CEReactions, Reflect, URL, RaisesException=Setter] attribute URLString src;
[CEReactions, Reflect] attribute DOMString srclang;
diff --git a/chromium/third_party/blink/renderer/core/html/track/text_track.idl b/chromium/third_party/blink/renderer/core/html/track/text_track.idl
index 1c4156b950c..a4268f5526e 100644
--- a/chromium/third_party/blink/renderer/core/html/track/text_track.idl
+++ b/chromium/third_party/blink/renderer/core/html/track/text_track.idl
@@ -28,6 +28,7 @@
enum TextTrackMode { "disabled", "hidden", "showing" };
enum TextTrackKind { "subtitles", "captions", "descriptions", "chapters", "metadata" };
+[Exposed=Window]
interface TextTrack : EventTarget {
readonly attribute TextTrackKind kind;
readonly attribute DOMString label;
diff --git a/chromium/third_party/blink/renderer/core/html/track/text_track_cue.idl b/chromium/third_party/blink/renderer/core/html/track/text_track_cue.idl
index 6cdef694cc4..7839d8873db 100644
--- a/chromium/third_party/blink/renderer/core/html/track/text_track_cue.idl
+++ b/chromium/third_party/blink/renderer/core/html/track/text_track_cue.idl
@@ -25,6 +25,7 @@
// https://html.spec.whatwg.org/C/#texttrackcue
+[Exposed=Window]
interface TextTrackCue : EventTarget {
readonly attribute TextTrack? track;
diff --git a/chromium/third_party/blink/renderer/core/html/track/text_track_cue_list.idl b/chromium/third_party/blink/renderer/core/html/track/text_track_cue_list.idl
index af3abb92ab1..a355f89f299 100644
--- a/chromium/third_party/blink/renderer/core/html/track/text_track_cue_list.idl
+++ b/chromium/third_party/blink/renderer/core/html/track/text_track_cue_list.idl
@@ -25,6 +25,7 @@
// https://html.spec.whatwg.org/C/#texttrackcuelist
+[Exposed=Window]
interface TextTrackCueList {
readonly attribute unsigned long length;
getter TextTrackCue (unsigned long index);
diff --git a/chromium/third_party/blink/renderer/core/html/track/text_track_list.idl b/chromium/third_party/blink/renderer/core/html/track/text_track_list.idl
index d781e2a6b47..2912d0cfa6a 100644
--- a/chromium/third_party/blink/renderer/core/html/track/text_track_list.idl
+++ b/chromium/third_party/blink/renderer/core/html/track/text_track_list.idl
@@ -25,6 +25,7 @@
// https://html.spec.whatwg.org/C/#texttracklist
+[Exposed=Window]
interface TextTrackList : EventTarget {
readonly attribute unsigned long length;
getter TextTrack (unsigned long index);
diff --git a/chromium/third_party/blink/renderer/core/html/track/track_event.idl b/chromium/third_party/blink/renderer/core/html/track/track_event.idl
index 4bf135ebc9d..78dd8b7b2d8 100644
--- a/chromium/third_party/blink/renderer/core/html/track/track_event.idl
+++ b/chromium/third_party/blink/renderer/core/html/track/track_event.idl
@@ -26,6 +26,7 @@
// https://html.spec.whatwg.org/C/#the-trackevent-interface
[
+ Exposed=Window,
Constructor(DOMString type, optional TrackEventInit eventInitDict)
] interface TrackEvent : Event {
readonly attribute (VideoTrack or AudioTrack or TextTrack)? track;
diff --git a/chromium/third_party/blink/renderer/core/html/track/vtt/buffered_line_reader.h b/chromium/third_party/blink/renderer/core/html/track/vtt/buffered_line_reader.h
index 37271cfe82c..bdbd338e565 100644
--- a/chromium/third_party/blink/renderer/core/html/track/vtt/buffered_line_reader.h
+++ b/chromium/third_party/blink/renderer/core/html/track/vtt/buffered_line_reader.h
@@ -34,7 +34,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/text/segmented_string.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/track/vtt/buffered_line_reader_test.cc b/chromium/third_party/blink/renderer/core/html/track/vtt/buffered_line_reader_test.cc
index 1ca85898fa7..9e06b5e2d4e 100644
--- a/chromium/third_party/blink/renderer/core/html/track/vtt/buffered_line_reader_test.cc
+++ b/chromium/third_party/blink/renderer/core/html/track/vtt/buffered_line_reader_test.cc
@@ -33,7 +33,6 @@
#include "base/stl_util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/platform/wtf/text/character_names.h"
-#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
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 b45190bcad6..04897fe44ac 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
@@ -37,7 +37,6 @@
#include "third_party/blink/renderer/core/dom/events/event.h"
#include "third_party/blink/renderer/core/dom/node_traversal.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_div_element.h"
#include "third_party/blink/renderer/core/html/track/text_track.h"
#include "third_party/blink/renderer/core/html/track/text_track_cue_list.h"
@@ -49,6 +48,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/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/text/bidi_resolver.h"
#include "third_party/blink/renderer/platform/text/text_run_iterator.h"
@@ -258,8 +258,8 @@ VTTCue::~VTTCue() = default;
#ifndef NDEBUG
String VTTCue::ToString() const {
return String::Format("%p id=%s interval=%f-->%f cue=%s)", this,
- id().Utf8().data(), startTime(), endTime(),
- text().Utf8().data());
+ id().Utf8().c_str(), startTime(), endTime(),
+ text().Utf8().c_str());
}
#endif
@@ -786,7 +786,7 @@ void VTTCue::UpdatePastAndFutureNodes(double movie_time) {
child_vtt_element->SetIsPastNode(is_past_node);
// Make an elemenet id match a cue id for style matching purposes.
if (!id().IsEmpty())
- ToElement(child).SetIdAttribute(id());
+ To<Element>(child).SetIdAttribute(id());
}
}
}
@@ -1129,6 +1129,13 @@ void VTTCue::ApplyUserOverrideCSSProperties() {
SetInlineStylePropertyIfNotEmpty(*cue_background_box_,
CSSPropertyID::kFontSize,
settings->GetTextTrackTextSize());
+ SetInlineStylePropertyIfNotEmpty(*display_tree_,
+ CSSPropertyID::kBackgroundColor,
+ settings->GetTextTrackWindowColor());
+ SetInlineStylePropertyIfNotEmpty(*display_tree_, CSSPropertyID::kPadding,
+ settings->GetTextTrackWindowPadding());
+ SetInlineStylePropertyIfNotEmpty(*display_tree_, CSSPropertyID::kBorderRadius,
+ settings->GetTextTrackWindowRadius());
}
ExecutionContext* VTTCue::GetExecutionContext() const {
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 f4eed44550c..77fa383f84e 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
@@ -32,7 +32,7 @@
#include "third_party/blink/renderer/core/html/track/text_track_cue.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_cue.idl b/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_cue.idl
index 060ab7722ba..10fe378eba0 100644
--- a/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_cue.idl
+++ b/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_cue.idl
@@ -36,6 +36,7 @@ enum DirectionSetting { "" /* horizontal */, "rl", "lr" };
enum AlignSetting { "start", "center", "end", "left", "right" };
[
+ Exposed=Window,
Constructor(double startTime, double endTime, DOMString text),
ConstructorCallWith=Document
] interface VTTCue : TextTrackCue {
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 a2f40ad0d4a..970eb19ca0e 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
@@ -33,11 +33,11 @@
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/processing_instruction.h"
#include "third_party/blink/renderer/core/dom/text.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/track/vtt/vtt_element.h"
#include "third_party/blink/renderer/core/html/track/vtt/vtt_region.h"
#include "third_party/blink/renderer/core/html/track/vtt/vtt_scanner.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/loader/fetch/text_resource_decoder_options.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/text/segmented_string.h"
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 28fe0d2aabf..98cd16e7134 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
@@ -69,7 +69,7 @@ constexpr bool kDefaultScroll = false;
constexpr float kLineHeight = 5.33;
// Default scrolling animation time period (s).
-constexpr TimeDelta kScrollTime = TimeDelta::FromMilliseconds(433);
+constexpr base::TimeDelta kScrollTime = base::TimeDelta::FromMilliseconds(433);
bool IsNonPercentage(double value,
const char* method,
@@ -401,7 +401,8 @@ void VTTRegion::StartTimer() {
if (scroll_timer_.IsActive())
return;
- TimeDelta duration = IsScrollingRegion() ? kScrollTime : TimeDelta();
+ base::TimeDelta duration =
+ IsScrollingRegion() ? kScrollTime : base::TimeDelta();
scroll_timer_.StartOneShot(duration, FROM_HERE);
}
diff --git a/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_region.idl b/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_region.idl
index e764131cfd1..e2cf419cc0f 100644
--- a/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_region.idl
+++ b/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_region.idl
@@ -28,6 +28,7 @@
enum ScrollSetting { "" /* none */, "up" };
[
+ Exposed=Window,
Constructor,
RuntimeEnabled=WebVTTRegions
] interface VTTRegion {
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 a84847617d5..58f92508c73 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
@@ -32,7 +32,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/parsing_utilities.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
diff --git a/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_token.h b/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_token.h
index 677128e3ab6..9c359834795 100644
--- a/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_token.h
+++ b/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_token.h
@@ -31,7 +31,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_HTML_TRACK_VTT_VTT_TOKEN_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_TRACK_VTT_VTT_TOKEN_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_tokenizer.h b/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_tokenizer.h
index 9f98bf66d40..3a1f98450fb 100644
--- a/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_tokenizer.h
+++ b/chromium/third_party/blink/renderer/core/html/track/vtt/vtt_tokenizer.h
@@ -34,7 +34,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/html/parser/input_stream_preprocessor.h"
#include "third_party/blink/renderer/core/html/track/vtt/vtt_token.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 620fd34a356..034129f0f3a 100644
--- a/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap.cc
+++ b/chromium/third_party/blink/renderer/core/imagebitmap/image_bitmap.cc
@@ -16,13 +16,13 @@
#include "third_party/blink/renderer/core/html/canvas/image_data.h"
#include "third_party/blink/renderer/core/html/media/html_video_element.h"
#include "third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.h"
-#include "third_party/blink/renderer/platform/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/graphics/canvas_color_params.h"
#include "third_party/blink/renderer/platform/graphics/canvas_resource_provider.h"
#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/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/scheduler/public/worker_pool.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkImageInfo.h"
#include "third_party/skia/include/core/SkSurface.h"
@@ -586,16 +586,17 @@ ImageBitmap::ImageBitmap(HTMLVideoElement* video,
if (DstBufferSizeHasOverflow(parsed_options))
return;
+ // TODO(fserb): this shouldn't be software?
std::unique_ptr<CanvasResourceProvider> resource_provider =
CanvasResourceProvider::Create(
IntSize(video->videoWidth(), video->videoHeight()),
- CanvasResourceProvider::kSoftwareResourceUsage,
+ CanvasResourceProvider::ResourceUsage::kSoftwareResourceUsage,
nullptr, // context_provider_wrapper
0, // msaa_sample_count
CanvasColorParams(), // TODO: set color space here to avoid clamping
CanvasResourceProvider::kDefaultPresentationMode,
- nullptr, // canvas_resource_dispatcher
- IsAccelerated()); // is_origin_top_left
+ nullptr, // canvas_resource_dispatcher
+ IsAccelerated()); // is_origin_top_left
if (!resource_provider)
return;
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 9c2ff5bdb7e..338eabd4ad2 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
@@ -39,7 +39,6 @@
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/fileapi/blob.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
-#include "third_party/blink/renderer/core/frame/use_counter.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/html_image_element.h"
@@ -50,13 +49,14 @@
#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"
-#include "third_party/blink/renderer/platform/cross_thread_functional.h"
-#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/instrumentation/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.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_pool.h"
#include "third_party/blink/renderer/platform/shared_buffer.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
#include "v8/include/v8.h"
namespace blink {
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 4792b6ca238..289f08778f7 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
@@ -12,7 +12,7 @@
#include "third_party/blink/renderer/platform/bindings/script_state.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/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 bfad26f5172..06e5f5b1980 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
@@ -267,7 +267,6 @@ TEST_F(ImageBitmapTest, AvoidGPUReadback) {
scoped_refptr<AcceleratedStaticBitmapImage> bitmap =
AcceleratedStaticBitmapImage::CreateFromSkImage(image,
context_provider_wrapper);
- EXPECT_TRUE(bitmap->TextureHolderForTesting()->IsSkiaTextureHolder());
ImageBitmap* image_bitmap = ImageBitmap::Create(bitmap);
EXPECT_TRUE(image_bitmap);
diff --git a/chromium/third_party/blink/renderer/core/input/context_menu_allowed_scope.h b/chromium/third_party/blink/renderer/core/input/context_menu_allowed_scope.h
index 721a78093ad..218f7f094b6 100644
--- a/chromium/third_party/blink/renderer/core/input/context_menu_allowed_scope.h
+++ b/chromium/third_party/blink/renderer/core/input/context_menu_allowed_scope.h
@@ -7,7 +7,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 ebde4d2747a..d576d49a37d 100644
--- a/chromium/third_party/blink/renderer/core/input/event_handler.cc
+++ b/chromium/third_party/blink/renderer/core/input/event_handler.cc
@@ -60,7 +60,6 @@
#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/frame/visual_viewport.h"
#include "third_party/blink/renderer/core/html/forms/html_input_element.h"
#include "third_party/blink/renderer/core/html/html_dialog_element.h"
@@ -96,8 +95,9 @@
#include "third_party/blink/renderer/platform/geometry/float_point.h"
#include "third_party/blink/renderer/platform/graphics/image.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/windows_keyboard_codes.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
@@ -127,8 +127,8 @@ bool ShouldRefetchEventTarget(const MouseEventWithHitTestResults& mev) {
// 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 =
- TimeDelta::FromMilliseconds(20);
+static constexpr base::TimeDelta kCursorUpdateInterval =
+ base::TimeDelta::FromMilliseconds(20);
static const int kMaximumCursorSize = 128;
@@ -144,7 +144,8 @@ static const double kMinimumCursorScale = 0.001;
// The minimum amount of time an element stays active after a ShowPress
// This is roughly 9 frames, which should be long enough to be noticeable.
-constexpr TimeDelta kMinimumActiveInterval = TimeDelta::FromSecondsD(0.15);
+constexpr base::TimeDelta kMinimumActiveInterval =
+ base::TimeDelta::FromSecondsD(0.15);
EventHandler::EventHandler(LocalFrame& frame)
: frame_(frame),
@@ -241,9 +242,21 @@ void EventHandler::StartMiddleClickAutoscroll(LayoutObject* layout_object) {
AutoscrollController* controller = scroll_manager_->GetAutoscrollController();
if (!controller)
return;
+ LayoutBox* scrollable = LayoutBox::FindAutoscrollable(layout_object);
+ Page* page = frame_->GetPage();
+ bool vertical_scroll_offset = false;
+ bool horizontal_scroll_offset = false;
+ if (page) {
+ ScrollOffset maximum_scroll_offset =
+ page->GetVisualViewport().MaximumScrollOffset();
+ vertical_scroll_offset = maximum_scroll_offset.Height() > 0;
+ horizontal_scroll_offset = maximum_scroll_offset.Width() > 0;
+ }
controller->StartMiddleClickAutoscroll(
layout_object->GetFrame(), LastKnownMousePositionInRootFrame(),
- mouse_event_manager_->LastKnownMouseScreenPosition());
+ mouse_event_manager_->LastKnownMouseScreenPosition(),
+ scrollable->HasScrollableOverflowY() || vertical_scroll_offset,
+ scrollable->HasScrollableOverflowX() || horizontal_scroll_offset);
mouse_event_manager_->InvalidateClick();
}
@@ -297,20 +310,18 @@ HitTestResult EventHandler::HitTestResultAtLocation(
DCHECK(location.IsRectilinear());
if (hit_type & HitTestRequest::kHitTestVisualOverflow) {
// Apply ancestor transforms to location rect
- PhysicalRect local_rect =
- PhysicalRectToBeNoop(location.BoundingBox());
+ PhysicalRect local_rect = location.BoundingBox();
PhysicalRect main_frame_rect =
frame_view->GetLayoutView()->LocalToAncestorRect(
local_rect, main_view->GetLayoutView(),
kTraverseDocumentBoundaries);
- adjusted_location = HitTestLocation(main_frame_rect.ToLayoutRect());
+ adjusted_location = HitTestLocation(main_frame_rect);
} else {
// Don't apply ancestor transforms to bounding box
- LayoutPoint main_content_point =
- main_view->ConvertFromRootFrame(frame_view->ConvertToRootFrame(
- location.BoundingBox().Location()));
+ PhysicalOffset main_content_point = main_view->ConvertFromRootFrame(
+ frame_view->ConvertToRootFrame(location.BoundingBox().offset));
adjusted_location = HitTestLocation(
- LayoutRect(main_content_point, location.BoundingBox().Size()));
+ PhysicalRect(main_content_point, location.BoundingBox().size));
}
} else {
adjusted_location = HitTestLocation(main_view->ConvertFromRootFrame(
@@ -480,8 +491,7 @@ EventHandler::OptionalCursor EventHandler::SelectCursor(
if (layout_object) {
Cursor override_cursor;
- switch (layout_object->GetCursor(RoundedIntPoint(result.LocalPoint()),
- override_cursor)) {
+ switch (layout_object->GetCursor(result.LocalPoint(), override_cursor)) {
case kSetCursorBasedOnStyle:
break;
case kSetCursor:
@@ -658,11 +668,12 @@ WebInputEventResult EventHandler::HandleMousePressEvent(
if (!frame_->View())
return WebInputEventResult::kNotHandled;
- HitTestRequest request(HitTestRequest::kActive);
+ HitTestRequest request(HitTestRequest::kActive |
+ HitTestRequest::kRetargetForInert);
// Save the document point we generate in case the window coordinate is
// invalidated by what happens when we dispatch the event.
- LayoutPoint document_point = frame_->View()->ConvertFromRootFrame(
- FlooredIntPoint(mouse_event.PositionInRootFrame()));
+ PhysicalOffset document_point = frame_->View()->ConvertFromRootFrame(
+ PhysicalOffset(FlooredIntPoint(mouse_event.PositionInRootFrame())));
MouseEventWithHitTestResults mev = GetMouseEventTarget(request, mouse_event);
if (!mev.InnerNode()) {
mouse_event_manager_->InvalidateClick();
@@ -701,6 +712,10 @@ WebInputEventResult EventHandler::HandleMousePressEvent(
return result;
}
+ if (event_handling_util::ShouldDiscardEventTargetingFrame(mev.Event(),
+ *frame_))
+ return WebInputEventResult::kHandledSuppressed;
+
std::unique_ptr<UserGestureIndicator> gesture_indicator =
LocalFrame::NotifyUserActivation(frame_);
frame_->LocalFrameRoot()
@@ -758,8 +773,10 @@ 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 = event_handling_util::HitTestResultInFrame(
- frame_, HitTestLocation(document_point), HitTestRequest::kReadOnly);
+ frame_, HitTestLocation(document_point),
+ HitTestRequest::kReadOnly | HitTestRequest::kRetargetForInert);
InputDeviceCapabilities* source_capabilities =
frame_->GetDocument()
->domWindow()
@@ -771,7 +788,9 @@ WebInputEventResult EventHandler::HandleMousePressEvent(
source_capabilities);
}
- if (event_result == WebInputEventResult::kNotHandled || mev.GetScrollbar()) {
+ if ((!RuntimeEnabledFeatures::MouseSubframeNoImplicitCaptureEnabled() &&
+ event_result == WebInputEventResult::kNotHandled) ||
+ mev.GetScrollbar()) {
mouse_event_manager_->SetCapturesDragging(true);
// Main frames don't implicitly capture mouse input on MouseDown, just
// subframes do (regardless of whether local or remote).
@@ -789,7 +808,8 @@ WebInputEventResult EventHandler::HandleMousePressEvent(
if (event_result == WebInputEventResult::kNotHandled) {
if (ShouldRefetchEventTarget(mev)) {
HitTestRequest read_only_request(HitTestRequest::kReadOnly |
- HitTestRequest::kActive);
+ HitTestRequest::kActive |
+ HitTestRequest::kRetargetForInert);
mev = frame_->GetDocument()->PerformMouseEventHitTest(
read_only_request, document_point, mouse_event);
}
@@ -906,7 +926,8 @@ WebInputEventResult EventHandler::HandleMouseMoveOrLeaveEvent(
return WebInputEventResult::kHandledSystem;
}
- HitTestRequest::HitTestRequestType hit_type = HitTestRequest::kMove;
+ HitTestRequest::HitTestRequestType hit_type =
+ HitTestRequest::kMove | HitTestRequest::kRetargetForInert;
if (mouse_event_manager_->MousePressed()) {
hit_type |= HitTestRequest::kActive;
} else if (only_update_scrollbars) {
@@ -923,7 +944,7 @@ WebInputEventResult EventHandler::HandleMouseMoveOrLeaveEvent(
if (pointer_event_manager_->IsAnyTouchActive() && !force_leave)
hit_type |= HitTestRequest::kActive | HitTestRequest::kReadOnly;
HitTestRequest request(hit_type);
- HitTestLocation out_location((LayoutPoint()));
+ HitTestLocation out_location((PhysicalOffset()));
MouseEventWithHitTestResults mev = MouseEventWithHitTestResults(
mouse_event, out_location, HitTestResult(request, out_location));
@@ -1069,7 +1090,8 @@ WebInputEventResult EventHandler::HandleMouseReleaseEvent(
// Mouse events simulated from touch should not hit-test again.
DCHECK(!mouse_event.FromTouch());
- HitTestRequest::HitTestRequestType hit_type = HitTestRequest::kRelease;
+ HitTestRequest::HitTestRequestType hit_type =
+ HitTestRequest::kRelease | HitTestRequest::kRetargetForInert;
HitTestRequest request(hit_type);
MouseEventWithHitTestResults mev = GetMouseEventTarget(request, mouse_event);
LocalFrame* subframe = event_handling_util::GetTargetSubframe(
@@ -1078,28 +1100,33 @@ WebInputEventResult EventHandler::HandleMouseReleaseEvent(
if (subframe)
return PassMouseReleaseEventToSubframe(mev, subframe);
- // Mouse events will be associated with the Document where mousedown
- // occurred. If, e.g., there is a mousedown, then a drag to a different
- // Document and mouseup there, the mouseup's gesture will be associated with
- // the mousedown's Document. It's not absolutely certain that this is the
- // correct behavior.
+ WebInputEventResult event_result = WebInputEventResult::kNotHandled;
+
std::unique_ptr<UserGestureIndicator> gesture_indicator;
- if (frame_->LocalFrameRoot()
- .GetEventHandler()
- .last_mouse_down_user_gesture_token_) {
- gesture_indicator = std::make_unique<UserGestureIndicator>(
- std::move(frame_->LocalFrameRoot()
- .GetEventHandler()
- .last_mouse_down_user_gesture_token_));
+ if (event_handling_util::ShouldDiscardEventTargetingFrame(mev.Event(),
+ *frame_)) {
+ event_result = WebInputEventResult::kHandledSuppressed;
} else {
- gesture_indicator = LocalFrame::NotifyUserActivation(frame_);
- }
+ // Mouse events will be associated with the Document where mousedown
+ // occurred. If, e.g., there is a mousedown, then a drag to a different
+ // Document and mouseup there, the mouseup's gesture will be associated with
+ // the mousedown's Document. It's not absolutely certain that this is the
+ // correct behavior.
+ if (frame_->LocalFrameRoot()
+ .GetEventHandler()
+ .last_mouse_down_user_gesture_token_) {
+ gesture_indicator = std::make_unique<UserGestureIndicator>(
+ std::move(frame_->LocalFrameRoot()
+ .GetEventHandler()
+ .last_mouse_down_user_gesture_token_));
+ }
- WebInputEventResult event_result = DispatchMousePointerEvent(
- WebInputEvent::kPointerUp, mev.InnerElement(), mev.CanvasRegionId(),
- mev.Event(), Vector<WebMouseEvent>(), Vector<WebMouseEvent>(),
- (GetSelectionController().HasExtendedSelection() &&
- IsSelectionOverLink(mev)));
+ event_result = DispatchMousePointerEvent(
+ WebInputEvent::kPointerUp, mev.InnerElement(), mev.CanvasRegionId(),
+ mev.Event(), Vector<WebMouseEvent>(), Vector<WebMouseEvent>(),
+ (GetSelectionController().HasExtendedSelection() &&
+ IsSelectionOverLink(mev)));
+ }
scroll_manager_->ClearResizeScrollableArea(false);
@@ -1127,7 +1154,8 @@ WebInputEventResult EventHandler::UpdateDragAndDrop(
if (!frame_->View())
return event_result;
- HitTestRequest request(HitTestRequest::kReadOnly);
+ HitTestRequest request(HitTestRequest::kReadOnly |
+ HitTestRequest::kRetargetForInert);
MouseEventWithHitTestResults mev =
event_handling_util::PerformMouseEventHitTest(frame_, request, event);
@@ -1273,48 +1301,104 @@ Element* EventHandler::EffectiveMouseEventTargetElement(
return new_element_under_mouse;
}
-bool EventHandler::IsTouchPointerIdActiveOnFrame(PointerId pointer_id,
- LocalFrame* frame) const {
- DCHECK_EQ(frame_, &frame_->LocalFrameRoot());
- return pointer_event_manager_->IsTouchPointerIdActiveOnFrame(pointer_id,
- frame);
+bool EventHandler::IsPointerIdActiveOnFrame(PointerId pointer_id,
+ LocalFrame* frame) const {
+ DCHECK(frame_ == &frame_->LocalFrameRoot() || frame_ == frame);
+ return pointer_event_manager_->IsPointerIdActiveOnFrame(pointer_id, frame);
}
-bool EventHandler::RootFrameTouchPointerActiveInCurrentFrame(
+bool EventHandler::RootFrameTrackedActivePointerInCurrentFrame(
PointerId pointer_id) const {
return frame_ != &frame_->LocalFrameRoot() &&
- frame_->LocalFrameRoot()
- .GetEventHandler()
- .IsTouchPointerIdActiveOnFrame(pointer_id, frame_);
+ frame_->LocalFrameRoot().GetEventHandler().IsPointerIdActiveOnFrame(
+ pointer_id, frame_);
}
bool EventHandler::IsPointerEventActive(PointerId pointer_id) {
return pointer_event_manager_->IsActive(pointer_id) ||
- RootFrameTouchPointerActiveInCurrentFrame(pointer_id);
+ RootFrameTrackedActivePointerInCurrentFrame(pointer_id);
+}
+
+LocalFrame* EventHandler::DetermineActivePointerTrackerFrame(
+ PointerId pointer_id) const {
+ // If pointer_id is active on current |frame_|, pointer states are in
+ // current frame's PEM; otherwise, check if it's a touch-like pointer that
+ // have its active states in the local frame root's PEM.
+ if (IsPointerIdActiveOnFrame(pointer_id, frame_))
+ return frame_;
+ if (RootFrameTrackedActivePointerInCurrentFrame(pointer_id))
+ return &frame_->LocalFrameRoot();
+ return nullptr;
}
void EventHandler::SetPointerCapture(PointerId pointer_id, Element* target) {
// TODO(crbug.com/591387): This functionality should be per page not per
// frame.
- if (RootFrameTouchPointerActiveInCurrentFrame(pointer_id)) {
- frame_->LocalFrameRoot().GetEventHandler().SetPointerCapture(pointer_id,
- target);
- } else {
- if (pointer_event_manager_->SetPointerCapture(pointer_id, target) &&
- pointer_id == PointerEventFactory::kMouseId)
- CaptureMouseEventsToWidget(true);
+ LocalFrame* tracking_frame = DetermineActivePointerTrackerFrame(pointer_id);
+
+ bool captured =
+ tracking_frame &&
+ tracking_frame->GetEventHandler()
+ .pointer_event_manager_->SetPointerCapture(pointer_id, target);
+
+ if (captured && pointer_id == PointerEventFactory::kMouseId) {
+ CaptureMouseEventsToWidget(true);
+
+ // TODO(crbug.com/919908) This is a temporary approach to make pointer
+ // capture work across in-process frames while mouse subframe capture
+ // disabled. It's to experiment removing the frame capture logic. This
+ // must be re-write before the flag enabled.
+ if (RuntimeEnabledFeatures::MouseSubframeNoImplicitCaptureEnabled()) {
+ LocalFrame* frame = frame_;
+ LocalFrame* parent = DynamicTo<LocalFrame>(frame_->Tree().Parent());
+ while (parent) {
+ Element* subframe_element = nullptr;
+ if (frame->OwnerLayoutObject() &&
+ frame->OwnerLayoutObject()->GetNode()) {
+ subframe_element =
+ DynamicTo<Element>(frame->OwnerLayoutObject()->GetNode());
+ }
+
+ parent->GetEventHandler().capturing_subframe_element_ =
+ subframe_element;
+ frame = parent;
+ parent = DynamicTo<LocalFrame>(parent->Tree().Parent());
+ }
+ }
}
}
void EventHandler::ReleasePointerCapture(PointerId pointer_id,
Element* target) {
- if (RootFrameTouchPointerActiveInCurrentFrame(pointer_id)) {
- frame_->LocalFrameRoot().GetEventHandler().ReleasePointerCapture(pointer_id,
- target);
- } else {
- if (pointer_event_manager_->ReleasePointerCapture(pointer_id, target) &&
- pointer_id == PointerEventFactory::kMouseId)
- CaptureMouseEventsToWidget(false);
+ LocalFrame* tracking_frame = DetermineActivePointerTrackerFrame(pointer_id);
+
+ bool released =
+ tracking_frame &&
+ tracking_frame->GetEventHandler()
+ .pointer_event_manager_->ReleasePointerCapture(pointer_id, target);
+
+ if (released && pointer_id == PointerEventFactory::kMouseId) {
+ CaptureMouseEventsToWidget(false);
+
+ // TODO(crbug/919908) same as SetPointerCapture, this is temporary
+ // approach for removing mouse subframe capture. It must be re-write
+ // before enable the flag.
+ if (RuntimeEnabledFeatures::MouseSubframeNoImplicitCaptureEnabled()) {
+ LocalFrame* frame = frame_;
+ LocalFrame* parent = DynamicTo<LocalFrame>(frame_->Tree().Parent());
+ while (parent) {
+ Element* subframe_element = nullptr;
+ if (frame->OwnerLayoutObject() &&
+ frame->OwnerLayoutObject()->GetNode()) {
+ subframe_element =
+ DynamicTo<Element>(frame->OwnerLayoutObject()->GetNode());
+ }
+
+ parent->GetEventHandler().capturing_subframe_element_ = nullptr;
+ frame = parent;
+ parent = DynamicTo<LocalFrame>(parent->Tree().Parent());
+ }
+ }
}
}
@@ -1324,12 +1408,12 @@ void EventHandler::ReleaseMousePointerCapture() {
bool EventHandler::HasPointerCapture(PointerId pointer_id,
const Element* target) const {
- if (RootFrameTouchPointerActiveInCurrentFrame(pointer_id)) {
- return frame_->LocalFrameRoot().GetEventHandler().HasPointerCapture(
- pointer_id, target);
- } else {
- return pointer_event_manager_->HasPointerCapture(pointer_id, target);
+ if (LocalFrame* tracking_frame =
+ DetermineActivePointerTrackerFrame(pointer_id)) {
+ return tracking_frame->GetEventHandler()
+ .pointer_event_manager_->HasPointerCapture(pointer_id, target);
}
+ return false;
}
void EventHandler::ElementRemoved(Element* target) {
@@ -1338,6 +1422,10 @@ void EventHandler::ElementRemoved(Element* target) {
mouse_wheel_event_manager_->ElementRemoved(target);
}
+void EventHandler::ResetMousePositionForPointerUnlock() {
+ pointer_event_manager_->RemoveLastMousePosition();
+}
+
WebInputEventResult EventHandler::DispatchMousePointerEvent(
const WebInputEvent::Type event_type,
Element* target_element,
@@ -1409,7 +1497,7 @@ WebInputEventResult EventHandler::HandleGestureEvent(
DCHECK(!targeted_event.Event().IsScrollEvent());
if (targeted_event.Event().GetType() == WebInputEvent::kGestureShowPress)
- last_show_press_timestamp_ = CurrentTimeTicks();
+ last_show_press_timestamp_ = base::TimeTicks::Now();
// Update mouseout/leave/over/enter events before jumping directly to the
// inner most frame.
@@ -1429,6 +1517,10 @@ WebInputEventResult EventHandler::HandleGestureEvent(
WebInputEventResult EventHandler::HandleGestureEventInFrame(
const GestureEventWithHitTestResults& targeted_event) {
+ if (event_handling_util::ShouldDiscardEventTargetingFrame(
+ targeted_event.Event(), *frame_)) {
+ return WebInputEventResult::kHandledSuppressed;
+ }
return gesture_manager_->HandleGestureEventInFrame(targeted_event);
}
@@ -1724,7 +1816,7 @@ GestureEventWithHitTestResults EventHandler::TargetGestureEvent(
HitTestRequest::HitTestRequestType hit_type =
gesture_manager_->GetHitTypeForGestureType(gesture_event.GetType());
- TimeDelta active_interval;
+ base::TimeDelta active_interval;
bool should_keep_active_for_min_interval = false;
if (read_only) {
hit_type |= HitTestRequest::kReadOnly;
@@ -1733,7 +1825,8 @@ GestureEventWithHitTestResults EventHandler::TargetGestureEvent(
// If the Tap is received very shortly after ShowPress, we want to
// delay clearing of the active state so that it's visible to the user
// for at least a couple of frames.
- active_interval = CurrentTimeTicks() - last_show_press_timestamp_.value();
+ active_interval =
+ base::TimeTicks::Now() - last_show_press_timestamp_.value();
should_keep_active_for_min_interval =
active_interval < kMinimumActiveInterval;
if (should_keep_active_for_min_interval)
@@ -1768,6 +1861,7 @@ GestureEventWithHitTestResults EventHandler::HitTestResultForGestureEvent(
// disabled). Note that we don't yet apply hover/active state here because
// we need to resolve touch adjustment first so that we apply hover/active
// it to the final adjusted node.
+ hit_type |= HitTestRequest::kRetargetForInert;
hit_type |= HitTestRequest::kReadOnly;
WebGestureEvent adjusted_event = gesture_event;
LayoutSize hit_rect_size;
@@ -1793,9 +1887,10 @@ GestureEventWithHitTestResults EventHandler::HitTestResultForGestureEvent(
hit_test_result = root_frame.GetEventHandler().HitTestResultAtLocation(
location, hit_type);
} else {
- LayoutPoint top_left(adjusted_event.PositionInRootFrame());
- top_left.Move(-hit_rect_size * 0.5f);
- location = HitTestLocation(LayoutRect(top_left, hit_rect_size));
+ PhysicalOffset top_left = PhysicalOffset::FromFloatPointRound(
+ adjusted_event.PositionInRootFrame());
+ top_left -= PhysicalOffset(hit_rect_size * 0.5f);
+ location = HitTestLocation(PhysicalRect(top_left, hit_rect_size));
hit_test_result = root_frame.GetEventHandler().HitTestResultAtLocation(
location, hit_type);
}
@@ -1823,15 +1918,6 @@ GestureEventWithHitTestResults EventHandler::HitTestResultForGestureEvent(
// candidates.
DCHECK(!location.IsRectBasedTest());
- if (ShouldApplyTouchAdjustment(gesture_event) &&
- (gesture_event.GetType() == WebInputEvent::kGestureTap ||
- gesture_event.GetType() == WebInputEvent::kGestureLongPress)) {
- float adjusted_distance = FloatSize(adjusted_event.PositionInRootFrame() -
- gesture_event.PositionInRootFrame())
- .DiagonalLength();
- UMA_HISTOGRAM_COUNTS_100("Event.Touch.TouchAdjustment.AdjustDistance",
- static_cast<int>(adjusted_distance));
- }
return GestureEventWithHitTestResults(adjusted_event, location,
hit_test_result);
}
@@ -1866,7 +1952,7 @@ void EventHandler::ApplyTouchAdjustment(WebGestureEvent* gesture_event,
// FIXME: We should do this even when no candidate matches the node filter.
// crbug.com/398914
if (adjusted) {
- LayoutPoint point = frame_->View()->ConvertFromRootFrame(adjusted_point);
+ PhysicalOffset point(frame_->View()->ConvertFromRootFrame(adjusted_point));
DCHECK(location.ContainsPoint(FloatPoint(point)));
DCHECK(location.IsRectBasedTest());
location = hit_test_result->ResolveRectBasedTest(adjusted_node, point);
@@ -1888,9 +1974,10 @@ WebInputEventResult EventHandler::SendContextMenuEvent(
if (last_scrollbar_under_mouse_)
last_scrollbar_under_mouse_->MouseUp(event);
- LayoutPoint position_in_contents =
- v->ConvertFromRootFrame(FlooredIntPoint(event.PositionInRootFrame()));
- HitTestRequest request(HitTestRequest::kActive);
+ PhysicalOffset position_in_contents(
+ v->ConvertFromRootFrame(FlooredIntPoint(event.PositionInRootFrame())));
+ HitTestRequest request(HitTestRequest::kActive |
+ HitTestRequest::kRetargetForInert);
MouseEventWithHitTestResults mev =
frame_->GetDocument()->PerformMouseEventHitTest(
request, position_in_contents, event);
@@ -1977,7 +2064,8 @@ WebInputEventResult EventHandler::ShowNonLocatedContextMenu(
target_node = doc;
// Use the focused node as the target for hover and active.
- HitTestRequest request(HitTestRequest::kActive);
+ HitTestRequest request(HitTestRequest::kActive |
+ HitTestRequest::kRetargetForInert);
HitTestLocation location(location_in_root_frame);
HitTestResult result(request, location);
result.SetInnerNode(target_node);
@@ -1996,7 +2084,7 @@ WebInputEventResult EventHandler::ShowNonLocatedContextMenu(
WebFloatPoint(location_in_root_frame.X(), location_in_root_frame.Y()),
WebFloatPoint(global_position.X(), global_position.Y()),
WebPointerProperties::Button::kNoButton, /* clickCount */ 0,
- WebInputEvent::kNoModifiers, CurrentTimeTicks(), source_type);
+ WebInputEvent::kNoModifiers, base::TimeTicks::Now(), source_type);
// TODO(dtapuska): Transition the mouseEvent to be created really in viewport
// coordinates instead of root frame coordinates.
@@ -2009,7 +2097,7 @@ void EventHandler::ScheduleHoverStateUpdate() {
// TODO(https://crbug.com/668758): Use a normal BeginFrame update for this.
if (!hover_timer_.IsActive() &&
!mouse_event_manager_->IsMousePositionUnknown())
- hover_timer_.StartOneShot(TimeDelta(), FROM_HERE);
+ hover_timer_.StartOneShot(base::TimeDelta(), FROM_HERE);
}
void EventHandler::ScheduleCursorUpdate() {
@@ -2034,7 +2122,7 @@ void EventHandler::MayUpdateHoverWhenContentUnderMouseChanged(
MouseEventManager::UpdateHoverReason update_hover_reason) {
if (update_hover_reason ==
MouseEventManager::UpdateHoverReason::kScrollOffsetChanged &&
- RuntimeEnabledFeatures::UpdateHoverFromScrollAtBeginFrameEnabled()) {
+ RuntimeEnabledFeatures::UpdateHoverAtBeginFrameEnabled()) {
return;
}
mouse_event_manager_->MayUpdateHoverWhenContentUnderMouseChanged(
@@ -2063,7 +2151,8 @@ void EventHandler::HoverTimerFired(TimerBase*) {
if (auto* layout_object = frame_->ContentLayoutObject()) {
if (LocalFrameView* view = frame_->View()) {
- HitTestRequest request(HitTestRequest::kMove);
+ HitTestRequest request(HitTestRequest::kMove |
+ HitTestRequest::kRetargetForInert);
HitTestLocation location(view->ViewportToFrame(
mouse_event_manager_->LastKnownMousePositionInViewport()));
HitTestResult result(request, location);
@@ -2081,7 +2170,8 @@ void EventHandler::ActiveIntervalTimerFired(TimerBase*) {
// FIXME: Enable condition when http://crbug.com/226842 lands
// m_lastDeferredTapElement.get() == m_frame->document()->activeElement()
HitTestRequest request(HitTestRequest::kTouchEvent |
- HitTestRequest::kRelease);
+ HitTestRequest::kRelease |
+ HitTestRequest::kRetargetForInert);
frame_->GetDocument()->UpdateHoverActiveState(
request.Active(), !request.Move(), last_deferred_tap_element_.Get());
}
@@ -2121,7 +2211,8 @@ void EventHandler::DragSourceEndedAt(const WebMouseEvent& event,
DragOperation operation) {
// Asides from routing the event to the correct frame, the hit test is also an
// opportunity for Layer to update the :hover and :active pseudoclasses.
- HitTestRequest request(HitTestRequest::kRelease);
+ HitTestRequest request(HitTestRequest::kRelease |
+ HitTestRequest::kRetargetForInert);
MouseEventWithHitTestResults mev =
event_handling_util::PerformMouseEventHitTest(frame_, request, event);
@@ -2274,8 +2365,9 @@ void EventHandler::CaptureMouseEventsToWidget(bool capture) {
MouseEventWithHitTestResults EventHandler::GetMouseEventTarget(
const HitTestRequest& request,
const WebMouseEvent& event) {
- LayoutPoint document_point = event_handling_util::ContentPointFromRootFrame(
- frame_, event.PositionInRootFrame());
+ PhysicalOffset document_point =
+ event_handling_util::ContentPointFromRootFrame(
+ frame_, event.PositionInRootFrame());
// TODO(eirage): This does not handle chorded buttons yet.
if (RuntimeEnabledFeatures::UnifiedPointerCaptureInBlinkEnabled() &&
@@ -2293,16 +2385,9 @@ MouseEventWithHitTestResults EventHandler::GetMouseEventTarget(
if (capture_target) {
LayoutObject* layout_object = capture_target->GetLayoutObject();
-
- // TODO(eirage): Is kIgnoreTransforms correct here?
- LayoutPoint local_point =
- layout_object ? layout_object
- ->AbsoluteToLocalPoint(
- PhysicalOffsetToBeNoop(document_point),
- kIgnoreTransforms)
- .ToLayoutPoint()
+ PhysicalOffset local_point =
+ layout_object ? layout_object->AbsoluteToLocalPoint(document_point)
: document_point;
-
result.SetNodeAndPosition(capture_target, local_point);
result.SetScrollbar(last_scrollbar_under_mouse_);
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 5701c464d6b..e2dfc39f52e 100644
--- a/chromium/third_party/blink/renderer/core/input/event_handler.h
+++ b/chromium/third_party/blink/renderer/core/input/event_handler.h
@@ -50,7 +50,7 @@
#include "third_party/blink/renderer/platform/cursor.h"
#include "third_party/blink/renderer/platform/geometry/layout_point.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.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/hash_traits.h"
@@ -104,8 +104,9 @@ class CORE_EXPORT EventHandler final
HitTestResult HitTestResultAtLocation(
const HitTestLocation&,
- HitTestRequest::HitTestRequestType hit_type = HitTestRequest::kReadOnly |
- HitTestRequest::kActive,
+ HitTestRequest::HitTestRequestType hit_type =
+ HitTestRequest::kReadOnly | HitTestRequest::kActive |
+ HitTestRequest::kRetargetForInert,
const LayoutObject* stop_node = nullptr,
bool no_lifecycle_update = false);
@@ -276,7 +277,9 @@ class CORE_EXPORT EventHandler final
ScrollGranularity,
Node* start_node = nullptr);
- bool IsTouchPointerIdActiveOnFrame(PointerId, LocalFrame*) const;
+ bool IsPointerIdActiveOnFrame(PointerId, LocalFrame*) const;
+
+ LocalFrame* DetermineActivePointerTrackerFrame(PointerId pointer_id) const;
// Clears drag target and related states. It is called when drag is done or
// canceled.
@@ -294,6 +297,10 @@ class CORE_EXPORT EventHandler final
void SetIsFallbackCursorModeOn(bool is_on);
+ // Reset the last mouse position so that movement after unlock will be
+ // restart from the lock position.
+ void ResetMousePositionForPointerUnlock();
+
private:
enum NoCursorChangeType { kNoCursorChange };
@@ -327,13 +334,6 @@ class CORE_EXPORT EventHandler final
// Updates the event, location and result to the adjusted target.
void ApplyTouchAdjustment(WebGestureEvent*, HitTestLocation&, HitTestResult*);
- WebInputEventResult HandleGestureTapDown(
- const GestureEventWithHitTestResults&);
- WebInputEventResult HandleGestureTap(const GestureEventWithHitTestResults&);
- WebInputEventResult HandleGestureLongPress(
- const GestureEventWithHitTestResults&);
- WebInputEventResult HandleGestureLongTap(
- const GestureEventWithHitTestResults&);
void PerformHitTest(const HitTestLocation& location,
HitTestResult&,
@@ -363,8 +363,9 @@ class CORE_EXPORT EventHandler final
Element* EffectiveMouseEventTargetElement(Element*);
- // Dispatches ME after corresponding PE provided the PE has not been canceled.
- // The |mouse_event_type| arg must be one of {mousedown, mousemove, mouseup}.
+ // Dispatches ME after corresponding PE provided the PE has not been
+ // canceled. The |mouse_event_type| arg must be one of {mousedown,
+ // mousemove, mouseup}.
WebInputEventResult DispatchMousePointerEvent(
const WebInputEvent::Type,
Element* target,
@@ -405,7 +406,7 @@ class CORE_EXPORT EventHandler final
bool ShouldBrowserControlsConsumeScroll(FloatSize) const;
- bool RootFrameTouchPointerActiveInCurrentFrame(PointerId pointer_id) const;
+ bool RootFrameTrackedActivePointerInCurrentFrame(PointerId pointer_id) const;
void CaptureMouseEventsToWidget(bool);
@@ -466,12 +467,11 @@ class CORE_EXPORT EventHandler final
TaskRunnerTimer<EventHandler> active_interval_timer_;
- // last_show_press_timestamp_ prevents the active state rewrited by following
- // events too soon (less than 0.15s).
- // It is ok we only record last_show_press_timestamp_ in root frame since
- // root frame will have subframe as active element if subframe has active
- // element.
- base::Optional<WTF::TimeTicks> last_show_press_timestamp_;
+ // last_show_press_timestamp_ prevents the active state rewrited by
+ // following events too soon (less than 0.15s). It is ok we only record
+ // last_show_press_timestamp_ in root frame since root frame will have
+ // subframe as active element if subframe has active element.
+ base::Optional<base::TimeTicks> last_show_press_timestamp_;
Member<Element> last_deferred_tap_element_;
// Set on GestureTapDown if unique_touch_event_id_ matches cached adjusted
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 58f01d816ca..c468f46b091 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
@@ -6,12 +6,15 @@
#include <memory>
+#include "base/test/bind_test_util.h"
#include "base/test/scoped_feature_list.h"
+#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/platform/web_keyboard_event.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/range.h"
+#include "third_party/blink/renderer/core/editing/dom_selection.h"
#include "third_party/blink/renderer/core/editing/editing_behavior.h"
#include "third_party/blink/renderer/core/editing/editor.h"
#include "third_party/blink/renderer/core/editing/ephemeral_range.h"
@@ -34,10 +37,13 @@
#include "third_party/blink/renderer/core/page/autoscroll_controller.h"
#include "third_party/blink/renderer/core/page/page.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/testing/core_unit_test_helper.h"
#include "third_party/blink/renderer/core/testing/page_test_base.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/keyboard_codes.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 "ui/events/keycodes/dom/dom_code.h"
#include "ui/events/keycodes/dom/dom_key.h"
@@ -51,14 +57,60 @@ class EventHandlerTest : public PageTestBase {
ShadowRoot* SetShadowContent(const char* shadow_content, const char* host);
};
-class EventHandlerSimTest : public SimTest {};
+class EventHandlerSimTest : public SimTest {
+ public:
+ void InitializeMousePositionAndActivateView(float x, float y) {
+ WebMouseEvent mouse_move_event(WebMouseEvent::kMouseMove,
+ WebFloatPoint(x, y), WebFloatPoint(x, y),
+ WebPointerProperties::Button::kNoButton, 0,
+ WebInputEvent::Modifiers::kNoModifiers,
+ WebInputEvent::GetStaticTimeStampForTests());
+ mouse_move_event.SetFrameScale(1);
+ GetDocument().GetFrame()->GetEventHandler().HandleMouseMoveEvent(
+ mouse_move_event, Vector<WebMouseEvent>(), Vector<WebMouseEvent>());
+
+ WebView().MainFrameWidget()->SetFocus(true);
+ WebView().SetIsActive(true);
+ }
+
+ void InjectScrollFromGestureEvents(cc::ElementIdType element_id,
+ float delta_x,
+ float delta_y) {
+ WebGestureEvent gesture_scroll_begin{
+ WebInputEvent::kGestureScrollBegin, WebInputEvent::kNoModifiers,
+ WebInputEvent::GetStaticTimeStampForTests()};
+ gesture_scroll_begin.SetFrameScale(1);
+ gesture_scroll_begin.data.scroll_begin.delta_x_hint = 0;
+ gesture_scroll_begin.data.scroll_begin.delta_y_hint = -delta_y;
+ gesture_scroll_begin.data.scroll_begin.scrollable_area_element_id =
+ element_id;
+ WebView().MainFrameWidget()->HandleInputEvent(
+ WebCoalescedInputEvent(gesture_scroll_begin));
+
+ WebGestureEvent gesture_scroll_update{
+ WebInputEvent::kGestureScrollUpdate, WebInputEvent::kNoModifiers,
+ WebInputEvent::GetStaticTimeStampForTests()};
+ gesture_scroll_update.SetFrameScale(1);
+ gesture_scroll_update.data.scroll_update.delta_x = delta_x;
+ gesture_scroll_update.data.scroll_update.delta_y = -delta_y;
+ WebView().MainFrameWidget()->HandleInputEvent(
+ WebCoalescedInputEvent(gesture_scroll_update));
+
+ WebGestureEvent gesture_scroll_end{
+ WebInputEvent::kGestureScrollEnd, WebInputEvent::kNoModifiers,
+ WebInputEvent::GetStaticTimeStampForTests()};
+ gesture_scroll_end.SetFrameScale(1);
+ WebView().MainFrameWidget()->HandleInputEvent(
+ WebCoalescedInputEvent(gesture_scroll_end));
+ }
+};
class TapEventBuilder : public WebGestureEvent {
public:
TapEventBuilder(FloatPoint position, int tap_count)
: WebGestureEvent(WebInputEvent::kGestureTap,
WebInputEvent::kNoModifiers,
- CurrentTimeTicks(),
+ base::TimeTicks::Now(),
WebGestureDevice::kTouchscreen) {
SetPositionInWidget(position);
SetPositionInScreen(position);
@@ -74,7 +126,7 @@ class TapDownEventBuilder : public WebGestureEvent {
TapDownEventBuilder(FloatPoint position)
: WebGestureEvent(WebInputEvent::kGestureTapDown,
WebInputEvent::kNoModifiers,
- CurrentTimeTicks(),
+ base::TimeTicks::Now(),
WebGestureDevice::kTouchscreen) {
SetPositionInWidget(position);
SetPositionInScreen(position);
@@ -89,7 +141,7 @@ class ShowPressEventBuilder : public WebGestureEvent {
ShowPressEventBuilder(FloatPoint position)
: WebGestureEvent(WebInputEvent::kGestureShowPress,
WebInputEvent::kNoModifiers,
- CurrentTimeTicks(),
+ base::TimeTicks::Now(),
WebGestureDevice::kTouchscreen) {
SetPositionInWidget(position);
SetPositionInScreen(position);
@@ -104,7 +156,7 @@ class LongPressEventBuilder : public WebGestureEvent {
LongPressEventBuilder(FloatPoint position)
: WebGestureEvent(WebInputEvent::kGestureLongPress,
WebInputEvent::kNoModifiers,
- CurrentTimeTicks(),
+ base::TimeTicks::Now(),
WebGestureDevice::kTouchscreen) {
SetPositionInWidget(position);
SetPositionInScreen(position);
@@ -121,7 +173,7 @@ class MousePressEventBuilder : public WebMouseEvent {
WebMouseEvent::Button button_param)
: WebMouseEvent(WebInputEvent::kMouseDown,
WebInputEvent::kNoModifiers,
- CurrentTimeTicks()) {
+ base::TimeTicks::Now()) {
click_count = click_count_param;
button = button_param;
SetPositionInWidget(position_param.X(), position_param.Y());
@@ -192,7 +244,7 @@ TEST_F(EventHandlerTest, dragSelectionAfterScroll) {
mouse_move_event, Vector<WebMouseEvent>(), Vector<WebMouseEvent>());
GetPage().GetAutoscrollController().Animate();
- GetPage().Animator().ServiceScriptedAnimations(WTF::CurrentTimeTicks());
+ GetPage().Animator().ServiceScriptedAnimations(base::TimeTicks::Now());
WebMouseEvent mouse_up_event(
WebMouseEvent::kMouseUp, WebFloatPoint(100, 50), WebFloatPoint(200, 250),
@@ -243,10 +295,10 @@ TEST_F(EventHandlerTest, multiClickSelectionFromTap) {
->GetEditor()
.IsSelectTrailingWhitespaceEnabled()) {
EXPECT_EQ(Position(line, 4), Selection().GetSelectionInDOMTree().Extent());
- EXPECT_EQ("One ", WebString(Selection().SelectedText()).Utf8());
+ EXPECT_EQ("One ", Selection().SelectedText().Utf8());
} else {
EXPECT_EQ(Position(line, 3), Selection().GetSelectionInDOMTree().Extent());
- EXPECT_EQ("One", WebString(Selection().SelectedText()).Utf8());
+ EXPECT_EQ("One", Selection().SelectedText().Utf8());
}
TapEventBuilder triple_tap_event(FloatPoint(0, 0), 3);
@@ -255,7 +307,7 @@ TEST_F(EventHandlerTest, multiClickSelectionFromTap) {
ASSERT_TRUE(Selection().GetSelectionInDOMTree().IsRange());
EXPECT_EQ(Position(line, 0), Selection().GetSelectionInDOMTree().Base());
EXPECT_EQ(Position(line, 13), Selection().GetSelectionInDOMTree().Extent());
- EXPECT_EQ("One Two Three", WebString(Selection().SelectedText()).Utf8());
+ EXPECT_EQ("One Two Three", Selection().SelectedText().Utf8());
}
TEST_F(EventHandlerTest, multiClickSelectionFromTapDisabledIfNotEditable) {
@@ -360,7 +412,7 @@ TEST_F(EventHandlerTest, draggedSVGImagePositionTest) {
TEST_F(EventHandlerTest, HitOnNothingDoesNotShowIBeam) {
SetHtmlInnerHTML("");
- HitTestLocation location((LayoutPoint(10, 10)));
+ HitTestLocation location((PhysicalOffset(10, 10)));
HitTestResult hit =
GetDocument().GetFrame()->GetEventHandler().HitTestResultAtLocation(
location);
@@ -539,7 +591,7 @@ TEST_F(EventHandlerTest, ReadOnlyInputDoesNotInheritUserSelect) {
TEST_F(EventHandlerTest, ImagesCannotStartSelection) {
SetHtmlInnerHTML("<img>");
- Element* const img = ToElement(GetDocument().body()->firstChild());
+ auto* const img = To<Element>(GetDocument().body()->firstChild());
HitTestLocation location(
img->GetLayoutObject()->AbsoluteBoundingBoxRect().Center());
HitTestResult hit =
@@ -574,7 +626,7 @@ TEST_F(EventHandlerTest, AnchorTextCannotStartSelection) {
.SelectCursor(location, result)
.GetCursor()
.GetType(),
- Cursor::Type::kHand); // A hand signals ability to navigate.
+ ui::CursorType::kHand); // A hand signals ability to navigate.
}
TEST_F(EventHandlerTest, EditableAnchorTextCanStartSelection) {
@@ -597,7 +649,7 @@ TEST_F(EventHandlerTest, EditableAnchorTextCanStartSelection) {
.SelectCursor(location, result)
.GetCursor()
.GetType(),
- Cursor::Type::kIBeam); // An I-beam signals editability.
+ ui::CursorType::kIBeam); // An I-beam signals editability.
}
TEST_F(EventHandlerTest, implicitSend) {
@@ -636,7 +688,7 @@ TEST_F(EventHandlerTest, sendContextMenuEventWithHover) {
WebMouseEvent mouse_down_event(
WebMouseEvent::kMouseDown, WebFloatPoint(0, 0), WebFloatPoint(100, 200),
WebPointerProperties::Button::kRight, 1,
- WebInputEvent::Modifiers::kRightButtonDown, CurrentTimeTicks());
+ WebInputEvent::Modifiers::kRightButtonDown, base::TimeTicks::Now());
mouse_down_event.SetFrameScale(1);
EXPECT_EQ(WebInputEventResult::kHandledApplication,
GetDocument().GetFrame()->GetEventHandler().SendContextMenuEvent(
@@ -793,7 +845,7 @@ TEST_F(EventHandlerTest, dragEndInNewDrag) {
WebMouseEvent mouse_down_event(
WebInputEvent::kMouseDown, WebFloatPoint(50, 50), WebFloatPoint(50, 50),
WebPointerProperties::Button::kLeft, 1,
- WebInputEvent::Modifiers::kLeftButtonDown, CurrentTimeTicks());
+ WebInputEvent::Modifiers::kLeftButtonDown, base::TimeTicks::Now());
mouse_down_event.SetFrameScale(1);
GetDocument().GetFrame()->GetEventHandler().HandleMousePressEvent(
mouse_down_event);
@@ -801,7 +853,7 @@ TEST_F(EventHandlerTest, dragEndInNewDrag) {
WebMouseEvent mouse_move_event(
WebInputEvent::kMouseMove, WebFloatPoint(51, 50), WebFloatPoint(51, 50),
WebPointerProperties::Button::kLeft, 1,
- WebInputEvent::Modifiers::kLeftButtonDown, CurrentTimeTicks());
+ WebInputEvent::Modifiers::kLeftButtonDown, base::TimeTicks::Now());
mouse_move_event.SetFrameScale(1);
GetDocument().GetFrame()->GetEventHandler().HandleMouseMoveEvent(
mouse_move_event, Vector<WebMouseEvent>(), Vector<WebMouseEvent>());
@@ -812,10 +864,10 @@ TEST_F(EventHandlerTest, dragEndInNewDrag) {
// this contrived test. Given the current code, it is unclear how the
// dragSourceEndedAt() call could occur before a drag operation is started.
- WebMouseEvent mouse_up_event(WebInputEvent::kMouseUp, WebFloatPoint(100, 50),
- WebFloatPoint(200, 250),
- WebPointerProperties::Button::kLeft, 1,
- WebInputEvent::kNoModifiers, CurrentTimeTicks());
+ WebMouseEvent mouse_up_event(
+ WebInputEvent::kMouseUp, WebFloatPoint(100, 50), WebFloatPoint(200, 250),
+ WebPointerProperties::Button::kLeft, 1, WebInputEvent::kNoModifiers,
+ base::TimeTicks::Now());
mouse_up_event.SetFrameScale(1);
GetDocument().GetFrame()->GetEventHandler().DragSourceEndedAt(
mouse_up_event, kDragOperationNone);
@@ -905,7 +957,7 @@ TEST_F(EventHandlerTooltipTest, mouseLeaveClearsTooltip) {
WebMouseEvent mouse_move_event(
WebInputEvent::kMouseMove, WebFloatPoint(51, 50), WebFloatPoint(51, 50),
WebPointerProperties::Button::kNoButton, 0, WebInputEvent::kNoModifiers,
- CurrentTimeTicks());
+ base::TimeTicks::Now());
mouse_move_event.SetFrameScale(1);
GetDocument().GetFrame()->GetEventHandler().HandleMouseMoveEvent(
mouse_move_event, Vector<WebMouseEvent>(), Vector<WebMouseEvent>());
@@ -915,7 +967,7 @@ TEST_F(EventHandlerTooltipTest, mouseLeaveClearsTooltip) {
WebMouseEvent mouse_leave_event(
WebInputEvent::kMouseLeave, WebFloatPoint(0, 0), WebFloatPoint(0, 0),
WebPointerProperties::Button::kNoButton, 0, WebInputEvent::kNoModifiers,
- CurrentTimeTicks());
+ base::TimeTicks::Now());
mouse_leave_event.SetFrameScale(1);
GetDocument().GetFrame()->GetEventHandler().HandleMouseLeaveEvent(
mouse_leave_event);
@@ -975,7 +1027,7 @@ TEST_F(EventHandlerLatencyTest, NeedsUnbufferedInput) {
WebMouseEvent mouse_press_event(
WebInputEvent::kMouseDown, WebFloatPoint(51, 50), WebFloatPoint(51, 50),
WebPointerProperties::Button::kLeft, 0, WebInputEvent::kNoModifiers,
- CurrentTimeTicks());
+ base::TimeTicks::Now());
mouse_press_event.SetFrameScale(1);
GetDocument().GetFrame()->GetEventHandler().HandleMousePressEvent(
mouse_press_event);
@@ -1033,7 +1085,7 @@ TEST_F(EventHandlerNavigationTest, MouseButtonsNavigate) {
WebMouseEvent mouse_back_event(
WebInputEvent::kMouseUp, WebFloatPoint(51, 50), WebFloatPoint(51, 50),
WebPointerProperties::Button::kBack, 0, WebInputEvent::kNoModifiers,
- CurrentTimeTicks());
+ base::TimeTicks::Now());
mouse_back_event.SetFrameScale(1);
GetDocument().GetFrame()->GetEventHandler().HandleMouseReleaseEvent(
mouse_back_event);
@@ -1043,7 +1095,7 @@ TEST_F(EventHandlerNavigationTest, MouseButtonsNavigate) {
WebMouseEvent mouse_forward_event(
WebInputEvent::kMouseUp, WebFloatPoint(51, 50), WebFloatPoint(51, 50),
WebPointerProperties::Button::kForward, 0, WebInputEvent::kNoModifiers,
- CurrentTimeTicks());
+ base::TimeTicks::Now());
mouse_forward_event.SetFrameScale(1);
GetDocument().GetFrame()->GetEventHandler().HandleMouseReleaseEvent(
mouse_forward_event);
@@ -1065,7 +1117,7 @@ TEST_F(EventHandlerNavigationTest, MouseButtonsDontNavigate) {
WebMouseEvent mouse_back_event(
WebInputEvent::kMouseUp, WebFloatPoint(51, 50), WebFloatPoint(51, 50),
WebPointerProperties::Button::kBack, 0, WebInputEvent::kNoModifiers,
- CurrentTimeTicks());
+ base::TimeTicks::Now());
mouse_back_event.SetFrameScale(1);
GetDocument().GetFrame()->GetEventHandler().HandleMouseReleaseEvent(
mouse_back_event);
@@ -1075,7 +1127,7 @@ TEST_F(EventHandlerNavigationTest, MouseButtonsDontNavigate) {
WebMouseEvent mouse_forward_event(
WebInputEvent::kMouseUp, WebFloatPoint(51, 50), WebFloatPoint(51, 50),
WebPointerProperties::Button::kForward, 0, WebInputEvent::kNoModifiers,
- CurrentTimeTicks());
+ base::TimeTicks::Now());
mouse_forward_event.SetFrameScale(1);
GetDocument().GetFrame()->GetEventHandler().HandleMouseReleaseEvent(
mouse_forward_event);
@@ -1083,67 +1135,33 @@ TEST_F(EventHandlerNavigationTest, MouseButtonsDontNavigate) {
EXPECT_EQ(0, Offset());
}
-class InjectedGestureCapturingChromeClient : public EmptyChromeClient {
- public:
- InjectedGestureCapturingChromeClient() = default;
-
- struct InjectedGestureData {
- WebFloatSize delta;
- ScrollGranularity granularity;
- CompositorElementId scrollable_area_element_id;
- WebInputEvent::Type type;
- };
-
- void InjectGestureScrollEvent(LocalFrame& local_frame,
- WebGestureDevice device,
- const WebFloatSize& delta,
- ScrollGranularity granularity,
- CompositorElementId scrollable_area_element_id,
- WebInputEvent::Type type) override {
- InjectedGestureData data{delta, granularity, scrollable_area_element_id,
- type};
- injected_data_.push_back(data);
- }
-
- const std::vector<InjectedGestureData>& GetInjectedData() const {
- return injected_data_;
- }
-
- private:
- std::vector<InjectedGestureData> injected_data_;
-};
-
-class EventHandlerScrollbarGestureInjectionTest : public EventHandlerTest {
+class EventHandlerScrollbarGestureInjectionTest : public SimTest {
public:
EventHandlerScrollbarGestureInjectionTest() = default;
void SetUp() override {
scoped_feature_list_.InitAndEnableFeature(
features::kScrollbarInjectScrollGestures);
- chrome_client_ =
- MakeGarbageCollected<InjectedGestureCapturingChromeClient>();
- Page::PageClients clients;
- FillWithEmptyClients(clients);
- clients.chrome_client = chrome_client_.Get();
- SetupPageWithClients(&clients);
- }
-
- const std::vector<InjectedGestureCapturingChromeClient::InjectedGestureData>&
- GetInjectedData() {
- return chrome_client_->GetInjectedData();
+ SimTest::SetUp();
}
private:
- Persistent<InjectedGestureCapturingChromeClient> chrome_client_;
base::test::ScopedFeatureList scoped_feature_list_;
};
TEST_F(EventHandlerScrollbarGestureInjectionTest,
MouseUpOffScrollbarGeneratesScrollEnd) {
- SetHtmlInnerHTML(
- "<div style=\"height:1000px\">"
- "Tall text to create viewport scrollbar</div>");
- EXPECT_EQ(GetInjectedData().size(), 0ULL);
+ WebView().MainFrameWidget()->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>
+ <div style='height:1000px'>
+ Tall text to create viewport scrollbar</div>
+ )HTML");
+
+ Compositor().BeginFrame();
+ EXPECT_EQ(WebWidgetClient().GetInjectedScrollGestureData().size(), 0u);
// PageTestBase sizes the page to 800x600. Click on the scrollbar
// track, move off, then release the mouse and verify that GestureScrollEnd
@@ -1153,60 +1171,72 @@ TEST_F(EventHandlerScrollbarGestureInjectionTest,
// any injected gesture events. Mobile overlay scrollbar theme does not
// allow hit testing.
bool scrollbar_theme_allows_hit_test =
- GetPage().GetScrollbarTheme().AllowsHitTest();
+ GetDocument().GetPage()->GetScrollbarTheme().AllowsHitTest();
const WebFloatPoint scrollbar_forward_track(795, 560);
WebMouseEvent mouse_down(WebInputEvent::kMouseDown, scrollbar_forward_track,
scrollbar_forward_track,
WebPointerProperties::Button::kLeft, 0,
- WebInputEvent::kNoModifiers, CurrentTimeTicks());
+ WebInputEvent::kNoModifiers, base::TimeTicks::Now());
mouse_down.SetFrameScale(1);
GetDocument().GetFrame()->GetEventHandler().HandleMousePressEvent(mouse_down);
// Mouse down on the scrollbar track should have generated GSB/GSU.
if (scrollbar_theme_allows_hit_test) {
- EXPECT_EQ(GetInjectedData().size(), 2ULL);
- EXPECT_EQ(GetInjectedData()[0].type, WebInputEvent::kGestureScrollBegin);
- EXPECT_EQ(GetInjectedData()[1].type, WebInputEvent::kGestureScrollUpdate);
+ EXPECT_EQ(WebWidgetClient().GetInjectedScrollGestureData().size(), 2u);
+ EXPECT_EQ(WebWidgetClient().GetInjectedScrollGestureData()[0].type,
+ WebInputEvent::kGestureScrollBegin);
+ EXPECT_EQ(WebWidgetClient().GetInjectedScrollGestureData()[1].type,
+ WebInputEvent::kGestureScrollUpdate);
} else {
- EXPECT_EQ(GetInjectedData().size(), 0ULL);
+ EXPECT_EQ(WebWidgetClient().GetInjectedScrollGestureData().size(), 0u);
}
const WebFloatPoint middle_of_page(100, 100);
WebMouseEvent mouse_move(WebInputEvent::kMouseMove, middle_of_page,
middle_of_page, WebPointerProperties::Button::kLeft,
- 0, WebInputEvent::kNoModifiers, CurrentTimeTicks());
+ 0, WebInputEvent::kNoModifiers,
+ base::TimeTicks::Now());
mouse_move.SetFrameScale(1);
GetDocument().GetFrame()->GetEventHandler().HandleMouseMoveEvent(
mouse_move, Vector<WebMouseEvent>(), Vector<WebMouseEvent>());
// Mouse move should not have generated any gestures.
if (scrollbar_theme_allows_hit_test) {
- EXPECT_EQ(GetInjectedData().size(), 2ULL);
+ EXPECT_EQ(WebWidgetClient().GetInjectedScrollGestureData().size(), 2u);
} else {
- EXPECT_EQ(GetInjectedData().size(), 0ULL);
+ EXPECT_EQ(WebWidgetClient().GetInjectedScrollGestureData().size(), 0u);
}
WebMouseEvent mouse_up(WebInputEvent::kMouseUp, middle_of_page,
middle_of_page, WebPointerProperties::Button::kLeft, 0,
- WebInputEvent::kNoModifiers, CurrentTimeTicks());
+ WebInputEvent::kNoModifiers, base::TimeTicks::Now());
mouse_up.SetFrameScale(1);
GetDocument().GetFrame()->GetEventHandler().HandleMouseReleaseEvent(mouse_up);
// Mouse up must generate GestureScrollEnd.
if (scrollbar_theme_allows_hit_test) {
- EXPECT_EQ(GetInjectedData().size(), 3ULL);
- EXPECT_EQ(GetInjectedData()[2].type, WebInputEvent::kGestureScrollEnd);
+ EXPECT_EQ(WebWidgetClient().GetInjectedScrollGestureData().size(), 3u);
+ EXPECT_EQ(WebWidgetClient().GetInjectedScrollGestureData()[2].type,
+ WebInputEvent::kGestureScrollEnd);
} else {
- EXPECT_EQ(GetInjectedData().size(), 0ULL);
+ EXPECT_EQ(WebWidgetClient().GetInjectedScrollGestureData().size(), 0u);
}
}
TEST_F(EventHandlerScrollbarGestureInjectionTest, MouseUpOnlyOnScrollbar) {
- SetHtmlInnerHTML(
- "<div style=\"height:1000px\">"
- "Tall text to create viewport scrollbar</div>");
- EXPECT_EQ(GetInjectedData().size(), 0ULL);
+ WebView().MainFrameWidget()->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>
+ <div style='height:1000px'>
+ Tall text to create viewport scrollbar</div>
+ )HTML");
+
+ Compositor().BeginFrame();
+
+ EXPECT_EQ(WebWidgetClient().GetInjectedScrollGestureData().size(), 0u);
// Mouse down on the page, the move the mouse to the scrollbar and release.
// Validate that we don't inject a ScrollEnd (since no ScrollBegin was
@@ -1215,41 +1245,50 @@ TEST_F(EventHandlerScrollbarGestureInjectionTest, MouseUpOnlyOnScrollbar) {
const WebFloatPoint middle_of_page(100, 100);
WebMouseEvent mouse_down(WebInputEvent::kMouseDown, middle_of_page,
middle_of_page, WebPointerProperties::Button::kLeft,
- 0, WebInputEvent::kNoModifiers, CurrentTimeTicks());
+ 0, WebInputEvent::kNoModifiers,
+ base::TimeTicks::Now());
mouse_down.SetFrameScale(1);
GetDocument().GetFrame()->GetEventHandler().HandleMousePressEvent(mouse_down);
// Mouse down on the page should not generate scroll gestures.
- EXPECT_EQ(GetInjectedData().size(), 0ULL);
+ EXPECT_EQ(WebWidgetClient().GetInjectedScrollGestureData().size(), 0u);
const WebFloatPoint scrollbar_forward_track(795, 560);
WebMouseEvent mouse_move(WebInputEvent::kMouseMove, scrollbar_forward_track,
scrollbar_forward_track,
WebPointerProperties::Button::kLeft, 0,
- WebInputEvent::kNoModifiers, CurrentTimeTicks());
+ WebInputEvent::kNoModifiers, base::TimeTicks::Now());
mouse_move.SetFrameScale(1);
GetDocument().GetFrame()->GetEventHandler().HandleMouseMoveEvent(
mouse_move, Vector<WebMouseEvent>(), Vector<WebMouseEvent>());
// Mouse move should not have generated any gestures.
- EXPECT_EQ(GetInjectedData().size(), 0ULL);
+ EXPECT_EQ(WebWidgetClient().GetInjectedScrollGestureData().size(), 0u);
WebMouseEvent mouse_up(WebInputEvent::kMouseUp, scrollbar_forward_track,
scrollbar_forward_track,
WebPointerProperties::Button::kLeft, 0,
- WebInputEvent::kNoModifiers, CurrentTimeTicks());
+ WebInputEvent::kNoModifiers, base::TimeTicks::Now());
mouse_up.SetFrameScale(1);
GetDocument().GetFrame()->GetEventHandler().HandleMouseReleaseEvent(mouse_up);
// Mouse up should not have generated any gestures.
- EXPECT_EQ(GetInjectedData().size(), 0ULL);
+ EXPECT_EQ(WebWidgetClient().GetInjectedScrollGestureData().size(), 0u);
}
TEST_F(EventHandlerScrollbarGestureInjectionTest, RightClickNoGestures) {
- SetHtmlInnerHTML(
- "<div style=\"height:1000px\">"
- "Tall text to create viewport scrollbar</div>");
- EXPECT_EQ(GetInjectedData().size(), 0ULL);
+ WebView().MainFrameWidget()->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>
+ <div style='height:1000px'>
+ Tall text to create viewport scrollbar</div>
+ )HTML");
+
+ Compositor().BeginFrame();
+
+ EXPECT_EQ(WebWidgetClient().GetInjectedScrollGestureData().size(), 0u);
// PageTestBase sizes the page to 800x600. Right click on the scrollbar
// track, and release the mouse and verify that no gesture events are
@@ -1259,20 +1298,149 @@ TEST_F(EventHandlerScrollbarGestureInjectionTest, RightClickNoGestures) {
WebMouseEvent mouse_down(WebInputEvent::kMouseDown, scrollbar_forward_track,
scrollbar_forward_track,
WebPointerProperties::Button::kRight, 0,
- WebInputEvent::kNoModifiers, CurrentTimeTicks());
+ WebInputEvent::kNoModifiers, base::TimeTicks::Now());
mouse_down.SetFrameScale(1);
GetDocument().GetFrame()->GetEventHandler().HandleMousePressEvent(mouse_down);
- EXPECT_EQ(GetInjectedData().size(), 0ULL);
+ EXPECT_EQ(WebWidgetClient().GetInjectedScrollGestureData().size(), 0u);
WebMouseEvent mouse_up(WebInputEvent::kMouseUp, scrollbar_forward_track,
scrollbar_forward_track,
WebPointerProperties::Button::kRight, 0,
- WebInputEvent::kNoModifiers, CurrentTimeTicks());
+ WebInputEvent::kNoModifiers, base::TimeTicks::Now());
mouse_up.SetFrameScale(1);
GetDocument().GetFrame()->GetEventHandler().HandleMouseReleaseEvent(mouse_up);
- EXPECT_EQ(GetInjectedData().size(), 0ULL);
+ EXPECT_EQ(WebWidgetClient().GetInjectedScrollGestureData().size(), 0u);
+}
+
+// https://crbug.com/976557 tracks the fix for re-enabling this test on Mac.
+#ifdef OS_MACOSX
+#define MAYBE_GestureTapWithScrollSnaps DISABLED_GestureTapWithScrollSnaps
+#else
+#define MAYBE_GestureTapWithScrollSnaps GestureTapWithScrollSnaps
+#endif
+
+TEST_F(EventHandlerScrollbarGestureInjectionTest,
+ MAYBE_GestureTapWithScrollSnaps) {
+ // Create a page that has scroll snaps enabled for a scroller. Tap on the
+ // scrollbar and verify that the SnapController does not immediately cancel
+ // the resulting animation during the handling of GestureScrollEnd - this
+ // should be deferred until the animation completes or is cancelled.
+
+ // Enable scroll animations - this test relies on animations being
+ // queued up in response to GestureScrollUpdate events.
+ GetDocument().GetSettings()->SetScrollAnimatorEnabled(true);
+
+ // Enable accelerated compositing in order to ensure the Page's
+ // ScrollingCoordinator is initialized.
+ GetDocument().GetSettings()->SetAcceleratedCompositingEnabled(true);
+
+ WebView().MainFrameWidget()->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>
+ body { margin:0 }
+ #container {
+ overflow: scroll;
+ width:500px;
+ height:500px;
+ scroll-snap-type: y mandatory;
+ }
+ div {
+ height:400px;
+ scroll-snap-align: start
+ }
+ </style>
+ <body>
+ <div id='container'>
+ <div></div><div></div><div></div>
+ </div>
+ )HTML");
+
+ Compositor().BeginFrame();
+
+ EXPECT_EQ(WebWidgetClient().GetInjectedScrollGestureData().size(), 0u);
+
+ // Only run this test if scrollbars are hit-testable (they are not on
+ // Android).
+ bool scrollbar_theme_allows_hit_test =
+ GetDocument().GetPage()->GetScrollbarTheme().AllowsHitTest();
+ if (!scrollbar_theme_allows_hit_test)
+ return;
+
+ // kGestureTapDown sets the pressed parts which is a pre-requisite for
+ // kGestureTap performing a scroll.
+ const WebFloatPoint scrollbar_forward_track(495, 450);
+ TapDownEventBuilder tap_down(scrollbar_forward_track);
+ GetDocument().GetFrame()->GetEventHandler().HandleGestureEvent(tap_down);
+
+ TapEventBuilder tap(scrollbar_forward_track, 1);
+ GetDocument().GetFrame()->GetEventHandler().HandleGestureEvent(tap);
+ EXPECT_EQ(WebWidgetClient().GetInjectedScrollGestureData().size(), 3u);
+
+ const Vector<frame_test_helpers::InjectedScrollGestureData>& data =
+ WebWidgetClient().GetInjectedScrollGestureData();
+ const frame_test_helpers::InjectedScrollGestureData gsb_data = data[0];
+ const frame_test_helpers::InjectedScrollGestureData gsu_data = data[1];
+ const frame_test_helpers::InjectedScrollGestureData gse_data = data[2];
+ EXPECT_EQ(gsb_data.type, WebInputEvent::Type::kGestureScrollBegin);
+ EXPECT_EQ(gsu_data.type, WebInputEvent::Type::kGestureScrollUpdate);
+ EXPECT_EQ(gse_data.type, WebInputEvent::Type::kGestureScrollEnd);
+
+ // Inject the gesture sequence based on the injected data.
+ WebGestureEvent gsb{WebInputEvent::kGestureScrollBegin,
+ WebInputEvent::kNoModifiers,
+ WebInputEvent::GetStaticTimeStampForTests()};
+ gsb.SetFrameScale(1);
+ gsb.SetSourceDevice(WebGestureDevice::kScrollbar);
+ gsb.data.scroll_begin.delta_x_hint = -gsb_data.delta.width;
+ gsb.data.scroll_begin.delta_y_hint = -gsb_data.delta.height;
+ gsb.data.scroll_begin.scrollable_area_element_id =
+ gsb_data.scrollable_area_element_id.GetInternalValue();
+ GetDocument().GetFrame()->GetEventHandler().HandleGestureEvent(gsb);
+ WebGestureEvent gsu{WebInputEvent::kGestureScrollUpdate,
+ WebInputEvent::kNoModifiers,
+ WebInputEvent::GetStaticTimeStampForTests()};
+ gsu.SetSourceDevice(WebGestureDevice::kScrollbar);
+ gsu.SetFrameScale(1);
+ gsu.data.scroll_update.delta_x = -gsu_data.delta.width;
+ gsu.data.scroll_update.delta_y = -gsu_data.delta.height;
+ gsu.data.scroll_update.delta_units = gsu_data.granularity;
+ GetDocument().GetFrame()->GetEventHandler().HandleGestureEvent(gsu);
+ WebGestureEvent gse{WebInputEvent::kGestureScrollEnd,
+ WebInputEvent::kNoModifiers,
+ WebInputEvent::GetStaticTimeStampForTests()};
+ gse.SetSourceDevice(WebGestureDevice::kScrollbar);
+ gse.SetFrameScale(1);
+ GetDocument().GetFrame()->GetEventHandler().HandleGestureEvent(gse);
+
+ // Ensure that there is an active animation on the scrollable area event
+ // though GSE was handled. The actual handling should be deferred.
+ Element* scrollable_div = GetDocument().getElementById("container");
+ ScrollableArea* scrollable_area =
+ scrollable_div->GetLayoutBox()->GetScrollableArea();
+ EXPECT_TRUE(scrollable_area->ExistingScrollAnimator());
+ EXPECT_TRUE(scrollable_area->ExistingScrollAnimator()->HasRunningAnimation());
+
+ // Run the animation for a few frames to ensure that snapping did not
+ // immediately happen.
+ // One frame to update run_state_, one to set start_time = now, then advance
+ // two frames into the animation.
+ const int kFramesToRun = 4;
+ for (int i = 0; i < kFramesToRun; i++)
+ Compositor().BeginFrame();
+
+ EXPECT_NE(scrollable_area->GetScrollOffset().Height(), 0);
+
+ // Finish the animation, verify that we're back at 0 and not animating.
+ Compositor().BeginFrame(0.3);
+
+ EXPECT_EQ(scrollable_area->GetScrollOffset().Height(), 0);
+ EXPECT_FALSE(
+ scrollable_area->ExistingScrollAnimator()->HasRunningAnimation());
}
// Test that leaving a window leaves mouse position unknown.
@@ -1401,11 +1569,11 @@ TEST_F(EventHandlerSimTest, CursorStyleBeforeStartDragging) {
mouse_move_event.SetFrameScale(1);
GetDocument().GetFrame()->GetEventHandler().HandleMouseMoveEvent(
mouse_move_event, Vector<WebMouseEvent>(), Vector<WebMouseEvent>());
- EXPECT_EQ(Cursor::Type::kHelp, GetDocument()
- .GetFrame()
- ->GetChromeClient()
- .LastSetCursorForTesting()
- .GetType());
+ EXPECT_EQ(ui::CursorType::kHelp, GetDocument()
+ .GetFrame()
+ ->GetChromeClient()
+ .LastSetCursorForTesting()
+ .GetType());
}
// Ensure that tap on element in iframe should apply active state.
@@ -1467,7 +1635,7 @@ TEST_F(EventHandlerSimTest, TapActiveInFrame) {
EXPECT_TRUE(iframe_doc->GetActiveElement());
// The active will cancel after 15ms.
- test::RunDelayedTasks(TimeDelta::FromSecondsD(0.2));
+ test::RunDelayedTasks(base::TimeDelta::FromSecondsD(0.2));
EXPECT_FALSE(GetDocument().GetActiveElement());
EXPECT_FALSE(iframe_doc->GetActiveElement());
}
@@ -1475,7 +1643,7 @@ TEST_F(EventHandlerSimTest, TapActiveInFrame) {
// Test that the hover is updated at the next begin frame after the compositor
// scroll ends.
TEST_F(EventHandlerSimTest, TestUpdateHoverAfterCompositorScrollAtBeginFrame) {
- RuntimeEnabledFeatures::SetUpdateHoverFromScrollAtBeginFrameEnabled(true);
+ ScopedUpdateHoverAtBeginFrameForTest scoped_feature(true);
WebView().MainFrameWidget()->Resize(WebSize(800, 600));
SimRequest request("https://example.com/test.html", "text/html");
LoadURL("https://example.com/test.html");
@@ -1512,25 +1680,7 @@ TEST_F(EventHandlerSimTest, TestUpdateHoverAfterCompositorScrollAtBeginFrame) {
Compositor().BeginFrame();
// Set mouse position and active web view.
- WebMouseEvent mouse_down_event(WebMouseEvent::kMouseDown, WebFloatPoint(1, 1),
- WebFloatPoint(1, 1),
- WebPointerProperties::Button::kLeft, 1,
- WebInputEvent::Modifiers::kLeftButtonDown,
- WebInputEvent::GetStaticTimeStampForTests());
- mouse_down_event.SetFrameScale(1);
- GetDocument().GetFrame()->GetEventHandler().HandleMousePressEvent(
- mouse_down_event);
-
- WebMouseEvent mouse_up_event(
- WebInputEvent::kMouseUp, WebFloatPoint(1, 1), WebFloatPoint(1, 1),
- WebPointerProperties::Button::kLeft, 1, WebInputEvent::kNoModifiers,
- WebInputEvent::GetStaticTimeStampForTests());
- mouse_up_event.SetFrameScale(1);
- GetDocument().GetFrame()->GetEventHandler().HandleMouseReleaseEvent(
- mouse_up_event);
-
- WebView().MainFrameWidget()->SetFocus(true);
- WebView().SetIsActive(true);
+ InitializeMousePositionAndActivateView(1, 1);
WebElement element1 = GetDocument().getElementById("line1");
WebElement element2 = GetDocument().getElementById("line2");
@@ -1561,7 +1711,7 @@ TEST_F(EventHandlerSimTest, TestUpdateHoverAfterCompositorScrollAtBeginFrame) {
// Test that the hover is updated at the next begin frame after the main thread
// scroll ends.
TEST_F(EventHandlerSimTest, TestUpdateHoverAfterMainThreadScrollAtBeginFrame) {
- RuntimeEnabledFeatures::SetUpdateHoverFromScrollAtBeginFrameEnabled(true);
+ ScopedUpdateHoverAtBeginFrameForTest scoped_feature(true);
WebView().MainFrameWidget()->Resize(WebSize(800, 600));
SimRequest request("https://example.com/test.html", "text/html");
LoadURL("https://example.com/test.html");
@@ -1598,25 +1748,7 @@ TEST_F(EventHandlerSimTest, TestUpdateHoverAfterMainThreadScrollAtBeginFrame) {
Compositor().BeginFrame();
// Set mouse position and active web view.
- WebMouseEvent mouse_down_event(WebMouseEvent::kMouseDown, WebFloatPoint(1, 1),
- WebFloatPoint(1, 1),
- WebPointerProperties::Button::kLeft, 1,
- WebInputEvent::Modifiers::kLeftButtonDown,
- WebInputEvent::GetStaticTimeStampForTests());
- mouse_down_event.SetFrameScale(1);
- GetDocument().GetFrame()->GetEventHandler().HandleMousePressEvent(
- mouse_down_event);
-
- WebMouseEvent mouse_up_event(
- WebInputEvent::kMouseUp, WebFloatPoint(1, 1), WebFloatPoint(1, 1),
- WebPointerProperties::Button::kLeft, 1, WebInputEvent::kNoModifiers,
- WebInputEvent::GetStaticTimeStampForTests());
- mouse_up_event.SetFrameScale(1);
- GetDocument().GetFrame()->GetEventHandler().HandleMouseReleaseEvent(
- mouse_up_event);
-
- WebView().MainFrameWidget()->SetFocus(true);
- WebView().SetIsActive(true);
+ InitializeMousePositionAndActivateView(1, 1);
WebElement element1 = GetDocument().getElementById("line1");
WebElement element2 = GetDocument().getElementById("line2");
@@ -1625,28 +1757,13 @@ TEST_F(EventHandlerSimTest, TestUpdateHoverAfterMainThreadScrollAtBeginFrame) {
EXPECT_EQ("hover over me", element2.InnerHTML().Utf8());
EXPECT_EQ("hover over me", element3.InnerHTML().Utf8());
- // Send scroll gesture events which will set
- // |hover_needs_update_at_scroll_end_| to be true in ScrollManager.
- WebGestureEvent scroll_begin_event(
- WebInputEvent::kGestureScrollBegin, WebInputEvent::kNoModifiers,
- WebInputEvent::GetStaticTimeStampForTests(),
- blink::WebGestureDevice::kTouchpad);
- WebGestureEvent scroll_update_event(
- WebInputEvent::kGestureScrollUpdate, WebInputEvent::kNoModifiers,
- WebInputEvent::GetStaticTimeStampForTests(),
- blink::WebGestureDevice::kTouchpad);
- scroll_update_event.data.scroll_update.delta_y = -500;
- WebGestureEvent scroll_end_event(WebInputEvent::kGestureScrollEnd,
- WebInputEvent::kNoModifiers,
- WebInputEvent::GetStaticTimeStampForTests(),
- blink::WebGestureDevice::kTouchpad);
- WebView().MainFrameWidget()->HandleInputEvent(
- WebCoalescedInputEvent(scroll_begin_event));
- WebView().MainFrameWidget()->HandleInputEvent(
- WebCoalescedInputEvent(scroll_update_event));
- WebView().MainFrameWidget()->HandleInputEvent(
- WebCoalescedInputEvent(scroll_end_event));
+ // Send scroll gesture events which will cause scroll happen in main thread
+ // and mark hover state dirty in ScrollManager.
LocalFrameView* frame_view = GetDocument().View();
+ constexpr float delta_y = 500;
+ InjectScrollFromGestureEvents(
+ frame_view->LayoutViewport()->GetCompositorElementId().GetInternalValue(),
+ 0, delta_y);
ASSERT_EQ(500, frame_view->LayoutViewport()->GetScrollOffset().Height());
EXPECT_EQ("currently hovered", element1.InnerHTML().Utf8());
EXPECT_EQ("hover over me", element2.InnerHTML().Utf8());
@@ -1659,10 +1776,83 @@ TEST_F(EventHandlerSimTest, TestUpdateHoverAfterMainThreadScrollAtBeginFrame) {
EXPECT_EQ("hover over me", element3.InnerHTML().Utf8());
}
+// Test that the hover is updated at the next begin frame after the main thread
+// scroll ends in an iframe.
+TEST_F(EventHandlerSimTest,
+ TestUpdateHoverAfterMainThreadScrollInIFrameAtBeginFrame) {
+ ScopedUpdateHoverAtBeginFrameForTest scoped_feature(true);
+ WebView().MainFrameWidget()->Resize(WebSize(800, 600));
+ SimRequest main_resource("https://example.com/test.html", "text/html");
+ SimRequest frame_resource("https://example.com/iframe.html", "text/html");
+ LoadURL("https://example.com/test.html");
+ main_resource.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ body {
+ margin: 0;
+ }
+ iframe {
+ width: 800px;
+ height: 600px;
+ }
+ </style>
+ <iframe id='iframe' src='iframe.html'>
+ </iframe>
+ )HTML");
+
+ frame_resource.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ body, html {
+ margin: 0;
+ height: 500vh;
+ }
+ div {
+ height: 500px;
+ width: 100%;
+ }
+ </style>
+ <body>
+ <div class="hoverme" id="hoverarea">hover over me</div>
+ </body>
+ )HTML");
+ Compositor().BeginFrame();
+
+ auto* iframe_element =
+ ToHTMLIFrameElement(GetDocument().getElementById("iframe"));
+ Document* iframe_doc = iframe_element->contentDocument();
+ FrameView* child_frame_view =
+ iframe_element->GetLayoutEmbeddedContent()->ChildFrameView();
+ auto* local_child_frame_view = DynamicTo<LocalFrameView>(child_frame_view);
+ ScrollableArea* iframe_scrollable_area =
+ local_child_frame_view->GetScrollableArea();
+
+ // Set mouse position and active web view.
+ InitializeMousePositionAndActivateView(100, 100);
+
+ Element* element = iframe_doc->getElementById("hoverarea");
+ EXPECT_TRUE(element->IsHovered());
+
+ // Send scroll gesture events which will cause scroll happen in main thread
+ // and mark hover state dirty in ScrollManager.
+ constexpr float delta_y = 1000;
+ InjectScrollFromGestureEvents(
+ iframe_scrollable_area->GetCompositorElementId().GetInternalValue(), 0,
+ delta_y);
+ LocalFrameView* frame_view = GetDocument().View();
+ ASSERT_EQ(0, frame_view->LayoutViewport()->GetScrollOffset().Height());
+ ASSERT_EQ(1000, iframe_scrollable_area->ScrollOffsetInt().Height());
+ EXPECT_TRUE(element->IsHovered());
+
+ // The fake mouse move event is dispatched at the begin frame to update hover.
+ Compositor().BeginFrame();
+ EXPECT_FALSE(element->IsHovered());
+}
+
// Test that the hover is updated at the next begin frame after the smooth JS
// scroll ends.
TEST_F(EventHandlerSimTest, TestUpdateHoverAfterJSScrollAtBeginFrame) {
- RuntimeEnabledFeatures::SetUpdateHoverFromScrollAtBeginFrameEnabled(true);
+ ScopedUpdateHoverAtBeginFrameForTest scoped_feature(true);
WebView().MainFrameWidget()->Resize(WebSize(800, 500));
SimRequest request("https://example.com/test.html", "text/html");
LoadURL("https://example.com/test.html");
@@ -1685,17 +1875,7 @@ TEST_F(EventHandlerSimTest, TestUpdateHoverAfterJSScrollAtBeginFrame) {
Compositor().BeginFrame();
// Set mouse position and active web view.
- WebMouseEvent mouse_move_event(
- WebMouseEvent::kMouseMove, WebFloatPoint(100, 100),
- WebFloatPoint(100, 100), WebPointerProperties::Button::kNoButton, 0,
- WebInputEvent::Modifiers::kNoModifiers,
- WebInputEvent::GetStaticTimeStampForTests());
- mouse_move_event.SetFrameScale(1);
- GetDocument().GetFrame()->GetEventHandler().HandleMouseMoveEvent(
- mouse_move_event, Vector<WebMouseEvent>(), Vector<WebMouseEvent>());
-
- WebView().MainFrameWidget()->SetFocus(true);
- WebView().SetIsActive(true);
+ InitializeMousePositionAndActivateView(100, 100);
Element* element = GetDocument().getElementById("hoverarea");
EXPECT_TRUE(element->IsHovered());
@@ -1731,6 +1911,91 @@ TEST_F(EventHandlerSimTest, TestUpdateHoverAfterJSScrollAtBeginFrame) {
EXPECT_FALSE(element->IsHovered());
}
+// Test that the hover is only updated at the next begin frame after the main
+// thread scroll snap animation finishes.
+TEST_F(EventHandlerSimTest,
+ TestUpdateHoverAfterMainThreadScrollSnapAtBeginFrame) {
+ ScopedUpdateHoverAtBeginFrameForTest scoped_feature(true);
+ WebView().MainFrameWidget()->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>
+ div {
+ position: absolute;
+ }
+ #scroller {
+ width: 500px;
+ height: 500px;
+ overflow: scroll;
+ scroll-snap-type: both mandatory;
+ border: solid black 5px;
+ }
+ .target:hover {
+ background-color: red;
+ }
+
+ .target {
+ width: 200px;
+ height: 800px;
+ scroll-snap-align: start;
+ background-color: blue;
+ }
+ </style>
+ <body>
+ <div id="scroller">
+ <div class="target" id="target1" style="left: 0px; top: 0px;"></div>
+ <div class="target" id="target2" style="left: 80px; top: 400px;"></div>
+ </div>
+ </body>
+ )HTML");
+ Compositor().BeginFrame();
+
+ // Set mouse position and active web view.
+ InitializeMousePositionAndActivateView(150, 150);
+ Compositor().BeginFrame();
+
+ Element* const scroller = GetDocument().getElementById("scroller");
+ Element* target1 = GetDocument().getElementById("target1");
+ Element* target2 = GetDocument().getElementById("target2");
+ EXPECT_TRUE(target1->IsHovered());
+ EXPECT_FALSE(target2->IsHovered());
+
+ // Send scroll gesture events which will cause scroll happen in main thread
+ // and the snap animation will happen after gesture scroll end. The hover
+ // state will be marked dirty after the snap animation finishes.
+ ScrollableArea* scrollable_area =
+ scroller->GetLayoutBox()->GetScrollableArea();
+ constexpr float delta_y = 300;
+ InjectScrollFromGestureEvents(
+ scrollable_area->GetCompositorElementId().GetInternalValue(), 0, delta_y);
+ ASSERT_EQ(300, scrollable_area->GetScrollOffset().Height());
+ EXPECT_TRUE(target1->IsHovered());
+ EXPECT_FALSE(target2->IsHovered());
+
+ // Gesture scroll end is received and scroll snap animation starts, but it is
+ // not finished.
+ Compositor().BeginFrame();
+ Compositor().BeginFrame();
+ ASSERT_EQ(300, scrollable_area->GetScrollOffset().Height());
+ EXPECT_TRUE(target1->IsHovered());
+ EXPECT_FALSE(target2->IsHovered());
+
+ // The programmatic scroll animation finishes and the hover state is set to
+ // dirty.
+ Compositor().BeginFrame(1);
+ ASSERT_EQ(400, scrollable_area->GetScrollOffset().Height());
+ EXPECT_TRUE(target1->IsHovered());
+ EXPECT_FALSE(target2->IsHovered());
+
+ // The hover effect on targets is updated after the next begin frame.
+ Compositor().BeginFrame();
+ ASSERT_EQ(400, scrollable_area->GetScrollOffset().Height());
+ EXPECT_FALSE(target1->IsHovered());
+ EXPECT_TRUE(target2->IsHovered());
+}
+
TEST_F(EventHandlerSimTest, LargeCustomCursorIntersectsViewport) {
WebView().MainFrameWidget()->Resize(WebSize(800, 600));
SimRequest request("https://example.com/test.html", "text/html");
@@ -1770,7 +2035,7 @@ TEST_F(EventHandlerSimTest, LargeCustomCursorIntersectsViewport) {
const Cursor& cursor =
GetDocument().GetFrame()->GetChromeClient().LastSetCursorForTesting();
- EXPECT_EQ(Cursor::Type::kCustom, cursor.GetType());
+ EXPECT_EQ(ui::CursorType::kCustom, cursor.GetType());
}
// Now, move the cursor so that it intersects the visual viewport. The cursor
@@ -1786,7 +2051,7 @@ TEST_F(EventHandlerSimTest, LargeCustomCursorIntersectsViewport) {
const Cursor& cursor =
GetDocument().GetFrame()->GetChromeClient().LastSetCursorForTesting();
- EXPECT_EQ(Cursor::Type::kPointer, cursor.GetType());
+ EXPECT_EQ(ui::CursorType::kPointer, cursor.GetType());
}
}
@@ -1829,7 +2094,7 @@ TEST_F(EventHandlerSimTest, SmallCustomCursorIntersectsViewport) {
const Cursor& cursor =
GetDocument().GetFrame()->GetChromeClient().LastSetCursorForTesting();
- EXPECT_EQ(Cursor::Type::kCustom, cursor.GetType());
+ EXPECT_EQ(ui::CursorType::kCustom, cursor.GetType());
}
// Now, move the cursor so that it intersects the visual viewport. The cursor
@@ -1846,7 +2111,7 @@ TEST_F(EventHandlerSimTest, SmallCustomCursorIntersectsViewport) {
const Cursor& cursor =
GetDocument().GetFrame()->GetChromeClient().LastSetCursorForTesting();
- EXPECT_EQ(Cursor::Type::kCustom, cursor.GetType());
+ EXPECT_EQ(ui::CursorType::kCustom, cursor.GetType());
}
}
@@ -2059,6 +2324,79 @@ TEST_F(EventHandlerSimTest, DoNotScrollWithTouchpadIfOverflowIsHidden) {
EXPECT_EQ(0, GetDocument().getElementById("outer")->scrollLeft());
}
+TEST_F(EventHandlerSimTest, GestureScrollUpdateModifiedScrollChain) {
+ WebView().MainFrameWidget()->Resize(WebSize(400, 400));
+ SimRequest request("https://example.com/test.html", "text/html");
+ LoadURL("https://example.com/test.html");
+ request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ #scroller {
+ width: 50vw;
+ height: 50vh;
+ overflow-y: scroll;
+ }
+ .inline {
+ display:inline;
+ }
+ .content {
+ height: 300vh;
+ }
+ </style>
+ <body>
+ <div id='scroller'>
+ <div class='content'>
+ </div>
+ </body>
+ )HTML");
+ Compositor().BeginFrame();
+
+ WebGestureEvent scroll_begin_event(
+ WebInputEvent::kGestureScrollBegin, WebInputEvent::kNoModifiers,
+ WebInputEvent::GetStaticTimeStampForTests(),
+ blink::WebGestureDevice::kTouchpad);
+ scroll_begin_event.SetPositionInWidget(WebFloatPoint(10, 10));
+ scroll_begin_event.SetPositionInScreen(WebFloatPoint(10, 10));
+ scroll_begin_event.SetFrameScale(1);
+
+ WebGestureEvent scroll_update_event(
+ WebInputEvent::kGestureScrollUpdate, WebInputEvent::kNoModifiers,
+ WebInputEvent::GetStaticTimeStampForTests(),
+ blink::WebGestureDevice::kTouchpad);
+ scroll_update_event.data.scroll_update.delta_x = 0;
+ scroll_update_event.data.scroll_update.delta_y = -100;
+ scroll_update_event.SetPositionInWidget(WebFloatPoint(10, 10));
+ scroll_update_event.SetPositionInScreen(WebFloatPoint(10, 10));
+ scroll_update_event.SetFrameScale(1);
+
+ WebGestureEvent scroll_end_event(WebInputEvent::kGestureScrollEnd,
+ WebInputEvent::kNoModifiers,
+ WebInputEvent::GetStaticTimeStampForTests(),
+ blink::WebGestureDevice::kTouchpad);
+ scroll_end_event.SetPositionInWidget(WebFloatPoint(10, 10));
+ scroll_end_event.SetPositionInScreen(WebFloatPoint(10, 10));
+
+ WebView().MainFrameWidget()->HandleInputEvent(
+ WebCoalescedInputEvent(scroll_begin_event));
+
+ // Between the GSB (when the scroll chain is computed) and GSU, update the
+ // scroller to be display:inline. Applying the scroll should handle this
+ // by detecting a non-box LayoutObject in the scroll chain and not crash.
+ Element* const scroller = GetDocument().getElementById("scroller");
+ scroller->setAttribute("class", "inline");
+
+ WebView().MainFrameWidget()->HandleInputEvent(
+ WebCoalescedInputEvent(scroll_update_event));
+ WebView().MainFrameWidget()->HandleInputEvent(
+ WebCoalescedInputEvent(scroll_end_event));
+
+ EXPECT_EQ(scroller->scrollTop(), 0);
+
+ // Since the scroller is now display:inline, the scroll should be routed to
+ // the document instead.
+ EXPECT_EQ(GetDocument().documentElement()->scrollTop(), 100);
+}
+
TEST_F(EventHandlerSimTest, ElementTargetedGestureScroll) {
WebView().MainFrameWidget()->Resize(WebSize(800, 600));
SimRequest request("https://example.com/test.html", "text/html");
@@ -2258,4 +2596,355 @@ TEST_F(EventHandlerSimTest, ElementTargetedGestureScrollViewport) {
ASSERT_EQ(visual_viewport.GetScrollOffset().Height(), 300);
}
+TEST_F(EventHandlerSimTest, SelecteTransformedTextWhenCapturing) {
+ WebView().MainFrameWidget()->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>
+ <div id='target' style = "width:250px; transform: rotate(180deg)">
+ Some text to select
+ </div>
+ )HTML");
+ Compositor().BeginFrame();
+
+ WebMouseEvent mouse_down_event(WebInputEvent::kMouseDown,
+ WebFloatPoint(100, 20), WebFloatPoint(0, 0),
+ WebPointerProperties::Button::kLeft, 1,
+ WebInputEvent::Modifiers::kLeftButtonDown,
+ WebInputEvent::GetStaticTimeStampForTests());
+ mouse_down_event.SetFrameScale(1);
+ GetDocument().GetFrame()->GetEventHandler().HandleMousePressEvent(
+ mouse_down_event);
+
+ ASSERT_TRUE(GetDocument()
+ .GetFrame()
+ ->GetEventHandler()
+ .GetSelectionController()
+ .MouseDownMayStartSelect());
+
+ Element* target = GetDocument().getElementById("target");
+ GetDocument().GetFrame()->GetEventHandler().SetPointerCapture(
+ PointerEventFactory::kMouseId, target);
+
+ WebMouseEvent mouse_move_event(WebInputEvent::kMouseMove,
+ WebFloatPoint(258, 20), WebFloatPoint(0, 0),
+ WebPointerProperties::Button::kLeft, 1,
+ WebInputEvent::Modifiers::kLeftButtonDown,
+ WebInputEvent::GetStaticTimeStampForTests());
+ mouse_move_event.SetFrameScale(1);
+ GetDocument().GetFrame()->GetEventHandler().HandleMouseMoveEvent(
+ mouse_move_event, Vector<WebMouseEvent>(), Vector<WebMouseEvent>());
+
+ WebMouseEvent mouse_up_event(
+ WebMouseEvent::kMouseUp, WebFloatPoint(258, 20), WebFloatPoint(0, 0),
+ WebPointerProperties::Button::kLeft, 1, WebInputEvent::kNoModifiers,
+ WebInputEvent::GetStaticTimeStampForTests());
+ mouse_up_event.SetFrameScale(1);
+ GetDocument().GetFrame()->GetEventHandler().HandleMouseReleaseEvent(
+ mouse_up_event);
+
+ ASSERT_FALSE(GetDocument()
+ .GetFrame()
+ ->GetEventHandler()
+ .GetSelectionController()
+ .MouseDownMayStartSelect());
+
+ ASSERT_TRUE(GetDocument().GetSelection());
+ EXPECT_EQ("Some text to select", GetDocument().GetSelection()->toString());
+}
+
+// Test that with MouseSubframeNoImplicitCapture enable, mouse down at inner
+// frame and move to outer frame does not capture mouse to inner frame.
+TEST_F(EventHandlerSimTest, MouseDragWithNoSubframeImplicitCapture) {
+ ScopedMouseSubframeNoImplicitCaptureForTest scoped_feature(true);
+ WebView().MainFrameWidget()->Resize(WebSize(800, 600));
+
+ SimRequest main_resource("https://example.com/test.html", "text/html");
+ SimRequest frame_resource("https://example.com/frame.html", "text/html");
+
+ LoadURL("https://example.com/test.html");
+
+ main_resource.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ iframe {
+ width: 200px;
+ height: 200px;
+ }
+ div {
+ width: 200px;
+ height: 200px;
+ }
+ </style>
+ <iframe id='frame' src='frame.html'></iframe>
+ <div id='outside'></div>
+ )HTML");
+
+ frame_resource.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ body {
+ margin: 0;
+ }
+ div {
+ width: 100px;
+ height: 100px;
+ }
+ </style>
+ <div id='target'></div>
+ )HTML");
+ Compositor().BeginFrame();
+
+ WebMouseEvent mouse_down_inside_event(
+ WebMouseEvent::kMouseDown, WebFloatPoint(50, 50), WebFloatPoint(50, 50),
+ WebPointerProperties::Button::kLeft, 0,
+ WebInputEvent::Modifiers::kLeftButtonDown,
+ WebInputEvent::GetStaticTimeStampForTests());
+ mouse_down_inside_event.SetFrameScale(1);
+ WebView().MainFrameWidget()->HandleInputEvent(
+ WebCoalescedInputEvent(mouse_down_inside_event));
+
+ WebMouseEvent mouse_move_inside_event(
+ WebInputEvent::kMouseMove, WebFloatPoint(100, 100),
+ WebFloatPoint(100, 100), WebPointerProperties::Button::kLeft, 1,
+ WebInputEvent::Modifiers::kLeftButtonDown,
+ WebInputEvent::GetStaticTimeStampForTests());
+ mouse_move_inside_event.SetFrameScale(1);
+ WebView().MainFrameWidget()->HandleInputEvent(
+ WebCoalescedInputEvent(mouse_move_inside_event));
+ auto* iframe_element =
+ ToHTMLIFrameElement(GetDocument().getElementById("frame"));
+ Document* iframe_doc = iframe_element->contentDocument();
+ Element* target = iframe_doc->getElementById("target");
+
+ EXPECT_EQ(iframe_doc->GetFrame()
+ ->GetEventHandler()
+ .LastKnownMousePositionInRootFrame(),
+ FloatPoint(100, 100));
+ EXPECT_EQ(iframe_doc->HoverElement(), target);
+ EXPECT_FALSE(target->hasPointerCapture(PointerEventFactory::kMouseId));
+
+ // Without capturing, next mouse move will be send to outer frame.
+ WebMouseEvent mouse_move_outside_event(
+ WebInputEvent::kMouseMove, WebFloatPoint(100, 300),
+ WebFloatPoint(100, 300), WebPointerProperties::Button::kLeft, 1,
+ WebInputEvent::Modifiers::kLeftButtonDown,
+ WebInputEvent::GetStaticTimeStampForTests());
+ mouse_move_outside_event.SetFrameScale(1);
+ WebView().MainFrameWidget()->HandleInputEvent(
+ WebCoalescedInputEvent(mouse_move_outside_event));
+
+ // Mouse is hovering the element in outer frame.
+ EXPECT_FALSE(iframe_doc->HoverElement());
+ EXPECT_TRUE(
+ iframe_doc->GetFrame()->GetEventHandler().IsMousePositionUnknown());
+ EXPECT_EQ(GetDocument().HoverElement(),
+ GetDocument().getElementById("outside"));
+}
+
+// Test that with MouseSubframeNoImplicitCapture enable, mouse down at inner
+// frame, set pointer capture and move to outer frame will capture mouse to
+// the capture target in inner frame.
+TEST_F(EventHandlerSimTest,
+ MouseDragWithPointerCaptureAndNoSubframeImplicitCapture) {
+ ScopedMouseSubframeNoImplicitCaptureForTest scoped_feature(true);
+
+ WebView().MainFrameWidget()->Resize(WebSize(800, 600));
+
+ SimRequest main_resource("https://example.com/test.html", "text/html");
+ SimRequest frame_resource("https://example.com/frame.html", "text/html");
+
+ LoadURL("https://example.com/test.html");
+
+ main_resource.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ iframe {
+ width: 200px;
+ height: 200px;
+ }
+ div {
+ width: 200px;
+ height: 200px;
+ }
+ </style>
+ <iframe id='frame' src='frame.html'></iframe>
+ <div id='outside'></div>
+ )HTML");
+
+ frame_resource.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ body {
+ margin: 0;
+ }
+ div {
+ width: 100px;
+ height: 100px;
+ }
+ </style>
+ <div id='target'></div>
+ )HTML");
+ Compositor().BeginFrame();
+
+ WebMouseEvent mouse_down_inside_event(
+ WebMouseEvent::kMouseDown, WebFloatPoint(50, 50), WebFloatPoint(50, 50),
+ WebPointerProperties::Button::kLeft, 0,
+ WebInputEvent::Modifiers::kLeftButtonDown,
+ WebInputEvent::GetStaticTimeStampForTests());
+ mouse_down_inside_event.SetFrameScale(1);
+ WebView().MainFrameWidget()->HandleInputEvent(
+ WebCoalescedInputEvent(mouse_down_inside_event));
+
+ auto* iframe_element =
+ ToHTMLIFrameElement(GetDocument().getElementById("frame"));
+ Document* iframe_doc = iframe_element->contentDocument();
+ Element* target = iframe_doc->getElementById("target");
+
+ ExceptionState exception(nullptr, ExceptionState::kExecutionContext, "", "");
+
+ target->setPointerCapture(PointerEventFactory::kMouseId, exception);
+ EXPECT_TRUE(target->hasPointerCapture(PointerEventFactory::kMouseId));
+
+ // With pointercapture, next mouse move will be send to inner frame.
+ WebMouseEvent mouse_move_event(
+ WebInputEvent::kMouseMove, WebFloatPoint(100, 300),
+ WebFloatPoint(100, 300), WebPointerProperties::Button::kLeft, 1,
+ WebInputEvent::Modifiers::kLeftButtonDown,
+ WebInputEvent::GetStaticTimeStampForTests());
+ mouse_move_event.SetFrameScale(1);
+ WebView().MainFrameWidget()->HandleInputEvent(
+ WebCoalescedInputEvent(mouse_move_event));
+
+ EXPECT_EQ(iframe_doc->GetFrame()
+ ->GetEventHandler()
+ .LastKnownMousePositionInRootFrame(),
+ FloatPoint(100, 300));
+ EXPECT_EQ(iframe_doc->HoverElement(), target);
+
+ // Release capture and move event will be send to outer frame.
+ target->releasePointerCapture(PointerEventFactory::kMouseId, exception);
+ WebView().MainFrameWidget()->HandleInputEvent(
+ WebCoalescedInputEvent(mouse_move_event));
+
+ // iframe no longer gets mouse move events.
+ EXPECT_FALSE(iframe_doc->HoverElement());
+ EXPECT_TRUE(
+ iframe_doc->GetFrame()->GetEventHandler().IsMousePositionUnknown());
+ // Mouse is hovering the element in outer frame.
+ EXPECT_EQ(GetDocument().HoverElement(),
+ GetDocument().getElementById("outside"));
+}
+
+// Test that mouse right button down and move to an iframe will route the events
+// to iframe correctly.
+TEST_F(EventHandlerSimTest, MouseRightButtonDownMoveToIFrame) {
+ WebView().MainFrameWidget()->Resize(WebSize(800, 600));
+
+ SimRequest main_resource("https://example.com/test.html", "text/html");
+ SimRequest frame_resource("https://example.com/frame.html", "text/html");
+
+ LoadURL("https://example.com/test.html");
+
+ main_resource.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ div {
+ width: 200px;
+ height: 200px;
+ }
+ iframe {
+ width: 200px;
+ height: 200px;
+ }
+ </style>
+ <div></div>
+ <iframe id='frame' src='frame.html'></iframe>
+ )HTML");
+
+ frame_resource.Complete("<!DOCTYPE html>");
+ Compositor().BeginFrame();
+ WebMouseEvent mouse_down_outside_event(
+ WebMouseEvent::kMouseDown, WebFloatPoint(300, 29), WebFloatPoint(300, 29),
+ WebPointerProperties::Button::kRight, 0,
+ WebInputEvent::Modifiers::kRightButtonDown,
+ WebInputEvent::GetStaticTimeStampForTests());
+ mouse_down_outside_event.SetFrameScale(1);
+ WebView().MainFrameWidget()->HandleInputEvent(
+ WebCoalescedInputEvent(mouse_down_outside_event));
+
+ WebMouseEvent mouse_move_outside_event(
+ WebMouseEvent::kMouseMove, WebFloatPoint(300, 29), WebFloatPoint(300, 29),
+ WebPointerProperties::Button::kRight, 0,
+ WebInputEvent::Modifiers::kRightButtonDown,
+ WebInputEvent::GetStaticTimeStampForTests());
+ mouse_move_outside_event.SetFrameScale(1);
+ WebView().MainFrameWidget()->HandleInputEvent(
+ WebCoalescedInputEvent(mouse_move_outside_event));
+
+ WebMouseEvent mouse_move_inside_event(
+ WebMouseEvent::kMouseMove, WebFloatPoint(100, 229),
+ WebFloatPoint(100, 229), WebPointerProperties::Button::kRight, 0,
+ WebInputEvent::Modifiers::kRightButtonDown,
+ WebInputEvent::GetStaticTimeStampForTests());
+ mouse_move_inside_event.SetFrameScale(1);
+ WebView().MainFrameWidget()->HandleInputEvent(
+ WebCoalescedInputEvent(mouse_move_inside_event));
+ EXPECT_FALSE(
+ GetDocument().GetFrame()->GetEventHandler().IsMousePositionUnknown());
+ EXPECT_FALSE(To<LocalFrame>(GetDocument().GetFrame()->Tree().FirstChild())
+ ->GetEventHandler()
+ .IsMousePositionUnknown());
+}
+
+// Tests that pen dragging on an element and moves will keep the element active.
+TEST_F(EventHandlerSimTest, PenDraggingOnElementActive) {
+ WebView().MainFrameWidget()->Resize(WebSize(800, 600));
+
+ SimRequest main_resource("https://example.com/test.html", "text/html");
+ LoadURL("https://example.com/test.html");
+
+ main_resource.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ div {
+ width: 200px;
+ height: 200px;
+ }
+ </style>
+ <div id="target"></div>
+ )HTML");
+
+ Compositor().BeginFrame();
+ WebMouseEvent pen_down(WebMouseEvent::kMouseDown, WebFloatPoint(100, 100),
+ WebFloatPoint(100, 100),
+ WebPointerProperties::Button::kLeft, 0,
+ WebInputEvent::Modifiers::kLeftButtonDown,
+ WebInputEvent::GetStaticTimeStampForTests());
+ pen_down.pointer_type = blink::WebPointerProperties::PointerType::kPen;
+ pen_down.SetFrameScale(1);
+ WebView().MainFrameWidget()->HandleInputEvent(
+ WebCoalescedInputEvent(pen_down));
+
+ WebMouseEvent pen_move(WebMouseEvent::kMouseMove, WebFloatPoint(100, 100),
+ WebFloatPoint(100, 100),
+ WebPointerProperties::Button::kLeft, 0,
+ WebInputEvent::Modifiers::kLeftButtonDown,
+ WebInputEvent::GetStaticTimeStampForTests());
+ pen_move.pointer_type = blink::WebPointerProperties::PointerType::kPen;
+ pen_move.SetFrameScale(1);
+ // Send first mouse move to update mouse event sates.
+ WebView().MainFrameWidget()->HandleInputEvent(
+ WebCoalescedInputEvent(pen_move));
+
+ // Send another mouse move again to update active element to verify mouse
+ // event states.
+ WebView().MainFrameWidget()->HandleInputEvent(
+ WebCoalescedInputEvent(pen_move));
+
+ EXPECT_EQ(GetDocument().GetActiveElement(),
+ GetDocument().getElementById("target"));
+}
+
} // namespace blink
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 6139ed72c42..fc1d1b92024 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
@@ -27,7 +27,7 @@ HitTestResult HitTestResultInFrame(
if (!frame || !frame->ContentLayoutObject())
return result;
if (LocalFrameView* frame_view = frame->View()) {
- LayoutRect rect(LayoutPoint(), LayoutSize(frame_view->Size()));
+ PhysicalRect rect(PhysicalOffset(), PhysicalSize(frame_view->Size()));
if (!location.Intersects(rect))
return result;
}
@@ -104,13 +104,15 @@ ContainerNode* ParentForClickEvent(const Node& node) {
return FlatTreeTraversal::Parent(node);
}
-LayoutPoint ContentPointFromRootFrame(LocalFrame* frame,
- const FloatPoint& point_in_root_frame) {
+PhysicalOffset ContentPointFromRootFrame(
+ LocalFrame* frame,
+ const FloatPoint& point_in_root_frame) {
LocalFrameView* view = frame->View();
// FIXME: Is it really OK to use the wrong coordinates here when view is 0?
// Historically the code would just crash; this is clearly no worse than that.
- return LayoutPoint(view ? view->ConvertFromRootFrame(point_in_root_frame)
- : point_in_root_frame);
+ return PhysicalOffset::FromFloatPointRound(
+ view ? view->ConvertFromRootFrame(point_in_root_frame)
+ : point_in_root_frame);
}
MouseEventWithHitTestResults PerformMouseEventHitTest(
@@ -125,6 +127,30 @@ MouseEventWithHitTestResults PerformMouseEventHitTest(
mev);
}
+bool ShouldDiscardEventTargetingFrame(const WebInputEvent& event,
+ const LocalFrame& frame) {
+ if (!RuntimeEnabledFeatures::DiscardInputToMovingIframesEnabled())
+ return false;
+
+ // There are two different mechanisms for tracking whether an iframe has moved
+ // recently, for OOPIF and in-process iframes. For OOPIF's, frame movement is
+ // tracked in the browser process using hit test data, and it's propagated
+ // in event.GetModifiers(). For in-process iframes, frame movement is tracked
+ // during lifecycle updates, in FrameView::UpdateViewportIntersection, and
+ // propagated via FrameView::RectInParentIsStable.
+ bool should_discard = false;
+ if (frame.NeedsOcclusionTracking() && frame.IsCrossOriginSubframe()) {
+ should_discard =
+ (event.GetModifiers() & WebInputEvent::kTargetFrameMovedRecently) ||
+ !frame.View()->RectInParentIsStable(event.TimeStamp());
+ }
+ if (should_discard) {
+ UseCounter::Count(frame.GetDocument(),
+ WebFeature::kDiscardInputEventToMovingIframe);
+ }
+ return should_discard;
+}
+
LocalFrame* SubframeForTargetNode(Node* node, bool* is_remote_frame) {
if (!node)
return nullptr;
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 1883ce83c19..9d5e6b990ac 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
@@ -8,9 +8,9 @@
#include "third_party/blink/public/platform/web_input_event_result.h"
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
+#include "third_party/blink/renderer/core/layout/geometry/physical_offset.h"
#include "third_party/blink/renderer/core/layout/hit_test_result.h"
#include "third_party/blink/renderer/core/page/event_with_hit_test_results.h"
-#include "third_party/blink/renderer/platform/geometry/layout_point.h"
namespace blink {
@@ -40,8 +40,8 @@ bool IsInDocument(EventTarget*);
ContainerNode* ParentForClickEvent(const Node&);
-LayoutPoint ContentPointFromRootFrame(LocalFrame*,
- const FloatPoint& point_in_root_frame);
+PhysicalOffset ContentPointFromRootFrame(LocalFrame*,
+ const FloatPoint& point_in_root_frame);
MouseEventWithHitTestResults PerformMouseEventHitTest(LocalFrame*,
const HitTestRequest&,
@@ -53,6 +53,13 @@ LocalFrame* GetTargetSubframe(const MouseEventWithHitTestResults&,
LocalFrame* SubframeForTargetNode(Node*, bool* is_remote_frame = nullptr);
+// Intervention: if an input event lands on a cross-origin iframe that has
+// moved or resized recently (recent==500ms), and which contains an
+// IntersectionObserver that is tracking visibility, then the event is quietly
+// discarded.
+bool ShouldDiscardEventTargetingFrame(const WebInputEvent& event,
+ const LocalFrame& frame);
+
class PointerEventTarget {
DISALLOW_NEW();
diff --git a/chromium/third_party/blink/renderer/core/input/fallback_cursor_event_manager.cc b/chromium/third_party/blink/renderer/core/input/fallback_cursor_event_manager.cc
index b691b8bd55e..7da8a252314 100644
--- a/chromium/third_party/blink/renderer/core/input/fallback_cursor_event_manager.cc
+++ b/chromium/third_party/blink/renderer/core/input/fallback_cursor_event_manager.cc
@@ -55,7 +55,8 @@ Node* ParentNode(const Node& node) {
HitTestResult HitTest(LayoutView* layout_view, const IntPoint& point_in_root) {
HitTestRequest request(HitTestRequest::kReadOnly |
- HitTestRequest::kAllowChildFrameContent);
+ HitTestRequest::kAllowChildFrameContent |
+ HitTestRequest::kRetargetForInert);
HitTestLocation location(point_in_root);
HitTestResult result(request, location);
layout_view->HitTest(location, result);
@@ -75,11 +76,9 @@ IntSize ScrollableAreaClipSizeInRootFrame(const ScrollableArea& scrollable) {
LocalFrameView* view = box->GetFrameView();
DCHECK(view);
- LayoutRect layout_rect =
- LayoutRect(scrollable.VisibleContentRect(blink::kIncludeScrollbars));
- layout_rect = view->DocumentToFrame(layout_rect);
- IntRect rect = view->ConvertToRootFrame(EnclosedIntRect(layout_rect));
- return rect.Size();
+ PhysicalRect rect(scrollable.VisibleContentRect(blink::kIncludeScrollbars));
+ rect = view->DocumentToFrame(rect);
+ return view->ConvertToRootFrame(EnclosedIntRect(FloatRect(rect))).Size();
}
IntPoint RootFrameLocationToScrollable(const IntPoint& location_in_root_frame,
@@ -342,7 +341,8 @@ void FallbackCursorEventManager::ComputeLockCursor(
void FallbackCursorEventManager::HandleMouseMoveEvent(const WebMouseEvent& e) {
DCHECK(RuntimeEnabledFeatures::FallbackCursorModeEnabled());
- DCHECK(is_fallback_cursor_mode_on_);
+ // TODO(crbug.com/953393): reenable after bug is fixed.
+ // DCHECK(is_fallback_cursor_mode_on_);
InvalidateCurrentScrollableIfNeeded();
ScrollableArea* scrollable = CurrentScrollingScrollableArea();
@@ -382,7 +382,8 @@ void FallbackCursorEventManager::HandleMouseMoveEvent(const WebMouseEvent& e) {
void FallbackCursorEventManager::HandleMousePressEvent(const WebMouseEvent& e) {
DCHECK(RuntimeEnabledFeatures::FallbackCursorModeEnabled());
- DCHECK(is_fallback_cursor_mode_on_);
+ // TODO(crbug.com/953393): reenable after bug is fixed.
+ // DCHECK(is_fallback_cursor_mode_on_);
ResetCurrentScrollable();
diff --git a/chromium/third_party/blink/renderer/core/input/fallback_cursor_event_manager.h b/chromium/third_party/blink/renderer/core/input/fallback_cursor_event_manager.h
index f1a0178cc4c..81a4e4c17b3 100644
--- a/chromium/third_party/blink/renderer/core/input/fallback_cursor_event_manager.h
+++ b/chromium/third_party/blink/renderer/core/input/fallback_cursor_event_manager.h
@@ -10,7 +10,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/visitor.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/input/fallback_cursor_event_manager_test.cc b/chromium/third_party/blink/renderer/core/input/fallback_cursor_event_manager_test.cc
index d186267c771..925a4a56144 100644
--- a/chromium/third_party/blink/renderer/core/input/fallback_cursor_event_manager_test.cc
+++ b/chromium/third_party/blink/renderer/core/input/fallback_cursor_event_manager_test.cc
@@ -13,6 +13,7 @@
#include "third_party/blink/renderer/core/loader/empty_clients.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/platform/testing/runtime_enabled_features_test_helpers.h"
namespace {
@@ -58,13 +59,13 @@ class FallbackCursorChromeClient : public RenderingTestChromeClient {
DISALLOW_COPY_AND_ASSIGN(FallbackCursorChromeClient);
};
-class FallbackCursorEventManagerTest : public RenderingTest {
+class FallbackCursorEventManagerTest : public RenderingTest,
+ private ScopedFallbackCursorModeForTest {
protected:
FallbackCursorEventManagerTest()
: RenderingTest(MakeGarbageCollected<SingleChildLocalFrameClient>()),
- chrome_client_(MakeGarbageCollected<FallbackCursorChromeClient>()) {
- RuntimeEnabledFeatures::SetFallbackCursorModeEnabled(true);
- }
+ ScopedFallbackCursorModeForTest(true),
+ chrome_client_(MakeGarbageCollected<FallbackCursorChromeClient>()) {}
~FallbackCursorEventManagerTest() override {}
@@ -84,7 +85,7 @@ class FallbackCursorEventManagerTest : public RenderingTest {
WebMouseEvent event(WebInputEvent::kMouseMove, WebFloatPoint(x, y),
WebFloatPoint(x, y),
WebPointerProperties::Button::kNoButton, 0,
- WebInputEvent::kNoModifiers, CurrentTimeTicks());
+ WebInputEvent::kNoModifiers, base::TimeTicks::Now());
event.SetFrameScale(scale);
GetDocument().GetFrame()->GetEventHandler().HandleMouseMoveEvent(
event, Vector<WebMouseEvent>(), Vector<WebMouseEvent>());
@@ -102,7 +103,7 @@ class FallbackCursorEventManagerTest : public RenderingTest {
WebMouseEvent event(WebInputEvent::kMouseMove, root_frame_point,
root_frame_point,
WebPointerProperties::Button::kNoButton, 0,
- WebInputEvent::kNoModifiers, CurrentTimeTicks());
+ WebInputEvent::kNoModifiers, base::TimeTicks::Now());
event.SetFrameScale(1.0f);
GetDocument().GetFrame()->GetEventHandler().HandleMouseMoveEvent(
event, Vector<WebMouseEvent>(), Vector<WebMouseEvent>());
@@ -112,7 +113,7 @@ class FallbackCursorEventManagerTest : public RenderingTest {
WebMouseEvent event(
WebInputEvent::kMouseDown, WebFloatPoint(x, y), WebFloatPoint(x, y),
WebPointerProperties::Button::kLeft, 0,
- WebInputEvent::Modifiers::kLeftButtonDown, CurrentTimeTicks());
+ WebInputEvent::Modifiers::kLeftButtonDown, base::TimeTicks::Now());
event.SetFrameScale(1);
GetDocument().GetFrame()->GetEventHandler().HandleMousePressEvent(event);
}
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 5937164ff94..4b3a760f101 100644
--- a/chromium/third_party/blink/renderer/core/input/gesture_manager.cc
+++ b/chromium/third_party/blink/renderer/core/input/gesture_manager.cc
@@ -65,7 +65,8 @@ void GestureManager::Trace(blink::Visitor* visitor) {
HitTestRequest::HitTestRequestType GestureManager::GetHitTypeForGestureType(
WebInputEvent::Type type) {
- HitTestRequest::HitTestRequestType hit_type = HitTestRequest::kTouchEvent;
+ HitTestRequest::HitTestRequestType hit_type =
+ HitTestRequest::kTouchEvent | HitTestRequest::kRetargetForInert;
switch (type) {
case WebInputEvent::kGestureShowPress:
case WebInputEvent::kGestureTapUnconfirmed:
@@ -188,8 +189,6 @@ WebInputEventResult GestureManager::HandleGestureTap(
// note that the position of the frame may have changed, so we need to
// recompute the content co-ordinates (updating layout/style as
// hitTestResultAtPoint normally would).
- // FIXME: Use a hit-test cache to avoid unnecessary hit tests.
- // http://crbug.com/398920
if (current_hit_test.InnerNode()) {
LocalFrame& main_frame = frame_->LocalFrameRoot();
if (!main_frame.View() ||
@@ -253,8 +252,6 @@ WebInputEventResult GestureManager::HandleGestureTap(
frame_->GetChromeClient().OnMouseDown(*result.InnerNode());
}
- // FIXME: Use a hit-test cache to avoid unnecessary hit tests.
- // http://crbug.com/398920
if (current_hit_test.InnerNode()) {
LocalFrame& main_frame = frame_->LocalFrameRoot();
if (main_frame.View()) {
@@ -292,9 +289,7 @@ WebInputEventResult GestureManager::HandleGestureTap(
tapped_element->UpdateDistributionForFlatTreeTraversal();
Node* click_target_node = current_hit_test.InnerNode()->CommonAncestor(
*tapped_element, event_handling_util::ParentForClickEvent);
- Element* click_target_element = nullptr;
- if (click_target_node && click_target_node->IsElementNode())
- click_target_element = ToElement(click_target_node);
+ auto* click_target_element = DynamicTo<Element>(click_target_node);
click_event_result =
mouse_event_manager_->SetMousePositionAndDispatchMouseEvent(
@@ -427,8 +422,8 @@ WebInputEventResult GestureManager::SendContextMenuEventForGesture(
if (!suppress_mouse_events_from_gestures_ && frame_->View()) {
HitTestRequest request(HitTestRequest::kActive);
- LayoutPoint document_point = frame_->View()->ConvertFromRootFrame(
- FlooredIntPoint(targeted_event.Event().PositionInRootFrame()));
+ PhysicalOffset document_point(frame_->View()->ConvertFromRootFrame(
+ FlooredIntPoint(targeted_event.Event().PositionInRootFrame())));
MouseEventWithHitTestResults mev =
frame_->GetDocument()->PerformMouseEventHitTest(request, document_point,
mouse_event);
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 c7e6cfb9f5a..69baae123df 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
@@ -54,13 +54,13 @@ class ImeOnFocusTest : public testing::Test {
protected:
void SendGestureTap(WebView*, IntPoint);
void Focus(const AtomicString& element);
- void RunImeOnFocusTest(std::string file_name,
+ void RunImeOnFocusTest(String file_name,
int,
IntPoint tap_point = IntPoint(-1, -1),
const AtomicString& focus_element = g_null_atom,
- std::string frame = "");
+ String frame = "");
- std::string base_url_;
+ String base_url_;
frame_test_helpers::WebViewHelper web_view_helper_;
Persistent<Document> document_;
};
@@ -87,19 +87,18 @@ void ImeOnFocusTest::Focus(const AtomicString& element) {
}
void ImeOnFocusTest::RunImeOnFocusTest(
- std::string file_name,
+ String file_name,
int expected_virtual_keyboard_request_count,
IntPoint tap_point,
const AtomicString& focus_element,
- std::string frame) {
+ String frame) {
ImeRequestTrackingWebWidgetClient client;
- RegisterMockedURLLoadFromBase(WebString::FromUTF8(base_url_),
- test::CoreTestDataPath(),
- WebString::FromUTF8(file_name));
+ RegisterMockedURLLoadFromBase(WebString(base_url_), test::CoreTestDataPath(),
+ WebString(file_name));
WebViewImpl* web_view =
web_view_helper_.Initialize(nullptr, nullptr, &client);
web_view->MainFrameWidget()->Resize(WebSize(800, 1200));
- LoadFrame(web_view->MainFrameImpl(), base_url_ + file_name);
+ LoadFrame(web_view->MainFrameImpl(), base_url_.Utf8() + file_name.Utf8());
document_ = web_view_helper_.GetWebView()
->MainFrameImpl()
->GetDocument()
@@ -112,13 +111,12 @@ void ImeOnFocusTest::RunImeOnFocusTest(
if (tap_point.X() >= 0 && tap_point.Y() >= 0)
SendGestureTap(web_view, tap_point);
- if (!frame.empty()) {
- RegisterMockedURLLoadFromBase(WebString::FromUTF8(base_url_),
- test::CoreTestDataPath(),
- WebString::FromUTF8(frame));
+ if (!frame.IsEmpty()) {
+ RegisterMockedURLLoadFromBase(WebString(base_url_),
+ test::CoreTestDataPath(), WebString(frame));
WebLocalFrame* child_frame =
web_view->MainFrame()->FirstChild()->ToWebLocalFrame();
- LoadFrame(child_frame, base_url_ + frame);
+ LoadFrame(child_frame, base_url_.Utf8() + frame.Utf8());
}
if (!focus_element.IsNull())
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 726593fa1f6..a09ac6bdfae 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
@@ -185,7 +185,9 @@ WebInputEventResult KeyboardEventManager::KeyEvent(
static_cast<ui::DomKey>(initial_key_event.dom_key));
std::unique_ptr<UserGestureIndicator> gesture_indicator;
- if (!is_modifier && initial_key_event.dom_key != ui::DomKey::ESCAPE) {
+ if (!is_modifier && initial_key_event.dom_key != ui::DomKey::ESCAPE &&
+ (initial_key_event.GetType() == WebInputEvent::kKeyDown ||
+ initial_key_event.GetType() == WebInputEvent::kRawKeyDown)) {
gesture_indicator = LocalFrame::NotifyUserActivation(frame_);
}
diff --git a/chromium/third_party/blink/renderer/core/input/keyboard_event_manager.h b/chromium/third_party/blink/renderer/core/input/keyboard_event_manager.h
index 3f1b4c4de8d..1c4373bcdfa 100644
--- a/chromium/third_party/blink/renderer/core/input/keyboard_event_manager.h
+++ b/chromium/third_party/blink/renderer/core/input/keyboard_event_manager.h
@@ -13,7 +13,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/visitor.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 38265676bdf..20109961259 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
@@ -31,24 +31,26 @@
#include "third_party/blink/renderer/core/layout/hit_test_result.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/page/autoscroll_controller.h"
+#include "third_party/blink/renderer/core/page/chrome_client.h"
#include "third_party/blink/renderer/core/page/drag_controller.h"
#include "third_party/blink/renderer/core/page/drag_state.h"
#include "third_party/blink/renderer/core/page/focus_controller.h"
+#include "third_party/blink/renderer/core/page/pointer_lock_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/svg_document_extensions.h"
#include "third_party/blink/renderer/platform/geometry/float_quad.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
namespace blink {
namespace {
String CanvasRegionId(Node* node, const WebMouseEvent& mouse_event) {
- if (!node->IsElementNode())
+ auto* element = DynamicTo<Element>(node);
+ if (!element)
return String();
- Element* element = ToElement(node);
if (!element->IsInCanvasSubtree())
return String();
@@ -63,44 +65,56 @@ String CanvasRegionId(Node* node, const WebMouseEvent& mouse_event) {
void UpdateMouseMovementXY(const WebMouseEvent& mouse_event,
const FloatPoint* last_position,
+ LocalDOMWindow* dom_window,
MouseEventInit* initializer) {
- if (RuntimeEnabledFeatures::MovementXYInBlinkEnabled() &&
+ if (RuntimeEnabledFeatures::ConsolidatedMovementXYEnabled() &&
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()));
+ // TODO(crbug.com/907309): Current movementX/Y is in physical pixel when
+ // zoom-for-dsf is enabled. Here we apply the device-scale-factor to align
+ // with the current behavior. We need to figure out what is the best
+ // behavior here.
+ float device_scale_factor = 1;
+ if (dom_window && dom_window->GetFrame()) {
+ LocalFrame* frame = dom_window->GetFrame();
+ if (frame->GetPage()->DeviceScaleFactorDeprecated() == 1) {
+ device_scale_factor = frame->GetPage()
+ ->GetChromeClient()
+ .GetScreenInfo()
+ .device_scale_factor;
+ }
}
+ // movementX/Y is type int for now, so we need to truncated the coordinates
+ // before calculate movement.
+ initializer->setMovementX(
+ base::saturated_cast<int>(mouse_event.PositionInScreen().x *
+ device_scale_factor) -
+ base::saturated_cast<int>(last_position->X() * device_scale_factor));
+ initializer->setMovementY(
+ base::saturated_cast<int>(mouse_event.PositionInScreen().y *
+ device_scale_factor) -
+ base::saturated_cast<int>(last_position->Y() * device_scale_factor));
}
}
// The amount of time to wait before sending a fake mouse event triggered
// during a scroll.
-constexpr TimeDelta kFakeMouseMoveIntervalDuringScroll =
- TimeDelta::FromMilliseconds(100);
+constexpr base::TimeDelta kFakeMouseMoveIntervalDuringScroll =
+ base::TimeDelta::FromMilliseconds(100);
// The amount of time to wait before sending a fake mouse event on style and
// layout changes sets to 50Hz, same as common screen refresh rate.
-constexpr TimeDelta kFakeMouseMoveIntervalAfterLayoutChange =
- TimeDelta::FromMilliseconds(20);
+constexpr base::TimeDelta kFakeMouseMoveIntervalAfterLayoutChange =
+ base::TimeDelta::FromMilliseconds(20);
// TODO(crbug.com/653490): Read these values from the OS.
#if defined(OS_MACOSX)
const int kDragThresholdX = 3;
const int kDragThresholdY = 3;
-constexpr TimeDelta kTextDragDelay = TimeDelta::FromSecondsD(0.15);
+constexpr base::TimeDelta kTextDragDelay = base::TimeDelta::FromSecondsD(0.15);
#else
const int kDragThresholdX = 4;
const int kDragThresholdY = 4;
-constexpr TimeDelta kTextDragDelay = TimeDelta::FromSecondsD(0.0);
+constexpr base::TimeDelta kTextDragDelay = base::TimeDelta::FromSecondsD(0.0);
#endif
} // namespace
@@ -132,10 +146,10 @@ void MouseEventManager::Clear() {
click_element_ = nullptr;
mouse_down_element_ = nullptr;
mouse_down_pos_ = IntPoint();
- mouse_down_timestamp_ = TimeTicks();
+ mouse_down_timestamp_ = base::TimeTicks();
mouse_down_ = WebMouseEvent();
svg_pan_ = false;
- drag_start_pos_ = LayoutPoint();
+ drag_start_pos_ = PhysicalOffset();
hover_state_dirty_ = false;
fake_mouse_move_event_timer_.Stop();
ResetDragSource();
@@ -255,7 +269,8 @@ WebInputEventResult MouseEventManager::DispatchMouseEvent(
MouseEvent::SetCoordinatesFromWebPointerProperties(
mouse_event.FlattenTransform(), target_node->GetDocument().domWindow(),
initializer);
- UpdateMouseMovementXY(mouse_event, last_position, initializer);
+ UpdateMouseMovementXY(mouse_event, last_position,
+ target_node->GetDocument().domWindow(), initializer);
initializer->setButton(static_cast<int16_t>(mouse_event.button));
initializer->setButtons(MouseEvent::WebInputEventModifiersToButtons(
mouse_event.GetModifiers()));
@@ -371,9 +386,10 @@ void MouseEventManager::FakeMouseMoveEventTimerFired(TimerBase* timer) {
}
void MouseEventManager::RecomputeMouseHoverStateIfNeeded() {
+ // |RecomputeMouseHoverState| may set |hover_state_dirty_| to be true.
if (HoverStateDirty()) {
- RecomputeMouseHoverState();
hover_state_dirty_ = false;
+ RecomputeMouseHoverState();
}
}
@@ -393,6 +409,10 @@ void MouseEventManager::RecomputeMouseHoverState() {
if (!frame_->GetPage()->IsCursorVisible())
return;
+ // Don't dispatch a synthetic event if pointer is locked.
+ if (frame_->GetPage()->GetPointerLockController().GetElement())
+ return;
+
WebPointerEvent::Button button = WebPointerProperties::Button::kNoButton;
int modifiers = KeyboardEventManager::GetCurrentModifierState() |
WebInputEvent::kRelativeMotionEvent;
@@ -403,7 +423,7 @@ void MouseEventManager::RecomputeMouseHoverState() {
WebMouseEvent fake_mouse_move_event(WebInputEvent::kMouseMove,
last_known_mouse_position_,
last_known_mouse_screen_position_, button,
- 0, modifiers, CurrentTimeTicks());
+ 0, modifiers, base::TimeTicks::Now());
Vector<WebMouseEvent> coalesced_events, predicted_events;
frame_->GetEventHandler().HandleMouseMoveEvent(
TransformWebMouseEvent(view, fake_mouse_move_event), coalesced_events,
@@ -415,17 +435,13 @@ void MouseEventManager::CancelFakeMouseMoveEvent() {
}
void MouseEventManager::MarkHoverStateDirty() {
- DCHECK(
- RuntimeEnabledFeatures::UpdateHoverFromScrollAtBeginFrameEnabled() ||
- RuntimeEnabledFeatures::UpdateHoverFromLayoutChangeAtBeginFrameEnabled());
+ DCHECK(RuntimeEnabledFeatures::UpdateHoverAtBeginFrameEnabled());
DCHECK(frame_->IsLocalRoot());
hover_state_dirty_ = true;
}
bool MouseEventManager::HoverStateDirty() {
- DCHECK(
- RuntimeEnabledFeatures::UpdateHoverFromScrollAtBeginFrameEnabled() ||
- RuntimeEnabledFeatures::UpdateHoverFromLayoutChangeAtBeginFrameEnabled());
+ DCHECK(RuntimeEnabledFeatures::UpdateHoverAtBeginFrameEnabled());
DCHECK(frame_->IsLocalRoot());
return hover_state_dirty_;
}
@@ -648,8 +664,7 @@ void MouseEventManager::SetLastMousePositionAsUnknown() {
void MouseEventManager::MayUpdateHoverWhenContentUnderMouseChanged(
MouseEventManager::UpdateHoverReason update_hover_reason) {
- if (RuntimeEnabledFeatures::
- UpdateHoverFromLayoutChangeAtBeginFrameEnabled() &&
+ if (RuntimeEnabledFeatures::UpdateHoverAtBeginFrameEnabled() &&
update_hover_reason ==
MouseEventManager::UpdateHoverReason::kLayoutOrStyleChanged) {
return;
@@ -657,7 +672,7 @@ void MouseEventManager::MayUpdateHoverWhenContentUnderMouseChanged(
if (update_hover_reason ==
MouseEventManager::UpdateHoverReason::kScrollOffsetChanged &&
- (RuntimeEnabledFeatures::UpdateHoverFromScrollAtBeginFrameEnabled() ||
+ (RuntimeEnabledFeatures::UpdateHoverAtBeginFrameEnabled() ||
mouse_pressed_)) {
return;
}
@@ -673,7 +688,7 @@ void MouseEventManager::MayUpdateHoverWhenContentUnderMouseChanged(
// during a scroll. This avoids a potential source of scroll jank.
// Or dispatch a fake mouse move to update hover states when the layout
// changes.
- TimeDelta interval =
+ base::TimeDelta interval =
update_hover_reason ==
MouseEventManager::UpdateHoverReason::kScrollOffsetChanged
? kFakeMouseMoveIntervalDuringScroll
@@ -732,7 +747,8 @@ WebInputEventResult MouseEventManager::HandleMousePressEvent(
mouse_press_node_ = inner_node;
frame_->GetDocument()->SetSequentialFocusNavigationStartingPoint(inner_node);
- drag_start_pos_ = FlooredIntPoint(event.Event().PositionInRootFrame());
+ drag_start_pos_ =
+ PhysicalOffset(FlooredIntPoint(event.Event().PositionInRootFrame()));
mouse_pressed_ = true;
@@ -767,8 +783,9 @@ WebInputEventResult MouseEventManager::HandleMouseReleaseEvent(
void MouseEventManager::UpdateSelectionForMouseDrag() {
frame_->GetEventHandler()
.GetSelectionController()
- .UpdateSelectionForMouseDrag(drag_start_pos_,
- LayoutPoint(last_known_mouse_position_));
+ .UpdateSelectionForMouseDrag(
+ drag_start_pos_,
+ PhysicalOffset::FromFloatPointRound(last_known_mouse_position_));
}
bool MouseEventManager::HandleDragDropIfPossible(
@@ -785,7 +802,7 @@ bool MouseEventManager::HandleDragDropIfPossible(
WebPointerProperties::Button::kLeft, 1,
modifiers | WebInputEvent::Modifiers::kLeftButtonDown |
WebInputEvent::Modifiers::kIsCompatibilityEventForTouch,
- CurrentTimeTicks());
+ base::TimeTicks::Now());
mouse_down_ = mouse_down_event;
WebMouseEvent mouse_drag_event(
@@ -793,7 +810,7 @@ bool MouseEventManager::HandleDragDropIfPossible(
WebPointerProperties::Button::kLeft, 1,
modifiers | WebInputEvent::Modifiers::kLeftButtonDown |
WebInputEvent::Modifiers::kIsCompatibilityEventForTouch,
- CurrentTimeTicks());
+ base::TimeTicks::Now());
HitTestRequest request(HitTestRequest::kReadOnly);
MouseEventWithHitTestResults mev =
event_handling_util::PerformMouseEventHitTest(frame_, request,
@@ -827,24 +844,12 @@ WebInputEventResult MouseEventManager::HandleMouseDraggedEvent(
frame_->GetSettings()->GetBarrelButtonForDragEnabled())
pen_drag_button = WebPointerProperties::Button::kBarrel;
- // While resetting m_mousePressed here may seem out of place, it turns out
- // to be needed to handle some bugs^Wfeatures in Blink mouse event handling:
- // 1. Certain elements, such as <embed>, capture mouse events. They do not
- // bubble back up. One way for a <embed> to start capturing mouse events
- // is on a mouse press. The problem is the <embed> node only starts
- // capturing mouse events *after* m_mousePressed for the containing frame
- // has already been set to true. As a result, the frame's EventHandler
- // never sees the mouse release event, which is supposed to reset
- // m_mousePressed... so m_mousePressed ends up remaining true until the
- // event handler finally gets another mouse released event. Oops.
- // 2. Dragging doesn't start until after a mouse press event, but a drag
- // that ends as a result of a mouse release does not send a mouse release
- // event. As a result, m_mousePressed also ends up remaining true until
- // the next mouse release event seen by the EventHandler.
+ // Only handles dragging for mouse left button drag and pen drag button.
if ((!is_pen &&
event.Event().button != WebPointerProperties::Button::kLeft) ||
(is_pen && event.Event().button != pen_drag_button)) {
- mouse_pressed_ = false;
+ mouse_down_may_start_drag_ = false;
+ return WebInputEventResult::kNotHandled;
}
// When pressing Esc key while dragging and the object is outside of the
@@ -880,7 +885,7 @@ WebInputEventResult MouseEventManager::HandleMouseDraggedEvent(
frame_->GetEventHandler().GetSelectionController().HandleMouseDraggedEvent(
event, mouse_down_pos_, drag_start_pos_,
- LayoutPoint(last_known_mouse_position_));
+ PhysicalOffset::FromFloatPointRound(last_known_mouse_position_));
// The call into HandleMouseDraggedEvent may have caused a re-layout,
// so get the LayoutObject again.
@@ -917,7 +922,8 @@ bool MouseEventManager::HandleDrag(const MouseEventWithHitTestResults& event,
return false;
if (mouse_down_may_start_drag_) {
- HitTestRequest request(HitTestRequest::kReadOnly);
+ HitTestRequest request(HitTestRequest::kReadOnly |
+ HitTestRequest::kRetargetForInert);
HitTestLocation location(mouse_down_pos_);
HitTestResult result(request, location);
frame_->ContentLayoutObject()->HitTest(location, result);
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 a011f5e5507..18ad3a35448 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
@@ -14,7 +14,7 @@
#include "third_party/blink/renderer/core/page/drag_actions.h"
#include "third_party/blink/renderer/core/page/event_with_hit_test_results.h"
#include "third_party/blink/renderer/platform/timer.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
namespace blink {
@@ -248,10 +248,10 @@ class CORE_EXPORT MouseEventManager final
Member<Element> mouse_down_element_;
IntPoint mouse_down_pos_; // In our view's coords.
- TimeTicks mouse_down_timestamp_;
+ base::TimeTicks mouse_down_timestamp_;
WebMouseEvent mouse_down_;
- LayoutPoint drag_start_pos_;
+ PhysicalOffset drag_start_pos_;
// This indicates that whether we should update the hover at each begin
// frame. This is set to be true after the compositor or main thread scroll
// ends, and at each begin frame, we will dispatch a fake mouse move event to
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 824e1e8e715..9a3074af898 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
@@ -116,10 +116,11 @@ Node* MouseWheelEventManager::FindTargetNode(const WebMouseWheelEvent& event,
const Document* doc,
const LocalFrameView* view) {
DCHECK(doc && doc->GetLayoutView() && view);
- LayoutPoint v_point =
- view->ConvertFromRootFrame(FlooredIntPoint(event.PositionInRootFrame()));
+ PhysicalOffset v_point(
+ view->ConvertFromRootFrame(FlooredIntPoint(event.PositionInRootFrame())));
- HitTestRequest request(HitTestRequest::kReadOnly);
+ HitTestRequest request(HitTestRequest::kReadOnly |
+ HitTestRequest::kRetargetForInert);
HitTestLocation location(v_point);
HitTestResult result(request, location);
doc->GetLayoutView()->HitTest(location, result);
diff --git a/chromium/third_party/blink/renderer/core/input/overscroll_behavior_test.cc b/chromium/third_party/blink/renderer/core/input/overscroll_behavior_test.cc
index 25584c71ee3..06b33633d96 100644
--- a/chromium/third_party/blink/renderer/core/input/overscroll_behavior_test.cc
+++ b/chromium/third_party/blink/renderer/core/input/overscroll_behavior_test.cc
@@ -71,7 +71,7 @@ void OverscrollBehaviorTest::SetInnerOverscrollBehavior(EOverscrollBehavior x,
void OverscrollBehaviorTest::ScrollBegin(double hint_x, double hint_y) {
WebGestureEvent event(WebInputEvent::kGestureScrollBegin,
- WebInputEvent::kNoModifiers, CurrentTimeTicks(),
+ WebInputEvent::kNoModifiers, base::TimeTicks::Now(),
WebGestureDevice::kTouchscreen);
event.SetPositionInWidget(WebFloatPoint(20, 20));
event.SetPositionInScreen(WebFloatPoint(20, 20));
@@ -84,7 +84,7 @@ void OverscrollBehaviorTest::ScrollBegin(double hint_x, double hint_y) {
void OverscrollBehaviorTest::ScrollUpdate(double delta_x, double delta_y) {
WebGestureEvent event(WebInputEvent::kGestureScrollUpdate,
- WebInputEvent::kNoModifiers, CurrentTimeTicks(),
+ WebInputEvent::kNoModifiers, base::TimeTicks::Now(),
WebGestureDevice::kTouchscreen);
event.SetPositionInWidget(WebFloatPoint(20, 20));
event.SetPositionInScreen(WebFloatPoint(20, 20));
@@ -96,7 +96,7 @@ void OverscrollBehaviorTest::ScrollUpdate(double delta_x, double delta_y) {
void OverscrollBehaviorTest::ScrollEnd() {
WebGestureEvent event(WebInputEvent::kGestureScrollEnd,
- WebInputEvent::kNoModifiers, CurrentTimeTicks(),
+ WebInputEvent::kNoModifiers, base::TimeTicks::Now(),
WebGestureDevice::kTouchscreen);
event.SetPositionInWidget(WebFloatPoint(20, 20));
event.SetPositionInScreen(WebFloatPoint(20, 20));
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 4c8debe8c17..1ccbd3b948f 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
@@ -15,7 +15,6 @@
#include "third_party/blink/renderer/core/frame/event_handler_registry.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/canvas/html_canvas_element.h"
#include "third_party/blink/renderer/core/input/event_handler.h"
#include "third_party/blink/renderer/core/input/event_handling_util.h"
@@ -26,6 +25,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/page/pointer_lock_controller.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
namespace blink {
@@ -364,12 +364,14 @@ void PointerEventManager::AdjustTouchPointerEvent(
HitTestRequest::HitTestRequestType hit_type =
HitTestRequest::kTouchEvent | HitTestRequest::kReadOnly |
- HitTestRequest::kActive | HitTestRequest::kListBased;
+ HitTestRequest::kActive | HitTestRequest::kListBased |
+ HitTestRequest::kRetargetForInert;
LocalFrame& root_frame = frame_->LocalFrameRoot();
// TODO(szager): Shouldn't this be PositionInScreen() ?
- LayoutPoint hit_test_point((FloatPoint)pointer_event.PositionInWidget());
- hit_test_point.Move(-hit_rect_size * 0.5f);
- HitTestLocation location(LayoutRect(hit_test_point, hit_rect_size));
+ PhysicalOffset hit_test_point =
+ PhysicalOffset::FromFloatPointRound(pointer_event.PositionInWidget());
+ hit_test_point -= PhysicalOffset(hit_rect_size * 0.5f);
+ HitTestLocation location(PhysicalRect(hit_test_point, hit_rect_size));
HitTestResult hit_test_result =
root_frame.GetEventHandler().HitTestResultAtLocation(location, hit_type);
Node* adjusted_node = nullptr;
@@ -419,11 +421,12 @@ PointerEventManager::ComputePointerEventTarget(
// before firing the event.
if (web_pointer_event.GetType() == WebInputEvent::kPointerDown ||
!pending_pointer_capture_target_.Contains(pointer_id)) {
- HitTestRequest::HitTestRequestType hit_type = HitTestRequest::kTouchEvent |
- HitTestRequest::kReadOnly |
- HitTestRequest::kActive;
+ HitTestRequest::HitTestRequestType hit_type =
+ HitTestRequest::kTouchEvent | HitTestRequest::kReadOnly |
+ HitTestRequest::kActive | HitTestRequest::kRetargetForInert;
HitTestLocation location(frame_->View()->ConvertFromRootFrame(
- LayoutPoint(web_pointer_event.PositionInWidget())));
+ PhysicalOffset::FromFloatPointRound(
+ web_pointer_event.PositionInWidget())));
HitTestResult hit_test_tesult =
frame_->GetEventHandler().HitTestResultAtLocation(location, hit_type);
Element* target = hit_test_tesult.InnerElement();
@@ -462,6 +465,9 @@ WebInputEventResult PointerEventManager::DispatchTouchPointerEvent(
WebInputEventResult result = WebInputEventResult::kHandledSystem;
if (pointer_event_target.target_element &&
pointer_event_target.target_frame && !non_hovering_pointers_canceled_) {
+ SetLastPointerPositionForFrameBoundary(web_pointer_event,
+ pointer_event_target.target_element);
+
PointerEvent* pointer_event = pointer_event_factory_.Create(
web_pointer_event, coalesced_events, predicted_events,
pointer_event_target.target_element
@@ -592,6 +598,30 @@ WebInputEventResult PointerEventManager::HandlePointerEvent(
event_handling_util::PointerEventTarget pointer_event_target =
ComputePointerEventTarget(pointer_event);
+ bool discard = pointer_event_target.target_frame &&
+ event_handling_util::ShouldDiscardEventTargetingFrame(
+ event, *pointer_event_target.target_frame);
+ if (discard) {
+ PointerEvent* pointer_event = pointer_event_factory_.Create(
+ event, coalesced_events, predicted_events,
+ pointer_event_target.target_element
+ ? pointer_event_target.target_element->GetDocument().domWindow()
+ : nullptr);
+ SendTouchPointerEvent(pointer_event_target.target_element,
+ pointer_event_factory_.CreatePointerCancelEvent(
+ pointer_event->pointerId(), event.TimeStamp()),
+ event.hovering);
+
+ WebPointerEvent pointer_cancel_event;
+ pointer_cancel_event.pointer_type = event.pointer_type;
+ pointer_cancel_event.SetTimeStamp(event.TimeStamp());
+ pointer_cancel_event.SetType(WebInputEvent::kPointerCancel);
+ touch_event_manager_->HandleTouchPoint(
+ pointer_cancel_event, coalesced_events, pointer_event_target);
+
+ return WebInputEventResult::kHandledSuppressed;
+ }
+
// Any finger lifting is a user gesture only when it wasn't associated with a
// scroll.
// https://docs.google.com/document/d/1oF1T3O7_E4t1PYHV6gyCwHxOi3ystm0eSL5xZu7nvOg/edit#
@@ -661,21 +691,29 @@ WebInputEventResult PointerEventManager::DirectDispatchMousePointerEvent(
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, predicted_events,
- canvas_region_id);
-
- result = event_handling_util::MergeEventResult(
- result, mouse_event_manager_->DispatchMouseEvent(
- target, mouse_event_type, event, canvas_region_id,
- &last_mouse_position, nullptr));
+ if (!(event.GetModifiers() &
+ WebInputEvent::Modifiers::kRelativeMotionEvent)) {
+ // 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, event.GetType());
+
+ WebInputEventResult result = CreateAndDispatchPointerEvent(
+ target, mouse_event_type, event, coalesced_events, predicted_events,
+ canvas_region_id);
+
+ result = event_handling_util::MergeEventResult(
+ result, mouse_event_manager_->DispatchMouseEvent(
+ target, mouse_event_type, event, canvas_region_id,
+ &last_mouse_position, nullptr));
+ return result;
+ }
+ pointer_event_factory_.SetLastPosition(
+ pointer_event_factory_.GetPointerEventId(event), event.PositionInScreen(),
+ event.GetType());
- return result;
+ return WebInputEventResult::kHandledSuppressed;
}
WebInputEventResult PointerEventManager::SendMousePointerEvent(
@@ -702,7 +740,8 @@ WebInputEventResult PointerEventManager::SendMousePointerEvent(
// pointer_event_factory updates it.
FloatPoint last_mouse_position =
pointer_event_factory_.GetLastPointerPosition(
- PointerEventFactory::kMouseId, mouse_event);
+ pointer_event_factory_.GetPointerEventId(mouse_event), mouse_event,
+ event_type);
PointerEvent* pointer_event = pointer_event_factory_.Create(
web_pointer_event, pointer_coalesced_events, pointer_predicted_events,
@@ -771,9 +810,9 @@ WebInputEventResult PointerEventManager::SendMousePointerEvent(
pointer_event->HasEventPath()) {
for (const auto& context :
pointer_event->GetEventPath().NodeEventContexts()) {
- if (context.GetNode().IsElementNode() &&
- event_handling_util::IsInDocument(&context.GetNode())) {
- mouse_target = ToElement(&context.GetNode());
+ auto* element = DynamicTo<Element>(&context.GetNode());
+ if (element && event_handling_util::IsInDocument(element)) {
+ mouse_target = element;
break;
}
}
@@ -806,7 +845,7 @@ WebInputEventResult PointerEventManager::SendMousePointerEvent(
if (pointer_capture_target_.find(pointer_event->pointerId()) !=
pointer_capture_target_.end()) {
HitTestRequest::HitTestRequestType hit_type =
- HitTestRequest::kRelease;
+ HitTestRequest::kRelease | HitTestRequest::kRetargetForInert;
HitTestRequest request(hit_type);
MouseEventWithHitTestResults mev =
event_handling_util::PerformMouseEventHitTest(frame_, request,
@@ -1006,12 +1045,8 @@ bool PointerEventManager::IsActive(const PointerId pointer_id) const {
// pointer events are the only ones that are directly dispatched from the main
// page managers to their target (event if target is in an iframe) and only
// those managers will keep track of these pointer events.
-bool PointerEventManager::IsTouchPointerIdActiveOnFrame(
- PointerId pointer_id,
- LocalFrame* frame) const {
- if (pointer_event_factory_.GetPointerType(pointer_id) !=
- WebPointerProperties::PointerType::kTouch)
- return false;
+bool PointerEventManager::IsPointerIdActiveOnFrame(PointerId pointer_id,
+ LocalFrame* frame) const {
Element* last_element_receiving_event =
element_under_pointer_.Contains(pointer_id)
? element_under_pointer_.at(pointer_id).target
@@ -1040,6 +1075,24 @@ bool PointerEventManager::PrimaryPointerdownCanceled(
return false;
}
+void PointerEventManager::SetLastPointerPositionForFrameBoundary(
+ const WebPointerEvent& web_pointer_event,
+ Element* new_target) {
+ PointerId pointer_id =
+ pointer_event_factory_.GetPointerEventId(web_pointer_event);
+ Element* last_target = element_under_pointer_.Contains(pointer_id)
+ ? element_under_pointer_.at(pointer_id).target
+ : nullptr;
+ if (!new_target) {
+ pointer_event_factory_.RemoveLastPosition(pointer_id);
+ } else if (!last_target || new_target->GetDocument().GetFrame() !=
+ last_target->GetDocument().GetFrame()) {
+ pointer_event_factory_.SetLastPosition(pointer_id,
+ web_pointer_event.PositionInScreen(),
+ web_pointer_event.GetType());
+ }
+}
+
void PointerEventManager::RemoveLastMousePosition() {
pointer_event_factory_.RemoveLastPosition(PointerEventFactory::kMouseId);
}
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 b3dbf065fad..f02d6ca8a98 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
@@ -14,7 +14,7 @@
#include "third_party/blink/renderer/core/input/boundary_event_dispatcher.h"
#include "third_party/blink/renderer/core/input/touch_event_manager.h"
#include "third_party/blink/renderer/core/page/touch_adjustment.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
namespace blink {
@@ -89,7 +89,7 @@ class CORE_EXPORT PointerEventManager
// Returns whether pointerId is for an active touch pointerevent and whether
// the last event was sent to the given frame.
- bool IsTouchPointerIdActiveOnFrame(PointerId, LocalFrame*) const;
+ bool IsPointerIdActiveOnFrame(PointerId, LocalFrame*) const;
// Returns true if the primary pointerdown corresponding to the given
// |uniqueTouchEventId| was canceled. Also drops stale ids from
@@ -191,6 +191,13 @@ class CORE_EXPORT PointerEventManager
PointerEvent*);
void SetElementUnderPointer(PointerEvent*, Element*);
+ // First movement after entering a new frame should be 0 as the new frame
+ // doesn't have the info for the previous events. This function sets the
+ // LastPosition to be same as current event position when target is in
+ // different frame, so that movement_x/y will be 0.
+ void SetLastPointerPositionForFrameBoundary(const WebPointerEvent& event,
+ Element* target);
+
// Processes the assignment of |m_pointerCaptureTarget| from
// |m_pendingPointerCaptureTarget| and sends the got/lostpointercapture
// events, as per the spec:
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 8d7a7580dc7..a39f43b47df 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
@@ -12,6 +12,7 @@
#include "third_party/blink/renderer/core/input/event_handler.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/runtime_enabled_features_test_helpers.h"
namespace blink {
@@ -162,12 +163,12 @@ TEST_F(PointerEventManagerTest, PointerCancelsOfAllTypes) {
WebView().MainFrameWidget()->HandleInputEvent(WebCoalescedInputEvent(
CreateTestPointerEvent(WebInputEvent::kPointerDown,
WebPointerProperties::PointerType::kTouch),
- std::vector<WebPointerEvent>(), std::vector<WebPointerEvent>()));
+ {}, {}));
WebView().MainFrameWidget()->HandleInputEvent(WebCoalescedInputEvent(
CreateTestPointerEvent(WebInputEvent::kPointerDown,
WebPointerProperties::PointerType::kPen),
- std::vector<WebPointerEvent>(), std::vector<WebPointerEvent>()));
+ {}, {}));
GetEventHandler().HandleMousePressEvent(
CreateTestMouseEvent(WebInputEvent::kMouseDown, WebFloatPoint(100, 100)));
@@ -179,7 +180,7 @@ TEST_F(PointerEventManagerTest, PointerCancelsOfAllTypes) {
WebView().MainFrameWidget()->HandleInputEvent(WebCoalescedInputEvent(
CreateTestPointerEvent(WebInputEvent::kPointerCausedUaAction,
WebPointerProperties::PointerType::kPen),
- std::vector<WebPointerEvent>(), std::vector<WebPointerEvent>()));
+ {}, {}));
ASSERT_EQ(callback->mouseEventCount(), 0);
ASSERT_EQ(callback->touchEventCount(), 1);
ASSERT_EQ(callback->penEventCount(), 1);
@@ -187,7 +188,7 @@ TEST_F(PointerEventManagerTest, PointerCancelsOfAllTypes) {
WebView().MainFrameWidget()->HandleInputEvent(WebCoalescedInputEvent(
CreateTestPointerEvent(WebInputEvent::kPointerCausedUaAction,
WebPointerProperties::PointerType::kTouch),
- std::vector<WebPointerEvent>(), std::vector<WebPointerEvent>()));
+ {}, {}));
ASSERT_EQ(callback->mouseEventCount(), 0);
ASSERT_EQ(callback->touchEventCount(), 1);
ASSERT_EQ(callback->penEventCount(), 1);
@@ -219,7 +220,7 @@ TEST_F(PointerEventManagerTest, PointerEventCoordinates) {
WebPointerProperties::PointerType::kTouch,
WebFloatPoint(150, 200), WebFloatPoint(100, 50),
10, 10, 16, 24),
- std::vector<WebPointerEvent>(), std::vector<WebPointerEvent>()));
+ {}, {}));
ASSERT_EQ(callback->last_client_x_, 75);
ASSERT_EQ(callback->last_client_y_, 100);
@@ -245,28 +246,144 @@ TEST_F(PointerEventManagerTest, PointerEventMovements) {
GetDocument().body()->addEventListener(event_type_names::kPointermove,
callback);
+ {
+ // Turn on the flag for test.
+ ScopedConsolidatedMovementXYForTest scoped_feature(true);
+
+ WebView().MainFrameWidget()->HandleInputEvent(WebCoalescedInputEvent(
+ CreateTestPointerEvent(WebInputEvent::kPointerMove,
+ WebPointerProperties::PointerType::kMouse,
+ WebFloatPoint(150, 210), WebFloatPoint(100, 50),
+ 10, 10),
+ {}, {}));
+ // 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().MainFrameWidget()->HandleInputEvent(WebCoalescedInputEvent(
+ CreateTestPointerEvent(WebInputEvent::kPointerMove,
+ WebPointerProperties::PointerType::kMouse,
+ WebFloatPoint(150, 200), WebFloatPoint(132, 29),
+ 10, 10),
+ {}, {}));
+ // 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().MainFrameWidget()->HandleInputEvent(WebCoalescedInputEvent(
+ CreateTestPointerEvent(WebInputEvent::kPointerMove,
+ WebPointerProperties::PointerType::kMouse,
+ WebFloatPoint(150, 210),
+ WebFloatPoint(113.8, 32.7), 10, 10),
+ {}, {}));
+ // 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_, -19);
+ ASSERT_FLOAT_EQ(callback->last_movement_y_, 3);
+ }
+
+ {
+ // When flag is off, movementX/Y follows the value in WebPointerProperties.
+ ScopedConsolidatedMovementXYForTest scoped_feature(false);
+
+ WebView().MainFrameWidget()->HandleInputEvent(WebCoalescedInputEvent(
+ CreateTestPointerEvent(WebInputEvent::kPointerMove,
+ WebPointerProperties::PointerType::kMouse,
+ WebFloatPoint(150, 210),
+ WebFloatPoint(100, 16.25), 1024, -8765),
+ {}, {}));
+ 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);
+ }
+}
+
+// Test that we are not losing fractions when truncating movements.
+TEST_F(PointerEventManagerTest, PointerEventSmallFractionMovements) {
+ WebView().MainFrameWidget()->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.
+ ScopedConsolidatedMovementXYForTest scoped_feature(true);
+
+ WebPointerEvent pointer_event = CreateTestPointerEvent(
+ WebInputEvent::kPointerMove, WebPointerProperties::PointerType::kMouse,
+ WebFloatPoint(150, 210), WebFloatPoint(113.8, 32.7), 0, 0);
+ WebView().MainFrameWidget()->HandleInputEvent(
+ WebCoalescedInputEvent(pointer_event));
+ ASSERT_FLOAT_EQ(callback->last_movement_x_, 0);
+ ASSERT_FLOAT_EQ(callback->last_movement_y_, 0);
+
+ pointer_event.SetPositionInScreen(113.4, 32.9);
+ WebView().MainFrameWidget()->HandleInputEvent(
+ WebCoalescedInputEvent(pointer_event));
+ ASSERT_FLOAT_EQ(callback->last_movement_x_, 0);
+ ASSERT_FLOAT_EQ(callback->last_movement_y_, 0);
+
+ pointer_event.SetPositionInScreen(113.0, 33.1);
+ WebView().MainFrameWidget()->HandleInputEvent(
+ WebCoalescedInputEvent(pointer_event));
+ ASSERT_FLOAT_EQ(callback->last_movement_x_, 0);
+ ASSERT_FLOAT_EQ(callback->last_movement_y_, 1);
+
+ pointer_event.SetPositionInScreen(112.6, 33.3);
+ WebView().MainFrameWidget()->HandleInputEvent(
+ WebCoalescedInputEvent(pointer_event));
+ ASSERT_FLOAT_EQ(callback->last_movement_x_, -1);
+ ASSERT_FLOAT_EQ(callback->last_movement_y_, 0);
+}
+
+TEST_F(PointerEventManagerTest, PointerRawUpdateMovements) {
+ WebView().MainFrameWidget()->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);
+ GetDocument().body()->addEventListener(event_type_names::kPointerrawupdate,
+ callback);
+
// Turn on the flag for test.
- RuntimeEnabledFeatures::SetMovementXYInBlinkEnabled(true);
+ ScopedConsolidatedMovementXYForTest scoped_feature(true);
WebView().MainFrameWidget()->HandleInputEvent(WebCoalescedInputEvent(
- CreateTestPointerEvent(WebInputEvent::kPointerMove,
+ CreateTestPointerEvent(WebInputEvent::kPointerRawUpdate,
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.
+ {}, {}));
+ // The first pointerrawupdate 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().MainFrameWidget()->HandleInputEvent(WebCoalescedInputEvent(
- CreateTestPointerEvent(WebInputEvent::kPointerMove,
+ CreateTestPointerEvent(WebInputEvent::kPointerRawUpdate,
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.
+ {}, {}));
+ // pointerrawupdate 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);
@@ -275,29 +392,26 @@ TEST_F(PointerEventManagerTest, PointerEventMovements) {
WebView().MainFrameWidget()->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);
+ WebFloatPoint(150, 200), WebFloatPoint(144, 30),
+ 10, 10),
+ {}, {}));
+ // First pointermove, have 0 movements.
+ ASSERT_EQ(callback->last_screen_x_, 144);
+ ASSERT_EQ(callback->last_screen_y_, 30);
+ ASSERT_EQ(callback->last_movement_x_, 0);
+ ASSERT_EQ(callback->last_movement_y_, 0);
WebView().MainFrameWidget()->HandleInputEvent(WebCoalescedInputEvent(
- CreateTestPointerEvent(WebInputEvent::kPointerMove,
+ CreateTestPointerEvent(WebInputEvent::kPointerRawUpdate,
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);
+ WebFloatPoint(150, 200), WebFloatPoint(142, 32),
+ 10, 10),
+ {}, {}));
+ // pointerrawupdate event's movement is independent from pointermoves.
+ ASSERT_EQ(callback->last_screen_x_, 142);
+ ASSERT_EQ(callback->last_screen_y_, 32);
+ ASSERT_EQ(callback->last_movement_x_, 10);
+ ASSERT_EQ(callback->last_movement_y_, 3);
}
} // 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 964a18e17e1..4c6de7e4e61 100644
--- a/chromium/third_party/blink/renderer/core/input/scroll_manager.cc
+++ b/chromium/third_party/blink/renderer/core/input/scroll_manager.cc
@@ -32,8 +32,9 @@
#include "third_party/blink/renderer/core/page/scrolling/snap_coordinator.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/scroll_animator_base.h"
#include "third_party/blink/renderer/core/scroll/scroll_customization.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
namespace blink {
@@ -94,7 +95,6 @@ void ScrollManager::Trace(blink::Visitor* visitor) {
visitor->Trace(previous_gesture_scrolled_node_);
visitor->Trace(scrollbar_handling_scroll_gesture_);
visitor->Trace(resize_scrollable_area_);
- visitor->Trace(last_logical_scrolled_node_);
}
void ScrollManager::ClearGestureScrollState() {
@@ -153,8 +153,8 @@ static bool CanPropagate(const ScrollState& scroll_state, const Node& node) {
void ScrollManager::RecomputeScrollChain(const Node& start_node,
const ScrollState& scroll_state,
- std::deque<DOMNodeId>& scroll_chain) {
- DCHECK(scroll_chain.empty());
+ Deque<DOMNodeId>& scroll_chain) {
+ DCHECK(scroll_chain.IsEmpty());
scroll_chain.clear();
DCHECK(start_node.GetLayoutObject());
@@ -237,11 +237,6 @@ bool ScrollManager::LogicalScroll(ScrollDirection direction,
if (!node)
node = mouse_press_node;
- if ((!node || !node->GetLayoutObject()) &&
- (last_logical_scrolled_node_ &&
- last_logical_scrolled_node_->GetLayoutObject()))
- node = last_logical_scrolled_node_;
-
if ((!node || !node->GetLayoutObject()) && frame_->View() &&
frame_->View()->GetLayoutView())
node = frame_->View()->GetLayoutView()->GetNode();
@@ -253,15 +248,14 @@ bool ScrollManager::LogicalScroll(ScrollDirection direction,
document.UpdateStyleAndLayout();
- std::deque<DOMNodeId> scroll_chain;
+ Deque<DOMNodeId> scroll_chain;
std::unique_ptr<ScrollStateData> scroll_state_data =
std::make_unique<ScrollStateData>();
ScrollState* scroll_state = ScrollState::Create(std::move(scroll_state_data));
RecomputeScrollChain(*node, *scroll_state, scroll_chain);
- while (!scroll_chain.empty()) {
- Node* scroll_chain_node = DOMNodeIds::NodeForId(scroll_chain.back());
- scroll_chain.pop_back();
+ while (!scroll_chain.IsEmpty()) {
+ Node* scroll_chain_node = DOMNodeIds::NodeForId(scroll_chain.TakeLast());
DCHECK(scroll_chain_node);
LayoutBox* box = ToLayoutBox(scroll_chain_node->GetLayoutObject());
@@ -322,13 +316,20 @@ bool ScrollManager::LogicalScroll(ScrollDirection direction,
NOTREACHED();
}
+ ScrollableArea::ScrollCallback callback;
+ if (RuntimeEnabledFeatures::UpdateHoverAtBeginFrameEnabled()) {
+ callback = ScrollableArea::ScrollCallback(WTF::Bind(
+ [](WeakPersistent<ScrollableArea> area) {
+ if (area)
+ area->MarkHoverStateDirty();
+ },
+ WrapWeakPersistent(scrollable_area)));
+ }
ScrollResult result = scrollable_area->UserScroll(
- granularity, ToScrollDelta(physical_direction, 1));
+ granularity, ToScrollDelta(physical_direction, 1), std::move(callback));
- if (result.DidScroll()) {
- last_logical_scrolled_node_ = scroll_chain_node;
+ if (result.DidScroll())
return true;
- }
}
return false;
@@ -364,7 +365,7 @@ void ScrollManager::CustomizedScroll(ScrollState& scroll_state) {
if (scroll_state.deltaX() || scroll_state.deltaY())
frame_->GetDocument()->UpdateStyleAndLayout();
- DCHECK(!current_scroll_chain_.empty());
+ DCHECK(!current_scroll_chain_.IsEmpty());
scroll_state.SetScrollChain(current_scroll_chain_);
@@ -484,7 +485,7 @@ WebInputEventResult ScrollManager::HandleGestureScrollBegin(
TRACE_EVENT_SCOPE_THREAD, "length",
current_scroll_chain_.size());
- if (current_scroll_chain_.empty()) {
+ if (current_scroll_chain_.IsEmpty()) {
// If a child has a non-empty scroll chain, we need to consider that instead
// of simply returning WebInputEventResult::kNotHandled.
return child_result;
@@ -494,10 +495,15 @@ WebInputEventResult ScrollManager::HandleGestureScrollBegin(
CustomizedScroll(*scroll_state);
- if (gesture_event.SourceDevice() == WebGestureDevice::kTouchscreen)
- UseCounter::Count(frame_->GetDocument(), WebFeature::kScrollByTouch);
- else
- UseCounter::Count(frame_->GetDocument(), WebFeature::kScrollByWheel);
+ if (gesture_event.SourceDevice() == WebGestureDevice::kTouchpad &&
+ gesture_event.data.scroll_begin.delta_hint_units ==
+ ui::input_types::ScrollGranularity::kScrollByPrecisePixel) {
+ UseCounter::Count(document, WebFeature::kScrollByPrecisionTouchPad);
+ } else if (gesture_event.SourceDevice() == WebGestureDevice::kTouchscreen) {
+ UseCounter::Count(document, WebFeature::kScrollByTouch);
+ } else {
+ UseCounter::Count(document, WebFeature::kScrollByWheel);
+ }
return WebInputEventResult::kHandledSystem;
}
@@ -562,7 +568,7 @@ WebInputEventResult ScrollManager::HandleGestureScrollUpdate(
return result;
}
- if (current_scroll_chain_.empty()) {
+ if (current_scroll_chain_.IsEmpty()) {
TRACE_EVENT_INSTANT0("input", "Empty Scroll Chain",
TRACE_EVENT_SCOPE_THREAD);
return WebInputEventResult::kNotHandled;
@@ -622,7 +628,7 @@ WebInputEventResult ScrollManager::HandleGestureScrollUpdate(
// Send the overscroll event to the node that scrolling is latched to which
// is either previously scrolled node or the last node in the scroll chain.
Node* overscroll_target = previous_gesture_scrolled_node_;
- if (!overscroll_target && !current_scroll_chain_.empty())
+ if (!overscroll_target && !current_scroll_chain_.IsEmpty())
overscroll_target = DOMNodeIds::NodeForId(current_scroll_chain_.front());
if (overscroll_target) {
@@ -634,14 +640,38 @@ WebInputEventResult ScrollManager::HandleGestureScrollUpdate(
return WebInputEventResult::kNotHandled;
}
+// This method is used as a ScrollCallback which requires a void return. Since
+// this call to HandleGestureScrollEnd is async, we can just ignore the return
+// value.
+void ScrollManager::HandleDeferredGestureScrollEnd(
+ const WebGestureEvent& gesture_event) {
+ HandleGestureScrollEnd(gesture_event);
+}
+
WebInputEventResult ScrollManager::HandleGestureScrollEnd(
const WebGestureEvent& gesture_event) {
TRACE_EVENT0("input", "ScrollManager::handleGestureScrollEnd");
Node* node = scroll_gesture_handling_node_;
+ bool snap_at_gesture_scroll_end = false;
if (node && node->GetLayoutObject()) {
+ // If the GSE is for a scrollable area that has an in-progress animation,
+ // defer the handling of the gesture event until the scroll animation is
+ // complete. This will allow things like scroll snapping to be deferred so
+ // that users can see the result of their scroll before the snap is applied.
+ LayoutBox* layout_box = node->GetLayoutBox();
+ ScrollableArea* scrollable_area =
+ layout_box ? layout_box->GetScrollableArea() : nullptr;
+ if (scrollable_area && scrollable_area->ExistingScrollAnimator() &&
+ scrollable_area->ExistingScrollAnimator()->HasRunningAnimation()) {
+ scrollable_area->RegisterScrollCompleteCallback(
+ WTF::Bind(&ScrollManager::HandleDeferredGestureScrollEnd,
+ WrapWeakPersistent(this), gesture_event));
+ return WebInputEventResult::kNotHandled;
+ }
+
PassScrollGestureEvent(gesture_event, node->GetLayoutObject());
- if (current_scroll_chain_.empty()) {
+ if (current_scroll_chain_.IsEmpty()) {
ClearGestureScrollState();
return WebInputEventResult::kNotHandled;
}
@@ -659,14 +689,14 @@ WebInputEventResult ScrollManager::HandleGestureScrollEnd(
ScrollState* scroll_state =
ScrollState::Create(std::move(scroll_state_data));
CustomizedScroll(*scroll_state);
- SnapAtGestureScrollEnd();
+ snap_at_gesture_scroll_end = SnapAtGestureScrollEnd();
NotifyScrollPhaseEndForCustomizedScroll();
if (RuntimeEnabledFeatures::OverscrollCustomizationEnabled()) {
// Send the scrollend event to the node that scrolling is latched to
// which is either previously scrolled node or the last node in the
// scroll chain.
- DCHECK(!current_scroll_chain_.empty());
+ DCHECK(!current_scroll_chain_.IsEmpty());
if (previous_gesture_scrolled_node_) {
previous_gesture_scrolled_node_->GetDocument()
.EnqueueScrollEndEventForNode(previous_gesture_scrolled_node_);
@@ -680,8 +710,13 @@ WebInputEventResult ScrollManager::HandleGestureScrollEnd(
ClearGestureScrollState();
- if (RuntimeEnabledFeatures::UpdateHoverFromScrollAtBeginFrameEnabled())
- frame_->GetEventHandler().MarkHoverStateDirty();
+ // If we are performing a snap at the scrollend gesture, we should update
+ // hover state dirty at the end of the programmatic scroll animation caused
+ // by the snap, and we should avoid marking the hover state dirty here.
+ if (!snap_at_gesture_scroll_end &&
+ RuntimeEnabledFeatures::UpdateHoverAtBeginFrameEnabled()) {
+ frame_->LocalFrameRoot().GetEventHandler().MarkHoverStateDirty();
+ }
return WebInputEventResult::kNotHandled;
}
@@ -692,19 +727,19 @@ LayoutBox* ScrollManager::LayoutBoxForSnapping() const {
return previous_gesture_scrolled_node_->GetLayoutBox();
}
-void ScrollManager::SnapAtGestureScrollEnd() {
+bool ScrollManager::SnapAtGestureScrollEnd() {
if (!previous_gesture_scrolled_node_ ||
(!did_scroll_x_for_scroll_gesture_ && !did_scroll_y_for_scroll_gesture_))
- return;
+ return false;
SnapCoordinator* snap_coordinator =
frame_->GetDocument()->GetSnapCoordinator();
LayoutBox* layout_box = LayoutBoxForSnapping();
if (!snap_coordinator || !layout_box)
- return;
+ return false;
- snap_coordinator->SnapAtCurrentPosition(*layout_box,
- did_scroll_x_for_scroll_gesture_,
- did_scroll_y_for_scroll_gesture_);
+ return snap_coordinator->SnapAtCurrentPosition(
+ *layout_box, did_scroll_x_for_scroll_gesture_,
+ did_scroll_y_for_scroll_gesture_);
}
bool ScrollManager::GetSnapFlingInfo(
@@ -760,7 +795,7 @@ gfx::Vector2dF ScrollManager::ScrollByForSnapFling(
}
void ScrollManager::ScrollEndForSnapFling() {
- if (current_scroll_chain_.empty()) {
+ if (current_scroll_chain_.IsEmpty()) {
NotifyScrollPhaseEndForCustomizedScroll();
ClearGestureScrollState();
return;
@@ -857,9 +892,10 @@ WebInputEventResult ScrollManager::HandleGestureScrollEvent(
TRACE_EVENT_SCOPE_THREAD);
LocalFrameView* view = frame_->View();
- LayoutPoint view_point = view->ConvertFromRootFrame(
- FlooredIntPoint(gesture_event.PositionInRootFrame()));
- HitTestRequest request(HitTestRequest::kReadOnly);
+ PhysicalOffset view_point(view->ConvertFromRootFrame(
+ FlooredIntPoint(gesture_event.PositionInRootFrame())));
+ HitTestRequest request(HitTestRequest::kReadOnly |
+ HitTestRequest::kRetargetForInert);
HitTestLocation location(view_point);
HitTestResult result(request, location);
document->GetLayoutView()->HitTest(location, result);
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 a72052352db..5ba2d85557a 100644
--- a/chromium/third_party/blink/renderer/core/input/scroll_manager.h
+++ b/chromium/third_party/blink/renderer/core/input/scroll_manager.h
@@ -5,7 +5,6 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_INPUT_SCROLL_MANAGER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_INPUT_SCROLL_MANAGER_H_
-#include <deque>
#include <memory>
#include "base/macros.h"
@@ -19,7 +18,8 @@
#include "third_party/blink/renderer/platform/graphics/compositor_element_id.h"
#include "third_party/blink/renderer/platform/heap/handle.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/allocator/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/deque.h"
namespace blink {
@@ -112,6 +112,10 @@ class CORE_EXPORT ScrollManager
WebInputEventResult HandleGestureScrollUpdate(const WebGestureEvent&);
WebInputEventResult HandleGestureScrollBegin(const WebGestureEvent&);
+ // Handling of GestureScrollEnd may be deferred if there's an outstanding
+ // scroll animation. This is the callback that invokes the deferred operation.
+ void HandleDeferredGestureScrollEnd(const WebGestureEvent& gesture_event);
+
WebInputEventResult PassScrollGestureEvent(const WebGestureEvent&,
LayoutObject*);
@@ -125,7 +129,7 @@ class CORE_EXPORT ScrollManager
void RecomputeScrollChain(const Node& start_node,
const ScrollState&,
- std::deque<DOMNodeId>& scroll_chain);
+ Deque<DOMNodeId>& scroll_chain);
bool CanScroll(const ScrollState&, const Node& current_node);
// scroller_size is set only when scrolling non root scroller.
@@ -136,7 +140,7 @@ class CORE_EXPORT ScrollManager
WebGestureEvent SynthesizeGestureScrollBegin(
const WebGestureEvent& update_event);
- void SnapAtGestureScrollEnd();
+ bool SnapAtGestureScrollEnd();
void NotifyScrollPhaseBeginForCustomizedScroll(const ScrollState&);
void NotifyScrollPhaseEndForCustomizedScroll();
@@ -149,12 +153,10 @@ class CORE_EXPORT ScrollManager
const Member<LocalFrame> frame_;
// Only used with the ScrollCustomization runtime enabled feature.
- std::deque<DOMNodeId> current_scroll_chain_;
+ Deque<DOMNodeId> current_scroll_chain_;
Member<Node> scroll_gesture_handling_node_;
- Member<Node> last_logical_scrolled_node_;
-
bool last_gesture_scroll_over_embedded_content_view_;
// The most recent Node to scroll natively during this scroll
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 0f93fefc34e..b385e838bd9 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
@@ -90,7 +90,7 @@ void ScrollSnapTest::ScrollBegin(double x,
double hint_x,
double hint_y) {
WebGestureEvent event(WebInputEvent::kGestureScrollBegin,
- WebInputEvent::kNoModifiers, CurrentTimeTicks(),
+ WebInputEvent::kNoModifiers, base::TimeTicks::Now(),
WebGestureDevice::kTouchscreen);
event.SetPositionInWidget(WebFloatPoint(x, y));
event.SetPositionInScreen(WebFloatPoint(x, y));
@@ -107,7 +107,7 @@ void ScrollSnapTest::ScrollUpdate(double x,
double delta_y,
bool is_in_inertial_phase) {
WebGestureEvent event(WebInputEvent::kGestureScrollUpdate,
- WebInputEvent::kNoModifiers, CurrentTimeTicks(),
+ WebInputEvent::kNoModifiers, base::TimeTicks::Now(),
WebGestureDevice::kTouchscreen);
event.SetPositionInWidget(WebFloatPoint(x, y));
event.SetPositionInScreen(WebFloatPoint(x, y));
@@ -124,7 +124,7 @@ void ScrollSnapTest::ScrollUpdate(double x,
void ScrollSnapTest::ScrollEnd(double x, double y, bool is_in_inertial_phase) {
WebGestureEvent event(WebInputEvent::kGestureScrollEnd,
- WebInputEvent::kNoModifiers, CurrentTimeTicks(),
+ WebInputEvent::kNoModifiers, base::TimeTicks::Now(),
WebGestureDevice::kTouchscreen);
event.SetPositionInWidget(WebFloatPoint(x, y));
event.SetPositionInScreen(WebFloatPoint(x, y));
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 59a4c0aae17..86780a2ef50 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
@@ -94,14 +94,14 @@ class TouchActionTest : public testing::Test {
public:
TouchActionTest() : base_url_("http://www.test.com/") {
url_test_helpers::RegisterMockedURLLoadFromBase(
- WebString::FromUTF8(base_url_), test::CoreTestDataPath(),
+ WebString(base_url_), test::CoreTestDataPath(),
"touch-action-tests.css", "text/css");
url_test_helpers::RegisterMockedURLLoadFromBase(
- WebString::FromUTF8(base_url_), test::CoreTestDataPath(),
- "touch-action-tests.js", "text/javascript");
+ WebString(base_url_), test::CoreTestDataPath(), "touch-action-tests.js",
+ "text/javascript");
url_test_helpers::RegisterMockedURLLoadFromBase(
- WebString::FromUTF8(base_url_), test::CoreTestDataPath(),
- "white-1x1.png", "image/png");
+ WebString(base_url_), test::CoreTestDataPath(), "white-1x1.png",
+ "image/png");
}
void TearDown() override {
@@ -111,20 +111,20 @@ class TouchActionTest : public testing::Test {
}
protected:
- void RunTouchActionTest(std::string file);
- void RunShadowDOMTest(std::string file);
- void RunIFrameTest(std::string file);
+ void RunTouchActionTest(String file);
+ void RunShadowDOMTest(String file);
+ void RunIFrameTest(String file);
void SendTouchEvent(WebView*, WebInputEvent::Type, IntPoint client_point);
- WebViewImpl* SetupTest(std::string file, TouchActionTrackingWebWidgetClient*);
+ WebViewImpl* SetupTest(String file, TouchActionTrackingWebWidgetClient*);
void RunTestOnTree(ContainerNode* root,
WebView*,
TouchActionTrackingWebWidgetClient&);
- std::string base_url_;
+ String base_url_;
frame_test_helpers::WebViewHelper web_view_helper_;
};
-void TouchActionTest::RunTouchActionTest(std::string file) {
+void TouchActionTest::RunTouchActionTest(String file) {
TouchActionTrackingWebWidgetClient client;
// runTouchActionTest() loads a document in a frame, setting up a
@@ -147,7 +147,7 @@ void TouchActionTest::RunTouchActionTest(std::string file) {
web_view_helper_.Reset();
}
-void TouchActionTest::RunShadowDOMTest(std::string file) {
+void TouchActionTest::RunShadowDOMTest(String file) {
TouchActionTrackingWebWidgetClient client;
WebViewImpl* web_view = SetupTest(file, &client);
@@ -175,7 +175,7 @@ void TouchActionTest::RunShadowDOMTest(std::string file) {
web_view_helper_.Reset();
}
-void TouchActionTest::RunIFrameTest(std::string file) {
+void TouchActionTest::RunIFrameTest(String file) {
TouchActionTrackingWebWidgetClient client;
WebViewImpl* web_view = SetupTest(file, &client);
@@ -195,14 +195,13 @@ void TouchActionTest::RunIFrameTest(std::string file) {
}
WebViewImpl* TouchActionTest::SetupTest(
- std::string file,
+ String file,
TouchActionTrackingWebWidgetClient* client) {
url_test_helpers::RegisterMockedURLLoadFromBase(
- WebString::FromUTF8(base_url_), test::CoreTestDataPath(),
- WebString::FromUTF8(file));
+ WebString(base_url_), test::CoreTestDataPath(), WebString(file));
// Note that JavaScript must be enabled for shadow DOM tests.
WebViewImpl* web_view = web_view_helper_.InitializeAndLoad(
- base_url_ + file, nullptr, nullptr, client);
+ base_url_.Utf8() + file.Utf8(), nullptr, nullptr, client);
// Set size to enable hit testing, and avoid line wrapping for consistency
// with browser.
@@ -243,19 +242,20 @@ void TouchActionTest::RunTestOnTree(
Element* element = elements->item(index);
element->scrollIntoViewIfNeeded();
- std::string failure_context("Test case: ");
+ StringBuilder failure_context;
+ failure_context.Append("Test case: ");
if (element->HasID()) {
- failure_context.append(element->GetIdAttribute().Ascii().data());
+ failure_context.Append(element->GetIdAttribute());
} else if (element->firstChild()) {
- failure_context.append("\"");
- failure_context.append(element->firstChild()
+ failure_context.Append("\"");
+ failure_context.Append(element->firstChild()
->textContent(false)
.StripWhiteSpace()
.Ascii()
.data());
- failure_context.append("\"");
+ failure_context.Append("\"");
} else {
- failure_context += "<missing ID>";
+ failure_context.Append("<missing ID>");
}
// Run each test three times at different positions in the element.
@@ -264,7 +264,7 @@ void TouchActionTest::RunTestOnTree(
// the first border box (which we can easily visualize in a browser for
// debugging).
Persistent<DOMRectList> rects = element->getClientRects();
- ASSERT_GE(rects->length(), 0u) << failure_context;
+ ASSERT_GE(rects->length(), 0u) << failure_context.ToString();
Persistent<DOMRect> r = rects->item(0);
FloatRect client_float_rect =
FloatRect(r->left(), r->top(), r->width(), r->height());
@@ -272,7 +272,7 @@ void TouchActionTest::RunTestOnTree(
for (int loc_idx = 0; loc_idx < 3; loc_idx++) {
IntPoint frame_point;
std::stringstream context_stream;
- context_stream << failure_context << " (";
+ context_stream << failure_context.ToString() << " (";
switch (loc_idx) {
case 0:
frame_point = client_rect.Center();
@@ -296,7 +296,7 @@ void TouchActionTest::RunTestOnTree(
frame_point);
context_stream << "=" << window_point.X() << "," << window_point.Y()
<< ").";
- std::string failure_context_pos = context_stream.str();
+ String failure_context_pos = String::FromUTF8(context_stream.str());
LocalFrame* main_frame =
To<LocalFrame>(WebFrame::ToCoreFrame(*web_view->MainFrame()));
@@ -327,9 +327,7 @@ void TouchActionTest::RunTestOnTree(
.data()
<< "\"" << std::endl
<< "Document render tree:" << std::endl
- << ExternalRepresentation(root->GetDocument().GetFrame())
- .Utf8()
- .data();
+ << ExternalRepresentation(root->GetDocument().GetFrame()).Utf8();
// Now send the touch event and check any touch action result.
SendTouchEvent(web_view, WebInputEvent::kPointerDown, window_point);
@@ -358,8 +356,7 @@ void TouchActionTest::RunTestOnTree(
client.LastTouchAction())
<< failure_context_pos;
} else {
- FAIL() << "Unrecognized expected-action \""
- << expected_action.Ascii().data() << "\" "
+ FAIL() << "Unrecognized expected-action " << expected_action << " "
<< failure_context_pos;
}
}
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 a6fde8d5edb..0aab096eb00 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
@@ -20,7 +20,7 @@
#include "third_party/blink/renderer/core/layout/hit_test_canvas_result.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/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
@@ -277,8 +277,7 @@ 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*>(),
- std::vector<const WebInputEvent*>());
+ WebCoalescedInputEvent result(event, {}, {});
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
@@ -529,7 +528,7 @@ void TouchEventManager::UpdateTouchAttributeMapsForPointerDown(
if (touch_sequence_document_ &&
(!touch_node || &touch_node->GetDocument() != touch_sequence_document_)) {
if (touch_sequence_document_->GetFrame()) {
- HitTestLocation location(LayoutPoint(
+ HitTestLocation location(PhysicalOffset::FromFloatPointRound(
touch_sequence_document_->GetFrame()->View()->ConvertFromRootFrame(
event.PositionInWidget())));
result = event_handling_util::HitTestResultInFrame(
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 dd7294c1b85..e168bcb67a7 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
@@ -14,7 +14,7 @@
#include "third_party/blink/renderer/core/events/pointer_event_factory.h"
#include "third_party/blink/renderer/core/input/event_handling_util.h"
#include "third_party/blink/renderer/platform/graphics/touch_action.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
#include "third_party/blink/renderer/platform/wtf/vector.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 a90396259fd..314474a6f73 100644
--- a/chromium/third_party/blink/renderer/core/inspector/browser_protocol.pdl
+++ b/chromium/third_party/blink/renderer/core/inspector/browser_protocol.pdl
@@ -481,6 +481,8 @@ experimental domain BackgroundService
backgroundSync
pushMessaging
notifications
+ paymentHandler
+ periodicBackgroundSync
# Enables event updates for the service.
command startObserving
@@ -585,6 +587,8 @@ domain Browser
sensors
videoCapture
idleDetection
+ wakeLockScreen
+ wakeLockSystem
# Grant specific permissions to the given origin and reject all others.
experimental command grantPermissions
@@ -2362,8 +2366,9 @@ experimental domain DOMSnapshot
LayoutTreeSnapshot layout
# The post-layout inline text nodes.
TextBoxSnapshot textBoxes
- # Scroll offsets.
+ # Horizontal scroll offset.
optional number scrollOffsetX
+ # Vertical scroll offset.
optional number scrollOffsetY
# Table containing nodes.
@@ -2402,12 +2407,12 @@ experimental domain DOMSnapshot
# The url of the script (if any) that generates this node.
optional RareStringData originURL
- # Details of an element in the DOM tree with a LayoutObject.
+ # Table of details of an element in the DOM tree with a LayoutObject.
type LayoutTreeSnapshot extends object
properties
- # The index of the related DOM node in the `domNodes` array returned by `getSnapshot`.
+ # Index of the corresponding node in the `NodeTreeSnapshot` array returned by `captureSnapshot`.
array of integer nodeIndex
- # Index into the `computedStyles` array returned by `captureSnapshot`.
+ # Array of indexes specifying computed style strings, filtered according to the `computedStyles` parameter passed to `captureSnapshot`.
array of ArrayOfStrings styles
# The absolute position bounding box.
array of Rectangle bounds
@@ -2415,12 +2420,18 @@ experimental domain DOMSnapshot
array of StringIndex text
# Stacking context information.
RareBooleanData stackingContexts
-
- # Details of post layout rendered text positions. The exact layout should not be regarded as
+ # The offset rect of nodes. Only available when includeDOMRects is set to true
+ optional array of Rectangle offsetRects
+ # The scroll rect of nodes. Only available when includeDOMRects is set to true
+ optional array of Rectangle scrollRects
+ # The client rect of nodes. Only available when includeDOMRects is set to true
+ optional array of Rectangle clientRects
+
+ # Table of details of the post layout rendered text positions. The exact layout should not be regarded as
# stable and may change between versions.
type TextBoxSnapshot extends object
properties
- # Intex of th elayout tree node that owns this box collection.
+ # Index of the layout tree node that owns this box collection.
array of integer layoutIndex
# The absolute position bounding box.
array of Rectangle bounds
@@ -2467,6 +2478,8 @@ experimental domain DOMSnapshot
parameters
# Whitelist of computed styles to return.
array of string computedStyles
+ # Whether to include DOM rectangles (offsetRects, clientRects, scrollRects) into the snapshot
+ optional boolean includeDOMRects
returns
# The nodes in the DOM tree. The DOMNode at index 0 corresponds to the root document.
array of DocumentSnapshot documents
@@ -4052,6 +4065,94 @@ domain Network
# Cookie SameSite type.
optional CookieSameSite sameSite
+ # Types of reasons why a cookie may not be stored from a response.
+ experimental type SetCookieBlockedReason extends string
+ enum
+ # The cookie had the "Secure" attribute but was not received over a secure connection.
+ SecureOnly
+ # The cookie had the "SameSite=Strict" attribute but came from a cross-origin response.
+ # This includes navigation requests intitiated by other origins.
+ SameSiteStrict
+ # The cookie had the "SameSite=Lax" attribute but came from a cross-origin response.
+ SameSiteLax
+ # The cookie had the "SameSite=Extended" attribute but came from a cross-origin response.
+ SameSiteExtended
+ # The cookie didn't specify a "SameSite" attribute and was defaulted to "SameSite=Lax" and
+ # broke the same rules specified in the SameSiteLax value.
+ SameSiteUnspecifiedTreatedAsLax
+ # The cookie had the "SameSite=None" attribute but did not specify the "Secure" attribute,
+ # which is required in order to use "SameSite=None".
+ SameSiteNoneInsecure
+ # The cookie was not stored due to user preferences.
+ UserPreferences
+ # The syntax of the Set-Cookie header of the response was invalid.
+ SyntaxError
+ # The scheme of the connection is not allowed to store cookies.
+ SchemeNotSupported
+ # The cookie was not sent over a secure connection and would have overwritten a cookie with
+ # the Secure attribute.
+ OverwriteSecure
+ # The cookie's domain attribute was invalid with regards to the current host url.
+ InvalidDomain
+ # The cookie used the "__Secure-" or "__Host-" prefix in its name and broke the additional
+ # rules applied to cookies with these prefixes as defined in
+ # https://tools.ietf.org/html/draft-west-cookie-prefixes-05
+ InvalidPrefix
+ # An unknown error was encountered when trying to store this cookie.
+ UnknownError
+
+ # Types of reasons why a cookie may not be sent with a request.
+ experimental type CookieBlockedReason extends string
+ enum
+ # The cookie had the "Secure" attribute and the connection was not secure.
+ SecureOnly
+ # The cookie's path was not within the request url's path.
+ NotOnPath
+ # The cookie's domain is not configured to match the request url's domain, even though they
+ # share a common TLD+1 (TLD+1 of foo.bar.example.com is example.com).
+ DomainMismatch
+ # The cookie had the "SameSite=Strict" attribute and the request was made on on a different
+ # site. This includes navigation requests initiated by other sites.
+ SameSiteStrict
+ # The cookie had the "SameSite=Lax" attribute and the request was made on a different site.
+ # This does not include navigation requests initiated by other sites.
+ SameSiteLax
+ # The cookie had the "SameSite=Extended" attribute and the request was made on a different
+ # site. The different site is outside of the cookie's trusted first-party set.
+ SameSiteExtended
+ # The cookie didn't specify a SameSite attribute when it was stored and was defaulted to
+ # "SameSite=Lax" and broke the same rules specified in the SameSiteLax value. The cookie had
+ # to have been set with "SameSite=None" to enable third-party usage.
+ SameSiteUnspecifiedTreatedAsLax
+ # The cookie had the "SameSite=None" attribute and the connection was not secure. Cookies
+ # without SameSite restrictions must be sent over a secure connection.
+ SameSiteNoneInsecure
+ # The cookie was not sent due to user preferences.
+ UserPreferences
+ # An unknown error was encountered when trying to send this cookie.
+ UnknownError
+
+ # A cookie which was not stored from a response with the corresponding reason.
+ experimental type BlockedSetCookieWithReason extends object
+ properties
+ # The reason this cookie was blocked.
+ SetCookieBlockedReason blockedReason
+ # The string representing this individual cookie as it would appear in the header.
+ # This is not the entire "cookie" or "set-cookie" header which could have multiple cookies.
+ string cookieLine
+ # The cookie object which represents the cookie which was not stored. It is optional because
+ # sometimes complete cookie information is not available, such as in the case of parsing
+ # errors.
+ optional Cookie cookie
+
+ # A cookie with was not sent with a request with the corresponding reason.
+ experimental type BlockedCookieWithReason extends object
+ properties
+ # The reason the cookie was blocked.
+ CookieBlockedReason blockedReason
+ # The cookie object representing the cookie which was not sent.
+ Cookie cookie
+
# Cookie parameter object
type CookieParam extends object
properties
@@ -4159,6 +4260,8 @@ domain Network
Headers responseHeaders
# Signed exchange response signature.
array of SignedExchangeSignature signatures
+ # Signed exchange header integrity hash in the form of "sha256-<base64-hash-value>".
+ string headerIntegrity
# Field type for a signed exchange related error.
experimental type SignedExchangeErrorField extends string
@@ -4220,7 +4323,8 @@ domain Network
# modifications, or blocks it, or completes it with the provided response bytes. If a network
# fetch occurs as a result which encounters a redirect an additional Network.requestIntercepted
# event will be sent with the same InterceptionId.
- experimental command continueInterceptedRequest
+ # Deprecated, use Fetch.continueRequest, Fetch.fulfillRequest and Fetch.failRequest instead.
+ experimental deprecated command continueInterceptedRequest
parameters
InterceptionId interceptionId
# If set this causes the request to fail with the given reason. Passing `Aborted` for requests
@@ -4438,7 +4542,8 @@ domain Network
Headers headers
# Sets the requests to intercept that match the provided patterns and optionally resource types.
- experimental command setRequestInterception
+ # Deprecated, please use Fetch.enable instead.
+ experimental deprecated command setRequestInterception
parameters
# Requests matching any of these patterns will be forwarded and wait for the corresponding
# continueInterceptedRequest call.
@@ -4512,7 +4617,8 @@ domain Network
# Details of an intercepted HTTP request, which must be either allowed, blocked, modified or
# mocked.
- experimental event requestIntercepted
+ # Deprecated, use Fetch.requestPaused instead.
+ experimental deprecated event requestIntercepted
parameters
# Each request the page makes will have a unique id, however if any redirects are encountered
# while processing that fetch, they will be reported with the same id as the original fetch.
@@ -4682,6 +4788,37 @@ domain Network
# WebSocket request data.
WebSocketRequest request
+ # Fired when additional information about a requestWillBeSent event is available from the
+ # network stack. Not every requestWillBeSent event will have an additional
+ # requestWillBeSentExtraInfo fired for it, and there is no guarantee whether requestWillBeSent
+ # or requestWillBeSentExtraInfo will be fired first for the same request.
+ experimental event requestWillBeSentExtraInfo
+ parameters
+ # Request identifier. Used to match this information to an existing requestWillBeSent event.
+ RequestId requestId
+ # A list of cookies which will not be sent with this request along with corresponding reasons
+ # for blocking.
+ array of BlockedCookieWithReason blockedCookies
+ # Raw request headers as they will be sent over the wire.
+ Headers headers
+
+ # Fired when additional information about a responseReceived event is available from the network
+ # stack. Not every responseReceived event will have an additional responseReceivedExtraInfo for
+ # it, and responseReceivedExtraInfo may be fired before or after responseReceived.
+ experimental event responseReceivedExtraInfo
+ parameters
+ # Request identifier. Used to match this information to another responseReceived event.
+ RequestId requestId
+ # A list of cookies which were not stored from the response along with the corresponding
+ # reasons for blocking. The cookies here may not be valid due to syntax errors, which
+ # are represented by the invalid cookie line string instead of a proper cookie.
+ array of BlockedSetCookieWithReason blockedCookies
+ # Raw response headers as they were received over the wire.
+ Headers headers
+ # Raw response header text as it was received over the wire. The raw text may not always be
+ # available, such as in the case of HTTP/2 or QUIC.
+ optional string headersText
+
# This domain provides various functionality related to drawing atop the inspected page.
experimental domain Overlay
depends on DOM
@@ -4737,6 +4874,8 @@ experimental domain Overlay
DOM.NodeId nodeId
# Whether to include distance info.
optional boolean includeDistance
+ # Whether to include style info.
+ optional boolean includeStyle
returns
# Highlight data for the node.
object highlight
@@ -4834,6 +4973,12 @@ experimental domain Overlay
# True for showing paint rectangles
boolean result
+ # Requests that backend shows layout shift regions
+ command setShowLayoutShiftRegions
+ parameters
+ # True for showing layout shift regions
+ boolean result
+
# Requests that backend shows scroll bottleneck rects
command setShowScrollBottleneckRects
parameters
@@ -4877,6 +5022,7 @@ experimental domain Overlay
domain Page
depends on Debugger
depends on DOM
+ depends on IO
depends on Network
depends on Runtime
@@ -4894,13 +5040,15 @@ domain Page
Network.LoaderId loaderId
# Frame's name as specified in the tag.
optional string name
- # Frame document's URL.
+ # Frame document's URL without fragment.
string url
+ # Frame document's URL fragment including the '#'.
+ experimental optional string urlFragment
# Frame document's security origin.
string securityOrigin
# Frame document's mimeType as determined by the browser.
string mimeType
- # If the frame failed to load, this contains the URL that could not be loaded.
+ # If the frame failed to load, this contains the URL that could not be loaded. Note that unlike url above, this URL may contain a fragment.
experimental optional string unreachableUrl
# Information about the Resource on the page.
@@ -5334,9 +5482,15 @@ domain Page
# Whether or not to prefer page size as defined by css. Defaults to false,
# in which case the content will be scaled to fit the paper size.
optional boolean preferCSSPageSize
+ # return as stream
+ experimental optional enum transferMode
+ ReturnAsBase64
+ ReturnAsStream
returns
- # Base64-encoded pdf data.
+ # Base64-encoded pdf data. Empty if |returnAsStream| is specified.
binary data
+ # A handle of the stream that holds resulting PDF data.
+ experimental optional IO.StreamHandle stream
# Reloads given page optionally ignoring the cache.
command reload
@@ -5565,10 +5719,35 @@ domain Page
# Pauses page execution. Can be resumed using generic Runtime.runIfWaitingForDebugger.
experimental command waitForDebugger
+ # Intercept file chooser requests and transfer control to protocol clients.
+ # When file chooser interception is enabled, native file chooser dialog is not shown.
+ # Instead, a protocol event `Page.fileChooserOpened` is emitted.
+ # File chooser can be handled with `page.handleFileChooser` command.
+ experimental command setInterceptFileChooserDialog
+ parameters
+ boolean enabled
+
+ # Accepts or cancels an intercepted file chooser dialog.
+ experimental command handleFileChooser
+ parameters
+ enum action
+ accept
+ cancel
+ fallback
+ # Array of absolute file paths to set, only respected with `accept` action.
+ optional array of string files
+
event domContentEventFired
parameters
Network.MonotonicTime timestamp
+ # Emitted only when `page.interceptFileChooser` is enabled.
+ event fileChooserOpened
+ parameters
+ enum mode
+ selectSingle
+ selectMultiple
+
# Fired when frame has been attached to its parent.
event frameAttached
parameters
@@ -5895,7 +6074,7 @@ domain Security
# Security state.
SecurityState securityState
# True if the page was loaded over cryptographic transport such as HTTPS.
- boolean schemeIsCryptographic
+ deprecated boolean schemeIsCryptographic
# List of explanations for the security state. If the overall security state is `insecure` or
# `warning`, at least one corresponding explanation should be included.
array of SecurityStateExplanation explanations
@@ -6134,6 +6313,66 @@ experimental domain SystemInfo
# String description of the GPU driver version.
string driverVersion
+ # Describes the width and height dimensions of an entity.
+ type Size extends object
+ properties
+ # Width in pixels.
+ integer width
+ # Height in pixels.
+ integer height
+
+ # Describes a supported video decoding profile with its associated minimum and
+ # maximum resolutions.
+ type VideoDecodeAcceleratorCapability extends object
+ properties
+ # Video codec profile that is supported, e.g. VP9 Profile 2.
+ string profile
+ # Maximum video dimensions in pixels supported for this |profile|.
+ Size maxResolution
+ # Minimum video dimensions in pixels supported for this |profile|.
+ Size minResolution
+
+ # Describes a supported video encoding profile with its associated maximum
+ # resolution and maximum framerate.
+ type VideoEncodeAcceleratorCapability extends object
+ properties
+ # Video codec profile that is supported, e.g H264 Main.
+ string profile
+ # Maximum video dimensions in pixels supported for this |profile|.
+ Size maxResolution
+ # Maximum encoding framerate in frames per second supported for this
+ # |profile|, as fraction's numerator and denominator, e.g. 24/1 fps,
+ # 24000/1001 fps, etc.
+ integer maxFramerateNumerator
+ integer maxFramerateDenominator
+
+ # YUV subsampling type of the pixels of a given image.
+ type SubsamplingFormat extends string
+ enum
+ yuv420
+ yuv422
+ yuv444
+
+ # Image format of a given image.
+ type ImageType extends string
+ enum
+ jpeg
+ webp
+ unknown
+
+ # Describes a supported image decoding profile with its associated minimum and
+ # maximum resolutions and subsampling.
+ type ImageDecodeAcceleratorCapability extends object
+ properties
+ # Image coded, e.g. Jpeg.
+ ImageType imageType
+ # Maximum supported dimensions of the image in pixels.
+ Size maxDimensions
+ # Minimum supported dimensions of the image in pixels.
+ Size minDimensions
+ # Optional array of supported subsampling formats, e.g. 4:2:0, if known.
+ array of SubsamplingFormat subsamplings
+
# Provides information about the GPU(s) on the system.
type GPUInfo extends object
properties
@@ -6145,6 +6384,12 @@ experimental domain SystemInfo
optional object featureStatus
# An optional array of GPU driver bug workarounds.
array of string driverBugWorkarounds
+ # Supported accelerated video decoding capabilities.
+ array of VideoDecodeAcceleratorCapability videoDecoding
+ # Supported accelerated video encoding capabilities.
+ array of VideoEncodeAcceleratorCapability videoEncoding
+ # Supported accelerated image decoding capabilities.
+ array of ImageDecodeAcceleratorCapability imageDecoding
# Represents process info.
type ProcessInfo extends object
@@ -6529,6 +6774,9 @@ experimental domain Tracing
# delivered via dataCollected events.
event tracingComplete
parameters
+ # Indicates whether some trace data is known to have been lost, e.g. because the trace ring
+ # buffer wrapped around.
+ boolean dataLossOccurred
# A handle of the stream that holds resulting trace data.
optional IO.StreamHandle stream
# Trace data format of returned stream.
@@ -6755,16 +7003,19 @@ experimental domain WebAudio
running
closed
- # Fields in AudioContext that change in real-time. These are not updated
- # on OfflineAudioContext.
+ # Fields in AudioContext that change in real-time.
type ContextRealtimeData extends object
properties
# The current context time in second in BaseAudioContext.
- optional number currentTime
+ number currentTime
# The time spent on rendering graph divided by render qunatum duration,
# and multiplied by 100. 100 means the audio renderer reached the full
# capacity and glitch may occur.
- optional number renderCapacity
+ number renderCapacity
+ # A running mean of callback interval.
+ number callbackIntervalMean
+ # A running variance of callback interval.
+ number callbackIntervalVariance
# Protocol object for BaseAudioContext
type BaseAudioContext extends object
@@ -6811,9 +7062,89 @@ experimental domain WebAudio
# This domain allows configuring virtual authenticators to test the WebAuthn
# API.
experimental domain WebAuthn
+ type AuthenticatorId extends string
+
+ type AuthenticatorProtocol extends string
+ enum
+ # Universal 2nd Factor.
+ u2f
+ # Client To Authenticator Protocol 2.
+ ctap2
+
+ type AuthenticatorTransport extends string
+ enum
+ # Cross-Platform authenticator attachments:
+ usb
+ nfc
+ ble
+ cable
+ # Platform authenticator attachment:
+ internal
+
+ type VirtualAuthenticatorOptions extends object
+ properties
+ AuthenticatorProtocol protocol
+ AuthenticatorTransport transport
+ boolean hasResidentKey
+ boolean hasUserVerification
+ # If set to true, tests of user presence will succeed immediately.
+ # Otherwise, they will not be resolved. Defaults to true.
+ optional boolean automaticPresenceSimulation
+
+ type Credential extends object
+ properties
+ binary credentialId
+ # SHA-256 hash of the Relying Party ID the credential is scoped to. Must
+ # be 32 bytes long.
+ # See https://w3c.github.io/webauthn/#rpidhash
+ binary rpIdHash
+ # The private key in PKCS#8 format.
+ binary privateKey
+ # Signature counter. This is incremented by one for each successful
+ # assertion.
+ # See https://w3c.github.io/webauthn/#signature-counter
+ integer signCount
+
# Enable the WebAuthn domain and start intercepting credential storage and
# retrieval with a virtual authenticator.
command enable
# Disable the WebAuthn domain.
command disable
+
+ # Creates and adds a virtual authenticator.
+ command addVirtualAuthenticator
+ parameters
+ VirtualAuthenticatorOptions options
+ returns
+ AuthenticatorId authenticatorId
+
+ # Removes the given authenticator.
+ command removeVirtualAuthenticator
+ parameters
+ AuthenticatorId authenticatorId
+
+ # Adds the credential to the specified authenticator.
+ command addCredential
+ parameters
+ AuthenticatorId authenticatorId
+ Credential credential
+
+ # Returns all the credentials stored in the given virtual authenticator.
+ command getCredentials
+ parameters
+ AuthenticatorId authenticatorId
+ returns
+ array of Credential credentials
+
+ # Clears all the credentials from the specified device.
+ command clearCredentials
+ parameters
+ AuthenticatorId authenticatorId
+
+ # Sets whether User Verification succeeds or fails for an authenticator.
+ # The default is true.
+ command setUserVerified
+ parameters
+ AuthenticatorId authenticatorId
+ boolean isUserVerified
diff --git a/chromium/third_party/blink/renderer/core/inspector/console_message.cc b/chromium/third_party/blink/renderer/core/inspector/console_message.cc
index 029a7d18754..19d5f8baadd 100644
--- a/chromium/third_party/blink/renderer/core/inspector/console_message.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/console_message.cc
@@ -93,7 +93,7 @@ ConsoleMessage::ConsoleMessage(mojom::ConsoleMessageSource source,
level_(level),
message_(message),
location_(std::move(location)),
- timestamp_(WTF::CurrentTimeMS()),
+ timestamp_(base::Time::Now().ToDoubleT() * 1000.0),
frame_(nullptr) {}
ConsoleMessage::~ConsoleMessage() = default;
diff --git a/chromium/third_party/blink/renderer/core/inspector/console_message.h b/chromium/third_party/blink/renderer/core/inspector/console_message.h
index 2d9eaf67817..ecaf42b8ebf 100644
--- a/chromium/third_party/blink/renderer/core/inspector/console_message.h
+++ b/chromium/third_party/blink/renderer/core/inspector/console_message.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_INSPECTOR_CONSOLE_MESSAGE_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_INSPECTOR_CONSOLE_MESSAGE_H_
-#include "third_party/blink/public/mojom/devtools/console_message.mojom-shared.h"
+#include "third_party/blink/public/mojom/devtools/console_message.mojom-blink.h"
#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/platform/heap/handle.h"
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 2eefbc9a904..9f97baf7dc1 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
@@ -219,7 +219,7 @@ void DevToolsEmulator::SetPrimaryHoverType(HoverType hover_type) {
web_view_->GetPage()->GetSettings().SetPrimaryHoverType(hover_type);
}
-void DevToolsEmulator::EnableDeviceEmulation(
+TransformationMatrix DevToolsEmulator::EnableDeviceEmulation(
const WebDeviceEmulationParams& params) {
if (device_metrics_enabled_ &&
emulation_params_.view_size == params.view_size &&
@@ -228,7 +228,7 @@ void DevToolsEmulator::EnableDeviceEmulation(
emulation_params_.scale == params.scale &&
emulation_params_.viewport_offset == params.viewport_offset &&
emulation_params_.viewport_scale == params.viewport_scale) {
- return;
+ return ComputeRootLayerTransform();
}
if (emulation_params_.device_scale_factor != params.device_scale_factor ||
!device_metrics_enabled_)
@@ -248,18 +248,19 @@ void DevToolsEmulator::EnableDeviceEmulation(
DisableMobileEmulation();
web_view_->SetCompositorDeviceScaleFactorOverride(params.device_scale_factor);
- if (params.viewport_offset.x >= 0)
- ForceViewport(params.viewport_offset, params.viewport_scale);
- else
- ResetViewport();
- // TODO(dgozman): MainFrameImpl() is null when it's remote. Figure out how
- // we end up with enabling emulation in this case.
+ // TODO(wjmaclean): Tell all local frames in the WebView's frame tree, not
+ // just a local main frame.
if (web_view_->MainFrameImpl()) {
if (Document* document =
web_view_->MainFrameImpl()->GetFrame()->GetDocument())
document->MediaQueryAffectingValueChanged();
}
+
+ if (params.viewport_offset.x >= 0)
+ return ForceViewport(params.viewport_offset, params.viewport_scale);
+ else
+ return ResetViewport();
}
void DevToolsEmulator::DisableDeviceEmulation() {
@@ -273,13 +274,17 @@ void DevToolsEmulator::DisableDeviceEmulation() {
DisableMobileEmulation();
web_view_->SetCompositorDeviceScaleFactorOverride(0.f);
web_view_->SetPageScaleFactor(1.f);
- ResetViewport();
- // mainFrameImpl() could be null during cleanup or remote <-> local swap.
+
+ // TODO(wjmaclean): Tell all local frames in the WebView's frame tree, not
+ // just a local main frame.
if (web_view_->MainFrameImpl()) {
if (Document* document =
web_view_->MainFrameImpl()->GetFrame()->GetDocument())
document->MediaQueryAffectingValueChanged();
}
+
+ TransformationMatrix matrix = ResetViewport();
+ DCHECK(matrix.IsIdentity());
}
void DevToolsEmulator::EnableMobileEmulation() {
@@ -319,8 +324,9 @@ void DevToolsEmulator::EnableMobileEmulation() {
original_default_maximum_page_scale_factor_ =
web_view_->DefaultMaximumPageScaleFactor();
web_view_->SetDefaultPageScaleLimits(0.25f, 5);
- // TODO(dgozman): MainFrameImpl() is null when it's remote. Figure out how
- // we end up with enabling emulation in this case.
+
+ // TODO(wjmaclean): Update all local frames in the WebView's frame tree, not
+ // just a local main frame.
if (web_view_->MainFrameImpl())
web_view_->MainFrameImpl()->GetFrameView()->UpdateLayout();
}
@@ -362,13 +368,14 @@ void DevToolsEmulator::DisableMobileEmulation() {
web_view_->MainFrameImpl()->GetFrameView()->UpdateLayout();
}
-void DevToolsEmulator::ForceViewport(const WebFloatPoint& position,
- float scale) {
- GraphicsLayer* container_layer =
- web_view_->GetPage()->GetVisualViewport().ContainerLayer();
+TransformationMatrix DevToolsEmulator::ForceViewport(
+ const WebFloatPoint& position,
+ float scale) {
if (!viewport_override_) {
viewport_override_ = ViewportOverride();
+ GraphicsLayer* container_layer =
+ web_view_->GetPage()->GetVisualViewport().ContainerLayer();
// Disable clipping on the visual viewport layer, to ensure the whole area
// is painted.
if (container_layer) {
@@ -383,31 +390,29 @@ void DevToolsEmulator::ForceViewport(const WebFloatPoint& position,
// Move the correct (scaled) content area to show in the top left of the
// CompositorFrame via the root transform.
- UpdateRootLayerTransform();
+ return ComputeRootLayerTransform();
}
-void DevToolsEmulator::ResetViewport() {
- if (!viewport_override_) {
- UpdateRootLayerTransform();
- return;
- }
-
- bool original_masking = viewport_override_->original_visual_viewport_masking;
- viewport_override_ = base::nullopt;
+TransformationMatrix DevToolsEmulator::ResetViewport() {
+ if (viewport_override_) {
+ GraphicsLayer* container_layer =
+ web_view_->GetPage()->GetVisualViewport().ContainerLayer();
+ if (container_layer) {
+ container_layer->SetMasksToBounds(
+ viewport_override_->original_visual_viewport_masking);
+ }
- GraphicsLayer* container_layer =
- web_view_->GetPage()->GetVisualViewport().ContainerLayer();
- if (container_layer)
- container_layer->SetMasksToBounds(original_masking);
+ viewport_override_ = base::nullopt;
+ }
- UpdateRootLayerTransform();
+ return ComputeRootLayerTransform();
}
-void DevToolsEmulator::MainFrameScrollOrScaleChanged() {
+TransformationMatrix DevToolsEmulator::MainFrameScrollOrScaleChanged() {
// Viewport override has to take current page scale and scroll offset into
// account. Update the transform if override is active.
- if (viewport_override_)
- UpdateRootLayerTransform();
+ DCHECK(viewport_override_);
+ return ComputeRootLayerTransform();
}
void DevToolsEmulator::ApplyViewportOverride(TransformationMatrix* transform) {
@@ -435,15 +440,14 @@ void DevToolsEmulator::ApplyViewportOverride(TransformationMatrix* transform) {
transform->Scale(1. / web_view_->PageScaleFactor());
}
-void DevToolsEmulator::UpdateRootLayerTransform() {
+TransformationMatrix DevToolsEmulator::ComputeRootLayerTransform() {
TransformationMatrix transform;
-
// Apply device emulation transform first, so that it is affected by the
// viewport override.
ApplyViewportOverride(&transform);
if (device_metrics_enabled_)
transform.Scale(emulation_params_.scale);
- web_view_->SetDeviceEmulationTransform(transform);
+ return transform;
}
void DevToolsEmulator::OverrideVisibleRect(const IntSize& viewport_size,
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 7ed71117913..fc743bdffd5 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
@@ -13,12 +13,12 @@
#include "third_party/blink/public/web/web_device_emulation_params.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
+#include "third_party/blink/renderer/platform/transforms/transformation_matrix.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
namespace blink {
class IntRect;
-class TransformationMatrix;
class WebViewImpl;
class CORE_EXPORT DevToolsEmulator final
@@ -45,21 +45,24 @@ class CORE_EXPORT DevToolsEmulator final
void SetPrimaryHoverType(HoverType);
void SetMainFrameResizesAreOrientationChanges(bool);
- // Emulation.
- void EnableDeviceEmulation(const WebDeviceEmulationParams&);
+ // Enables and/or sets the parameters for emulation. Returns the emulation
+ // transform to be used as a result.
+ TransformationMatrix EnableDeviceEmulation(const WebDeviceEmulationParams&);
+ // Disables emulation.
void DisableDeviceEmulation();
- // Position is given in CSS pixels, scale relative to a page scale of 1.0.
- void ForceViewport(const WebFloatPoint& position, float scale);
- void ResetViewport();
+
bool ResizeIsDeviceSizeChange();
void SetTouchEventEmulationEnabled(bool, int max_touch_points);
void SetScriptExecutionDisabled(bool);
void SetScrollbarsHidden(bool);
void SetDocumentCookieDisabled(bool);
+ bool HasViewportOverride() const { return !!viewport_override_; }
+
// Notify the DevToolsEmulator about a scroll or scale change of the main
- // frame. Updates the transform for a viewport override.
- void MainFrameScrollOrScaleChanged();
+ // frame. Returns an updated emulation transform for a viewport override, and
+ // should only be called when HasViewportOverride() is true.
+ TransformationMatrix MainFrameScrollOrScaleChanged();
// Rewrites the |visible_rect| to the area of the devtools custom viewport if
// it is enabled. Otherwise, leaves |visible_rect| unchanged. Takes as input
@@ -73,16 +76,30 @@ class CORE_EXPORT DevToolsEmulator final
// device metics.
float InputEventsScaleForEmulation();
+ TransformationMatrix ForceViewportForTesting(const WebFloatPoint& position,
+ float scale) {
+ return ForceViewport(position, scale);
+ }
+ TransformationMatrix ResetViewportForTesting() { return ResetViewport(); }
+
private:
void EnableMobileEmulation();
void DisableMobileEmulation();
+ // Enables viewport override and returns the emulation transform to be used.
+ // The |position| is in CSS pixels, and |scale| is relative to a page scale of
+ // 1.0.
+ TransformationMatrix ForceViewport(const WebFloatPoint& position,
+ float scale);
+ // Disables viewport override and returns the emulation transform to be used.
+ TransformationMatrix ResetViewport();
+
// Returns the original device scale factor when overridden by DevTools, or
// deviceScaleFactor() otherwise.
float CompositorDeviceScaleFactor() const;
void ApplyViewportOverride(TransformationMatrix*);
- void UpdateRootLayerTransform();
+ TransformationMatrix ComputeRootLayerTransform();
WebViewImpl* web_view_;
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 3652940fff8..91ef4360266 100644
--- a/chromium/third_party/blink/renderer/core/inspector/devtools_agent.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/devtools_agent.cc
@@ -106,11 +106,13 @@ void DevToolsAgent::AttachDevToolsSession(
mojom::blink::DevToolsSessionHostAssociatedPtrInfo host,
mojom::blink::DevToolsSessionAssociatedRequest session_request,
mojom::blink::DevToolsSessionRequest io_session_request,
- mojom::blink::DevToolsSessionStatePtr reattach_session_state) {
+ mojom::blink::DevToolsSessionStatePtr reattach_session_state,
+ bool client_expects_binary_responses) {
client_->DebuggerTaskStarted();
DevToolsSession* session = MakeGarbageCollected<DevToolsSession>(
this, std::move(host), std::move(session_request),
- std::move(io_session_request), std::move(reattach_session_state));
+ std::move(io_session_request), std::move(reattach_session_state),
+ client_expects_binary_responses);
sessions_.insert(session);
client_->DebuggerTaskFinished();
}
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 fde85d798cc..0d447be72b7 100644
--- a/chromium/third_party/blink/renderer/core/inspector/devtools_agent.h
+++ b/chromium/third_party/blink/renderer/core/inspector/devtools_agent.h
@@ -74,7 +74,8 @@ class CORE_EXPORT DevToolsAgent
mojom::blink::DevToolsSessionHostAssociatedPtrInfo,
mojom::blink::DevToolsSessionAssociatedRequest main_session,
mojom::blink::DevToolsSessionRequest io_session,
- mojom::blink::DevToolsSessionStatePtr reattach_session_state) override;
+ mojom::blink::DevToolsSessionStatePtr reattach_session_state,
+ bool client_expects_binary_responses) override;
void InspectElement(const WebPoint& point) override;
void ReportChildWorkers(bool report,
bool wait_for_debugger,
diff --git a/chromium/third_party/blink/renderer/core/inspector/devtools_session.cc b/chromium/third_party/blink/renderer/core/inspector/devtools_session.cc
index e839efcfbd0..789b09417ce 100644
--- a/chromium/third_party/blink/renderer/core/inspector/devtools_session.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/devtools_session.cc
@@ -7,7 +7,6 @@
#include "base/containers/span.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"
@@ -16,18 +15,23 @@
#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/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/web_test_support.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h"
#include "third_party/inspector_protocol/encoding/encoding.h"
namespace blink {
namespace {
+using ::inspector_protocol_encoding::span;
using ::inspector_protocol_encoding::SpanFrom;
using ::inspector_protocol_encoding::cbor::IsCBORMessage;
+using ::inspector_protocol_encoding::json::ConvertCBORToJSON;
+using IPEStatus = ::inspector_protocol_encoding::Status;
+
const char kV8StateKey[] = "v8";
bool ShouldInterruptForMethod(const String& method) {
// Keep in sync with DevToolsSession::ShouldSendOnIO.
@@ -42,10 +46,10 @@ bool ShouldInterruptForMethod(const String& method) {
method == "Emulation.setScriptExecutionDisabled";
}
-std::vector<uint8_t> UnwrapMessage(
- const mojom::blink::DevToolsMessagePtr& message) {
- return std::vector<uint8_t>(message->data.data(),
- message->data.data() + message->data.size());
+Vector<uint8_t> UnwrapMessage(const mojom::blink::DevToolsMessagePtr& message) {
+ Vector<uint8_t> unwrap_message;
+ unwrap_message.Append(message->data.data(), message->data.size());
+ return unwrap_message;
}
mojom::blink::DevToolsMessagePtr WrapMessage(
@@ -53,7 +57,7 @@ mojom::blink::DevToolsMessagePtr WrapMessage(
auto result = mojom::blink::DevToolsMessage::New();
if (message.json.IsEmpty()) {
- result->data = std::move(message.binary);
+ result->data = message.binary.ReleaseVector();
} else {
WTF::StringUTF8Adaptor adaptor(message.json);
result->data =
@@ -68,11 +72,36 @@ protocol::ProtocolMessage ToProtocolMessage(
const auto& string = buffer->string();
DCHECK(string.is8Bit());
// TODO: add StringBuffer::takeBytes().
- message.binary = std::vector<uint8_t>(string.characters8(),
- string.characters8() + string.length());
+ message.binary = WebVector<uint8_t>(string.characters8(), string.length());
return message;
}
+// Platform allows us to inject the string<->double conversion
+// routines from Blink into the inspector_protocol JSON parser / serializer.
+class JsonPlatform : public ::inspector_protocol_encoding::json::Platform {
+ public:
+ bool StrToD(const char* str, double* result) const override {
+ bool ok;
+ *result = String(str).ToDouble(&ok);
+ return ok;
+ }
+
+ // Prints |value| in a format suitable for JSON.
+ std::unique_ptr<char[]> DToStr(double value) const override {
+ String str = String::NumberToStringECMAScript(value);
+ DCHECK(str.Is8Bit());
+ std::unique_ptr<char[]> result(new char[str.length() + 1]);
+ memcpy(result.get(), str.Characters8(), str.length());
+ result.get()[str.length()] = '\0';
+ return result;
+ }
+};
+
+IPEStatus ConvertCBORToJSON(span<uint8_t> cbor, std::vector<uint8_t>* json) {
+ DCHECK(IsCBORMessage(cbor));
+ JsonPlatform platform;
+ return ConvertCBORToJSON(platform, cbor, json);
+}
} // namespace
// Created and stored in unique_ptr on UI.
@@ -129,14 +158,16 @@ DevToolsSession::DevToolsSession(
mojom::blink::DevToolsSessionHostAssociatedPtrInfo host_ptr_info,
mojom::blink::DevToolsSessionAssociatedRequest main_request,
mojom::blink::DevToolsSessionRequest io_request,
- mojom::blink::DevToolsSessionStatePtr reattach_session_state)
+ mojom::blink::DevToolsSessionStatePtr reattach_session_state,
+ bool client_expects_binary_responses)
: agent_(agent),
binding_(this, std::move(main_request)),
inspector_backend_dispatcher_(new protocol::UberDispatcher(this)),
session_state_(std::move(reattach_session_state)),
+ client_expects_binary_responses_(client_expects_binary_responses),
v8_session_state_(kV8StateKey),
v8_session_state_cbor_(&v8_session_state_,
- /*default_value=*/std::vector<uint8_t>()) {
+ /*default_value=*/{}) {
io_session_ =
new IOSession(agent_->io_task_runner_, agent_->inspector_task_runner_,
WrapCrossThreadWeakPersistent(this), std::move(io_request));
@@ -161,7 +192,7 @@ DevToolsSession::~DevToolsSession() {
void DevToolsSession::ConnectToV8(v8_inspector::V8Inspector* inspector,
int context_group_id) {
- const std::vector<uint8_t>& cbor = v8_session_state_cbor_.Get();
+ const auto& cbor = v8_session_state_cbor_.Get();
v8_session_ =
inspector->connect(context_group_id, this,
v8_inspector::StringView(cbor.data(), cbor.size()));
@@ -208,8 +239,8 @@ void DevToolsSession::DispatchProtocolCommand(
void DevToolsSession::DispatchProtocolCommandImpl(int call_id,
const String& method,
- std::vector<uint8_t> data) {
- DCHECK(IsCBORMessage(SpanFrom(data)));
+ Vector<uint8_t> data) {
+ DCHECK(IsCBORMessage(span<uint8_t>(data.data(), data.size())));
// IOSession does not provide ordering guarantees relative to
// Session, so a command may come to IOSession after Session is detached,
@@ -292,7 +323,16 @@ void DevToolsSession::SendProtocolResponse(
// protocol response in any of them.
if (WebTestSupport::IsRunningWebTest())
agent_->FlushProtocolNotifications();
- host_ptr_->DispatchProtocolResponse(WrapMessage(message), call_id,
+
+ mojom::blink::DevToolsMessagePtr serialized = WrapMessage(message);
+ if (!client_expects_binary_responses_) {
+ std::vector<uint8_t> json;
+ IPEStatus status = ConvertCBORToJSON(
+ span<uint8_t>(serialized->data.data(), serialized->data.size()), &json);
+ CHECK(status.ok()) << status.ToASCIIString();
+ serialized->data = mojo_base::BigBuffer(json);
+ }
+ host_ptr_->DispatchProtocolResponse(std::move(serialized), call_id,
session_state_.TakeUpdates());
}
@@ -360,7 +400,16 @@ void DevToolsSession::flushProtocolNotifications() {
if (v8_session_)
v8_session_state_cbor_.Set(v8_session_->state());
for (wtf_size_t i = 0; i < notification_queue_.size(); ++i) {
- auto serialized = notification_queue_[i]->Serialize();
+ mojom::blink::DevToolsMessagePtr serialized =
+ notification_queue_[i]->Serialize();
+ if (!client_expects_binary_responses_) {
+ std::vector<uint8_t> json;
+ IPEStatus status = ConvertCBORToJSON(
+ span<uint8_t>(serialized->data.data(), serialized->data.size()),
+ &json);
+ CHECK(status.ok()) << status.ToASCIIString();
+ serialized->data = mojo_base::BigBuffer(json);
+ }
host_ptr_->DispatchProtocolNotification(std::move(serialized),
session_state_.TakeUpdates());
}
diff --git a/chromium/third_party/blink/renderer/core/inspector/devtools_session.h b/chromium/third_party/blink/renderer/core/inspector/devtools_session.h
index e554d87127e..3b7d42866c1 100644
--- a/chromium/third_party/blink/renderer/core/inspector/devtools_session.h
+++ b/chromium/third_party/blink/renderer/core/inspector/devtools_session.h
@@ -35,7 +35,8 @@ class CORE_EXPORT DevToolsSession
mojom::blink::DevToolsSessionHostAssociatedPtrInfo host_ptr_info,
mojom::blink::DevToolsSessionAssociatedRequest main_request,
mojom::blink::DevToolsSessionRequest io_request,
- mojom::blink::DevToolsSessionStatePtr reattach_session_state);
+ mojom::blink::DevToolsSessionStatePtr reattach_session_state,
+ bool client_expects_binary_responses);
~DevToolsSession() override;
void ConnectToV8(v8_inspector::V8Inspector*, int context_group_id);
@@ -61,7 +62,7 @@ class CORE_EXPORT DevToolsSession
mojom::blink::DevToolsMessagePtr message) override;
void DispatchProtocolCommandImpl(int call_id,
const String& method,
- std::vector<uint8_t> message);
+ Vector<uint8_t> message);
// protocol::FrontendChannel implementation.
void sendProtocolResponse(
@@ -95,6 +96,7 @@ class CORE_EXPORT DevToolsSession
HeapVector<Member<InspectorAgent>> agents_;
class Notification;
Vector<std::unique_ptr<Notification>> notification_queue_;
+ const bool client_expects_binary_responses_;
InspectorAgentState v8_session_state_;
InspectorAgentState::Bytes v8_session_state_cbor_;
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 2dc2dbd0a63..8da4b579745 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
@@ -53,7 +53,6 @@
#include "third_party/blink/renderer/platform/wtf/deque.h"
#include "third_party/blink/renderer/platform/wtf/hash_traits.h"
#include "third_party/blink/renderer/platform/wtf/text/base64.h"
-#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
namespace blink {
@@ -117,7 +116,7 @@ Node* DOMPatchSupport::PatchNode(Node* node,
// root children, as it provides an equivalent parsing context.
if (target_node->IsShadowRoot())
target_node = GetDocument().body();
- Element* target_element = ToElement(target_node);
+ auto* target_element = To<Element>(target_node);
// FIXME: This code should use one of createFragment* in Serialization.h
if (GetDocument().IsHTMLDocument())
@@ -185,12 +184,12 @@ bool DOMPatchSupport::InnerPatchNode(Digest* old_digest,
return false;
}
- if (!old_node->IsElementNode())
+ auto* old_element = DynamicTo<Element>(old_node);
+ if (!old_element)
return true;
// Patch attributes
- Element* old_element = ToElement(old_node);
- Element* new_element = ToElement(new_node);
+ auto* new_element = To<Element>(new_node);
if (old_digest->attrs_sha1_ != new_digest->attrs_sha1_) {
// FIXME: Create a function in Element for removing all properties. Take in
// account whether did/willModifyAttribute are important.
@@ -444,9 +443,8 @@ DOMPatchSupport::Digest* DOMPatchSupport::CreateDigest(
digestor.UpdateUtf8(node->nodeName());
digestor.UpdateUtf8(node->nodeValue());
- if (node->IsElementNode()) {
- Element& element = ToElement(*node);
- Node* child = element.firstChild();
+ if (auto* element = DynamicTo<Element>(node)) {
+ Node* child = element->firstChild();
while (child) {
Digest* child_info = CreateDigest(child, unused_nodes_map);
digestor.UpdateUtf8(child_info->sha1_);
@@ -454,7 +452,7 @@ DOMPatchSupport::Digest* DOMPatchSupport::CreateDigest(
digest->children_.push_back(child_info);
}
- AttributeCollection attributes = element.AttributesWithoutUpdate();
+ AttributeCollection attributes = element->AttributesWithoutUpdate();
if (!attributes.IsEmpty()) {
Digestor attrs_digestor(kHashAlgorithmSha1);
for (auto& attribute : attributes) {
@@ -465,15 +463,14 @@ DOMPatchSupport::Digest* DOMPatchSupport::CreateDigest(
attrs_digestor.Finish(digest_result);
DCHECK(!attrs_digestor.has_failed());
digest->attrs_sha1_ =
- Base64Encode(reinterpret_cast<const char*>(digest_result.data()), 10);
+ Base64Encode(base::make_span(digest_result).first<10>());
digestor.UpdateUtf8(digest->attrs_sha1_);
}
}
digestor.Finish(digest_result);
DCHECK(!digestor.has_failed());
- digest->sha1_ =
- Base64Encode(reinterpret_cast<const char*>(digest_result.data()), 10);
+ digest->sha1_ = Base64Encode(base::make_span(digest_result).first<10>());
if (unused_nodes_map)
unused_nodes_map->insert(digest->sha1_, digest);
diff --git a/chromium/third_party/blink/renderer/core/inspector/identifiers_factory.h b/chromium/third_party/blink/renderer/core/inspector/identifiers_factory.h
index 53b70f736e9..5325b855f75 100644
--- a/chromium/third_party/blink/renderer/core/inspector/identifiers_factory.h
+++ b/chromium/third_party/blink/renderer/core/inspector/identifiers_factory.h
@@ -28,7 +28,7 @@
#include "base/unguessable_token.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspect_tools.cc b/chromium/third_party/blink/renderer/core/inspector/inspect_tools.cc
index 17889b2efdb..9adeb945771 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspect_tools.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/inspect_tools.cc
@@ -33,13 +33,14 @@ namespace {
InspectorHighlightContrastInfo FetchContrast(Node* node) {
InspectorHighlightContrastInfo result;
- if (!node->IsElementNode())
+ auto* element = DynamicTo<Element>(node);
+ if (!element)
return result;
Vector<Color> bgcolors;
String font_size;
String font_weight;
- InspectorCSSAgent::GetBackgroundColors(ToElement(node), &bgcolors, &font_size,
+ InspectorCSSAgent::GetBackgroundColors(element, &bgcolors, &font_size,
&font_weight);
if (bgcolors.size() == 1) {
result.font_size = font_size;
@@ -99,10 +100,9 @@ Node* HoveredNodeForEvent(LocalFrame* frame,
SearchingForNodeTool::SearchingForNodeTool(InspectorDOMAgent* dom_agent,
bool ua_shadow,
- const String& config)
+ const std::vector<uint8_t>& config)
: dom_agent_(dom_agent), ua_shadow_(ua_shadow) {
- std::unique_ptr<protocol::Value> value =
- protocol::StringUtil::parseJSON(config);
+ auto value = protocol::Value::parseBinary(config.data(), config.size());
if (!value)
return;
protocol::ErrorSupport errors;
@@ -343,8 +343,8 @@ void NodeHighlightTool::Trace(blink::Visitor* visitor) {
// NearbyDistanceTool ----------------------------------------------------------
-CString NearbyDistanceTool::GetDataResourceName() {
- return "inspect_tool_distances.html";
+String NearbyDistanceTool::GetDataResourceName() {
+ return String("inspect_tool_distances.html");
}
bool NearbyDistanceTool::HandleMouseDown(const WebMouseEvent& event,
@@ -413,8 +413,8 @@ void ShowViewSizeTool::Draw(float scale) {
overlay_->EvaluateInOverlay("drawViewSize", "");
}
-CString ShowViewSizeTool::GetDataResourceName() {
- return "inspect_tool_viewport_size.html";
+String ShowViewSizeTool::GetDataResourceName() {
+ return String("inspect_tool_viewport_size.html");
}
bool ShowViewSizeTool::ForwardEventsToOverlay() {
@@ -430,8 +430,8 @@ void ScreenshotTool::DoInit() {
client.SetCursorOverridden(true);
}
-CString ScreenshotTool::GetDataResourceName() {
- return "inspect_tool_screenshot.html";
+String ScreenshotTool::GetDataResourceName() {
+ return String("inspect_tool_screenshot.html");
}
void ScreenshotTool::Dispatch(const String& message) {
@@ -500,8 +500,8 @@ void ScreenshotTool::Dispatch(const String& message) {
// PausedInDebuggerTool --------------------------------------------------------
-CString PausedInDebuggerTool::GetDataResourceName() {
- return "inspect_tool_paused.html";
+String PausedInDebuggerTool::GetDataResourceName() {
+ return String("inspect_tool_paused.html");
}
void PausedInDebuggerTool::Draw(float scale) {
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspect_tools.h b/chromium/third_party/blink/renderer/core/inspector/inspect_tools.h
index 2bc42c57baf..ede4decd289 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspect_tools.h
+++ b/chromium/third_party/blink/renderer/core/inspector/inspect_tools.h
@@ -5,6 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_INSPECTOR_INSPECT_TOOLS_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_INSPECTOR_INSPECT_TOOLS_H_
+#include <vector>
#include <v8-inspector.h>
#include "base/macros.h"
#include "third_party/blink/renderer/core/inspector/inspector_overlay_agent.h"
@@ -20,7 +21,7 @@ class SearchingForNodeTool : public InspectTool {
public:
SearchingForNodeTool(InspectorDOMAgent* dom_agent,
bool ua_shadow,
- const String& highlight_config);
+ const std::vector<uint8_t>& highlight_config);
private:
bool HandleInputEvent(LocalFrameView* frame_view,
@@ -95,7 +96,7 @@ class NearbyDistanceTool : public InspectTool {
NearbyDistanceTool() = default;
private:
- CString GetDataResourceName() override;
+ String GetDataResourceName() override;
bool HandleMouseDown(const WebMouseEvent& event,
bool* swallow_next_mouse_up) override;
bool HandleMouseMove(const WebMouseEvent& event) override;
@@ -115,7 +116,7 @@ class ShowViewSizeTool : public InspectTool {
private:
bool ForwardEventsToOverlay() override;
- CString GetDataResourceName() override;
+ String GetDataResourceName() override;
void Draw(float scale) override;
DISALLOW_COPY_AND_ASSIGN(ShowViewSizeTool);
};
@@ -127,7 +128,7 @@ class ScreenshotTool : public InspectTool {
ScreenshotTool() = default;
private:
- CString GetDataResourceName() override;
+ String GetDataResourceName() override;
void DoInit() override;
void Dispatch(const String& message) override;
@@ -143,7 +144,7 @@ class PausedInDebuggerTool : public InspectTool {
: v8_session_(v8_session), message_(message) {}
private:
- CString GetDataResourceName() override;
+ String GetDataResourceName() override;
void Draw(float scale) override;
void Dispatch(const String& message) override;
v8_inspector::V8InspectorSession* v8_session_;
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 8eaf6a38ba2..888a4494f9c 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
@@ -12,7 +12,6 @@
#include "third_party/blink/renderer/core/animation/computed_effect_timing.h"
#include "third_party/blink/renderer/core/animation/css/css_animations.h"
#include "third_party/blink/renderer/core/animation/effect_model.h"
-#include "third_party/blink/renderer/core/animation/element_animation.h"
#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"
@@ -127,8 +126,8 @@ BuildObjectForAnimationKeyframes(const KeyframeEffect* effect) {
const KeyframeEffectModelBase* model = effect->Model();
Vector<double> computed_offsets =
KeyframeEffectModelBase::GetComputedOffsets(model->GetFrames());
- std::unique_ptr<protocol::Array<protocol::Animation::KeyframeStyle>>
- keyframes = protocol::Array<protocol::Animation::KeyframeStyle>::create();
+ auto keyframes =
+ std::make_unique<protocol::Array<protocol::Animation::KeyframeStyle>>();
for (wtf_size_t i = 0; i < model->GetFrames().size(); i++) {
const Keyframe* keyframe = model->GetFrames().at(i);
@@ -136,7 +135,7 @@ BuildObjectForAnimationKeyframes(const KeyframeEffect* effect) {
if (!keyframe->IsStringKeyframe())
continue;
const StringKeyframe* string_keyframe = ToStringKeyframe(keyframe);
- keyframes->addItem(
+ keyframes->emplace_back(
BuildObjectForStringKeyframe(string_keyframe, computed_offsets.at(i)));
}
return protocol::Animation::KeyframesRule::create()
@@ -222,12 +221,16 @@ Response InspectorAnimationAgent::getCurrentTime(const String& id,
if (id_to_animation_clone_.at(id))
animation = id_to_animation_clone_.at(id);
- if (animation->Paused()) {
+ if (animation->Paused() || !animation->timeline()->IsActive()) {
*current_time = animation->currentTime();
} else {
// Use startTime where possible since currentTime is limited.
- *current_time = animation->TimelineInternal()->currentTime() -
- animation->startTime().value_or(NullValue());
+ base::Optional<double> timeline_time = animation->timeline()->CurrentTime();
+ // TODO(crbug.com/916117): Handle NaN values for scroll linked animations.
+ *current_time = timeline_time
+ ? timeline_time.value() -
+ animation->startTime().value_or(NullValue())
+ : NullValue();
}
return Response::OK();
}
@@ -235,8 +238,7 @@ Response InspectorAnimationAgent::getCurrentTime(const String& id,
Response InspectorAnimationAgent::setPaused(
std::unique_ptr<protocol::Array<String>> animation_ids,
bool paused) {
- for (size_t i = 0; i < animation_ids->length(); ++i) {
- String animation_id = animation_ids->get(i);
+ for (const String& animation_id : *animation_ids) {
blink::Animation* animation = nullptr;
Response response = AssertAnimation(animation_id, animation);
if (!response.isSuccess())
@@ -246,8 +248,17 @@ Response InspectorAnimationAgent::setPaused(
return Response::Error("Failed to clone detached animation");
if (paused && !clone->Paused()) {
// Ensure we restore a current time if the animation is limited.
- double current_time = clone->TimelineInternal()->currentTime() -
- clone->startTime().value_or(NullValue());
+ double current_time = 0;
+ if (!clone->timeline()->IsActive()) {
+ current_time = clone->currentTime();
+ } else {
+ base::Optional<double> timeline_time = clone->timeline()->CurrentTime();
+ // TODO(crbug.com/916117): Handle NaN values.
+ current_time = timeline_time
+ ? timeline_time.value() -
+ clone->startTime().value_or(NullValue())
+ : NullValue();
+ }
clone->pause();
clone->setCurrentTime(current_time, false);
} else if (!paused && clone->Paused()) {
@@ -306,8 +317,7 @@ blink::Animation* InspectorAnimationAgent::AnimationClone(
Response InspectorAnimationAgent::seekAnimations(
std::unique_ptr<protocol::Array<String>> animation_ids,
double current_time) {
- for (size_t i = 0; i < animation_ids->length(); ++i) {
- String animation_id = animation_ids->get(i);
+ for (const String& animation_id : *animation_ids) {
blink::Animation* animation = nullptr;
Response response = AssertAnimation(animation_id, animation);
if (!response.isSuccess())
@@ -324,8 +334,7 @@ Response InspectorAnimationAgent::seekAnimations(
Response InspectorAnimationAgent::releaseAnimations(
std::unique_ptr<protocol::Array<String>> animation_ids) {
- for (size_t i = 0; i < animation_ids->length(); ++i) {
- String animation_id = animation_ids->get(i);
+ for (const String& animation_id : *animation_ids) {
blink::Animation* animation = id_to_animation_.at(animation_id);
if (animation)
animation->SetEffectSuppressed(false);
@@ -443,7 +452,7 @@ String InspectorAnimationAgent::CreateCSSId(blink::Animation& animation) {
DigestValue digest_result;
digestor.Finish(digest_result);
DCHECK(!digestor.has_failed());
- return Base64Encode(reinterpret_cast<const char*>(digest_result.data()), 10);
+ return Base64Encode(base::make_span(digest_result).first<10>());
}
void InspectorAnimationAgent::DidCreateAnimation(unsigned sequence_number) {
@@ -497,14 +506,16 @@ DocumentTimeline& InspectorAnimationAgent::ReferenceTimeline() {
double InspectorAnimationAgent::NormalizedStartTime(
blink::Animation& animation) {
double time_ms = animation.startTime().value_or(NullValue());
- if (ReferenceTimeline().PlaybackRate() == 0) {
- time_ms += ReferenceTimeline().currentTime() -
- animation.TimelineInternal()->currentTime();
- } else {
- time_ms += (animation.TimelineInternal()->ZeroTime() -
- ReferenceTimeline().ZeroTime())
- .InMillisecondsF() *
- ReferenceTimeline().PlaybackRate();
+ if (animation.timeline()->IsDocumentTimeline()) {
+ if (ReferenceTimeline().PlaybackRate() == 0) {
+ time_ms += ReferenceTimeline().currentTime() -
+ ToDocumentTimeline(animation.timeline())->currentTime();
+ } else {
+ time_ms += (ToDocumentTimeline(animation.timeline())->ZeroTime() -
+ ReferenceTimeline().ZeroTime())
+ .InMillisecondsF() *
+ ReferenceTimeline().PlaybackRate();
+ }
}
// Round to the closest microsecond.
return std::round(time_ms * 1000) / 1000;
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_application_cache_agent.cc b/chromium/third_party/blink/renderer/core/inspector/inspector_application_cache_agent.cc
index 32cd93cd66f..7f17efcabee 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_application_cache_agent.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_application_cache_agent.cc
@@ -92,8 +92,8 @@ Response InspectorApplicationCacheAgent::getFramesWithManifests(
std::unique_ptr<
protocol::Array<protocol::ApplicationCache::FrameWithManifest>>*
result) {
- *result =
- protocol::Array<protocol::ApplicationCache::FrameWithManifest>::create();
+ *result = std::make_unique<
+ protocol::Array<protocol::ApplicationCache::FrameWithManifest>>();
for (LocalFrame* frame : *inspected_frames_) {
DocumentLoader* document_loader = frame->Loader().GetDocumentLoader();
@@ -110,7 +110,7 @@ Response InspectorApplicationCacheAgent::getFramesWithManifests(
.setManifestURL(manifest_url)
.setStatus(static_cast<int>(host->GetStatus()))
.build();
- (*result)->addItem(std::move(value));
+ (*result)->emplace_back(std::move(value));
}
}
return Response::OK();
@@ -156,7 +156,7 @@ Response InspectorApplicationCacheAgent::getApplicationCacheForFrame(
ApplicationCacheHost* host = document_loader->GetApplicationCacheHost();
ApplicationCacheHost::CacheInfo info = host->ApplicationCacheInfo();
- ApplicationCacheHost::ResourceInfoList resources;
+ Vector<mojom::blink::AppCacheResourceInfo> resources;
host->FillResourceList(&resources);
*application_cache = BuildObjectForApplicationCache(resources, info);
@@ -165,7 +165,8 @@ Response InspectorApplicationCacheAgent::getApplicationCacheForFrame(
std::unique_ptr<protocol::ApplicationCache::ApplicationCache>
InspectorApplicationCacheAgent::BuildObjectForApplicationCache(
- const ApplicationCacheHost::ResourceInfoList& application_cache_resources,
+ const Vector<mojom::blink::AppCacheResourceInfo>&
+ application_cache_resources,
const ApplicationCacheHost::CacheInfo& application_cache_info) {
return protocol::ApplicationCache::ApplicationCache::create()
.setManifestURL(application_cache_info.manifest_.GetString())
@@ -180,45 +181,40 @@ InspectorApplicationCacheAgent::BuildObjectForApplicationCache(
std::unique_ptr<
protocol::Array<protocol::ApplicationCache::ApplicationCacheResource>>
InspectorApplicationCacheAgent::BuildArrayForApplicationCacheResources(
- const ApplicationCacheHost::ResourceInfoList& application_cache_resources) {
- std::unique_ptr<
- protocol::Array<protocol::ApplicationCache::ApplicationCacheResource>>
- resources = protocol::Array<
- protocol::ApplicationCache::ApplicationCacheResource>::create();
-
- ApplicationCacheHost::ResourceInfoList::const_iterator end =
- application_cache_resources.end();
- ApplicationCacheHost::ResourceInfoList::const_iterator it =
- application_cache_resources.begin();
- for (int i = 0; it != end; ++it, i++)
- resources->addItem(BuildObjectForApplicationCacheResource(*it));
+ const Vector<mojom::blink::AppCacheResourceInfo>&
+ application_cache_resources) {
+ auto resources = std::make_unique<
+ protocol::Array<protocol::ApplicationCache::ApplicationCacheResource>>();
+
+ for (const auto& resource : application_cache_resources)
+ resources->emplace_back(BuildObjectForApplicationCacheResource(resource));
return resources;
}
std::unique_ptr<protocol::ApplicationCache::ApplicationCacheResource>
InspectorApplicationCacheAgent::BuildObjectForApplicationCacheResource(
- const ApplicationCacheHost::ResourceInfo& resource_info) {
+ const mojom::blink::AppCacheResourceInfo& resource_info) {
StringBuilder builder;
- if (resource_info.is_master_)
+ if (resource_info.is_master)
builder.Append("Master ");
- if (resource_info.is_manifest_)
+ if (resource_info.is_manifest)
builder.Append("Manifest ");
- if (resource_info.is_fallback_)
+ if (resource_info.is_fallback)
builder.Append("Fallback ");
- if (resource_info.is_foreign_)
+ if (resource_info.is_foreign)
builder.Append("Foreign ");
- if (resource_info.is_explicit_)
+ if (resource_info.is_explicit)
builder.Append("Explicit ");
std::unique_ptr<protocol::ApplicationCache::ApplicationCacheResource> value =
protocol::ApplicationCache::ApplicationCacheResource::create()
- .setUrl(resource_info.resource_.GetString())
- .setSize(static_cast<int>(resource_info.response_size_))
+ .setUrl(resource_info.url.GetString())
+ .setSize(static_cast<int>(resource_info.response_size))
.setType(builder.ToString())
.build();
return value;
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 2cde4bc3d10..2857fda2778 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
@@ -76,15 +76,16 @@ class CORE_EXPORT InspectorApplicationCacheAgent final
void InnerEnable();
std::unique_ptr<protocol::ApplicationCache::ApplicationCache>
- BuildObjectForApplicationCache(const ApplicationCacheHost::ResourceInfoList&,
- const ApplicationCacheHost::CacheInfo&);
+ BuildObjectForApplicationCache(
+ const Vector<mojom::blink::AppCacheResourceInfo>&,
+ const ApplicationCacheHost::CacheInfo&);
std::unique_ptr<
protocol::Array<protocol::ApplicationCache::ApplicationCacheResource>>
BuildArrayForApplicationCacheResources(
- const ApplicationCacheHost::ResourceInfoList&);
+ const Vector<mojom::blink::AppCacheResourceInfo>&);
std::unique_ptr<protocol::ApplicationCache::ApplicationCacheResource>
BuildObjectForApplicationCacheResource(
- const ApplicationCacheHost::ResourceInfo&);
+ const mojom::blink::AppCacheResourceInfo&);
protocol::Response AssertFrameWithDocumentLoader(String frame_id,
DocumentLoader*&);
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 ac058bc18c7..9f1c97720cd 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
@@ -94,8 +94,7 @@
#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_view.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
#include "third_party/blink/renderer/platform/text/text_run.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
-#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/string_concatenate.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
@@ -151,7 +150,7 @@ HeapVector<Member<CSSStyleRule>> FilterDuplicateRules(CSSRuleList* rule_list) {
}
// Get the elements which overlap the given rectangle.
-HeapVector<Member<Element>> ElementsFromRect(LayoutRect rect,
+HeapVector<Member<Element>> ElementsFromRect(const PhysicalRect& rect,
Document& document) {
HitTestRequest request(HitTestRequest::kReadOnly | HitTestRequest::kActive |
HitTestRequest::kListBased |
@@ -169,9 +168,10 @@ HeapVector<Member<Element>> ElementsFromRect(LayoutRect rect,
continue;
if (node->IsPseudoElement() || node->IsTextNode())
node = node->ParentOrShadowHostNode();
- if (!node || node == previous_node || !node->IsElementNode())
+ auto* element = DynamicTo<Element>(node);
+ if (!node || node == previous_node || !element)
continue;
- elements.push_back(ToElement(node));
+ elements.push_back(element);
previous_node = node;
}
return elements;
@@ -242,7 +242,7 @@ void AddColorsFromImageStyle(const ComputedStyle& style,
// walking up all the elements returned by a hit test (but not going beyond
// |topElement|) covering the area of the rect, and blending their background
// colors.
-bool GetColorsFromRect(LayoutRect rect,
+bool GetColorsFromRect(PhysicalRect rect,
Document& document,
Element* top_element,
Vector<Color>& colors) {
@@ -347,12 +347,11 @@ static unsigned ComputePseudoClassMask(
DEFINE_STATIC_LOCAL(String, focusVisible, ("focus-visible"));
DEFINE_STATIC_LOCAL(String, focusWithin, ("focus-within"));
DEFINE_STATIC_LOCAL(String, visited, ("visited"));
- if (!pseudo_class_array || !pseudo_class_array->length())
+ if (!pseudo_class_array || pseudo_class_array->empty())
return kPseudoNone;
unsigned result = kPseudoNone;
- for (size_t i = 0; i < pseudo_class_array->length(); ++i) {
- String pseudo_class = pseudo_class_array->get(i);
+ for (const String& pseudo_class : *pseudo_class_array) {
if (pseudo_class == active)
result |= kPseudoActive;
else if (pseudo_class == hover)
@@ -407,7 +406,7 @@ class InspectorCSSAgent::SetStyleSheetTextAction final
String MergeId() override {
return String::Format("SetStyleSheetText %s",
- style_sheet_->Id().Utf8().data());
+ style_sheet_->Id().Utf8().c_str());
}
void Merge(Action* action) override {
@@ -524,7 +523,7 @@ class InspectorCSSAgent::ModifyRuleAction final
String MergeId() override {
return String::Format("ModifyRuleAction:%d %s:%d", type_,
- style_sheet_->Id().Utf8().data(), old_range_.start);
+ style_sheet_->Id().Utf8().c_str(), old_range_.start);
}
bool IsNoop() override { return old_text_ == new_text_; }
@@ -578,7 +577,7 @@ class InspectorCSSAgent::SetElementStyleAction final
String MergeId() override {
return String::Format("SetElementStyleAction:%s",
- style_sheet_->Id().Utf8().data());
+ style_sheet_->Id().Utf8().c_str());
}
std::unique_ptr<protocol::CSS::CSSStyle> TakeSerializedStyle() override {
@@ -895,7 +894,7 @@ void InspectorCSSAgent::ForcePseudoState(Element* element,
Response InspectorCSSAgent::getMediaQueries(
std::unique_ptr<protocol::Array<protocol::CSS::CSSMedia>>* medias) {
- *medias = protocol::Array<protocol::CSS::CSSMedia>::create();
+ *medias = std::make_unique<protocol::Array<protocol::CSS::CSSMedia>>();
for (auto& style : id_to_inspector_style_sheet_) {
InspectorStyleSheet* style_sheet = style.value;
CollectMediaQueriesFromStyleSheet(style_sheet->PageStyleSheet(),
@@ -969,7 +968,7 @@ Response InspectorCSSAgent::getMatchedStylesForNode(
}
*pseudo_id_matches =
- protocol::Array<protocol::CSS::PseudoElementMatches>::create();
+ std::make_unique<protocol::Array<protocol::CSS::PseudoElementMatches>>();
for (PseudoId pseudo_id = kFirstPublicPseudoId;
pseudo_id < kAfterLastInternalPseudoId;
pseudo_id = static_cast<PseudoId>(pseudo_id + 1)) {
@@ -978,7 +977,7 @@ Response InspectorCSSAgent::getMatchedStylesForNode(
protocol::DOM::PseudoType pseudo_type;
if (matched_rules && matched_rules->length() &&
dom_agent_->GetPseudoElementType(pseudo_id, &pseudo_type)) {
- pseudo_id_matches->fromJust()->addItem(
+ pseudo_id_matches->fromJust()->emplace_back(
protocol::CSS::PseudoElementMatches::create()
.setPseudoType(pseudo_type)
.setMatches(BuildArrayForMatchedRuleList(matched_rules, element,
@@ -989,7 +988,7 @@ Response InspectorCSSAgent::getMatchedStylesForNode(
// Inherited styles.
*inherited_entries =
- protocol::Array<protocol::CSS::InheritedStyleEntry>::create();
+ std::make_unique<protocol::Array<protocol::CSS::InheritedStyleEntry>>();
Element* parent_element = element->ParentOrShadowHostElement();
while (parent_element) {
StyleResolver& parent_style_resolver =
@@ -1010,7 +1009,7 @@ Response InspectorCSSAgent::getMatchedStylesForNode(
style_sheet->BuildObjectForStyle(style_sheet->InlineStyle()));
}
- inherited_entries->fromJust()->addItem(std::move(entry));
+ inherited_entries->fromJust()->emplace_back(std::move(entry));
parent_element = parent_element->ParentOrShadowHostElement();
}
@@ -1038,9 +1037,8 @@ static CSSKeyframesRule* FindKeyframesRule(CSSRuleCollection* css_rules,
std::unique_ptr<protocol::Array<protocol::CSS::CSSKeyframesRule>>
InspectorCSSAgent::AnimationsForNode(Element* element) {
- std::unique_ptr<protocol::Array<protocol::CSS::CSSKeyframesRule>>
- css_keyframes_rules =
- protocol::Array<protocol::CSS::CSSKeyframesRule>::create();
+ auto css_keyframes_rules =
+ std::make_unique<protocol::Array<protocol::CSS::CSSKeyframesRule>>();
Document* owner_document = element->ownerDocument();
StyleResolver& style_resolver = owner_document->EnsureStyleResolver();
@@ -1069,12 +1067,12 @@ InspectorCSSAgent::AnimationsForNode(Element* element) {
if (!css_keyframes_rule)
continue;
- std::unique_ptr<protocol::Array<protocol::CSS::CSSKeyframeRule>> keyframes =
- protocol::Array<protocol::CSS::CSSKeyframeRule>::create();
+ auto keyframes =
+ std::make_unique<protocol::Array<protocol::CSS::CSSKeyframeRule>>();
for (unsigned j = 0; j < css_keyframes_rule->length(); ++j) {
InspectorStyleSheet* inspector_style_sheet =
BindStyleSheet(css_keyframes_rule->parentStyleSheet());
- keyframes->addItem(inspector_style_sheet->BuildObjectForKeyframeRule(
+ keyframes->emplace_back(inspector_style_sheet->BuildObjectForKeyframeRule(
css_keyframes_rule->Item(j)));
}
@@ -1089,10 +1087,10 @@ InspectorCSSAgent::AnimationsForNode(Element* element) {
if (source_data)
name->setRange(inspector_style_sheet->BuildSourceRangeObject(
source_data->rule_header_range));
- css_keyframes_rules->addItem(protocol::CSS::CSSKeyframesRule::create()
- .setAnimationName(std::move(name))
- .setKeyframes(std::move(keyframes))
- .build());
+ css_keyframes_rules->emplace_back(protocol::CSS::CSSKeyframesRule::create()
+ .setAnimationName(std::move(name))
+ .setKeyframes(std::move(keyframes))
+ .build());
}
return css_keyframes_rules;
}
@@ -1133,14 +1131,15 @@ Response InspectorCSSAgent::getComputedStyleForNode(
auto* computed_style_info =
MakeGarbageCollected<CSSComputedStyleDeclaration>(node, true);
- *style = protocol::Array<protocol::CSS::CSSComputedStyleProperty>::create();
+ *style = std::make_unique<
+ protocol::Array<protocol::CSS::CSSComputedStyleProperty>>();
for (CSSPropertyID property_id : CSSPropertyIDList()) {
const CSSProperty& property_class =
CSSProperty::Get(resolveCSSPropertyID(property_id));
- if (!property_class.IsEnabled() || property_class.IsShorthand() ||
+ if (!property_class.IsWebExposed() || property_class.IsShorthand() ||
!property_class.IsProperty())
continue;
- (*style)->addItem(
+ (*style)->emplace_back(
protocol::CSS::CSSComputedStyleProperty::create()
.setName(property_class.GetPropertyNameString())
.setValue(computed_style_info->GetPropertyValue(property_id))
@@ -1148,10 +1147,10 @@ Response InspectorCSSAgent::getComputedStyleForNode(
}
for (const auto& it : computed_style_info->GetVariables()) {
- (*style)->addItem(protocol::CSS::CSSComputedStyleProperty::create()
- .setName(it.key)
- .setValue(it.value->CssText())
- .build());
+ (*style)->emplace_back(protocol::CSS::CSSComputedStyleProperty::create()
+ .setName(it.key)
+ .setValue(it.value->CssText())
+ .build());
}
return Response::OK();
}
@@ -1238,17 +1237,18 @@ Response InspectorCSSAgent::getPlatformFontsForNode(
const unsigned descendants_depth = 2;
CollectPlatformFontsForLayoutObject(root, &font_stats, descendants_depth);
}
- *platform_fonts = protocol::Array<protocol::CSS::PlatformFontUsage>::create();
+ *platform_fonts =
+ std::make_unique<protocol::Array<protocol::CSS::PlatformFontUsage>>();
for (auto& font : font_stats) {
std::pair<int, String>& font_description = font.key;
bool is_custom_font = font_description.first == 1;
String font_name = font_description.second;
(*platform_fonts)
- ->addItem(protocol::CSS::PlatformFontUsage::create()
- .setFamilyName(font_name)
- .setIsCustomFont(is_custom_font)
- .setGlyphCount(font.value)
- .build());
+ ->emplace_back(protocol::CSS::PlatformFontUsage::create()
+ .setFamilyName(font_name)
+ .setIsCustomFont(is_custom_font)
+ .setGlyphCount(font.value)
+ .build());
}
return Response::OK();
}
@@ -1406,12 +1406,12 @@ Response InspectorCSSAgent::setKeyframeKey(
Response InspectorCSSAgent::MultipleStyleTextsActions(
std::unique_ptr<protocol::Array<protocol::CSS::StyleDeclarationEdit>> edits,
HeapVector<Member<StyleSheetAction>>* actions) {
- size_t n = edits->length();
+ size_t n = edits->size();
if (n == 0)
return Response::Error("Edits should not be empty");
for (size_t i = 0; i < n; ++i) {
- protocol::CSS::StyleDeclarationEdit* edit = edits->get(i);
+ protocol::CSS::StyleDeclarationEdit* edit = (*edits)[i].get();
InspectorStyleSheetBase* inspector_style_sheet = nullptr;
Response response =
AssertStyleSheetForId(edit->getStyleSheetId(), inspector_style_sheet);
@@ -1457,8 +1457,8 @@ Response InspectorCSSAgent::setStyleTexts(
DummyExceptionStateForTesting exception_state;
int n = actions.size();
- std::unique_ptr<protocol::Array<protocol::CSS::CSSStyle>> serialized_styles =
- protocol::Array<protocol::CSS::CSSStyle>::create();
+ auto serialized_styles =
+ std::make_unique<protocol::Array<protocol::CSS::CSSStyle>>();
for (int i = 0; i < n; ++i) {
Member<StyleSheetAction> action = actions.at(i);
bool success = action->Perform(exception_state);
@@ -1473,7 +1473,7 @@ Response InspectorCSSAgent::setStyleTexts(
String::Format("Failed applying edit #%d: ", i) +
InspectorDOMAgent::ToResponse(exception_state).errorMessage());
}
- serialized_styles->addItem(action->TakeSerializedStyle());
+ serialized_styles->emplace_back(action->TakeSerializedStyle());
}
for (int i = 0; i < n; ++i) {
@@ -1673,16 +1673,15 @@ std::unique_ptr<protocol::CSS::CSSMedia> InspectorCSSAgent::BuildMediaObject(
parent_style_sheet
? css_style_sheet_to_inspector_style_sheet_.at(parent_style_sheet)
: nullptr;
- std::unique_ptr<protocol::Array<protocol::CSS::MediaQuery>> media_list_array =
- protocol::Array<protocol::CSS::MediaQuery>::create();
+ auto media_list_array =
+ std::make_unique<protocol::Array<protocol::CSS::MediaQuery>>();
MediaValues* media_values = MediaValues::CreateDynamicIfFrameExists(frame);
bool has_media_query_items = false;
for (wtf_size_t i = 0; i < query_vector.size(); ++i) {
MediaQuery& query = *query_vector.at(i);
const ExpressionHeapVector& expressions = query.Expressions();
- std::unique_ptr<protocol::Array<protocol::CSS::MediaQueryExpression>>
- expression_array =
- protocol::Array<protocol::CSS::MediaQueryExpression>::create();
+ auto expression_array = std::make_unique<
+ protocol::Array<protocol::CSS::MediaQueryExpression>>();
bool has_expression_items = false;
for (wtf_size_t j = 0; j < expressions.size(); ++j) {
const MediaQueryExp& media_query_exp = expressions.at(j);
@@ -1709,7 +1708,7 @@ std::unique_ptr<protocol::CSS::CSSMedia> InspectorCSSAgent::BuildMediaObject(
computed_length))
media_query_expression->setComputedLength(computed_length);
- expression_array->addItem(std::move(media_query_expression));
+ expression_array->emplace_back(std::move(media_query_expression));
has_expression_items = true;
}
if (!has_expression_items)
@@ -1719,7 +1718,7 @@ std::unique_ptr<protocol::CSS::CSSMedia> InspectorCSSAgent::BuildMediaObject(
.setActive(media_evaluator->Eval(query, nullptr))
.setExpressions(std::move(expression_array))
.build();
- media_list_array->addItem(std::move(media_query));
+ media_list_array->emplace_back(std::move(media_query));
has_media_query_items = true;
}
@@ -1761,11 +1760,11 @@ void InspectorCSSAgent::CollectMediaQueriesFromStyleSheet(
source_url = style_sheet->Contents()->BaseURL();
else
source_url = "";
- media_array->addItem(BuildMediaObject(media_list,
- style_sheet->ownerNode()
- ? kMediaListSourceLinkedSheet
- : kMediaListSourceInlineSheet,
- source_url, style_sheet));
+ media_array->emplace_back(
+ BuildMediaObject(media_list,
+ style_sheet->ownerNode() ? kMediaListSourceLinkedSheet
+ : kMediaListSourceInlineSheet,
+ source_url, style_sheet));
}
}
@@ -1797,7 +1796,7 @@ void InspectorCSSAgent::CollectMediaQueriesFromRule(
}
if (media_list && media_list->length())
- media_array->addItem(BuildMediaObject(
+ media_array->emplace_back(BuildMediaObject(
media_list,
is_media_rule ? kMediaListSourceMediaRule : kMediaListSourceImportRule,
source_url, parent_style_sheet));
@@ -1807,8 +1806,8 @@ std::unique_ptr<protocol::Array<protocol::CSS::CSSMedia>>
InspectorCSSAgent::BuildMediaListChain(CSSRule* rule) {
if (!rule)
return nullptr;
- std::unique_ptr<protocol::Array<protocol::CSS::CSSMedia>> media_array =
- protocol::Array<protocol::CSS::CSSMedia>::create();
+ auto media_array =
+ std::make_unique<protocol::Array<protocol::CSS::CSSMedia>>();
CSSRule* parent_rule = rule;
while (parent_rule) {
CollectMediaQueriesFromRule(parent_rule, media_array.get());
@@ -2025,8 +2024,7 @@ InspectorCSSAgent::BuildArrayForMatchedRuleList(
CSSRuleList* rule_list,
Element* element,
PseudoId matches_for_pseudo_id) {
- std::unique_ptr<protocol::Array<protocol::CSS::RuleMatch>> result =
- protocol::Array<protocol::CSS::RuleMatch>::create();
+ auto result = std::make_unique<protocol::Array<protocol::CSS::RuleMatch>>();
if (!rule_list)
return result;
@@ -2037,8 +2035,7 @@ InspectorCSSAgent::BuildArrayForMatchedRuleList(
BuildObjectForRule(rule);
if (!rule_object)
continue;
- std::unique_ptr<protocol::Array<int>> matching_selectors =
- protocol::Array<int>::create();
+ auto matching_selectors = std::make_unique<protocol::Array<int>>();
const CSSSelectorList& selector_list = rule->GetStyleRule()->SelectorList();
wtf_size_t index = 0;
PseudoId element_pseudo_id =
@@ -2055,13 +2052,14 @@ InspectorCSSAgent::BuildArrayForMatchedRuleList(
AtomicString(first_tag_history_selector->SelectorText()),
IGNORE_EXCEPTION_FOR_TESTING);
if (matched)
- matching_selectors->addItem(index);
+ matching_selectors->emplace_back(index);
++index;
}
- result->addItem(protocol::CSS::RuleMatch::create()
- .setRule(std::move(rule_object))
- .setMatchingSelectors(std::move(matching_selectors))
- .build());
+ result->emplace_back(
+ protocol::CSS::RuleMatch::create()
+ .setRule(std::move(rule_object))
+ .setMatchingSelectors(std::move(matching_selectors))
+ .build());
}
return result;
@@ -2135,7 +2133,7 @@ void InspectorCSSAgent::StyleSheetChanged(
void InspectorCSSAgent::ResetPseudoStates() {
HeapHashSet<Member<Document>> documents_to_change;
for (auto& state : node_id_to_forced_pseudo_state_) {
- Element* element = ToElement(dom_agent_->NodeForId(state.key));
+ auto* element = To<Element>(dom_agent_->NodeForId(state.key));
if (element && element->ownerDocument())
documents_to_change.insert(element->ownerDocument());
}
@@ -2318,9 +2316,9 @@ Response InspectorCSSAgent::getBackgroundColors(
InspectorCSSAgent::GetBackgroundColors(element, &bgcolors, &fs, &fw);
if (bgcolors.size()) {
- *background_colors = protocol::Array<String>::create();
+ *background_colors = std::make_unique<protocol::Array<String>>();
for (const auto& color : bgcolors) {
- background_colors->fromJust()->addItem(
+ background_colors->fromJust()->emplace_back(
cssvalue::CSSColorValue::SerializeAsCSSComponentValue(color));
}
}
@@ -2343,7 +2341,7 @@ void InspectorCSSAgent::GetBackgroundColors(Element* element,
return;
}
- LayoutRect content_bounds(text_node->BoundingBox());
+ PhysicalRect content_bounds = text_node->BoundingBox();
LocalFrameView* view = text_node->GetDocument().View();
if (!view)
return;
@@ -2373,11 +2371,11 @@ void InspectorCSSAgent::GetBackgroundColors(Element* element,
auto* computed_style_info =
MakeGarbageCollected<CSSComputedStyleDeclaration>(element, true);
const CSSValue* font_size =
- computed_style_info->GetPropertyCSSValue(GetCSSPropertyFontSize());
+ computed_style_info->GetPropertyCSSValue(CSSPropertyID::kFontSize);
if (font_size)
*computed_font_size = font_size->CssText();
const CSSValue* font_weight =
- computed_style_info->GetPropertyCSSValue(GetCSSPropertyFontWeight());
+ computed_style_info->GetPropertyCSSValue(CSSPropertyID::kFontWeight);
if (font_weight)
*computed_font_weight = font_weight->CssText();
}
@@ -2426,7 +2424,7 @@ Response InspectorCSSAgent::takeCoverageDelta(
StyleRuleUsageTracker::RuleListByStyleSheet coverage_delta =
tracker_->TakeDelta();
- *result = protocol::Array<protocol::CSS::RuleUsage>::create();
+ *result = std::make_unique<protocol::Array<protocol::CSS::RuleUsage>>();
for (const auto& entry : coverage_delta) {
const CSSStyleSheet* css_style_sheet = entry.key.Get();
@@ -2448,7 +2446,7 @@ Response InspectorCSSAgent::takeCoverageDelta(
CSSStyleRule* css_style_rule = rule_to_css_rule.at(used_rule);
if (std::unique_ptr<protocol::CSS::RuleUsage> rule_usage_object =
style_sheet->BuildObjectForRuleUsage(css_style_rule, true)) {
- (*result)->addItem(std::move(rule_usage_object));
+ (*result)->emplace_back(std::move(rule_usage_object));
}
}
}
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 35eb165bfdf..5d0cf170a02 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
@@ -85,7 +85,6 @@
#include "third_party/blink/renderer/core/xml/xpath_result.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/graphics/color.h"
-#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
@@ -127,7 +126,7 @@ void InspectorRevalidateDOMTask::ScheduleStyleAttrRevalidationFor(
Element* element) {
style_attr_invalidated_elements_.insert(element);
if (!timer_.IsActive())
- timer_.StartOneShot(TimeDelta(), FROM_HERE);
+ timer_.StartOneShot(base::TimeDelta(), FROM_HERE);
}
void InspectorRevalidateDOMTask::OnTimer(TimerBase*) {
@@ -322,8 +321,8 @@ void InspectorDOMAgent::Unbind(Node* node, NodeToIdMap* nodes_map) {
if (ShadowRoot* root = node->GetShadowRoot())
Unbind(root, nodes_map);
- if (node->IsElementNode()) {
- Element* element = ToElement(node);
+ auto* element = DynamicTo<Element>(node);
+ if (element) {
if (element->GetPseudoElement(kPseudoIdBefore))
Unbind(element->GetPseudoElement(kPseudoIdBefore), nodes_map);
if (element->GetPseudoElement(kPseudoIdAfter))
@@ -387,9 +386,9 @@ Response InspectorDOMAgent::AssertElement(int node_id, Element*& element) {
if (!response.isSuccess())
return response;
- if (!node->IsElementNode())
+ element = DynamicTo<Element>(node);
+ if (!element)
return Response::Error("Node is not an Element");
- element = ToElement(node);
return Response::OK();
}
@@ -514,7 +513,7 @@ Response InspectorDOMAgent::getFlattenedDocument(
sanitized_depth = INT_MAX;
nodes->reset(new protocol::Array<protocol::DOM::Node>());
- (*nodes)->addItem(BuildObjectForNode(
+ (*nodes)->emplace_back(BuildObjectForNode(
document_.Get(), sanitized_depth, pierce.fromMaybe(false),
document_node_to_id_map_.Get(), nodes->get()));
return Response::OK();
@@ -578,26 +577,25 @@ Response InspectorDOMAgent::collectClassNamesFromSubtree(
int node_id,
std::unique_ptr<protocol::Array<String>>* class_names) {
HashSet<String> unique_names;
- *class_names = protocol::Array<String>::create();
+ *class_names = std::make_unique<protocol::Array<String>>();
Node* parent_node = NodeForId(node_id);
- if (!parent_node ||
- (!parent_node->IsElementNode() && !parent_node->IsDocumentNode() &&
- !parent_node->IsDocumentFragment()))
+ auto* parent_element = DynamicTo<Element>(parent_node);
+ if (!parent_element && !parent_node->IsDocumentNode() &&
+ !parent_node->IsDocumentFragment())
return Response::Error("No suitable node with given id found");
for (Node* node = parent_node; node;
node = FlatTreeTraversal::Next(*node, parent_node)) {
- if (node->IsElementNode()) {
- const Element& element = ToElement(*node);
- if (!element.HasClass())
+ if (const auto* element = DynamicTo<Element>(node)) {
+ if (!element->HasClass())
continue;
- const SpaceSplitString& class_name_list = element.ClassNames();
+ const SpaceSplitString& class_name_list = element->ClassNames();
for (unsigned i = 0; i < class_name_list.size(); ++i)
unique_names.insert(class_name_list[i]);
}
}
for (const String& class_name : unique_names)
- (*class_names)->addItem(class_name);
+ (*class_names)->emplace_back(class_name);
return Response::OK();
}
@@ -660,10 +658,10 @@ Response InspectorDOMAgent::querySelectorAll(
if (exception_state.HadException())
return Response::Error("DOM Error while querying");
- *result = protocol::Array<int>::create();
+ *result = std::make_unique<protocol::Array<int>>();
for (unsigned i = 0; i < elements->length(); ++i)
- (*result)->addItem(PushNodePathToFrontend(elements->item(i)));
+ (*result)->emplace_back(PushNodePathToFrontend(elements->item(i)));
return Response::OK();
}
@@ -719,9 +717,8 @@ int InspectorDOMAgent::PushNodePathToFrontend(Node* node_to_push) {
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 =
- protocol::Array<protocol::DOM::Node>::create();
- children->addItem(BuildObjectForNode(node, 0, false, dangling_map));
+ auto children = std::make_unique<protocol::Array<protocol::DOM::Node>>();
+ children->emplace_back(BuildObjectForNode(node, 0, false, dangling_map));
GetFrontend()->setChildNodes(0, std::move(children));
return PushNodePathToFrontend(node_to_push, dangling_map);
@@ -766,10 +763,7 @@ Response InspectorDOMAgent::setAttributesAsText(int element_id,
fragment->ParseXML(markup, contextElement, kAllowScriptingContent);
}
- Element* parsed_element =
- fragment->firstChild() && fragment->firstChild()->IsElementNode()
- ? ToElement(fragment->firstChild())
- : nullptr;
+ Element* parsed_element = DynamicTo<Element>(fragment->firstChild());
if (!parsed_element)
return Response::Error("Could not parse value as attributes");
@@ -980,6 +974,7 @@ Response InspectorDOMAgent::performSearch(
unsigned query_length = whitespace_trimmed_query.length();
bool start_tag_found = !whitespace_trimmed_query.find('<');
+ bool start_closing_tag_found = !whitespace_trimmed_query.Find("</");
bool end_tag_found =
whitespace_trimmed_query.ReverseFind('>') + 1 == query_length;
bool start_quote_found = !whitespace_trimmed_query.find('"');
@@ -989,7 +984,9 @@ Response InspectorDOMAgent::performSearch(
String tag_name_query = whitespace_trimmed_query;
String attribute_query = whitespace_trimmed_query;
- if (start_tag_found)
+ if (start_closing_tag_found)
+ tag_name_query = tag_name_query.Right(tag_name_query.length() - 2);
+ else if (start_tag_found)
tag_name_query = tag_name_query.Right(tag_name_query.length() - 1);
if (end_tag_found)
tag_name_query = tag_name_query.Left(tag_name_query.length() - 1);
@@ -999,7 +996,7 @@ Response InspectorDOMAgent::performSearch(
attribute_query = attribute_query.Left(attribute_query.length() - 1);
HeapVector<Member<Document>> docs = Documents();
- HeapListHashSet<Member<Node>> result_collector;
+ HeapLinkedHashSet<Member<Node>> result_collector;
for (Document* document : docs) {
Node* document_element = document->documentElement();
@@ -1033,7 +1030,7 @@ Response InspectorDOMAgent::performSearch(
break;
}
// Go through all attributes and serialize them.
- const Element* element = ToElement(node);
+ const auto* element = To<Element>(node);
AttributeCollection attributes = element->Attributes();
for (auto& attribute : attributes) {
// Add attribute pair
@@ -1122,9 +1119,9 @@ Response InspectorDOMAgent::getSearchResults(
if (from_index < 0 || to_index > size || from_index >= to_index)
return Response::Error("Invalid search result range");
- *node_ids = protocol::Array<int>::create();
+ *node_ids = std::make_unique<protocol::Array<int>>();
for (int i = from_index; i < to_index; ++i)
- (*node_ids)->addItem(PushNodePathToFrontend((it->value)[i].Get()));
+ (*node_ids)->emplace_back(PushNodePathToFrontend((it->value)[i].Get()));
return Response::OK();
}
@@ -1252,9 +1249,9 @@ Response InspectorDOMAgent::focus(Maybe<int> node_id,
Response response = AssertNode(node_id, backend_node_id, object_id, node);
if (!response.isSuccess())
return response;
- if (!node->IsElementNode())
+ auto* element = DynamicTo<Element>(node);
+ if (!element)
return Response::Error("Node is not an Element");
- Element* element = ToElement(node);
element->GetDocument().UpdateStyleAndLayout();
if (!element->IsFocusable())
return Response::Error("Element is not focusable");
@@ -1276,8 +1273,8 @@ Response InspectorDOMAgent::setFileInputFiles(
return Response::Error("Node is not a file input element");
Vector<String> paths;
- for (size_t index = 0; index < files->length(); ++index)
- paths.push_back(files->get(index));
+ for (const String& file : *files)
+ paths.push_back(file);
ToHTMLInputElement(node)->SetFilesFromPaths(paths);
return Response::OK();
}
@@ -1322,8 +1319,9 @@ Response InspectorDOMAgent::getNodeForLocation(
bool include_user_agent_shadow_dom =
optional_include_user_agent_shadow_dom.fromMaybe(false);
Document* document = inspected_frames_->Root()->GetDocument();
- LayoutPoint document_point(x * inspected_frames_->Root()->PageZoomFactor(),
- y * inspected_frames_->Root()->PageZoomFactor());
+ PhysicalOffset document_point(
+ LayoutUnit(x * inspected_frames_->Root()->PageZoomFactor()),
+ LayoutUnit(y * inspected_frames_->Root()->PageZoomFactor()));
HitTestRequest request(HitTestRequest::kMove | HitTestRequest::kReadOnly |
HitTestRequest::kAllowChildFrameContent);
HitTestLocation location(document->View()->DocumentToFrame(document_point));
@@ -1444,7 +1442,7 @@ std::unique_ptr<protocol::DOM::Node> InspectorDOMAgent::BuildObjectForNode(
local_name = To<Attr>(node)->localName();
break;
case Node::kElementNode:
- local_name = ToElement(node)->localName();
+ local_name = To<Element>(node)->localName();
break;
default:
break;
@@ -1464,8 +1462,7 @@ std::unique_ptr<protocol::DOM::Node> InspectorDOMAgent::BuildObjectForNode(
value->setIsSVG(true);
bool force_push_children = false;
- if (node->IsElementNode()) {
- Element* element = ToElement(node);
+ if (auto* element = DynamicTo<Element>(node)) {
value->setAttributes(BuildArrayForElementAttributes(element));
if (auto* frame_owner = DynamicTo<HTMLFrameOwnerElement>(node)) {
@@ -1486,10 +1483,10 @@ std::unique_ptr<protocol::DOM::Node> InspectorDOMAgent::BuildObjectForNode(
}
if (ShadowRoot* root = element->GetShadowRoot()) {
- std::unique_ptr<protocol::Array<protocol::DOM::Node>> shadow_roots =
- protocol::Array<protocol::DOM::Node>::create();
- shadow_roots->addItem(BuildObjectForNode(root, pierce ? depth : 0, pierce,
- nodes_map, flatten_result));
+ auto shadow_roots =
+ std::make_unique<protocol::Array<protocol::DOM::Node>>();
+ shadow_roots->emplace_back(BuildObjectForNode(
+ root, pierce ? depth : 0, pierce, nodes_map, flatten_result));
value->setShadowRoots(std::move(shadow_roots));
force_push_children = true;
}
@@ -1561,7 +1558,7 @@ std::unique_ptr<protocol::DOM::Node> InspectorDOMAgent::BuildObjectForNode(
std::unique_ptr<protocol::Array<protocol::DOM::Node>> children =
BuildArrayForContainerChildren(node, depth, pierce, nodes_map,
flatten_result);
- if (children->length() > 0 ||
+ if (!children->empty() ||
depth) // Push children along with shadow in any case.
value->setChildren(std::move(children));
}
@@ -1571,14 +1568,12 @@ std::unique_ptr<protocol::DOM::Node> InspectorDOMAgent::BuildObjectForNode(
std::unique_ptr<protocol::Array<String>>
InspectorDOMAgent::BuildArrayForElementAttributes(Element* element) {
- std::unique_ptr<protocol::Array<String>> attributes_value =
- protocol::Array<String>::create();
+ auto attributes_value = std::make_unique<protocol::Array<String>>();
// Go through all attributes and serialize them.
- AttributeCollection attributes = element->Attributes();
- for (auto& attribute : attributes) {
+ for (const blink::Attribute& attribute : element->Attributes()) {
// Add attribute pair
- attributes_value->addItem(attribute.GetName().ToString());
- attributes_value->addItem(attribute.Value());
+ attributes_value->emplace_back(attribute.GetName().ToString());
+ attributes_value->emplace_back(attribute.Value());
}
return attributes_value;
}
@@ -1590,8 +1585,7 @@ InspectorDOMAgent::BuildArrayForContainerChildren(
bool pierce,
NodeToIdMap* nodes_map,
protocol::Array<protocol::DOM::Node>* flatten_result) {
- std::unique_ptr<protocol::Array<protocol::DOM::Node>> children =
- protocol::Array<protocol::DOM::Node>::create();
+ auto children = std::make_unique<protocol::Array<protocol::DOM::Node>>();
if (depth == 0) {
if (!nodes_map)
return children;
@@ -1604,9 +1598,9 @@ InspectorDOMAgent::BuildArrayForContainerChildren(
BuildObjectForNode(first_child, 0, pierce, nodes_map, flatten_result);
child_node->setParentId(Bind(container, nodes_map));
if (flatten_result) {
- flatten_result->addItem(std::move(child_node));
+ flatten_result->emplace_back(std::move(child_node));
} else {
- children->addItem(std::move(child_node));
+ children->emplace_back(std::move(child_node));
}
children_requested_.insert(Bind(container, nodes_map));
}
@@ -1623,9 +1617,9 @@ InspectorDOMAgent::BuildArrayForContainerChildren(
BuildObjectForNode(child, depth, pierce, nodes_map, flatten_result);
child_node->setParentId(Bind(container, nodes_map));
if (flatten_result) {
- flatten_result->addItem(std::move(child_node));
+ flatten_result->emplace_back(std::move(child_node));
} else {
- children->addItem(std::move(child_node));
+ children->emplace_back(std::move(child_node));
}
if (nodes_map)
children_requested_.insert(Bind(container, nodes_map));
@@ -1641,14 +1635,14 @@ InspectorDOMAgent::BuildArrayForPseudoElements(Element* element,
!element->GetPseudoElement(kPseudoIdAfter))
return nullptr;
- std::unique_ptr<protocol::Array<protocol::DOM::Node>> pseudo_elements =
- protocol::Array<protocol::DOM::Node>::create();
+ auto pseudo_elements =
+ std::make_unique<protocol::Array<protocol::DOM::Node>>();
if (element->GetPseudoElement(kPseudoIdBefore)) {
- pseudo_elements->addItem(BuildObjectForNode(
+ pseudo_elements->emplace_back(BuildObjectForNode(
element->GetPseudoElement(kPseudoIdBefore), 0, false, nodes_map));
}
if (element->GetPseudoElement(kPseudoIdAfter)) {
- pseudo_elements->addItem(BuildObjectForNode(
+ pseudo_elements->emplace_back(BuildObjectForNode(
element->GetPseudoElement(kPseudoIdAfter), 0, false, nodes_map));
}
return pseudo_elements;
@@ -1657,8 +1651,8 @@ InspectorDOMAgent::BuildArrayForPseudoElements(Element* element,
std::unique_ptr<protocol::Array<protocol::DOM::BackendNode>>
InspectorDOMAgent::BuildArrayForDistributedNodes(
V0InsertionPoint* insertion_point) {
- std::unique_ptr<protocol::Array<protocol::DOM::BackendNode>>
- distributed_nodes = protocol::Array<protocol::DOM::BackendNode>::create();
+ auto distributed_nodes =
+ std::make_unique<protocol::Array<protocol::DOM::BackendNode>>();
for (wtf_size_t i = 0; i < insertion_point->DistributedNodesSize(); ++i) {
Node* distributed_node = insertion_point->DistributedNodeAt(i);
if (IsWhitespace(distributed_node))
@@ -1671,7 +1665,7 @@ InspectorDOMAgent::BuildArrayForDistributedNodes(
.setBackendNodeId(
IdentifiersFactory::IntIdForNode(distributed_node))
.build();
- distributed_nodes->addItem(std::move(backend_node));
+ distributed_nodes->emplace_back(std::move(backend_node));
}
return distributed_nodes;
}
@@ -1682,8 +1676,8 @@ InspectorDOMAgent::BuildDistributedNodesForSlot(HTMLSlotElement* slot_element) {
// not be used anymore. DistributedNodes should be replaced with
// AssignedNodes() when IncrementalShadowDOM becomes stable and Shadow DOM v0
// is removed.
- std::unique_ptr<protocol::Array<protocol::DOM::BackendNode>>
- distributed_nodes = protocol::Array<protocol::DOM::BackendNode>::create();
+ auto distributed_nodes =
+ std::make_unique<protocol::Array<protocol::DOM::BackendNode>>();
for (auto& node : slot_element->AssignedNodes()) {
if (IsWhitespace(node))
continue;
@@ -1694,7 +1688,7 @@ InspectorDOMAgent::BuildDistributedNodesForSlot(HTMLSlotElement* slot_element) {
.setNodeName(node->nodeName())
.setBackendNodeId(IdentifiersFactory::IntIdForNode(node))
.build();
- distributed_nodes->addItem(std::move(backend_node));
+ distributed_nodes->emplace_back(std::move(backend_node));
}
return distributed_nodes;
}
@@ -1763,8 +1757,8 @@ void InspectorDOMAgent::CollectNodes(
if (--depth <= 0)
return;
- if (pierce && node->IsElementNode()) {
- Element* element = ToElement(node);
+ auto* element = DynamicTo<Element>(node);
+ if (pierce && element) {
if (auto* frame_owner = DynamicTo<HTMLFrameOwnerElement>(node)) {
if (frame_owner->ContentFrame() &&
frame_owner->ContentFrame()->IsLocalFrame()) {
@@ -1935,8 +1929,7 @@ void InspectorDOMAgent::DidRemoveDOMAttr(Element* element,
void InspectorDOMAgent::StyleAttributeInvalidated(
const HeapVector<Member<Element>>& elements) {
- std::unique_ptr<protocol::Array<int>> node_ids =
- protocol::Array<int>::create();
+ auto node_ids = std::make_unique<protocol::Array<int>>();
for (unsigned i = 0, size = elements.size(); i < size; ++i) {
Element* element = elements.at(i);
int id = BoundNodeId(element);
@@ -1946,7 +1939,7 @@ void InspectorDOMAgent::StyleAttributeInvalidated(
if (dom_listener_)
dom_listener_->DidModifyDOMAttr(element);
- node_ids->addItem(id);
+ node_ids->emplace_back(id);
}
GetFrontend()->inlineStyleInvalidated(std::move(node_ids));
}
@@ -1977,7 +1970,7 @@ void InspectorDOMAgent::DidInvalidateStyleAttr(Node* node) {
if (!id)
return;
- RevalidateTask()->ScheduleStyleAttrRevalidationFor(ToElement(node));
+ RevalidateTask()->ScheduleStyleAttrRevalidationFor(To<Element>(node));
}
void InspectorDOMAgent::DidPushShadowRoot(Element* host, ShadowRoot* root) {
@@ -2088,12 +2081,13 @@ void InspectorDOMAgent::PseudoElementDestroyed(PseudoElement* pseudo_element) {
}
static ShadowRoot* ShadowRootForNode(Node* node, const String& type) {
- if (!node->IsElementNode())
+ auto* element = DynamicTo<Element>(node);
+ if (!element)
return nullptr;
if (type == "a")
- return ToElement(node)->AuthorShadowRoot();
+ return element->AuthorShadowRoot();
if (type == "u")
- return ToElement(node)->UserAgentShadowRoot();
+ return element->UserAgentShadowRoot();
return nullptr;
}
@@ -2152,14 +2146,14 @@ Response InspectorDOMAgent::pushNodesByBackendIdsToFrontend(
if (!document_ || !document_node_to_id_map_->Contains(document_))
return Response::Error("Document needs to be requested first");
- *result = protocol::Array<int>::create();
- for (size_t index = 0; index < backend_node_ids->length(); ++index) {
- Node* node = DOMNodeIds::NodeForId(backend_node_ids->get(index));
+ *result = std::make_unique<protocol::Array<int>>();
+ for (int id : *backend_node_ids) {
+ Node* node = DOMNodeIds::NodeForId(id);
if (node && node->GetDocument().GetFrame() &&
inspected_frames_->Contains(node->GetDocument().GetFrame()))
- (*result)->addItem(PushNodePathToFrontend(node));
+ (*result)->emplace_back(PushNodePathToFrontend(node));
else
- (*result)->addItem(0);
+ (*result)->emplace_back(0);
}
return Response::OK();
}
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_dom_debugger_agent.cc b/chromium/third_party/blink/renderer/core/inspector/inspector_dom_debugger_agent.cc
index 29d65745a5e..d1bbcbcd5fe 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_dom_debugger_agent.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_dom_debugger_agent.cc
@@ -423,9 +423,8 @@ InspectorDOMDebuggerAgent::BuildObjectsForEventListeners(
const V8EventListenerInfoList& event_information,
v8::Local<v8::Context> context,
const v8_inspector::StringView& object_group_id) {
- std::unique_ptr<protocol::Array<protocol::DOMDebugger::EventListener>>
- listeners_array =
- protocol::Array<protocol::DOMDebugger::EventListener>::create();
+ auto listeners_array =
+ std::make_unique<protocol::Array<protocol::DOMDebugger::EventListener>>();
// Make sure listeners with |use_capture| true come first because they have
// precedence.
for (const auto& info : event_information) {
@@ -434,7 +433,7 @@ InspectorDOMDebuggerAgent::BuildObjectsForEventListeners(
std::unique_ptr<protocol::DOMDebugger::EventListener> listener_object =
BuildObjectForEventListener(context, info, object_group_id);
if (listener_object)
- listeners_array->addItem(std::move(listener_object));
+ listeners_array->emplace_back(std::move(listener_object));
}
for (const auto& info : event_information) {
if (info.use_capture)
@@ -442,7 +441,7 @@ InspectorDOMDebuggerAgent::BuildObjectsForEventListeners(
std::unique_ptr<protocol::DOMDebugger::EventListener> listener_object =
BuildObjectForEventListener(context, info, object_group_id);
if (listener_object)
- listeners_array->addItem(std::move(listener_object));
+ listeners_array->emplace_back(std::move(listener_object));
}
return listeners_array;
}
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 8e38ad396fe..a93cb08dd5c 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
@@ -37,9 +37,8 @@
#include "third_party/blink/renderer/core/layout/layout_text.h"
#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/paint/paint_layer_paint_order_iterator.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
-#include "third_party/blink/renderer/core/paint/paint_layer_stacking_node.h"
-#include "third_party/blink/renderer/core/paint/paint_layer_stacking_node_iterator.h"
#include "v8/include/v8-inspector.h"
namespace blink {
@@ -48,8 +47,8 @@ using protocol::Response;
namespace {
-std::unique_ptr<protocol::DOM::Rect> BuildRectForLayoutRect(
- const LayoutRect& rect) {
+std::unique_ptr<protocol::DOM::Rect> BuildRectForPhysicalRect(
+ const PhysicalRect& rect) {
return protocol::DOM::Rect::create()
.setX(rect.X())
.setY(rect.Y())
@@ -58,20 +57,24 @@ std::unique_ptr<protocol::DOM::Rect> BuildRectForLayoutRect(
.build();
}
-std::unique_ptr<protocol::Array<double>> BuildRectForLayoutRect2(
- const LayoutRect& rect) {
- std::unique_ptr<protocol::Array<double>> result =
- protocol::Array<double>::create();
- result->addItem(rect.X());
- result->addItem(rect.Y());
- result->addItem(rect.Width());
- result->addItem(rect.Height());
- return result;
+std::unique_ptr<protocol::Array<double>> BuildRectForPhysicalRect2(
+ const PhysicalRect& rect) {
+ return std::make_unique<std::vector<double>, std::initializer_list<double>>(
+ {rect.X(), rect.Y(), rect.Width(), rect.Height()});
+}
+
+std::unique_ptr<protocol::Array<double>> BuildRectForLayout(const int x,
+ const int y,
+ const int width,
+ const int height) {
+ return std::make_unique<std::vector<double>, std::initializer_list<double>>(
+ {x, y, width, height});
}
// Returns |layout_object|'s bounding box in document coordinates.
-LayoutRect RectInDocument(const LayoutObject* layout_object) {
- LayoutRect rect_in_absolute(layout_object->AbsoluteBoundingBoxFloatRect());
+PhysicalRect RectInDocument(const LayoutObject* layout_object) {
+ PhysicalRect rect_in_absolute = PhysicalRect::EnclosingRect(
+ layout_object->AbsoluteBoundingBoxFloatRect());
LocalFrameView* local_frame_view = layout_object->GetFrameView();
// Don't do frame to document coordinate transformation for layout view,
// whose bounding box is not affected by scroll offset.
@@ -80,17 +83,17 @@ LayoutRect RectInDocument(const LayoutObject* layout_object) {
return rect_in_absolute;
}
-LayoutRect TextFragmentRectInDocument(const LayoutObject* layout_object,
- const LayoutText::TextBoxInfo& text_box) {
+PhysicalRect TextFragmentRectInDocument(
+ const LayoutObject* layout_object,
+ const LayoutText::TextBoxInfo& text_box) {
PhysicalRect local_coords_text_box_rect =
layout_object->FlipForWritingMode(text_box.local_rect);
PhysicalRect absolute_coords_text_box_rect =
layout_object->LocalToAbsoluteRect(local_coords_text_box_rect);
LocalFrameView* local_frame_view = layout_object->GetFrameView();
- return (local_frame_view
- ? local_frame_view->FrameToDocument(absolute_coords_text_box_rect)
- : absolute_coords_text_box_rect)
- .ToLayoutRect();
+ return local_frame_view
+ ? local_frame_view->FrameToDocument(absolute_coords_text_box_rect)
+ : absolute_coords_text_box_rect;
}
Document* GetEmbeddedDocument(PaintLayer* layer) {
@@ -106,21 +109,21 @@ Document* GetEmbeddedDocument(PaintLayer* layer) {
std::unique_ptr<protocol::DOMSnapshot::RareStringData> StringData() {
return protocol::DOMSnapshot::RareStringData::create()
- .setIndex(protocol::Array<int>::create())
- .setValue(protocol::Array<int>::create())
+ .setIndex(std::make_unique<protocol::Array<int>>())
+ .setValue(std::make_unique<protocol::Array<int>>())
.build();
}
std::unique_ptr<protocol::DOMSnapshot::RareIntegerData> IntegerData() {
return protocol::DOMSnapshot::RareIntegerData::create()
- .setIndex(protocol::Array<int>::create())
- .setValue(protocol::Array<int>::create())
+ .setIndex(std::make_unique<protocol::Array<int>>())
+ .setValue(std::make_unique<protocol::Array<int>>())
.build();
}
std::unique_ptr<protocol::DOMSnapshot::RareBooleanData> BooleanData() {
return protocol::DOMSnapshot::RareBooleanData::create()
- .setIndex(protocol::Array<int>::create())
+ .setIndex(std::make_unique<protocol::Array<int>>())
.build();
}
@@ -251,21 +254,21 @@ Response InspectorDOMSnapshotAgent::getSnapshot(
return Response::Error("Document is not available");
// Setup snapshot.
- dom_nodes_ = protocol::Array<protocol::DOMSnapshot::DOMNode>::create();
- layout_tree_nodes_ =
- protocol::Array<protocol::DOMSnapshot::LayoutTreeNode>::create();
+ dom_nodes_ =
+ std::make_unique<protocol::Array<protocol::DOMSnapshot::DOMNode>>();
+ layout_tree_nodes_ = std::make_unique<
+ protocol::Array<protocol::DOMSnapshot::LayoutTreeNode>>();
computed_styles_ =
- protocol::Array<protocol::DOMSnapshot::ComputedStyle>::create();
+ std::make_unique<protocol::Array<protocol::DOMSnapshot::ComputedStyle>>();
computed_styles_map_ = std::make_unique<ComputedStylesMap>();
css_property_filter_ = std::make_unique<CSSPropertyFilter>();
// Look up the CSSPropertyIDs for each entry in |style_filter|.
- for (wtf_size_t i = 0; i < style_filter->length(); i++) {
- CSSPropertyID property_id = cssPropertyID(style_filter->get(i));
+ for (const String& entry : *style_filter) {
+ CSSPropertyID property_id = cssPropertyID(entry);
if (property_id == CSSPropertyID::kInvalid)
continue;
- css_property_filter_->push_back(
- std::make_pair(style_filter->get(i), property_id));
+ css_property_filter_->emplace_back(entry, property_id);
}
if (include_paint_order.fromMaybe(false)) {
@@ -290,23 +293,26 @@ Response InspectorDOMSnapshotAgent::getSnapshot(
protocol::Response InspectorDOMSnapshotAgent::captureSnapshot(
std::unique_ptr<protocol::Array<String>> computed_styles,
+ protocol::Maybe<bool> include_dom_rects,
std::unique_ptr<protocol::Array<protocol::DOMSnapshot::DocumentSnapshot>>*
documents,
std::unique_ptr<protocol::Array<String>>* strings) {
- strings_ = protocol::Array<String>::create();
- documents_ =
- protocol::Array<protocol::DOMSnapshot::DocumentSnapshot>::create();
+ strings_ = std::make_unique<protocol::Array<String>>();
+ documents_ = std::make_unique<
+ protocol::Array<protocol::DOMSnapshot::DocumentSnapshot>>();
css_property_filter_ = std::make_unique<CSSPropertyFilter>();
// Look up the CSSPropertyIDs for each entry in |computed_styles|.
- for (size_t i = 0; i < computed_styles->length(); i++) {
- CSSPropertyID property_id = cssPropertyID(computed_styles->get(i));
+ for (String& entry : *computed_styles) {
+ CSSPropertyID property_id = cssPropertyID(entry);
if (property_id == CSSPropertyID::kInvalid)
continue;
- css_property_filter_->push_back(
- std::make_pair(computed_styles->get(i), property_id));
+ css_property_filter_->emplace_back(std::move(entry),
+ std::move(property_id));
}
+ include_snapshot_dom_rects_ = include_dom_rects.fromMaybe(false);
+
for (LocalFrame* frame : *inspected_frames_) {
if (Document* document = frame->GetDocument())
document_order_map_.Set(document, document_order_map_.size());
@@ -370,8 +376,8 @@ int InspectorDOMSnapshotAgent::VisitNode(Node* node,
}
}
protocol::DOMSnapshot::DOMNode* value = owned_value.get();
- int index = static_cast<int>(dom_nodes_->length());
- dom_nodes_->addItem(std::move(owned_value));
+ int index = static_cast<int>(dom_nodes_->size());
+ dom_nodes_->emplace_back(std::move(owned_value));
int layoutNodeIndex =
VisitLayoutTreeNode(node->GetLayoutObject(), node, index);
@@ -399,8 +405,8 @@ int InspectorDOMSnapshotAgent::VisitNode(Node* node,
}
}
- if (node->IsElementNode()) {
- Element* element = ToElement(node);
+ auto* element = DynamicTo<Element>(node);
+ if (element) {
value->setAttributes(BuildArrayForElementAttributes(element));
if (auto* frame_owner = DynamicTo<HTMLFrameOwnerElement>(node)) {
@@ -455,9 +461,9 @@ int InspectorDOMSnapshotAgent::VisitNode(Node* node,
value->setDocumentURL(InspectorDOMAgent::DocumentURLString(document));
value->setBaseURL(InspectorDOMAgent::DocumentBaseURLString(document));
if (document->ContentLanguage())
- value->setContentLanguage(document->ContentLanguage().Utf8().data());
+ value->setContentLanguage(document->ContentLanguage().Utf8().c_str());
if (document->EncodingName())
- value->setDocumentEncoding(document->EncodingName().Utf8().data());
+ value->setDocumentEncoding(document->EncodingName().Utf8().c_str());
value->setFrameId(IdentifiersFactory::FrameId(document->GetFrame()));
if (document->View() && document->View()->LayoutViewport()) {
auto offset = document->View()->LayoutViewport()->GetScrollOffset();
@@ -486,8 +492,8 @@ int InspectorDOMSnapshotAgent::AddString(const String& string) {
auto it = string_table_.find(string);
int index;
if (it == string_table_.end()) {
- index = static_cast<int>(strings_->length());
- strings_->addItem(string);
+ index = static_cast<int>(strings_->size());
+ strings_->emplace_back(string);
string_table_.Set(string, index);
} else {
index = it->value;
@@ -499,22 +505,22 @@ void InspectorDOMSnapshotAgent::SetRare(
protocol::DOMSnapshot::RareIntegerData* data,
int index,
int value) {
- data->getIndex()->addItem(index);
- data->getValue()->addItem(value);
+ data->getIndex()->emplace_back(index);
+ data->getValue()->emplace_back(value);
}
void InspectorDOMSnapshotAgent::SetRare(
protocol::DOMSnapshot::RareStringData* data,
int index,
const String& value) {
- data->getIndex()->addItem(index);
- data->getValue()->addItem(AddString(value));
+ data->getIndex()->emplace_back(index);
+ data->getValue()->emplace_back(AddString(value));
}
void InspectorDOMSnapshotAgent::SetRare(
protocol::DOMSnapshot::RareBooleanData* data,
int index) {
- data->getIndex()->addItem(index);
+ data->getIndex()->emplace_back(index);
}
void InspectorDOMSnapshotAgent::VisitDocument2(Document* document) {
@@ -537,38 +543,42 @@ void InspectorDOMSnapshotAgent::VisitDocument2(Document* document) {
AddString(IdentifiersFactory::FrameId(document->GetFrame())))
.setPublicId(AddString(doc_type ? doc_type->publicId() : String()))
.setSystemId(AddString(doc_type ? doc_type->systemId() : String()))
- .setNodes(protocol::DOMSnapshot::NodeTreeSnapshot::create()
- .setParentIndex(protocol::Array<int>::create())
- .setNodeType(protocol::Array<int>::create())
- .setNodeName(protocol::Array<int>::create())
- .setNodeValue(protocol::Array<int>::create())
- .setBackendNodeId(protocol::Array<int>::create())
- .setAttributes(
- protocol::Array<protocol::Array<int>>::create())
- .setTextValue(StringData())
- .setInputValue(StringData())
- .setInputChecked(BooleanData())
- .setOptionSelected(BooleanData())
- .setContentDocumentIndex(IntegerData())
- .setPseudoType(StringData())
- .setIsClickable(BooleanData())
- .setCurrentSourceURL(StringData())
- .setOriginURL(StringData())
- .build())
+ .setNodes(
+ protocol::DOMSnapshot::NodeTreeSnapshot::create()
+ .setParentIndex(std::make_unique<protocol::Array<int>>())
+ .setNodeType(std::make_unique<protocol::Array<int>>())
+ .setNodeName(std::make_unique<protocol::Array<int>>())
+ .setNodeValue(std::make_unique<protocol::Array<int>>())
+ .setBackendNodeId(std::make_unique<protocol::Array<int>>())
+ .setAttributes(
+ std::make_unique<protocol::Array<protocol::Array<int>>>())
+ .setTextValue(StringData())
+ .setInputValue(StringData())
+ .setInputChecked(BooleanData())
+ .setOptionSelected(BooleanData())
+ .setContentDocumentIndex(IntegerData())
+ .setPseudoType(StringData())
+ .setIsClickable(BooleanData())
+ .setCurrentSourceURL(StringData())
+ .setOriginURL(StringData())
+ .build())
.setLayout(
protocol::DOMSnapshot::LayoutTreeSnapshot::create()
- .setNodeIndex(protocol::Array<int>::create())
- .setBounds(protocol::Array<protocol::Array<double>>::create())
- .setText(protocol::Array<int>::create())
- .setStyles(protocol::Array<protocol::Array<int>>::create())
+ .setNodeIndex(std::make_unique<protocol::Array<int>>())
+ .setBounds(std::make_unique<
+ protocol::Array<protocol::Array<double>>>())
+ .setText(std::make_unique<protocol::Array<int>>())
+ .setStyles(
+ std::make_unique<protocol::Array<protocol::Array<int>>>())
.setStackingContexts(BooleanData())
.build())
.setTextBoxes(
protocol::DOMSnapshot::TextBoxSnapshot::create()
- .setLayoutIndex(protocol::Array<int>::create())
- .setBounds(protocol::Array<protocol::Array<double>>::create())
- .setStart(protocol::Array<int>::create())
- .setLength(protocol::Array<int>::create())
+ .setLayoutIndex(std::make_unique<protocol::Array<int>>())
+ .setBounds(std::make_unique<
+ protocol::Array<protocol::Array<double>>>())
+ .setStart(std::make_unique<protocol::Array<int>>())
+ .setLength(std::make_unique<protocol::Array<int>>())
.build())
.build();
@@ -578,8 +588,17 @@ void InspectorDOMSnapshotAgent::VisitDocument2(Document* document) {
document_->setScrollOffsetY(offset.Height());
}
+ if (include_snapshot_dom_rects_) {
+ document_->getLayout()->setOffsetRects(
+ std::make_unique<protocol::Array<protocol::Array<double>>>());
+ document_->getLayout()->setClientRects(
+ std::make_unique<protocol::Array<protocol::Array<double>>>());
+ document_->getLayout()->setScrollRects(
+ std::make_unique<protocol::Array<protocol::Array<double>>>());
+ }
+
VisitNode2(document, -1);
- documents_->addItem(std::move(document_));
+ documents_->emplace_back(std::move(document_));
}
int InspectorDOMSnapshotAgent::VisitNode2(Node* node, int parent_index) {
@@ -597,19 +616,21 @@ int InspectorDOMSnapshotAgent::VisitNode2(Node* node, int parent_index) {
}
auto* nodes = document_->getNodes();
- int index = static_cast<int>(nodes->getNodeName(nullptr)->length());
+ int index = static_cast<int>(nodes->getNodeName(nullptr)->size());
DOMNodeId backend_node_id = DOMNodeIds::IdForNode(node);
// Create DOMNode object and add it to the result array before traversing
// children, so that parents appear before their children in the array.
- nodes->getParentIndex(nullptr)->addItem(parent_index);
+ nodes->getParentIndex(nullptr)->emplace_back(parent_index);
- nodes->getNodeType(nullptr)->addItem(static_cast<int>(node->getNodeType()));
- nodes->getNodeName(nullptr)->addItem(AddString(node->nodeName()));
- nodes->getNodeValue(nullptr)->addItem(AddString(node_value));
- nodes->getBackendNodeId(nullptr)->addItem(
+ nodes->getNodeType(nullptr)->emplace_back(
+ static_cast<int>(node->getNodeType()));
+ nodes->getNodeName(nullptr)->emplace_back(AddString(node->nodeName()));
+ nodes->getNodeValue(nullptr)->emplace_back(AddString(node_value));
+ nodes->getBackendNodeId(nullptr)->emplace_back(
IdentifiersFactory::IntIdForNode(node));
- nodes->getAttributes(nullptr)->addItem(BuildArrayForElementAttributes2(node));
+ nodes->getAttributes(nullptr)->emplace_back(
+ BuildArrayForElementAttributes2(node));
BuildLayoutTreeNode(node->GetLayoutObject(), node, index);
if (origin_url_map_ && origin_url_map_->Contains(backend_node_id)) {
@@ -625,8 +646,8 @@ int InspectorDOMSnapshotAgent::VisitNode2(Node* node, int parent_index) {
if (node->WillRespondToMouseClickEvents())
SetRare(nodes->getIsClickable(nullptr), index);
- if (node->IsElementNode()) {
- Element* element = ToElement(node);
+ auto* element = DynamicTo<Element>(node);
+ if (element) {
if (auto* frame_owner = DynamicTo<HTMLFrameOwnerElement>(node)) {
if (Document* doc = frame_owner->contentDocument()) {
SetRare(nodes->getContentDocumentIndex(nullptr), index,
@@ -721,15 +742,15 @@ InspectorDOMSnapshotAgent::VisitContainerChildren(
Node* container,
bool include_event_listeners,
bool include_user_agent_shadow_tree) {
- auto children = protocol::Array<int>::create();
+ auto children = std::make_unique<protocol::Array<int>>();
if (!HasChildren(*container, include_user_agent_shadow_tree))
return nullptr;
Node* child = FirstChild(*container, include_user_agent_shadow_tree);
while (child) {
- children->addItem(VisitNode(child, include_event_listeners,
- include_user_agent_shadow_tree));
+ children->emplace_back(VisitNode(child, include_event_listeners,
+ include_user_agent_shadow_tree));
child = NextSibling(*child, include_user_agent_shadow_tree);
}
@@ -777,12 +798,13 @@ InspectorDOMSnapshotAgent::VisitPseudoElements(
return nullptr;
}
- auto pseudo_elements = protocol::Array<int>::create();
+ auto pseudo_elements = std::make_unique<protocol::Array<int>>();
for (PseudoId pseudo_id :
{kPseudoIdFirstLetter, kPseudoIdBefore, kPseudoIdAfter}) {
if (Node* pseudo_node = parent->GetPseudoElement(pseudo_id)) {
- pseudo_elements->addItem(VisitNode(pseudo_node, include_event_listeners,
- include_user_agent_shadow_tree));
+ pseudo_elements->emplace_back(VisitNode(pseudo_node,
+ include_event_listeners,
+ include_user_agent_shadow_tree));
}
}
return pseudo_elements;
@@ -799,29 +821,30 @@ void InspectorDOMSnapshotAgent::VisitPseudoElements2(Element* parent,
std::unique_ptr<protocol::Array<protocol::DOMSnapshot::NameValue>>
InspectorDOMSnapshotAgent::BuildArrayForElementAttributes(Element* element) {
- auto attributes_value =
- protocol::Array<protocol::DOMSnapshot::NameValue>::create();
AttributeCollection attributes = element->Attributes();
+ if (attributes.IsEmpty())
+ return nullptr;
+ auto attributes_value =
+ std::make_unique<protocol::Array<protocol::DOMSnapshot::NameValue>>();
for (const auto& attribute : attributes) {
- attributes_value->addItem(protocol::DOMSnapshot::NameValue::create()
- .setName(attribute.GetName().ToString())
- .setValue(attribute.Value())
- .build());
+ attributes_value->emplace_back(protocol::DOMSnapshot::NameValue::create()
+ .setName(attribute.GetName().ToString())
+ .setValue(attribute.Value())
+ .build());
}
- if (attributes_value->length() == 0)
- return nullptr;
return attributes_value;
}
std::unique_ptr<protocol::Array<int>>
InspectorDOMSnapshotAgent::BuildArrayForElementAttributes2(Node* node) {
- auto result = protocol::Array<int>::create();
- if (!node->IsElementNode())
+ auto result = std::make_unique<protocol::Array<int>>();
+ auto* element = DynamicTo<Element>(node);
+ if (!element)
return result;
- AttributeCollection attributes = ToElement(node)->Attributes();
+ AttributeCollection attributes = element->Attributes();
for (const auto& attribute : attributes) {
- result->addItem(AddString(attribute.GetName().ToString()));
- result->addItem(AddString(attribute.Value()));
+ result->emplace_back(AddString(attribute.GetName().ToString()));
+ result->emplace_back(AddString(attribute.Value()));
}
return result;
}
@@ -832,11 +855,11 @@ int InspectorDOMSnapshotAgent::VisitLayoutTreeNode(LayoutObject* layout_object,
if (!layout_object)
return -1;
- auto layout_tree_node =
- protocol::DOMSnapshot::LayoutTreeNode::create()
- .setDomNodeIndex(node_index)
- .setBoundingBox(BuildRectForLayoutRect(RectInDocument(layout_object)))
- .build();
+ auto layout_tree_node = protocol::DOMSnapshot::LayoutTreeNode::create()
+ .setDomNodeIndex(node_index)
+ .setBoundingBox(BuildRectForPhysicalRect(
+ RectInDocument(layout_object)))
+ .build();
int style_index = GetStyleIndexForNode(node);
if (style_index != -1)
@@ -860,15 +883,14 @@ int InspectorDOMSnapshotAgent::VisitLayoutTreeNode(LayoutObject* layout_object,
layout_tree_node->setLayoutText(layout_text->GetText());
Vector<LayoutText::TextBoxInfo> text_boxes = layout_text->GetTextBoxInfo();
if (!text_boxes.IsEmpty()) {
- std::unique_ptr<protocol::Array<protocol::DOMSnapshot::InlineTextBox>>
- inline_text_nodes =
- protocol::Array<protocol::DOMSnapshot::InlineTextBox>::create();
+ auto inline_text_nodes = std::make_unique<
+ protocol::Array<protocol::DOMSnapshot::InlineTextBox>>();
for (const auto& text_box : text_boxes) {
- inline_text_nodes->addItem(
+ inline_text_nodes->emplace_back(
protocol::DOMSnapshot::InlineTextBox::create()
.setStartCharacterIndex(text_box.dom_start_offset)
.setNumCharacters(text_box.dom_length)
- .setBoundingBox(BuildRectForLayoutRect(
+ .setBoundingBox(BuildRectForPhysicalRect(
TextFragmentRectInDocument(layout_object, text_box)))
.build());
}
@@ -876,8 +898,8 @@ int InspectorDOMSnapshotAgent::VisitLayoutTreeNode(LayoutObject* layout_object,
}
}
- int index = static_cast<int>(layout_tree_nodes_->length());
- layout_tree_nodes_->addItem(std::move(layout_tree_node));
+ int index = static_cast<int>(layout_tree_nodes_->size());
+ layout_tree_nodes_->emplace_back(std::move(layout_tree_node));
return index;
}
@@ -890,18 +912,50 @@ int InspectorDOMSnapshotAgent::BuildLayoutTreeNode(LayoutObject* layout_object,
auto* text_box_snapshot = document_->getTextBoxes();
int layout_index =
- static_cast<int>(layout_tree_snapshot->getNodeIndex()->length());
- layout_tree_snapshot->getNodeIndex()->addItem(node_index);
- layout_tree_snapshot->getStyles()->addItem(BuildStylesForNode(node));
- layout_tree_snapshot->getBounds()->addItem(
- BuildRectForLayoutRect2(RectInDocument(layout_object)));
+ static_cast<int>(layout_tree_snapshot->getNodeIndex()->size());
+ layout_tree_snapshot->getNodeIndex()->emplace_back(node_index);
+ layout_tree_snapshot->getStyles()->emplace_back(BuildStylesForNode(node));
+ layout_tree_snapshot->getBounds()->emplace_back(
+ BuildRectForPhysicalRect2(RectInDocument(layout_object)));
+
+ if (include_snapshot_dom_rects_) {
+ protocol::Array<protocol::Array<double>>* offsetRects =
+ layout_tree_snapshot->getOffsetRects(nullptr);
+ DCHECK(offsetRects);
+
+ protocol::Array<protocol::Array<double>>* clientRects =
+ layout_tree_snapshot->getClientRects(nullptr);
+ DCHECK(clientRects);
+
+ protocol::Array<protocol::Array<double>>* scrollRects =
+ layout_tree_snapshot->getScrollRects(nullptr);
+ DCHECK(scrollRects);
+
+ if (auto* element = DynamicTo<Element>(node)) {
+ offsetRects->emplace_back(
+ BuildRectForLayout(element->OffsetLeft(), element->OffsetTop(),
+ element->OffsetWidth(), element->OffsetHeight()));
+
+ clientRects->emplace_back(
+ BuildRectForLayout(element->clientLeft(), element->clientTop(),
+ element->clientWidth(), element->clientHeight()));
+
+ scrollRects->emplace_back(
+ BuildRectForLayout(element->scrollLeft(), element->scrollTop(),
+ element->scrollWidth(), element->scrollHeight()));
+ } else {
+ offsetRects->emplace_back(std::make_unique<protocol::Array<double>>());
+ clientRects->emplace_back(std::make_unique<protocol::Array<double>>());
+ scrollRects->emplace_back(std::make_unique<protocol::Array<double>>());
+ }
+ }
if (layout_object->Style() && layout_object->Style()->IsStackingContext())
SetRare(layout_tree_snapshot->getStackingContexts(), layout_index);
String text = layout_object->IsText() ? ToLayoutText(layout_object)->GetText()
: String();
- layout_tree_snapshot->getText()->addItem(AddString(text));
+ layout_tree_snapshot->getText()->emplace_back(AddString(text));
if (!layout_object->IsText())
return layout_index;
@@ -912,11 +966,11 @@ int InspectorDOMSnapshotAgent::BuildLayoutTreeNode(LayoutObject* layout_object,
return layout_index;
for (const auto& text_box : text_boxes) {
- text_box_snapshot->getLayoutIndex()->addItem(layout_index);
- text_box_snapshot->getBounds()->addItem(BuildRectForLayoutRect2(
+ text_box_snapshot->getLayoutIndex()->emplace_back(layout_index);
+ text_box_snapshot->getBounds()->emplace_back(BuildRectForPhysicalRect2(
TextFragmentRectInDocument(layout_object, text_box)));
- text_box_snapshot->getStart()->addItem(text_box.dom_start_offset);
- text_box_snapshot->getLength()->addItem(text_box.dom_length);
+ text_box_snapshot->getStart()->emplace_back(text_box.dom_start_offset);
+ text_box_snapshot->getLength()->emplace_back(text_box.dom_length);
}
return layout_index;
@@ -945,21 +999,22 @@ int InspectorDOMSnapshotAgent::GetStyleIndexForNode(Node* node) {
// It's a distinct style, so append to |computedStyles|.
auto style_properties =
- protocol::Array<protocol::DOMSnapshot::NameValue>::create();
+ std::make_unique<protocol::Array<protocol::DOMSnapshot::NameValue>>();
for (wtf_size_t i = 0; i < style.size(); i++) {
if (style[i].IsEmpty())
continue;
- style_properties->addItem(protocol::DOMSnapshot::NameValue::create()
- .setName((*css_property_filter_)[i].first)
- .setValue(style[i])
- .build());
+ style_properties->emplace_back(
+ protocol::DOMSnapshot::NameValue::create()
+ .setName((*css_property_filter_)[i].first)
+ .setValue(style[i])
+ .build());
}
- wtf_size_t index = static_cast<wtf_size_t>(computed_styles_->length());
- computed_styles_->addItem(protocol::DOMSnapshot::ComputedStyle::create()
- .setProperties(std::move(style_properties))
- .build());
+ wtf_size_t index = static_cast<wtf_size_t>(computed_styles_->size());
+ computed_styles_->emplace_back(protocol::DOMSnapshot::ComputedStyle::create()
+ .setProperties(std::move(style_properties))
+ .build());
computed_styles_map_->insert(std::move(style), index);
return index;
}
@@ -968,10 +1023,10 @@ std::unique_ptr<protocol::Array<int>>
InspectorDOMSnapshotAgent::BuildStylesForNode(Node* node) {
auto* computed_style_info =
MakeGarbageCollected<CSSComputedStyleDeclaration>(node, true);
- std::unique_ptr<protocol::Array<int>> result = protocol::Array<int>::create();
+ auto result = std::make_unique<protocol::Array<int>>();
for (const auto& pair : *css_property_filter_) {
String value = computed_style_info->GetPropertyValue(pair.second);
- result->addItem(AddString(value));
+ result->emplace_back(AddString(value));
}
return result;
}
@@ -1003,12 +1058,9 @@ void InspectorDOMSnapshotAgent::VisitPaintLayer(PaintLayer* layer) {
DCHECK(!embedded_document || !layer->FirstChild());
if (!embedded_document) {
- if (PaintLayerStackingNode* node = layer->StackingNode()) {
- PaintLayerStackingNodeIterator iterator(*node, kAllChildren);
- while (PaintLayer* child_layer = iterator.Next()) {
- VisitPaintLayer(child_layer);
- }
- }
+ PaintLayerPaintOrderIterator iterator(*layer, kAllChildren);
+ while (PaintLayer* child_layer = iterator.Next())
+ VisitPaintLayer(child_layer);
}
}
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 9be646a8dcd..19829750e73 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
@@ -53,6 +53,7 @@ class CORE_EXPORT InspectorDOMSnapshotAgent final
computed_styles) override;
protocol::Response captureSnapshot(
std::unique_ptr<protocol::Array<String>> computed_styles,
+ protocol::Maybe<bool> include_dom_rects,
std::unique_ptr<protocol::Array<protocol::DOMSnapshot::DocumentSnapshot>>*
documents,
std::unique_ptr<protocol::Array<String>>* strings) override;
@@ -156,6 +157,7 @@ class CORE_EXPORT InspectorDOMSnapshotAgent final
// Maps a style string vector to an index in |computed_styles_|. Used to avoid
// duplicate entries in |computed_styles_|.
std::unique_ptr<ComputedStylesMap> computed_styles_map_;
+ bool include_snapshot_dom_rects_ = false;
std::unique_ptr<CSSPropertyFilter> css_property_filter_;
// Maps a PaintLayer to its paint order index.
std::unique_ptr<PaintOrderMap> paint_order_map_;
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 21b0e05cabc..9ed251954b1 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
@@ -32,7 +32,7 @@ InspectorEmulationAgent::InspectorEmulationAgent(
WebLocalFrameImpl* web_local_frame_impl)
: web_local_frame_(web_local_frame_impl),
default_background_color_override_rgba_(&agent_state_,
- /*default_value=*/WTF::String()),
+ /*default_value=*/{}),
script_execution_disabled_(&agent_state_, /*default_value=*/false),
scrollbars_hidden_(&agent_state_, /*default_value=*/false),
document_cookie_disabled_(&agent_state_, /*default_value=*/false),
@@ -60,6 +60,20 @@ WebViewImpl* InspectorEmulationAgent::GetWebViewImpl() {
return web_local_frame_ ? web_local_frame_->ViewImpl() : nullptr;
}
+namespace {
+std::unique_ptr<protocol::DOM::RGBA> ParseRGBA(
+ const std::vector<uint8_t>& cbor) {
+ auto parsed = protocol::Value::parseBinary(cbor.data(), cbor.size());
+ if (!parsed)
+ return nullptr;
+ blink::protocol::ErrorSupport errors;
+ auto rgba = protocol::DOM::RGBA::fromValue(parsed.get(), &errors);
+ if (errors.hasErrors())
+ return nullptr;
+ return rgba;
+}
+} // namespace
+
void InspectorEmulationAgent::Restore() {
setUserAgentOverride(user_agent_override_.Get(),
accept_language_override_.Get(),
@@ -77,18 +91,9 @@ void InspectorEmulationAgent::Restore() {
setTouchEmulationEnabled(touch_event_emulation_enabled_.Get(),
max_touch_points_.Get());
setEmulatedMedia(emulated_media_.Get());
- if (!default_background_color_override_rgba_.Get().IsNull()) {
- std::unique_ptr<protocol::Value> parsed = protocol::StringUtil::parseJSON(
- default_background_color_override_rgba_.Get());
- if (parsed) {
- blink::protocol::ErrorSupport errors;
- auto rgba = protocol::DOM::RGBA::fromValue(parsed.get(), &errors);
- if (!errors.hasErrors()) {
- setDefaultBackgroundColorOverride(
- Maybe<protocol::DOM::RGBA>(std::move(rgba)));
- }
- }
- }
+ auto rgba = ParseRGBA(default_background_color_override_rgba_.Get());
+ if (rgba)
+ setDefaultBackgroundColorOverride(std::move(rgba));
setFocusEmulationEnabled(emulate_focus_.Get());
if (!timezone_id_override_.Get().IsNull())
@@ -317,7 +322,7 @@ Response InspectorEmulationAgent::setVirtualTimePolicy(
*virtual_time_ticks_base_ms = 0;
} else {
*virtual_time_ticks_base_ms =
- (virtual_time_base_ticks_ - WTF::TimeTicks()).InMillisecondsF();
+ (virtual_time_base_ticks_ - base::TimeTicks()).InMillisecondsF();
}
return response;
@@ -333,8 +338,8 @@ void InspectorEmulationAgent::ApplyVirtualTimePolicy(
if (new_policy.virtual_time_budget_ms) {
TRACE_EVENT_ASYNC_BEGIN1("renderer.scheduler", "VirtualTimeBudget", this,
"budget", *new_policy.virtual_time_budget_ms);
- WTF::TimeDelta budget_amount =
- WTF::TimeDelta::FromMillisecondsD(*new_policy.virtual_time_budget_ms);
+ base::TimeDelta budget_amount =
+ base::TimeDelta::FromMillisecondsD(*new_policy.virtual_time_budget_ms);
web_local_frame_->View()->Scheduler()->GrantVirtualTimeBudget(
budget_amount,
WTF::Bind(&InspectorEmulationAgent::VirtualTimeBudgetExpired,
@@ -404,7 +409,7 @@ Response InspectorEmulationAgent::setDefaultBackgroundColorOverride(
}
blink::protocol::DOM::RGBA* rgba = color.fromJust();
- default_background_color_override_rgba_.Set(rgba->toJSON());
+ default_background_color_override_rgba_.Set(rgba->serializeToBinary());
// Clamping of values is done by Color() constructor.
int alpha = static_cast<int>(lroundf(255.0f * rgba->getA(1.0f)));
GetWebViewImpl()->SetBaseBackgroundColorOverride(
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_emulation_agent.h b/chromium/third_party/blink/renderer/core/inspector/inspector_emulation_agent.h
index 6b6991737c1..fc13e54b3c2 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_emulation_agent.h
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_emulation_agent.h
@@ -107,7 +107,7 @@ class CORE_EXPORT InspectorEmulationAgent final
void ApplyVirtualTimePolicy(const PendingVirtualTimePolicy& new_policy);
Member<WebLocalFrameImpl> web_local_frame_;
- WTF::TimeTicks virtual_time_base_ticks_;
+ base::TimeTicks virtual_time_base_ticks_;
std::unique_ptr<TimeZoneController::TimeZoneOverride> timezone_override_;
@@ -116,7 +116,7 @@ class CORE_EXPORT InspectorEmulationAgent final
base::Optional<PendingVirtualTimePolicy> pending_virtual_time_policy_;
bool enabled_ = false;
- InspectorAgentState::String default_background_color_override_rgba_;
+ InspectorAgentState::Bytes default_background_color_override_rgba_;
InspectorAgentState::Boolean script_execution_disabled_;
InspectorAgentState::Boolean scrollbars_hidden_;
InspectorAgentState::Boolean document_cookie_disabled_;
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 082edaedeec..bee7c0b4be4 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_highlight.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_highlight.cc
@@ -139,17 +139,9 @@ class ShapePathBuilder : public PathBuilder {
std::unique_ptr<protocol::Array<double>> BuildArrayForQuad(
const FloatQuad& quad) {
- std::unique_ptr<protocol::Array<double>> array =
- protocol::Array<double>::create();
- array->addItem(quad.P1().X());
- array->addItem(quad.P1().Y());
- array->addItem(quad.P2().X());
- array->addItem(quad.P2().Y());
- array->addItem(quad.P3().X());
- array->addItem(quad.P3().Y());
- array->addItem(quad.P4().X());
- array->addItem(quad.P4().Y());
- return array;
+ return std::make_unique<std::vector<double>, std::initializer_list<double>>(
+ {quad.P1().X(), quad.P1().Y(), quad.P2().X(), quad.P2().Y(),
+ quad.P3().X(), quad.P3().Y(), quad.P4().X(), quad.P4().Y()});
}
Path QuadToPath(const FloatQuad& quad) {
@@ -209,9 +201,9 @@ void AppendStyleInfo(Node* node,
const InspectorHighlightContrastInfo& node_contrast) {
std::unique_ptr<protocol::DictionaryValue> computed_style =
protocol::DictionaryValue::create();
- CSSStyleDeclaration* style =
+ CSSComputedStyleDeclaration* style =
MakeGarbageCollected<CSSComputedStyleDeclaration>(node, true);
- Vector<AtomicString> properties;
+ Vector<CSSPropertyID> properties;
// For text nodes, we can show color & font properties.
bool has_text_children = false;
@@ -220,25 +212,26 @@ void AppendStyleInfo(Node* node,
has_text_children = child->IsTextNode();
}
if (has_text_children) {
- properties.push_back("color");
- properties.push_back("font-family");
- properties.push_back("font-size");
- properties.push_back("line-height");
+ properties.push_back(CSSPropertyID::kColor);
+ properties.push_back(CSSPropertyID::kFontFamily);
+ properties.push_back(CSSPropertyID::kFontSize);
+ properties.push_back(CSSPropertyID::kLineHeight);
}
- properties.push_back("padding");
- properties.push_back("margin");
- properties.push_back("background-color");
+ properties.push_back(CSSPropertyID::kPadding);
+ properties.push_back(CSSPropertyID::kMargin);
+ properties.push_back(CSSPropertyID::kBackgroundColor);
for (size_t i = 0; i < properties.size(); ++i) {
- const CSSValue* value = style->GetPropertyCSSValueInternal(properties[i]);
+ const CSSValue* value = style->GetPropertyCSSValue(properties[i]);
if (!value)
continue;
+ AtomicString name = CSSPropertyName(properties[i]).ToAtomicString();
if (value->IsColorValue()) {
Color color = static_cast<const cssvalue::CSSColorValue*>(value)->Value();
- computed_style->setString(properties[i], ToHEXA(color));
+ computed_style->setString(name, ToHEXA(color));
} else {
- computed_style->setString(properties[i], value->CssText());
+ computed_style->setString(name, value->CssText());
}
}
element_info->setValue("style", std::move(computed_style));
@@ -400,38 +393,32 @@ void CollectQuads(Node* node, Vector<FloatQuad>& out_quads) {
}
}
-std::unique_ptr<protocol::Array<double>> RectForLayoutRect(
- const LayoutRect& rect) {
- std::unique_ptr<protocol::Array<double>> result =
- protocol::Array<double>::create();
-
- result->addItem(rect.X());
- result->addItem(rect.Y());
- result->addItem(rect.Width());
- result->addItem(rect.Height());
- return result;
+std::unique_ptr<protocol::Array<double>> RectForPhysicalRect(
+ const PhysicalRect& rect) {
+ return std::make_unique<std::vector<double>, std::initializer_list<double>>(
+ {rect.X(), rect.Y(), rect.Width(), rect.Height()});
}
// Returns |layout_object|'s bounding box in document coordinates.
-LayoutRect RectInRootFrame(const LayoutObject* layout_object) {
+PhysicalRect RectInRootFrame(const LayoutObject* layout_object) {
LocalFrameView* local_frame_view = layout_object->GetFrameView();
- LayoutRect rect_in_absolute(layout_object->AbsoluteBoundingBoxFloatRect());
+ PhysicalRect rect_in_absolute = PhysicalRect::EnclosingRect(
+ layout_object->AbsoluteBoundingBoxFloatRect());
return local_frame_view
? local_frame_view->ConvertToRootFrame(rect_in_absolute)
: rect_in_absolute;
}
-LayoutRect TextFragmentRectInRootFrame(
+PhysicalRect TextFragmentRectInRootFrame(
const LayoutObject* layout_object,
const LayoutText::TextBoxInfo& text_box) {
PhysicalRect absolute_coords_text_box_rect =
layout_object->LocalToAbsoluteRect(
layout_object->FlipForWritingMode(text_box.local_rect));
LocalFrameView* local_frame_view = layout_object->GetFrameView();
- return (local_frame_view ? local_frame_view->ConvertToRootFrame(
- absolute_coords_text_box_rect)
- : absolute_coords_text_box_rect)
- .ToLayoutRect();
+ return local_frame_view ? local_frame_view->ConvertToRootFrame(
+ absolute_coords_text_box_rect)
+ : absolute_coords_text_box_rect;
}
} // namespace
@@ -466,8 +453,9 @@ InspectorHighlight::InspectorHighlight(
AppendPathsForShapeOutside(node, highlight_config);
AppendNodeHighlight(node, highlight_config);
auto* text_node = DynamicTo<Text>(node);
- if (append_element_info && node->IsElementNode())
- element_info_ = BuildElementInfo(ToElement(node));
+ auto* element = DynamicTo<Element>(node);
+ if (append_element_info && element)
+ element_info_ = BuildElementInfo(element);
else if (append_element_info && text_node)
element_info_ = BuildTextNodeInfo(text_node);
if (element_info_ && highlight_config.show_styles)
@@ -484,7 +472,7 @@ InspectorHighlight::~InspectorHighlight() = default;
void InspectorHighlight::AppendDistanceInfo(Node* node) {
if (!InspectorHighlight::GetBoxModel(node, &model_, false))
return;
- boxes_ = protocol::Array<protocol::Array<double>>::create();
+ boxes_ = std::make_unique<protocol::Array<protocol::Array<double>>>();
computed_style_ = protocol::DictionaryValue::create();
node->GetDocument().EnsurePaintLocationDataValidForNode(node);
@@ -492,11 +480,11 @@ void InspectorHighlight::AppendDistanceInfo(Node* node) {
if (!layout_object)
return;
- CSSStyleDeclaration* style =
+ CSSComputedStyleDeclaration* style =
MakeGarbageCollected<CSSComputedStyleDeclaration>(node, true);
for (size_t i = 0; i < style->length(); ++i) {
AtomicString name(style->item(i));
- const CSSValue* value = style->GetPropertyCSSValueInternal(name);
+ const CSSValue* value = style->GetPropertyCSSValue(cssPropertyID(name));
if (!value)
continue;
if (value->IsColorValue()) {
@@ -511,10 +499,11 @@ void InspectorHighlight::AppendDistanceInfo(Node* node) {
}
VisitAndCollectDistanceInfo(&(node->GetDocument()));
- LayoutRect document_rect(node->GetDocument().GetLayoutView()->DocumentRect());
+ PhysicalRect document_rect(
+ node->GetDocument().GetLayoutView()->DocumentRect());
LocalFrameView* local_frame_view = node->GetDocument().View();
- boxes_->addItem(
- RectForLayoutRect(local_frame_view->ConvertToRootFrame(document_rect)));
+ boxes_->emplace_back(
+ RectForPhysicalRect(local_frame_view->ConvertToRootFrame(document_rect)));
}
void InspectorHighlight::VisitAndCollectDistanceInfo(Node* node) {
@@ -522,9 +511,7 @@ void InspectorHighlight::VisitAndCollectDistanceInfo(Node* node) {
if (layout_object)
AddLayoutBoxToDistanceInfo(layout_object);
- if (node->IsElementNode()) {
- Element* element = ToElement(node);
-
+ if (auto* element = DynamicTo<Element>(node)) {
if (element->GetPseudoId()) {
if (layout_object)
VisitAndCollectDistanceInfo(element->GetPseudoId(), layout_object);
@@ -563,13 +550,13 @@ void InspectorHighlight::AddLayoutBoxToDistanceInfo(
if (layout_object->IsText()) {
LayoutText* layout_text = ToLayoutText(layout_object);
for (const auto& text_box : layout_text->GetTextBoxInfo()) {
- LayoutRect text_rect(
+ PhysicalRect text_rect(
TextFragmentRectInRootFrame(layout_object, text_box));
- boxes_->addItem(RectForLayoutRect(text_rect));
+ boxes_->emplace_back(RectForPhysicalRect(text_rect));
}
} else {
- LayoutRect rect(RectInRootFrame(layout_object));
- boxes_->addItem(RectForLayoutRect(rect));
+ PhysicalRect rect(RectInRootFrame(layout_object));
+ boxes_->emplace_back(RectForPhysicalRect(rect));
}
}
@@ -688,10 +675,19 @@ std::unique_ptr<protocol::DictionaryValue> InspectorHighlight::AsProtocolValue()
if (model_) {
std::unique_ptr<protocol::DictionaryValue> distance_info =
protocol::DictionaryValue::create();
- distance_info->setArray("boxes", boxes_->toValue());
- distance_info->setArray("content", model_->getContent()->toValue());
- distance_info->setArray("padding", model_->getPadding()->toValue());
- distance_info->setArray("border", model_->getBorder()->toValue());
+ distance_info->setArray(
+ "boxes",
+ protocol::ValueConversions<std::vector<
+ std::unique_ptr<std::vector<double>>>>::toValue(boxes_.get()));
+ distance_info->setArray(
+ "content", protocol::ValueConversions<std::vector<double>>::toValue(
+ model_->getContent()));
+ distance_info->setArray(
+ "padding", protocol::ValueConversions<std::vector<double>>::toValue(
+ model_->getPadding()));
+ distance_info->setArray(
+ "border", protocol::ValueConversions<std::vector<double>>::toValue(
+ model_->getBorder()));
distance_info->setValue("style", computed_style_->clone());
object->setValue("distanceInfo", std::move(distance_info));
}
@@ -768,21 +764,19 @@ bool InspectorHighlight::GetBoxModel(
protocol::ErrorSupport errors;
if (const ShapeOutsideInfo* shape_outside_info =
ShapeOutsideInfoForNode(node, &paths, &bounds_quad)) {
+ auto shape = ShapePathBuilder::BuildPath(
+ *view, *layout_object, *shape_outside_info, paths.shape, 1.f);
+ auto margin_shape = ShapePathBuilder::BuildPath(
+ *view, *layout_object, *shape_outside_info, paths.margin_shape, 1.f);
(*model)->setShapeOutside(
protocol::DOM::ShapeOutsideInfo::create()
.setBounds(BuildArrayForQuad(bounds_quad))
- .setShape(protocol::Array<protocol::Value>::fromValue(
- ShapePathBuilder::BuildPath(*view, *layout_object,
- *shape_outside_info, paths.shape,
- 1.f)
- .get(),
- &errors))
- .setMarginShape(protocol::Array<protocol::Value>::fromValue(
- ShapePathBuilder::BuildPath(*view, *layout_object,
- *shape_outside_info,
- paths.margin_shape, 1.f)
- .get(),
- &errors))
+ .setShape(protocol::ValueConversions<
+ protocol::Array<protocol::Value>>::fromValue(shape.get(),
+ &errors))
+ .setMarginShape(
+ protocol::ValueConversions<protocol::Array<protocol::Value>>::
+ fromValue(margin_shape.get(), &errors))
.build());
}
@@ -819,7 +813,7 @@ bool InspectorHighlight::GetContentQuads(
result->reset(new protocol::Array<protocol::Array<double>>());
for (FloatQuad& quad : quads)
- (*result)->addItem(BuildArrayForQuad(quad));
+ (*result)->emplace_back(BuildArrayForQuad(quad));
return true;
}
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 82eab793232..f66a0f38e62 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
@@ -56,6 +56,7 @@
#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"
@@ -96,31 +97,31 @@ static std::unique_ptr<protocol::LayerTree::ScrollRect> BuildScrollRect(
static std::unique_ptr<Array<protocol::LayerTree::ScrollRect>>
BuildScrollRectsForLayer(const cc::Layer* layer, bool report_wheel_scrollers) {
- std::unique_ptr<Array<protocol::LayerTree::ScrollRect>> scroll_rects =
- Array<protocol::LayerTree::ScrollRect>::create();
+ auto scroll_rects =
+ std::make_unique<protocol::Array<protocol::LayerTree::ScrollRect>>();
const cc::Region& non_fast_scrollable_rects =
layer->non_fast_scrollable_region();
for (const gfx::Rect& rect : non_fast_scrollable_rects) {
- scroll_rects->addItem(BuildScrollRect(
+ scroll_rects->emplace_back(BuildScrollRect(
IntRect(rect),
protocol::LayerTree::ScrollRect::TypeEnum::RepaintsOnScroll));
}
- const cc::Region& touch_event_handler_region =
- layer->touch_action_region().region();
+ const cc::Region& touch_event_handler_regions =
+ layer->touch_action_region().GetAllRegions();
- for (const gfx::Rect& rect : touch_event_handler_region) {
- scroll_rects->addItem(BuildScrollRect(
+ for (const gfx::Rect& rect : touch_event_handler_regions) {
+ scroll_rects->emplace_back(BuildScrollRect(
IntRect(rect),
protocol::LayerTree::ScrollRect::TypeEnum::TouchEventHandler));
}
if (report_wheel_scrollers) {
- scroll_rects->addItem(BuildScrollRect(
+ scroll_rects->emplace_back(BuildScrollRect(
// TODO(yutak): This truncates the floating point position to integers.
gfx::Rect(layer->position().x(), layer->position().y(),
layer->bounds().width(), layer->bounds().height()),
protocol::LayerTree::ScrollRect::TypeEnum::WheelEventHandler));
}
- return scroll_rects->length() ? std::move(scroll_rects) : nullptr;
+ return scroll_rects->empty() ? nullptr : std::move(scroll_rects);
}
// TODO(flackr): We should be getting the sticky position constraints from the
@@ -215,10 +216,10 @@ static std::unique_ptr<protocol::LayerTree::Layer> BuildObjectForLayer(
}
if (!transform.IsIdentity()) {
- auto transform_array = Array<double>::create();
+ auto transform_array = std::make_unique<protocol::Array<double>>();
for (int col = 0; col < 4; ++col) {
for (int row = 0; row < 4; ++row)
- transform_array->addItem(transform.matrix().get(row, col));
+ transform_array->emplace_back(transform.matrix().get(row, col));
}
layer_object->setTransform(std::move(transform_array));
// FIXME: rename these to setTransformOrigin*
@@ -336,8 +337,7 @@ InspectorLayerTreeAgent::BuildLayerTree() {
if (!root_layer)
return nullptr;
- std::unique_ptr<Array<protocol::LayerTree::Layer>> layers =
- Array<protocol::LayerTree::Layer>::create();
+ auto layers = std::make_unique<protocol::Array<protocol::LayerTree::Layer>>();
auto* root_frame = inspected_frames_->Root();
auto* layer_for_scrolling =
root_frame->View()->LayoutViewport()->LayerForScrolling();
@@ -361,7 +361,7 @@ void InspectorLayerTreeAgent::GatherLayers(
if (client_->IsInspectorLayer(layer))
return;
int layer_id = layer->id();
- layers->addItem(BuildObjectForLayer(
+ layers->emplace_back(BuildObjectForLayer(
RootLayer(), layer,
has_wheel_event_handlers && layer_id == scrolling_layer_id));
for (auto child : layer->children()) {
@@ -405,21 +405,14 @@ Response InspectorLayerTreeAgent::compositingReasons(
if (!response.isSuccess())
return response;
CompositingReasons reasons = layer->compositing_reasons();
- *reason_strings = Array<String>::create();
+ *reason_strings = std::make_unique<protocol::Array<String>>();
for (const char* name : CompositingReason::ShortNames(reasons))
- (*reason_strings)->addItem(name);
+ (*reason_strings)->emplace_back(name);
return Response::OK();
}
Response InspectorLayerTreeAgent::makeSnapshot(const String& layer_id,
String* snapshot_id) {
- const cc::Layer* layer = nullptr;
- Response response = LayerById(layer_id, layer);
- if (!response.isSuccess())
- return response;
- if (!layer->DrawsContent())
- return Response::Error("Layer does not draw content");
-
suppress_layer_paint_events_ = true;
// If we hit a devtool break point in the middle of document lifecycle, for
@@ -436,6 +429,13 @@ Response InspectorLayerTreeAgent::makeSnapshot(const String& layer_id,
suppress_layer_paint_events_ = false;
+ const cc::Layer* layer = nullptr;
+ Response response = LayerById(layer_id, layer);
+ if (!response.isSuccess())
+ return response;
+ if (!layer->DrawsContent())
+ return Response::Error("Layer does not draw content");
+
auto picture = layer->GetPicture();
if (!picture)
return Response::Error("Layer does not produce picture");
@@ -450,15 +450,15 @@ Response InspectorLayerTreeAgent::makeSnapshot(const String& layer_id,
Response InspectorLayerTreeAgent::loadSnapshot(
std::unique_ptr<Array<protocol::LayerTree::PictureTile>> tiles,
String* snapshot_id) {
- if (!tiles->length())
+ if (tiles->empty())
return Response::Error("Invalid argument, no tiles provided");
- if (tiles->length() > UINT_MAX)
+ if (tiles->size() > UINT_MAX)
return Response::Error("Invalid argument, too many tiles provided");
- wtf_size_t tiles_length = static_cast<wtf_size_t>(tiles->length());
+ wtf_size_t tiles_length = static_cast<wtf_size_t>(tiles->size());
Vector<scoped_refptr<PictureSnapshot::TilePictureStream>> decoded_tiles;
decoded_tiles.Grow(tiles_length);
for (wtf_size_t i = 0; i < tiles_length; ++i) {
- protocol::LayerTree::PictureTile* tile = tiles->get(i);
+ protocol::LayerTree::PictureTile* tile = (*tiles)[i].get();
decoded_tiles[i] = base::AdoptRef(new PictureSnapshot::TilePictureStream());
decoded_tiles[i]->layer_offset.Set(tile->getX(), tile->getY());
const protocol::Binary& data = tile->getPicture();
@@ -505,16 +505,11 @@ Response InspectorLayerTreeAgent::replaySnapshot(const String& snapshot_id,
Response response = GetSnapshotById(snapshot_id, snapshot);
if (!response.isSuccess())
return response;
- Vector<char> base64_data = snapshot->Replay(
- from_step.fromMaybe(0), to_step.fromMaybe(0), scale.fromMaybe(1.0));
- if (base64_data.IsEmpty())
+ auto png_data = snapshot->Replay(from_step.fromMaybe(0), to_step.fromMaybe(0),
+ scale.fromMaybe(1.0));
+ if (png_data.IsEmpty())
return Response::Error("Image encoding failed");
- static constexpr char kUrlPrefix[] = "data:image/png;base64,";
- StringBuilder url;
- url.ReserveCapacity(sizeof(kUrlPrefix) + base64_data.size());
- url.Append(kUrlPrefix);
- url.Append(base64_data.begin(), base64_data.size());
- *data_url = url.ToString();
+ *data_url = "data:image/png;base64," + Base64Encode(png_data);
return Response::OK();
}
@@ -536,16 +531,16 @@ Response InspectorLayerTreeAgent::profileSnapshot(
FloatRect rect;
if (clip_rect.isJust())
ParseRect(clip_rect.fromJust(), &rect);
- auto timings =
- snapshot->Profile(min_repeat_count.fromMaybe(1),
- TimeDelta::FromSecondsD(min_duration.fromMaybe(0)),
- clip_rect.isJust() ? &rect : nullptr);
- *out_timings = Array<Array<double>>::create();
+ auto timings = snapshot->Profile(
+ min_repeat_count.fromMaybe(1),
+ base::TimeDelta::FromSecondsD(min_duration.fromMaybe(0)),
+ clip_rect.isJust() ? &rect : nullptr);
+ *out_timings = std::make_unique<Array<Array<double>>>();
for (const auto& row : timings) {
- std::unique_ptr<Array<double>> out_row = Array<double>::create();
- for (TimeDelta delta : row)
- out_row->addItem(delta.InSecondsF());
- (*out_timings)->addItem(std::move(out_row));
+ auto out_row = std::make_unique<protocol::Array<double>>();
+ for (base::TimeDelta delta : row)
+ out_row->emplace_back(delta.InSecondsF());
+ (*out_timings)->emplace_back(std::move(out_row));
}
return Response::OK();
}
@@ -560,8 +555,9 @@ Response InspectorLayerTreeAgent::snapshotCommandLog(
protocol::ErrorSupport errors;
std::unique_ptr<protocol::Value> log_value = protocol::StringUtil::parseJSON(
snapshot->SnapshotCommandLog()->ToJSONString());
- *command_log =
- Array<protocol::DictionaryValue>::fromValue(log_value.get(), &errors);
+ *command_log = protocol::ValueConversions<
+ protocol::Array<protocol::DictionaryValue>>::fromValue(log_value.get(),
+ &errors);
if (errors.hasErrors())
return Response::Error(errors.errors());
return Response::OK();
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_log_agent.cc b/chromium/third_party/blink/renderer/core/inspector/inspector_log_agent.cc
index 0c7617844f1..704802d5cd0 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_log_agent.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_log_agent.cc
@@ -95,12 +95,12 @@ void InspectorLogAgent::Restore() {
InnerEnable();
if (violation_thresholds_.IsEmpty())
return;
- auto settings = protocol::Array<ViolationSetting>::create();
+ auto settings = std::make_unique<protocol::Array<ViolationSetting>>();
for (const WTF::String& key : violation_thresholds_.Keys()) {
- settings->addItem(ViolationSetting::create()
- .setName(key)
- .setThreshold(violation_thresholds_.Get(key))
- .build());
+ settings->emplace_back(ViolationSetting::create()
+ .setName(key)
+ .setThreshold(violation_thresholds_.Get(key))
+ .build());
}
startViolationsReport(std::move(settings));
}
@@ -133,10 +133,8 @@ void InspectorLogAgent::ConsoleMessageAdded(ConsoleMessage* message) {
if (v8_session_ && message->Frame() && !message->Nodes().IsEmpty()) {
ScriptForbiddenScope::AllowUserAgentScript allow_script;
- std::unique_ptr<
- protocol::Array<v8_inspector::protocol::Runtime::API::RemoteObject>>
- remote_objects = protocol::Array<
- v8_inspector::protocol::Runtime::API::RemoteObject>::create();
+ auto remote_objects = std::make_unique<
+ protocol::Array<v8_inspector::protocol::Runtime::API::RemoteObject>>();
for (DOMNodeId node_id : message->Nodes()) {
std::unique_ptr<v8_inspector::protocol::Runtime::API::RemoteObject>
remote_object = nullptr;
@@ -150,7 +148,7 @@ void InspectorLogAgent::ConsoleMessageAdded(ConsoleMessage* message) {
NullRemoteObject(v8_session_, message->Frame(), "console");
}
if (remote_object) {
- remote_objects->addItem(std::move(remote_object));
+ remote_objects->emplace_back(std::move(remote_object));
} else {
// If a null object could not be referenced, we do not send the message
// at all, to avoid situations in which the arguments are misleading.
@@ -230,9 +228,9 @@ Response InspectorLogAgent::startViolationsReport(
return Response::Error("Violations are not supported for this target");
performance_monitor_->UnsubscribeAll(this);
violation_thresholds_.Clear();
- for (size_t i = 0; i < settings->length(); ++i) {
- const WTF::String& name = settings->get(i)->getName();
- double threshold = settings->get(i)->getThreshold();
+ for (const std::unique_ptr<ViolationSetting>& setting : *settings) {
+ const WTF::String& name = setting->getName();
+ double threshold = setting->getThreshold();
PerformanceMonitor::Violation violation = ParseViolation(name);
if (violation == PerformanceMonitor::kAfterLast)
continue;
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_memory_agent.cc b/chromium/third_party/blink/renderer/core/inspector/inspector_memory_agent.cc
index 45fb50f1f1e..23adb49e4e4 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_memory_agent.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_memory_agent.cc
@@ -40,7 +40,7 @@
#include "third_party/blink/renderer/core/inspector/inspected_frames.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/platform/bindings/v8_per_isolate_data.h"
-#include "third_party/blink/renderer/platform/instance_counters.h"
+#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h"
namespace blink {
@@ -129,27 +129,24 @@ Response InspectorMemoryAgent::getSamplingProfile(
std::unique_ptr<protocol::Memory::SamplingProfile>
InspectorMemoryAgent::GetSamplingProfileById(uint32_t id) {
base::ModuleCache module_cache;
- std::unique_ptr<protocol::Array<protocol::Memory::SamplingProfileNode>>
- samples =
- protocol::Array<protocol::Memory::SamplingProfileNode>::create();
- std::vector<base::SamplingHeapProfiler::Sample> raw_samples =
- base::SamplingHeapProfiler::Get()->GetSamples(id);
+ auto samples = std::make_unique<
+ protocol::Array<protocol::Memory::SamplingProfileNode>>();
+ auto raw_samples = base::SamplingHeapProfiler::Get()->GetSamples(id);
for (auto& it : raw_samples) {
- std::unique_ptr<protocol::Array<protocol::String>> stack =
- protocol::Array<protocol::String>::create();
for (const void* frame : it.stack) {
uintptr_t address = reinterpret_cast<uintptr_t>(frame);
module_cache.GetModuleForAddress(address); // Populates module_cache.
}
- std::vector<std::string> source_stack = Symbolize(it.stack);
- for (auto& it2 : source_stack)
- stack->addItem(it2.c_str());
- samples->addItem(protocol::Memory::SamplingProfileNode::create()
- .setSize(it.size)
- .setTotal(it.total)
- .setStack(std::move(stack))
- .build());
+ Vector<String> source_stack = Symbolize(it.stack);
+ auto stack = std::make_unique<protocol::Array<protocol::String>>();
+ for (const auto& frame : source_stack)
+ stack->emplace_back(frame);
+ samples->emplace_back(protocol::Memory::SamplingProfileNode::create()
+ .setSize(it.size)
+ .setTotal(it.total)
+ .setStack(std::move(stack))
+ .build());
}
// Mix in v8 main isolate heap size as a synthetic node.
@@ -158,26 +155,25 @@ InspectorMemoryAgent::GetSamplingProfileById(uint32_t id) {
v8::HeapStatistics heap_stats;
v8::Isolate::GetCurrent()->GetHeapStatistics(&heap_stats);
size_t total_bytes = heap_stats.total_heap_size();
- std::unique_ptr<protocol::Array<protocol::String>> stack =
- protocol::Array<protocol::String>::create();
- stack->addItem("<V8 Heap>");
- samples->addItem(protocol::Memory::SamplingProfileNode::create()
- .setSize(total_bytes)
- .setTotal(total_bytes)
- .setStack(std::move(stack))
- .build());
+ auto stack = std::make_unique<protocol::Array<protocol::String>>();
+ stack->emplace_back("<V8 Heap>");
+ samples->emplace_back(protocol::Memory::SamplingProfileNode::create()
+ .setSize(total_bytes)
+ .setTotal(total_bytes)
+ .setStack(std::move(stack))
+ .build());
}
- std::unique_ptr<protocol::Array<protocol::Memory::Module>> modules =
- protocol::Array<protocol::Memory::Module>::create();
+ auto modules = std::make_unique<protocol::Array<protocol::Memory::Module>>();
for (const auto* module : module_cache.GetModules()) {
- modules->addItem(protocol::Memory::Module::create()
- .setName(module->GetDebugBasename().value().c_str())
- .setUuid(module->GetId().c_str())
- .setBaseAddress(String::Format(
- "0x%" PRIxPTR, module->GetBaseAddress()))
- .setSize(static_cast<double>(module->GetSize()))
- .build());
+ modules->emplace_back(
+ protocol::Memory::Module::create()
+ .setName(module->GetDebugBasename().value().c_str())
+ .setUuid(module->GetId().c_str())
+ .setBaseAddress(
+ String::Format("0x%" PRIxPTR, module->GetBaseAddress()))
+ .setSize(static_cast<double>(module->GetSize()))
+ .build());
}
return protocol::Memory::SamplingProfile::create()
@@ -186,42 +182,48 @@ InspectorMemoryAgent::GetSamplingProfileById(uint32_t id) {
.build();
}
-std::vector<std::string> InspectorMemoryAgent::Symbolize(
- const std::vector<void*>& addresses) {
+Vector<String> InspectorMemoryAgent::Symbolize(
+ const WebVector<void*>& addresses) {
#if defined(OS_LINUX)
// TODO(alph): Move symbolization to the client.
- std::vector<void*> addresses_to_symbolize;
- for (void* address : addresses) {
+ Vector<void*> addresses_to_symbolize;
+ for (size_t i = 0; i < addresses.size(); i++) {
+ void* address = addresses[i];
if (!symbols_cache_.Contains(address))
addresses_to_symbolize.push_back(address);
}
- std::string text = base::debug::StackTrace(addresses_to_symbolize.data(),
- addresses_to_symbolize.size())
- .ToString();
+ String text(base::debug::StackTrace(addresses_to_symbolize.data(),
+ addresses_to_symbolize.size())
+ .ToString()
+ .c_str());
// Populate cache with new entries.
size_t next_pos;
for (size_t pos = 0, i = 0;; pos = next_pos + 1, ++i) {
next_pos = text.find('\n', pos);
- if (next_pos == std::string::npos)
+ if (next_pos == kNotFound)
break;
- std::string line = text.substr(pos, next_pos - pos);
- size_t space_pos = line.rfind(' ');
- std::string name =
- line.substr(space_pos == std::string::npos ? 0 : space_pos + 1);
+ String line = text.Substring(pos, next_pos - pos);
+ size_t space_pos = line.ReverseFind(' ');
+ String name = line.Substring(space_pos == kNotFound ? 0 : space_pos + 1);
symbols_cache_.insert(addresses_to_symbolize[i], name);
}
#endif
- std::vector<std::string> result;
+ Vector<String> result;
for (void* address : addresses) {
char buffer[20];
std::snprintf(buffer, sizeof(buffer), "0x%" PRIxPTR,
reinterpret_cast<uintptr_t>(address));
- if (symbols_cache_.Contains(address))
- result.push_back(std::string(buffer) + " " + symbols_cache_.at(address));
- else
+ if (symbols_cache_.Contains(address)) {
+ StringBuilder builder;
+ builder.Append(buffer);
+ builder.Append(" ");
+ builder.Append(symbols_cache_.at(address));
+ result.push_back(builder.ToString());
+ } else {
result.push_back(buffer);
+ }
}
return result;
}
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 7431c4f6137..264b9ca18fc 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
@@ -70,13 +70,13 @@ class CORE_EXPORT InspectorMemoryAgent final
std::unique_ptr<protocol::Memory::SamplingProfile>*) override;
private:
- std::vector<std::string> Symbolize(const std::vector<void*>& addresses);
+ Vector<String> Symbolize(const WebVector<void*>& addresses);
std::unique_ptr<protocol::Memory::SamplingProfile> GetSamplingProfileById(
uint32_t id);
Member<InspectedFrames> frames_;
uint32_t profile_id_ = 0;
- HashMap<void*, std::string> symbols_cache_;
+ HashMap<void*, String> symbols_cache_;
InspectorAgentState::Integer sampling_profile_interval_;
DISALLOW_COPY_AND_ASSIGN(InspectorMemoryAgent);
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 710ab7aa673..728866b5669 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
@@ -37,9 +37,9 @@
#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/referrer_policy.mojom-blink.h"
#include "services/network/public/mojom/websocket.mojom-blink.h"
-#include "third_party/blink/public/mojom/loader/request_context_frame_type.mojom-shared.h"
+#include "third_party/blink/public/mojom/loader/request_context_frame_type.mojom-blink.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/public/platform/web_effective_connection_type.h"
#include "third_party/blink/public/platform/web_mixed_content_context_type.h"
@@ -426,9 +426,11 @@ std::unique_ptr<protocol::Network::WebSocketFrame> WebSocketMessageToProtocol(
.setOpcode(op_code)
.setMask(masked)
// Only interpret the payload as UTF-8 when it's a text message
- .setPayloadData(op_code == 1 ? String::FromUTF8WithLatin1Fallback(
- payload, payload_length)
- : Base64Encode(payload, payload_length))
+ .setPayloadData(
+ op_code == 1
+ ? String::FromUTF8WithLatin1Fallback(payload, payload_length)
+ : Base64Encode(
+ base::as_bytes(base::make_span(payload, payload_length))))
.build();
}
@@ -537,16 +539,16 @@ BuildObjectForResourceResponse(const ResourceResponse& response,
String security_state = protocol::Security::SecurityStateEnum::Unknown;
switch (response.GetSecurityStyle()) {
- case ResourceResponse::kSecurityStyleUnknown:
+ case kWebSecurityStyleUnknown:
security_state = protocol::Security::SecurityStateEnum::Unknown;
break;
- case ResourceResponse::kSecurityStyleUnauthenticated:
+ case kWebSecurityStyleNeutral:
security_state = protocol::Security::SecurityStateEnum::Neutral;
break;
- case ResourceResponse::kSecurityStyleAuthenticationBroken:
+ case kWebSecurityStyleInsecure:
security_state = protocol::Security::SecurityStateEnum::Insecure;
break;
- case ResourceResponse::kSecurityStyleAuthenticated:
+ case kWebSecurityStyleSecure:
security_state = protocol::Security::SecurityStateEnum::Secure;
break;
}
@@ -621,21 +623,15 @@ BuildObjectForResourceResponse(const ResourceResponse& response,
}
response_object->setProtocol(protocol);
- if (response.GetSecurityStyle() != ResourceResponse::kSecurityStyleUnknown &&
- response.GetSecurityStyle() !=
- ResourceResponse::kSecurityStyleUnauthenticated) {
- const ResourceResponse::SecurityDetails* response_security_details =
- response.GetSecurityDetails();
+ const base::Optional<ResourceResponse::SecurityDetails>&
+ response_security_details = response.GetSecurityDetails();
+ if (response_security_details.has_value()) {
+ auto san_list = std::make_unique<protocol::Array<String>>(
+ response_security_details->san_list.begin(),
+ response_security_details->san_list.end());
- std::unique_ptr<protocol::Array<String>> san_list =
- protocol::Array<String>::create();
- for (auto const& san : response_security_details->san_list)
- san_list->addItem(san);
-
- std::unique_ptr<
- protocol::Array<protocol::Network::SignedCertificateTimestamp>>
- signed_certificate_timestamp_list = protocol::Array<
- protocol::Network::SignedCertificateTimestamp>::create();
+ auto signed_certificate_timestamp_list = std::make_unique<
+ protocol::Array<protocol::Network::SignedCertificateTimestamp>>();
for (auto const& sct : response_security_details->sct_list) {
std::unique_ptr<protocol::Network::SignedCertificateTimestamp>
signed_certificate_timestamp =
@@ -649,7 +645,7 @@ BuildObjectForResourceResponse(const ResourceResponse& response,
.setSignatureAlgorithm(sct.signature_algorithm_)
.setSignatureData(sct.signature_data_)
.build();
- signed_certificate_timestamp_list->addItem(
+ signed_certificate_timestamp_list->emplace_back(
std::move(signed_certificate_timestamp));
}
@@ -727,7 +723,7 @@ void InspectorNetworkAgent::DidBlockRequest(
String request_id = IdentifiersFactory::RequestId(loader, identifier);
String protocol_reason = BuildBlockedReason(reason);
GetFrontend()->loadingFailed(
- request_id, CurrentTimeTicksInSeconds(),
+ request_id, base::TimeTicks::Now().since_origin().InSecondsF(),
InspectorPageAgent::ResourceTypeJson(
resources_data_->GetResourceType(request_id)),
String(), false, protocol_reason);
@@ -738,9 +734,9 @@ void InspectorNetworkAgent::DidChangeResourcePriority(
uint64_t identifier,
ResourceLoadPriority load_priority) {
String request_id = IdentifiersFactory::RequestId(loader, identifier);
- GetFrontend()->resourceChangedPriority(request_id,
- ResourcePriorityJSON(load_priority),
- CurrentTimeTicksInSeconds());
+ GetFrontend()->resourceChangedPriority(
+ request_id, ResourcePriorityJSON(load_priority),
+ base::TimeTicks::Now().since_origin().InSecondsF());
}
void InspectorNetworkAgent::WillSendRequestInternal(
@@ -780,7 +776,7 @@ void InspectorNetworkAgent::WillSendRequestInternal(
BuildInitiatorObject(loader && loader->GetFrame()
? loader->GetFrame()->GetDocument()
: nullptr,
- initiator_info);
+ initiator_info, std::numeric_limits<int>::max());
std::unique_ptr<protocol::Network::Request> request_info(
BuildObjectForResourceRequest(request, max_post_data_size_.Get()));
@@ -808,7 +804,8 @@ void InspectorNetworkAgent::WillSendRequestInternal(
maybe_frame_id = frame_id;
GetFrontend()->requestWillBeSent(
request_id, loader_id, documentURL, std::move(request_info),
- CurrentTimeTicksInSeconds(), CurrentTime(), std::move(initiator_object),
+ base::TimeTicks::Now().since_origin().InSecondsF(),
+ base::Time::Now().ToDoubleT(), std::move(initiator_object),
BuildObjectForResourceResponse(redirect_response), resource_type,
std::move(maybe_frame_id), request.HasUserGesture());
if (is_handling_sync_xhr_)
@@ -864,7 +861,8 @@ void InspectorNetworkAgent::PrepareRequest(
// inside state_'s kExtraRequestHeaders, somewhere else.
if (header_name.LowerASCII() == http_names::kReferer.LowerASCII()) {
request.SetHttpReferrer(
- Referrer(value, network::mojom::ReferrerPolicy::kAlways));
+ Referrer(value, network::mojom::ReferrerPolicy::kAlways),
+ ResourceRequest::SetHttpReferrerLocation::kInspectorNetworkAgent);
} else {
request.SetHttpHeaderField(header_name, AtomicString(value));
}
@@ -960,11 +958,9 @@ void InspectorNetworkAgent::DidReceiveResourceResponse(
resources_data_->ResponseReceived(request_id, frame_id, response);
resources_data_->SetResourceType(request_id, type);
- if (response.GetSecurityStyle() != ResourceResponse::kSecurityStyleUnknown &&
- response.GetSecurityStyle() !=
- ResourceResponse::kSecurityStyleUnauthenticated) {
- const ResourceResponse::SecurityDetails* response_security_details =
- response.GetSecurityDetails();
+ const base::Optional<ResourceResponse::SecurityDetails>&
+ response_security_details = response.GetSecurityDetails();
+ if (response_security_details.has_value()) {
resources_data_->SetCertificate(request_id,
response_security_details->certificate);
}
@@ -976,7 +972,8 @@ void InspectorNetworkAgent::DidReceiveResourceResponse(
if (!frame_id.IsEmpty())
maybe_frame_id = frame_id;
GetFrontend()->responseReceived(
- request_id, loader_id, CurrentTimeTicksInSeconds(),
+ request_id, loader_id,
+ base::TimeTicks::Now().since_origin().InSecondsF(),
InspectorPageAgent::ResourceTypeJson(type),
std::move(resource_response), std::move(maybe_frame_id));
}
@@ -1011,7 +1008,8 @@ void InspectorNetworkAgent::DidReceiveData(uint64_t identifier,
}
GetFrontend()->dataReceived(
- request_id, CurrentTimeTicksInSeconds(), static_cast<int>(data_length),
+ request_id, base::TimeTicks::Now().since_origin().InSecondsF(),
+ static_cast<int>(data_length),
static_cast<int>(
resources_data_->GetAndClearPendingEncodedDataLength(request_id)));
}
@@ -1031,12 +1029,13 @@ void InspectorNetworkAgent::DidReceiveEncodedDataLength(
resources_data_->AddPendingEncodedDataLength(request_id, encoded_data_length);
}
-void InspectorNetworkAgent::DidFinishLoading(uint64_t identifier,
- DocumentLoader* loader,
- TimeTicks monotonic_finish_time,
- int64_t encoded_data_length,
- int64_t decoded_body_length,
- bool should_report_corb_blocking) {
+void InspectorNetworkAgent::DidFinishLoading(
+ uint64_t identifier,
+ DocumentLoader* loader,
+ base::TimeTicks monotonic_finish_time,
+ int64_t encoded_data_length,
+ int64_t decoded_body_length,
+ bool should_report_corb_blocking) {
String request_id = IdentifiersFactory::RequestId(loader, identifier);
NetworkResourcesData::ResourceData const* resource_data =
resources_data_->Data(request_id);
@@ -1044,8 +1043,9 @@ void InspectorNetworkAgent::DidFinishLoading(uint64_t identifier,
int pending_encoded_data_length = static_cast<int>(
resources_data_->GetAndClearPendingEncodedDataLength(request_id));
if (pending_encoded_data_length > 0) {
- GetFrontend()->dataReceived(request_id, CurrentTimeTicksInSeconds(), 0,
- pending_encoded_data_length);
+ GetFrontend()->dataReceived(
+ request_id, base::TimeTicks::Now().since_origin().InSecondsF(), 0,
+ pending_encoded_data_length);
}
if (resource_data &&
@@ -1058,10 +1058,10 @@ void InspectorNetworkAgent::DidFinishLoading(uint64_t identifier,
resources_data_->MaybeDecodeDataToContent(request_id);
if (monotonic_finish_time.is_null())
- monotonic_finish_time = CurrentTimeTicks();
+ monotonic_finish_time = base::TimeTicks::Now();
is_handling_sync_xhr_ = false;
- // TODO(npm): Use TimeTicks in Network.h.
+ // TODO(npm): Use base::TimeTicks in Network.h.
GetFrontend()->loadingFinished(
request_id, monotonic_finish_time.since_origin().InSecondsF(),
encoded_data_length, should_report_corb_blocking);
@@ -1074,7 +1074,7 @@ void InspectorNetworkAgent::DidReceiveCorsRedirectResponse(
Resource* resource) {
// Update the response and finish loading
DidReceiveResourceResponse(identifier, loader, response, resource);
- DidFinishLoading(identifier, loader, TimeTicks(),
+ DidFinishLoading(identifier, loader, base::TimeTicks(),
WebURLLoaderClient::kUnknownEncodedDataLength, 0, false);
}
@@ -1092,7 +1092,7 @@ void InspectorNetworkAgent::DidFailLoading(uint64_t identifier,
}
is_handling_sync_xhr_ = false;
GetFrontend()->loadingFailed(
- request_id, CurrentTimeTicksInSeconds(),
+ request_id, base::TimeTicks::Now().since_origin().InSecondsF(),
InspectorPageAgent::ResourceTypeJson(
resources_data_->GetResourceType(request_id)),
error.LocalizedDescription(), canceled, std::move(blocked_reason));
@@ -1150,14 +1150,15 @@ void InspectorNetworkAgent::WillDispatchEventSourceEvent(
const String& data) {
GetFrontend()->eventSourceMessageReceived(
IdentifiersFactory::SubresourceRequestId(identifier),
- CurrentTimeTicksInSeconds(), event_name.GetString(), event_id.GetString(),
- data);
+ base::TimeTicks::Now().since_origin().InSecondsF(),
+ event_name.GetString(), event_id.GetString(), data);
}
std::unique_ptr<protocol::Network::Initiator>
InspectorNetworkAgent::BuildInitiatorObject(
Document* document,
- const FetchInitiatorInfo& initiator_info) {
+ const FetchInitiatorInfo& initiator_info,
+ int max_async_depth) {
if (!initiator_info.imported_module_referrer.IsEmpty()) {
std::unique_ptr<protocol::Network::Initiator> initiator_object =
protocol::Network::Initiator::create()
@@ -1171,7 +1172,8 @@ InspectorNetworkAgent::BuildInitiatorObject(
std::unique_ptr<v8_inspector::protocol::Runtime::API::StackTrace>
current_stack_trace =
- SourceLocation::Capture(document)->BuildInspectorObject();
+ SourceLocation::Capture(document)->BuildInspectorObject(
+ max_async_depth);
if (current_stack_trace) {
std::unique_ptr<protocol::Network::Initiator> initiator_object =
protocol::Network::Initiator::create()
@@ -1243,7 +1245,8 @@ void InspectorNetworkAgent::WillSendWebSocketHandshakeRequest(
.build();
GetFrontend()->webSocketWillSendHandshakeRequest(
IdentifiersFactory::SubresourceRequestId(identifier),
- CurrentTimeTicksInSeconds(), CurrentTime(), std::move(request_object));
+ base::TimeTicks::Now().since_origin().InSecondsF(),
+ base::Time::Now().ToDoubleT(), std::move(request_object));
}
void InspectorNetworkAgent::DidReceiveWebSocketHandshakeResponse(
@@ -1286,25 +1289,36 @@ void InspectorNetworkAgent::DidReceiveWebSocketHandshakeResponse(
GetFrontend()->webSocketHandshakeResponseReceived(
IdentifiersFactory::SubresourceRequestId(identifier),
- CurrentTimeTicksInSeconds(), std::move(response_object));
+ base::TimeTicks::Now().since_origin().InSecondsF(),
+ std::move(response_object));
}
void InspectorNetworkAgent::DidCloseWebSocket(ExecutionContext*,
uint64_t identifier) {
GetFrontend()->webSocketClosed(
IdentifiersFactory::SubresourceRequestId(identifier),
- CurrentTimeTicksInSeconds());
+ base::TimeTicks::Now().since_origin().InSecondsF());
}
-void InspectorNetworkAgent::DidReceiveWebSocketMessage(uint64_t identifier,
- int op_code,
- bool masked,
- const char* payload,
- size_t payload_length) {
+void InspectorNetworkAgent::DidReceiveWebSocketMessage(
+ uint64_t identifier,
+ int op_code,
+ bool masked,
+ const Vector<base::span<const char>>& data) {
+ size_t size = 0;
+ for (const auto& span : data) {
+ size += span.size();
+ }
+ Vector<char> flatten;
+ flatten.ReserveCapacity(SafeCast<wtf_size_t>(size));
+ for (const auto& span : data) {
+ flatten.Append(span.data(), SafeCast<wtf_size_t>(span.size()));
+ }
GetFrontend()->webSocketFrameReceived(
IdentifiersFactory::SubresourceRequestId(identifier),
- CurrentTimeTicksInSeconds(),
- WebSocketMessageToProtocol(op_code, masked, payload, payload_length));
+ base::TimeTicks::Now().since_origin().InSecondsF(),
+ WebSocketMessageToProtocol(op_code, masked, flatten.data(),
+ flatten.size()));
}
void InspectorNetworkAgent::DidSendWebSocketMessage(uint64_t identifier,
@@ -1314,7 +1328,7 @@ void InspectorNetworkAgent::DidSendWebSocketMessage(uint64_t identifier,
size_t payload_length) {
GetFrontend()->webSocketFrameSent(
IdentifiersFactory::RequestId(nullptr, identifier),
- CurrentTimeTicksInSeconds(),
+ base::TimeTicks::Now().since_origin().InSecondsF(),
WebSocketMessageToProtocol(op_code, masked, payload, payload_length));
}
@@ -1323,7 +1337,7 @@ void InspectorNetworkAgent::DidReceiveWebSocketMessageError(
const String& error_message) {
GetFrontend()->webSocketFrameError(
IdentifiersFactory::RequestId(nullptr, identifier),
- CurrentTimeTicksInSeconds(), error_message);
+ base::TimeTicks::Now().since_origin().InSecondsF(), error_message);
}
Response InspectorNetworkAgent::enable(Maybe<int> total_buffer_size,
@@ -1348,6 +1362,8 @@ void InspectorNetworkAgent::Enable() {
Response InspectorNetworkAgent::disable() {
DCHECK(!pending_request_type_);
+ if (IsMainThread())
+ GetNetworkStateNotifier().ClearOverride();
instrumenting_agents_->RemoveInspectorNetworkAgent(this);
agent_state_.ClearAllFields();
resources_data_->Clear();
@@ -1416,8 +1432,8 @@ void InspectorNetworkAgent::getResponseBody(
Response InspectorNetworkAgent::setBlockedURLs(
std::unique_ptr<protocol::Array<String>> urls) {
blocked_urls_.Clear();
- for (size_t i = 0; i < urls->length(); i++)
- blocked_urls_.Set(urls->get(i), true);
+ for (const String& url : *urls)
+ blocked_urls_.Set(url, true);
return Response::OK();
}
@@ -1519,7 +1535,7 @@ Response InspectorNetworkAgent::setDataSizeLimitsForTest(int max_total,
Response InspectorNetworkAgent::getCertificate(
const String& origin,
std::unique_ptr<protocol::Array<String>>* certificate) {
- *certificate = protocol::Array<String>::create();
+ *certificate = std::make_unique<protocol::Array<String>>();
scoped_refptr<const SecurityOrigin> security_origin =
SecurityOrigin::CreateFromString(origin);
for (auto& resource : resources_data_->Resources()) {
@@ -1528,8 +1544,9 @@ Response InspectorNetworkAgent::getCertificate(
if (resource_origin->IsSameSchemeHostPort(security_origin.get()) &&
resource->Certificate().size()) {
for (auto& cert : resource->Certificate()) {
- certificate->get()->addItem(
- Base64Encode(base::as_bytes(base::make_span(cert.Latin1()))));
+ (*certificate)
+ ->emplace_back(
+ Base64Encode(base::as_bytes(base::make_span(cert.Latin1()))));
}
return Response::OK();
}
@@ -1553,9 +1570,13 @@ void InspectorNetworkAgent::FrameScheduledNavigation(LocalFrame* frame,
const KURL&,
double,
ClientNavigationReason) {
+ // For navigations, we limit async stack trace to depth 1 to avoid the
+ // base::Value depth limits with Mojo serialization / parsing.
+ // See http://crbug.com/809996.
frame_navigation_initiator_map_.Set(
IdentifiersFactory::FrameId(frame),
- BuildInitiatorObject(frame->GetDocument(), FetchInitiatorInfo()));
+ BuildInitiatorObject(frame->GetDocument(), FetchInitiatorInfo(),
+ /*max_async_depth=*/1));
}
void InspectorNetworkAgent::FrameClearedScheduledNavigation(LocalFrame* frame) {
@@ -1615,10 +1636,9 @@ Response InspectorNetworkAgent::searchInResponseBody(
auto results = v8_session_->searchInTextByLines(
ToV8InspectorStringView(content), ToV8InspectorStringView(query),
case_sensitive.fromMaybe(false), is_regex.fromMaybe(false));
- *matches = protocol::Array<
- v8_inspector::protocol::Debugger::API::SearchMatch>::create();
- for (size_t i = 0; i < results.size(); ++i)
- matches->get()->addItem(std::move(results[i]));
+ *matches = std::make_unique<
+ protocol::Array<v8_inspector::protocol::Debugger::API::SearchMatch>>(
+ std::move(results));
return Response::OK();
}
@@ -1656,7 +1676,11 @@ String InspectorNetworkAgent::NavigationInitiatorInfo(LocalFrame* frame) {
frame_navigation_initiator_map_.find(IdentifiersFactory::FrameId(frame));
if (it != frame_navigation_initiator_map_.end())
return it->value->toJSON();
- return BuildInitiatorObject(frame->GetDocument(), FetchInitiatorInfo())
+ // For navigations, we limit async stack trace to depth 1 to avoid the
+ // base::Value depth limits with Mojo serialization / parsing.
+ // See http://crbug.com/809996.
+ return BuildInitiatorObject(frame->GetDocument(), FetchInitiatorInfo(),
+ /*max_async_depth=*/1)
->toJSON();
}
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 6be907ae667..86a67007f6a 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
@@ -31,6 +31,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_INSPECTOR_INSPECTOR_NETWORK_AGENT_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_INSPECTOR_INSPECTOR_NETWORK_AGENT_H_
+#include "base/containers/span.h"
#include "base/optional.h"
#include "base/unguessable_token.h"
#include "third_party/blink/renderer/core/core_export.h"
@@ -127,7 +128,7 @@ class CORE_EXPORT InspectorNetworkAgent final
size_t encoded_data_length);
void DidFinishLoading(uint64_t identifier,
DocumentLoader*,
- TimeTicks monotonic_finish_time,
+ base::TimeTicks monotonic_finish_time,
int64_t encoded_data_length,
int64_t decoded_body_length,
bool should_report_corb_blocking);
@@ -185,8 +186,7 @@ class CORE_EXPORT InspectorNetworkAgent final
void DidReceiveWebSocketMessage(uint64_t identifier,
int op_code,
bool masked,
- const char* payload,
- size_t payload_length);
+ const Vector<base::span<const char>>& data);
void DidSendWebSocketMessage(uint64_t identifier,
int op_code,
bool masked,
@@ -260,7 +260,8 @@ class CORE_EXPORT InspectorNetworkAgent final
static std::unique_ptr<protocol::Network::Initiator> BuildInitiatorObject(
Document*,
- const FetchInitiatorInfo&);
+ const FetchInitiatorInfo&,
+ int max_async_depth);
static bool IsNavigation(DocumentLoader*, uint64_t identifier);
// This is null while inspecting workers.
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 9f68b585ad0..99bf4d3c9aa 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
@@ -31,7 +31,6 @@
#include <algorithm>
#include <memory>
#include <utility>
-#include <vector>
#include "base/auto_reset.h"
#include "build/build_config.h"
@@ -94,12 +93,12 @@ namespace {
bool ParseQuad(std::unique_ptr<protocol::Array<double>> quad_array,
FloatQuad* quad) {
const size_t kCoordinatesInQuad = 8;
- if (!quad_array || quad_array->length() != kCoordinatesInQuad)
+ if (!quad_array || quad_array->size() != kCoordinatesInQuad)
return false;
- quad->SetP1(FloatPoint(quad_array->get(0), quad_array->get(1)));
- quad->SetP2(FloatPoint(quad_array->get(2), quad_array->get(3)));
- quad->SetP3(FloatPoint(quad_array->get(4), quad_array->get(5)));
- quad->SetP4(FloatPoint(quad_array->get(6), quad_array->get(7)));
+ quad->SetP1(FloatPoint((*quad_array)[0], (*quad_array)[1]));
+ quad->SetP2(FloatPoint((*quad_array)[2], (*quad_array)[3]));
+ quad->SetP3(FloatPoint((*quad_array)[4], (*quad_array)[5]));
+ quad->SetP4(FloatPoint((*quad_array)[6], (*quad_array)[7]));
return true;
}
@@ -114,8 +113,8 @@ void InspectTool::Init(InspectorOverlayAgent* overlay,
DoInit();
}
-CString InspectTool::GetDataResourceName() {
- return "inspect_tool_highlight.html";
+String InspectTool::GetDataResourceName() {
+ return String("inspect_tool_highlight.html");
}
bool InspectTool::HandleInputEvent(LocalFrameView* frame_view,
@@ -331,12 +330,13 @@ InspectorOverlayAgent::InspectorOverlayAgent(
show_debug_borders_(&agent_state_, false),
show_fps_counter_(&agent_state_, false),
show_paint_rects_(&agent_state_, false),
+ show_layout_shift_regions_(&agent_state_, false),
show_scroll_bottleneck_rects_(&agent_state_, false),
show_hit_test_borders_(&agent_state_, false),
show_size_on_resize_(&agent_state_, false),
paused_in_debugger_message_(&agent_state_, String()),
inspect_mode_(&agent_state_, protocol::Overlay::InspectModeEnum::None),
- inspect_mode_protocol_config_(&agent_state_, String()) {}
+ inspect_mode_protocol_config_(&agent_state_, std::vector<uint8_t>()) {}
InspectorOverlayAgent::~InspectorOverlayAgent() {
DCHECK(!overlay_page_);
@@ -360,6 +360,7 @@ void InspectorOverlayAgent::Restore() {
setShowDebugBorders(show_debug_borders_.Get());
setShowFPSCounter(show_fps_counter_.Get());
setShowPaintRects(show_paint_rects_.Get());
+ setShowLayoutShiftRegions(show_layout_shift_regions_.Get());
setShowScrollBottleneckRects(show_scroll_bottleneck_rects_.Get());
setShowHitTestBorders(show_hit_test_borders_.Get());
setShowViewportSizeOnResize(show_size_on_resize_.Get());
@@ -390,12 +391,13 @@ Response InspectorOverlayAgent::disable() {
setShowDebugBorders(false);
setShowFPSCounter(false);
setShowPaintRects(false);
+ setShowLayoutShiftRegions(false);
setShowScrollBottleneckRects(false);
setShowHitTestBorders(false);
setShowViewportSizeOnResize(false);
paused_in_debugger_message_.Clear();
inspect_mode_.Set(protocol::Overlay::InspectModeEnum::None);
- inspect_mode_protocol_config_.Set(String());
+ inspect_mode_protocol_config_.Set(std::vector<uint8_t>());
if (overlay_page_) {
overlay_page_->WillBeDestroyed();
overlay_page_.Clear();
@@ -406,7 +408,7 @@ Response InspectorOverlayAgent::disable() {
resize_timer_.Stop();
resize_timer_active_ = false;
frame_overlay_.reset();
- frame_resource_name_ = CString();
+ frame_resource_name_ = String();
PickTheRightTool();
SetNeedsUnbufferedInput(false);
return Response::OK();
@@ -468,6 +470,24 @@ Response InspectorOverlayAgent::setShowPaintRects(bool show) {
return Response::OK();
}
+Response InspectorOverlayAgent::setShowLayoutShiftRegions(bool show) {
+ show_layout_shift_regions_.Set(show);
+ if (show) {
+ Response response = CompositingEnabled();
+ if (!response.isSuccess())
+ return response;
+ }
+ WebFrameWidget* widget = frame_impl_->LocalRoot()->FrameWidget();
+ WebFrameWidgetBase* widget_impl = static_cast<WebFrameWidgetBase*>(widget);
+ // While a frame is being detached the inspector will shutdown and
+ // turn off debug overlays, but the WebFrameWidget is already gone.
+ if (widget_impl)
+ widget_impl->Client()->SetShowLayoutShiftRegions(show);
+ if (!show && frame_impl_->GetFrameView())
+ frame_impl_->GetFrameView()->Invalidate();
+ return Response::OK();
+}
+
Response InspectorOverlayAgent::setShowScrollBottleneckRects(bool show) {
show_scroll_bottleneck_rects_.Set(show);
if (show) {
@@ -599,6 +619,7 @@ Response InspectorOverlayAgent::hideHighlight() {
Response InspectorOverlayAgent::getHighlightObjectForTest(
int node_id,
Maybe<bool> include_distance,
+ Maybe<bool> include_style,
std::unique_ptr<protocol::DictionaryValue>* result) {
Node* node = nullptr;
Response response = dom_agent_->AssertNode(node_id, node);
@@ -614,10 +635,12 @@ Response InspectorOverlayAgent::getHighlightObjectForTest(
is_locked_ancestor = true;
}
- InspectorHighlight highlight(
- node, InspectorHighlight::DefaultConfig(),
- InspectorHighlightContrastInfo(), true /* append_element_info */,
- include_distance.fromMaybe(false), is_locked_ancestor);
+ InspectorHighlightConfig config = InspectorHighlight::DefaultConfig();
+ config.show_styles = include_style.fromMaybe(false);
+ InspectorHighlight highlight(node, config, InspectorHighlightContrastInfo(),
+ true /* append_element_info */,
+ include_distance.fromMaybe(false),
+ is_locked_ancestor);
*result = highlight.AsProtocolValue();
return Response::OK();
}
@@ -719,9 +742,9 @@ WebInputEventResult InspectorOverlayAgent::HandleInputEventInOverlay(
return OverlayMainFrame()->GetEventHandler().HandleMouseMoveEvent(
mouse_event,
TransformWebMouseEventVector(frame_impl_->GetFrameView(),
- std::vector<const WebInputEvent*>()),
+ WebVector<const WebInputEvent*>()),
TransformWebMouseEventVector(frame_impl_->GetFrameView(),
- std::vector<const WebInputEvent*>()));
+ WebVector<const WebInputEvent*>()));
}
if (mouse_event.GetType() == WebInputEvent::kMouseDown) {
return OverlayMainFrame()->GetEventHandler().HandleMousePressEvent(
@@ -847,8 +870,8 @@ void InspectorOverlayAgent::EnsureOverlayPageCreated() {
DEFINE_STATIC_LOCAL(Persistent<LocalFrameClient>, dummy_local_frame_client,
(MakeGarbageCollected<EmptyLocalFrameClient>()));
- auto* frame = MakeGarbageCollected<LocalFrame>(dummy_local_frame_client,
- *overlay_page_, nullptr);
+ auto* frame = MakeGarbageCollected<LocalFrame>(
+ dummy_local_frame_client, *overlay_page_, nullptr, nullptr, nullptr);
frame->SetView(MakeGarbageCollected<LocalFrameView>(*frame));
frame->Init();
frame->View()->SetCanHaveScrollbars(false);
@@ -863,8 +886,8 @@ void InspectorOverlayAgent::LoadFrameForTool() {
DEFINE_STATIC_LOCAL(Persistent<LocalFrameClient>, dummy_local_frame_client,
(MakeGarbageCollected<EmptyLocalFrameClient>()));
- auto* frame = MakeGarbageCollected<LocalFrame>(dummy_local_frame_client,
- *overlay_page_, nullptr);
+ auto* frame = MakeGarbageCollected<LocalFrame>(
+ dummy_local_frame_client, *overlay_page_, nullptr, nullptr, nullptr);
frame->SetView(MakeGarbageCollected<LocalFrameView>(*frame));
frame->Init();
frame->View()->SetCanHaveScrollbars(false);
@@ -877,8 +900,8 @@ void InspectorOverlayAgent::LoadFrameForTool() {
data->Append("<script>", static_cast<size_t>(8));
data->Append(Platform::Current()->GetDataResource("inspect_tool_common.js"));
data->Append("</script>", static_cast<size_t>(9));
- data->Append(
- Platform::Current()->GetDataResource(frame_resource_name_.data()));
+ data->Append(Platform::Current()->GetDataResource(
+ frame_resource_name_.Utf8().c_str()));
frame->ForceSynchronousDocumentInstall("text/html", data);
@@ -993,7 +1016,7 @@ void InspectorOverlayAgent::OnResizeTimer(TimerBase*) {
SetInspectTool(MakeGarbageCollected<ShowViewSizeTool>());
resize_timer_active_ = true;
resize_timer_.Stop();
- resize_timer_.StartOneShot(TimeDelta::FromSeconds(1), FROM_HERE);
+ resize_timer_.StartOneShot(base::TimeDelta::FromSeconds(1), FROM_HERE);
}
void InspectorOverlayAgent::Dispatch(const String& message) {
@@ -1007,7 +1030,7 @@ void InspectorOverlayAgent::PageLayoutInvalidated(bool resized) {
// the main page layout to avoid document lifecycle issues caused by
// Microtask::PerformCheckpoint() called when we rebuild the overlay page.
resize_timer_.Stop();
- resize_timer_.StartOneShot(TimeDelta::FromSeconds(0), FROM_HERE);
+ resize_timer_.StartOneShot(base::TimeDelta::FromSeconds(0), FROM_HERE);
return;
}
ScheduleUpdate();
@@ -1059,10 +1082,11 @@ Response InspectorOverlayAgent::setInspectMode(
String("Unknown mode \"" + mode + "\" was provided."));
}
- String serialized_config =
- highlight_inspector_object.isJust()
- ? highlight_inspector_object.fromJust()->toJSON()
- : String();
+ std::vector<uint8_t> serialized_config;
+ if (highlight_inspector_object.isJust()) {
+ serialized_config =
+ highlight_inspector_object.fromJust()->serializeToBinary();
+ }
std::unique_ptr<InspectorHighlightConfig> config;
Response response = HighlightConfigFromInspectorObject(
std::move(highlight_inspector_object), &config);
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 37e6802bb61..ab0b77fbfdc 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
@@ -76,7 +76,7 @@ class CORE_EXPORT InspectTool : public GarbageCollectedFinalized<InspectTool> {
public:
virtual ~InspectTool() = default;
void Init(InspectorOverlayAgent* overlay, OverlayFrontend* frontend);
- virtual CString GetDataResourceName();
+ virtual String GetDataResourceName();
virtual bool HandleInputEvent(LocalFrameView* frame_view,
const WebInputEvent& input_event,
bool* swallow_next_mouse_up);
@@ -122,6 +122,7 @@ class CORE_EXPORT InspectorOverlayAgent final
protocol::Response disable() override;
protocol::Response setShowAdHighlights(bool) override;
protocol::Response setShowPaintRects(bool) override;
+ protocol::Response setShowLayoutShiftRegions(bool) override;
protocol::Response setShowDebugBorders(bool) override;
protocol::Response setShowFPSCounter(bool) override;
protocol::Response setShowScrollBottleneckRects(bool) override;
@@ -157,6 +158,7 @@ class CORE_EXPORT InspectorOverlayAgent final
protocol::Response getHighlightObjectForTest(
int node_id,
protocol::Maybe<bool> include_distance,
+ protocol::Maybe<bool> include_style,
std::unique_ptr<protocol::DictionaryValue>* highlight) override;
// InspectorBaseAgent overrides.
@@ -214,7 +216,7 @@ class CORE_EXPORT InspectorOverlayAgent final
Member<WebLocalFrameImpl> frame_impl_;
Member<InspectedFrames> inspected_frames_;
Member<Page> overlay_page_;
- CString frame_resource_name_;
+ String frame_resource_name_;
Member<InspectorOverlayChromeClient> overlay_chrome_client_;
Member<InspectorOverlayHost> overlay_host_;
bool resize_timer_active_;
@@ -232,12 +234,13 @@ class CORE_EXPORT InspectorOverlayAgent final
InspectorAgentState::Boolean show_debug_borders_;
InspectorAgentState::Boolean show_fps_counter_;
InspectorAgentState::Boolean show_paint_rects_;
+ InspectorAgentState::Boolean show_layout_shift_regions_;
InspectorAgentState::Boolean show_scroll_bottleneck_rects_;
InspectorAgentState::Boolean show_hit_test_borders_;
InspectorAgentState::Boolean show_size_on_resize_;
InspectorAgentState::String paused_in_debugger_message_;
InspectorAgentState::String inspect_mode_;
- InspectorAgentState::String inspect_mode_protocol_config_;
+ InspectorAgentState::Bytes inspect_mode_protocol_config_;
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 98229c0fc7f..53e27cc4f67 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
@@ -140,40 +140,39 @@ Resource* CachedResource(LocalFrame* frame,
std::unique_ptr<protocol::Array<String>> GetEnabledWindowFeatures(
const WebWindowFeatures& window_features) {
- std::unique_ptr<protocol::Array<String>> feature_strings =
- protocol::Array<String>::create();
+ auto feature_strings = std::make_unique<protocol::Array<String>>();
if (window_features.x_set) {
- feature_strings->addItem(
+ feature_strings->emplace_back(
String::Format("left=%d", static_cast<int>(window_features.x)));
}
if (window_features.y_set) {
- feature_strings->addItem(
+ feature_strings->emplace_back(
String::Format("top=%d", static_cast<int>(window_features.y)));
}
if (window_features.width_set) {
- feature_strings->addItem(
+ feature_strings->emplace_back(
String::Format("width=%d", static_cast<int>(window_features.width)));
}
if (window_features.height_set) {
- feature_strings->addItem(
+ feature_strings->emplace_back(
String::Format("height=%d", static_cast<int>(window_features.height)));
}
if (window_features.menu_bar_visible)
- feature_strings->addItem("menubar");
+ feature_strings->emplace_back("menubar");
if (window_features.tool_bar_visible)
- feature_strings->addItem("toolbar");
+ feature_strings->emplace_back("toolbar");
if (window_features.status_bar_visible)
- feature_strings->addItem("status");
+ feature_strings->emplace_back("status");
if (window_features.scrollbars_visible)
- feature_strings->addItem("scrollbars");
+ feature_strings->emplace_back("scrollbars");
if (window_features.resizable)
- feature_strings->addItem("resizable");
+ feature_strings->emplace_back("resizable");
if (window_features.noopener)
- feature_strings->addItem("noopener");
+ feature_strings->emplace_back("noopener");
if (window_features.background)
- feature_strings->addItem("background");
+ feature_strings->emplace_back("background");
if (window_features.persistent)
- feature_strings->addItem("persistent");
+ feature_strings->emplace_back("persistent");
return feature_strings;
}
@@ -241,12 +240,12 @@ static void MaybeEncodeTextContent(const String& text_content,
wtf_size_t buffer_size,
String* result,
bool* base64_encoded) {
- if (!text_content.IsNull() &&
- !text_content.Utf8(WTF::kStrictUTF8Conversion).IsNull()) {
+ if (!text_content.IsNull()) {
*result = text_content;
*base64_encoded = false;
} else if (buffer_data) {
- *result = Base64Encode(buffer_data, buffer_size);
+ *result =
+ Base64Encode(base::as_bytes(base::make_span(buffer_data, buffer_size)));
*base64_encoded = true;
} else if (text_content.IsNull()) {
*result = "";
@@ -327,8 +326,8 @@ bool InspectorPageAgent::CachedResourceContent(const Resource* cached_resource,
return false;
const SharedBuffer::DeprecatedFlatData flat_buffer(std::move(buffer));
- *result = Base64Encode(flat_buffer.Data(),
- SafeCast<wtf_size_t>(flat_buffer.size()));
+ *result = Base64Encode(base::as_bytes(
+ base::make_span(flat_buffer.Data(), flat_buffer.size())));
*base64_encoded = true;
return true;
}
@@ -540,8 +539,8 @@ Response InspectorPageAgent::addScriptToEvaluateOnNewDocument(
const String& source,
Maybe<String> world_name,
String* identifier) {
- std::vector<WTF::String> keys = scripts_to_evaluate_on_load_.Keys();
- auto result = std::max_element(
+ Vector<WTF::String> keys = scripts_to_evaluate_on_load_.Keys();
+ auto* result = std::max_element(
keys.begin(), keys.end(), [](const WTF::String& a, const WTF::String& b) {
return Decimal::FromString(a) < Decimal::FromString(b);
});
@@ -588,33 +587,34 @@ Response InspectorPageAgent::setLifecycleEventsEnabled(bool enabled) {
continue;
DocumentLoadTiming& timing = loader->GetTiming();
- TimeTicks commit_timestamp = timing.ResponseEnd();
+ base::TimeTicks commit_timestamp = timing.ResponseEnd();
if (!commit_timestamp.is_null()) {
LifecycleEvent(frame, loader, "commit",
commit_timestamp.since_origin().InSecondsF());
}
- TimeTicks domcontentloaded_timestamp =
+ base::TimeTicks domcontentloaded_timestamp =
document->GetTiming().DomContentLoadedEventEnd();
if (!domcontentloaded_timestamp.is_null()) {
LifecycleEvent(frame, loader, "DOMContentLoaded",
domcontentloaded_timestamp.since_origin().InSecondsF());
}
- TimeTicks load_timestamp = timing.LoadEventEnd();
+ base::TimeTicks load_timestamp = timing.LoadEventEnd();
if (!load_timestamp.is_null()) {
LifecycleEvent(frame, loader, "load",
load_timestamp.since_origin().InSecondsF());
}
IdlenessDetector* idleness_detector = frame->GetIdlenessDetector();
- TimeTicks network_almost_idle_timestamp =
+ base::TimeTicks network_almost_idle_timestamp =
idleness_detector->GetNetworkAlmostIdleTime();
if (!network_almost_idle_timestamp.is_null()) {
LifecycleEvent(frame, loader, "networkAlmostIdle",
network_almost_idle_timestamp.since_origin().InSecondsF());
}
- TimeTicks network_idle_timestamp = idleness_detector->GetNetworkIdleTime();
+ base::TimeTicks network_idle_timestamp =
+ idleness_detector->GetNetworkIdleTime();
if (!network_idle_timestamp.is_null()) {
LifecycleEvent(frame, loader, "networkIdle",
network_idle_timestamp.since_origin().InSecondsF());
@@ -764,11 +764,10 @@ void InspectorPageAgent::SearchContentAfterResourcesContentLoaded(
auto matches = v8_session_->searchInTextByLines(
ToV8InspectorStringView(content), ToV8InspectorStringView(query),
case_sensitive, is_regex);
- auto results = protocol::Array<
- v8_inspector::protocol::Debugger::API::SearchMatch>::create();
- for (size_t i = 0; i < matches.size(); ++i)
- results->addItem(std::move(matches[i]));
- callback->sendSuccess(std::move(results));
+ callback->sendSuccess(
+ std::make_unique<
+ protocol::Array<v8_inspector::protocol::Debugger::API::SearchMatch>>(
+ std::move(matches)));
}
void InspectorPageAgent::searchInResource(
@@ -820,16 +819,40 @@ void InspectorPageAgent::DidNavigateWithinDocument(LocalFrame* frame) {
}
}
+scoped_refptr<DOMWrapperWorld> InspectorPageAgent::EnsureDOMWrapperWorld(
+ LocalFrame* frame,
+ const String& world_name,
+ bool grant_universal_access) {
+ if (!isolated_worlds_.Contains(frame))
+ isolated_worlds_.Set(frame, FrameIsolatedWorlds());
+ FrameIsolatedWorlds& frame_worlds = isolated_worlds_.find(frame)->value;
+
+ auto world_it = frame_worlds.find(world_name);
+ if (world_it != frame_worlds.end())
+ return world_it->value;
+ scoped_refptr<DOMWrapperWorld> world =
+ frame->GetScriptController().CreateNewInspectorIsolatedWorld(world_name);
+ if (!world)
+ return nullptr;
+ frame_worlds.Set(world_name, world);
+ scoped_refptr<SecurityOrigin> security_origin =
+ frame->GetSecurityContext()->GetSecurityOrigin()->IsolatedCopy();
+ if (grant_universal_access)
+ security_origin->GrantUniversalAccess();
+ DOMWrapperWorld::SetIsolatedWorldSecurityOrigin(world->GetWorldId(),
+ security_origin);
+ return world;
+}
+
void InspectorPageAgent::DidClearDocumentOfWindowObject(LocalFrame* frame) {
if (!GetFrontend())
return;
- std::vector<WTF::String> keys = scripts_to_evaluate_on_load_.Keys();
+ Vector<WTF::String> keys = scripts_to_evaluate_on_load_.Keys();
std::sort(keys.begin(), keys.end(),
[](const WTF::String& a, const WTF::String& b) {
return Decimal::FromString(a) < Decimal::FromString(b);
});
- HashMap<String, int> world_id_by_name;
for (const WTF::String& key : keys) {
const String source = scripts_to_evaluate_on_load_.Get(key);
const String world_name = worlds_to_evaluate_on_load_.Get(key);
@@ -840,31 +863,16 @@ void InspectorPageAgent::DidClearDocumentOfWindowObject(LocalFrame* frame) {
continue;
}
- auto it = world_id_by_name.find(world_name);
- int world_id = 0;
- if (it != world_id_by_name.end()) {
- world_id = it->value;
- } else {
- scoped_refptr<DOMWrapperWorld> world =
- frame->GetScriptController().CreateNewInspectorIsolatedWorld(
- world_name);
- if (!world)
- continue;
- world_id = world->GetWorldId();
- world_id_by_name.Set(world_name, world_id);
-
- scoped_refptr<SecurityOrigin> security_origin =
- frame->GetSecurityContext()->GetSecurityOrigin()->IsolatedCopy();
- security_origin->GrantUniversalAccess();
- DOMWrapperWorld::SetIsolatedWorldSecurityOrigin(world_id,
- security_origin);
- }
+ scoped_refptr<DOMWrapperWorld> world = EnsureDOMWrapperWorld(
+ frame, world_name, true /* grant_universal_access */);
+ if (!world)
+ continue;
// Note: An error event in an isolated world will never be dispatched to
// a foreign world.
v8::HandleScope handle_scope(V8PerIsolateData::MainThreadIsolate());
frame->GetScriptController().ExecuteScriptInIsolatedWorld(
- world_id, source, KURL(), SanitizeScriptErrors::kSanitize);
+ world->GetWorldId(), source, KURL(), SanitizeScriptErrors::kSanitize);
}
if (!script_to_evaluate_on_load_once_.IsEmpty()) {
@@ -875,7 +883,7 @@ void InspectorPageAgent::DidClearDocumentOfWindowObject(LocalFrame* frame) {
}
void InspectorPageAgent::DomContentLoadedEventFired(LocalFrame* frame) {
- double timestamp = CurrentTimeTicksInSeconds();
+ double timestamp = base::TimeTicks::Now().since_origin().InSecondsF();
if (frame == inspected_frames_->Root())
GetFrontend()->domContentEventFired(timestamp);
DocumentLoader* loader = frame->Loader().GetDocumentLoader();
@@ -883,7 +891,7 @@ void InspectorPageAgent::DomContentLoadedEventFired(LocalFrame* frame) {
}
void InspectorPageAgent::LoadEventFired(LocalFrame* frame) {
- double timestamp = CurrentTimeTicksInSeconds();
+ double timestamp = base::TimeTicks::Now().since_origin().InSecondsF();
if (frame == inspected_frames_->Root())
GetFrontend()->loadEventFired(timestamp);
DocumentLoader* loader = frame->Loader().GetDocumentLoader();
@@ -1032,6 +1040,8 @@ std::unique_ptr<protocol::Page::Frame> InspectorPageAgent::BuildObjectForFrame(
.setSecurityOrigin(
SecurityOrigin::Create(loader->Url())->ToRawString())
.build();
+ if (loader->Url().HasFragmentIdentifier())
+ frame_object->setUrlFragment("#" + loader->Url().FragmentIdentifier());
Frame* parent_frame = frame->Tree().Parent();
if (parent_frame) {
frame_object->setParentId(IdentifiersFactory::FrameId(parent_frame));
@@ -1058,9 +1068,11 @@ InspectorPageAgent::BuildObjectForFrameTree(LocalFrame* frame) {
auto* child_local_frame = DynamicTo<LocalFrame>(child);
if (!child_local_frame)
continue;
- if (!children_array)
- children_array = protocol::Array<protocol::Page::FrameTree>::create();
- children_array->addItem(BuildObjectForFrameTree(child_local_frame));
+ if (!children_array) {
+ children_array =
+ std::make_unique<protocol::Array<protocol::Page::FrameTree>>();
+ }
+ children_array->emplace_back(BuildObjectForFrameTree(child_local_frame));
}
result->setChildFrames(std::move(children_array));
return result;
@@ -1070,8 +1082,8 @@ std::unique_ptr<protocol::Page::FrameResourceTree>
InspectorPageAgent::BuildObjectForResourceTree(LocalFrame* frame) {
std::unique_ptr<protocol::Page::Frame> frame_object =
BuildObjectForFrame(frame);
- std::unique_ptr<protocol::Array<protocol::Page::FrameResource>> subresources =
- protocol::Array<protocol::Page::FrameResource>::create();
+ auto subresources =
+ std::make_unique<protocol::Array<protocol::Page::FrameResource>>();
HeapVector<Member<Resource>> all_resources =
CachedResourcesForFrame(frame, true);
@@ -1090,7 +1102,7 @@ InspectorPageAgent::BuildObjectForResourceTree(LocalFrame* frame) {
resource_object->setCanceled(true);
else if (cached_resource->GetStatus() == ResourceStatus::kLoadError)
resource_object->setFailed(true);
- subresources->addItem(std::move(resource_object));
+ subresources->emplace_back(std::move(resource_object));
}
HeapVector<Member<Document>> all_imports =
@@ -1102,7 +1114,7 @@ InspectorPageAgent::BuildObjectForResourceTree(LocalFrame* frame) {
.setType(ResourceTypeJson(InspectorPageAgent::kDocumentResource))
.setMimeType(import->SuggestedMIMEType())
.build();
- subresources->addItem(std::move(resource_object));
+ subresources->emplace_back(std::move(resource_object));
}
std::unique_ptr<protocol::Page::FrameResourceTree> result =
@@ -1118,10 +1130,11 @@ InspectorPageAgent::BuildObjectForResourceTree(LocalFrame* frame) {
auto* child_local_frame = DynamicTo<LocalFrame>(child);
if (!child_local_frame)
continue;
- if (!children_array)
- children_array =
- protocol::Array<protocol::Page::FrameResourceTree>::create();
- children_array->addItem(BuildObjectForResourceTree(child_local_frame));
+ if (!children_array) {
+ children_array = std::make_unique<
+ protocol::Array<protocol::Page::FrameResourceTree>>();
+ }
+ children_array->emplace_back(BuildObjectForResourceTree(child_local_frame));
}
result->setChildFrames(std::move(children_array));
return result;
@@ -1206,19 +1219,11 @@ protocol::Response InspectorPageAgent::createIsolatedWorld(
if (!frame)
return Response::Error("No frame for given id found");
- scoped_refptr<DOMWrapperWorld> world =
- frame->GetScriptController().CreateNewInspectorIsolatedWorld(
- world_name.fromMaybe(""));
+ scoped_refptr<DOMWrapperWorld> world = EnsureDOMWrapperWorld(
+ frame, world_name.fromMaybe(""), grant_universal_access.fromMaybe(false));
if (!world)
return Response::Error("Could not create isolated world");
- scoped_refptr<SecurityOrigin> security_origin =
- frame->GetSecurityContext()->GetSecurityOrigin()->IsolatedCopy();
- if (grant_universal_access.fromMaybe(false))
- security_origin->GrantUniversalAccess();
- DOMWrapperWorld::SetIsolatedWorldSecurityOrigin(world->GetWorldId(),
- security_origin);
-
LocalWindowProxy* isolated_world_window_proxy =
frame->GetScriptController().WindowProxy(*world);
v8::HandleScope handle_scope(V8PerIsolateData::MainThreadIsolate());
@@ -1370,6 +1375,7 @@ protocol::Response InspectorPageAgent::generateTestReport(const String& message,
void InspectorPageAgent::Trace(blink::Visitor* visitor) {
visitor->Trace(inspected_frames_);
visitor->Trace(inspector_resource_content_loader_);
+ visitor->Trace(isolated_worlds_);
InspectorBaseAgent::Trace(visitor);
}
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 cbb6824fa94..7b179031193 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
@@ -228,6 +228,10 @@ class CORE_EXPORT InspectorPageAgent final
bool case_sensitive,
bool is_regex,
std::unique_ptr<SearchInResourceCallback>);
+ scoped_refptr<DOMWrapperWorld> EnsureDOMWrapperWorld(
+ LocalFrame* frame,
+ const String& world_name,
+ bool grant_universal_access);
static KURL UrlWithoutFragment(const KURL&);
@@ -240,6 +244,8 @@ class CORE_EXPORT InspectorPageAgent final
LocalFrame*);
Member<InspectedFrames> inspected_frames_;
HashMap<String, protocol::Binary> compilation_cache_;
+ using FrameIsolatedWorlds = HashMap<String, scoped_refptr<DOMWrapperWorld>>;
+ HeapHashMap<WeakMember<LocalFrame>, FrameIsolatedWorlds> isolated_worlds_;
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 898e5c90a95..ca49dbe223a 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
@@ -14,7 +14,7 @@
#include "third_party/blink/renderer/core/paint/paint_timing.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
#include "third_party/blink/renderer/platform/bindings/v8_per_isolate_data.h"
-#include "third_party/blink/renderer/platform/instance_counters.h"
+#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h"
#include "third_party/blink/renderer/platform/wtf/dtoa/utils.h"
namespace blink {
@@ -51,11 +51,11 @@ void InspectorPerformanceAgent::Restore() {
void InspectorPerformanceAgent::InnerEnable() {
instrumenting_agents_->AddInspectorPerformanceAgent(this);
Thread::Current()->AddTaskTimeObserver(this);
- layout_start_ticks_ = TimeTicks();
- recalc_style_start_ticks_ = TimeTicks();
- task_start_ticks_ = TimeTicks();
- script_start_ticks_ = TimeTicks();
- v8compile_start_ticks_ = TimeTicks();
+ layout_start_ticks_ = base::TimeTicks();
+ recalc_style_start_ticks_ = base::TimeTicks();
+ task_start_ticks_ = base::TimeTicks();
+ script_start_ticks_ = base::TimeTicks();
+ v8compile_start_ticks_ = base::TimeTicks();
thread_time_origin_ = GetThreadTimeNow();
}
@@ -80,10 +80,10 @@ namespace {
void AppendMetric(protocol::Array<protocol::Performance::Metric>* container,
const String& name,
double value) {
- container->addItem(protocol::Performance::Metric::create()
- .setName(name)
- .setValue(value)
- .build());
+ container->emplace_back(protocol::Performance::Metric::create()
+ .setName(name)
+ .setValue(value)
+ .build());
}
} // namespace
@@ -111,12 +111,12 @@ Response InspectorPerformanceAgent::setTimeDomain(const String& time_domain) {
return Response::OK();
}
-TimeTicks InspectorPerformanceAgent::GetTimeTicksNow() {
+base::TimeTicks InspectorPerformanceAgent::GetTimeTicksNow() {
return use_thread_ticks_.Get() ? GetThreadTimeNow()
: base::subtle::TimeTicksNowIgnoringOverride();
}
-TimeTicks InspectorPerformanceAgent::GetThreadTimeNow() {
+base::TimeTicks InspectorPerformanceAgent::GetThreadTimeNow() {
return base::TimeTicks() +
base::TimeDelta::FromMicroseconds(
base::ThreadTicks::Now().since_origin().InMicroseconds());
@@ -126,15 +126,16 @@ Response InspectorPerformanceAgent::getMetrics(
std::unique_ptr<protocol::Array<protocol::Performance::Metric>>*
out_result) {
if (!enabled_.Get()) {
- *out_result = protocol::Array<protocol::Performance::Metric>::create();
+ *out_result =
+ std::make_unique<protocol::Array<protocol::Performance::Metric>>();
return Response::OK();
}
- std::unique_ptr<protocol::Array<protocol::Performance::Metric>> result =
- protocol::Array<protocol::Performance::Metric>::create();
+ auto result =
+ std::make_unique<protocol::Array<protocol::Performance::Metric>>();
AppendMetric(result.get(), "Timestamp",
- CurrentTimeTicks().since_origin().InSecondsF());
+ base::TimeTicks::Now().since_origin().InSecondsF());
// Renderer instance counters.
for (size_t i = 0; i < ARRAY_SIZE(kInstanceCounterNames); ++i) {
@@ -144,7 +145,7 @@ Response InspectorPerformanceAgent::getMetrics(
}
// Page performance metrics.
- TimeTicks now = GetTimeTicksNow();
+ base::TimeTicks now = GetTimeTicksNow();
AppendMetric(result.get(), "LayoutCount", static_cast<double>(layout_count_));
AppendMetric(result.get(), "RecalcStyleCount",
static_cast<double>(recalc_style_count_));
@@ -152,30 +153,30 @@ Response InspectorPerformanceAgent::getMetrics(
AppendMetric(result.get(), "RecalcStyleDuration",
recalc_style_duration_.InSecondsF());
- TimeDelta script_duration = script_duration_;
+ base::TimeDelta script_duration = script_duration_;
if (!script_start_ticks_.is_null())
script_duration += now - script_start_ticks_;
AppendMetric(result.get(), "ScriptDuration", script_duration.InSecondsF());
- TimeDelta v8compile_duration = v8compile_duration_;
+ base::TimeDelta v8compile_duration = v8compile_duration_;
if (!v8compile_start_ticks_.is_null())
v8compile_duration += now - v8compile_start_ticks_;
AppendMetric(result.get(), "V8CompileDuration",
v8compile_duration.InSecondsF());
- TimeDelta task_duration = task_duration_;
+ base::TimeDelta task_duration = task_duration_;
if (!task_start_ticks_.is_null())
task_duration += now - task_start_ticks_;
AppendMetric(result.get(), "TaskDuration", task_duration.InSecondsF());
// Compute task time not accounted for by other metrics.
- TimeDelta other_tasks_duration =
+ base::TimeDelta other_tasks_duration =
task_duration -
(script_duration + recalc_style_duration_ + layout_duration_);
AppendMetric(result.get(), "TaskOtherDuration",
other_tasks_duration.InSecondsF());
- TimeDelta thread_time = GetThreadTimeNow() - thread_time_origin_;
+ base::TimeDelta thread_time = GetThreadTimeNow() - thread_time_origin_;
AppendMetric(result.get(), "ThreadTime", thread_time.InSecondsF());
v8::HeapStatistics heap_statistics;
@@ -227,7 +228,7 @@ void InspectorPerformanceAgent::ScriptEnds() {
if (--script_call_depth_)
return;
script_duration_ += GetTimeTicksNow() - script_start_ticks_;
- script_start_ticks_ = TimeTicks();
+ script_start_ticks_ = base::TimeTicks();
}
void InspectorPerformanceAgent::Will(const probe::CallFunction& probe) {
@@ -251,10 +252,10 @@ void InspectorPerformanceAgent::Will(const probe::RecalculateStyle& probe) {
}
void InspectorPerformanceAgent::Did(const probe::RecalculateStyle& probe) {
- TimeDelta delta = GetTimeTicksNow() - recalc_style_start_ticks_;
+ base::TimeDelta delta = GetTimeTicksNow() - recalc_style_start_ticks_;
recalc_style_duration_ += delta;
recalc_style_count_++;
- recalc_style_start_ticks_ = TimeTicks();
+ recalc_style_start_ticks_ = base::TimeTicks();
// Exclude nested style re-calculations from script and layout duration.
if (!script_start_ticks_.is_null())
@@ -271,10 +272,10 @@ void InspectorPerformanceAgent::Will(const probe::UpdateLayout& probe) {
void InspectorPerformanceAgent::Did(const probe::UpdateLayout& probe) {
if (--layout_depth_)
return;
- TimeDelta delta = GetTimeTicksNow() - layout_start_ticks_;
+ base::TimeDelta delta = GetTimeTicksNow() - layout_start_ticks_;
layout_duration_ += delta;
layout_count_++;
- layout_start_ticks_ = TimeTicks();
+ layout_start_ticks_ = base::TimeTicks();
// Exclude nested layout update from script and style re-calculations
// duration.
@@ -291,7 +292,7 @@ void InspectorPerformanceAgent::Will(const probe::V8Compile& probe) {
void InspectorPerformanceAgent::Did(const probe::V8Compile& probe) {
v8compile_duration_ += GetTimeTicksNow() - v8compile_start_ticks_;
- v8compile_start_ticks_ = TimeTicks();
+ v8compile_start_ticks_ = base::TimeTicks();
}
// Will/DidProcessTask() ignore caller provided times to ensure time domain
@@ -304,7 +305,7 @@ void InspectorPerformanceAgent::DidProcessTask(base::TimeTicks start_time,
base::TimeTicks end_time) {
if (!task_start_ticks_.is_null())
task_duration_ += GetTimeTicksNow() - task_start_ticks_;
- task_start_ticks_ = TimeTicks();
+ task_start_ticks_ = base::TimeTicks();
}
void InspectorPerformanceAgent::Trace(blink::Visitor* visitor) {
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 9202700e260..48ed7f5fbda 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
@@ -67,21 +67,21 @@ class CORE_EXPORT InspectorPerformanceAgent final
void ScriptStarts();
void ScriptEnds();
void InnerEnable();
- TimeTicks GetTimeTicksNow();
- TimeTicks GetThreadTimeNow();
+ base::TimeTicks GetTimeTicksNow();
+ base::TimeTicks GetThreadTimeNow();
Member<InspectedFrames> inspected_frames_;
- TimeDelta layout_duration_;
- TimeTicks layout_start_ticks_;
- TimeDelta recalc_style_duration_;
- TimeTicks recalc_style_start_ticks_;
- TimeDelta script_duration_;
- TimeTicks script_start_ticks_;
- TimeDelta task_duration_;
- TimeTicks task_start_ticks_;
- TimeDelta v8compile_duration_;
- TimeTicks v8compile_start_ticks_;
- TimeTicks thread_time_origin_;
+ base::TimeDelta layout_duration_;
+ base::TimeTicks layout_start_ticks_;
+ base::TimeDelta recalc_style_duration_;
+ base::TimeTicks recalc_style_start_ticks_;
+ base::TimeDelta script_duration_;
+ base::TimeTicks script_start_ticks_;
+ base::TimeDelta task_duration_;
+ base::TimeTicks task_start_ticks_;
+ base::TimeDelta v8compile_duration_;
+ base::TimeTicks v8compile_start_ticks_;
+ base::TimeTicks thread_time_origin_;
uint64_t layout_count_ = 0;
uint64_t recalc_style_count_ = 0;
int script_call_depth_ = 0;
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 f203f955c89..a66e4c47a86 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", "resetNavigationHistory", "captureScreenshot", "screencastFrameAck", "handleJavaScriptDialog", "setColorPickerEnabled",
- "getAppManifest", "setControlNavigations", "processNavigation", "printToPDF", "bringToFront", "setDownloadBehavior", "navigate", "crash", "close", "setWebLifecycleState", "captureSnapshot", "getInstallabilityErrors"],
+ "getAppManifest", "setControlNavigations", "processNavigation", "printToPDF", "bringToFront", "setDownloadBehavior", "navigate", "crash", "close", "setWebLifecycleState", "captureSnapshot", "getInstallabilityErrors", "setInterceptFileChooserDialog", "handleFileChooser"],
"async": ["getResourceContent", "searchInResource"],
"exclude_events": ["screencastFrame", "screencastVisibilityChanged", "colorPicked", "interstitialShown", "interstitialHidden", "javascriptDialogOpening", "javascriptDialogClosed", "navigationRequested"]
},
@@ -127,7 +127,10 @@
},
"encoding_lib": {
- "header": "third_party/inspector_protocol/encoding/encoding.h",
- "namespace": ["inspector_protocol_encoding"]
+ "namespace": "inspector_protocol_encoding"
+ },
+
+ "bindings_lib": {
+ "namespace": "inspector_protocol_bindings"
}
}
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 057e35ead67..ba9eb2836b9 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
@@ -4,7 +4,7 @@
#include "third_party/blink/renderer/core/inspector/inspector_resource_content_loader.h"
-#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-shared.h"
+#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h"
#include "third_party/blink/public/platform/web_url_request.h"
#include "third_party/blink/renderer/core/css/css_style_sheet.h"
#include "third_party/blink/renderer/core/css/style_sheet_contents.h"
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_session_state.cc b/chromium/third_party/blink/renderer/core/inspector/inspector_session_state.cc
index 4c906ae3107..206ad8724dd 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_session_state.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_session_state.cc
@@ -36,11 +36,11 @@ const mojom::blink::DevToolsSessionState* InspectorSessionState::ReattachState()
}
void InspectorSessionState::EnqueueUpdate(const WTF::String& key,
- const std::vector<uint8_t>* value) {
+ const WebVector<uint8_t>* value) {
base::Optional<WTF::Vector<uint8_t>> updated_value;
if (value) {
WTF::Vector<uint8_t> payload;
- payload.Append(value->data(), value->size());
+ payload.AppendRange(value->begin(), value->end());
updated_value = std::move(payload);
}
updates_->entries.Set(key, std::move(updated_value));
@@ -56,8 +56,8 @@ mojom::blink::DevToolsSessionStatePtr InspectorSessionState::TakeUpdates() {
// Encoding / Decoding routines.
//
/*static*/
-void InspectorAgentState::Serialize(bool v, std::vector<uint8_t>* out) {
- out->push_back(v ? EncodeTrue() : EncodeFalse());
+void InspectorAgentState::Serialize(bool v, WebVector<uint8_t>* out) {
+ out->emplace_back(v ? EncodeTrue() : EncodeFalse());
}
/*static*/
@@ -75,8 +75,10 @@ bool InspectorAgentState::Deserialize(span<uint8_t> in, bool* v) {
}
/*static*/
-void InspectorAgentState::Serialize(int32_t v, std::vector<uint8_t>* out) {
- ::inspector_protocol_encoding::cbor::EncodeInt32(v, out);
+void InspectorAgentState::Serialize(int32_t v, WebVector<uint8_t>* out) {
+ auto encode = out->ReleaseVector();
+ ::inspector_protocol_encoding::cbor::EncodeInt32(v, &encode);
+ *out = std::move(encode);
}
/*static*/
@@ -90,8 +92,10 @@ bool InspectorAgentState::Deserialize(span<uint8_t> in, int32_t* v) {
}
/*static*/
-void InspectorAgentState::Serialize(double v, std::vector<uint8_t>* out) {
- ::inspector_protocol_encoding::cbor::EncodeDouble(v, out);
+void InspectorAgentState::Serialize(double v, WebVector<uint8_t>* out) {
+ auto encode = out->ReleaseVector();
+ ::inspector_protocol_encoding::cbor::EncodeDouble(v, &encode);
+ *out = std::move(encode);
}
/*static*/
@@ -106,17 +110,19 @@ bool InspectorAgentState::Deserialize(span<uint8_t> in, double* v) {
/*static*/
void InspectorAgentState::Serialize(const WTF::String& v,
- std::vector<uint8_t>* out) {
+ WebVector<uint8_t>* out) {
+ auto encode = out->ReleaseVector();
if (v.Is8Bit()) {
auto span8 = v.Span8();
- EncodeFromLatin1(span<uint8_t>(span8.data(), span8.size()), out);
+ EncodeFromLatin1(span<uint8_t>(span8.data(), span8.size()), &encode);
} else {
auto span16 = v.Span16();
EncodeFromUTF16(
span<uint16_t>(reinterpret_cast<const uint16_t*>(span16.data()),
span16.size()),
- out);
+ &encode);
}
+ *out = std::move(encode);
}
/*static*/
@@ -139,11 +145,11 @@ bool InspectorAgentState::Deserialize(span<uint8_t> in, WTF::String* v) {
/*static*/
void InspectorAgentState::Serialize(const std::vector<uint8_t>& v,
- std::vector<uint8_t>* out) {
+ WebVector<uint8_t>* out) {
// We could CBOR encode this, but since we never look at the contents
// anyway (except for decoding just below), we just cheat and use the
// blob directly.
- out->insert(out->end(), v.begin(), v.end());
+ out->Assign(v.data(), v.size());
}
/*static*/
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_session_state.h b/chromium/third_party/blink/renderer/core/inspector/inspector_session_state.h
index bc63d69766e..74611e91198 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_session_state.h
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_session_state.h
@@ -7,8 +7,8 @@
#include <memory>
#include <type_traits>
-#include <vector>
#include "third_party/blink/public/mojom/devtools/devtools_agent.mojom-blink.h"
+#include "third_party/blink/public/platform/web_vector.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/inspector_protocol/encoding/encoding.h"
@@ -30,7 +30,7 @@ class CORE_EXPORT InspectorSessionState {
// that are sent back to the browser.
// A null string for |value| indicates a deletion.
// TODO(johannes): Lower cost of repeated updates.
- void EnqueueUpdate(const WTF::String& key, const std::vector<uint8_t>* value);
+ void EnqueueUpdate(const WTF::String& key, const WebVector<uint8_t>* value);
// Yields and consumes the field updates that have thus far accumulated.
// These updates are sent back to DevToolsSession on the browser side.
@@ -50,20 +50,19 @@ class CORE_EXPORT InspectorAgentState {
// these is to be able to call overloaded methods from the template
// implementations below; they just delegate to protocol::Value parsing
// and serialization.
- static void Serialize(bool v, std::vector<uint8_t>* out);
+ static void Serialize(bool v, WebVector<uint8_t>* out);
static bool Deserialize(::inspector_protocol_encoding::span<uint8_t> in,
bool* v);
- static void Serialize(int32_t v, std::vector<uint8_t>* out);
+ static void Serialize(int32_t v, WebVector<uint8_t>* out);
static bool Deserialize(::inspector_protocol_encoding::span<uint8_t> in,
int32_t* v);
- static void Serialize(double v, std::vector<uint8_t>* out);
+ static void Serialize(double v, WebVector<uint8_t>* out);
static bool Deserialize(::inspector_protocol_encoding::span<uint8_t> in,
double* v);
- static void Serialize(const WTF::String& v, std::vector<uint8_t>* out);
+ static void Serialize(const WTF::String& v, WebVector<uint8_t>* out);
static bool Deserialize(::inspector_protocol_encoding::span<uint8_t> in,
WTF::String* v);
- static void Serialize(const std::vector<uint8_t>& v,
- std::vector<uint8_t>* out);
+ static void Serialize(const std::vector<uint8_t>& v, WebVector<uint8_t>* out);
static bool Deserialize(::inspector_protocol_encoding::span<uint8_t> in,
std::vector<uint8_t>* v);
@@ -128,7 +127,7 @@ class CORE_EXPORT InspectorAgentState {
return;
}
value_ = value;
- std::vector<uint8_t> encoded_value;
+ WebVector<uint8_t> encoded_value;
Serialize(value, &encoded_value);
session_state_->EnqueueUpdate(prefix_key_, &encoded_value);
}
@@ -180,10 +179,10 @@ class CORE_EXPORT InspectorAgentState {
// Enumerates the keys for which values are stored in this field.
// The order of the keys is undefined.
- std::vector<WTF::String> Keys() const {
+ Vector<WTF::String> Keys() const {
// TODO(johannes): It'd be nice to avoid copying; unfortunately
// it didn't seem easy to return map_.Keys().
- std::vector<WTF::String> keys;
+ Vector<WTF::String> keys;
for (const WTF::String& s : map_.Keys())
keys.push_back(s);
return keys;
@@ -210,7 +209,7 @@ class CORE_EXPORT InspectorAgentState {
if (it != map_.end() && it->value == value)
return;
map_.Set(key, value);
- std::vector<uint8_t> encoded_value;
+ WebVector<uint8_t> encoded_value;
Serialize(value, &encoded_value);
session_state_->EnqueueUpdate(prefix_key_ + key, &encoded_value);
}
@@ -287,7 +286,7 @@ class CORE_EXPORT InspectorAgentState {
private:
const WTF::String domain_name_;
- std::vector<Field*> fields_;
+ Vector<Field*> fields_;
};
} // 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 dcb657f141e..9b632b8b80d 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
@@ -55,7 +55,7 @@ struct AgentWithSimpleFields {
multiplier_(&agent_state_, /*default_value=*/1.0),
counter_(&agent_state_, /*default_value=*/1),
message_(&agent_state_, /*default_value=*/WTF::String()),
- bytes_(&agent_state_, /*default_value=*/std::vector<uint8_t>()) {}
+ bytes_(&agent_state_, /*default_value=*/{}) {}
InspectorAgentState agent_state_;
InspectorAgentState::Boolean enabled_;
@@ -230,7 +230,7 @@ TEST(InspectorSessionStateTest, MultipleAgents) {
// Show that the keys for the field values are prefixed with the domain name
// passed to AgentState so that the stored values won't collide.
DevToolsSessionStatePtr cookie = dev_tools_session.CloneCookie();
- std::vector<WTF::String> keys;
+ Vector<WTF::String> keys;
for (const WTF::String& k : cookie->entries.Keys())
keys.push_back(k);
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 dda59f9cdf2..5c8dc0d6b6d 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
@@ -55,7 +55,7 @@
#include "third_party/blink/renderer/core/svg/svg_style_element.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#include "third_party/blink/renderer/platform/wtf/text/text_position.h"
@@ -670,7 +670,7 @@ String CanonicalCSSText(CSSRule* rule) {
property_names.push_back(style->item(i));
std::sort(property_names.begin(), property_names.end(),
- WTF::CodePointCompareLessThan);
+ WTF::CodeUnitCompareLessThan);
StringBuilder builder;
builder.Append(style_rule->selectorText());
@@ -802,10 +802,10 @@ void InspectorStyle::PopulateAllProperties(
}
std::unique_ptr<protocol::CSS::CSSStyle> InspectorStyle::StyleWithProperties() {
- std::unique_ptr<Array<protocol::CSS::CSSProperty>> properties_object =
- Array<protocol::CSS::CSSProperty>::create();
- std::unique_ptr<Array<protocol::CSS::ShorthandEntry>> shorthand_entries =
- Array<protocol::CSS::ShorthandEntry>::create();
+ auto properties_object =
+ std::make_unique<protocol::Array<protocol::CSS::CSSProperty>>();
+ auto shorthand_entries =
+ std::make_unique<protocol::Array<protocol::CSS::ShorthandEntry>>();
HashSet<String> found_shorthands;
Vector<CSSPropertySourceData> properties;
@@ -855,11 +855,11 @@ std::unique_ptr<protocol::CSS::CSSStyle> InspectorStyle::StyleWithProperties() {
.build();
if (!style_->getPropertyPriority(name).IsEmpty())
entry->setImportant(true);
- shorthand_entries->addItem(std::move(entry));
+ shorthand_entries->emplace_back(std::move(entry));
}
}
}
- properties_object->addItem(std::move(property));
+ properties_object->emplace_back(std::move(property));
}
std::unique_ptr<protocol::CSS::CSSStyle> result =
@@ -1382,8 +1382,7 @@ bool InspectorStyleSheet::DeleteRule(const SourceRange& range,
std::unique_ptr<protocol::Array<String>>
InspectorStyleSheet::CollectClassNames() {
HashSet<String> unique_names;
- std::unique_ptr<protocol::Array<String>> result =
- protocol::Array<String>::create();
+ auto result = std::make_unique<protocol::Array<String>>();
for (wtf_size_t i = 0; i < parsed_flat_rules_.size(); ++i) {
if (auto* style_rule =
@@ -1391,7 +1390,7 @@ InspectorStyleSheet::CollectClassNames() {
GetClassNamesFromRule(style_rule, unique_names);
}
for (const String& class_name : unique_names)
- result->addItem(class_name);
+ result->emplace_back(class_name);
return result;
}
@@ -1493,8 +1492,7 @@ std::unique_ptr<protocol::Array<protocol::CSS::Value>>
InspectorStyleSheet::SelectorsFromSource(CSSRuleSourceData* source_data,
const String& sheet_text) {
ScriptRegexp comment("/\\*[^]*?\\*/", kTextCaseSensitive, kMultilineEnabled);
- std::unique_ptr<protocol::Array<protocol::CSS::Value>> result =
- protocol::Array<protocol::CSS::Value>::create();
+ auto result = std::make_unique<protocol::Array<protocol::CSS::Value>>();
const Vector<SourceRange>& ranges = source_data->selector_ranges;
for (wtf_size_t i = 0, size = ranges.size(); i < size; ++i) {
const SourceRange& range = ranges.at(i);
@@ -1512,7 +1510,7 @@ InspectorStyleSheet::SelectorsFromSource(CSSRuleSourceData* source_data,
.setText(selector.StripWhiteSpace())
.build();
simple_selector->setRange(BuildSourceRangeObject(range));
- result->addItem(std::move(simple_selector));
+ result->emplace_back(std::move(simple_selector));
}
return result;
}
@@ -1529,13 +1527,14 @@ InspectorStyleSheet::BuildObjectForSelectorList(CSSStyleRule* rule) {
if (source_data) {
selectors = SelectorsFromSource(source_data, text_);
} else {
- selectors = protocol::Array<protocol::CSS::Value>::create();
+ selectors = std::make_unique<protocol::Array<protocol::CSS::Value>>();
const CSSSelectorList& selector_list = rule->GetStyleRule()->SelectorList();
for (const CSSSelector* selector = selector_list.First(); selector;
- selector = CSSSelectorList::Next(*selector))
- selectors->addItem(protocol::CSS::Value::create()
- .setText(selector->SelectorText())
- .build());
+ selector = CSSSelectorList::Next(*selector)) {
+ selectors->emplace_back(protocol::CSS::Value::create()
+ .setText(selector->SelectorText())
+ .build());
+ }
}
return protocol::CSS::SelectorList::create()
.setSelectors(std::move(selectors))
@@ -1858,9 +1857,9 @@ bool InspectorStyleSheet::ResourceStyleSheetText(String* result) {
Element* InspectorStyleSheet::OwnerStyleElement() {
Node* owner_node = page_style_sheet_->ownerNode();
- if (!owner_node || !owner_node->IsElementNode())
+ auto* owner_element = DynamicTo<Element>(owner_node);
+ if (!owner_element)
return nullptr;
- Element* owner_element = ToElement(owner_node);
if (!IsHTMLStyleElement(owner_element) && !IsSVGStyleElement(owner_element))
return nullptr;
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 99dfd378422..467c718798b 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
@@ -5,8 +5,8 @@
#include "third_party/blink/renderer/core/inspector/inspector_task_runner.h"
#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/scheduler/public/post_cross_thread_task.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/inspector/inspector_task_runner.h b/chromium/third_party/blink/renderer/core/inspector/inspector_task_runner.h
index 7dd6706b5cc..e5d164a666d 100644
--- a/chromium/third_party/blink/renderer/core/inspector/inspector_task_runner.h
+++ b/chromium/third_party/blink/renderer/core/inspector/inspector_task_runner.h
@@ -9,7 +9,7 @@
#include "base/single_thread_task_runner.h"
#include "base/thread_annotations.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/deque.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
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 ca1f117c8ec..6d0f4cf7ce8 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
@@ -9,7 +9,7 @@
#include <memory>
#include "cc/layers/picture_layer.h"
-#include "third_party/blink/public/mojom/loader/request_context_frame_type.mojom-shared.h"
+#include "third_party/blink/public/mojom/loader/request_context_frame_type.mojom-blink.h"
#include "third_party/blink/public/platform/web_layer_tree_view.h"
#include "third_party/blink/renderer/bindings/core/v8/script_source_code.h"
#include "third_party/blink/renderer/bindings/core/v8/source_location.h"
@@ -35,7 +35,7 @@
#include "third_party/blink/renderer/core/workers/worker_thread.h"
#include "third_party/blink/renderer/core/xmlhttprequest/xml_http_request.h"
#include "third_party/blink/renderer/platform/graphics/graphics_layer.h"
-#include "third_party/blink/renderer/platform/instance_counters.h"
+#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/traced_value.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_load_priority.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_request.h"
@@ -156,7 +156,7 @@ void InspectorTraceEvents::DidReceiveData(uint64_t identifier,
void InspectorTraceEvents::DidFinishLoading(uint64_t identifier,
DocumentLoader* loader,
- TimeTicks finish_time,
+ base::TimeTicks finish_time,
int64_t encoded_data_length,
int64_t decoded_body_length,
bool should_report_corb_blocking) {
@@ -176,7 +176,7 @@ void InspectorTraceEvents::DidFailLoading(uint64_t identifier,
TRACE_EVENT_INSTANT1("devtools.timeline", "ResourceFinish",
TRACE_EVENT_SCOPE_THREAD, "data",
inspector_resource_finish_event::Data(
- loader, identifier, TimeTicks(), true, 0, 0));
+ loader, identifier, base::TimeTicks(), true, 0, 0));
}
void InspectorTraceEvents::Will(const probe::ExecuteScript&) {}
@@ -682,6 +682,7 @@ const char kAnonymousBlockChange[] = "Anonymous block change";
const char kFullscreen[] = "Fullscreen change";
const char kChildChanged[] = "Child changed";
const char kListValueChange[] = "List value change";
+const char kListStyleTypeChange[] = "List style type change";
const char kImageChanged[] = "Image changed";
const char kLineBoxesChanged[] = "Line boxes changed";
const char kSliderValueChanged[] = "Slider value changed";
@@ -716,19 +717,6 @@ std::unique_ptr<TracedValue> inspector_layout_invalidation_tracking_event::Data(
return value;
}
-std::unique_ptr<TracedValue> inspector_paint_invalidation_tracking_event::Data(
- const LayoutObject& layout_object) {
- auto value = std::make_unique<TracedValue>();
- value->SetString("frame",
- IdentifiersFactory::FrameId(layout_object.GetFrame()));
- const auto* paint_container =
- layout_object.IsRooted() ? &layout_object.ContainerForPaintInvalidation()
- : nullptr;
- SetGeneratingNodeInfo(value.get(), paint_container, "paintId");
- SetGeneratingNodeInfo(value.get(), &layout_object, "nodeId", "nodeName");
- return value;
-}
-
std::unique_ptr<TracedValue> inspector_change_resource_priority_event::Data(
DocumentLoader* loader,
uint64_t identifier,
@@ -853,7 +841,7 @@ std::unique_ptr<TracedValue> inspector_receive_data_event::Data(
std::unique_ptr<TracedValue> inspector_resource_finish_event::Data(
DocumentLoader* loader,
uint64_t identifier,
- TimeTicks finish_time,
+ base::TimeTicks finish_time,
bool did_fail,
int64_t encoded_data_length,
int64_t decoded_body_length) {
@@ -887,7 +875,7 @@ static std::unique_ptr<TracedValue> GenericTimerData(ExecutionContext* context,
std::unique_ptr<TracedValue> inspector_timer_install_event::Data(
ExecutionContext* context,
int timer_id,
- TimeDelta timeout,
+ base::TimeDelta timeout,
bool single_shot) {
std::unique_ptr<TracedValue> value = GenericTimerData(context, timer_id);
value->SetDouble("timeout", timeout.InMillisecondsF());
@@ -1008,35 +996,6 @@ static void LocalToPageQuad(const LayoutObject& layout_object,
quad->SetP4(LocalCoordToFloatPoint(view, absolute.P4()));
}
-const char inspector_layer_invalidation_tracking_event::
- kSquashingLayerGeometryWasUpdated[] =
- "Squashing layer geometry was updated";
-const char
- 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
- 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> inspector_layer_invalidation_tracking_event::Data(
- const PaintLayer* layer,
- const char* reason) {
- const LayoutObject& paint_invalidation_container =
- layer->GetLayoutObject().ContainerForPaintInvalidation();
-
- auto value = std::make_unique<TracedValue>();
- value->SetString("frame", IdentifiersFactory::FrameId(
- paint_invalidation_container.GetFrame()));
- SetGeneratingNodeInfo(value.get(), &paint_invalidation_container, "paintId");
- value->SetString("reason", reason);
- return value;
-}
-
std::unique_ptr<TracedValue> inspector_paint_event::Data(
LayoutObject* layout_object,
const PhysicalRect& clip_rect,
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 414a6933f00..a1a9977d7b8 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
@@ -60,7 +60,6 @@ class LayoutObject;
class LocalFrame;
class LocalFrameView;
class Node;
-class PaintLayer;
struct PhysicalRect;
class QualifiedName;
class Resource;
@@ -105,7 +104,7 @@ class CORE_EXPORT InspectorTraceEvents
uint64_t data_length);
void DidFinishLoading(uint64_t identifier,
DocumentLoader*,
- TimeTicks monotonic_finish_time,
+ base::TimeTicks monotonic_finish_time,
int64_t encoded_data_length,
int64_t decoded_body_length,
bool should_report_corb_blocking);
@@ -228,6 +227,7 @@ extern const char kAnonymousBlockChange[];
extern const char kFullscreen[];
extern const char kChildChanged[];
extern const char kListValueChange[];
+extern const char kListStyleTypeChange[];
extern const char kImageChanged[];
extern const char kLineBoxesChanged[];
extern const char kSliderValueChanged[];
@@ -260,10 +260,6 @@ std::unique_ptr<TracedValue> CORE_EXPORT
Data(const LayoutObject*, LayoutInvalidationReasonForTracing);
}
-namespace inspector_paint_invalidation_tracking_event {
-std::unique_ptr<TracedValue> Data(const LayoutObject&);
-}
-
namespace inspector_change_resource_priority_event {
std::unique_ptr<TracedValue> Data(DocumentLoader*,
uint64_t identifier,
@@ -302,7 +298,7 @@ std::unique_ptr<TracedValue> Data(DocumentLoader*,
namespace inspector_resource_finish_event {
std::unique_ptr<TracedValue> Data(DocumentLoader*,
uint64_t identifier,
- TimeTicks finish_time,
+ base::TimeTicks finish_time,
bool did_fail,
int64_t encoded_data_length,
int64_t decoded_body_length);
@@ -311,7 +307,7 @@ std::unique_ptr<TracedValue> Data(DocumentLoader*,
namespace inspector_timer_install_event {
std::unique_ptr<TracedValue> Data(ExecutionContext*,
int timer_id,
- TimeDelta timeout,
+ base::TimeDelta timeout,
bool single_shot);
}
@@ -354,22 +350,6 @@ namespace inspector_xhr_load_event {
std::unique_ptr<TracedValue> Data(ExecutionContext*, XMLHttpRequest*);
}
-namespace inspector_layer_invalidation_tracking_event {
-extern const char kSquashingLayerGeometryWasUpdated[];
-extern const char kAddedToSquashingLayer[];
-extern const char kRemovedFromSquashingLayer[];
-extern const char kReflectionLayerChanged[];
-extern const char kNewCompositedLayer[];
-
-std::unique_ptr<TracedValue> Data(const PaintLayer*, const char* reason);
-} // 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", \
- inspector_layer_invalidation_tracking_event::Data((LAYER), (REASON)));
-
namespace inspector_paint_event {
std::unique_ptr<TracedValue> Data(LayoutObject*,
const PhysicalRect& clip_rect,
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 672e62d1172..08425de5a3b 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
@@ -51,7 +51,6 @@
#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"
-#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/inspector/console_message_storage.h"
#include "third_party/blink/renderer/core/inspector/identifiers_factory.h"
@@ -64,6 +63,7 @@
#include "third_party/blink/renderer/core/xml/xpath_evaluator.h"
#include "third_party/blink/renderer/core/xml/xpath_result.h"
#include "third_party/blink/renderer/platform/bindings/dom_wrapper_world.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#include "third_party/blink/renderer/platform/wtf/threading_primitives.h"
diff --git a/chromium/third_party/blink/renderer/core/inspector/protocol_parser_test.cc b/chromium/third_party/blink/renderer/core/inspector/protocol_parser_test.cc
index 259f6778243..2f6d31bcff7 100644
--- a/chromium/third_party/blink/renderer/core/inspector/protocol_parser_test.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/protocol_parser_test.cc
@@ -333,7 +333,7 @@ TEST(ProtocolParserTest, Reading) {
" \"S\":\"str\"\n"
"}\n");
ASSERT_TRUE(root2.get());
- EXPECT_EQ(root->serializeToJSON(), root2->serializeToJSON());
+ EXPECT_EQ(root->toJSONString(), root2->toJSONString());
root2 = ParseJSON(
"{\r\n"
@@ -342,7 +342,7 @@ TEST(ProtocolParserTest, Reading) {
" \"S\":\"str\"\r\n"
"}\r\n");
ASSERT_TRUE(root2.get());
- EXPECT_EQ(root->serializeToJSON(), root2->serializeToJSON());
+ EXPECT_EQ(root->toJSONString(), root2->toJSONString());
// Test nesting
root = ParseJSON("{\"inner\":{\"array\":[true]},\"false\":false,\"d\":{}}");
diff --git a/chromium/third_party/blink/renderer/core/inspector/protocol_unittest.cc b/chromium/third_party/blink/renderer/core/inspector/protocol_unittest.cc
index 376c836c616..017e00a7acd 100644
--- a/chromium/third_party/blink/renderer/core/inspector/protocol_unittest.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/protocol_unittest.cc
@@ -4,7 +4,6 @@
#include "third_party/blink/renderer/core/inspector/v8_inspector_string.h"
-#include <vector>
#include "testing/gtest/include/gtest/gtest.h"
namespace blink {
@@ -16,9 +15,9 @@ TEST(ProtocolBinaryTest, base64EmptyArgs) {
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()));
+ Vector<uint8_t> decoded_bytes;
+ decoded_bytes.Append(decoded.data(), decoded.size());
+ EXPECT_EQ(Vector<uint8_t>(), decoded_bytes);
}
TEST(ProtocolStringTest, AllBytesBase64Roundtrip) {
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 e247b3756cc..de227eb55f8 100644
--- a/chromium/third_party/blink/renderer/core/inspector/thread_debugger.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/thread_debugger.cc
@@ -190,7 +190,7 @@ bool ThreadDebugger::formatAccessorsAsProperties(v8::Local<v8::Value> value) {
}
double ThreadDebugger::currentTimeMS() {
- return WTF::CurrentTimeMS();
+ return base::Time::Now().ToDoubleT() * 1000.0;
}
bool ThreadDebugger::isInspectableHeapObject(v8::Local<v8::Object> object) {
@@ -460,14 +460,14 @@ void ThreadDebugger::consoleTime(const v8_inspector::StringView& title) {
// TODO(dgozman): we can save on a copy here if trace macro would take a
// pointer with length.
TRACE_EVENT_COPY_ASYNC_BEGIN0("blink.console",
- ToCoreString(title).Utf8().data(), this);
+ ToCoreString(title).Utf8().c_str(), this);
}
void ThreadDebugger::consoleTimeEnd(const v8_inspector::StringView& title) {
// TODO(dgozman): we can save on a copy here if trace macro would take a
// pointer with length.
TRACE_EVENT_COPY_ASYNC_END0("blink.console",
- ToCoreString(title).Utf8().data(), this);
+ ToCoreString(title).Utf8().c_str(), this);
}
void ThreadDebugger::consoleTimeStamp(const v8_inspector::StringView& title) {
@@ -493,7 +493,7 @@ void ThreadDebugger::startRepeatingTimer(
&ThreadDebugger::OnTimer);
TaskRunnerTimer<ThreadDebugger>* timer_ptr = timer.get();
timers_.push_back(std::move(timer));
- timer_ptr->StartRepeating(TimeDelta::FromSecondsD(interval), FROM_HERE);
+ timer_ptr->StartRepeating(base::TimeDelta::FromSecondsD(interval), FROM_HERE);
}
void ThreadDebugger::cancelTimer(void* data) {
diff --git a/chromium/third_party/blink/renderer/core/inspector/thread_debugger.h b/chromium/third_party/blink/renderer/core/inspector/thread_debugger.h
index 8d0345db9a7..7adb02fcbea 100644
--- a/chromium/third_party/blink/renderer/core/inspector/thread_debugger.h
+++ b/chromium/third_party/blink/renderer/core/inspector/thread_debugger.h
@@ -7,12 +7,12 @@
#include <memory>
#include "base/macros.h"
-#include "third_party/blink/public/mojom/devtools/console_message.mojom-shared.h"
+#include "third_party/blink/public/mojom/devtools/console_message.mojom-blink.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/dom/user_gesture_indicator.h"
#include "third_party/blink/renderer/platform/bindings/v8_per_isolate_data.h"
-#include "third_party/blink/renderer/platform/cross_thread_copier.h"
#include "third_party/blink/renderer/platform/timer.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_copier.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
#include "v8/include/v8-inspector.h"
@@ -118,12 +118,16 @@ class CORE_EXPORT ThreadDebugger : public v8_inspector::V8InspectorClient,
DISALLOW_COPY_AND_ASSIGN(ThreadDebugger);
};
+} // namespace blink
+
+namespace WTF {
+
template <>
struct CrossThreadCopier<v8_inspector::V8StackTraceId> {
typedef v8_inspector::V8StackTraceId Type;
static Type Copy(const Type& id) { return id; }
};
-} // namespace blink
+} // namespace WTF
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_INSPECTOR_THREAD_DEBUGGER_H_
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 83f403fcbee..b18130a61ab 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
@@ -66,7 +66,7 @@ ProtocolMessage StringUtil::jsonToMessage(const String& message) {
}
// static
-ProtocolMessage StringUtil::binaryToMessage(std::vector<uint8_t> message) {
+ProtocolMessage StringUtil::binaryToMessage(WebVector<uint8_t> message) {
ProtocolMessage result;
result.binary = std::move(message);
return result;
@@ -91,7 +91,8 @@ void StringUtil::builderAppendQuotedString(StringBuilder& builder,
}
// static
-String StringUtil::fromUTF16(const uint16_t* data, size_t length) {
+String StringUtil::fromUTF16LE(const uint16_t* data, size_t length) {
+ // Chromium doesn't support big endian architectures, so it's OK to cast here.
return String(reinterpret_cast<const UChar*>(data), length);
}
@@ -99,7 +100,7 @@ namespace {
class BinaryBasedOnSharedBuffer : public Binary::Impl {
public:
explicit BinaryBasedOnSharedBuffer(scoped_refptr<SharedBuffer> buffer)
- : buffer_(buffer) {}
+ : buffer_(std::move(buffer)) {}
const uint8_t* data() const override {
return reinterpret_cast<const uint8_t*>(buffer_->Data());
@@ -139,9 +140,7 @@ class BinaryBasedOnCachedData : public Binary::Impl {
} // namespace
String Binary::toBase64() const {
- return impl_ ? WTF::Base64Encode(reinterpret_cast<const char*>(impl_->data()),
- impl_->size())
- : String();
+ return impl_ ? Base64Encode(*impl_) : String();
}
// static
@@ -154,7 +153,8 @@ Binary Binary::fromBase64(const String& base64, bool* success) {
// static
Binary Binary::fromSharedBuffer(scoped_refptr<SharedBuffer> buffer) {
- return Binary(base::AdoptRef(new BinaryBasedOnSharedBuffer(buffer)));
+ return Binary(
+ base::AdoptRef(new BinaryBasedOnSharedBuffer(std::move(buffer))));
}
// static
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 cd07f3b2b13..bbd05c2dbfd 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
@@ -6,11 +6,11 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_INSPECTOR_V8_INSPECTOR_STRING_H_
#include <memory>
-#include <vector>
+#include "third_party/blink/public/platform/web_vector.h"
#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/allocator/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"
@@ -41,7 +41,7 @@ using StringBuilder = WTF::StringBuilder;
struct ProtocolMessage {
String json;
- std::vector<uint8_t> binary;
+ WebVector<uint8_t> binary;
};
class CORE_EXPORT StringUtil {
@@ -84,13 +84,13 @@ class CORE_EXPORT StringUtil {
}
static std::unique_ptr<protocol::Value> parseJSON(const String&);
static ProtocolMessage jsonToMessage(const String& message);
- static ProtocolMessage binaryToMessage(std::vector<uint8_t> message);
+ static ProtocolMessage binaryToMessage(WebVector<uint8_t> message);
static String fromUTF8(const uint8_t* data, size_t length) {
return String::FromUTF8(reinterpret_cast<const char*>(data), length);
}
- static String fromUTF16(const uint16_t* data, size_t length);
+ static String fromUTF16LE(const uint16_t* data, size_t length);
static const uint8_t* CharactersLatin1(const String& s) {
if (!s.Is8Bit())
@@ -134,7 +134,7 @@ class CORE_EXPORT Binary {
std::unique_ptr<v8::ScriptCompiler::CachedData> data);
private:
- explicit Binary(scoped_refptr<Impl> impl) : impl_(impl) {}
+ explicit Binary(scoped_refptr<Impl> impl) : impl_(std::move(impl)) {}
scoped_refptr<Impl> impl_;
};
} // namespace protocol
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 b62bdb1425b..6c0f6ce6088 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
@@ -46,7 +46,6 @@
#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/runtime_enabled_features.h"
-#include "third_party/blink/renderer/platform/web_thread_supporting_gc.h"
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 b9e5efcc3c8..4014ad57e06 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
@@ -41,7 +41,7 @@
#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/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/inspector/worker_thread_debugger.cc b/chromium/third_party/blink/renderer/core/inspector/worker_thread_debugger.cc
index 1af4bdb5987..a493c370b18 100644
--- a/chromium/third_party/blink/renderer/core/inspector/worker_thread_debugger.cc
+++ b/chromium/third_party/blink/renderer/core/inspector/worker_thread_debugger.cc
@@ -45,6 +45,7 @@
#include "third_party/blink/renderer/core/workers/worker_thread.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/bindings/v8_per_isolate_data.h"
+#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "v8/include/v8.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/inspector/worker_thread_debugger.h b/chromium/third_party/blink/renderer/core/inspector/worker_thread_debugger.h
index 8b94febadea..0730ec7119d 100644
--- a/chromium/third_party/blink/renderer/core/inspector/worker_thread_debugger.h
+++ b/chromium/third_party/blink/renderer/core/inspector/worker_thread_debugger.h
@@ -38,6 +38,7 @@
namespace blink {
class ErrorEvent;
+class KURL;
class SourceLocation;
class WorkerThread;
diff --git a/chromium/third_party/blink/renderer/core/intersection_observer/intersection_geometry.cc b/chromium/third_party/blink/renderer/core/intersection_observer/intersection_geometry.cc
index af92219b21b..402133b8937 100644
--- a/chromium/third_party/blink/renderer/core/intersection_observer/intersection_geometry.cc
+++ b/chromium/third_party/blink/renderer/core/intersection_observer/intersection_geometry.cc
@@ -69,7 +69,7 @@ bool ComputeIsVisible(LayoutObject* target, const PhysicalRect& rect) {
// TODO(layout-dev): This should hit-test the intersection rect, not the
// target rect; it's not helpful to know that the portion of the target that
// is clipped is also occluded.
- HitTestResult result(target->HitTestForOcclusion(rect.ToLayoutRect()));
+ HitTestResult result(target->HitTestForOcclusion(rect));
Node* hit_node = result.InnerNode();
if (!hit_node || hit_node == target->GetNode())
return true;
@@ -276,7 +276,8 @@ bool IntersectionGeometry::ClipToRoot(LayoutObject* root,
return does_intersect;
if (local_ancestor->HasOverflowClip()) {
intersection_rect.Move(
- -PhysicalOffset(local_ancestor->ScrolledContentOffset()));
+ -PhysicalOffset(LayoutPoint(local_ancestor->ScrollOrigin()) +
+ local_ancestor->ScrolledContentOffset()));
}
LayoutRect root_clip_rect = root_rect.ToLayoutRect();
// TODO(szager): This flipping seems incorrect because root_rect is already
diff --git a/chromium/third_party/blink/renderer/core/intersection_observer/intersection_observer.idl b/chromium/third_party/blink/renderer/core/intersection_observer/intersection_observer.idl
index b53d71e18c2..f96388ff449 100644
--- a/chromium/third_party/blink/renderer/core/intersection_observer/intersection_observer.idl
+++ b/chromium/third_party/blink/renderer/core/intersection_observer/intersection_observer.idl
@@ -2,13 +2,12 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// https://wicg.github.io/IntersectionObserver/#intersection-observer-callback
+// https://www.w3.org/TR/intersection-observer/#intersection-observer-interface
callback IntersectionObserverCallback = void (sequence<IntersectionObserverEntry> entries, IntersectionObserver observer);
-// https://wicg.github.io/IntersectionObserver/#intersection-observer-interface
-
[
+ Exposed=Window,
ActiveScriptWrappable,
Constructor(IntersectionObserverCallback callback, optional IntersectionObserverInit options),
ConstructorCallWith=ScriptState,
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 0fe8f35099b..1da67bf97d7 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
@@ -69,7 +69,7 @@ void IntersectionObserverController::DeliverIntersectionObservations(
bool IntersectionObserverController::ComputeTrackedIntersectionObservations(
unsigned flags) {
- bool needs_occlusion_tracking = false;
+ needs_occlusion_tracking_ = false;
if (Document* document = To<Document>(GetExecutionContext())) {
TRACE_EVENT0("blink",
"IntersectionObserverController::"
@@ -77,11 +77,11 @@ bool IntersectionObserverController::ComputeTrackedIntersectionObservations(
HeapVector<Member<Element>> elements_to_process;
CopyToVector(tracked_observation_targets_, elements_to_process);
for (auto& element : elements_to_process) {
- needs_occlusion_tracking |=
+ needs_occlusion_tracking_ |=
element->ComputeIntersectionObservations(flags);
}
}
- return needs_occlusion_tracking;
+ return needs_occlusion_tracking_;
}
void IntersectionObserverController::AddTrackedTarget(Element& target,
@@ -89,6 +89,7 @@ void IntersectionObserverController::AddTrackedTarget(Element& target,
tracked_observation_targets_.insert(&target);
if (!track_occlusion)
return;
+ needs_occlusion_tracking_ = true;
if (LocalFrameView* frame_view = target.GetDocument().View()) {
if (FrameOwner* frame_owner = frame_view->GetFrame().Owner()) {
// Set this bit as early as possible, rather than waiting for a lifecycle
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 516756a5cd7..7986f188951 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
@@ -45,6 +45,7 @@ class IntersectionObserverController
// observers for which observer->trackVisibility() is true.
void AddTrackedTarget(Element&, bool);
void RemoveTrackedTarget(Element&);
+ bool NeedsOcclusionTracking() const { return needs_occlusion_tracking_; }
void Trace(blink::Visitor*) override;
const char* NameInHeapSnapshot() const override {
@@ -68,6 +69,9 @@ class IntersectionObserverController
// get supported by either of wrapper-tracing or unified GC.
HeapVector<Member<IntersectionObserver>>
intersection_observers_being_invoked_;
+ // This is 'true' if any tracked observation target is being tracked by an
+ // observer for which observer->trackVisibility() is true.
+ bool needs_occlusion_tracking_;
};
} // namespace blink
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 cdee296105c..315bf0d6f06 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
@@ -304,7 +304,7 @@ TEST_F(IntersectionObserverTest, HitTestAfterMutation) {
GetDocument().View()->LayoutViewport()->SetScrollOffset(ScrollOffset(0, 300),
kProgrammaticScroll);
- HitTestLocation location(LayoutPoint(0, 0));
+ HitTestLocation location{PhysicalOffset()};
HitTestResult result(
HitTestRequest(HitTestRequest::kReadOnly | HitTestRequest::kActive |
HitTestRequest::kAllowChildFrameContent),
diff --git a/chromium/third_party/blink/renderer/core/invisible_dom/invisible_dom.cc b/chromium/third_party/blink/renderer/core/invisible_dom/invisible_dom.cc
index dc133704acf..2114664a489 100644
--- a/chromium/third_party/blink/renderer/core/invisible_dom/invisible_dom.cc
+++ b/chromium/third_party/blink/renderer/core/invisible_dom/invisible_dom.cc
@@ -15,8 +15,8 @@ bool InvisibleDOM::IsInsideInvisibleSubtree(const Node& node) {
if (!node.CanParticipateInFlatTree())
return false;
for (Node& ancestor : FlatTreeTraversal::InclusiveAncestorsOf(node)) {
- if (ancestor.IsElementNode() &&
- ToElement(ancestor).HasInvisibleAttribute()) {
+ auto* element = DynamicTo<Element>(ancestor);
+ if (element && element->HasInvisibleAttribute()) {
return true;
}
}
@@ -28,9 +28,9 @@ Element* InvisibleDOM::InvisibleRoot(const Node& node) {
return nullptr;
Element* root = nullptr;
for (Node& ancestor : FlatTreeTraversal::InclusiveAncestorsOf(node)) {
- if (ancestor.IsElementNode() &&
- ToElement(ancestor).HasInvisibleAttribute()) {
- root = &ToElement(ancestor);
+ auto* element = DynamicTo<Element>(ancestor);
+ if (element && element->HasInvisibleAttribute()) {
+ root = element;
}
}
return root;
@@ -47,8 +47,9 @@ bool InvisibleDOM::ActivateRangeIfNeeded(
if (!InvisibleDOM::IsInsideInvisibleSubtree(node))
continue;
for (Node& ancestor_node : FlatTreeTraversal::AncestorsOf(node)) {
- if (ancestor_node.IsElementNode()) {
- elements_to_activate.push_back(ToElement(ancestor_node));
+ auto* element = DynamicTo<Element>(ancestor_node);
+ if (element) {
+ elements_to_activate.push_back(element);
break;
}
}
diff --git a/chromium/third_party/blink/renderer/core/invisible_dom/invisible_dom.h b/chromium/third_party/blink/renderer/core/invisible_dom/invisible_dom.h
index 33e87e4c240..ece89ccd185 100644
--- a/chromium/third_party/blink/renderer/core/invisible_dom/invisible_dom.h
+++ b/chromium/third_party/blink/renderer/core/invisible_dom/invisible_dom.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/editing/ephemeral_range.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/BUILD.gn b/chromium/third_party/blink/renderer/core/layout/BUILD.gn
index 1b36cc86ca2..b3cfd30f60a 100644
--- a/chromium/third_party/blink/renderer/core/layout/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/layout/BUILD.gn
@@ -107,10 +107,6 @@ blink_core_sources("layout") {
"hit_testing_transform_state.cc",
"hit_testing_transform_state.h",
"intrinsic_sizing_info.h",
- "jank_region.cc",
- "jank_region.h",
- "jank_tracker.cc",
- "jank_tracker.h",
"layout_analyzer.cc",
"layout_analyzer.h",
"layout_block.cc",
@@ -210,6 +206,10 @@ blink_core_sources("layout") {
"layout_scrollbar_theme.h",
"layout_search_field.cc",
"layout_search_field.h",
+ "layout_shift_region.cc",
+ "layout_shift_region.h",
+ "layout_shift_tracker.cc",
+ "layout_shift_tracker.h",
"layout_slider.cc",
"layout_slider.h",
"layout_slider_container.cc",
@@ -318,7 +318,6 @@ blink_core_sources("layout") {
"ng/geometry/ng_fragment_geometry.h",
"ng/geometry/ng_margin_strut.cc",
"ng/geometry/ng_margin_strut.h",
- "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",
@@ -349,7 +348,6 @@ blink_core_sources("layout") {
"ng/inline/ng_inline_item_result.h",
"ng/inline/ng_inline_item_segment.cc",
"ng/inline/ng_inline_item_segment.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",
@@ -386,6 +384,8 @@ blink_core_sources("layout") {
"ng/layout_box_utils.h",
"ng/layout_ng_block_flow.cc",
"ng/layout_ng_block_flow.h",
+ "ng/layout_ng_block_flow_mixin.cc",
+ "ng/layout_ng_block_flow_mixin.h",
"ng/layout_ng_fieldset.cc",
"ng/layout_ng_fieldset.h",
"ng/layout_ng_flexible_box.cc",
@@ -455,7 +455,7 @@ blink_core_sources("layout") {
"ng/ng_link.h",
"ng/ng_out_of_flow_layout_part.cc",
"ng/ng_out_of_flow_layout_part.h",
- "ng/ng_out_of_flow_positioned_descendant.h",
+ "ng/ng_out_of_flow_positioned_node.h",
"ng/ng_outline_type.h",
"ng/ng_outline_utils.cc",
"ng/ng_outline_utils.h",
diff --git a/chromium/third_party/blink/renderer/core/layout/README.md b/chromium/third_party/blink/renderer/core/layout/README.md
index 7b2723b769a..4a30ad5dc73 100644
--- a/chromium/third_party/blink/renderer/core/layout/README.md
+++ b/chromium/third_party/blink/renderer/core/layout/README.md
@@ -1,3 +1,8 @@
+<!---
+ The live version of this document can be viewed at:
+ https://chromium.googlesource.com/chromium/src/+/master/third_party/blink/renderer/core/layout/README.md
+-->
+
# Blink Layout
The `Source/core/layout` directory contains the implementation of layout objects.
@@ -150,8 +155,8 @@ the box (the vertical scrollbar is the `|/|` part):
## Coordinate Spaces
-Layout and Paint work with and frequently refer to three main coordinate spaces
-(really two, with one variant):
+Layout and Paint work with and frequently refer to four coordinate spaces
+(really two, with two variants):
* Physical coordinates: Corresponds to physical direction of the output per the
physical display (screen, printed page). Generally used for painting, thus
@@ -180,6 +185,10 @@ Layout and Paint work with and frequently refer to three main coordinate spaces
look up the writing mode of an object. Performing computation on values known
to be in this space can save on the overhead required to unflip/reflip.
+* Logical coordinates without flipping inline direction: those are "logical
+ block coordinates", without considering text direction. Examples are
+ "LogicalLeft" and "LogicalRight".
+
Example with `writing-mode: vertical-rl; direction: ltr`:
'top' / 'start' side
diff --git a/chromium/third_party/blink/renderer/core/layout/api/line_layout_api_shim.h b/chromium/third_party/blink/renderer/core/layout/api/line_layout_api_shim.h
index 1453c77b44f..b06d6a3643e 100644
--- a/chromium/third_party/blink/renderer/core/layout/api/line_layout_api_shim.h
+++ b/chromium/third_party/blink/renderer/core/layout/api/line_layout_api_shim.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_API_LINE_LAYOUT_API_SHIM_H_
#include "third_party/blink/renderer/core/layout/api/line_layout_item.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.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 4b1bcadb02f..0bda2210bb5 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
@@ -122,6 +122,11 @@ class LineLayoutBlockFlow : public LineLayoutBox {
*ToLayoutBox(box.GetLayoutObject()));
}
+ FloatingObject* LastPlacedFloat(
+ FloatingObjectSetIterator* iterator = nullptr) const {
+ return ToBlockFlow()->LastPlacedFloat(iterator);
+ }
+
bool PlaceNewFloats(LayoutUnit logical_top_margin_edge, LineWidth* width) {
return ToBlockFlow()->PlaceNewFloats(logical_top_margin_edge, width);
}
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 1983f2c26e5..2b04d32da86 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
@@ -29,6 +29,9 @@ class LineLayoutBox : public LineLayoutBoxModel {
LineLayoutBox() = default;
LayoutPoint Location() const { return ToBox()->Location(); }
+ PhysicalOffset PhysicalLocation() const {
+ return ToBox()->PhysicalLocation();
+ }
LayoutSize Size() const { return ToBox()->Size(); }
@@ -52,12 +55,6 @@ class LineLayoutBox : public LineLayoutBoxModel {
return ToBox()->DeprecatedFlipForWritingMode(point);
}
- LayoutPoint FlipForWritingModeForChild(const LineLayoutBox& child,
- LayoutPoint child_point) const {
- return ToBox()->FlipForWritingModeForChild(
- ToLayoutBox(child.GetLayoutObject()), child_point);
- }
-
void MoveWithEdgeOfInlineContainerIfNecessary(bool is_horizontal) {
ToBox()->MoveWithEdgeOfInlineContainerIfNecessary(is_horizontal);
}
@@ -81,7 +78,7 @@ class LineLayoutBox : public LineLayoutBoxModel {
void SetSize(const LayoutSize& size) { return ToBox()->SetSize(size); }
- IntSize ScrolledContentOffset() const {
+ LayoutSize ScrolledContentOffset() const {
return ToBox()->ScrolledContentOffset();
}
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 3099fb2dd32..ab9d90cc19a 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
@@ -66,9 +66,9 @@ class LineLayoutInline : public LineLayoutBoxModel {
LineBoxList* LineBoxes() { return ToInline()->MutableLineBoxes(); }
bool HitTestCulledInline(HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset) {
- return ToInline()->HitTestCulledInline(result, location_in_container,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset) {
+ return ToInline()->HitTestCulledInline(result, hit_test_location,
accumulated_offset);
}
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 dfe2be0f85d..f3c8d5a489e 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
@@ -12,7 +12,7 @@
#include "third_party/blink/renderer/core/paint/object_paint_invalidator.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/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_table_deleted_value_type.h"
namespace blink {
@@ -81,7 +81,7 @@ class LineLayoutItem {
return layout_object_->IsDescendantOf(item.layout_object_);
}
- void UpdateHitTestResult(HitTestResult& result, const LayoutPoint& point) {
+ void UpdateHitTestResult(HitTestResult& result, const PhysicalOffset& point) {
return layout_object_->UpdateHitTestResult(result, point);
}
@@ -234,9 +234,9 @@ class LineLayoutItem {
}
bool HitTestAllPhases(HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset) {
- return layout_object_->HitTestAllPhases(result, location_in_container,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset) {
+ return layout_object_->HitTestAllPhases(result, hit_test_location,
accumulated_offset);
}
@@ -256,7 +256,7 @@ class LineLayoutItem {
// TODO(dgrogan/eae): Can we change this to GlobalToLocal and vice versa
// instead of having 4 methods? See localToAbsoluteQuad below.
- PositionWithAffinity PositionForPoint(const LayoutPoint& point) {
+ PositionWithAffinity PositionForPoint(const PhysicalOffset& point) {
return layout_object_->PositionForPoint(point);
}
diff --git a/chromium/third_party/blink/renderer/core/layout/collapsed_border_value.h b/chromium/third_party/blink/renderer/core/layout/collapsed_border_value.h
index 6eefa76cf7c..36e20d7b0af 100644
--- a/chromium/third_party/blink/renderer/core/layout/collapsed_border_value.h
+++ b/chromium/third_party/blink/renderer/core/layout/collapsed_border_value.h
@@ -30,7 +30,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/platform/geometry/layout_rect.h"
#include "third_party/blink/renderer/platform/graphics/color.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/column_balancer.h b/chromium/third_party/blink/renderer/core/layout/column_balancer.h
index f77cb7a7e4d..f0c3827fd9e 100644
--- a/chromium/third_party/blink/renderer/core/layout/column_balancer.h
+++ b/chromium/third_party/blink/renderer/core/layout/column_balancer.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_COLUMN_BALANCER_H_
#include "third_party/blink/renderer/core/layout/layout_multi_column_set.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/counter_node.h b/chromium/third_party/blink/renderer/core/layout/counter_node.h
index 8ef81400876..5388c8bf27b 100644
--- a/chromium/third_party/blink/renderer/core/layout/counter_node.h
+++ b/chromium/third_party/blink/renderer/core/layout/counter_node.h
@@ -22,7 +22,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_COUNTER_NODE_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_COUNTER_NODE_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.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/layout/custom/layout_worklet_global_scope.cc b/chromium/third_party/blink/renderer/core/layout/custom/layout_worklet_global_scope.cc
index 1eb519d0445..1fb34688a59 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
@@ -11,6 +11,7 @@
#include "third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.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/execution_context/agent.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"
@@ -44,7 +45,13 @@ LayoutWorkletGlobalScope::LayoutWorkletGlobalScope(
std::unique_ptr<GlobalScopeCreationParams> creation_params,
WorkerReportingProxy& reporting_proxy,
PendingLayoutRegistry* pending_layout_registry)
- : WorkletGlobalScope(std::move(creation_params), reporting_proxy, frame),
+ : WorkletGlobalScope(std::move(creation_params),
+ reporting_proxy,
+ frame,
+ // Enable a separate microtask queue for LayoutWorklet.
+ // TODO(yutak): Set agent for all worklets and workers,
+ // not just LayoutWorklet.
+ Agent::CreateForWorkerOrWorklet(ToIsolate(frame))),
pending_layout_registry_(pending_layout_registry) {}
LayoutWorkletGlobalScope::~LayoutWorkletGlobalScope() = default;
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 10868d995e1..7dd44d8795a 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
@@ -60,7 +60,7 @@ LayoutWorkletGlobalScopeProxy::LayoutWorkletGlobalScopeProxy(
void LayoutWorkletGlobalScopeProxy::FetchAndInvokeScript(
const KURL& module_url_record,
- network::mojom::FetchCredentialsMode credentials_mode,
+ network::mojom::CredentialsMode credentials_mode,
const FetchClientSettingsObjectSnapshot& outside_settings_object,
WorkerResourceTimingNotifier& outside_resource_timing_notifier,
scoped_refptr<base::SingleThreadTaskRunner> outside_settings_task_runner,
diff --git a/chromium/third_party/blink/renderer/core/layout/custom/layout_worklet_global_scope_proxy.h b/chromium/third_party/blink/renderer/core/layout/custom/layout_worklet_global_scope_proxy.h
index 6e9c6befbe1..ed8e228f078 100644
--- a/chromium/third_party/blink/renderer/core/layout/custom/layout_worklet_global_scope_proxy.h
+++ b/chromium/third_party/blink/renderer/core/layout/custom/layout_worklet_global_scope_proxy.h
@@ -34,7 +34,7 @@ class CORE_EXPORT LayoutWorkletGlobalScopeProxy
// Implements WorkletGlobalScopeProxy.
void FetchAndInvokeScript(
const KURL& module_url_record,
- network::mojom::FetchCredentialsMode,
+ network::mojom::CredentialsMode,
const FetchClientSettingsObjectSnapshot& outside_settings_object,
WorkerResourceTimingNotifier& outside_resource_timing_notifier,
scoped_refptr<base::SingleThreadTaskRunner> outside_settings_task_runner,
diff --git a/chromium/third_party/blink/renderer/core/layout/depth_ordered_layout_object_list.h b/chromium/third_party/blink/renderer/core/layout/depth_ordered_layout_object_list.h
index 956df4be7e2..3b116f3d624 100644
--- a/chromium/third_party/blink/renderer/core/layout/depth_ordered_layout_object_list.h
+++ b/chromium/third_party/blink/renderer/core/layout/depth_ordered_layout_object_list.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_DEPTH_ORDERED_LAYOUT_OBJECT_LIST_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_DEPTH_ORDERED_LAYOUT_OBJECT_LIST_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
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 d4cf2cfbc94..aedbf18050c 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
@@ -40,7 +40,7 @@
#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/geometry/layout_unit.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
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 3db8f737b5f..1fe5923973b 100644
--- a/chromium/third_party/blink/renderer/core/layout/floating_objects.cc
+++ b/chromium/third_party/blink/renderer/core/layout/floating_objects.cc
@@ -449,13 +449,16 @@ void FloatingObjects::SetCachedLowestFloatLogicalBottom(
lowest_float_bottom_cache_[float_index].dirty = false;
}
-FloatingObject* FloatingObjects::LowestFloatingObject() const {
+FloatingObject* FloatingObjects::LowestFloatingObject() {
bool is_in_horizontal_writing_mode = horizontal_writing_mode_;
+
+ // If we haven't yet found our lowest float, calculate it now:
if (!HasLowestFloatLogicalBottomCached(is_in_horizontal_writing_mode,
FloatingObject::kFloatLeft) &&
!HasLowestFloatLogicalBottomCached(is_in_horizontal_writing_mode,
FloatingObject::kFloatRight))
- return nullptr;
+ LowestFloatLogicalBottom(FloatingObject::kFloatLeftRight);
+
FloatingObject* lowest_left_object =
lowest_float_bottom_cache_[0].floating_object;
FloatingObject* lowest_right_object =
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 7820696f20c..f11a30e3aad 100644
--- a/chromium/third_party/blink/renderer/core/layout/floating_objects.h
+++ b/chromium/third_party/blink/renderer/core/layout/floating_objects.h
@@ -267,7 +267,7 @@ class FloatingObjects {
LayoutUnit FindNextFloatLogicalBottomBelowForBlock(LayoutUnit logical_height);
LayoutUnit LowestFloatLogicalBottom(FloatingObject::Type);
- FloatingObject* LowestFloatingObject() const;
+ FloatingObject* LowestFloatingObject();
private:
bool HasLowestFloatLogicalBottomCached(bool is_horizontal,
diff --git a/chromium/third_party/blink/renderer/core/layout/fragmentainer_iterator.h b/chromium/third_party/blink/renderer/core/layout/fragmentainer_iterator.h
index 0a966fdeb99..e95e8810412 100644
--- a/chromium/third_party/blink/renderer/core/layout/fragmentainer_iterator.h
+++ b/chromium/third_party/blink/renderer/core/layout/fragmentainer_iterator.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/layout/multi_column_fragmentainer_group.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/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/geometry/logical_offset.h b/chromium/third_party/blink/renderer/core/layout/geometry/logical_offset.h
index 220606008d5..ae0a241fc25 100644
--- a/chromium/third_party/blink/renderer/core/layout/geometry/logical_offset.h
+++ b/chromium/third_party/blink/renderer/core/layout/geometry/logical_offset.h
@@ -25,7 +25,7 @@ struct CORE_EXPORT LogicalOffset {
constexpr LogicalOffset(LayoutUnit inline_offset, LayoutUnit block_offset)
: inline_offset(inline_offset), block_offset(block_offset) {}
- // For testing only. It's defined in core/testing/core_unit_test_helpers.h.
+ // For testing only. It's defined in core/testing/core_unit_test_helper.h.
inline LogicalOffset(int inline_offset, int block_offset);
LayoutUnit inline_offset;
diff --git a/chromium/third_party/blink/renderer/core/layout/geometry/logical_rect.cc b/chromium/third_party/blink/renderer/core/layout/geometry/logical_rect.cc
index 3ee275d799e..4b1604f9d3f 100644
--- a/chromium/third_party/blink/renderer/core/layout/geometry/logical_rect.cc
+++ b/chromium/third_party/blink/renderer/core/layout/geometry/logical_rect.cc
@@ -39,10 +39,10 @@ void LogicalRect::Unite(const LogicalRect& other) {
String LogicalRect::ToString() const {
return String::Format("%s,%s %sx%s",
- offset.inline_offset.ToString().Ascii().data(),
- offset.block_offset.ToString().Ascii().data(),
- size.inline_size.ToString().Ascii().data(),
- size.block_size.ToString().Ascii().data());
+ offset.inline_offset.ToString().Ascii().c_str(),
+ offset.block_offset.ToString().Ascii().c_str(),
+ size.inline_size.ToString().Ascii().c_str(),
+ size.block_size.ToString().Ascii().c_str());
}
std::ostream& operator<<(std::ostream& os, const LogicalRect& value) {
diff --git a/chromium/third_party/blink/renderer/core/layout/geometry/physical_offset.cc b/chromium/third_party/blink/renderer/core/layout/geometry/physical_offset.cc
index 8dcf2716bbe..d2c6d1634f1 100644
--- a/chromium/third_party/blink/renderer/core/layout/geometry/physical_offset.cc
+++ b/chromium/third_party/blink/renderer/core/layout/geometry/physical_offset.cc
@@ -42,8 +42,8 @@ LogicalOffset PhysicalOffset::ConvertToLogical(WritingMode mode,
}
String PhysicalOffset::ToString() const {
- return String::Format("%s,%s", left.ToString().Ascii().data(),
- top.ToString().Ascii().data());
+ return String::Format("%s,%s", left.ToString().Ascii().c_str(),
+ top.ToString().Ascii().c_str());
}
std::ostream& operator<<(std::ostream& os, const PhysicalOffset& value) {
diff --git a/chromium/third_party/blink/renderer/core/layout/geometry/physical_offset.h b/chromium/third_party/blink/renderer/core/layout/geometry/physical_offset.h
index ef881305b6f..f435b7ec3bd 100644
--- a/chromium/third_party/blink/renderer/core/layout/geometry/physical_offset.h
+++ b/chromium/third_party/blink/renderer/core/layout/geometry/physical_offset.h
@@ -48,6 +48,11 @@ struct CORE_EXPORT PhysicalOffset {
return left.HasFraction() || top.HasFraction();
}
+ void ClampNegativeToZero() {
+ left = std::max(left, LayoutUnit());
+ top = std::max(top, LayoutUnit());
+ }
+
PhysicalOffset operator+(const PhysicalOffset& other) const {
return PhysicalOffset{this->left + other.left, this->top + other.top};
}
@@ -92,10 +97,18 @@ struct CORE_EXPORT PhysicalOffset {
explicit PhysicalOffset(const IntSize& size)
: left(size.Width()), top(size.Height()) {}
+ static PhysicalOffset FromFloatPointFloor(const FloatPoint& point) {
+ return {LayoutUnit::FromFloatFloor(point.X()),
+ LayoutUnit::FromFloatFloor(point.Y())};
+ }
static PhysicalOffset FromFloatPointRound(const FloatPoint& point) {
return {LayoutUnit::FromFloatRound(point.X()),
LayoutUnit::FromFloatRound(point.Y())};
}
+ static PhysicalOffset FromFloatSizeFloor(const FloatSize& size) {
+ return {LayoutUnit::FromFloatFloor(size.Width()),
+ LayoutUnit::FromFloatFloor(size.Height())};
+ }
static PhysicalOffset FromFloatSizeRound(const FloatSize& size) {
return {LayoutUnit::FromFloatRound(size.Width()),
LayoutUnit::FromFloatRound(size.Height())};
diff --git a/chromium/third_party/blink/renderer/core/layout/geometry/physical_rect.cc b/chromium/third_party/blink/renderer/core/layout/geometry/physical_rect.cc
index 1dee4cceda7..33091885aab 100644
--- a/chromium/third_party/blink/renderer/core/layout/geometry/physical_rect.cc
+++ b/chromium/third_party/blink/renderer/core/layout/geometry/physical_rect.cc
@@ -133,8 +133,8 @@ LayoutRect PhysicalRect::ToLayoutFlippedRect(
}
String PhysicalRect::ToString() const {
- return String::Format("%s %s", offset.ToString().Ascii().data(),
- size.ToString().Ascii().data());
+ return String::Format("%s %s", offset.ToString().Ascii().c_str(),
+ size.ToString().Ascii().c_str());
}
PhysicalRect UnionRect(const Vector<PhysicalRect>& rects) {
diff --git a/chromium/third_party/blink/renderer/core/layout/geometry/physical_rect.h b/chromium/third_party/blink/renderer/core/layout/geometry/physical_rect.h
index a5476da6c39..18f0a8fe6c6 100644
--- a/chromium/third_party/blink/renderer/core/layout/geometry/physical_rect.h
+++ b/chromium/third_party/blink/renderer/core/layout/geometry/physical_rect.h
@@ -190,6 +190,14 @@ struct CORE_EXPORT PhysicalRect {
return PhysicalRect(offset, size);
}
+ // This is faster than EnclosingRect(). Can be used in situation that we
+ // prefer performance to accuracy and haven't observed problems caused by the
+ // tiny error (< LayoutUnit::Epsilon()).
+ static PhysicalRect FastAndLossyFromFloatRect(const FloatRect& rect) {
+ return PhysicalRect(LayoutUnit(rect.X()), LayoutUnit(rect.Y()),
+ LayoutUnit(rect.Width()), LayoutUnit(rect.Height()));
+ }
+
explicit PhysicalRect(const IntRect& r)
: offset(r.Location()), size(r.Size()) {}
diff --git a/chromium/third_party/blink/renderer/core/layout/geometry/physical_size.cc b/chromium/third_party/blink/renderer/core/layout/geometry/physical_size.cc
index 5c1b6ec387c..c0b88a4d0a9 100644
--- a/chromium/third_party/blink/renderer/core/layout/geometry/physical_size.cc
+++ b/chromium/third_party/blink/renderer/core/layout/geometry/physical_size.cc
@@ -26,8 +26,8 @@ PhysicalSize PhysicalSize::FitToAspectRatio(const PhysicalSize& aspect_ratio,
}
String PhysicalSize::ToString() const {
- return String::Format("%sx%s", width.ToString().Ascii().data(),
- height.ToString().Ascii().data());
+ return String::Format("%sx%s", width.ToString().Ascii().c_str(),
+ height.ToString().Ascii().c_str());
}
std::ostream& operator<<(std::ostream& os, const PhysicalSize& value) {
diff --git a/chromium/third_party/blink/renderer/core/layout/geometry/transform_state.h b/chromium/third_party/blink/renderer/core/layout/geometry/transform_state.h
index 400f05f1072..9866efdaa74 100644
--- a/chromium/third_party/blink/renderer/core/layout/geometry/transform_state.h
+++ b/chromium/third_party/blink/renderer/core/layout/geometry/transform_state.h
@@ -36,7 +36,7 @@
#include "third_party/blink/renderer/platform/geometry/layout_size.h"
#include "third_party/blink/renderer/platform/transforms/affine_transform.h"
#include "third_party/blink/renderer/platform/transforms/transformation_matrix.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/grid.h b/chromium/third_party/blink/renderer/core/layout/grid.h
index 3f3340adfca..528bed93c14 100644
--- a/chromium/third_party/blink/renderer/core/layout/grid.h
+++ b/chromium/third_party/blink/renderer/core/layout/grid.h
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/layout/order_iterator.h"
#include "third_party/blink/renderer/core/style/grid_area.h"
#include "third_party/blink/renderer/core/style/grid_positions_resolver.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
#include "third_party/blink/renderer/platform/wtf/doubly_linked_list.h"
#include "third_party/blink/renderer/platform/wtf/linked_hash_set.h"
diff --git a/chromium/third_party/blink/renderer/core/layout/grid_baseline_alignment.h b/chromium/third_party/blink/renderer/core/layout/grid_baseline_alignment.h
index 93208349e1d..64a97f6c621 100644
--- a/chromium/third_party/blink/renderer/core/layout/grid_baseline_alignment.h
+++ b/chromium/third_party/blink/renderer/core/layout/grid_baseline_alignment.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/layout/grid_layout_utils.h"
#include "third_party/blink/renderer/core/layout/layout_box.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/grid_layout_utils.h b/chromium/third_party/blink/renderer/core/layout/grid_layout_utils.h
index 987f834b708..0321ef9b740 100644
--- a/chromium/third_party/blink/renderer/core/layout/grid_layout_utils.h
+++ b/chromium/third_party/blink/renderer/core/layout/grid_layout_utils.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_GRID_LAYOUT_UTILS_H_
#include "third_party/blink/renderer/core/layout/layout_box.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 c298683c3fa..1f81a76b93b 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
@@ -13,7 +13,7 @@
#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/geometry/layout_unit.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.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.cc b/chromium/third_party/blink/renderer/core/layout/hit_test_cache.cc
index 5b650e1ee6c..2b536141ab6 100644
--- a/chromium/third_party/blink/renderer/core/layout/hit_test_cache.cc
+++ b/chromium/third_party/blink/renderer/core/layout/hit_test_cache.cc
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/layout/hit_test_cache.h"
#include "third_party/blink/public/platform/platform.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/hit_test_location.cc b/chromium/third_party/blink/renderer/core/layout/hit_test_location.cc
index 4ca0f47f14f..7d83acd0115 100644
--- a/chromium/third_party/blink/renderer/core/layout/hit_test_location.cc
+++ b/chromium/third_party/blink/renderer/core/layout/hit_test_location.cc
@@ -29,9 +29,9 @@ HitTestLocation::HitTestLocation()
: is_rect_based_(false), is_rectilinear_(true) {}
HitTestLocation::HitTestLocation(const IntPoint& point)
- : HitTestLocation(LayoutPoint(point)) {}
+ : HitTestLocation(PhysicalOffset(point)) {}
-HitTestLocation::HitTestLocation(const LayoutPoint& point)
+HitTestLocation::HitTestLocation(const PhysicalOffset& point)
: point_(point),
bounding_box_(RectForPoint(point)),
transformed_point_(point),
@@ -40,7 +40,7 @@ HitTestLocation::HitTestLocation(const LayoutPoint& point)
is_rectilinear_(true) {}
HitTestLocation::HitTestLocation(const FloatPoint& point)
- : point_(FlooredLayoutPoint(point)),
+ : point_(PhysicalOffset::FromFloatPointFloor(point)),
bounding_box_(RectForPoint(point_)),
transformed_point_(point),
transformed_rect_(FloatRect(bounding_box_)),
@@ -52,12 +52,12 @@ HitTestLocation::HitTestLocation(const DoublePoint& point)
HitTestLocation::HitTestLocation(const FloatPoint& point, const FloatQuad& quad)
: transformed_point_(point), transformed_rect_(quad), is_rect_based_(true) {
- point_ = FlooredLayoutPoint(point);
- bounding_box_ = EnclosingLayoutRect(quad.BoundingBox());
+ point_ = PhysicalOffset::FromFloatPointFloor(point);
+ bounding_box_ = PhysicalRect::EnclosingRect(quad.BoundingBox());
is_rectilinear_ = quad.IsRectilinear();
}
-HitTestLocation::HitTestLocation(const LayoutRect& rect)
+HitTestLocation::HitTestLocation(const PhysicalRect& rect)
: point_(rect.Center()),
bounding_box_(rect),
transformed_point_(point_),
@@ -67,7 +67,7 @@ HitTestLocation::HitTestLocation(const LayoutRect& rect)
}
HitTestLocation::HitTestLocation(const HitTestLocation& other,
- const LayoutSize& offset)
+ const PhysicalOffset& offset)
: point_(other.point_),
bounding_box_(other.bounding_box_),
transformed_point_(other.transformed_point_),
@@ -84,11 +84,11 @@ HitTestLocation::~HitTestLocation() = default;
HitTestLocation& HitTestLocation::operator=(const HitTestLocation& other) =
default;
-void HitTestLocation::Move(const LayoutSize& offset) {
- point_.Move(offset);
+void HitTestLocation::Move(const PhysicalOffset& offset) {
+ point_ += offset;
bounding_box_.Move(offset);
transformed_point_.Move(FloatSize(offset));
- transformed_rect_.Move(offset);
+ transformed_rect_.Move(FloatSize(offset));
}
template <typename RectType>
@@ -116,7 +116,7 @@ bool HitTestLocation::IntersectsRect(const RectType& rect,
return transformed_rect_.IntersectsRect(FloatRect(rect));
}
-bool HitTestLocation::Intersects(const LayoutRect& rect) const {
+bool HitTestLocation::Intersects(const PhysicalRect& rect) const {
return IntersectsRect(rect, bounding_box_);
}
diff --git a/chromium/third_party/blink/renderer/core/layout/hit_test_location.h b/chromium/third_party/blink/renderer/core/layout/hit_test_location.h
index e4c95df2b6f..dece9e2bbd1 100644
--- a/chromium/third_party/blink/renderer/core/layout/hit_test_location.h
+++ b/chromium/third_party/blink/renderer/core/layout/hit_test_location.h
@@ -24,10 +24,10 @@
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/layout/geometry/physical_rect.h"
#include "third_party/blink/renderer/platform/geometry/float_quad.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/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
namespace blink {
@@ -46,35 +46,34 @@ class CORE_EXPORT HitTestLocation {
// scroll offset. See:
// http://www.chromium.org/developers/design-documents/blink-coordinate-spaces
HitTestLocation();
- explicit HitTestLocation(const LayoutPoint&);
+ explicit HitTestLocation(const PhysicalOffset&);
explicit HitTestLocation(const IntPoint&);
explicit HitTestLocation(const FloatPoint&);
explicit HitTestLocation(const DoublePoint&);
explicit HitTestLocation(const FloatPoint&, const FloatQuad&);
- explicit HitTestLocation(const LayoutRect&);
- HitTestLocation(const HitTestLocation&, const LayoutSize& offset);
+ explicit HitTestLocation(const PhysicalRect&);
+ HitTestLocation(const HitTestLocation&, const PhysicalOffset& offset);
HitTestLocation(const HitTestLocation&);
~HitTestLocation();
HitTestLocation& operator=(const HitTestLocation&);
- const LayoutPoint& Point() const { return point_; }
+ const PhysicalOffset& Point() const { return point_; }
IntPoint RoundedPoint() const { return RoundedIntPoint(point_); }
// Rect-based hit test related methods.
bool IsRectBasedTest() const { return is_rect_based_; }
bool IsRectilinear() const { return is_rectilinear_; }
- const LayoutRect& BoundingBox() const { return bounding_box_; }
+ const PhysicalRect& BoundingBox() const { return bounding_box_; }
IntRect EnclosingIntRect() const {
return ::blink::EnclosingIntRect(bounding_box_);
}
// Returns the 1px x 1px hit test rect for a point.
- // TODO(pdr): Should we be using a one-layout-unit rect instead?
- static LayoutRect RectForPoint(const LayoutPoint& point) {
- return LayoutRect(FlooredIntPoint(point), IntSize(1, 1));
+ static PhysicalRect RectForPoint(const PhysicalOffset& point) {
+ return PhysicalRect(point, PhysicalSize(LayoutUnit(1), LayoutUnit(1)));
}
- bool Intersects(const LayoutRect&) const;
+ bool Intersects(const PhysicalRect&) const;
// Uses floating-point intersection, which uses inclusive intersection
// (see LayoutRect::InclusiveIntersect for a definition)
bool Intersects(const FloatRect&) const;
@@ -88,12 +87,12 @@ class CORE_EXPORT HitTestLocation {
private:
template <typename RectType>
bool IntersectsRect(const RectType&, const RectType& bounding_box) const;
- void Move(const LayoutSize& offset);
+ void Move(const PhysicalOffset& offset);
// These are cached forms of the more accurate |transformed_point_| and
// |transformed_rect_|, below.
- LayoutPoint point_;
- LayoutRect bounding_box_;
+ PhysicalOffset point_;
+ PhysicalRect bounding_box_;
FloatPoint transformed_point_;
FloatQuad transformed_rect_;
diff --git a/chromium/third_party/blink/renderer/core/layout/hit_test_request.h b/chromium/third_party/blink/renderer/core/layout/hit_test_request.h
index 4cc67b38db0..e96db5ccdc0 100644
--- a/chromium/third_party/blink/renderer/core/layout/hit_test_request.h
+++ b/chromium/third_party/blink/renderer/core/layout/hit_test_request.h
@@ -23,7 +23,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_HIT_TEST_REQUEST_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_HIT_TEST_REQUEST_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
namespace blink {
@@ -45,15 +45,16 @@ class HitTestRequest {
kAllowChildFrameContent = 1 << 8,
kChildFrameHitTest = 1 << 9,
kIgnorePointerEventsNone = 1 << 10,
+ kRetargetForInert = 1 << 11,
// Collect a list of nodes instead of just one.
// (This is for elementsFromPoint and rect-based tests).
- kListBased = 1 << 11,
+ kListBased = 1 << 12,
// When using list-based testing, this flag causes us to continue hit
// testing after a hit has been found.
- kPenetratingList = 1 << 12,
- kAvoidCache = 1 << 13,
- kIgnoreZeroOpacityObjects = 1 << 14,
- kHitTestVisualOverflow = 1 << 15,
+ kPenetratingList = 1 << 13,
+ kAvoidCache = 1 << 14,
+ kIgnoreZeroOpacityObjects = 1 << 15,
+ kHitTestVisualOverflow = 1 << 16,
};
typedef unsigned HitTestRequestType;
@@ -81,6 +82,7 @@ class HitTestRequest {
bool IgnorePointerEventsNone() const {
return request_type_ & kIgnorePointerEventsNone;
}
+ bool RetargetForInert() const { return request_type_ & kRetargetForInert; }
bool ListBased() const { return request_type_ & kListBased; }
bool PenetratingList() const { return request_type_ & kPenetratingList; }
bool AvoidCache() const { return request_type_ & kAvoidCache; }
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 ac00fc11213..1247cf71f4b 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
@@ -64,6 +64,7 @@ HitTestResult::HitTestResult(const HitTestResult& other)
: hit_test_request_(other.hit_test_request_),
cacheable_(other.cacheable_),
inner_node_(other.InnerNode()),
+ inert_node_(other.InertNode()),
inner_element_(other.InnerElement()),
inner_possibly_pseudo_node_(other.inner_possibly_pseudo_node_),
point_in_inner_node_frame_(other.point_in_inner_node_frame_),
@@ -90,7 +91,7 @@ HitTestResult& HitTestResult::operator=(const HitTestResult& other) {
bool HitTestResult::EqualForCacheability(const HitTestResult& other) const {
return hit_test_request_.EqualForCacheability(other.hit_test_request_) &&
- inner_node_ == other.InnerNode() &&
+ inner_node_ == other.InnerNode() && inert_node_ == other.InertNode() &&
inner_element_ == other.InnerElement() &&
inner_possibly_pseudo_node_ == other.InnerPossiblyPseudoNode() &&
point_in_inner_node_frame_ == other.point_in_inner_node_frame_ &&
@@ -107,6 +108,7 @@ void HitTestResult::CacheValues(const HitTestResult& other) {
void HitTestResult::PopulateFromCachedResult(const HitTestResult& other) {
inner_node_ = other.InnerNode();
+ inert_node_ = other.InertNode();
inner_element_ = other.InnerElement();
inner_possibly_pseudo_node_ = other.InnerPossiblyPseudoNode();
point_in_inner_node_frame_ = other.point_in_inner_node_frame_;
@@ -126,6 +128,7 @@ void HitTestResult::PopulateFromCachedResult(const HitTestResult& other) {
void HitTestResult::Trace(blink::Visitor* visitor) {
visitor->Trace(inner_node_);
+ visitor->Trace(inert_node_);
visitor->Trace(inner_element_);
visitor->Trace(inner_possibly_pseudo_node_);
visitor->Trace(inner_url_element_);
@@ -201,6 +204,23 @@ void HitTestResult::SetInnerNode(Node* n) {
inner_element_ = nullptr;
return;
}
+
+ if (RuntimeEnabledFeatures::InertAttributeEnabled()) {
+ if (GetHitTestRequest().RetargetForInert()) {
+ if (n->IsInert()) {
+ if (!inert_node_)
+ inert_node_ = n;
+
+ return;
+ }
+
+ if (inert_node_ && n != inert_node_ &&
+ !n->IsShadowIncludingInclusiveAncestorOf(*inert_node_)) {
+ return;
+ }
+ }
+ }
+
inner_possibly_pseudo_node_ = n;
if (auto* pseudo_element = DynamicTo<PseudoElement>(n))
n = pseudo_element->InnerNodeForHitTesting();
@@ -209,12 +229,20 @@ void HitTestResult::SetInnerNode(Node* n) {
inner_node_ = area;
inner_possibly_pseudo_node_ = area;
}
- if (inner_node_->IsElementNode())
- inner_element_ = ToElement(inner_node_);
+ if (auto* element = DynamicTo<Element>(inner_node_.Get()))
+ inner_element_ = element;
else
inner_element_ = FlatTreeTraversal::ParentElement(*inner_node_);
}
+void HitTestResult::SetInertNode(Node* n) {
+ // Don't overwrite an existing value for inert_node_
+ if (inert_node_)
+ DCHECK(n == inert_node_);
+
+ inert_node_ = n;
+}
+
void HitTestResult::SetURLElement(Element* n) {
inner_url_element_ = n;
}
@@ -247,8 +275,8 @@ String HitTestResult::Title(TextDirection& dir) const {
inner_node_->UpdateDistributionForFlatTreeTraversal();
for (Node* title_node = inner_node_.Get(); title_node;
title_node = FlatTreeTraversal::Parent(*title_node)) {
- if (title_node->IsElementNode()) {
- String title = ToElement(title_node)->title();
+ if (auto* element = DynamicTo<Element>(title_node)) {
+ String title = element->title();
if (!title.IsNull()) {
if (LayoutObject* layout_object = title_node->GetLayoutObject())
dir = layout_object->StyleRef().Direction();
@@ -312,13 +340,13 @@ KURL HitTestResult::AbsoluteImageURL() const {
(IsHTMLInputElement(*inner_node_or_image_map_image) &&
ToHTMLInputElement(inner_node_or_image_map_image)->type() ==
input_type_names::kImage))
- url_string = ToElement(*inner_node_or_image_map_image).ImageSourceURL();
+ url_string = To<Element>(*inner_node_or_image_map_image).ImageSourceURL();
else if ((inner_node_or_image_map_image->GetLayoutObject() &&
inner_node_or_image_map_image->GetLayoutObject()->IsImage()) &&
(IsHTMLEmbedElement(*inner_node_or_image_map_image) ||
IsHTMLObjectElement(*inner_node_or_image_map_image) ||
IsSVGImageElement(*inner_node_or_image_map_image)))
- url_string = ToElement(*inner_node_or_image_map_image).ImageSourceURL();
+ url_string = To<Element>(*inner_node_or_image_map_image).ImageSourceURL();
if (url_string.IsEmpty())
return KURL();
@@ -392,7 +420,11 @@ bool HitTestResult::IsContentEditable() const {
ListBasedHitTestBehavior HitTestResult::AddNodeToListBasedTestResult(
Node* node,
const HitTestLocation& location,
- const LayoutRect& rect) {
+ const PhysicalRect& rect) {
+ // If we are in the process of retargeting for `inert`, continue.
+ if (GetHitTestRequest().RetargetForInert() && InertNode() && !InnerNode())
+ return kContinueHitTesting;
+
// If not a list-based test, stop testing because the hit has been found.
if (!GetHitTestRequest().ListBased())
return kStopHitTesting;
@@ -413,6 +445,10 @@ ListBasedHitTestBehavior HitTestResult::AddNodeToListBasedTestResult(
Node* node,
const HitTestLocation& location,
const Region& region) {
+ // If we are in the process of retargeting for `inert`, continue.
+ if (GetHitTestRequest().RetargetForInert() && InertNode() && !InnerNode())
+ return kContinueHitTesting;
+
// If not a list-based test, stop testing because the hit has been found.
if (!GetHitTestRequest().ListBased())
return kStopHitTesting;
@@ -447,6 +483,9 @@ void HitTestResult::Append(const HitTestResult& other) {
canvas_region_id_ = other.CanvasRegionId();
}
+ if (!inert_node_ && other.InertNode())
+ SetInertNode(other.InertNode());
+
if (other.list_based_test_result_) {
NodeSet& set = MutableListBasedTestResult();
for (NodeSet::const_iterator it = other.list_based_test_result_->begin(),
@@ -470,7 +509,7 @@ HitTestResult::NodeSet& HitTestResult::MutableListBasedTestResult() {
HitTestLocation HitTestResult::ResolveRectBasedTest(
Node* resolved_inner_node,
- const LayoutPoint& resolved_point_in_main_frame) {
+ const PhysicalOffset& resolved_point_in_main_frame) {
point_in_inner_node_frame_ = resolved_point_in_main_frame;
SetInnerNode(nullptr);
list_based_test_result_ = nullptr;
@@ -481,7 +520,7 @@ HitTestLocation HitTestResult::ResolveRectBasedTest(
// never use it so shouldn't bother with the cost of computing it.
DCHECK(resolved_inner_node);
if (auto* layout_object = resolved_inner_node->GetLayoutObject())
- layout_object->UpdateHitTestResult(*this, LayoutPoint());
+ layout_object->UpdateHitTestResult(*this, PhysicalOffset());
return HitTestLocation(resolved_point_in_main_frame);
}
@@ -502,10 +541,4 @@ Node* HitTestResult::InnerNodeOrImageMapImage() const {
return image_map_image_element;
}
-void HitTestResult::SetNodeAndPosition(Node* node, const PhysicalOffset& p) {
- SetNodeAndPosition(node, node && node->GetLayoutObject()
- ? node->GetLayoutObject()->FlipForWritingMode(p)
- : p.ToLayoutPoint());
-}
-
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/hit_test_result.h b/chromium/third_party/blink/renderer/core/layout/hit_test_result.h
index bc05624925f..c6ea07e53a6 100644
--- a/chromium/third_party/blink/renderer/core/layout/hit_test_result.h
+++ b/chromium/third_party/blink/renderer/core/layout/hit_test_result.h
@@ -24,6 +24,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/editing/forward.h"
+#include "third_party/blink/renderer/core/layout/geometry/physical_offset.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/platform/geometry/float_quad.h"
@@ -81,6 +82,7 @@ class CORE_EXPORT HitTestResult {
// FIXME: Make these less error-prone for rect-based hit tests (center point
// or fail).
Node* InnerNode() const { return inner_node_.Get(); }
+ Node* InertNode() const { return inert_node_.Get(); }
Node* InnerPossiblyPseudoNode() const {
return inner_possibly_pseudo_node_.Get();
}
@@ -98,10 +100,10 @@ class CORE_EXPORT HitTestResult {
// The hit-tested point in the coordinates of the innerNode frame, the frame
// containing innerNode.
- const LayoutPoint& PointInInnerNodeFrame() const {
+ const PhysicalOffset& PointInInnerNodeFrame() const {
return point_in_inner_node_frame_;
}
- void SetPointInInnerNodeFrame(const LayoutPoint& point) {
+ void SetPointInInnerNodeFrame(const PhysicalOffset& point) {
point_in_inner_node_frame_ = point;
}
IntPoint RoundedPointInInnerNodeFrame() const {
@@ -109,14 +111,12 @@ class CORE_EXPORT HitTestResult {
}
LocalFrame* InnerNodeFrame() const;
- // The hit-tested point in the coordinates of the inner node, in physical
- // coordinates with flipped blocks direction.
- const LayoutPoint& LocalPoint() const { return local_point_; }
- void SetNodeAndPosition(Node* node, const LayoutPoint& p) {
+ // The hit-tested point in the coordinates of the inner node.
+ const PhysicalOffset& LocalPoint() const { return local_point_; }
+ void SetNodeAndPosition(Node* node, const PhysicalOffset& p) {
local_point_ = p;
SetInnerNode(node);
}
- void SetNodeAndPosition(Node* node, const PhysicalOffset& p);
PositionWithAffinity GetPosition() const;
LayoutObject* GetLayoutObject() const;
@@ -126,6 +126,7 @@ class CORE_EXPORT HitTestResult {
const HitTestRequest& GetHitTestRequest() const { return hit_test_request_; }
void SetInnerNode(Node*);
+ void SetInertNode(Node*);
HTMLAreaElement* ImageAreaForImage() const;
void SetURLElement(Element*);
void SetScrollbar(Scrollbar*);
@@ -156,12 +157,12 @@ class CORE_EXPORT HitTestResult {
// TODO(pdr): When using the default rect argument, this function does not
// check if the tapped area is entirely contained by the HitTestLocation's
- // bounding box. Callers should pass a LayoutRect as the third parameter so
+ // bounding box. Callers should pass a PhysicalRect as the third parameter so
// hit testing can early-out when a tapped area is covered.
ListBasedHitTestBehavior AddNodeToListBasedTestResult(
Node*,
const HitTestLocation&,
- const LayoutRect& = LayoutRect());
+ const PhysicalRect& = PhysicalRect());
ListBasedHitTestBehavior AddNodeToListBasedTestResult(Node*,
const HitTestLocation&,
const Region&);
@@ -179,7 +180,7 @@ class CORE_EXPORT HitTestResult {
// location.
HitTestLocation ResolveRectBasedTest(
Node* resolved_inner_node,
- const LayoutPoint& resolved_point_in_main_frame);
+ const PhysicalOffset& resolved_point_in_main_frame);
private:
NodeSet& MutableListBasedTestResult(); // See above.
@@ -189,16 +190,17 @@ class CORE_EXPORT HitTestResult {
bool cacheable_;
Member<Node> inner_node_;
+ Member<Node> inert_node_;
// This gets calculated in the first call to InnerElement function.
Member<Element> inner_element_;
Member<Node> inner_possibly_pseudo_node_;
// FIXME: Nothing changes this to a value different from m_hitTestLocation!
// The hit-tested point in innerNode frame coordinates.
- LayoutPoint point_in_inner_node_frame_;
+ PhysicalOffset point_in_inner_node_frame_;
// A point in the local coordinate space of m_innerNode's layoutObject.Allows
// us to efficiently determine where inside the layoutObject we hit on
// subsequent operations.
- LayoutPoint local_point_;
+ PhysicalOffset local_point_;
// For non-URL, this is the enclosing that triggers navigation.
Member<Element> inner_url_element_;
Member<Scrollbar> scrollbar_;
diff --git a/chromium/third_party/blink/renderer/core/layout/hit_testing_transform_state.cc b/chromium/third_party/blink/renderer/core/layout/hit_testing_transform_state.cc
index b2aeafe8709..44078b30f30 100644
--- a/chromium/third_party/blink/renderer/core/layout/hit_testing_transform_state.cc
+++ b/chromium/third_party/blink/renderer/core/layout/hit_testing_transform_state.cc
@@ -76,9 +76,10 @@ FloatQuad HitTestingTransformState::MappedArea() const {
return accumulated_transform_.Inverse().ProjectQuad(last_planar_area_);
}
-LayoutRect HitTestingTransformState::BoundsOfMappedArea() const {
- return accumulated_transform_.Inverse().ClampedBoundsOfProjectedQuad(
- last_planar_area_);
+PhysicalRect HitTestingTransformState::BoundsOfMappedArea() const {
+ return PhysicalRectToBeNoop(
+ accumulated_transform_.Inverse().ClampedBoundsOfProjectedQuad(
+ last_planar_area_));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/hit_testing_transform_state.h b/chromium/third_party/blink/renderer/core/layout/hit_testing_transform_state.h
index 647dd3ea46c..b45cf3c8ecd 100644
--- a/chromium/third_party/blink/renderer/core/layout/hit_testing_transform_state.h
+++ b/chromium/third_party/blink/renderer/core/layout/hit_testing_transform_state.h
@@ -26,12 +26,12 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_HIT_TESTING_TRANSFORM_STATE_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_HIT_TESTING_TRANSFORM_STATE_H_
+#include "third_party/blink/renderer/core/layout/geometry/physical_rect.h"
#include "third_party/blink/renderer/platform/geometry/float_point.h"
#include "third_party/blink/renderer/platform/geometry/float_quad.h"
-#include "third_party/blink/renderer/platform/geometry/int_size.h"
#include "third_party/blink/renderer/platform/transforms/affine_transform.h"
#include "third_party/blink/renderer/platform/transforms/transformation_matrix.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -68,7 +68,7 @@ class HitTestingTransformState {
FloatPoint MappedPoint() const;
FloatQuad MappedQuad() const;
FloatQuad MappedArea() const;
- LayoutRect BoundsOfMappedArea() const;
+ PhysicalRect BoundsOfMappedArea() const;
void Flatten();
FloatPoint last_planar_point_;
diff --git a/chromium/third_party/blink/renderer/core/layout/intrinsic_sizing_info.h b/chromium/third_party/blink/renderer/core/layout/intrinsic_sizing_info.h
index 3fbdecc33b4..3c75bfad4a4 100644
--- a/chromium/third_party/blink/renderer/core/layout/intrinsic_sizing_info.h
+++ b/chromium/third_party/blink/renderer/core/layout/intrinsic_sizing_info.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_INTRINSIC_SIZING_INFO_H_
#include "third_party/blink/renderer/platform/geometry/float_size.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/jank_tracker.h b/chromium/third_party/blink/renderer/core/layout/jank_tracker.h
deleted file mode 100644
index ba33663fcf0..00000000000
--- a/chromium/third_party/blink/renderer/core/layout/jank_tracker.h
+++ /dev/null
@@ -1,110 +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_LAYOUT_JANK_TRACKER_H_
-#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/core/scroll/scroll_types.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"
-
-namespace blink {
-
-class IntRect;
-class LayoutObject;
-class LocalFrameView;
-class PropertyTreeState;
-class TracedValue;
-class WebInputEvent;
-
-// Tracks "jank" from layout objects changing their visual location between
-// animation frames.
-class CORE_EXPORT JankTracker {
- USING_FAST_MALLOC(JankTracker);
-
- public:
- JankTracker(LocalFrameView*);
- ~JankTracker() {}
- void NotifyObjectPrePaint(const LayoutObject& object,
- const PropertyTreeState& property_tree_state,
- const IntRect& old_visual_rect,
- const IntRect& new_visual_rect);
- // Layer rects are relative to old layer position.
- void NotifyCompositedLayerMoved(const LayoutObject& object,
- FloatRect old_layer_rect,
- FloatRect new_layer_rect);
- void NotifyPrePaintFinished();
- void NotifyInput(const WebInputEvent&);
- void NotifyScroll(ScrollType);
- void NotifyViewportSizeChanged();
- bool IsActive();
- double Score() const { return score_; }
- double ScoreWithMoveDistance() const { return score_with_move_distance_; }
- double WeightedScore() const { return weighted_score_; }
- float OverallMaxDistance() const { return overall_max_distance_; }
- bool ObservedInputOrScroll() const { return observed_input_or_scroll_; }
- void Dispose() { timer_.Stop(); }
-
- private:
- void AccumulateJank(const LayoutObject&,
- const PropertyTreeState&,
- FloatRect old_rect,
- FloatRect new_rect);
- void TimerFired(TimerBase*) {}
- std::unique_ptr<TracedValue> PerFrameTraceData(
- double jank_fraction,
- double jank_fraction_with_move_distance,
- double granularity_scale) const;
- double SubframeWeightingFactor() const;
- std::vector<gfx::Rect> ConvertIntRectsToGfxRects(
- const Vector<IntRect>& int_rects,
- double granularity_scale);
- void SetLayoutShiftRects(const Vector<IntRect>& int_rects,
- double granularity_scale);
-
- // This owns us.
- UntracedMember<LocalFrameView> frame_view_;
-
- // The cumulative jank score for this LocalFrame, unweighted.
- double score_;
-
- // The cumulative jank score for this LocalFrame, unweighted, with move
- // distance applied. This is a temporary member needed to understand the
- // impact of move distance on scores, and will be removed once analysis is
- // complete.
- double score_with_move_distance_;
-
- // The cumulative jank score for this LocalFrame, with each increase weighted
- // by the extent to which the LocalFrame visibly occupied the main frame at
- // the time the jank occurred (e.g. x0.5 if the subframe occupied half of the
- // main frame's reported size (see JankTracker::SubframeWeightingFactor).
- double weighted_score_;
-
- // The per-animation-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_;
-
- // The maximum distance any layout object has moved in the current animation
- // frame.
- float frame_max_distance_;
-
- // The maximum distance any layout object has moved, across all animation
- // frames.
- float overall_max_distance_;
-
- // Whether either a user input or document scroll have been observed.
- bool observed_input_or_scroll_;
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_JANK_TRACKER_H_
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_analyzer.cc b/chromium/third_party/blink/renderer/core/layout/layout_analyzer.cc
index 3778ade79b6..075b463d7f3 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_analyzer.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_analyzer.cc
@@ -47,7 +47,6 @@ LayoutAnalyzer::BlockScope::~BlockScope() {
}
void LayoutAnalyzer::Reset() {
- start_ms_ = CurrentTimeMS();
depth_ = 0;
for (size_t i = 0; i < kNumCounters; ++i) {
counters_[i] = 0;
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 b4178849c50..aaa014597b1 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_analyzer.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_analyzer.h
@@ -8,7 +8,7 @@
#include <memory>
#include "base/macros.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/allocator/allocator.h"
namespace blink {
@@ -88,7 +88,6 @@ class LayoutAnalyzer {
private:
const char* NameForCounter(Counter) const;
- double start_ms_;
unsigned depth_;
unsigned counters_[kNumCounters];
DISALLOW_COPY_AND_ASSIGN(LayoutAnalyzer);
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 54b0485d5ce..a6b1d43b8ce 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_block.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_block.cc
@@ -50,6 +50,7 @@
#include "third_party/blink/renderer/core/layout/layout_flow_thread.h"
#include "third_party/blink/renderer/core/layout/layout_grid.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_spanner_placeholder.h"
#include "third_party/blink/renderer/core/layout/layout_object_factory.h"
#include "third_party/blink/renderer/core/layout/layout_table_cell.h"
@@ -671,10 +672,19 @@ bool LayoutBlock::SimplifiedLayout() {
!TryLayoutDoingPositionedMovementOnly())
return false;
+ // If this block is inside a multicol container, we may not be able to
+ // perform simplified layout.
if (LayoutFlowThread* flow_thread = FlowThreadContainingBlock()) {
if (!flow_thread->CanSkipLayout(*this))
return false;
}
+ // Additionally, if this block itself establishes a multicol container, we
+ // may not be able to perform simplified layout inside it. This is really
+ // only unsafe if there are spanners in there, but let's just bail.
+ if (const auto* block_flow = DynamicTo<LayoutBlockFlow>(this)) {
+ if (block_flow->MultiColumnFlowThread())
+ return false;
+ }
if (LayoutBlockedByDisplayLock(DisplayLockContext::kChildren))
return false;
@@ -1036,19 +1046,12 @@ void LayoutBlock::ImageChanged(WrappedImagePtr image,
if (!StyleRef().HasPseudoStyle(kPseudoIdFirstLine))
return;
- // ImageChanged() is also called when we add image observers. Don't use
- // FirstLineStyleRef() here because it will update the first line style cache
- // too early. We should just access the current cached style and bail out if
- // it's not ready (and we'll update pending image observer when the cache is
- // updated).
- const auto* cached_first_line_style =
- StyleRef().GetCachedPseudoStyle(kPseudoIdFirstLine);
- if (!cached_first_line_style)
+ const auto* first_line_style = FirstLineStyleWithoutFallback();
+ if (!first_line_style)
return;
-
if (auto* first_line_container = NearestInnerBlockWithFirstLine()) {
- for (const auto* layer = &cached_first_line_style->BackgroundLayers();
- layer; layer = layer->Next()) {
+ for (const auto* layer = &first_line_style->BackgroundLayers(); layer;
+ layer = layer->Next()) {
if (layer->GetImage() && image == layer->GetImage()->Data()) {
first_line_container->SetShouldDoFullPaintInvalidationForFirstLine();
break;
@@ -1115,13 +1118,13 @@ void LayoutBlock::RemovePositionedObjects(
void LayoutBlock::AddPercentHeightDescendant(LayoutBox* descendant) {
// A replaced object is incapable of properly acting as a containing block for
- // its children (this is an issue with VIDEO elements, for instance, which
- // inserts some percentage height flexbox children). Assert that the
- // descendant hasn't escaped from within a replaced object. Registering the
- // percentage height descendant further up in the tree is only going to cause
- // trouble, especially if the replaced object is out-of-flow positioned (and
- // we failed to notice).
- DCHECK(!descendant->Container()->IsLayoutReplaced());
+ // its children. This is an issue with VIDEO elements, for instance, which
+ // insert some percentage height flexbox children. It is also very easily
+ // achievable with a foreignObject inside an SVG. Detect this situation and
+ // bail. The assumption is that there is no situation where we require quirky
+ // percentage height behavior inside replaced content.
+ if (UNLIKELY(descendant->Container()->IsLayoutReplaced()))
+ return;
if (descendant->PercentHeightContainer()) {
if (descendant->PercentHeightContainer() == this) {
@@ -1193,36 +1196,34 @@ LayoutUnit LayoutBlock::TextIndentOffset() const {
bool LayoutBlock::IsPointInOverflowControl(
HitTestResult& result,
- const LayoutPoint& location_in_container,
- const LayoutPoint& accumulated_offset) const {
+ const PhysicalOffset& hit_test_location,
+ const PhysicalOffset& accumulated_offset) const {
if (!ScrollsOverflow())
return false;
return Layer()->GetScrollableArea()->HitTestOverflowControls(
- result, RoundedIntPoint(location_in_container -
- ToLayoutSize(accumulated_offset)));
+ result, RoundedIntPoint(hit_test_location - accumulated_offset));
}
bool LayoutBlock::HitTestOverflowControl(
HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& adjusted_location) {
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& adjusted_location) {
if (VisibleToHitTestRequest(result.GetHitTestRequest()) &&
- IsPointInOverflowControl(result, location_in_container.Point(),
+ IsPointInOverflowControl(result, hit_test_location.Point(),
adjusted_location)) {
- UpdateHitTestResult(result, location_in_container.Point() -
- ToLayoutSize(adjusted_location));
+ UpdateHitTestResult(result, hit_test_location.Point() - adjusted_location);
// FIXME: isPointInOverflowControl() doesn't handle rect-based tests yet.
if (result.AddNodeToListBasedTestResult(
- NodeForHitTest(), location_in_container) == kStopHitTesting)
+ NodeForHitTest(), hit_test_location) == kStopHitTesting)
return true;
}
return false;
}
bool LayoutBlock::HitTestChildren(HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
HitTestAction hit_test_action) {
// We may use legacy code to hit-test the anonymous fieldset content wrapper
// child. The layout object for the rendered legend will be a child of that
@@ -1231,9 +1232,9 @@ bool LayoutBlock::HitTestChildren(HitTestResult& result,
bool may_contain_rendered_legend = IsAnonymousNGFieldsetContentWrapper();
DCHECK(!ChildrenInline());
- LayoutPoint scrolled_offset(HasOverflowClip()
- ? accumulated_offset - ScrolledContentOffset()
- : accumulated_offset);
+ PhysicalOffset scrolled_offset = accumulated_offset;
+ if (HasOverflowClip())
+ scrolled_offset -= PhysicalOffset(ScrolledContentOffset());
HitTestAction child_hit_test = hit_test_action;
if (hit_test_action == kHitTestChildBlockBackgrounds)
child_hit_test = kHitTestChildBlockBackground;
@@ -1243,25 +1244,23 @@ bool LayoutBlock::HitTestChildren(HitTestResult& result,
(may_contain_rendered_legend && child->IsRenderedLegend()))
continue;
- LayoutPoint child_point =
- FlipForWritingModeForChild(child, scrolled_offset);
-
+ PhysicalOffset child_accumulated_offset =
+ scrolled_offset + child->PhysicalLocation(this);
bool did_hit;
if (child->IsFloating()) {
if (hit_test_action != kHitTestFloat || !IsLayoutNGObject())
continue;
// Hit-test the floats in regular tree order if this is LayoutNG. Only
// legacy layout uses the FloatingObjects list.
- did_hit =
- child->HitTestAllPhases(result, location_in_container, child_point);
+ did_hit = child->HitTestAllPhases(result, hit_test_location,
+ child_accumulated_offset);
} else {
- did_hit = child->NodeAtPoint(result, location_in_container, child_point,
- child_hit_test);
+ did_hit = child->NodeAtPoint(result, hit_test_location,
+ child_accumulated_offset, child_hit_test);
}
if (did_hit) {
- UpdateHitTestResult(
- result, DeprecatedFlipForWritingMode(ToLayoutPoint(
- location_in_container.Point() - accumulated_offset)));
+ UpdateHitTestResult(result,
+ hit_test_location.Point() - accumulated_offset);
return true;
}
}
@@ -1305,15 +1304,13 @@ static inline bool IsEditingBoundary(const LayoutObject* ancestor,
// prevent crossing editable boundaries. This would require many tests.
PositionWithAffinity LayoutBlock::PositionForPointRespectingEditingBoundaries(
LineLayoutBox child,
- const LayoutPoint& point_in_parent_coordinates) const {
- LayoutPoint child_location = child.Location();
+ const PhysicalOffset& point_in_parent_coordinates) const {
+ PhysicalOffset child_location = child.PhysicalLocation();
if (child.IsInFlowPositioned())
- child_location += child.OffsetForInFlowPosition().ToLayoutPoint();
+ child_location += child.OffsetForInFlowPosition();
- // FIXME: This is wrong if the child's writing-mode is different from the
- // parent's.
- LayoutPoint point_in_child_coordinates(
- ToLayoutPoint(point_in_parent_coordinates - child_location));
+ PhysicalOffset point_in_child_coordinates =
+ point_in_parent_coordinates - child_location;
// If this is an anonymous layoutObject, we just recur normally
const Node* child_node = child.NonPseudoNode();
@@ -1336,8 +1333,8 @@ PositionWithAffinity LayoutBlock::PositionForPointRespectingEditingBoundaries(
// to the logical left or logical right of the child
LayoutUnit child_middle = LogicalWidthForChildSize(child.Size()) / 2;
LayoutUnit logical_left = IsHorizontalWritingMode()
- ? point_in_child_coordinates.X()
- : point_in_child_coordinates.Y();
+ ? point_in_child_coordinates.left
+ : point_in_child_coordinates.top;
if (logical_left < child_middle)
return ancestor->CreatePositionWithAffinity(child_node->NodeIndex());
return ancestor->CreatePositionWithAffinity(child_node->NodeIndex() + 1,
@@ -1345,27 +1342,18 @@ PositionWithAffinity LayoutBlock::PositionForPointRespectingEditingBoundaries(
}
PositionWithAffinity LayoutBlock::PositionForPointIfOutsideAtomicInlineLevel(
- const LayoutPoint& point) const {
+ const PhysicalOffset& point) const {
DCHECK(IsAtomicInlineLevel());
- // FIXME: This seems wrong when the object's writing-mode doesn't match the
- // line's writing-mode.
- LayoutUnit point_logical_left =
- IsHorizontalWritingMode() ? point.X() : point.Y();
- LayoutUnit point_logical_top =
- IsHorizontalWritingMode() ? point.Y() : point.X();
-
- const bool is_ltr = IsLtr(ResolvedDirection());
- if (point_logical_left < 0) {
- return CreatePositionWithAffinity(is_ltr ? CaretMinOffset()
- : CaretMaxOffset());
- }
- if (point_logical_left >= LogicalWidth()) {
- return CreatePositionWithAffinity(is_ltr ? CaretMaxOffset()
- : CaretMinOffset());
- }
- if (point_logical_top < 0)
+ LogicalOffset logical_offset =
+ point.ConvertToLogical(StyleRef().GetWritingMode(), ResolvedDirection(),
+ PhysicalSize(Size()), PhysicalSize());
+ if (logical_offset.inline_offset < 0)
return CreatePositionWithAffinity(CaretMinOffset());
- if (point_logical_top >= LogicalHeight())
+ if (logical_offset.inline_offset >= LogicalWidth())
+ return CreatePositionWithAffinity(CaretMaxOffset());
+ if (logical_offset.block_offset < 0)
+ return CreatePositionWithAffinity(CaretMinOffset());
+ if (logical_offset.block_offset >= LogicalHeight())
return CreatePositionWithAffinity(CaretMaxOffset());
return PositionWithAffinity();
}
@@ -1377,7 +1365,7 @@ static inline bool IsChildHitTestCandidate(LayoutBox* box) {
}
PositionWithAffinity LayoutBlock::PositionForPoint(
- const LayoutPoint& point) const {
+ const PhysicalOffset& point) const {
if (IsTable())
return LayoutBox::PositionForPoint(point);
@@ -1388,9 +1376,9 @@ PositionWithAffinity LayoutBlock::PositionForPoint(
return position;
}
- LayoutPoint point_in_contents = point;
+ PhysicalOffset point_in_contents = point;
OffsetForContents(point_in_contents);
- LayoutPoint point_in_logical_contents(point_in_contents);
+ LayoutPoint point_in_logical_contents = FlipForWritingMode(point_in_contents);
if (!IsHorizontalWritingMode())
point_in_logical_contents = point_in_logical_contents.TransposedPoint();
@@ -1431,13 +1419,9 @@ PositionWithAffinity LayoutBlock::PositionForPoint(
return LayoutBox::PositionForPoint(point);
}
-void LayoutBlock::OffsetForContents(LayoutPoint& offset) const {
- offset = DeprecatedFlipForWritingMode(offset);
-
+void LayoutBlock::OffsetForContents(PhysicalOffset& offset) const {
if (HasOverflowClip())
- offset += LayoutSize(ScrolledContentOffset());
-
- offset = DeprecatedFlipForWritingMode(offset);
+ offset += PhysicalOffset(ScrolledContentOffset());
}
void LayoutBlock::ScrollbarsChanged(bool horizontal_scrollbar_changed,
@@ -1981,6 +1965,8 @@ LayoutRect LayoutBlock::LocalCaretRect(
void LayoutBlock::AddOutlineRects(Vector<PhysicalRect>& rects,
const PhysicalOffset& additional_offset,
NGOutlineType include_block_overflows) const {
+ DCHECK_GE(GetDocument().Lifecycle().GetState(),
+ DocumentLifecycle::kAfterPerformLayout);
if (!IsAnonymous()) // For anonymous blocks, the children add outline rects.
rects.emplace_back(additional_offset, Size());
@@ -2283,6 +2269,9 @@ void LayoutBlock::CheckPositionedObjectsNeedLayout() {
if (!g_positioned_descendants_map)
return;
+ if (LayoutBlockedByDisplayLock(DisplayLockContext::kChildren))
+ return;
+
if (TrackedLayoutBoxListHashSet* positioned_descendant_set =
PositionedObjects()) {
TrackedLayoutBoxListHashSet::const_iterator end =
@@ -2291,7 +2280,10 @@ void LayoutBlock::CheckPositionedObjectsNeedLayout() {
positioned_descendant_set->begin();
it != end; ++it) {
LayoutBox* curr_box = *it;
- DCHECK(!curr_box->NeedsLayout());
+ DCHECK(!curr_box->SelfNeedsLayout());
+ DCHECK(
+ curr_box->LayoutBlockedByDisplayLock(DisplayLockContext::kChildren) ||
+ !curr_box->NeedsLayout());
}
}
}
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 d1081896b3e..824aa9b6ec4 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_block.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_block.h
@@ -218,7 +218,7 @@ class CORE_EXPORT LayoutBlock : public LayoutBox {
LayoutUnit TextIndentOffset() const;
- PositionWithAffinity PositionForPoint(const LayoutPoint&) const override;
+ PositionWithAffinity PositionForPoint(const PhysicalOffset&) const override;
static LayoutBlock* CreateAnonymousWithParentAndDisplay(
const LayoutObject*,
@@ -425,10 +425,10 @@ class CORE_EXPORT LayoutBlock : public LayoutBox {
bool HitTestOverflowControl(HitTestResult&,
const HitTestLocation&,
- const LayoutPoint& adjusted_location) override;
+ const PhysicalOffset& adjusted_location) override;
bool HitTestChildren(HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
HitTestAction) override;
void StyleWillChange(StyleDifference,
@@ -500,8 +500,8 @@ class CORE_EXPORT LayoutBlock : public LayoutBox {
bool TryLayoutDoingPositionedMovementOnly();
bool IsPointInOverflowControl(HitTestResult&,
- const LayoutPoint& location_in_container,
- const LayoutPoint& accumulated_offset) const;
+ const PhysicalOffset&,
+ const PhysicalOffset& accumulated_offset) const;
void ComputeBlockPreferredLogicalWidths(LayoutUnit& min_logical_width,
LayoutUnit& max_logical_width) const;
@@ -542,12 +542,13 @@ class CORE_EXPORT LayoutBlock : public LayoutBox {
// Adjust from painting offsets to the local coords of this layoutObject
void OffsetForContents(LayoutPoint&) const;
+ void OffsetForContents(PhysicalOffset&) const;
PositionWithAffinity PositionForPointRespectingEditingBoundaries(
LineLayoutBox child,
- const LayoutPoint& point_in_parent_coordinates) const;
+ const PhysicalOffset& point_in_parent_coordinates) const;
PositionWithAffinity PositionForPointIfOutsideAtomicInlineLevel(
- const LayoutPoint&) const;
+ const PhysicalOffset&) const;
virtual bool UpdateLogicalWidthAndColumnWidth();
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 74a283b17e8..d3e2b755633 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
@@ -38,7 +38,6 @@
#include "third_party/blink/renderer/core/editing/editor.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/use_counter.h"
#include "third_party/blink/renderer/core/html/html_dialog_element.h"
#include "third_party/blink/renderer/core/layout/hit_test_location.h"
#include "third_party/blink/renderer/core/layout/layout_analyzer.h"
@@ -69,6 +68,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_layer_scrollable_area.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
namespace blink {
@@ -381,9 +381,9 @@ bool LayoutBlockFlow::CheckIfIsSelfCollapsingBlock() const {
// text control are known, so they don't get layout until their parent has had
// layout - this is unique in the layout tree and means when we call
// isSelfCollapsingBlock on them we find that they still need layout.
- DCHECK(!NeedsLayout() || (GetNode() && GetNode()->IsElementNode() &&
- ToElement(GetNode())->ShadowPseudoId() ==
- "-webkit-input-placeholder"));
+ auto* element = DynamicTo<Element>(GetNode());
+ DCHECK(!NeedsLayout() ||
+ (element && element->ShadowPseudoId() == "-webkit-input-placeholder"));
if (LogicalHeight() > LayoutUnit() ||
StyleRef().LogicalMinHeight().IsPositive() ||
@@ -540,8 +540,7 @@ void LayoutBlockFlow::UpdateBlockLayout(bool relayout_children) {
if (IsHTMLDialogElement(GetNode()) && IsOutOfFlowPositioned())
PositionDialog();
- // Only clear child dirty bits, if we allowed child layout.
- ClearNeedsLayout(!LayoutBlockedByDisplayLock(DisplayLockContext::kChildren));
+ ClearNeedsLayout();
UpdateIsSelfCollapsing();
NotifyDisplayLockDidLayout(DisplayLockContext::kSelf);
}
@@ -2647,6 +2646,12 @@ void LayoutBlockFlow::DeleteLineBoxTree() {
floating_objects_->ClearLineBoxTreePointers();
line_boxes_.DeleteLineBoxTree();
+
+ // This function is called when children are moved to different parent. Clear
+ // NGPaintFragment now, because clearing NGPaintFragment clears associations
+ // between LayoutObject and NGPaintFragment. It needs to happen before moved
+ // children are laid out and associated.
+ SetPaintFragment(nullptr, nullptr);
}
int LayoutBlockFlow::LineCount(
@@ -3798,6 +3803,26 @@ void LayoutBlockFlow::RemoveFloatingObjectsBelow(FloatingObject* last_float,
}
}
+FloatingObject* LayoutBlockFlow::LastPlacedFloat(
+ FloatingObjectSetIterator* iterator) const {
+ const FloatingObjectSet& floating_object_set = floating_objects_->Set();
+ FloatingObjectSetIterator it = floating_object_set.end();
+ --it; // Go to last item.
+ FloatingObjectSetIterator begin = floating_object_set.begin();
+ FloatingObject* last_placed_floating_object = nullptr;
+ while (it != begin) {
+ --it;
+ if ((*it)->IsPlaced()) {
+ last_placed_floating_object = it->get();
+ ++it;
+ break;
+ }
+ }
+ if (iterator)
+ *iterator = it;
+ return last_placed_floating_object;
+}
+
bool LayoutBlockFlow::PlaceNewFloats(LayoutUnit logical_top_margin_edge,
LineWidth* width) {
if (!floating_objects_)
@@ -3814,18 +3839,8 @@ bool LayoutBlockFlow::PlaceNewFloats(LayoutUnit logical_top_margin_edge,
// Move backwards through our floating object list until we find a float that
// has already been positioned. Then we'll be able to move forward,
// positioning all of the new floats that need it.
- FloatingObjectSetIterator it = floating_object_set.end();
- --it; // Go to last item.
- FloatingObjectSetIterator begin = floating_object_set.begin();
- FloatingObject* last_placed_floating_object = nullptr;
- while (it != begin) {
- --it;
- if ((*it)->IsPlaced()) {
- last_placed_floating_object = it->get();
- ++it;
- break;
- }
- }
+ FloatingObjectSetIterator it;
+ FloatingObject* last_placed_floating_object = LastPlacedFloat(&it);
// The float cannot start above the top position of the last positioned float.
if (last_placed_floating_object) {
@@ -4173,33 +4188,30 @@ Node* LayoutBlockFlow::NodeForHitTest() const {
: LayoutBlock::NodeForHitTest();
}
-bool LayoutBlockFlow::HitTestChildren(
- HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
- HitTestAction hit_test_action) {
- LayoutPoint scrolled_offset(HasOverflowClip()
- ? accumulated_offset - ScrolledContentOffset()
- : accumulated_offset);
+bool LayoutBlockFlow::HitTestChildren(HitTestResult& result,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
+ HitTestAction hit_test_action) {
+ PhysicalOffset scrolled_offset = accumulated_offset;
+ if (HasOverflowClip())
+ scrolled_offset -= PhysicalOffset(ScrolledContentOffset());
if (hit_test_action == kHitTestFloat && !IsLayoutNGObject()) {
// Hit-test the floats using the FloatingObjects list if we're in legacy
// layout. LayoutNG, on the other hand, just hit-tests floats in regular
// tree order.
- if (HitTestFloats(result, location_in_container, scrolled_offset))
+ if (HitTestFloats(result, hit_test_location, scrolled_offset))
return true;
}
if (ChildrenInline()) {
- if (line_boxes_.HitTest(LineLayoutBoxModel(this), result,
- location_in_container, scrolled_offset,
- hit_test_action)) {
- UpdateHitTestResult(
- result, DeprecatedFlipForWritingMode(ToLayoutPoint(
- location_in_container.Point() - accumulated_offset)));
+ if (line_boxes_.HitTest(LineLayoutBoxModel(this), result, hit_test_location,
+ scrolled_offset, hit_test_action)) {
+ UpdateHitTestResult(result,
+ hit_test_location.Point() - accumulated_offset);
return true;
}
- } else if (LayoutBlock::HitTestChildren(result, location_in_container,
+ } else if (LayoutBlock::HitTestChildren(result, hit_test_location,
accumulated_offset,
hit_test_action)) {
return true;
@@ -4208,10 +4220,9 @@ bool LayoutBlockFlow::HitTestChildren(
return false;
}
-bool LayoutBlockFlow::HitTestFloats(
- HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset) {
+bool LayoutBlockFlow::HitTestFloats(HitTestResult& result,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset) {
if (!floating_objects_)
return false;
@@ -4223,16 +4234,16 @@ bool LayoutBlockFlow::HitTestFloats(
if (floating_object.ShouldPaint() &&
// TODO(wangxianzhu): Should this be a DCHECK?
!floating_object.GetLayoutObject()->HasSelfPaintingLayer()) {
- LayoutUnit x_offset = XPositionForFloatIncludingMargin(floating_object) -
- floating_object.GetLayoutObject()->Location().X();
- LayoutUnit y_offset = YPositionForFloatIncludingMargin(floating_object) -
- floating_object.GetLayoutObject()->Location().Y();
- LayoutPoint child_point = FlipFloatForWritingModeForChild(
- floating_object, accumulated_offset + LayoutSize(x_offset, y_offset));
+ PhysicalOffset child_accumulated_offset = accumulated_offset;
+ child_accumulated_offset +=
+ PhysicalOffset(XPositionForFloatIncludingMargin(floating_object),
+ YPositionForFloatIncludingMargin(floating_object));
if (floating_object.GetLayoutObject()->HitTestAllPhases(
- result, location_in_container, child_point)) {
- UpdateHitTestResult(
- result, location_in_container.Point() - ToLayoutSize(child_point));
+ result, hit_test_location, child_accumulated_offset)) {
+ PhysicalOffset result_offset =
+ child_accumulated_offset -
+ floating_object.GetLayoutObject()->PhysicalLocation();
+ UpdateHitTestResult(result, hit_test_location.Point() - result_offset);
return true;
}
}
@@ -4535,7 +4546,7 @@ void LayoutBlockFlow::PositionDialog() {
void LayoutBlockFlow::SimplifiedNormalFlowInlineLayout() {
DCHECK(ChildrenInline());
- ListHashSet<RootInlineBox*> line_boxes;
+ LinkedHashSet<RootInlineBox*> line_boxes;
for (InlineWalker walker(LineLayoutBlockFlow(this)); !walker.AtEnd();
walker.Advance()) {
LayoutObject* o = walker.Current().GetLayoutObject();
@@ -4555,7 +4566,7 @@ void LayoutBlockFlow::SimplifiedNormalFlowInlineLayout() {
// FIXME: Glyph overflow will get lost in this case, but not really a big
// deal.
GlyphOverflowAndFallbackFontsMap text_box_data_map;
- for (ListHashSet<RootInlineBox*>::const_iterator it = line_boxes.begin();
+ for (LinkedHashSet<RootInlineBox*>::const_iterator it = line_boxes.begin();
it != line_boxes.end(); ++it) {
RootInlineBox* box = *it;
box->ComputeOverflow(box->LineTop(), box->LineBottom(), text_box_data_map);
@@ -4565,7 +4576,7 @@ void LayoutBlockFlow::SimplifiedNormalFlowInlineLayout() {
bool LayoutBlockFlow::RecalcInlineChildrenLayoutOverflow() {
DCHECK(ChildrenInline());
bool children_layout_overflow_changed = false;
- ListHashSet<RootInlineBox*> line_boxes;
+ LinkedHashSet<RootInlineBox*> line_boxes;
for (InlineWalker walker(LineLayoutBlockFlow(this)); !walker.AtEnd();
walker.Advance()) {
LayoutObject* layout_object = walker.Current().GetLayoutObject();
@@ -4585,7 +4596,7 @@ bool LayoutBlockFlow::RecalcInlineChildrenLayoutOverflow() {
// FIXME: Glyph overflow will get lost in this case, but not really a big
// deal.
GlyphOverflowAndFallbackFontsMap text_box_data_map;
- for (ListHashSet<RootInlineBox*>::const_iterator it = line_boxes.begin();
+ for (LinkedHashSet<RootInlineBox*>::const_iterator it = line_boxes.begin();
it != line_boxes.end(); ++it) {
RootInlineBox* box = *it;
box->ClearKnownToHaveNoOverflow();
@@ -4615,7 +4626,7 @@ void LayoutBlockFlow::RecalcInlineChildrenVisualOverflow() {
}
PositionWithAffinity LayoutBlockFlow::PositionForPoint(
- const LayoutPoint& point) const {
+ const PhysicalOffset& point) const {
if (IsAtomicInlineLevel()) {
PositionWithAffinity position =
PositionForPointIfOutsideAtomicInlineLevel(point);
@@ -4625,9 +4636,9 @@ PositionWithAffinity LayoutBlockFlow::PositionForPoint(
if (!ChildrenInline())
return LayoutBlock::PositionForPoint(point);
- LayoutPoint point_in_contents = point;
+ PhysicalOffset point_in_contents = point;
OffsetForContents(point_in_contents);
- LayoutPoint point_in_logical_contents(point_in_contents);
+ LayoutPoint point_in_logical_contents = FlipForWritingMode(point_in_contents);
if (!IsHorizontalWritingMode())
point_in_logical_contents = point_in_logical_contents.TransposedPoint();
@@ -4722,7 +4733,8 @@ PositionWithAffinity LayoutBlockFlow::PositionForPoint(
if (!IsHorizontalWritingMode())
point = point.TransposedPoint();
return PositionForPointRespectingEditingBoundaries(
- LineLayoutBox(closest_box->GetLineLayoutItem()), point);
+ LineLayoutBox(closest_box->GetLineLayoutItem()),
+ FlipForWritingMode(point));
}
// pass the box a top position that is inside it
@@ -4730,7 +4742,8 @@ PositionWithAffinity LayoutBlockFlow::PositionForPoint(
closest_box->Root().BlockDirectionPointInLine());
if (!IsHorizontalWritingMode())
point = point.TransposedPoint();
- return closest_box->GetLineLayoutItem().PositionForPoint(point);
+ return closest_box->GetLineLayoutItem().PositionForPoint(
+ FlipForWritingMode(point));
}
if (last_root_box_with_children) {
@@ -4765,7 +4778,7 @@ void LayoutBlockFlow::ShowLineTreeAndMark(const InlineBox* marked_box1,
root->DumpLineTreeAndMark(string_blockflow, marked_box1, marked_label1,
marked_box2, marked_label2, obj, 1);
}
- DLOG(INFO) << "\n" << string_blockflow.ToString().Utf8().data();
+ DLOG(INFO) << "\n" << string_blockflow.ToString().Utf8();
}
#endif
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 2253ccb9101..c18351ae675 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
@@ -392,6 +392,11 @@ class CORE_EXPORT LayoutBlockFlow : public LayoutBlock {
FloatingObject* InsertFloatingObject(LayoutBox&);
+ // Return the last placed float. If |iterator| is non-null, it will be set to
+ // the float right after said float.
+ FloatingObject* LastPlacedFloat(
+ FloatingObjectSetIterator* iterator = nullptr) const;
+
// Position and lay out all floats that have not yet been positioned.
//
// This will mark them as "placed", which means that they have found their
@@ -424,7 +429,7 @@ class CORE_EXPORT LayoutBlockFlow : public LayoutBlock {
bool RecalcInlineChildrenLayoutOverflow();
void RecalcInlineChildrenVisualOverflow();
- PositionWithAffinity PositionForPoint(const LayoutPoint&) const override;
+ PositionWithAffinity PositionForPoint(const PhysicalOffset&) const override;
LayoutUnit LowestFloatLogicalBottom(EClear = EClear::kBoth) const;
@@ -527,8 +532,8 @@ class CORE_EXPORT LayoutBlockFlow : public LayoutBlock {
Node* NodeForHitTest() const final;
bool HitTestChildren(HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
HitTestAction) override;
PhysicalOffset AccumulateInFlowPositionOffsets() const override;
@@ -576,8 +581,8 @@ class CORE_EXPORT LayoutBlockFlow : public LayoutBlock {
bool make_child_paint_other_floats);
bool HitTestFloats(HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset);
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset);
void ClearFloats(EClear);
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 a2ae7e23a12..bd50e651198 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
@@ -197,16 +197,17 @@ InlineFlowBox* LayoutBlockFlow::CreateLineBoxes(LineLayoutItem line_layout_item,
line_layout_item = LineLayoutItem(this);
}
- SECURITY_DCHECK(line_layout_item.IsLayoutInline() ||
- line_layout_item.IsEqual(this));
-
- LineLayoutInline inline_flow(
- !line_layout_item.IsEqual(this) ? line_layout_item : nullptr);
-
// Get the last box we made for this layout object.
- parent_box = inline_flow
- ? inline_flow.LastLineBox()
- : LineLayoutBlockFlow(line_layout_item).LastLineBox();
+ bool allowed_to_construct_new_box;
+ if (line_layout_item.IsLayoutInline()) {
+ LineLayoutInline inline_flow(line_layout_item);
+ parent_box = inline_flow.LastLineBox();
+ allowed_to_construct_new_box = inline_flow.AlwaysCreateLineBoxes();
+ } else {
+ DCHECK(line_layout_item.IsEqual(this));
+ parent_box = LineLayoutBlockFlow(line_layout_item).LastLineBox();
+ allowed_to_construct_new_box = true;
+ }
// If this box or its ancestor is constructed then it is from a previous
// line, and we need to make a new box for our line. If this box or its
@@ -215,8 +216,6 @@ InlineFlowBox* LayoutBlockFlow::CreateLineBoxes(LineLayoutItem line_layout_item,
// inline has actually been split in two on the same line (this can happen
// with very fancy language mixtures).
bool constructed_new_box = false;
- bool allowed_to_construct_new_box =
- !inline_flow || inline_flow.AlwaysCreateLineBoxes();
bool can_use_existing_parent_box =
parent_box && !ParentIsConstructedOrHaveNext(parent_box);
if (allowed_to_construct_new_box && !can_use_existing_parent_box) {
@@ -2222,15 +2221,25 @@ void LayoutBlockFlow::DetermineEndPosition(LineLayoutState& layout_state,
BidiStatus& clean_line_bidi_status) {
DCHECK(!layout_state.EndLine());
RootInlineBox* last = nullptr;
+ bool previous_was_clean = false;
for (RootInlineBox* curr = start_line->NextRootBox(); curr;
curr = curr->NextRootBox()) {
if (!curr->IsDirty() && LineBoxHasBRWithClearance(curr))
return;
- if (curr->IsDirty())
+ // A line is considered clean when it's not marked dirty, AND it either
+ // doesn't contain floats, or follows another clean line. The legacy line
+ // layout engine has issues with handling floats at line boundaries,
+ // potentially resulting in a float belonging to two different lines,
+ // causing all kinds of misery.
+ if (curr->IsDirty() || (curr->FloatsPtr() && !previous_was_clean)) {
last = nullptr;
- else if (!last)
- last = curr;
+ previous_was_clean = false;
+ } else {
+ if (!last)
+ last = curr;
+ previous_was_clean = true;
+ }
}
if (!last)
@@ -2315,10 +2324,11 @@ bool LayoutBlockFlow::MatchedEndLine(LineLayoutState& layout_state,
// The first clean line doesn't match, but we can check a handful of following
// lines to try to match back up.
- static int num_lines = 8; // The # of lines we're willing to match against.
+ // The # of lines we're willing to match against.
+ constexpr int kNumLines = 8;
RootInlineBox* original_end_line = layout_state.EndLine();
RootInlineBox* line = original_end_line;
- for (int i = 0; i < num_lines && line; i++, line = line->NextRootBox()) {
+ for (int i = 0; i < kNumLines && line; i++, line = line->NextRootBox()) {
if (line->LineBreakObj() == resolver.GetPosition().GetLineLayoutItem() &&
line->LineBreakPos() == resolver.GetPosition().Offset()) {
// We have a match.
@@ -2712,7 +2722,7 @@ LayoutUnit LayoutBlockFlow::StartAlignedOffsetForLine(
void LayoutBlockFlow::SetShouldDoFullPaintInvalidationForFirstLine() {
DCHECK(ChildrenInline());
if (RootInlineBox* first_root_box = FirstRootBox())
- first_root_box->SetShouldDoFullPaintInvalidationRecursively();
+ first_root_box->SetShouldDoFullPaintInvalidationForFirstLine();
else if (const NGPaintFragment* paint_fragment = PaintFragment())
paint_fragment->SetShouldDoFullPaintInvalidationForFirstLine();
}
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 88eabb36612..62900aa1f95 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
@@ -25,7 +25,7 @@ TEST_F(LayoutBlockTest, LayoutNameCalledWithNullStyle) {
obj->SetModifiedStyleOutsideStyleRecalc(nullptr,
LayoutObject::ApplyStyleChanges::kNo);
EXPECT_FALSE(obj->Style());
- EXPECT_THAT(obj->DecoratedName().Ascii().data(),
+ EXPECT_THAT(obj->DecoratedName().Ascii(),
MatchesRegex("LayoutN?G?BlockFlow \\(anonymous\\)"));
obj->Destroy();
}
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 b25fa1ffddb..b4b7de92a26 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_box.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_box.cc
@@ -39,6 +39,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/visual_viewport.h"
#include "third_party/blink/renderer/core/html/html_element.h"
#include "third_party/blink/renderer/core/html/html_frame_element_base.h"
#include "third_party/blink/renderer/core/html/html_frame_owner_element.h"
@@ -130,12 +131,7 @@ LayoutBox::LayoutBox(ContainerNode* node)
SetIsHTMLLegendElement();
}
-LayoutBox::~LayoutBox() {
-#if DCHECK_IS_ON()
- if (IsInLayoutNGInlineFormattingContext())
- DCHECK(!first_paint_fragment_);
-#endif
-}
+LayoutBox::~LayoutBox() = default;
PaintLayerType LayoutBox::LayerTypeRequired() const {
// hasAutoZIndex only returns true if the element is positioned or a flex-item
@@ -167,6 +163,11 @@ void LayoutBox::WillBeDestroyed() {
ShapeOutsideInfo::RemoveInfo(*this);
+ if (!DocumentBeingDestroyed()) {
+ if (NGPaintFragment* first_inline_fragment = FirstInlineFragment())
+ first_inline_fragment->LayoutObjectWillBeDestroyed();
+ }
+
LayoutBoxModelObject::WillBeDestroyed();
}
@@ -664,8 +665,8 @@ void LayoutBox::ScrollToPosition(const FloatPoint& position,
GetScrollableArea()->ScrollToAbsolutePosition(position, scroll_behavior);
}
-LayoutRect LayoutBox::ScrollRectToVisibleRecursive(
- const LayoutRect& absolute_rect,
+PhysicalRect LayoutBox::ScrollRectToVisibleRecursive(
+ const PhysicalRect& absolute_rect,
const WebScrollIntoViewParams& params) {
DCHECK(params.GetScrollType() == kProgrammaticScroll ||
params.GetScrollType() == kUserScroll);
@@ -684,7 +685,7 @@ LayoutRect LayoutBox::ScrollRectToVisibleRecursive(
// Presumably the same issue as in setScrollTop. See crbug.com/343132.
DisableCompositingQueryAsserts disabler;
- LayoutRect absolute_rect_to_scroll = absolute_rect;
+ PhysicalRect absolute_rect_to_scroll = absolute_rect;
if (absolute_rect_to_scroll.Width() <= 0)
absolute_rect_to_scroll.SetWidth(LayoutUnit(1));
if (absolute_rect_to_scroll.Height() <= 0)
@@ -695,7 +696,7 @@ LayoutRect LayoutBox::ScrollRectToVisibleRecursive(
if (ContainingBlock())
parent_box = ContainingBlock();
- LayoutRect absolute_rect_for_parent;
+ PhysicalRect absolute_rect_for_parent;
if (!IsLayoutView() && HasOverflowClip()) {
absolute_rect_for_parent =
GetScrollableArea()->ScrollIntoView(absolute_rect_to_scroll, params);
@@ -714,21 +715,26 @@ LayoutRect LayoutBox::ScrollRectToVisibleRecursive(
AllowedToPropagateRecursiveScrollToParentFrame(params)) {
parent_box = owner_element->GetLayoutObject()->EnclosingBox();
LayoutView* parent_view = owner_element->GetLayoutObject()->View();
- absolute_rect_for_parent =
- View()
- ->LocalToAncestorRect(
- PhysicalRectToBeNoop(absolute_rect_for_parent), parent_view,
- kTraverseDocumentBoundaries)
- .ToLayoutRect();
+ absolute_rect_for_parent = View()->LocalToAncestorRect(
+ absolute_rect_for_parent, parent_view, kTraverseDocumentBoundaries);
}
} else {
absolute_rect_for_parent = absolute_rect_to_scroll;
}
- // If we are fixed-position and stick to the viewport, it is useless to
- // scroll the parent.
- if (StyleRef().GetPosition() == EPosition::kFixed && Container() == View())
- return absolute_rect_for_parent;
+ // If we're in a position:fixed element, scrolling the layout viewport won't
+ // have any effect, so we avoid using the RootFrameViewport and explicitly
+ // scroll the visual viewport if we can. If not, we're done.
+ if (StyleRef().GetPosition() == EPosition::kFixed && Container() == View() &&
+ params.make_visible_in_visual_viewport) {
+ if (GetFrame()->IsMainFrame()) {
+ // TODO(donnd): We should continue the recursion if we're in a subframe.
+ return GetFrame()->GetPage()->GetVisualViewport().ScrollIntoView(
+ absolute_rect_for_parent, params);
+ } else {
+ return absolute_rect_for_parent;
+ }
+ }
if (parent_box) {
return parent_box->ScrollRectToVisibleRecursive(absolute_rect_for_parent,
@@ -1024,7 +1030,7 @@ bool LayoutBox::CanBeProgramaticallyScrolled() const {
return node && HasEditableStyle(*node);
}
-void LayoutBox::Autoscroll(const LayoutPoint& position_in_root_frame) {
+void LayoutBox::Autoscroll(const PhysicalOffset& position_in_root_frame) {
LocalFrame* frame = GetFrame();
if (!frame)
return;
@@ -1033,10 +1039,11 @@ void LayoutBox::Autoscroll(const LayoutPoint& position_in_root_frame) {
if (!frame_view)
return;
- LayoutPoint absolute_position =
- frame_view->ConvertFromRootFrame(LayoutPoint(position_in_root_frame));
+ PhysicalOffset absolute_position =
+ frame_view->ConvertFromRootFrame(position_in_root_frame);
ScrollRectToVisibleRecursive(
- LayoutRect(absolute_position, LayoutSize(1, 1)),
+ PhysicalRect(absolute_position,
+ PhysicalSize(LayoutUnit(1), LayoutUnit(1))),
WebScrollIntoViewParams(ScrollAlignment::kAlignToEdgeIfNeeded,
ScrollAlignment::kAlignToEdgeIfNeeded,
kUserScroll));
@@ -1158,11 +1165,10 @@ IntPoint LayoutBox::ScrollOrigin() const {
return GetScrollableArea() ? GetScrollableArea()->ScrollOrigin() : IntPoint();
}
-IntSize LayoutBox::ScrolledContentOffset() const {
+LayoutSize LayoutBox::ScrolledContentOffset() const {
DCHECK(HasOverflowClip());
DCHECK(GetScrollableArea());
- // FIXME: Return DoubleSize here. crbug.com/414283.
- return GetScrollableArea()->ScrollOffsetInt();
+ return LayoutSize(GetScrollableArea()->GetScrollOffset());
}
PhysicalRect LayoutBox::ClippingRect(const PhysicalOffset& location) const {
@@ -1235,7 +1241,7 @@ bool LayoutBox::MapVisualRectToContainer(
// c) Container scroll offset.
if (container_object->IsBox() && container_object != ancestor &&
ToLayoutBox(container_object)->ContainedContentsScroll(*this)) {
- IntSize offset = -ToLayoutBox(container_object)->ScrolledContentOffset();
+ LayoutSize offset(-ToLayoutBox(container_object)->ScrolledContentOffset());
transform.PostTranslate(offset.Width(), offset.Height());
}
@@ -1587,8 +1593,8 @@ LayoutUnit LayoutBox::AdjustContentBoxLogicalHeightForBoxSizing(
// Hit Testing
bool LayoutBox::HitTestAllPhases(HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
HitTestFilter hit_test_filter) {
// Check if we need to do anything at all.
// If we have clipping, then we can't have any spillout.
@@ -1604,70 +1610,68 @@ bool LayoutBox::HitTestAllPhases(HitTestResult& result,
: PhysicalVisualOverflowRect();
}
- LayoutRect adjusted_overflow_box = overflow_box.ToLayoutRect();
- adjusted_overflow_box.MoveBy(accumulated_offset + Location());
- if (!location_in_container.Intersects(adjusted_overflow_box))
+ PhysicalRect adjusted_overflow_box = overflow_box;
+ adjusted_overflow_box.Move(accumulated_offset);
+ if (!hit_test_location.Intersects(adjusted_overflow_box))
return false;
}
- return LayoutObject::HitTestAllPhases(result, location_in_container,
+ return LayoutObject::HitTestAllPhases(result, hit_test_location,
accumulated_offset, hit_test_filter);
}
bool LayoutBox::NodeAtPoint(HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
HitTestAction action) {
- LayoutPoint adjusted_location = accumulated_offset + Location();
-
bool should_hit_test_self = IsInSelfHitTestingPhase(action);
if (should_hit_test_self && HasOverflowClip() &&
- HitTestOverflowControl(result, location_in_container, adjusted_location))
+ HitTestOverflowControl(result, hit_test_location, accumulated_offset))
return true;
- bool skip_children = (result.GetHitTestRequest().GetStopNode() == this);
+ bool skip_children = (result.GetHitTestRequest().GetStopNode() == this) ||
+ PaintBlockedByDisplayLock(DisplayLockContext::kChildren);
if (!skip_children && ShouldClipOverflow()) {
// PaintLayer::HitTestContentsForFragments checked the fragments'
// foreground rect for intersection if a layer is self painting,
// so only do the overflow clip check here for non-self-painting layers.
if (!HasSelfPaintingLayer() &&
- !location_in_container.Intersects(OverflowClipRect(
- adjusted_location, kExcludeOverlayScrollbarSizeForHitTesting))) {
+ !hit_test_location.Intersects(OverflowClipRect(
+ accumulated_offset, kExcludeOverlayScrollbarSizeForHitTesting))) {
skip_children = true;
}
if (!skip_children && StyleRef().HasBorderRadius()) {
- LayoutRect bounds_rect(adjusted_location, Size());
- skip_children = !location_in_container.Intersects(
- StyleRef().GetRoundedInnerBorderFor(bounds_rect));
+ PhysicalRect bounds_rect(accumulated_offset, Size());
+ skip_children = !hit_test_location.Intersects(
+ StyleRef().GetRoundedInnerBorderFor(bounds_rect.ToLayoutRect()));
}
}
- if (!skip_children && HitTestChildren(result, location_in_container,
- adjusted_location, action)) {
+ if (!skip_children &&
+ HitTestChildren(result, hit_test_location, accumulated_offset, action)) {
return true;
}
if (StyleRef().HasBorderRadius() &&
- HitTestClippedOutByBorder(location_in_container, adjusted_location))
+ HitTestClippedOutByBorder(hit_test_location, accumulated_offset))
return false;
// Now hit test ourselves.
if (should_hit_test_self &&
VisibleToHitTestRequest(result.GetHitTestRequest())) {
- LayoutRect bounds_rect;
+ PhysicalRect bounds_rect;
if (result.GetHitTestRequest().GetType() &
HitTestRequest::kHitTestVisualOverflow) {
- bounds_rect = PhysicalVisualOverflowRectIncludingFilters().ToLayoutRect();
+ bounds_rect = PhysicalVisualOverflowRectIncludingFilters();
} else {
- bounds_rect = BorderBoxRect();
+ bounds_rect = PhysicalBorderBoxRect();
}
- bounds_rect.Move(ToSize(adjusted_location));
- if (location_in_container.Intersects(bounds_rect)) {
- UpdateHitTestResult(result, DeprecatedFlipForWritingMode(
- location_in_container.Point() -
- ToLayoutSize(adjusted_location)));
+ bounds_rect.Move(accumulated_offset);
+ if (hit_test_location.Intersects(bounds_rect)) {
+ UpdateHitTestResult(result,
+ hit_test_location.Point() - accumulated_offset);
if (result.AddNodeToListBasedTestResult(NodeForHitTest(),
- location_in_container,
+ hit_test_location,
bounds_rect) == kStopHitTesting)
return true;
}
@@ -1677,14 +1681,20 @@ bool LayoutBox::NodeAtPoint(HitTestResult& result,
}
bool LayoutBox::HitTestChildren(HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
HitTestAction action) {
for (LayoutObject* child = SlowLastChild(); child;
child = child->PreviousSibling()) {
- if ((!child->HasLayer() ||
- !ToLayoutBoxModelObject(child)->Layer()->IsSelfPaintingLayer()) &&
- child->NodeAtPoint(result, location_in_container, accumulated_offset,
+ if (child->HasLayer() &&
+ ToLayoutBoxModelObject(child)->Layer()->IsSelfPaintingLayer())
+ continue;
+
+ PhysicalOffset child_accumulated_offset = accumulated_offset;
+ if (child->IsBox())
+ child_accumulated_offset += ToLayoutBox(child)->PhysicalLocation(this);
+
+ if (child->NodeAtPoint(result, hit_test_location, child_accumulated_offset,
action))
return true;
}
@@ -1693,12 +1703,12 @@ bool LayoutBox::HitTestChildren(HitTestResult& result,
}
bool LayoutBox::HitTestClippedOutByBorder(
- const HitTestLocation& location_in_container,
- const LayoutPoint& border_box_location) const {
- LayoutRect border_rect = BorderBoxRect();
- border_rect.MoveBy(border_box_location);
- return !location_in_container.Intersects(
- StyleRef().GetRoundedBorderFor(border_rect));
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& border_box_location) const {
+ PhysicalRect border_rect = PhysicalBorderBoxRect();
+ border_rect.Move(border_box_location);
+ return !hit_test_location.Intersects(
+ StyleRef().GetRoundedBorderFor(border_rect.ToLayoutRect()));
}
void LayoutBox::Paint(const PaintInfo& paint_info) const {
@@ -1966,9 +1976,8 @@ void LayoutBox::SizeChanged() {
if (!NeedsLayout())
SetShouldCheckForPaintInvalidation();
- if (GetNode() && GetNode()->IsElementNode()) {
- Element& element = ToElement(*GetNode());
- element.SetNeedsResizeObserverUpdate();
+ if (auto* element = DynamicTo<Element>(GetNode())) {
+ element->SetNeedsResizeObserverUpdate();
}
}
@@ -2278,9 +2287,7 @@ InlineBox* LayoutBox::CreateInlineBox() {
}
void LayoutBox::DirtyLineBoxes(bool full_layout) {
- if (IsInLayoutNGInlineFormattingContext()) {
- SetFirstInlineFragment(nullptr);
- } else if (inline_box_wrapper_) {
+ if (!IsInLayoutNGInlineFormattingContext() && inline_box_wrapper_) {
if (full_layout) {
inline_box_wrapper_->Destroy();
inline_box_wrapper_ = nullptr;
@@ -2449,14 +2456,16 @@ scoped_refptr<const NGLayoutResult> LayoutBox::CachedLayoutResult(
if (*out_cache_status == NGLayoutCacheStatus::kNeedsSimplifiedLayout)
return nullptr;
+ physical_fragment.CheckType();
+
DCHECK_EQ(*out_cache_status, NGLayoutCacheStatus::kHit);
// We can safely re-use this fragment if we are positioned, and only our
// position constraints changed (left/top/etc). However we need to clear the
// dirty layout bit(s). Note that we may be here because we are display locked
- // and have cached a locked layout result. In that case, we still need to
- // retain child bits.
- ClearNeedsLayout(!LayoutBlockedByDisplayLock(DisplayLockContext::kChildren));
+ // and have cached a locked layout result. In that case, this function will
+ // not clear the child dirty bits.
+ ClearNeedsLayout();
// The checks above should be enough to bail if layout is incomplete, but
// let's verify:
@@ -2543,9 +2552,7 @@ void LayoutBox::MoveWithEdgeOfInlineContainerIfNecessary(bool is_horizontal) {
}
void LayoutBox::DeleteLineBoxWrapper() {
- if (IsInLayoutNGInlineFormattingContext()) {
- SetFirstInlineFragment(nullptr);
- } else if (inline_box_wrapper_) {
+ if (!IsInLayoutNGInlineFormattingContext() && inline_box_wrapper_) {
if (!DocumentBeingDestroyed())
inline_box_wrapper_->Remove();
inline_box_wrapper_->Destroy();
@@ -2780,7 +2787,7 @@ bool LayoutBox::MapToVisualRectInAncestorSpaceInternal(
// get the right dirty rect. Since this is called from
// LayoutObject::setStyle, the relative position flag on the LayoutObject
// has been cleared, so use the one on the style().
- container_offset += Layer()->OffsetForInFlowPosition();
+ container_offset += OffsetForInFlowPosition();
}
if (skip_info.FilterSkipped()) {
@@ -3796,13 +3803,7 @@ LayoutUnit LayoutBox::ComputePercentageLogicalHeight(
&cb, &skipped_auto_height_containing_block);
DCHECK(cb);
-
- // If the container of the descendant is a replaced element (a VIDEO, for
- // instance), |cb| (which uses ContainingBlock()) may actually not be in the
- // containing block chain for the descendant.
- const LayoutObject* container = Container();
- if (!container->IsLayoutReplaced())
- cb->AddPercentHeightDescendant(const_cast<LayoutBox*>(this));
+ cb->AddPercentHeightDescendant(const_cast<LayoutBox*>(this));
if (available_height == -1)
return available_height;
@@ -5236,7 +5237,7 @@ LayoutRect LayoutBox::LocalCaretRect(
}
PositionWithAffinity LayoutBox::PositionForPoint(
- const LayoutPoint& point) const {
+ const PhysicalOffset& point) const {
// no children...return this layout object's element, if there is one, and
// offset 0
LayoutObject* first_child = SlowFirstChild();
@@ -5247,12 +5248,10 @@ PositionWithAffinity LayoutBox::PositionForPoint(
if (IsTable() && NonPseudoNode()) {
const Node& node = *NonPseudoNode();
- LayoutUnit right = Size().Width() - VerticalScrollbarWidth();
- LayoutUnit bottom = Size().Height() - HorizontalScrollbarHeight();
-
- if (point.X() < 0 || point.X() > right || point.Y() < 0 ||
- point.Y() > bottom) {
- if (point.X() <= right / 2) {
+ LayoutUnit x_in_block_direction = FlipForWritingMode(point.left);
+ if (x_in_block_direction < 0 || x_in_block_direction > Size().Width() ||
+ point.top < 0 || point.top > Size().Height()) {
+ if (x_in_block_direction <= Size().Width() / 2) {
return CreatePositionWithAffinity(FirstPositionInOrBeforeNode(node));
}
return CreatePositionWithAffinity(LastPositionInOrAfterNode(node));
@@ -5262,9 +5261,9 @@ PositionWithAffinity LayoutBox::PositionForPoint(
// Pass off to the closest child.
LayoutUnit min_dist = LayoutUnit::Max();
LayoutBox* closest_layout_object = nullptr;
- LayoutPoint adjusted_point = point;
+ PhysicalOffset adjusted_point = point;
if (IsTableRow())
- adjusted_point.MoveBy(Location());
+ adjusted_point += PhysicalLocation();
for (LayoutObject* layout_object = first_child; layout_object;
layout_object = layout_object->NextSibling()) {
@@ -5283,55 +5282,58 @@ PositionWithAffinity LayoutBox::PositionForPoint(
LayoutUnit bottom = top + layout_box->ContentHeight();
LayoutUnit left =
layout_box->BorderLeft() + layout_box->PaddingLeft() +
- (IsTableRow() ? LayoutUnit() : layout_box->Location().X());
+ (IsTableRow() ? LayoutUnit() : layout_box->PhysicalLocation().left);
LayoutUnit right = left + layout_box->ContentWidth();
- if (point.X() <= right && point.X() >= left && point.Y() <= top &&
- point.Y() >= bottom) {
- if (layout_box->IsTableRow())
+ if (point.left <= right && point.left >= left && point.top <= top &&
+ point.top >= bottom) {
+ if (layout_box->IsTableRow()) {
return layout_box->PositionForPoint(point + adjusted_point -
- layout_box->LocationOffset());
- return layout_box->PositionForPoint(point - layout_box->LocationOffset());
+ layout_box->PhysicalLocation());
+ }
+ return layout_box->PositionForPoint(point -
+ layout_box->PhysicalLocation());
}
// Find the distance from (x, y) to the box. Split the space around the box
// into 8 pieces and use a different compare depending on which piece (x, y)
// is in.
- LayoutPoint cmp;
- if (point.X() > right) {
- if (point.Y() < top)
- cmp = LayoutPoint(right, top);
- else if (point.Y() > bottom)
- cmp = LayoutPoint(right, bottom);
+ PhysicalOffset cmp;
+ if (point.left > right) {
+ if (point.top < top)
+ cmp = PhysicalOffset(right, top);
+ else if (point.top > bottom)
+ cmp = PhysicalOffset(right, bottom);
else
- cmp = LayoutPoint(right, point.Y());
- } else if (point.X() < left) {
- if (point.Y() < top)
- cmp = LayoutPoint(left, top);
- else if (point.Y() > bottom)
- cmp = LayoutPoint(left, bottom);
+ cmp = PhysicalOffset(right, point.top);
+ } else if (point.left < left) {
+ if (point.top < top)
+ cmp = PhysicalOffset(left, top);
+ else if (point.top > bottom)
+ cmp = PhysicalOffset(left, bottom);
else
- cmp = LayoutPoint(left, point.Y());
+ cmp = PhysicalOffset(left, point.top);
} else {
- if (point.Y() < top)
- cmp = LayoutPoint(point.X(), top);
+ if (point.top < top)
+ cmp = PhysicalOffset(point.left, top);
else
- cmp = LayoutPoint(point.X(), bottom);
+ cmp = PhysicalOffset(point.left, bottom);
}
- LayoutSize difference = cmp - point;
+ PhysicalOffset difference = cmp - point;
- LayoutUnit dist = difference.Width() * difference.Width() +
- difference.Height() * difference.Height();
+ LayoutUnit dist =
+ difference.left * difference.left + difference.top * difference.top;
if (dist < min_dist) {
closest_layout_object = layout_box;
min_dist = dist;
}
}
- if (closest_layout_object)
+ if (closest_layout_object) {
return closest_layout_object->PositionForPoint(
- adjusted_point - closest_layout_object->LocationOffset());
+ adjusted_point - closest_layout_object->PhysicalLocation());
+ }
return CreatePositionWithAffinity(
NonPseudoNode() ? FirstPositionInOrBeforeNode(*NonPseudoNode())
: Position());
@@ -5379,7 +5381,7 @@ bool LayoutBox::ShouldBeConsideredAsReplaced() const {
// to check the Element type. This also applies to images, since we may have
// created a block-flow LayoutObject for the ALT text (which still counts as
// replaced).
- auto* element = ToElementOrNull(GetNode());
+ auto* element = DynamicTo<Element>(GetNode());
if (!element)
return false;
if (element->IsFormControlElement()) {
@@ -5741,7 +5743,8 @@ LayoutBox::PaginationBreakability LayoutBox::GetPaginationBreakability() const {
(Parent() && IsWritingModeRoot()) ||
(IsOutOfFlowPositioned() &&
StyleRef().GetPosition() == EPosition::kFixed) ||
- ShouldApplySizeContainment() || DisplayLockInducesSizeContainment())
+ ShouldApplySizeContainment() || DisplayLockInducesSizeContainment() ||
+ IsFrameSet())
return kForbidBreaks;
EBreakInside break_value = BreakInside();
@@ -5906,19 +5909,6 @@ LayoutUnit LayoutBox::OffsetTop(const Element* parent) const {
return OffsetPoint(parent).top;
}
-LayoutPoint LayoutBox::FlipForWritingModeForChild(
- const LayoutBox* child,
- const LayoutPoint& point) const {
- if (!StyleRef().IsFlippedBlocksWritingMode())
- return point;
-
- // The child is going to add in its x(), so we have to make sure it ends up in
- // the right place.
- return LayoutPoint(point.X() + Size().Width() - child->Size().Width() -
- (2 * child->Location().X()),
- point.Y());
-}
-
LayoutBox* LayoutBox::LocationContainer() const {
// Location of a non-root SVG object derived from LayoutBox should not be
// affected by writing-mode of the containing box (SVGRoot).
@@ -5932,21 +5922,6 @@ LayoutBox* LayoutBox::LocationContainer() const {
return ToLayoutBox(container);
}
-PhysicalOffset LayoutBox::PhysicalLocation(
- const LayoutBox* flipped_blocks_container) const {
- const LayoutBox* container_box;
- if (flipped_blocks_container) {
- DCHECK_EQ(flipped_blocks_container, LocationContainer());
- container_box = flipped_blocks_container;
- } else {
- container_box = LocationContainer();
- }
- if (!container_box)
- return PhysicalOffset(Location());
- return PhysicalOffset(
- container_box->FlipForWritingModeForChild(this, Location()));
-}
-
bool LayoutBox::HasRelativeLogicalWidth() const {
return StyleRef().LogicalWidth().IsPercentOrCalc() ||
StyleRef().LogicalMinWidth().IsPercentOrCalc() ||
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 7ca1d06f16d..51fc685bad3 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_box.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_box.h
@@ -699,8 +699,8 @@ class CORE_EXPORT LayoutBox : public LayoutBoxModelObject {
void ScrollByRecursively(const ScrollOffset& delta);
// If makeVisibleInVisualViewport is set, the visual viewport will be scrolled
// if required to make the rect visible.
- LayoutRect ScrollRectToVisibleRecursive(const LayoutRect&,
- const WebScrollIntoViewParams&);
+ PhysicalRect ScrollRectToVisibleRecursive(const PhysicalRect&,
+ const WebScrollIntoViewParams&);
LayoutRectOutsets MarginBoxOutsets() const { return margin_box_outsets_; }
LayoutUnit MarginTop() const override { return margin_box_outsets_.Top(); }
@@ -768,12 +768,12 @@ class CORE_EXPORT LayoutBox : public LayoutBoxModelObject {
}
bool HitTestAllPhases(HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
HitTestFilter = kHitTestAll) final;
bool NodeAtPoint(HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
HitTestAction) override;
LayoutUnit MinPreferredLogicalWidth() const override;
@@ -1134,7 +1134,7 @@ class CORE_EXPORT LayoutBox : public LayoutBoxModelObject {
bool CanBeScrolledAndHasScrollableArea() const;
virtual bool CanBeProgramaticallyScrolled() const;
- virtual void Autoscroll(const LayoutPoint&);
+ virtual void Autoscroll(const PhysicalOffset&);
bool CanAutoscroll() const;
PhysicalOffset CalculateAutoscrollDirection(
const FloatPoint& point_in_root_frame) const;
@@ -1232,7 +1232,7 @@ class CORE_EXPORT LayoutBox : public LayoutBoxModelObject {
void LogicalExtentAfterUpdatingLogicalWidth(const LayoutUnit& logical_top,
LogicalExtentComputedValues&);
- PositionWithAffinity PositionForPoint(const LayoutPoint&) const override;
+ PositionWithAffinity PositionForPoint(const PhysicalOffset&) const override;
void RemoveFloatingOrPositionedChildFromBlockLists();
@@ -1305,11 +1305,6 @@ class CORE_EXPORT LayoutBox : public LayoutBoxModelObject {
LayoutUnit OffsetLeft(const Element*) const final;
LayoutUnit OffsetTop(const Element*) const final;
- // TODO(wangxianzhu): This should be also type-safe. Will do when converting
- // hit testing geometry to use physical geometry types.
- LayoutPoint FlipForWritingModeForChild(const LayoutBox* child,
- const LayoutPoint&) const;
-
WARN_UNUSED_RESULT LayoutUnit
FlipForWritingMode(LayoutUnit position,
LayoutUnit width = LayoutUnit()) const {
@@ -1336,7 +1331,11 @@ class CORE_EXPORT LayoutBox : public LayoutBoxModelObject {
// Passing |flipped_blocks_container| causes flipped-block flipping w.r.t.
// that container, or LocationContainer() otherwise.
PhysicalOffset PhysicalLocation(
- const LayoutBox* flipped_blocks_container = nullptr) const;
+ const LayoutBox* flipped_blocks_container = nullptr) const {
+ return PhysicalLocationInternal(flipped_blocks_container
+ ? flipped_blocks_container
+ : LocationContainer());
+ }
// Convert a local rect in this box's blocks direction into parent's blocks
// direction, for parent to accumulate layout or visual overflow.
@@ -1374,7 +1373,7 @@ class CORE_EXPORT LayoutBox : public LayoutBoxModelObject {
// See README.md for an explanation of scroll origin.
IntSize OriginAdjustmentForScrollbars() const;
IntPoint ScrollOrigin() const;
- IntSize ScrolledContentOffset() const;
+ LayoutSize ScrolledContentOffset() const;
// Maps from scrolling contents space to box space and apply overflow
// clip if needed. Returns true if no clipping applied or the flattened quad
@@ -1465,8 +1464,9 @@ class CORE_EXPORT LayoutBox : public LayoutBoxModelObject {
void AddCustomLayoutChildIfNeeded();
void ClearCustomLayoutChild();
- bool HitTestClippedOutByBorder(const HitTestLocation& location_in_container,
- const LayoutPoint& border_box_location) const;
+ bool HitTestClippedOutByBorder(
+ const HitTestLocation&,
+ const PhysicalOffset& border_box_location) const;
// Returns true if the box intersects the viewport visible to the user.
bool IntersectsVisibleViewport() const;
@@ -1614,12 +1614,12 @@ class CORE_EXPORT LayoutBox : public LayoutBoxModelObject {
virtual bool HitTestOverflowControl(HitTestResult&,
const HitTestLocation&,
- const LayoutPoint&) {
+ const PhysicalOffset&) {
return false;
}
virtual bool HitTestChildren(HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
HitTestAction);
void InvalidatePaint(const PaintInvalidatorContext&) const override;
@@ -1782,6 +1782,17 @@ class CORE_EXPORT LayoutBox : public LayoutBoxModelObject {
return FlipForWritingMode(position, width);
}
+ PhysicalOffset PhysicalLocationInternal(
+ const LayoutBox* container_box) const {
+ DCHECK_EQ(container_box, LocationContainer());
+ if (LIKELY(!container_box || !container_box->HasFlippedBlocksWritingMode()))
+ return PhysicalOffset(Location());
+
+ return PhysicalOffset(
+ container_box->Size().Width() - Size().Width() - Location().X(),
+ Location().Y());
+ }
+
// The CSS border box rect for this box.
//
// The rectangle is in LocationContainer's physical coordinates in flipped
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 cbe6e6e3a0f..c21d90b50ad 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
@@ -1047,6 +1047,9 @@ FloatRect LayoutBoxModelObject::ComputeStickyConstrainingRect() const {
}
PhysicalOffset LayoutBoxModelObject::StickyPositionOffset() const {
+ // TODO(chrishtr): StickyPositionOffset depends on compositing at present,
+ // but there are callsites within Layout for it.
+
const PaintLayer* ancestor_overflow_layer = Layer()->AncestorOverflowLayer();
// TODO: Force compositing input update if we ask for offset before
// compositing inputs have been computed?
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 23e65eb64f8..c2488d7fb77 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
@@ -79,7 +79,7 @@ enum LineDirectionMode { kHorizontalLine, kVerticalLine };
//
// In order to fully understand LayoutBoxModelObject and the inherited classes,
// we need to introduce the concept of coordinate systems.
-// There is 3 main coordinate systems:
+// There are 4 coordinate systems:
// - physical coordinates: it is the coordinate system used for painting and
// correspond to physical direction as seen on the physical display (screen,
// printed page). In CSS, 'top', 'right', 'bottom', 'left' are all in physical
@@ -119,6 +119,10 @@ enum LineDirectionMode { kHorizontalLine, kVerticalLine };
// (e.g. InlineStart, BlockEnd) or physical (e.g. Top, Left), or the return
// type is PhysicalRect.
//
+// - logical coordinates without flipping inline direction: those are "logical
+// block coordinates", without considering text direction. Examples are
+// "LogicalLeft" and "LogicalRight".
+//
// For more, see Source/core/layout/README.md ### Coordinate Spaces.
class CORE_EXPORT LayoutBoxModelObject : public LayoutObject {
public:
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 9aa0490bb44..f9b52612858 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
@@ -1139,7 +1139,7 @@ TEST_F(LayoutBoxModelObjectTest, StickyRemovedFromRootScrollableArea) {
// Now make the scroller into an actual scroller. This will reparent the
// sticky element to be a child of the scroller, and will set its previous
// overflow layer to nullptr.
- ToElement(scroller->GetNode())
+ To<Element>(scroller->GetNode())
->SetInlineStyleProperty(CSSPropertyID::kOverflow, "scroll");
UpdateAllLifecyclePhasesForTest();
@@ -1149,9 +1149,9 @@ TEST_F(LayoutBoxModelObjectTest, StickyRemovedFromRootScrollableArea) {
// Making the scroller have visible overflow but still have a PaintLayer
// (in this case by making it position: relative) will cause us to need to
// recompute the sticky element's ancestor overflow layer.
- ToElement(scroller->GetNode())
+ To<Element>(scroller->GetNode())
->SetInlineStyleProperty(CSSPropertyID::kPosition, "relative");
- ToElement(scroller->GetNode())
+ To<Element>(scroller->GetNode())
->SetInlineStyleProperty(CSSPropertyID::kOverflow, "visible");
// Now try to scroll to the sticky element, this used to crash.
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_box_test.cc b/chromium/third_party/blink/renderer/core/layout/layout_box_test.cc
index ada8f7b130b..e298eb904a7 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_box_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_box_test.cc
@@ -1208,7 +1208,7 @@ TEST_P(LayoutBoxTest, GeometriesWithScrollbarsNonScrollable) {
#define EXPECT_ZERO_SCROLL(box) \
do { \
- EXPECT_EQ(IntSize(), box->ScrolledContentOffset()); \
+ EXPECT_EQ(LayoutSize(), box->ScrolledContentOffset()); \
const auto* scrollable_area = box->GetScrollableArea(); \
EXPECT_EQ(IntSize(), scrollable_area->ScrollOffsetInt()); \
EXPECT_EQ(IntPoint(), scrollable_area->ScrollOrigin()); \
@@ -1313,7 +1313,7 @@ TEST_P(LayoutBoxTest, GeometriesWithScrollbarsScrollable) {
const auto* normal = GetLayoutBoxByElementId("normal");
const auto* scrollable_area = normal->GetScrollableArea();
- EXPECT_EQ(IntSize(), normal->ScrolledContentOffset());
+ EXPECT_EQ(LayoutSize(), normal->ScrolledContentOffset());
EXPECT_EQ(IntSize(), normal->OriginAdjustmentForScrollbars());
EXPECT_EQ(IntSize(), scrollable_area->ScrollOffsetInt());
// 50 = border_left, 20 = border_top
@@ -1335,7 +1335,7 @@ TEST_P(LayoutBoxTest, GeometriesWithScrollbarsScrollable) {
const auto* vlr = GetLayoutBoxByElementId("vlr");
scrollable_area = vlr->GetScrollableArea();
- EXPECT_EQ(IntSize(), vlr->ScrolledContentOffset());
+ EXPECT_EQ(LayoutSize(), vlr->ScrolledContentOffset());
EXPECT_EQ(IntSize(), vlr->OriginAdjustmentForScrollbars());
EXPECT_EQ(IntSize(), scrollable_area->ScrollOffsetInt());
// 2060 = child_width + padding_left + padding_right
@@ -1356,7 +1356,7 @@ TEST_P(LayoutBoxTest, GeometriesWithScrollbarsScrollable) {
const auto* vrl = GetLayoutBoxByElementId("vrl");
scrollable_area = vrl->GetScrollableArea();
- EXPECT_EQ(IntSize(), vrl->ScrolledContentOffset());
+ EXPECT_EQ(LayoutSize(), vrl->ScrolledContentOffset());
EXPECT_EQ(IntSize(), vrl->OriginAdjustmentForScrollbars());
EXPECT_EQ(IntSize(), scrollable_area->ScrollOffsetInt());
// Same as "vlr" except for flipping.
@@ -1373,7 +1373,7 @@ TEST_P(LayoutBoxTest, GeometriesWithScrollbarsScrollable) {
const auto* rtl = GetLayoutBoxByElementId("rtl");
scrollable_area = rtl->GetScrollableArea();
- EXPECT_EQ(IntSize(), rtl->ScrolledContentOffset());
+ EXPECT_EQ(LayoutSize(), rtl->ScrolledContentOffset());
EXPECT_EQ(IntSize(15, 0), rtl->OriginAdjustmentForScrollbars());
EXPECT_EQ(IntSize(), scrollable_area->ScrollOffsetInt());
// The contents overflow to the left.
@@ -1393,7 +1393,7 @@ TEST_P(LayoutBoxTest, GeometriesWithScrollbarsScrollable) {
const auto* rtl_vlr = GetLayoutBoxByElementId("rtl-vlr");
scrollable_area = rtl_vlr->GetScrollableArea();
- EXPECT_EQ(IntSize(), rtl_vlr->ScrolledContentOffset());
+ EXPECT_EQ(LayoutSize(), rtl_vlr->ScrolledContentOffset());
EXPECT_EQ(IntSize(), rtl_vlr->OriginAdjustmentForScrollbars());
EXPECT_EQ(IntSize(), scrollable_area->ScrollOffsetInt());
// 2060 = child_width + padding_left + padding_right
@@ -1412,7 +1412,7 @@ TEST_P(LayoutBoxTest, GeometriesWithScrollbarsScrollable) {
const auto* rtl_vrl = GetLayoutBoxByElementId("rtl-vrl");
scrollable_area = rtl_vrl->GetScrollableArea();
- EXPECT_EQ(IntSize(), rtl_vrl->ScrolledContentOffset());
+ EXPECT_EQ(LayoutSize(), rtl_vrl->ScrolledContentOffset());
EXPECT_EQ(IntSize(), rtl_vrl->OriginAdjustmentForScrollbars());
EXPECT_EQ(IntSize(), scrollable_area->ScrollOffsetInt());
// Same as "vlr" except for flipping.
@@ -1434,7 +1434,7 @@ TEST_P(LayoutBoxTest, HasNonCollapsedBorderDecoration) {
auto* div = GetLayoutBoxByElementId("div");
EXPECT_FALSE(div->HasNonCollapsedBorderDecoration());
- ToElement(div->GetNode())
+ To<Element>(div->GetNode())
->setAttribute(html_names::kStyleAttr, "border: 1px solid black");
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
EXPECT_TRUE(div->HasNonCollapsedBorderDecoration());
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_br.cc b/chromium/third_party/blink/renderer/core/layout/layout_br.cc
index 094d44a8e54..c96e4cd4a6a 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_br.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_br.cc
@@ -56,7 +56,7 @@ int LayoutBR::CaretMaxOffset() const {
return 1;
}
-PositionWithAffinity LayoutBR::PositionForPoint(const LayoutPoint&) const {
+PositionWithAffinity LayoutBR::PositionForPoint(const PhysicalOffset&) const {
return CreatePositionWithAffinity(0);
}
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_br.h b/chromium/third_party/blink/renderer/core/layout/layout_br.h
index de9a9b9308a..1cf6f774e29 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_br.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_br.h
@@ -68,7 +68,7 @@ class LayoutBR final : public LayoutText {
int CaretMinOffset() const override;
int CaretMaxOffset() const override;
- PositionWithAffinity PositionForPoint(const LayoutPoint&) const final;
+ PositionWithAffinity PositionForPoint(const PhysicalOffset&) const final;
Position PositionForCaretOffset(unsigned) const final;
base::Optional<unsigned> CaretOffsetForPosition(const Position&) const final;
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 2e6cbcee913..69728d6bd2e 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_button.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_button.cc
@@ -90,7 +90,8 @@ LayoutUnit LayoutButton::BaselinePosition(
// We want to call the LayoutBlock version of firstLineBoxBaseline to
// avoid LayoutFlexibleBox synthesizing a baseline that we don't want.
// We use this check as a proxy for "are there any line boxes in this button"
- if (!HasLineIfEmpty() && LayoutBlock::FirstLineBoxBaseline() == -1) {
+ if (!HasLineIfEmpty() && !ShouldApplyLayoutContainment() &&
+ LayoutBlock::FirstLineBoxBaseline() == -1) {
// To ensure that we have a consistent baseline when we have no children,
// even when we have the anonymous LayoutBlock child, we calculate the
// baseline for the empty case manually here.
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 54e14d184bd..0d7cb557ef6 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_counter.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_counter.cc
@@ -122,7 +122,7 @@ static inline bool AreElementsSiblings(const Element& first,
static LayoutObject* NextInPreOrder(const LayoutObject& object,
const Element* stay_within,
bool skip_descendants = false) {
- Element* self = ToElement(object.GetNode());
+ auto* self = To<Element>(object.GetNode());
DCHECK(self);
Element* next =
skip_descendants
@@ -225,7 +225,7 @@ static bool FindPlaceForCounter(LayoutObject& counter_owner,
// We cannot stop searching for counters with the same identifier before we
// also check this layout object, because it may affect the positioning in the
// tree of our counter.
- Element* counter_owner_element = ToElement(counter_owner.GetNode());
+ auto* counter_owner_element = To<Element>(counter_owner.GetNode());
Element* search_end_element =
PreviousSiblingOrParentRespectingContainment(*counter_owner_element);
Element* current_element =
@@ -364,7 +364,7 @@ static bool FindPlaceForCounter(LayoutObject& counter_owner,
}
static inline Element* ParentElement(LayoutObject& object) {
- return ToElement(object.GetNode())->parentElement();
+ return To<Element>(object.GetNode())->parentElement();
}
static CounterNode* MakeCounterNodeIfNeeded(LayoutObject& object,
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_deprecated_flexible_box.cc b/chromium/third_party/blink/renderer/core/layout/layout_deprecated_flexible_box.cc
index 6c693651ebe..929ce2d1ea4 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_deprecated_flexible_box.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_deprecated_flexible_box.cc
@@ -25,7 +25,6 @@
#include "third_party/blink/renderer/core/layout/layout_deprecated_flexible_box.h"
#include <algorithm>
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/layout/api/line_layout_block_flow.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/layout/text_autosizer.h"
@@ -33,6 +32,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/platform/fonts/font.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/blink/renderer/platform/wtf/text/character_names.h"
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 857827e6aa3..190448dd329 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
@@ -64,7 +64,7 @@ bool LayoutDetailsMarker::IsOpen() const {
if (!layout_object->GetNode())
continue;
if (IsHTMLDetailsElement(*layout_object->GetNode()))
- return !ToElement(layout_object->GetNode())
+ return !To<Element>(layout_object->GetNode())
->getAttribute(kOpenAttr)
.IsNull();
if (IsHTMLInputElement(*layout_object->GetNode()))
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_embedded_content.cc b/chromium/third_party/blink/renderer/core/layout/layout_embedded_content.cc
index cd95d67d7b4..124ed8b5159 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_embedded_content.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_embedded_content.cc
@@ -141,33 +141,33 @@ bool LayoutEmbeddedContent::RequiresAcceleratedCompositing() const {
bool LayoutEmbeddedContent::NodeAtPointOverEmbeddedContentView(
HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
HitTestAction action) {
bool had_result = result.InnerNode();
- bool inside = LayoutReplaced::NodeAtPoint(result, location_in_container,
+ bool inside = LayoutReplaced::NodeAtPoint(result, hit_test_location,
accumulated_offset, action);
// Check to see if we are really over the EmbeddedContentView itself (and not
// just in the border/padding area).
- if ((inside || location_in_container.IsRectBasedTest()) && !had_result &&
+ if ((inside || hit_test_location.IsRectBasedTest()) && !had_result &&
result.InnerNode() == GetNode()) {
- result.SetIsOverEmbeddedContentView(PhysicalContentBoxRect().Contains(
- PhysicalOffsetToBeNoop(result.LocalPoint())));
+ result.SetIsOverEmbeddedContentView(
+ PhysicalContentBoxRect().Contains(result.LocalPoint()));
}
return inside;
}
bool LayoutEmbeddedContent::NodeAtPoint(
HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
HitTestAction action) {
auto* local_frame_view = DynamicTo<LocalFrameView>(ChildFrameView());
bool skip_contents = (result.GetHitTestRequest().GetStopNode() == this ||
!result.GetHitTestRequest().AllowsChildFrameContent());
if (!local_frame_view || skip_contents) {
- return NodeAtPointOverEmbeddedContentView(result, location_in_container,
+ return NodeAtPointOverEmbeddedContentView(result, hit_test_location,
accumulated_offset, action);
}
@@ -180,7 +180,7 @@ bool LayoutEmbeddedContent::NodeAtPoint(
!local_frame_view->GetFrame().GetDocument() ||
local_frame_view->GetFrame().GetDocument()->Lifecycle().GetState() <
DocumentLifecycle::kCompositingClean) {
- return NodeAtPointOverEmbeddedContentView(result, location_in_container,
+ return NodeAtPointOverEmbeddedContentView(result, hit_test_location,
accumulated_offset, action);
}
@@ -192,17 +192,17 @@ bool LayoutEmbeddedContent::NodeAtPoint(
if (VisibleToHitTestRequest(result.GetHitTestRequest()) &&
child_layout_view) {
- LayoutPoint adjusted_location = accumulated_offset + Location();
- LayoutPoint content_offset =
- LayoutPoint(BorderLeft() + PaddingLeft(), BorderTop() + PaddingTop());
+ PhysicalOffset content_offset(BorderLeft() + PaddingLeft(),
+ BorderTop() + PaddingTop());
HitTestLocation new_hit_test_location(
- location_in_container, -adjusted_location - content_offset);
+ hit_test_location, -accumulated_offset - content_offset);
HitTestRequest new_hit_test_request(
result.GetHitTestRequest().GetType() |
HitTestRequest::kChildFrameHitTest,
result.GetHitTestRequest().GetStopNode());
HitTestResult child_frame_result(new_hit_test_request,
new_hit_test_location);
+ child_frame_result.SetInertNode(result.InertNode());
// The frame's layout and style must be up to date if we reach here.
bool is_inside_child_frame = child_layout_view->HitTestNoLifecycleUpdate(
@@ -225,12 +225,12 @@ bool LayoutEmbeddedContent::NodeAtPoint(
// iframe element itself if the hit-test rect is totally within the
// iframe.
if (is_inside_child_frame) {
- if (!location_in_container.IsRectBasedTest())
+ if (!hit_test_location.IsRectBasedTest())
return true;
HitTestResult point_over_embedded_content_view_result = result;
bool point_over_embedded_content_view =
NodeAtPointOverEmbeddedContentView(
- point_over_embedded_content_view_result, location_in_container,
+ point_over_embedded_content_view_result, hit_test_location,
accumulated_offset, action);
if (point_over_embedded_content_view)
return true;
@@ -240,7 +240,7 @@ bool LayoutEmbeddedContent::NodeAtPoint(
}
}
- return NodeAtPointOverEmbeddedContentView(result, location_in_container,
+ return NodeAtPointOverEmbeddedContentView(result, hit_test_location,
accumulated_offset, action);
}
@@ -280,6 +280,8 @@ void LayoutEmbeddedContent::UpdateLayout() {
void LayoutEmbeddedContent::PaintReplaced(
const PaintInfo& paint_info,
const PhysicalOffset& paint_offset) const {
+ if (PaintBlockedByDisplayLock(DisplayLockContext::kChildren))
+ return;
EmbeddedContentPainter(*this).PaintReplaced(paint_info, paint_offset);
}
@@ -290,7 +292,7 @@ void LayoutEmbeddedContent::InvalidatePaint(
plugin->InvalidatePaint();
}
-CursorDirective LayoutEmbeddedContent::GetCursor(const LayoutPoint& point,
+CursorDirective LayoutEmbeddedContent::GetCursor(const PhysicalOffset& point,
Cursor& cursor) const {
if (Plugin()) {
// A plugin is responsible for setting the cursor when the pointer is over
@@ -382,8 +384,11 @@ void LayoutEmbeddedContent::UpdateGeometry(
// TODO(szager): Refactor this functionality into EmbeddedContentView, rather
// than reimplementing in each concrete subclass.
LayoutView* layout_view = View();
- if (layout_view && layout_view->HasOverflowClip())
- frame_rect.Move(layout_view->ScrolledContentOffset());
+ if (layout_view && layout_view->HasOverflowClip()) {
+ // Floored because the frame_rect in a content view is an IntRect. We may
+ // want to reevaluate that since scroll offsets/layout can be fractional.
+ frame_rect.Move(FlooredIntSize(layout_view->ScrolledContentOffset()));
+ }
embedded_content_view.SetFrameRect(frame_rect);
}
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_embedded_content.h b/chromium/third_party/blink/renderer/core/layout/layout_embedded_content.h
index 35801d7c45d..1869147c1dc 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_embedded_content.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_embedded_content.h
@@ -42,8 +42,8 @@ class CORE_EXPORT LayoutEmbeddedContent : public LayoutReplaced {
bool RequiresAcceleratedCompositing() const;
bool NodeAtPoint(HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
HitTestAction) override;
void AddRef() { ++ref_count_; }
@@ -74,7 +74,7 @@ class CORE_EXPORT LayoutEmbeddedContent : public LayoutReplaced {
void PaintReplaced(const PaintInfo&,
const PhysicalOffset& paint_offset) const override;
void InvalidatePaint(const PaintInvalidatorContext&) const final;
- CursorDirective GetCursor(const LayoutPoint&, Cursor&) const final;
+ CursorDirective GetCursor(const PhysicalOffset&, Cursor&) const final;
bool CanBeSelectionLeafInternal() const final { return true; }
@@ -86,8 +86,8 @@ class CORE_EXPORT LayoutEmbeddedContent : public LayoutReplaced {
bool NodeAtPointOverEmbeddedContentView(
HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
HitTestAction);
int ref_count_;
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 d44c66f8061..cc9106b3d10 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
@@ -49,7 +49,7 @@ static String LocalizedUnavailablePluginReplacementText(
Node* node,
LayoutEmbeddedObject::PluginAvailability availability) {
Locale& locale =
- node ? ToElement(node)->GetLocale() : Locale::DefaultLocale();
+ node ? To<Element>(node)->GetLocale() : Locale::DefaultLocale();
switch (availability) {
case LayoutEmbeddedObject::kPluginAvailable:
break;
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 f2786b5883f..3c4467b2c27 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
@@ -153,7 +153,7 @@ void LayoutFileUploadControl::ComputePreferredLogicalWidths() {
}
PositionWithAffinity LayoutFileUploadControl::PositionForPoint(
- const LayoutPoint&) const {
+ const PhysicalOffset&) const {
return PositionWithAffinity();
}
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_file_upload_control.h b/chromium/third_party/blink/renderer/core/layout/layout_file_upload_control.h
index 5232c77a918..bdd8d843941 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_file_upload_control.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_file_upload_control.h
@@ -70,7 +70,7 @@ class CORE_EXPORT LayoutFileUploadControl final : public LayoutBlockFlow {
int MaxFilenameWidth() const;
- PositionWithAffinity PositionForPoint(const LayoutPoint&) const override;
+ PositionWithAffinity PositionForPoint(const PhysicalOffset&) const override;
bool can_receive_dropped_files_;
};
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 35e0438a362..4fcefb3de1d 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
@@ -32,7 +32,6 @@
#include <limits>
#include "base/auto_reset.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/layout/flexible_box_algorithm.h"
#include "third_party/blink/renderer/core/layout/layout_state.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
@@ -45,6 +44,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/platform/geometry/length_functions.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
namespace blink {
@@ -283,30 +283,28 @@ void LayoutFlexibleBox::RemoveChild(LayoutObject* child) {
bool LayoutFlexibleBox::HitTestChildren(
HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
HitTestAction hit_test_action) {
if (hit_test_action != kHitTestForeground)
return false;
- LayoutPoint scrolled_offset(HasOverflowClip()
- ? accumulated_offset - ScrolledContentOffset()
- : accumulated_offset);
+ PhysicalOffset scrolled_offset = accumulated_offset;
+ if (HasOverflowClip())
+ scrolled_offset -= PhysicalOffset(ScrolledContentOffset());
for (LayoutBox* child = LastChildBox(); child;
child = child->PreviousSiblingBox()) {
if (child->HasSelfPaintingLayer())
continue;
- LayoutPoint child_point =
- FlipForWritingModeForChild(child, scrolled_offset);
-
- bool child_hit =
- child->HitTestAllPhases(result, location_in_container, child_point);
+ PhysicalOffset child_accumulated_offset =
+ scrolled_offset + child->PhysicalLocation(this);
+ bool child_hit = child->HitTestAllPhases(result, hit_test_location,
+ child_accumulated_offset);
if (child_hit) {
- UpdateHitTestResult(
- result, DeprecatedFlipForWritingMode(ToLayoutPoint(
- location_in_container.Point() - accumulated_offset)));
+ UpdateHitTestResult(result,
+ hit_test_location.Point() - accumulated_offset);
return true;
}
}
@@ -501,6 +499,12 @@ LayoutUnit LayoutFlexibleBox::ChildUnstretchedLogicalHeight(
// This should only be called if the logical height is the cross size
DCHECK(MainAxisIsInlineAxis(child));
if (NeedToStretchChildLogicalHeight(child)) {
+ LayoutUnit old_override_height = LayoutUnit(-1);
+ if (child.HasOverrideLogicalHeight()) {
+ old_override_height = child.OverrideLogicalHeight();
+ const_cast<LayoutBox&>(child).ClearOverrideLogicalHeight();
+ }
+
LayoutUnit child_intrinsic_content_logical_height;
if (!child.ShouldApplySizeContainment()) {
if (child.DisplayLockInducesSizeContainment()) {
@@ -518,6 +522,10 @@ LayoutUnit LayoutFlexibleBox::ChildUnstretchedLogicalHeight(
LogicalExtentComputedValues values;
child.ComputeLogicalHeight(child_intrinsic_logical_height, LayoutUnit(),
values);
+ if (old_override_height != LayoutUnit(-1)) {
+ const_cast<LayoutBox&>(child).SetOverrideLogicalHeight(
+ old_override_height);
+ }
return values.extent_;
}
return child.LogicalHeight();
@@ -528,14 +536,23 @@ LayoutUnit LayoutFlexibleBox::ChildUnstretchedLogicalWidth(
const LayoutBox& child) const {
// This should only be called if the logical width is the cross size
DCHECK(!MainAxisIsInlineAxis(child));
- DCHECK(!child.HasOverrideLogicalWidth());
+
// We compute the width as if we were unstretched. Only the main axis
// override size is set at this point.
// However, if our cross axis length is definite we don't need to recompute
// and can just return the already-set logical width.
if (!CrossAxisLengthIsDefinite(child, child.StyleRef().LogicalWidth())) {
+ LayoutUnit old_override_width = LayoutUnit(-1);
+ if (child.HasOverrideLogicalWidth()) {
+ old_override_width = child.OverrideLogicalWidth();
+ const_cast<LayoutBox&>(child).ClearOverrideLogicalWidth();
+ }
+
LogicalExtentComputedValues values;
child.ComputeLogicalWidth(values);
+
+ if (old_override_width != LayoutUnit(-1))
+ const_cast<LayoutBox&>(child).SetOverrideLogicalWidth(old_override_width);
return values.extent_;
}
@@ -1206,8 +1223,6 @@ void LayoutFlexibleBox::ConstructAndAppendFlexItem(
FlexLayoutAlgorithm* algorithm,
LayoutBox& child,
ChildLayoutType layout_type) {
- if (layout_type != kNeverLayout)
- child.ClearOverrideSize();
if (layout_type != kNeverLayout &&
ChildHasIntrinsicMainAxisSize(*algorithm, child)) {
// If this condition is true, then ComputeMainAxisExtentForChild will call
@@ -1222,6 +1237,7 @@ void LayoutFlexibleBox::ConstructAndAppendFlexItem(
UpdateBlockChildDirtyBitsBeforeLayout(layout_type == kForceLayout, child);
if (child.NeedsLayout() || layout_type == kForceLayout ||
!intrinsic_size_along_main_axis_.Contains(&child)) {
+ child.ClearOverrideSize();
child.ForceLayout();
CacheChildMainSize(child);
}
@@ -1488,8 +1504,19 @@ void LayoutFlexibleBox::LayoutLineItems(FlexLine* current_line,
UpdateBlockChildDirtyBitsBeforeLayout(force_child_relayout, *child);
if (!child->NeedsLayout())
MarkChildForPaginationRelayoutIfNeeded(*child, layout_scope);
- if (child->NeedsLayout())
+ if (child->NeedsLayout()) {
relaid_out_children_.insert(child);
+ // It is very important that we only clear the cross axis override size
+ // if we are in fact going to lay out the child. Otherwise, the cross
+ // axis size and the actual laid out size get out of sync, which will
+ // cause problems if we later lay out the child in simplified layout,
+ // which does not go through regular flex layout and therefore would
+ // not reset the cross axis size.
+ if (MainAxisIsInlineAxis(*child))
+ child->ClearOverrideLogicalHeight();
+ else
+ child->ClearOverrideLogicalWidth();
+ }
child->LayoutIfNeeded();
// This shouldn't be necessary, because we set the override size to be
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 636261ad4ac..f03f4986fb6 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
@@ -104,8 +104,8 @@ class CORE_EXPORT LayoutFlexibleBox : public LayoutBlock {
LayoutUnit& max_logical_width) const override;
bool HitTestChildren(HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
HitTestAction) override;
void StyleDidChange(StyleDifference, const ComputedStyle* old_style) override;
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_flexible_box_test.cc b/chromium/third_party/blink/renderer/core/layout/layout_flexible_box_test.cc
index b71ecd390fa..781b9c7e0fb 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_flexible_box_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_flexible_box_test.cc
@@ -4,6 +4,7 @@
#include "third_party/blink/renderer/core/layout/layout_flexible_box.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"
@@ -79,8 +80,8 @@ static void CheckFlexBoxPhysicalGeometries(const LayoutBox* flex_box) {
flex_box->PhysicalContentBoxRect());
}
- EXPECT_EQ(IntSize(), flex_box->ScrolledContentOffset());
- EXPECT_EQ(IntSize(), flex_box->GetScrollableArea()->ScrollOffsetInt());
+ EXPECT_EQ(LayoutSize(), flex_box->ScrolledContentOffset());
+ EXPECT_EQ(ScrollOffset(), flex_box->GetScrollableArea()->GetScrollOffset());
}
void LayoutFlexibleBoxTest::ExpectSameAsRowHTB() {
@@ -462,4 +463,49 @@ TEST_P(LayoutFlexibleBoxTest, GeometriesWithScrollbarsRTLRowReverseVRL) {
ExpectSameAsRowVRL();
}
+TEST_P(LayoutFlexibleBoxTest, ResizedFlexChildRequiresVisualOverflowRecalc) {
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ #parent {
+ display: flex;
+ flex-direction: column;
+ width: 100px;
+ height: 1000px;
+ }
+ #child1 {
+ flex-grow: 1;
+ width: 100px;
+ will-change: transform;
+ }
+ #overflow-child {
+ width: 100px;
+ height: 950px;
+ box-shadow: 5px 10px;
+ }
+ #child2 {
+ width: 100px;
+ }
+ </style>
+ <div id="parent">
+ <div id="child1">
+ <div id="overflow-child"></div>
+ </div>
+ <div id="child2"></div>
+ </div>
+ )HTML");
+ auto* child1_element = GetElementById("child1");
+ auto* child2_element = GetElementById("child2");
+ child2_element->setAttribute(html_names::kStyleAttr, "height: 100px;");
+ GetDocument().View()->UpdateLifecycleToLayoutClean();
+
+ auto* child1_box = ToLayoutBox(child1_element->GetLayoutObject());
+ ASSERT_TRUE(child1_box->HasSelfPaintingLayer());
+ EXPECT_TRUE(child1_box->Layer()->NeedsVisualOverflowRecalcForTesting());
+
+ UpdateAllLifecyclePhasesForTest();
+
+ EXPECT_EQ(child1_box->PhysicalVisualOverflowRect(),
+ PhysicalRect(0, 0, 105, 960));
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_flow_thread.cc b/chromium/third_party/blink/renderer/core/layout/layout_flow_thread.cc
index 4e9869c8ee8..118511adc7a 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_flow_thread.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_flow_thread.cc
@@ -179,12 +179,12 @@ void LayoutFlowThread::AddOutlineRects(
}
bool LayoutFlowThread::NodeAtPoint(HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
HitTestAction hit_test_action) {
if (hit_test_action == kHitTestBlockBackground)
return false;
- return LayoutBlockFlow::NodeAtPoint(result, location_in_container,
+ return LayoutBlockFlow::NodeAtPoint(result, hit_test_location,
accumulated_offset, hit_test_action);
}
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_flow_thread.h b/chromium/third_party/blink/renderer/core/layout/layout_flow_thread.h
index 2cc0d545761..51130666c56 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_flow_thread.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_flow_thread.h
@@ -32,7 +32,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/layout/layout_block_flow.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/linked_hash_set.h"
namespace blink {
@@ -125,8 +125,8 @@ class CORE_EXPORT LayoutFlowThread : public LayoutBlockFlow {
NGOutlineType) const override;
bool NodeAtPoint(HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
HitTestAction) final;
virtual void AddColumnSetToThread(LayoutMultiColumnSet*) = 0;
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 42e29613915..af24df10914 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
@@ -581,7 +581,7 @@ bool LayoutFrameSet::IsChildAllowed(LayoutObject* child,
return child->IsFrame() || child->IsFrameSet();
}
-CursorDirective LayoutFrameSet::GetCursor(const LayoutPoint& point,
+CursorDirective LayoutFrameSet::GetCursor(const PhysicalOffset& point,
Cursor& cursor) const {
IntPoint rounded_point = RoundedIntPoint(point);
if (CanResizeRow(rounded_point)) {
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_frame_set.h b/chromium/third_party/blink/renderer/core/layout/layout_frame_set.h
index 6e4df71d46c..95cb2c48018 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_frame_set.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_frame_set.h
@@ -134,7 +134,7 @@ class LayoutFrameSet final : public LayoutBox {
void Paint(const PaintInfo&) const override;
void ComputePreferredLogicalWidths() override;
bool IsChildAllowed(LayoutObject*, const ComputedStyle&) const override;
- CursorDirective GetCursor(const LayoutPoint&, Cursor&) const override;
+ CursorDirective GetCursor(const PhysicalOffset&, Cursor&) const override;
void SetIsResizing(bool);
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 396e040e57c..8a933f61e59 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
@@ -139,7 +139,7 @@ void LayoutGeometryMap::DumpSteps() const {
accumulated_offset_.left.ToInt(), accumulated_offset_.top.ToInt());
for (int i = mapping_.size() - 1; i >= 0; --i) {
fprintf(stderr, " [%d] %s: offset=%d,%d", i,
- mapping_[i].layout_object_->DebugName().Ascii().data(),
+ mapping_[i].layout_object_->DebugName().Ascii().c_str(),
mapping_[i].offset_.left.ToInt(), mapping_[i].offset_.top.ToInt());
if (mapping_[i].flags_ & kContainsFixedPosition)
fprintf(stderr, " containsFixedPosition");
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 bddf09f1d0c..0c6ac1fb026 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
@@ -32,7 +32,7 @@
#include "third_party/blink/renderer/core/layout/layout_geometry_map_step.h"
#include "third_party/blink/renderer/core/layout/map_coordinates_flags.h"
#include "third_party/blink/renderer/platform/geometry/float_quad.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_geometry_map_step.h b/chromium/third_party/blink/renderer/core/layout/layout_geometry_map_step.h
index 4d453891623..d9d8d10954b 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_geometry_map_step.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_geometry_map_step.h
@@ -30,7 +30,7 @@
#include <memory>
#include "third_party/blink/renderer/platform/geometry/layout_size.h"
#include "third_party/blink/renderer/platform/transforms/transformation_matrix.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 f8ba8a6fcb5..a3edf797642 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_grid.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_grid.cc
@@ -30,7 +30,6 @@
#include <utility>
#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/layout/grid_layout_utils.h"
#include "third_party/blink/renderer/core/layout/layout_state.h"
#include "third_party/blink/renderer/core/layout/text_autosizer.h"
@@ -40,6 +39,7 @@
#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/geometry/length_functions.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.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->SetSelfNeedsLayoutForAvailableSpace(true);
+ child->SetNeedsLayout(layout_invalidation_reason::kGridChanged);
}
}
}
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 ff5f4cfc17e..ac1eed15d2d 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_image.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_image.cc
@@ -32,7 +32,6 @@
#include "third_party/blink/renderer/core/dom/pseudo_element.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/use_counter.h"
#include "third_party/blink/renderer/core/html/html_area_element.h"
#include "third_party/blink/renderer/core/html/html_image_element.h"
#include "third_party/blink/renderer/core/html/media/media_element_parser_helpers.h"
@@ -45,6 +44,7 @@
#include "third_party/blink/renderer/core/paint/image_painter.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/svg/graphics/svg_image.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
namespace blink {
@@ -68,10 +68,6 @@ LayoutImage::~LayoutImage() = default;
void LayoutImage::WillBeDestroyed() {
DCHECK(image_resource_);
image_resource_->Shutdown();
- if (RuntimeEnabledFeatures::ElementTimingEnabled(&GetDocument())) {
- if (LocalDOMWindow* window = GetDocument().domWindow())
- ImageElementTiming::From(*window).NotifyWillBeDestroyed(this);
- }
LayoutReplaced::WillBeDestroyed();
}
@@ -220,6 +216,8 @@ void LayoutImage::ImageNotifyFinished(ImageResourceContent* new_image) {
void LayoutImage::PaintReplaced(const PaintInfo& paint_info,
const PhysicalOffset& paint_offset) const {
+ if (PaintBlockedByDisplayLock(DisplayLockContext::kChildren))
+ return;
ImagePainter(*this).PaintReplaced(paint_info, paint_offset);
}
@@ -293,12 +291,12 @@ HTMLMapElement* LayoutImage::ImageMap() const {
}
bool LayoutImage::NodeAtPoint(HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
HitTestAction hit_test_action) {
HitTestResult temp_result(result);
bool inside = LayoutReplaced::NodeAtPoint(
- temp_result, location_in_container, accumulated_offset, hit_test_action);
+ temp_result, hit_test_location, accumulated_offset, hit_test_action);
if (!inside && result.GetHitTestRequest().ListBased())
result.Append(temp_result);
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 39bc5ed0eee..f93426510ae 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_image.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_image.h
@@ -125,8 +125,8 @@ class CORE_EXPORT LayoutImage : public LayoutReplaced {
void ImageNotifyFinished(ImageResourceContent*) final;
bool NodeAtPoint(HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
HitTestAction) final;
void InvalidatePaintAndMarkForLayoutIfNeeded(CanDeferInvalidation);
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 dc3b5638582..4ab57c5e361 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
@@ -169,10 +169,9 @@ scoped_refptr<Image> LayoutImageResource::GetImage(
return image;
KURL url;
- Node* node = layout_object_->GetNode();
- if (node && node->IsElementNode()) {
- const AtomicString& url_string = ToElement(node)->ImageSourceURL();
- url = node->GetDocument().CompleteURL(url_string);
+ if (auto* element = DynamicTo<Element>(layout_object_->GetNode())) {
+ const AtomicString& url_string = element->ImageSourceURL();
+ url = element->GetDocument().CompleteURL(url_string);
}
return SVGImageForContainer::Create(
ToSVGImage(image), container_size,
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_image_test.cc b/chromium/third_party/blink/renderer/core/layout/layout_image_test.cc
index 3258c1e8e75..ec88f7442fa 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_image_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_image_test.cc
@@ -18,13 +18,13 @@ TEST_F(LayoutImageTest, HitTestUnderTransform) {
)HTML");
const auto& target = *GetDocument().getElementById("target");
- HitTestLocation location(LayoutPoint(60, 10));
+ HitTestLocation location(PhysicalOffset(60, 10));
HitTestResult result(
HitTestRequest(HitTestRequest::kReadOnly | HitTestRequest::kActive |
HitTestRequest::kAllowChildFrameContent),
location);
GetLayoutView().HitTest(location, result);
- EXPECT_EQ(LayoutPoint(60, 10), result.PointInInnerNodeFrame());
+ EXPECT_EQ(PhysicalOffset(60, 10), result.PointInInnerNodeFrame());
EXPECT_EQ(target, result.InnerNode());
}
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 476537efff8..fa456091d39 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_inline.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_inline.cc
@@ -91,9 +91,7 @@ LayoutInline::LayoutInline(Element* element)
LayoutInline::~LayoutInline() {
#if DCHECK_IS_ON()
- if (IsInLayoutNGInlineFormattingContext())
- DCHECK(!first_paint_fragment_);
- else
+ if (!IsInLayoutNGInlineFormattingContext())
line_boxes_.AssertIsEmpty();
#endif
}
@@ -132,8 +130,11 @@ void LayoutInline::WillBeDestroyed() {
for (InlineFlowBox* box : *LineBoxes())
box->Remove();
}
- } else if (Parent()) {
- Parent()->DirtyLinesFromChangedChild(this);
+ } else {
+ if (NGPaintFragment* first_inline_fragment = FirstInlineFragment())
+ first_inline_fragment->LayoutObjectWillBeDestroyed();
+ if (Parent())
+ Parent()->DirtyLinesFromChangedChild(this);
}
}
@@ -143,9 +144,7 @@ void LayoutInline::WillBeDestroyed() {
}
void LayoutInline::DeleteLineBoxes() {
- if (IsInLayoutNGInlineFormattingContext())
- SetFirstInlineFragment(nullptr);
- else
+ if (!IsInLayoutNGInlineFormattingContext())
MutableLineBoxes()->DeleteLineBoxes();
}
@@ -276,7 +275,7 @@ void LayoutInline::StyleDidChange(StyleDifference diff,
LayoutBoxModelObject* next_cont = curr_cont->Continuation();
curr_cont->SetContinuation(nullptr);
- curr_cont->SetStyle(MutableStyle());
+ curr_cont->SetStyle(Style());
curr_cont->SetContinuation(next_cont);
end_of_continuation = curr_cont;
}
@@ -554,7 +553,7 @@ void LayoutInline::AddChildIgnoringContinuation(LayoutObject* new_child,
LayoutInline* LayoutInline::Clone() const {
DCHECK(!IsAnonymous());
LayoutInline* clone_inline = new LayoutInline(GetNode());
- clone_inline->SetStyle(MutableStyle());
+ clone_inline->SetStyle(Style());
clone_inline->SetIsInsideFlowThread(IsInsideFlowThread());
return clone_inline;
}
@@ -1019,8 +1018,8 @@ LayoutUnit LayoutInline::MarginBottom() const {
}
bool LayoutInline::NodeAtPoint(HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
HitTestAction hit_test_action) {
if (ContainingNGBlockFlow()) {
// TODO(crbug.com/965976): We should fix the root cause of the missed
@@ -1035,38 +1034,35 @@ bool LayoutInline::NodeAtPoint(HitTestResult& result,
NGPaintFragment::InlineFragmentsFor(this)) {
// NGBoxFragmentPainter::NodeAtPoint() takes an offset that is accumulated
// up to the fragment itself. Compute this offset.
- LayoutPoint adjusted_location =
- accumulated_offset +
- fragment->InlineOffsetToContainerBox().ToLayoutPoint();
+ PhysicalOffset adjusted_location =
+ accumulated_offset + fragment->InlineOffsetToContainerBox();
if (NGBoxFragmentPainter(*fragment).NodeAtPoint(
- result, location_in_container, adjusted_location,
- hit_test_action))
+ result, hit_test_location, adjusted_location, hit_test_action))
return true;
}
return false;
}
return LineBoxes()->HitTest(LineLayoutBoxModel(this), result,
- location_in_container, accumulated_offset,
+ hit_test_location, accumulated_offset,
hit_test_action);
}
bool LayoutInline::HitTestCulledInline(
HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
const NGPaintFragment* container_fragment) {
DCHECK(container_fragment || !AlwaysCreateLineBoxes());
if (!VisibleToHitTestRequest(result.GetHitTestRequest()))
return false;
- HitTestLocation adjusted_location(location_in_container,
- -ToLayoutSize(accumulated_offset));
+ HitTestLocation adjusted_location(hit_test_location, -accumulated_offset);
Region region_result;
bool intersected = false;
auto yield = [&adjusted_location, &region_result,
&intersected](const PhysicalRect& rect) {
- if (adjusted_location.Intersects(rect.ToLayoutRect())) {
+ if (adjusted_location.Intersects(rect)) {
intersected = true;
region_result.Unite(EnclosingIntRect(rect));
}
@@ -1106,7 +1102,7 @@ bool LayoutInline::HitTestCulledInline(
}
PositionWithAffinity LayoutInline::PositionForPoint(
- const LayoutPoint& point) const {
+ const PhysicalOffset& point) const {
// FIXME: Does not deal with relative positioned inlines (should it?)
// If there are continuations, test them first because our containing block
@@ -1292,14 +1288,11 @@ PhysicalRect LayoutInline::LinesVisualOverflowBoundingBox() const {
if (IsInLayoutNGInlineFormattingContext()) {
PhysicalRect result;
NGPaintFragment::InlineFragmentsIncludingCulledFor(
- *this,
- [](NGPaintFragment* fragment, void* context) {
- PhysicalRect* result = static_cast<PhysicalRect*>(context);
+ *this, [&result](const NGPaintFragment* fragment) {
PhysicalRect child_rect = fragment->InkOverflow();
child_rect.offset += fragment->InlineOffsetToContainerBox();
- result->Unite(child_rect);
- },
- &result);
+ result.Unite(child_rect);
+ });
return result;
}
@@ -1432,7 +1425,8 @@ bool LayoutInline::MapToVisualRectInAncestorSpaceInternal(
// get the right dirty rect. Since this is called from LayoutObject::
// setStyle, the relative position flag on the LayoutObject has been
// cleared, so use the one on the style().
- transform_state.Move(Layer()->OffsetForInFlowPosition(), accumulation);
+ transform_state.Move(Layer()->GetLayoutObject().OffsetForInFlowPosition(),
+ accumulation);
}
LayoutBox* container_box =
@@ -1481,12 +1475,12 @@ void LayoutInline::ChildBecameNonInline(LayoutObject* child) {
}
void LayoutInline::UpdateHitTestResult(HitTestResult& result,
- const LayoutPoint& point) const {
+ const PhysicalOffset& point) const {
if (result.InnerNode())
return;
Node* n = GetNode();
- LayoutPoint local_point(point);
+ PhysicalOffset local_point = point;
if (n) {
if (IsInlineElementContinuation()) {
// We're in the continuation of a split inline. Adjust our local point to
@@ -1496,7 +1490,8 @@ void LayoutInline::UpdateHitTestResult(HitTestResult& result,
// Get our containing block.
LayoutBox* block = ContainingBlock();
- local_point.MoveBy(block->Location() - first_block->LocationOffset());
+ local_point += block->PhysicalLocation();
+ local_point -= first_block->PhysicalLocation();
}
result.SetNodeAndPosition(n, local_point);
@@ -1647,6 +1642,8 @@ void LayoutInline::AddOutlineRects(
Vector<PhysicalRect>& rects,
const PhysicalOffset& additional_offset,
NGOutlineType include_block_overflows) const {
+ DCHECK_GE(GetDocument().Lifecycle().GetState(),
+ DocumentLifecycle::kAfterPerformLayout);
CollectLineBoxRects([&rects, &additional_offset](const PhysicalRect& r) {
auto rect = r;
rect.Move(additional_offset);
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 bae52a73f79..de6e98d9b5d 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_inline.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_inline.h
@@ -136,7 +136,7 @@ class CORE_EXPORT LayoutInline : public LayoutBoxModelObject {
LayoutObject* before_child = nullptr) override;
Element* GetNode() const {
- return ToElement(LayoutBoxModelObject::GetNode());
+ return To<Element>(LayoutBoxModelObject::GetNode());
}
LayoutUnit MarginLeft() const final;
@@ -233,8 +233,8 @@ class CORE_EXPORT LayoutInline : public LayoutBoxModelObject {
// rects to be from descendant fragments of |parent_fragment|.
// In legacy, |parent_fragment| is always null, and all rects are regenerated.
bool HitTestCulledInline(HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
const NGPaintFragment* parent_fragment = nullptr);
PhysicalOffset FirstLineBoxTopLeft() const {
@@ -332,8 +332,8 @@ class CORE_EXPORT LayoutInline : public LayoutBoxModelObject {
void Paint(const PaintInfo&) const final;
bool NodeAtPoint(HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
HitTestAction) final;
PaintLayerType LayerTypeRequired() const override;
@@ -358,7 +358,7 @@ class CORE_EXPORT LayoutInline : public LayoutBoxModelObject {
TransformState&,
VisualRectFlags = kDefaultVisualRectFlags) const final;
- PositionWithAffinity PositionForPoint(const LayoutPoint&) const override;
+ PositionWithAffinity PositionForPoint(const PhysicalOffset&) const override;
IntRect BorderBoundingBox() const final {
IntRect bounding_box = EnclosingIntRect(PhysicalLinesBoundingBox());
@@ -383,7 +383,7 @@ class CORE_EXPORT LayoutInline : public LayoutBoxModelObject {
void ChildBecameNonInline(LayoutObject* child) final;
- void UpdateHitTestResult(HitTestResult&, const LayoutPoint&) const final;
+ void UpdateHitTestResult(HitTestResult&, const PhysicalOffset&) const final;
void ImageChanged(WrappedImagePtr, CanDeferInvalidation) final;
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 5aa29860e12..7570ca21718 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
@@ -110,10 +110,10 @@ TEST_F(LayoutInlineTest, RegionHitTest) {
HitTestRequest hit_request(HitTestRequest::kTouchEvent |
HitTestRequest::kListBased);
- LayoutRect hit_rect(1, 3, 2, 4);
+ PhysicalRect hit_rect(1, 3, 2, 4);
HitTestLocation location(hit_rect);
HitTestResult hit_result(hit_request, location);
- LayoutPoint hit_offset;
+ PhysicalOffset hit_offset;
// The return value of HitTestCulledInline() indicates whether the hit test
// rect is completely contained by the part of |lots_of_boxes| being hit-
@@ -158,8 +158,8 @@ TEST_P(ParameterizedLayoutInlineTest, RelativePositionedHitTest) {
HitTestRequest hit_request(HitTestRequest::kReadOnly |
HitTestRequest::kActive);
- const LayoutPoint container_offset(8, 8);
- const LayoutPoint hit_location(18, 15);
+ const PhysicalOffset container_offset(8, 8);
+ const PhysicalOffset hit_location(18, 15);
HitTestLocation location(hit_location);
Element* div = GetDocument().QuerySelector("div");
@@ -211,11 +211,11 @@ TEST_P(ParameterizedLayoutInlineTest, MultilineRelativePositionedHitTest) {
HitTestRequest hit_request(HitTestRequest::kReadOnly |
HitTestRequest::kActive |
HitTestRequest::kIgnorePointerEventsNone);
- const LayoutPoint container_offset(8, 8);
+ const PhysicalOffset container_offset(8, 8);
// Hit test first line
{
- LayoutPoint hit_location(13, 13);
+ PhysicalOffset hit_location(13, 13);
HitTestLocation location(hit_location);
Node* target = GetElementById("span")->firstChild();
@@ -235,7 +235,7 @@ TEST_P(ParameterizedLayoutInlineTest, MultilineRelativePositionedHitTest) {
// Hit test second line
{
- LayoutPoint hit_location(13, 23);
+ PhysicalOffset hit_location(13, 23);
HitTestLocation location(hit_location);
Node* target = GetElementById("line2")->firstChild();
@@ -255,7 +255,7 @@ TEST_P(ParameterizedLayoutInlineTest, MultilineRelativePositionedHitTest) {
// Hit test image in third line
{
- LayoutPoint hit_location(13, 33);
+ PhysicalOffset hit_location(13, 33);
HitTestLocation location(hit_location);
Node* target = GetDocument().QuerySelector("img");
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_list_box.cc b/chromium/third_party/blink/renderer/core/layout/layout_list_box.cc
index 687f4bd2d89..12c920aca3d 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_list_box.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_list_box.cc
@@ -83,7 +83,7 @@ LayoutUnit LayoutListBox::ItemHeight() const {
return LayoutUnit();
const auto& items = select->GetListItems();
- if (items.IsEmpty())
+ if (items.IsEmpty() || ShouldApplySizeContainment())
return DefaultItemHeight();
LayoutUnit max_height;
@@ -131,7 +131,7 @@ void LayoutListBox::ComputeIntrinsicLogicalWidths(
min_logical_width = LayoutUnit();
}
-void LayoutListBox::ScrollToRect(const LayoutRect& absolute_rect) {
+void LayoutListBox::ScrollToRect(const PhysicalRect& absolute_rect) {
if (HasOverflowClip()) {
DCHECK(Layer());
DCHECK(Layer()->GetScrollableArea());
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_list_box.h b/chromium/third_party/blink/renderer/core/layout/layout_list_box.h
index 10ebb01e814..91e76c1b097 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_list_box.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_list_box.h
@@ -45,7 +45,7 @@ class CORE_EXPORT LayoutListBox final : public LayoutBlockFlow {
unsigned size() const;
// Unlike scrollRectToVisible this will not scroll parent boxes.
- void ScrollToRect(const LayoutRect&);
+ void ScrollToRect(const PhysicalRect&);
const char* GetName() const override { return "LayoutListBox"; }
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 e6ca8ec009c..7153991c71e 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
@@ -54,10 +54,11 @@ LayoutMenuList::LayoutMenuList(Element* element)
LayoutMenuList::~LayoutMenuList() = default;
-// FIXME: Instead of this hack we should add a ShadowRoot to <select> with no
-// insertion point to prevent children from rendering.
bool LayoutMenuList::IsChildAllowed(LayoutObject* object,
const ComputedStyle&) const {
+ // For a size=1 <select>, we only render the active option through the
+ // anonymous inner_block_ plus button_text_. We do not allow adding layout
+ // objects for options or optgroups.
return object->IsAnonymous();
}
@@ -98,7 +99,7 @@ void LayoutMenuList::CreateInnerBlock() {
CreateInnerStyle(), legacy);
button_text_ =
- LayoutText::CreateEmptyAnonymous(GetDocument(), MutableStyle(), legacy);
+ LayoutText::CreateEmptyAnonymous(GetDocument(), Style(), legacy);
// We need to set the text explicitly though it was specified in the
// constructor because LayoutText doesn't refer to the text
// specified in the constructor in a case of re-transforming.
@@ -195,7 +196,7 @@ void LayoutMenuList::StyleDidChange(StyleDifference diff,
if (!inner_block_)
CreateInnerBlock();
- button_text_->SetStyle(MutableStyle());
+ button_text_->SetStyle(Style());
UpdateInnerStyle();
UpdateInnerBlockHeight();
}
@@ -208,6 +209,11 @@ void LayoutMenuList::UpdateInnerBlockHeight() {
}
void LayoutMenuList::UpdateOptionsWidth() const {
+ if (ShouldApplySizeContainment()) {
+ options_width_ = 0;
+ return;
+ }
+
float max_option_width = 0;
for (auto* const option : SelectElement()->GetOptionList()) {
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 b17a217eebc..e351e0691b0 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
@@ -475,15 +475,17 @@ void LayoutMultiColumnSet::ComputeLogicalHeight(
}
PositionWithAffinity LayoutMultiColumnSet::PositionForPoint(
- const LayoutPoint& point) const {
+ const PhysicalOffset& point) const {
+ LayoutPoint flipped_point = FlipForWritingMode(point);
// Convert the visual point to a flow thread point.
const MultiColumnFragmentainerGroup& row =
- FragmentainerGroupAtVisualPoint(point);
+ FragmentainerGroupAtVisualPoint(flipped_point);
LayoutPoint flow_thread_point = row.VisualPointToFlowThreadPoint(
- point + row.OffsetFromColumnSet(),
+ flipped_point + row.OffsetFromColumnSet(),
MultiColumnFragmentainerGroup::kSnapToColumn);
// Then drill into the flow thread, where we'll find the actual content.
- return FlowThread()->PositionForPoint(flow_thread_point);
+ return FlowThread()->PositionForPoint(
+ FlowThread()->FlipForWritingMode(flow_thread_point));
}
LayoutUnit LayoutMultiColumnSet::ColumnGap() const {
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 505e0bf2f4e..ed5ed54a877 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
@@ -250,7 +250,7 @@ class CORE_EXPORT LayoutMultiColumnSet final : public LayoutBlockFlow {
void ComputeLogicalHeight(LayoutUnit logical_height,
LayoutUnit logical_top,
LogicalExtentComputedValues&) const override;
- PositionWithAffinity PositionForPoint(const LayoutPoint&) const override;
+ PositionWithAffinity PositionForPoint(const PhysicalOffset&) const override;
void PaintObject(const PaintInfo&,
const PhysicalOffset& paint_offset) const override;
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 fafa63248c3..13220f6d0e9 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
@@ -167,12 +167,12 @@ void LayoutMultiColumnSpannerPlaceholder::Paint(
bool LayoutMultiColumnSpannerPlaceholder::NodeAtPoint(
HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
HitTestAction action) {
return !layout_object_in_flow_thread_->HasSelfPaintingLayer() &&
- layout_object_in_flow_thread_->NodeAtPoint(
- result, location_in_container, accumulated_offset, action);
+ layout_object_in_flow_thread_->NodeAtPoint(result, hit_test_location,
+ accumulated_offset, action);
}
} // namespace blink
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 3cff65393fa..c4018fbc0ae 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
@@ -68,8 +68,8 @@ class LayoutMultiColumnSpannerPlaceholder final : public LayoutBox {
LogicalExtentComputedValues&) const override;
void Paint(const PaintInfo&) const override;
bool NodeAtPoint(HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
HitTestAction) override;
private:
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 d138360ca59..f3b5dc3a336 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_object.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_object.cc
@@ -38,6 +38,7 @@
#include "third_party/blink/renderer/core/css/resolver/style_resolver.h"
#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/display_lock/display_lock_utilities.h"
#include "third_party/blink/renderer/core/dom/element_traversal.h"
#include "third_party/blink/renderer/core/dom/first_letter_pseudo_element.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
@@ -53,7 +54,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/frame/settings.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/html_element.h"
#include "third_party/blink/renderer/core/html/html_html_element.h"
#include "third_party/blink/renderer/core/html/html_table_cell_element.h"
@@ -105,8 +105,9 @@
#include "third_party/blink/renderer/platform/graphics/paint/geometry_mapper.h"
#include "third_party/blink/renderer/platform/graphics/paint/property_tree_state.h"
#include "third_party/blink/renderer/platform/graphics/touch_action.h"
-#include "third_party/blink/renderer/platform/instance_counters.h"
+#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/traced_value.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.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/text/string_builder.h"
@@ -159,23 +160,22 @@ LayoutObject::SetLayoutNeededForbiddenScope::~SetLayoutNeededForbiddenScope() {
}
#endif
-struct SameSizeAsLayoutObject : DisplayItemClient {
+struct SameSizeAsLayoutObject : ImageResourceObserver, DisplayItemClient {
// Normally this field uses the gap between DisplayItemClient and
// LayoutObject's other fields.
uint8_t paint_invalidation_reason_;
- void* pointers[5];
- Member<void*> members[1];
#if DCHECK_IS_ON()
unsigned debug_bitfields_;
#endif
unsigned bitfields_;
unsigned bitfields2_;
unsigned bitfields3_;
+ void* pointers[4];
+ Member<void*> members[1];
// The following fields are in FragmentData.
- LayoutRect visual_rect_;
- LayoutPoint paint_offset_;
+ IntRect visual_rect_;
+ PhysicalOffset paint_offset_;
std::unique_ptr<int> rare_data_;
- std::unique_ptr<FragmentData> next_fragment_;
};
static_assert(sizeof(LayoutObject) == sizeof(SameSizeAsLayoutObject),
@@ -274,26 +274,24 @@ LayoutObject* LayoutObject::CreateObject(Element* element,
LayoutObject::LayoutObject(Node* node)
: full_paint_invalidation_reason_(PaintInvalidationReason::kNone),
- style_(nullptr),
- node_(node),
- parent_(nullptr),
- previous_(nullptr),
- next_(nullptr),
#if DCHECK_IS_ON()
has_ax_object_(false),
set_needs_layout_forbidden_(false),
as_image_observer_count_(0),
#endif
- bitfields_(node) {
+ bitfields_(node),
+ style_(nullptr),
+ node_(node),
+ parent_(nullptr),
+ previous_(nullptr),
+ next_(nullptr) {
InstanceCounters::IncrementCounter(InstanceCounters::kLayoutObjectCounter);
if (node_)
GetFrameView()->IncrementLayoutObjectCount();
- if (const Node* node = GetNode()) {
- if (const Element* element = ToElementOrNull(node)) {
- if (element->ShouldForceLegacyLayout())
- SetForceLegacyLayout();
- }
+ if (const auto* element = DynamicTo<Element>(GetNode())) {
+ if (element->ShouldForceLegacyLayout())
+ SetForceLegacyLayout();
}
}
@@ -742,8 +740,8 @@ bool LayoutObject::IsFixedPositionObjectInPagedMedia() const {
view->IsHorizontalWritingMode();
}
-LayoutRect LayoutObject::ScrollRectToVisible(
- const LayoutRect& rect,
+PhysicalRect LayoutObject::ScrollRectToVisible(
+ const PhysicalRect& rect,
const WebScrollIntoViewParams& params) {
LayoutBox* enclosing_box = EnclosingBox();
if (!enclosing_box)
@@ -755,7 +753,7 @@ LayoutRect LayoutObject::ScrollRectToVisible(
WebScrollIntoViewParams new_params(params);
new_params.is_for_scroll_sequence |=
params.GetScrollType() == kProgrammaticScroll;
- LayoutRect new_location =
+ PhysicalRect new_location =
enclosing_box->ScrollRectToVisibleRecursive(rect, new_params);
GetDocument().GetFrame()->GetSmoothScrollSequencer().RunQueuedAnimations();
@@ -959,11 +957,14 @@ void LayoutObject::SetChildNeedsCollectInlines() {
if (object->NeedsCollectInlines())
break;
object->SetNeedsCollectInlines(true);
- if (object->IsLayoutBlockFlow() ||
- // Some LayoutReplaced have children (e.g., LayoutSVGRoot). Stop marking
- // because their children belong to different context.
- object->IsAtomicInlineLevel())
+
+ // Stop marking at the inline formatting context root. This is usually a
+ // |LayoutBlockFlow|, but some other classes can have children; e.g.,
+ // |LayoutButton| or |LayoutSVGRoot|. |LayoutInline| is the only class we
+ // collect recursively (see |CollectInlines|). Use the same condition here.
+ if (!object->IsLayoutInline())
break;
+
object = object->Parent();
} while (object);
}
@@ -1027,9 +1028,7 @@ void LayoutObject::MarkContainerChainForLayout(bool schedule_relayout,
DCHECK(!object->IsSetNeedsLayoutForbidden());
#endif
- if (object->HasLayer() &&
- ToLayoutBoxModelObject(object)->Layer()->IsSelfPaintingLayer())
- ToLayoutBoxModelObject(object)->Layer()->SetNeedsVisualOverflowRecalc();
+ object->MarkSelfPaintingLayerForVisualOverflowRecalc();
if (layouter) {
layouter->RecordObjectMarkedForLayout(object);
@@ -1037,7 +1036,6 @@ void LayoutObject::MarkContainerChainForLayout(bool schedule_relayout,
if (object == layouter->Root()) {
if (auto* painting_layer = PaintingLayer())
painting_layer->SetNeedsVisualOverflowRecalc();
-
return;
}
}
@@ -1569,7 +1567,7 @@ void LayoutObject::InvalidatePaint(
}
void LayoutObject::AdjustVisualRectForCompositedScrolling(
- IntRect& rect,
+ LayoutRect& rect,
const LayoutBoxModelObject& paint_invalidation_container) const {
if (CompositedScrollsWithRespectTo(paint_invalidation_container)) {
rect.Move(
@@ -1577,9 +1575,9 @@ void LayoutObject::AdjustVisualRectForCompositedScrolling(
}
}
-IntRect LayoutObject::VisualRectIncludingCompositedScrolling(
+LayoutRect LayoutObject::VisualRectIncludingCompositedScrolling(
const LayoutBoxModelObject& paint_invalidation_container) const {
- IntRect rect = VisualRect();
+ LayoutRect rect(VisualRect());
AdjustVisualRectForCompositedScrolling(rect, paint_invalidation_container);
return rect;
}
@@ -1703,7 +1701,7 @@ bool LayoutObject::MapToVisualRectInAncestorSpaceInternal(
}
HitTestResult LayoutObject::HitTestForOcclusion(
- const LayoutRect& hit_rect) const {
+ const PhysicalRect& hit_rect) const {
LocalFrame* frame = GetDocument().GetFrame();
DCHECK(!frame->View()->NeedsLayout());
HitTestRequest::HitTestRequestType hit_type =
@@ -1727,7 +1725,7 @@ std::ostream& operator<<(std::ostream& out, const LayoutObject& object) {
#else
info = object.DebugName();
#endif
- return out << static_cast<const void*>(&object) << ":" << info.Utf8().data();
+ return out << static_cast<const void*>(&object) << ":" << info.Utf8();
}
std::ostream& operator<<(std::ostream& out, const LayoutObject* object) {
@@ -1760,7 +1758,7 @@ void LayoutObject::ShowLineTreeForThis() const {
void LayoutObject::ShowLayoutObject() const {
StringBuilder string_builder;
DumpLayoutObject(string_builder, true, kShowTreeCharacterOffset);
- DLOG(INFO) << "\n" << string_builder.ToString().Utf8().data();
+ DLOG(INFO) << "\n" << string_builder.ToString().Utf8();
}
void LayoutObject::DumpLayoutObject(StringBuilder& string_builder,
@@ -1773,7 +1771,7 @@ void LayoutObject::DumpLayoutObject(StringBuilder& string_builder,
if (IsText() && ToLayoutText(this)->IsTextFragment()) {
string_builder.AppendFormat(" \"%s\" ",
- ToLayoutText(this)->GetText().Ascii().data());
+ ToLayoutText(this)->GetText().Ascii().c_str());
}
if (VirtualContinuation())
@@ -1785,6 +1783,8 @@ void LayoutObject::DumpLayoutObject(StringBuilder& string_builder,
string_builder.Append('\t');
string_builder.Append(GetNode()->ToString());
}
+ if (LayoutBlockedByDisplayLock(DisplayLockContext::kChildren))
+ string_builder.Append(" (display-locked)");
}
void LayoutObject::DumpLayoutTreeAndMark(StringBuilder& string_builder,
@@ -1804,11 +1804,14 @@ void LayoutObject::DumpLayoutTreeAndMark(StringBuilder& string_builder,
DumpLayoutObject(object_info, true, kShowTreeCharacterOffset);
string_builder.Append(object_info);
- for (const LayoutObject* child = SlowFirstChild(); child;
- child = child->NextSibling()) {
- string_builder.Append('\n');
- child->DumpLayoutTreeAndMark(string_builder, marked_object1, marked_label1,
- marked_object2, marked_label2, depth + 1);
+ if (!LayoutBlockedByDisplayLock(DisplayLockContext::kChildren)) {
+ for (const LayoutObject* child = SlowFirstChild(); child;
+ child = child->NextSibling()) {
+ string_builder.Append('\n');
+ child->DumpLayoutTreeAndMark(string_builder, marked_object1,
+ marked_label1, marked_object2, marked_label2,
+ depth + 1);
+ }
}
}
@@ -1899,7 +1902,8 @@ StyleDifference LayoutObject::AdjustStyleDifference(
return diff;
}
-void LayoutObject::SetPseudoStyle(scoped_refptr<ComputedStyle> pseudo_style) {
+void LayoutObject::SetPseudoStyle(
+ scoped_refptr<const ComputedStyle> pseudo_style) {
DCHECK(pseudo_style->StyleType() == kPseudoIdBefore ||
pseudo_style->StyleType() == kPseudoIdAfter ||
pseudo_style->StyleType() == kPseudoIdFirstLetter);
@@ -1935,12 +1939,7 @@ void LayoutObject::MarkContainerChainForOverflowRecalcIfNeeded() {
: object->Container();
if (object) {
object->SetChildNeedsLayoutOverflowRecalc();
-
- if (object->HasLayer()) {
- auto* box_model_object = ToLayoutBoxModelObject(object);
- if (box_model_object->HasSelfPaintingLayer())
- box_model_object->Layer()->SetNeedsVisualOverflowRecalc();
- }
+ object->MarkSelfPaintingLayerForVisualOverflowRecalc();
}
} while (object);
@@ -1950,18 +1949,14 @@ void LayoutObject::SetNeedsOverflowRecalc() {
bool needed_recalc = SelfNeedsLayoutOverflowRecalc();
SetSelfNeedsLayoutOverflowRecalc();
SetShouldCheckForPaintInvalidation();
+ MarkSelfPaintingLayerForVisualOverflowRecalc();
- if (HasLayer()) {
- auto* box_model_object = ToLayoutBoxModelObject(this);
- if (box_model_object->HasSelfPaintingLayer())
- box_model_object->Layer()->SetNeedsVisualOverflowRecalc();
- }
if (!needed_recalc)
MarkContainerChainForOverflowRecalcIfNeeded();
}
DISABLE_CFI_PERF
-void LayoutObject::SetStyle(scoped_refptr<ComputedStyle> style,
+void LayoutObject::SetStyle(scoped_refptr<const ComputedStyle> style,
ApplyStyleChanges apply_changes) {
if (style_ == style)
return;
@@ -1974,14 +1969,24 @@ void LayoutObject::SetStyle(scoped_refptr<ComputedStyle> style,
DCHECK(style);
StyleDifference diff;
- if (style_)
+ if (style_) {
diff = style_->VisualInvalidationDiff(GetDocument(), *style);
+ if (const auto* cached_inherited_first_line_style =
+ style_->GetCachedPseudoStyle(kPseudoIdFirstLineInherited)) {
+ // Merge the difference to the first line style because even if the new
+ // style is the same as the old style, the new style may have some higher
+ // priority properties overriding first line style.
+ // See external/wpt/css/css-pseudo/first-line-change-inline-color*.html.
+ diff.Merge(cached_inherited_first_line_style->VisualInvalidationDiff(
+ GetDocument(), *style));
+ }
+ }
diff = AdjustStyleDifference(diff);
StyleWillChange(diff, *style);
- scoped_refptr<ComputedStyle> old_style = std::move(style_);
+ scoped_refptr<const ComputedStyle> old_style = std::move(style_);
SetStyleInternal(std::move(style));
if (!IsText())
@@ -2016,6 +2021,8 @@ void LayoutObject::SetStyle(scoped_refptr<ComputedStyle> style,
}
}
+ // TODO(cbiesinger): Shouldn't this check container->NeedsLayout, since that's
+ // the one we'll mark for NeedsOverflowRecalc()?
if (diff.TransformChanged() && !NeedsLayout()) {
if (LayoutBlock* container = ContainingBlock())
container->SetNeedsOverflowRecalc();
@@ -2113,7 +2120,10 @@ void LayoutObject::UpdateImageObservers(const ComputedStyle* old_style,
void LayoutObject::UpdateFirstLineImageObservers(
const ComputedStyle* new_style) {
bool has_new_first_line_style =
- new_style && new_style->HasPseudoStyle(kPseudoIdFirstLine);
+ new_style && new_style->HasPseudoStyle(kPseudoIdFirstLine) &&
+ BehavesLikeBlockContainer();
+ DCHECK(!has_new_first_line_style || new_style == Style());
+
if (!bitfields_.RegisteredAsFirstLineImageObserver() &&
!has_new_first_line_style)
return;
@@ -2128,36 +2138,31 @@ void LayoutObject::UpdateFirstLineImageObservers(
? first_line_style_map.at(this)
: nullptr;
- // Don't call CacheFirstLineStyle() which will update the cache, because this
- // function can be called when the object has not been inserted into the tree
- // and we can't update the pseudo style cache which may depend on ancestors.
- const auto* cached_new_first_line_style =
- has_new_first_line_style
- ? new_style->GetCachedPseudoStyle(kPseudoIdFirstLine)
- : nullptr;
-
- if (has_new_first_line_style) {
- // If cached_new_first_line_style is null, it means that the new first line
- // style has not been cached yet. Will check again when the object's first
- // line style is actually used and cached.
- bitfields_.SetPendingUpdateFirstLineImageObservers(
- !cached_new_first_line_style);
- }
-
- if (cached_new_first_line_style &&
- !cached_new_first_line_style->HasBackgroundImage())
- cached_new_first_line_style = nullptr;
-
- if (old_first_line_style || cached_new_first_line_style) {
- UpdateFillImages(old_first_line_style
- ? &old_first_line_style->BackgroundLayers()
- : nullptr,
- cached_new_first_line_style
- ? &cached_new_first_line_style->BackgroundLayers()
- : nullptr);
- if (cached_new_first_line_style) {
+ // UpdateFillImages() may indirectly call LayoutBlock::ImageChanged() which
+ // will invalidate the first line style cache and remove a reference to
+ // new_first_line_style, so hold a reference here.
+ scoped_refptr<const ComputedStyle> new_first_line_style =
+ has_new_first_line_style ? FirstLineStyleWithoutFallback() : nullptr;
+
+ if (new_first_line_style && !new_first_line_style->HasBackgroundImage())
+ new_first_line_style = nullptr;
+
+ if (old_first_line_style || new_first_line_style) {
+ UpdateFillImages(
+ old_first_line_style ? &old_first_line_style->BackgroundLayers()
+ : nullptr,
+ new_first_line_style ? &new_first_line_style->BackgroundLayers()
+ : nullptr);
+ if (new_first_line_style) {
+ // The cached first line style may have been invalidated during
+ // UpdateFillImages, so get it again. However, the new cached first line
+ // style should be the same as the previous new_first_line_style.
+ DCHECK(FillLayer::ImagesIdentical(
+ &new_first_line_style->BackgroundLayers(),
+ &FirstLineStyleWithoutFallback()->BackgroundLayers()));
+ new_first_line_style = FirstLineStyleWithoutFallback();
bitfields_.SetRegisteredAsFirstLineImageObserver(true);
- first_line_style_map.Set(this, cached_new_first_line_style);
+ first_line_style_map.Set(this, std::move(new_first_line_style));
} else {
bitfields_.SetRegisteredAsFirstLineImageObserver(false);
first_line_style_map.erase(this);
@@ -2266,12 +2271,11 @@ void LayoutObject::StyleWillChange(StyleDifference diff,
}
void LayoutObject::ClearBaseComputedStyle() {
- if (!GetNode())
- return;
- if (!GetNode()->IsElementNode())
+ auto* element = DynamicTo<Element>(GetNode());
+ if (!element)
return;
- if (ElementAnimations* animations =
- ToElement(GetNode())->GetElementAnimations())
+
+ if (ElementAnimations* animations = element->GetElementAnimations())
animations->ClearBaseComputedStyle();
}
@@ -2392,7 +2396,7 @@ void LayoutObject::ApplyFirstLineChanges(const ComputedStyle* old_style) {
if (Parent() && has_old_first_line_style && has_new_first_line_style) {
if (const auto* old_first_line_style =
old_style->GetCachedPseudoStyle(kPseudoIdFirstLine)) {
- if (auto new_first_line_style = UncachedFirstLineStyle()) {
+ if (const auto* new_first_line_style = FirstLineStyleWithoutFallback()) {
diff = old_first_line_style->VisualInvalidationDiff(
GetDocument(), *new_first_line_style);
has_diff = true;
@@ -2470,13 +2474,14 @@ void LayoutObject::PropagateStyleToAnonymousChildren() {
continue;
}
if (child->IsText() || child->IsQuote() || child->IsImage())
- child->SetPseudoStyle(MutableStyle());
+ child->SetPseudoStyle(Style());
child = child->NextInPreOrder(this);
}
}
-void LayoutObject::SetStyleWithWritingModeOf(scoped_refptr<ComputedStyle> style,
- LayoutObject* parent) {
+void LayoutObject::SetStyleWithWritingModeOfParent(
+ scoped_refptr<ComputedStyle> style) {
+ const LayoutObject* parent = Parent();
if (parent) {
style->SetWritingMode(parent->StyleRef().GetWritingMode());
style->UpdateFontOrientation();
@@ -2484,11 +2489,6 @@ void LayoutObject::SetStyleWithWritingModeOf(scoped_refptr<ComputedStyle> style,
SetStyle(std::move(style));
}
-void LayoutObject::SetStyleWithWritingModeOfParent(
- scoped_refptr<ComputedStyle> style) {
- SetStyleWithWritingModeOf(std::move(style), Parent());
-}
-
void LayoutObject::AddAsImageObserver(StyleImage* image) {
if (!image)
return;
@@ -3149,7 +3149,7 @@ void LayoutObject::WillBeRemovedFromTree() {
if (RuntimeEnabledFeatures::FirstContentfulPaintPlusPlusEnabled() ||
RuntimeEnabledFeatures::ElementTimingEnabled(&GetDocument())) {
if (LocalFrameView* frame_view = GetFrameView()) {
- frame_view->GetPaintTimingDetector().NotifyNodeRemoved(*this);
+ frame_view->GetPaintTimingDetector().LayoutObjectWillBeDestroyed(*this);
}
}
}
@@ -3268,7 +3268,8 @@ void LayoutObject::Destroy() {
delete this;
}
-PositionWithAffinity LayoutObject::PositionForPoint(const LayoutPoint&) const {
+PositionWithAffinity LayoutObject::PositionForPoint(
+ const PhysicalOffset&) const {
return CreatePositionWithAffinity(CaretMinOffset());
}
@@ -3282,32 +3283,31 @@ CompositingReasons LayoutObject::AdditionalCompositingReasons() const {
return CompositingReason::kNone;
}
-bool LayoutObject::HitTestAllPhases(
- HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
- HitTestFilter hit_test_filter) {
+bool LayoutObject::HitTestAllPhases(HitTestResult& result,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
+ HitTestFilter hit_test_filter) {
bool inside = false;
if (hit_test_filter != kHitTestSelf) {
// First test the foreground layer (lines and inlines).
- inside = NodeAtPoint(result, location_in_container, accumulated_offset,
+ inside = NodeAtPoint(result, hit_test_location, accumulated_offset,
kHitTestForeground);
// Test floats next.
if (!inside)
- inside = NodeAtPoint(result, location_in_container, accumulated_offset,
+ inside = NodeAtPoint(result, hit_test_location, accumulated_offset,
kHitTestFloat);
// Finally test to see if the mouse is in the background (within a child
// block's background).
if (!inside)
- inside = NodeAtPoint(result, location_in_container, accumulated_offset,
+ inside = NodeAtPoint(result, hit_test_location, accumulated_offset,
kHitTestChildBlockBackgrounds);
}
// See if the mouse is inside us but not any of our descendants
if (hit_test_filter != kHitTestDescendants && !inside)
- inside = NodeAtPoint(result, location_in_container, accumulated_offset,
+ inside = NodeAtPoint(result, hit_test_location, accumulated_offset,
kHitTestBlockBackground);
return inside;
@@ -3328,7 +3328,7 @@ Node* LayoutObject::NodeForHitTest() const {
}
void LayoutObject::UpdateHitTestResult(HitTestResult& result,
- const LayoutPoint& point) const {
+ const PhysicalOffset& point) const {
if (result.InnerNode())
return;
@@ -3337,8 +3337,8 @@ void LayoutObject::UpdateHitTestResult(HitTestResult& result,
}
bool LayoutObject::NodeAtPoint(HitTestResult&,
- const HitTestLocation& /*locationInContainer*/,
- const LayoutPoint& /*accumulatedOffset*/,
+ const HitTestLocation&,
+ const PhysicalOffset&,
HitTestAction) {
return false;
}
@@ -3363,75 +3363,50 @@ void LayoutObject::ForceLayout() {
UpdateLayout();
}
-enum StyleCacheState { kCached, kUncached };
-
-static scoped_refptr<const ComputedStyle> FirstLineStyleForCachedUncachedType(
- StyleCacheState type,
- const LayoutObject* layout_object,
- const ComputedStyle* style) {
- DCHECK(layout_object);
+const ComputedStyle* LayoutObject::FirstLineStyleWithoutFallback() const {
+ DCHECK(GetDocument().GetStyleEngine().UsesFirstLineRules());
- const LayoutObject* layout_object_for_first_line_style = layout_object;
- if (layout_object->IsBeforeOrAfterContent()) {
- if (!layout_object->Parent())
+ if (IsBeforeOrAfterContent() || IsText()) {
+ if (!Parent())
return nullptr;
- layout_object_for_first_line_style = layout_object->Parent();
+ return Parent()->FirstLineStyleWithoutFallback();
}
- if (layout_object_for_first_line_style->BehavesLikeBlockContainer()) {
+ if (BehavesLikeBlockContainer()) {
+ if (const ComputedStyle* cached =
+ StyleRef().GetCachedPseudoStyle(kPseudoIdFirstLine))
+ return cached;
+
if (const LayoutBlock* first_line_block =
- To<LayoutBlock>(layout_object_for_first_line_style)
- ->EnclosingFirstLineStyleBlock()) {
- if (type == kCached)
- return first_line_block->GetCachedPseudoStyle(kPseudoIdFirstLine,
- style);
- return first_line_block->GetUncachedPseudoStyle(
- PseudoStyleRequest(kPseudoIdFirstLine), style);
+ To<LayoutBlock>(this)->EnclosingFirstLineStyleBlock()) {
+ if (first_line_block->Style() == Style())
+ return first_line_block->GetCachedPseudoStyle(kPseudoIdFirstLine);
+
+ // We can't use first_line_block->GetCachedPseudoStyle() because it's
+ // based on first_line_block's style. We need to get the uncached first
+ // line style based on this object's style and cache the result in it.
+ return StyleRef().AddCachedPseudoStyle(
+ first_line_block->GetUncachedPseudoStyle(
+ PseudoStyleRequest(kPseudoIdFirstLine), Style()));
}
- } else if (!layout_object_for_first_line_style->IsAnonymous() &&
- layout_object_for_first_line_style->IsLayoutInline() &&
- !layout_object_for_first_line_style->GetNode()
- ->IsFirstLetterPseudoElement()) {
- const ComputedStyle* parent_style =
- layout_object_for_first_line_style->Parent()->FirstLineStyle();
- if (parent_style != layout_object_for_first_line_style->Parent()->Style()) {
- if (type == kCached) {
- // A first-line style is in effect. Cache a first-line style for
- // ourselves.
- return layout_object_for_first_line_style->GetCachedPseudoStyle(
- kPseudoIdFirstLineInherited, parent_style);
- }
- return layout_object_for_first_line_style->GetUncachedPseudoStyle(
- PseudoStyleRequest(kPseudoIdFirstLineInherited), parent_style);
+ } else if (!IsAnonymous() && IsLayoutInline() &&
+ !GetNode()->IsFirstLetterPseudoElement()) {
+ if (const ComputedStyle* cached =
+ StyleRef().GetCachedPseudoStyle(kPseudoIdFirstLineInherited))
+ return cached;
+
+ if (const ComputedStyle* parent_first_line_style =
+ Parent()->FirstLineStyleWithoutFallback()) {
+ // A first-line style is in effect. Get uncached first line style based on
+ // parent_first_line_style and cache the result in this object's style.
+ return StyleRef().AddCachedPseudoStyle(GetUncachedPseudoStyle(
+ kPseudoIdFirstLineInherited, parent_first_line_style));
}
}
return nullptr;
}
-scoped_refptr<const ComputedStyle> LayoutObject::UncachedFirstLineStyle()
- const {
- if (!GetDocument().GetStyleEngine().UsesFirstLineRules())
- return nullptr;
-
- DCHECK(!IsText());
-
- return FirstLineStyleForCachedUncachedType(kUncached, this, style_.get());
-}
-
-const ComputedStyle* LayoutObject::CachedFirstLineStyle() const {
- DCHECK(GetDocument().GetStyleEngine().UsesFirstLineRules());
-
- if (scoped_refptr<const ComputedStyle> style =
- FirstLineStyleForCachedUncachedType(
- kCached, IsText() ? Parent() : this, style_.get()))
- return style.get();
-
- return style_.get();
-}
-
-const ComputedStyle* LayoutObject::GetCachedPseudoStyle(
- PseudoId pseudo,
- const ComputedStyle* parent_style) const {
+const ComputedStyle* LayoutObject::GetCachedPseudoStyle(PseudoId pseudo) const {
DCHECK_NE(pseudo, kPseudoIdBefore);
DCHECK_NE(pseudo, kPseudoIdAfter);
if (!GetNode())
@@ -3441,15 +3416,7 @@ const ComputedStyle* LayoutObject::GetCachedPseudoStyle(
if (!element)
return nullptr;
- const auto* cached_pseudo_style = element->CachedStyleForPseudoElement(
- PseudoStyleRequest(pseudo), parent_style);
- if (cached_pseudo_style && pseudo == kPseudoIdFirstLine &&
- bitfields_.PendingUpdateFirstLineImageObservers()) {
- // Update image observers now after we have updated the first line
- // style cache.
- const_cast<LayoutObject*>(this)->UpdateFirstLineImageObservers(Style());
- }
- return cached_pseudo_style;
+ return element->CachedStyleForPseudoElement(PseudoStyleRequest(pseudo));
}
scoped_refptr<ComputedStyle> LayoutObject::GetUncachedPseudoStyle(
@@ -3546,9 +3513,21 @@ void LayoutObject::ImageChanged(ImageResourceContent* image,
ImageChanged(static_cast<WrappedImagePtr>(image), defer);
}
-void LayoutObject::ImageNotifyFinished(ImageResourceContent*) {
+void LayoutObject::ImageNotifyFinished(ImageResourceContent* image) {
if (AXObjectCache* cache = GetDocument().ExistingAXObjectCache())
cache->ImageLoaded(this);
+
+ if (RuntimeEnabledFeatures::ElementTimingEnabled(&GetDocument())) {
+ LocalDOMWindow* window = GetDocument().domWindow();
+ if (window) {
+ ImageElementTiming::From(*window).NotifyImageFinished(*this, image);
+ }
+ }
+ if (RuntimeEnabledFeatures::FirstContentfulPaintPlusPlusEnabled()) {
+ if (LocalFrameView* frame_view = GetFrameView()) {
+ frame_view->GetPaintTimingDetector().NotifyImageFinished(*this, image);
+ }
+ }
}
Element* LayoutObject::OffsetParent(const Element* base) const {
@@ -3597,21 +3576,19 @@ Element* LayoutObject::OffsetParent(const Element* base) const {
break;
}
- return node && node->IsElementNode() ? ToElement(node) : nullptr;
+ return DynamicTo<Element>(node);
}
void LayoutObject::NotifyImageFullyRemoved(ImageResourceContent* image) {
if (RuntimeEnabledFeatures::ElementTimingEnabled(&GetDocument())) {
LocalDOMWindow* window = GetDocument().domWindow();
if (window) {
- ImageElementTiming::From(*window).NotifyBackgroundImageRemoved(this,
- image);
+ ImageElementTiming::From(*window).NotifyImageRemoved(this, image);
}
}
if (RuntimeEnabledFeatures::FirstContentfulPaintPlusPlusEnabled()) {
if (LocalFrameView* frame_view = GetFrameView()) {
- frame_view->GetPaintTimingDetector().NotifyBackgroundImageRemoved(*this,
- image);
+ frame_view->GetPaintTimingDetector().NotifyImageRemoved(*this, image);
}
}
}
@@ -3693,7 +3670,7 @@ PositionWithAffinity LayoutObject::CreatePositionWithAffinity(
return CreatePositionWithAffinity(0);
}
-CursorDirective LayoutObject::GetCursor(const LayoutPoint&, Cursor&) const {
+CursorDirective LayoutObject::GetCursor(const PhysicalOffset&, Cursor&) const {
return kSetCursorBasedOnStyle;
}
@@ -3941,7 +3918,7 @@ void LayoutObject::MarkEffectiveAllowedTouchActionChanged() {
// If we're locked, mark our descendants as needing this change. This is used
// a signal to ensure we mark the element as needing effective allowed
// touch action recalculation when the element becomes unlocked.
- if (PrePaintBlockedByDisplayLock()) {
+ if (PrePaintBlockedByDisplayLock(DisplayLockContext::kChildren)) {
bitfields_.SetDescendantEffectiveAllowedTouchActionChanged(true);
return;
}
@@ -3949,7 +3926,7 @@ void LayoutObject::MarkEffectiveAllowedTouchActionChanged() {
LayoutObject* obj = ParentCrossingFrames();
while (obj && !obj->DescendantEffectiveAllowedTouchActionChanged()) {
obj->bitfields_.SetDescendantEffectiveAllowedTouchActionChanged(true);
- if (obj->PrePaintBlockedByDisplayLock())
+ if (obj->PrePaintBlockedByDisplayLock(DisplayLockContext::kChildren))
break;
obj = obj->ParentCrossingFrames();
@@ -4018,8 +3995,10 @@ const LayoutObject* AssociatedLayoutObjectOf(const Node& node,
}
bool LayoutObject::CanBeSelectionLeaf() const {
- if (SlowFirstChild() || StyleRef().Visibility() != EVisibility::kVisible)
+ if (SlowFirstChild() || StyleRef().Visibility() != EVisibility::kVisible ||
+ DisplayLockUtilities::NearestLockedExclusiveAncestor(*GetNode())) {
return false;
+ }
return CanBeSelectionLeafInternal();
}
@@ -4057,7 +4036,7 @@ Vector<PhysicalRect> LayoutObject::OutlineRects(
}
void LayoutObject::SetModifiedStyleOutsideStyleRecalc(
- scoped_refptr<ComputedStyle> style,
+ scoped_refptr<const ComputedStyle> style,
ApplyStyleChanges apply_changes) {
SetStyle(style, apply_changes);
if (IsAnonymous() || !GetNode() || !GetNode()->IsElementNode())
@@ -4079,6 +4058,14 @@ LayoutUnit LayoutObject::FlipForWritingModeInternal(
->FlipForWritingMode(position, width);
}
+void LayoutObject::MarkSelfPaintingLayerForVisualOverflowRecalc() {
+ if (HasLayer()) {
+ auto* box_model_object = ToLayoutBoxModelObject(this);
+ if (box_model_object->HasSelfPaintingLayer())
+ box_model_object->Layer()->SetNeedsVisualOverflowRecalc();
+ }
+}
+
} // namespace blink
#if DCHECK_IS_ON()
@@ -4111,7 +4098,7 @@ void showLayoutTree(const blink::LayoutObject* object1,
StringBuilder string_builder;
root->DumpLayoutTreeAndMark(string_builder, object1, "*", object2, "-",
0);
- DLOG(INFO) << "\n" << string_builder.ToString().Utf8().data();
+ DLOG(INFO) << "\n" << string_builder.ToString().Utf8();
}
} else {
DLOG(INFO) << "Cannot showLayoutTree. Root is (nil)";
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 20fba260c30..05ad47a2734 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_object.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_object.h
@@ -61,7 +61,7 @@
#include "third_party/blink/renderer/platform/graphics/paint_invalidation_reason.h"
#include "third_party/blink/renderer/platform/graphics/subtree_paint_property_update_reason.h"
#include "third_party/blink/renderer/platform/transforms/transformation_matrix.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -369,8 +369,8 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
// space of the local root frame.
// TODO(nburris): The returned rect is actually in document coordinates, not
// root frame coordinates.
- LayoutRect ScrollRectToVisible(const LayoutRect&,
- const WebScrollIntoViewParams&);
+ PhysicalRect ScrollRectToVisible(const PhysicalRect&,
+ const WebScrollIntoViewParams&);
// Convenience function for getting to the nearest enclosing box of a
// LayoutObject.
@@ -435,7 +435,8 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
}
void AssertClearedPaintInvalidationFlags() const {
- if (PaintInvalidationStateIsDirty() && !PrePaintBlockedByDisplayLock()) {
+ if (PaintInvalidationStateIsDirty() &&
+ !PrePaintBlockedByDisplayLock(DisplayLockContext::kChildren)) {
ShowLayoutTreeForThis();
NOTREACHED();
}
@@ -443,7 +444,8 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
void AssertSubtreeClearedPaintInvalidationFlags() const {
for (const LayoutObject* layout_object = this; layout_object;
- layout_object = layout_object->PrePaintBlockedByDisplayLock()
+ layout_object = layout_object->PrePaintBlockedByDisplayLock(
+ DisplayLockContext::kChildren)
? layout_object->NextInPreOrderAfterChildren()
: layout_object->NextInPreOrder()) {
layout_object->AssertClearedPaintInvalidationFlags();
@@ -1141,12 +1143,12 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
bool IsRenderedLegendInternal() const;
- // The pseudo element style can be cached or uncached. Use the cached method
+ // The pseudo element style can be cached or uncached. Use the cached method
// if the pseudo element doesn't respect any pseudo classes (and therefore
- // has no concept of changing state).
- const ComputedStyle* GetCachedPseudoStyle(
- PseudoId,
- const ComputedStyle* parent_style = nullptr) const;
+ // has no concept of changing state). The cached pseudo style always inherits
+ // from the originating element's style (because we can cache only one
+ // version), while the uncached pseudo style can inherit from any style.
+ const ComputedStyle* GetCachedPseudoStyle(PseudoId) const;
scoped_refptr<ComputedStyle> GetUncachedPseudoStyle(
const PseudoStyleRequest&,
const ComputedStyle* parent_style = nullptr) const;
@@ -1268,9 +1270,9 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
// It is also used for correctly sizing absolutely positioned elements
// (point 3 above).
LayoutObject* Container(AncestorSkipInfo* = nullptr) const;
- // Finds the container as if this object is fixed-position.
- LayoutObject* ContainerForAbsolutePosition(AncestorSkipInfo* = nullptr) const;
// Finds the container as if this object is absolute-position.
+ LayoutObject* ContainerForAbsolutePosition(AncestorSkipInfo* = nullptr) const;
+ // Finds the container as if this object is fixed-position.
LayoutObject* ContainerForFixedPosition(AncestorSkipInfo* = nullptr) const;
bool CanContainOutOfFlowPositionedElement(EPosition position) const {
@@ -1308,12 +1310,10 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
MarkingBehavior = kMarkContainerChain,
SubtreeLayoutScope* = nullptr);
- void ClearNeedsLayoutWithoutPaintInvalidation(
- bool clear_child_dirty_bits = true);
+ void ClearNeedsLayoutWithoutPaintInvalidation();
// |ClearNeedsLayout()| calls |SetShouldCheckForPaintInvalidation()|.
- void ClearNeedsLayout(bool clear_child_dirty_bits = true);
- void ClearNeedsLayoutWithFullPaintInvalidation(
- bool clear_child_dirty_bits = true);
+ void ClearNeedsLayout();
+ void ClearNeedsLayoutWithFullPaintInvalidation();
void SetChildNeedsLayout(MarkingBehavior = kMarkContainerChain,
SubtreeLayoutScope* = nullptr);
@@ -1453,22 +1453,32 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
CompositingState GetCompositingState() const;
virtual CompositingReasons AdditionalCompositingReasons() const;
+ // |accumulated_offset| is accumulated physical offset of this object from
+ // the same origin as |hit_test_location|. The caller just ensures that
+ // |hit_test_location| and |accumulated_offset| are in the same coordinate
+ // space that is transform-compatible with this object (i.e. we can add 2d
+ // local offset to it without considering transforms). The implementation
+ // should not assume any specific coordinate space of them. The local offset
+ // of |hit_test_location| in this object can be calculated by
+ // |hit_test_location.Point() - accumulated_offset|.
virtual bool HitTestAllPhases(HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
HitTestFilter = kHitTestAll);
// Returns the node that is ultimately added to the hit test result. Some
// objects report a hit testing node that is not their own (such as
// continuations and some psuedo elements) and it is important that the
// node be consistent between point- and list-based hit test results.
virtual Node* NodeForHitTest() const;
- virtual void UpdateHitTestResult(HitTestResult&, const LayoutPoint&) const;
+ virtual void UpdateHitTestResult(HitTestResult&, const PhysicalOffset&) const;
+ // See HitTestAllPhases() for explanation of |hit_test_location| and
+ // |accumulated_offset|.
virtual bool NodeAtPoint(HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
HitTestAction);
- virtual PositionWithAffinity PositionForPoint(const LayoutPoint&) const;
+ virtual PositionWithAffinity PositionForPoint(const PhysicalOffset&) const;
PositionWithAffinity CreatePositionWithAffinity(int offset,
TextAffinity) const;
PositionWithAffinity CreatePositionWithAffinity(int offset) const;
@@ -1483,11 +1493,11 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
// and new ComputedStyle like paint and size invalidations. If kNo, just set
// the ComputedStyle member.
enum class ApplyStyleChanges { kNo, kYes };
- void SetStyle(scoped_refptr<ComputedStyle>,
+ void SetStyle(scoped_refptr<const ComputedStyle>,
ApplyStyleChanges = ApplyStyleChanges::kYes);
// Set the style of the object if it's generated content.
- void SetPseudoStyle(scoped_refptr<ComputedStyle>);
+ void SetPseudoStyle(scoped_refptr<const ComputedStyle>);
// In some cases we modify the ComputedStyle after the style recalc, either
// for updating anonymous style or doing layout hacks for special elements
@@ -1499,11 +1509,9 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
// visual invalidation etc.
//
// Do not use unless strictly necessary.
- void SetModifiedStyleOutsideStyleRecalc(scoped_refptr<ComputedStyle>,
+ void SetModifiedStyleOutsideStyleRecalc(scoped_refptr<const ComputedStyle>,
ApplyStyleChanges);
- void SetStyleWithWritingModeOf(scoped_refptr<ComputedStyle>,
- LayoutObject* parent);
void SetStyleWithWritingModeOfParent(scoped_refptr<ComputedStyle>);
void ClearBaseComputedStyle();
@@ -1724,17 +1732,17 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
virtual LayoutUnit MaxPreferredLogicalWidth() const { return LayoutUnit(); }
const ComputedStyle* Style() const { return style_.get(); }
- ComputedStyle* MutableStyle() const { return style_.get(); }
// style_ can only be nullptr before the first style is set, thus most
// callers will never see a nullptr style and should use StyleRef().
- const ComputedStyle& StyleRef() const { return MutableStyleRef(); }
- ComputedStyle& MutableStyleRef() const {
+ const ComputedStyle& StyleRef() const {
DCHECK(style_);
return *style_;
}
/* The following methods are inlined in LayoutObjectInlines.h */
+ // If first line style is requested and there is no applicable first line
+ // style, the functions will return the style of this object.
inline const ComputedStyle* FirstLineStyle() const;
inline const ComputedStyle& FirstLineStyleRef() const;
inline const ComputedStyle* Style(bool first_line) const;
@@ -1749,7 +1757,7 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
return StyleRef().VisitedDependentColor(color_property);
}
- virtual CursorDirective GetCursor(const LayoutPoint&, Cursor&) const;
+ virtual CursorDirective GetCursor(const PhysicalOffset&, Cursor&) const;
// Return the LayoutBoxModelObject in the container chain which is responsible
// for painting this object. The function crosses frames boundaries so the
@@ -1819,9 +1827,9 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
VisualRectFlags = kDefaultVisualRectFlags) const;
// Do a rect-based hit test with this object as the stop node.
- HitTestResult HitTestForOcclusion(const LayoutRect&) const;
+ HitTestResult HitTestForOcclusion(const PhysicalRect&) const;
HitTestResult HitTestForOcclusion() const {
- return HitTestForOcclusion(VisualRectInDocument().ToLayoutRect());
+ return HitTestForOcclusion(VisualRectInDocument());
}
// Return the offset to the column in which the specified point (in
@@ -1947,14 +1955,10 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
bool VisibleToHitTestRequest(const HitTestRequest& request) const {
return StyleRef().Visibility() == EVisibility::kVisible &&
(request.IgnorePointerEventsNone() ||
- StyleRef().PointerEvents() != EPointerEvents::kNone) &&
- !IsInert();
+ StyleRef().PointerEvents() != EPointerEvents::kNone);
}
- // Warning: inertness can change without causing relayout.
- bool VisibleToHitTesting() const {
- return StyleRef().VisibleToHitTesting() && !IsInert();
- }
+ bool VisibleToHitTesting() const { return StyleRef().VisibleToHitTesting(); }
// Map points and quads through elements, potentially via 3d transforms. You
// should never need to call these directly; use localToAbsolute/
@@ -2022,14 +2026,16 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
// The visual rect, in the the space of the paint invalidation container
// (*not* the graphics layer that paints this object).
- IntRect VisualRectIncludingCompositedScrolling(
+ LayoutRect VisualRectIncludingCompositedScrolling(
const LayoutBoxModelObject& paint_invalidation_container) const;
// Called when the previous visual rect(s) is no longer valid.
virtual void ClearPreviousVisualRects();
- void SetSelfNeedsLayoutForAvailableSpace(bool b) {
- bitfields_.SetSelfNeedsLayoutForAvailableSpace(b);
+ void SetSelfNeedsLayoutForAvailableSpace(bool flag) {
+ bitfields_.SetSelfNeedsLayoutForAvailableSpace(flag);
+ if (flag)
+ MarkSelfPaintingLayerForVisualOverflowRecalc();
}
PaintInvalidationReason FullPaintInvalidationReason() const {
@@ -2191,11 +2197,15 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
DocumentLifecycle::kInPrePaint);
layout_object_.ClearPaintInvalidationFlags();
layout_object_.bitfields_.SetNeedsPaintPropertyUpdate(false);
- layout_object_.bitfields_.ResetSubtreePaintPropertyUpdateReasons();
- layout_object_.bitfields_.SetDescendantNeedsPaintPropertyUpdate(false);
layout_object_.bitfields_.SetEffectiveAllowedTouchActionChanged(false);
- layout_object_.bitfields_.SetDescendantEffectiveAllowedTouchActionChanged(
- false);
+
+ if (!layout_object_.PrePaintBlockedByDisplayLock(
+ DisplayLockContext::kChildren)) {
+ layout_object_.bitfields_.SetDescendantNeedsPaintPropertyUpdate(false);
+ layout_object_.bitfields_
+ .SetDescendantEffectiveAllowedTouchActionChanged(false);
+ layout_object_.bitfields_.ResetSubtreePaintPropertyUpdateReasons();
+ }
}
void SetShouldCheckForPaintInvalidation() {
layout_object_.SetShouldCheckForPaintInvalidation();
@@ -2386,7 +2396,7 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
bitfields_.SetOutlineMayBeAffectedByDescendants(b);
}
- bool LayoutBlockedByDisplayLock(
+ inline bool LayoutBlockedByDisplayLock(
DisplayLockContext::LifecycleTarget target) const {
auto* context = GetDisplayLockContext();
return context && !context->ShouldLayout(target);
@@ -2397,24 +2407,28 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
return context && context->IsLocked();
}
- bool PrePaintBlockedByDisplayLock() const {
+ bool PrePaintBlockedByDisplayLock(
+ DisplayLockContext::LifecycleTarget target) const {
auto* context = GetDisplayLockContext();
- return context && !context->ShouldPrePaint();
+ return context && !context->ShouldPrePaint(target);
}
- bool PaintBlockedByDisplayLock() const {
+ bool PaintBlockedByDisplayLock(
+ DisplayLockContext::LifecycleTarget target) const {
auto* context = GetDisplayLockContext();
- return context && !context->ShouldPaint();
+ return context && !context->ShouldPaint(target);
}
- void NotifyDisplayLockDidPrePaint() const {
+ void NotifyDisplayLockDidPrePaint(
+ DisplayLockContext::LifecycleTarget target) const {
if (auto* context = GetDisplayLockContext())
- context->DidPrePaint();
+ context->DidPrePaint(target);
}
- void NotifyDisplayLockDidPaint() const {
+ void NotifyDisplayLockDidPaint(
+ DisplayLockContext::LifecycleTarget target) const {
if (auto* context = GetDisplayLockContext())
- context->DidPaint();
+ context->DidPaint(target);
}
// This flag caches StyleRef().HasBorderDecoration() &&
@@ -2432,9 +2446,10 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
DisplayLockContext* GetDisplayLockContext() const {
if (!RuntimeEnabledFeatures::DisplayLockingEnabled())
return nullptr;
- if (!GetNode() || !GetNode()->IsElementNode())
+ auto* element = DynamicTo<Element>(GetNode());
+ if (!element)
return nullptr;
- return ToElement(GetNode())->GetDisplayLockContext();
+ return element->GetDisplayLockContext();
}
protected:
@@ -2517,7 +2532,7 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
// Updates only the local style ptr of the object. Does not update the state
// of the object, and so only should be called when the style is known not to
// have changed (or from SetStyle).
- void SetStyleInternal(scoped_refptr<ComputedStyle> style) {
+ void SetStyleInternal(scoped_refptr<const ComputedStyle> style) {
style_ = std::move(style);
}
// Overrides should call the superclass at the end. style_ will be 0 the
@@ -2574,7 +2589,10 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
#endif
// Called before paint invalidation.
- virtual void EnsureIsReadyForPaintInvalidation() { DCHECK(!NeedsLayout()); }
+ virtual void EnsureIsReadyForPaintInvalidation() {
+ DCHECK(!NeedsLayout() ||
+ LayoutBlockedByDisplayLock(DisplayLockContext::kChildren));
+ }
void SetIsBackgroundAttachmentFixedObject(bool);
@@ -2629,16 +2647,19 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
LayoutBlock* ContainingBlockForFixedPosition(
AncestorSkipInfo* = nullptr) const;
- private:
- // Used only by applyFirstLineChanges to get a first line style based off of a
- // given new style, without accessing the cache.
- scoped_refptr<const ComputedStyle> UncachedFirstLineStyle() const;
+ // Returns the first line style declared in CSS. The style may be declared on
+ // an ancestor block (see EnclosingFirstLineStyleBlock()) that applies to this
+ // object. Returns nullptr if there is no applicable first line style.
+ // Whether the style applies is based on CSS rules, regardless of whether this
+ // object is really in the first line which is unknown before layout.
+ const ComputedStyle* FirstLineStyleWithoutFallback() const;
+ private:
// Adjusts a visual rect in the space of |visual_rect| to be in the space of
// the |paint_invalidation_container|, if needed. They can be different only
// if |paint_invalidation_container| is a composited scroller.
void AdjustVisualRectForCompositedScrolling(
- IntRect& visual_rect,
+ LayoutRect& visual_rect,
const LayoutBoxModelObject& paint_invalidation_container) const;
FloatQuad LocalToAncestorQuadInternal(const FloatQuad&,
@@ -2679,7 +2700,6 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
LayoutFlowThread* LocateFlowThreadContainingBlock() const;
void RemoveFromLayoutFlowThreadRecursive(LayoutFlowThread*);
- const ComputedStyle* CachedFirstLineStyle() const;
StyleDifference AdjustStyleDifference(StyleDifference) const;
#if DCHECK_IS_ON()
@@ -2708,6 +2728,8 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
LayoutUnit width,
const LayoutBox* box_for_flipping) const;
+ void MarkSelfPaintingLayerForVisualOverflowRecalc();
+
// 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
@@ -2716,15 +2738,6 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
// DisplayItemClient and LayoutObject's other fields.
PaintInvalidationReason full_paint_invalidation_reason_;
- scoped_refptr<ComputedStyle> style_;
-
- // Oilpan: This untraced pointer to the owning Node is considered safe.
- UntracedMember<Node> node_;
-
- LayoutObject* parent_;
- LayoutObject* previous_;
- LayoutObject* next_;
-
#if DCHECK_IS_ON()
unsigned has_ax_object_ : 1;
unsigned set_needs_layout_forbidden_ : 1;
@@ -2828,7 +2841,6 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
descendant_effective_allowed_touch_action_changed_(false),
is_effective_root_scroller_(false),
is_global_root_scroller_(false),
- pending_update_first_line_image_observers_(false),
registered_as_first_line_image_observer_(false),
is_html_legend_element_(false),
has_non_collapsed_border_decoration_(false),
@@ -3078,11 +3090,6 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
ADD_BOOLEAN_BITFIELD(is_effective_root_scroller_, IsEffectiveRootScroller);
ADD_BOOLEAN_BITFIELD(is_global_root_scroller_, IsGlobalRootScroller);
- // First line style is resolvable only after the object is inserted into
- // the tree, so we should set this flag when the object set a style having
- // first line style before it is inserted into the tree.
- ADD_BOOLEAN_BITFIELD(pending_update_first_line_image_observers_,
- PendingUpdateFirstLineImageObservers);
// Indicates whether this object has been added as a first line image
// observer.
ADD_BOOLEAN_BITFIELD(registered_as_first_line_image_observer_,
@@ -3209,6 +3216,15 @@ class CORE_EXPORT LayoutObject : public ImageResourceObserver,
private:
friend class LineLayoutItem;
+ scoped_refptr<const ComputedStyle> style_;
+
+ // Oilpan: This untraced pointer to the owning Node is considered safe.
+ UntracedMember<Node> node_;
+
+ LayoutObject* parent_;
+ LayoutObject* previous_;
+ LayoutObject* next_;
+
// Store state between styleWillChange and styleDidChange
static bool affects_parent_block_;
@@ -3279,8 +3295,7 @@ inline void LayoutObject::SetNeedsLayoutAndFullPaintInvalidation(
SetShouldDoFullPaintInvalidation();
}
-inline void LayoutObject::ClearNeedsLayoutWithoutPaintInvalidation(
- bool clear_child_dirty_bits) {
+inline void LayoutObject::ClearNeedsLayoutWithoutPaintInvalidation() {
// Set flags for later stages/cycles.
SetEverHadLayout();
@@ -3290,10 +3305,19 @@ inline void LayoutObject::ClearNeedsLayoutWithoutPaintInvalidation(
SetNeedsPositionedMovementLayout(false);
SetAncestorLineBoxDirty(false);
- if (clear_child_dirty_bits) {
+ if (!LayoutBlockedByDisplayLock(DisplayLockContext::kChildren)) {
SetPosChildNeedsLayout(false);
SetNormalChildNeedsLayout(false);
SetNeedsSimplifiedNormalFlowLayout(false);
+ } else if (!PosChildNeedsLayout() && !NormalChildNeedsLayout() &&
+ !NeedsSimplifiedNormalFlowLayout()) {
+ // We aren't clearing the child dirty bits because the node is locked and
+ // layout for children is not done. If the children aren't dirty, we need
+ // to notify the display lock that child traversal was blocked so that when
+ // the subtree gets updated/unlocked we will traverse the children.
+ auto* context = GetDisplayLockContext();
+ DCHECK(context);
+ context->NotifyChildLayoutWasBlocked();
}
#if DCHECK_IS_ON()
@@ -3303,14 +3327,13 @@ inline void LayoutObject::ClearNeedsLayoutWithoutPaintInvalidation(
SetScrollAnchorDisablingStyleChanged(false);
}
-inline void LayoutObject::ClearNeedsLayout(bool clear_child_dirty_bits) {
- ClearNeedsLayoutWithoutPaintInvalidation(clear_child_dirty_bits);
+inline void LayoutObject::ClearNeedsLayout() {
+ ClearNeedsLayoutWithoutPaintInvalidation();
SetShouldCheckForPaintInvalidation();
}
-inline void LayoutObject::ClearNeedsLayoutWithFullPaintInvalidation(
- bool clear_child_dirty_bits) {
- ClearNeedsLayoutWithoutPaintInvalidation(clear_child_dirty_bits);
+inline void LayoutObject::ClearNeedsLayoutWithFullPaintInvalidation() {
+ ClearNeedsLayoutWithoutPaintInvalidation();
SetShouldDoFullPaintInvalidation();
}
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 1e3b8cf86a4..fb9db0a519e 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,6 +31,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_view.h"
+#include "third_party/blink/renderer/core/paint/ng/ng_paint_fragment.h"
#include "third_party/blink/renderer/core/paint/object_paint_invalidator.h"
namespace blink {
@@ -45,15 +46,8 @@ void InvalidateInlineItems(LayoutObject* object) {
DCHECK(object->IsInLayoutNGInlineFormattingContext());
if (auto* layout_text = ToLayoutTextOrNull(object)) {
- layout_text->SetFirstInlineFragment(nullptr);
layout_text->InvalidateInlineItems();
- layout_text->SetIsInLayoutNGInlineFormattingContext(false);
- return;
- }
-
- if (auto* layout_inline = ToLayoutInlineOrNull(object)) {
- layout_inline->SetFirstInlineFragment(nullptr);
-
+ } else if (auto* layout_inline = ToLayoutInlineOrNull(object)) {
// In some cases, only top-level objects are moved, when |SplitFlow()| moves
// subtree, or when moving without |notify_layout_object|. Ensure to
// invalidate all descendants in this inline formatting context.
@@ -62,11 +56,14 @@ void InvalidateInlineItems(LayoutObject* object) {
if (child->IsInLayoutNGInlineFormattingContext())
InvalidateInlineItems(child);
}
- layout_inline->SetIsInLayoutNGInlineFormattingContext(false);
- return;
}
- object->SetFirstInlineFragment(nullptr);
+ if (NGPaintFragment* fragment = object->FirstInlineFragment()) {
+ // This LayoutObject is not technically destroyed, but further access should
+ // be prohibited when moved to different parent as if it were destroyed.
+ fragment->LayoutObjectWillBeDestroyed();
+ object->SetFirstInlineFragment(nullptr);
+ }
object->SetIsInLayoutNGInlineFormattingContext(false);
}
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_object_factory.cc b/chromium/third_party/blink/renderer/core/layout/layout_object_factory.cc
index 22b83178ead..9b6024f0f83 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_object_factory.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_object_factory.cc
@@ -30,8 +30,8 @@ namespace blink {
namespace {
inline Element* GetElementForLayoutObject(Node& node) {
- if (node.IsElementNode())
- return &ToElement(node);
+ if (auto* element = DynamicTo<Element>(node))
+ return element;
// If |node| is a Document, the layout object is going to be anonymous.
DCHECK(node.IsDocumentNode());
return nullptr;
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_object_factory.h b/chromium/third_party/blink/renderer/core/layout/layout_object_factory.h
index 79ca3dd8b35..a9596a42359 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_object_factory.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_object_factory.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_LAYOUT_OBJECT_FACTORY_H_
#include "base/memory/scoped_refptr.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_object_inlines.h b/chromium/third_party/blink/renderer/core/layout/layout_object_inlines.h
index d5cb8e32545..e48a3548b03 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_object_inlines.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_object_inlines.h
@@ -16,9 +16,11 @@ namespace blink {
// these methods.
inline const ComputedStyle* LayoutObject::FirstLineStyle() const {
- return GetDocument().GetStyleEngine().UsesFirstLineRules()
- ? CachedFirstLineStyle()
- : Style();
+ if (GetDocument().GetStyleEngine().UsesFirstLineRules()) {
+ if (const ComputedStyle* first_line_style = FirstLineStyleWithoutFallback())
+ return first_line_style;
+ }
+ return Style();
}
inline const ComputedStyle& LayoutObject::FirstLineStyleRef() const {
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 e8b2a8debf4..61a6ebab391 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
@@ -58,7 +58,7 @@ TEST_F(LayoutObjectTest, LayoutDecoratedNameCalledWithPositionedObject) {
DCHECK(div);
LayoutObject* obj = div->GetLayoutObject();
DCHECK(obj);
- EXPECT_THAT(obj->DecoratedName().Ascii().data(),
+ EXPECT_THAT(obj->DecoratedName().Ascii(),
MatchesRegex("LayoutN?G?BlockFlow \\(positioned\\)"));
}
@@ -740,7 +740,7 @@ lime'>
StringBuilder result;
block->DumpLayoutObject(result, false, 0);
- EXPECT_THAT(result.ToString().Utf8().data(),
+ EXPECT_THAT(result.ToString().Utf8(),
MatchesRegex("LayoutN?G?BlockFlow\tDIV id=\"block\" "
"style=\"background:\\\\nlime\""));
@@ -1040,4 +1040,28 @@ TEST_F(LayoutObjectTest, FirstLineBackgroundImageAddBlockBackgroundImageCrash) {
UpdateAllLifecyclePhasesForTest();
}
+TEST_F(LayoutObjectTest, FirstLineBackgroundImageChangeStyleCrash) {
+ SetBodyInnerHTML(R"HTML(
+ <style id="style">
+ #target::first-line {
+ background-image: url(data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==);
+ }
+ </style>
+ <div id="target">Target</div>
+ )HTML");
+
+ // These should not crash.
+ GetDocument().getElementById("target")->setAttribute(html_names::kStyleAttr,
+ "color: blue");
+ UpdateAllLifecyclePhasesForTest();
+
+ GetDocument().getElementById("target")->setAttribute(html_names::kStyleAttr,
+ "display: none");
+ UpdateAllLifecyclePhasesForTest();
+
+ auto* style_element = GetDocument().getElementById("style");
+ style_element->setTextContent(style_element->textContent() + "dummy");
+ UpdateAllLifecyclePhasesForTest();
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_progress.cc b/chromium/third_party/blink/renderer/core/layout/layout_progress.cc
index ebc3235f0fc..85384a00dec 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_progress.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_progress.cc
@@ -61,7 +61,7 @@ void LayoutProgress::UpdateFromElement() {
double LayoutProgress::AnimationProgress() const {
if (!animating_)
return 0;
- TimeDelta elapsed = CurrentTimeTicks() - animation_start_time_;
+ base::TimeDelta elapsed = base::TimeTicks::Now() - animation_start_time_;
return (elapsed % animation_duration_).InSecondsF() /
animation_duration_.InSecondsF();
}
@@ -92,13 +92,13 @@ void LayoutProgress::UpdateAnimationState() {
LayoutTheme::GetTheme().AnimationRepeatIntervalForProgressBar();
bool animating = !IsDeterminate() && StyleRef().HasAppearance() &&
- animation_duration_ > TimeDelta();
+ animation_duration_ > base::TimeDelta();
if (animating == animating_)
return;
animating_ = animating;
if (animating_) {
- animation_start_time_ = CurrentTimeTicks();
+ animation_start_time_ = base::TimeTicks::Now();
animation_timer_.StartOneShot(animation_repeat_interval_, FROM_HERE);
} else {
animation_timer_.Stop();
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_progress.h b/chromium/third_party/blink/renderer/core/layout/layout_progress.h
index ab8a0cbd65f..7430461c998 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_progress.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_progress.h
@@ -58,9 +58,9 @@ class CORE_EXPORT LayoutProgress final : public LayoutBlockFlow {
void UpdateAnimationState();
double position_;
- TimeTicks animation_start_time_;
- TimeDelta animation_repeat_interval_;
- TimeDelta animation_duration_;
+ base::TimeTicks animation_start_time_;
+ base::TimeDelta animation_repeat_interval_;
+ base::TimeDelta animation_duration_;
bool animating_;
TaskRunnerTimer<LayoutProgress> animation_timer_;
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 a458d0d1ab9..5e0f03d51fa 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_quote.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_quote.cc
@@ -235,8 +235,8 @@ const QuotesData* QuotesDataForLanguage(const AtomicString& lang) {
// This could be just a hash table, but doing that adds 200k to LayoutQuote.o
Language* languages_end = g_languages + base::size(g_languages);
- CString lowercase_lang = lang.DeprecatedLower().Utf8();
- Language key = {lowercase_lang.data(), 0, 0, 0, 0, nullptr};
+ std::string lowercase_lang = lang.DeprecatedLower().Utf8();
+ Language key = {lowercase_lang.c_str(), 0, 0, 0, 0, nullptr};
Language* match = std::lower_bound(g_languages, languages_end, key);
if (match == languages_end || strcmp(match->lang, key.lang))
return nullptr;
@@ -267,14 +267,14 @@ void LayoutQuote::UpdateText() {
LayoutTextFragment* fragment = FindFragmentChild();
if (fragment) {
- fragment->SetStyle(MutableStyle());
+ fragment->SetStyle(Style());
fragment->SetContentString(text_.Impl());
} else {
LegacyLayout legacy =
ForceLegacyLayout() ? LegacyLayout::kForce : LegacyLayout::kAuto;
fragment = LayoutTextFragment::CreateAnonymous(*owning_pseudo_,
text_.Impl(), legacy);
- fragment->SetStyle(MutableStyle());
+ fragment->SetStyle(Style());
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 0117955744f..ca219039e58 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_replaced.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_replaced.cc
@@ -955,17 +955,19 @@ static std::pair<LayoutUnit, LayoutUnit> SelectionTopAndBottom(
}
PositionWithAffinity LayoutReplaced::PositionForPoint(
- const LayoutPoint& point) const {
+ const PhysicalOffset& point) const {
LayoutUnit top;
LayoutUnit bottom;
std::tie(top, bottom) = SelectionTopAndBottom(*this);
+ LayoutPoint flipped_point_in_container =
+ LocationContainer()->FlipForWritingMode(point + PhysicalLocation());
LayoutUnit block_direction_position = IsHorizontalWritingMode()
- ? point.Y() + Location().Y()
- : point.X() + Location().X();
+ ? flipped_point_in_container.Y()
+ : flipped_point_in_container.X();
LayoutUnit line_direction_position = IsHorizontalWritingMode()
- ? point.X() + Location().X()
- : point.Y() + Location().Y();
+ ? flipped_point_in_container.X()
+ : flipped_point_in_container.Y();
if (block_direction_position < top)
return CreatePositionWithAffinity(
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_replaced.h b/chromium/third_party/blink/renderer/core/layout/layout_replaced.h
index 8ced52668d3..a945fcf357b 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_replaced.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_replaced.h
@@ -99,6 +99,13 @@ class CORE_EXPORT LayoutReplaced : public LayoutBox {
// intrinsic size in LayoutNG.
virtual void ComputeIntrinsicSizingInfo(IntrinsicSizingInfo&) const;
+ // This callback is invoked whenever the intrinsic size changed.
+ //
+ // The intrinsic size can change due to the network (from the default
+ // intrinsic size [see above] to the actual intrinsic size) or to some
+ // CSS properties like 'zoom' or 'image-orientation'.
+ virtual void IntrinsicSizeChanged();
+
protected:
void WillBeDestroyed() override;
@@ -132,14 +139,7 @@ class CORE_EXPORT LayoutReplaced : public LayoutBox {
intrinsic_size_ = intrinsic_size;
}
- // This callback is invoked whenever the intrinsic size changed.
- //
- // The intrinsic size can change due to the network (from the default
- // intrinsic size [see above] to the actual intrinsic size) or to some
- // CSS properties like 'zoom' or 'image-orientation'.
- virtual void IntrinsicSizeChanged();
-
- PositionWithAffinity PositionForPoint(const LayoutPoint&) const override;
+ PositionWithAffinity PositionForPoint(const PhysicalOffset&) const override;
bool IsOfType(LayoutObjectType type) const override {
return type == kLayoutObjectLayoutReplaced || LayoutBox::IsOfType(type);
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_ruby.cc b/chromium/third_party/blink/renderer/core/layout/layout_ruby.cc
index a6e5a5abb75..b2fc1ef5706 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_ruby.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_ruby.cc
@@ -30,8 +30,8 @@
#include "third_party/blink/renderer/core/layout/layout_ruby.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/layout/layout_ruby_run.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
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 7a6de8c0564..e3ed83b0e4a 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
@@ -26,11 +26,11 @@
#include "third_party/blink/renderer/core/layout/layout_scrollbar_part.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/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/geometry/length_functions.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_scrollbar_theme.h b/chromium/third_party/blink/renderer/core/layout/layout_scrollbar_theme.h
index f158bb40eab..01595041193 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_scrollbar_theme.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_scrollbar_theme.h
@@ -60,11 +60,11 @@ class LayoutScrollbarTheme final : public ScrollbarTheme {
.ShouldSnapBackToDragOrigin(scrollbar, event);
}
- TimeDelta InitialAutoscrollTimerDelay() override {
+ base::TimeDelta InitialAutoscrollTimerDelay() override {
return ScrollbarTheme::DeprecatedStaticGetTheme()
.InitialAutoscrollTimerDelay();
}
- TimeDelta AutoscrollTimerDelay() override {
+ base::TimeDelta AutoscrollTimerDelay() override {
return ScrollbarTheme::DeprecatedStaticGetTheme().AutoscrollTimerDelay();
}
diff --git a/chromium/third_party/blink/renderer/core/layout/jank_region.cc b/chromium/third_party/blink/renderer/core/layout/layout_shift_region.cc
index 2625c798829..b43c354da99 100644
--- a/chromium/third_party/blink/renderer/core/layout/jank_region.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_shift_region.cc
@@ -2,7 +2,8 @@
// 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 "third_party/blink/renderer/core/layout/layout_shift_region.h"
+#include "third_party/blink/renderer/platform/wtf/hash_map.h"
namespace blink {
@@ -43,8 +44,13 @@ class BasicIntervals {
private:
Vector<int> endpoints_;
- // Avoid WTF::HashMap as key may be 0 or -1.
- std::unordered_map<int, unsigned> endpoint_to_index_;
+ // Use int64_t which is larger than real |int| since the empty value of the
+ // key is max and deleted value of the key is max - 1 in HashMap.
+ HashMap<int64_t,
+ unsigned,
+ WTF::IntHash<int64_t>,
+ WTF::UnsignedWithZeroKeyHashTraits<int64_t>>
+ endpoint_to_index_;
#if DCHECK_IS_ON()
bool has_index_ = false;
@@ -61,8 +67,8 @@ 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)
+ auto ret = endpoint_to_index_.insert(endpoint, 0u);
+ if (ret.is_new_entry)
endpoints_.push_back(endpoint);
}
@@ -71,7 +77,7 @@ void BasicIntervals::CreateIndex() {
std::sort(endpoints_.begin(), endpoints_.end());
unsigned i = 0;
for (const int& e : endpoints_)
- endpoint_to_index_[e] = i++;
+ endpoint_to_index_.Set(e, i++);
#if DCHECK_IS_ON()
has_index_ = true;
@@ -302,7 +308,7 @@ uint64_t Sweeper::SweepImpl(SegmentTree& tree,
} // namespace
-uint64_t JankRegion::Area() const {
+uint64_t LayoutShiftRegion::Area() const {
if (rects_.IsEmpty())
return 0;
diff --git a/chromium/third_party/blink/renderer/core/layout/jank_region.h b/chromium/third_party/blink/renderer/core/layout/layout_shift_region.h
index 804861cbdc5..78a774bb64c 100644
--- a/chromium/third_party/blink/renderer/core/layout/jank_region.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_shift_region.h
@@ -2,23 +2,23 @@
// 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_
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_LAYOUT_SHIFT_REGION_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_LAYOUT_SHIFT_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/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.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.
+// Represents a per-frame layout shift region for LayoutShiftTracker. 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.
+// where n is the number of rects recorded by AddRect. For complex layout shift
+// 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
@@ -26,14 +26,14 @@ namespace blink {
// 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:
+// The sweep line's current intersection with the layout shift 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 {
+class CORE_EXPORT LayoutShiftRegion {
DISALLOW_NEW();
public:
@@ -54,4 +54,4 @@ class CORE_EXPORT JankRegion {
} // namespace blink
-#endif // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_JANK_REGION_H_
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_LAYOUT_SHIFT_REGION_H_
diff --git a/chromium/third_party/blink/renderer/core/layout/jank_region_test.cc b/chromium/third_party/blink/renderer/core/layout/layout_shift_region_test.cc
index a688fec0592..fe1cf3b8b1d 100644
--- a/chromium/third_party/blink/renderer/core/layout/jank_region_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_shift_region_test.cc
@@ -2,17 +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/layout/jank_region.h"
+#include "third_party/blink/renderer/core/layout/layout_shift_region.h"
#include <gtest/gtest.h>
#include "third_party/blink/renderer/platform/geometry/region.h"
namespace blink {
-class JankRegionTest : public testing::Test {};
+class LayoutShiftRegionTest : public testing::Test {};
-TEST_F(JankRegionTest, Basic) {
- JankRegion region;
+TEST_F(LayoutShiftRegionTest, Basic) {
+ LayoutShiftRegion region;
EXPECT_EQ(0u, region.Area());
region.AddRect(IntRect(2, 1, 1, 3));
@@ -43,8 +43,8 @@ TEST_F(JankRegionTest, Basic) {
EXPECT_EQ(0u, region.Area());
}
-TEST_F(JankRegionTest, LargeRandom) {
- JankRegion region;
+TEST_F(LayoutShiftRegionTest, LargeRandom) {
+ LayoutShiftRegion region;
Region naive_region;
static const int data[] = {
52613, 38528, 20785, 40550, 29734, 48229, 37113, 3520, 66776, 26746,
@@ -107,8 +107,8 @@ TEST_F(JankRegionTest, LargeRandom) {
// █ █ █
// ███████
// █ █ █
-TEST_F(JankRegionTest, Waffle) {
- JankRegion region;
+TEST_F(LayoutShiftRegionTest, Waffle) {
+ LayoutShiftRegion region;
unsigned n = 250000;
for (unsigned i = 2; i <= n; i += 2) {
region.AddRect(IntRect(i, 1, 1, n + 1));
diff --git a/chromium/third_party/blink/renderer/core/layout/jank_tracker.cc b/chromium/third_party/blink/renderer/core/layout/layout_shift_tracker.cc
index 3d9f8ddd287..5c3b039122a 100644
--- a/chromium/third_party/blink/renderer/core/layout/jank_tracker.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_shift_tracker.cc
@@ -2,10 +2,11 @@
// 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_tracker.h"
+#include "third_party/blink/renderer/core/layout/layout_shift_tracker.h"
#include "cc/layers/heads_up_display_layer.h"
#include "cc/layers/picture_layer.h"
+#include "third_party/blink/public/platform/web_pointer_event.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"
@@ -25,8 +26,11 @@
namespace blink {
-static constexpr TimeDelta kTimerDelay = TimeDelta::FromMilliseconds(500);
+static constexpr base::TimeDelta kTimerDelay =
+ base::TimeDelta::FromMilliseconds(500);
static const float kRegionGranularitySteps = 60.0;
+// TODO: Vary by Finch experiment parameter.
+static const float kSweepLineRegionGranularity = 1.0;
static const float kMovementThreshold = 3.0; // CSS pixels.
static FloatPoint LogicalStart(const FloatRect& rect,
@@ -47,9 +51,10 @@ static float GetMoveDistance(const FloatRect& old_rect,
return std::max(fabs(location_delta.Width()), fabs(location_delta.Height()));
}
-static float RegionGranularityScale(const IntRect& viewport) {
+float LayoutShiftTracker::RegionGranularityScale(
+ const IntRect& viewport) const {
if (RuntimeEnabledFeatures::JankTrackingSweepLineEnabled())
- return 1;
+ return kSweepLineRegionGranularity;
return kRegionGranularitySteps /
std::min(viewport.Height(), viewport.Width());
@@ -90,7 +95,7 @@ static void RegionToTracedValue(const Region& region,
value.EndArray();
}
-static void RegionToTracedValue(const JankRegion& region,
+static void RegionToTracedValue(const LayoutShiftRegion& region,
double granularity_scale,
TracedValue& value) {
Region old_region;
@@ -101,26 +106,28 @@ static void RegionToTracedValue(const JankRegion& region,
#if DCHECK_IS_ON()
static bool ShouldLog(const LocalFrame& frame) {
- return !frame.GetDocument()->Url().GetString().StartsWith("chrome-devtools:");
+ const String& url = frame.GetDocument()->Url().GetString();
+ return !url.StartsWith("chrome-devtools:") && !url.StartsWith("devtools:");
}
#endif
-JankTracker::JankTracker(LocalFrameView* frame_view)
+LayoutShiftTracker::LayoutShiftTracker(LocalFrameView* frame_view)
: frame_view_(frame_view),
score_(0.0),
- score_with_move_distance_(0.0),
weighted_score_(0.0),
timer_(frame_view->GetFrame().GetTaskRunner(TaskType::kInternalDefault),
this,
- &JankTracker::TimerFired),
+ &LayoutShiftTracker::TimerFired),
frame_max_distance_(0.0),
overall_max_distance_(0.0),
- observed_input_or_scroll_(false) {}
+ observed_input_or_scroll_(false),
+ most_recent_input_timestamp_initialized_(false) {}
-void JankTracker::AccumulateJank(const LayoutObject& source,
- const PropertyTreeState& property_tree_state,
- FloatRect old_rect,
- FloatRect new_rect) {
+void LayoutShiftTracker::ObjectShifted(
+ const LayoutObject& source,
+ const PropertyTreeState& property_tree_state,
+ FloatRect old_rect,
+ FloatRect new_rect) {
if (old_rect.IsEmpty() || new_rect.IsEmpty())
return;
@@ -139,7 +146,7 @@ void JankTracker::AccumulateJank(const LayoutObject& source,
// Ignore layout objects that move (in the coordinate space of the paint
// invalidation container) on scroll.
- // TODO(skobes): Find a way to detect when these objects jank.
+ // TODO(skobes): Find a way to detect when these objects shift.
if (source.IsFixedPositioned() || source.IsStickyPositioned())
return;
@@ -163,6 +170,19 @@ void JankTracker::AccumulateJank(const LayoutObject& source,
GeometryMapper::SourceToDestinationRect(property_tree_state.Transform(),
root_state.Transform(), new_rect);
+ if (EqualWithinMovementThreshold(old_rect.Location(), new_rect.Location(),
+ source)) {
+ return;
+ }
+
+ if (EqualWithinMovementThreshold(old_rect.Location() + frame_scroll_delta_,
+ new_rect.Location(), source)) {
+ // TODO(skobes): Checking frame_scroll_delta_ is an imperfect solution to
+ // allowing counterscrolled layout shifts. Ideally, we would map old_rect
+ // to viewport coordinates using the previous frame's scroll tree.
+ return;
+ }
+
FloatRect clipped_old_rect(old_rect), clipped_new_rect(new_rect);
if (!clip_rect.IsInfinite()) {
clipped_old_rect.Intersect(clip_rect.Rect());
@@ -206,7 +226,7 @@ void JankTracker::AccumulateJank(const LayoutObject& source,
}
}
-void JankTracker::NotifyObjectPrePaint(
+void LayoutShiftTracker::NotifyObjectPrePaint(
const LayoutObject& object,
const PropertyTreeState& property_tree_state,
const IntRect& old_visual_rect,
@@ -214,13 +234,14 @@ void JankTracker::NotifyObjectPrePaint(
if (!IsActive())
return;
- AccumulateJank(object, property_tree_state, FloatRect(old_visual_rect),
- FloatRect(new_visual_rect));
+ ObjectShifted(object, property_tree_state, FloatRect(old_visual_rect),
+ FloatRect(new_visual_rect));
}
-void JankTracker::NotifyCompositedLayerMoved(const LayoutObject& layout_object,
- FloatRect old_layer_rect,
- FloatRect new_layer_rect) {
+void LayoutShiftTracker::NotifyCompositedLayerMoved(
+ const LayoutObject& layout_object,
+ FloatRect old_layer_rect,
+ FloatRect new_layer_rect) {
if (!IsActive())
return;
@@ -228,11 +249,11 @@ void JankTracker::NotifyCompositedLayerMoved(const LayoutObject& layout_object,
if (!layout_object.FirstFragment().HasLocalBorderBoxProperties())
return;
- AccumulateJank(layout_object, PropertyTreeStateFor(layout_object),
- old_layer_rect, new_layer_rect);
+ ObjectShifted(layout_object, PropertyTreeStateFor(layout_object),
+ old_layer_rect, new_layer_rect);
}
-double JankTracker::SubframeWeightingFactor() const {
+double LayoutShiftTracker::SubframeWeightingFactor() const {
LocalFrame& frame = frame_view_->GetFrame();
if (frame.IsMainFrame())
return 1;
@@ -248,8 +269,6 @@ double JankTracker::SubframeWeightingFactor() const {
// Intersect with the portion of the local root that overlaps the main frame.
frame.LocalFrameRoot().View()->MapToVisualRectInTopFrameSpace(subframe_rect);
IntSize subframe_visible_size = subframe_rect.PixelSnappedSize();
-
- // TODO(crbug.com/939050): This does not update on window resize.
IntSize main_frame_size = frame.GetPage()->GetVisualViewport().Size();
// TODO(crbug.com/940711): This comparison ignores page scale and CSS
@@ -258,7 +277,7 @@ double JankTracker::SubframeWeightingFactor() const {
main_frame_size.Area();
}
-void JankTracker::NotifyPrePaintFinished() {
+void LayoutShiftTracker::NotifyPrePaintFinished() {
if (!IsActive())
return;
bool use_sweep_line = RuntimeEnabledFeatures::JankTrackingSweepLineEnabled();
@@ -268,19 +287,19 @@ void JankTracker::NotifyPrePaintFinished() {
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());
+ double granularity_scale = RegionGranularityScale(viewport);
+ IntRect scaled_viewport = viewport;
+ scaled_viewport.Scale(granularity_scale);
+
+ double viewport_area =
+ double(scaled_viewport.Width()) * double(scaled_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);
-
- score_ += jank_fraction;
+ double impact_fraction = region_area / viewport_area;
+ DCHECK_GT(impact_fraction, 0);
DCHECK_GT(frame_max_distance_, 0.0);
double viewport_max_dimension = std::max(viewport.Width(), viewport.Height());
@@ -288,138 +307,183 @@ void JankTracker::NotifyPrePaintFinished() {
(frame_max_distance_ < viewport_max_dimension)
? double(frame_max_distance_) / viewport_max_dimension
: 1.0;
- double jank_fraction_with_move_distance =
- jank_fraction * move_distance_factor;
-
- score_with_move_distance_ += jank_fraction_with_move_distance;
+ double score_delta = impact_fraction * move_distance_factor;
+ double weighted_score_delta = score_delta * SubframeWeightingFactor();
overall_max_distance_ = std::max(overall_max_distance_, frame_max_distance_);
- LocalFrame& frame = frame_view_->GetFrame();
#if DCHECK_IS_ON()
+ LocalFrame& frame = frame_view_->GetFrame();
if (ShouldLog(frame)) {
DVLOG(1) << "in " << (frame.IsMainFrame() ? "" : "subframe ")
<< frame.GetDocument()->Url().GetString() << ", viewport was "
- << (jank_fraction * 100) << "% janked; raising score to "
- << score_;
+ << (impact_fraction * 100) << "% impacted with distance fraction "
+ << move_distance_factor;
}
#endif
- TRACE_EVENT_INSTANT2(
- "loading", "LayoutShift", TRACE_EVENT_SCOPE_THREAD, "data",
- PerFrameTraceData(jank_fraction, jank_fraction_with_move_distance,
- granularity_scale),
- "frame", ToTraceValue(&frame));
-
- double weighted_jank_fraction = jank_fraction * SubframeWeightingFactor();
- if (weighted_jank_fraction > 0) {
- weighted_score_ += weighted_jank_fraction;
- if (RuntimeEnabledFeatures::LayoutInstabilityMoveDistanceEnabled())
- weighted_jank_fraction *= move_distance_factor;
- frame.Client()->DidObserveLayoutJank(weighted_jank_fraction,
- observed_input_or_scroll_);
- }
-
- if (RuntimeEnabledFeatures::LayoutInstabilityAPIEnabled(
- frame.GetDocument()) &&
- frame.DomWindow()) {
- WindowPerformance* performance =
- DOMWindowPerformance::performance(*frame.DomWindow());
- if (performance &&
- (performance->HasObserverFor(PerformanceEntry::kLayoutJank) ||
- performance->ShouldBufferEntries())) {
- performance->AddLayoutJankFraction(
- RuntimeEnabledFeatures::LayoutInstabilityMoveDistanceEnabled()
- ? jank_fraction_with_move_distance
- : jank_fraction);
- }
+ if (pointerdown_pending_data_.saw_pointerdown) {
+ pointerdown_pending_data_.score_delta += score_delta;
+ pointerdown_pending_data_.weighted_score_delta += weighted_score_delta;
+ } else {
+ ReportShift(score_delta, weighted_score_delta);
}
if (use_sweep_line) {
if (!region_experimental_.IsEmpty()) {
- SetLayoutShiftRects(region_experimental_.GetRects(), 1);
+ SetLayoutShiftRects(region_experimental_.GetRects(), 1, true);
}
region_experimental_.Reset();
} else {
if (!region_.IsEmpty()) {
- SetLayoutShiftRects(region_.Rects(), granularity_scale);
+ SetLayoutShiftRects(region_.Rects(), granularity_scale, false);
}
region_ = Region();
}
frame_max_distance_ = 0.0;
+ frame_scroll_delta_ = ScrollOffset();
}
-void JankTracker::NotifyInput(const WebInputEvent& event) {
- bool event_is_meaningful =
- event.GetType() == WebInputEvent::kMouseDown ||
- event.GetType() == WebInputEvent::kKeyDown ||
- event.GetType() == WebInputEvent::kRawKeyDown ||
+void LayoutShiftTracker::ReportShift(double score_delta,
+ double weighted_score_delta) {
+ LocalFrame& frame = frame_view_->GetFrame();
+ bool had_recent_input = timer_.IsActive();
+
+ if (!had_recent_input) {
+ score_ += score_delta;
+ if (weighted_score_delta > 0) {
+ weighted_score_ += weighted_score_delta;
+ frame.Client()->DidObserveLayoutShift(weighted_score_delta,
+ observed_input_or_scroll_);
+ }
+ }
+
+ if (RuntimeEnabledFeatures::LayoutInstabilityAPIEnabled(
+ frame.GetDocument()) &&
+ frame.DomWindow()) {
+ WindowPerformance* performance =
+ DOMWindowPerformance::performance(*frame.DomWindow());
+ if (performance) {
+ performance->AddLayoutJankFraction(score_delta, had_recent_input,
+ most_recent_input_timestamp_);
+ }
+ }
+
+ TRACE_EVENT_INSTANT2("loading", "LayoutShift", TRACE_EVENT_SCOPE_THREAD,
+ "data", PerFrameTraceData(score_delta, had_recent_input),
+ "frame", ToTraceValue(&frame));
+
+#if DCHECK_IS_ON()
+ if (ShouldLog(frame)) {
+ DVLOG(1) << "in " << (frame.IsMainFrame() ? "" : "subframe ")
+ << frame.GetDocument()->Url().GetString() << ", layout shift of "
+ << score_delta
+ << (had_recent_input ? " excluded by recent input" : " reported")
+ << "; cumulative score is " << score_;
+ }
+#endif
+}
+
+void LayoutShiftTracker::NotifyInput(const WebInputEvent& event) {
+ const WebInputEvent::Type type = event.GetType();
+ const bool saw_pointerdown = pointerdown_pending_data_.saw_pointerdown;
+ const bool pointerdown_became_tap =
+ saw_pointerdown && type == WebInputEvent::kPointerUp;
+ const bool event_type_stops_pointerdown_buffering =
+ type == WebInputEvent::kPointerUp ||
+ type == WebInputEvent::kPointerCausedUaAction ||
+ type == WebInputEvent::kPointerCancel;
+
+ // Only non-hovering pointerdown requires buffering.
+ const bool is_hovering_pointerdown =
+ type == WebInputEvent::kPointerDown &&
+ static_cast<const WebPointerEvent&>(event).hovering;
+
+ const bool should_trigger_shift_exclusion =
+ type == WebInputEvent::kMouseDown || type == WebInputEvent::kKeyDown ||
+ type == WebInputEvent::kRawKeyDown ||
// We need to explicitly include tap, as if there are no listeners, we
// won't receive the pointer events.
- event.GetType() == WebInputEvent::kGestureTap ||
- // Ignore kPointerDown, since it might be a scroll.
- event.GetType() == WebInputEvent::kPointerUp;
+ type == WebInputEvent::kGestureTap || is_hovering_pointerdown ||
+ pointerdown_became_tap;
- if (!event_is_meaningful)
- return;
+ if (should_trigger_shift_exclusion) {
+ observed_input_or_scroll_ = true;
- observed_input_or_scroll_ = true;
+ // This cancels any previously scheduled task from the same timer.
+ timer_.StartOneShot(kTimerDelay, FROM_HERE);
+ UpdateInputTimestamp(event.TimeStamp());
+ }
- // This cancels any previously scheduled task from the same timer.
- timer_.StartOneShot(kTimerDelay, FROM_HERE);
+ if (saw_pointerdown && event_type_stops_pointerdown_buffering) {
+ double score_delta = pointerdown_pending_data_.score_delta;
+ if (score_delta > 0)
+ ReportShift(score_delta, pointerdown_pending_data_.weighted_score_delta);
+ pointerdown_pending_data_ = PointerdownPendingData();
+ }
+ if (type == WebInputEvent::kPointerDown && !is_hovering_pointerdown)
+ pointerdown_pending_data_.saw_pointerdown = true;
}
-void JankTracker::NotifyScroll(ScrollType scroll_type) {
- // Only include user-initiated scrolls. Ignore scrolls due to e.g. hash
- // fragment navigations.
- if (scroll_type != kUserScroll && scroll_type != kCompositorScroll)
- return;
+void LayoutShiftTracker::UpdateInputTimestamp(base::TimeTicks timestamp) {
+ if (!most_recent_input_timestamp_initialized_) {
+ most_recent_input_timestamp_ = timestamp;
+ most_recent_input_timestamp_initialized_ = true;
+ } else if (timestamp > most_recent_input_timestamp_) {
+ most_recent_input_timestamp_ = timestamp;
+ }
+}
- observed_input_or_scroll_ = true;
+void LayoutShiftTracker::NotifyScroll(ScrollType scroll_type,
+ ScrollOffset delta) {
+ frame_scroll_delta_ += delta;
+
+ // Only set observed_input_or_scroll_ for user-initiated scrolls, and not
+ // other scrolls such as hash fragment navigations.
+ if (scroll_type == kUserScroll || scroll_type == kCompositorScroll)
+ observed_input_or_scroll_ = true;
}
-void JankTracker::NotifyViewportSizeChanged() {
+void LayoutShiftTracker::NotifyViewportSizeChanged() {
// This cancels any previously scheduled task from the same timer.
timer_.StartOneShot(kTimerDelay, FROM_HERE);
+ UpdateInputTimestamp(base::TimeTicks::Now());
}
-bool JankTracker::IsActive() {
+bool LayoutShiftTracker::IsActive() {
// This eliminates noise from the private Page object created by
// SVGImage::DataChanged.
if (frame_view_->GetFrame().GetChromeClient().IsSVGImageChromeClient())
return false;
-
- if (timer_.IsActive())
- return false;
-
return true;
}
-std::unique_ptr<TracedValue> JankTracker::PerFrameTraceData(
- double jank_fraction,
- double jank_fraction_with_move_distance,
- double granularity_scale) const {
+std::unique_ptr<TracedValue> LayoutShiftTracker::PerFrameTraceData(
+ double score_delta,
+ bool input_detected) const {
auto value = std::make_unique<TracedValue>();
- value->SetDouble("score", jank_fraction);
- value->SetDouble("score_with_move_distance",
- jank_fraction_with_move_distance);
+ value->SetDouble("score", score_delta);
value->SetDouble("cumulative_score", score_);
- value->SetDouble("cumulative_score_with_move_distance",
- score_with_move_distance_);
value->SetDouble("overall_max_distance", overall_max_distance_);
value->SetDouble("frame_max_distance", frame_max_distance_);
+
+ float granularity_scale = RegionGranularityScale(
+ IntRect(IntPoint(),
+ frame_view_->GetScrollableArea()->VisibleContentRect().Size()));
if (RuntimeEnabledFeatures::JankTrackingSweepLineEnabled())
RegionToTracedValue(region_experimental_, granularity_scale, *value);
else
RegionToTracedValue(region_, granularity_scale, *value);
+
value->SetBoolean("is_main_frame", frame_view_->GetFrame().IsMainFrame());
+ value->SetBoolean("had_recent_input", input_detected);
return value;
}
-std::vector<gfx::Rect> JankTracker::ConvertIntRectsToGfxRects(
+WebVector<gfx::Rect> LayoutShiftTracker::ConvertIntRectsToGfxRects(
const Vector<IntRect>& int_rects,
double granularity_scale) {
- std::vector<gfx::Rect> rects;
+ WebVector<gfx::Rect> rects;
for (const IntRect& rect : int_rects) {
gfx::Rect r = gfx::Rect(
rect.X() / granularity_scale, rect.Y() / granularity_scale,
@@ -429,8 +493,9 @@ std::vector<gfx::Rect> JankTracker::ConvertIntRectsToGfxRects(
return rects;
}
-void JankTracker::SetLayoutShiftRects(const Vector<IntRect>& int_rects,
- double granularity_scale) {
+void LayoutShiftTracker::SetLayoutShiftRects(const Vector<IntRect>& int_rects,
+ double granularity_scale,
+ bool using_sweep_line) {
// Store the layout shift rects in the HUD layer.
GraphicsLayer* root_graphics_layer =
frame_view_->GetLayoutView()->Compositor()->RootGraphicsLayer();
@@ -444,9 +509,18 @@ void JankTracker::SetLayoutShiftRects(const Vector<IntRect>& int_rects,
if (!cc_layer->layer_tree_host()->GetDebugState().show_layout_shift_regions)
return;
if (cc_layer->layer_tree_host()->hud_layer()) {
- std::vector<gfx::Rect> rects =
- ConvertIntRectsToGfxRects(int_rects, granularity_scale);
- cc_layer->layer_tree_host()->hud_layer()->SetLayoutShiftRects(rects);
+ WebVector<gfx::Rect> rects;
+ if (using_sweep_line) {
+ Region old_region;
+ for (IntRect rect : int_rects)
+ old_region.Unite(Region(rect));
+ rects =
+ ConvertIntRectsToGfxRects(old_region.Rects(), granularity_scale);
+ } else {
+ rects = ConvertIntRectsToGfxRects(int_rects, granularity_scale);
+ }
+ cc_layer->layer_tree_host()->hud_layer()->SetLayoutShiftRects(
+ rects.ReleaseVector());
cc_layer->layer_tree_host()->hud_layer()->SetNeedsPushProperties();
}
}
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_shift_tracker.h b/chromium/third_party/blink/renderer/core/layout/layout_shift_tracker.h
new file mode 100644
index 00000000000..d095b646980
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/layout/layout_shift_tracker.h
@@ -0,0 +1,139 @@
+// Copyright 2018 The Chromium 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_LAYOUT_SHIFT_TRACKER_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_LAYOUT_SHIFT_TRACKER_H_
+
+#include "third_party/blink/public/platform/web_vector.h"
+#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/layout/layout_shift_region.h"
+#include "third_party/blink/renderer/core/scroll/scroll_types.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/allocator.h"
+
+namespace blink {
+
+class IntRect;
+class LayoutObject;
+class LocalFrameView;
+class PropertyTreeState;
+class TracedValue;
+class WebInputEvent;
+
+// Tracks "layout shifts" from layout objects changing their visual location
+// between animation frames. See https://github.com/WICG/layout-instability.
+class CORE_EXPORT LayoutShiftTracker {
+ USING_FAST_MALLOC(LayoutShiftTracker);
+
+ public:
+ LayoutShiftTracker(LocalFrameView*);
+ ~LayoutShiftTracker() {}
+ void NotifyObjectPrePaint(const LayoutObject& object,
+ const PropertyTreeState& property_tree_state,
+ const IntRect& old_visual_rect,
+ const IntRect& new_visual_rect);
+ // Layer rects are relative to old layer position.
+ void NotifyCompositedLayerMoved(const LayoutObject& object,
+ FloatRect old_layer_rect,
+ FloatRect new_layer_rect);
+ void NotifyPrePaintFinished();
+ void NotifyInput(const WebInputEvent&);
+ void NotifyScroll(ScrollType, ScrollOffset delta);
+ void NotifyViewportSizeChanged();
+ bool IsActive();
+ double Score() const { return score_; }
+ double WeightedScore() const { return weighted_score_; }
+ float OverallMaxDistance() const { return overall_max_distance_; }
+ bool ObservedInputOrScroll() const { return observed_input_or_scroll_; }
+ void Dispose() { timer_.Stop(); }
+ base::TimeTicks MostRecentInputTimestamp() {
+ return most_recent_input_timestamp_;
+ }
+
+ private:
+ void ObjectShifted(const LayoutObject&,
+ const PropertyTreeState&,
+ FloatRect old_rect,
+ FloatRect new_rect);
+ void ReportShift(double score_delta, double weighted_score_delta);
+ void TimerFired(TimerBase*) {}
+ std::unique_ptr<TracedValue> PerFrameTraceData(double score_delta,
+ bool input_detected) const;
+ float RegionGranularityScale(const IntRect& viewport) const;
+ double SubframeWeightingFactor() const;
+ WebVector<gfx::Rect> ConvertIntRectsToGfxRects(
+ const Vector<IntRect>& int_rects,
+ double granularity_scale);
+ void SetLayoutShiftRects(const Vector<IntRect>& int_rects,
+ double granularity_scale,
+ bool using_sweep_line);
+ void UpdateInputTimestamp(base::TimeTicks timestamp);
+
+ // This owns us.
+ UntracedMember<LocalFrameView> frame_view_;
+
+ // The document cumulative layout shift (DCLS) score for this LocalFrame,
+ // unweighted, with move distance applied.
+ double score_;
+
+ // The cumulative layout shift score for this LocalFrame, with each increase
+ // weighted by the extent to which the LocalFrame visibly occupied the main
+ // frame at the time the shift occurred, e.g. x0.5 if the subframe occupied
+ // half of the main frame's reported size; see SubframeWeightingFactor().
+ double weighted_score_;
+
+ // Stores information related to buffering layout shifts after pointerdown.
+ // We accumulate score deltas in this object until we know whether the
+ // pointerdown should be treated as a tap (triggering layout shift exclusion)
+ // or a scroll (not triggering layout shift exclusion). Once the correct
+ // treatment is known, the pending layout shifts are reported appropriately
+ // and the PointerdownPendingData object is reset.
+ struct PointerdownPendingData {
+ PointerdownPendingData()
+ : saw_pointerdown(false), score_delta(0), weighted_score_delta(0) {}
+ bool saw_pointerdown;
+ double score_delta;
+ double weighted_score_delta;
+ };
+
+ PointerdownPendingData pointerdown_pending_data_;
+
+ // The per-animation-frame impact region.
+ Region region_;
+
+ // Experimental impact region implementation using sweep-line algorithm.
+ LayoutShiftRegion region_experimental_;
+
+ // Tracks the short period after an input event during which we ignore shifts
+ // for the purpose of cumulative scoring, and report them to the web perf API
+ // with hadRecentInput == true.
+ TaskRunnerTimer<LayoutShiftTracker> timer_;
+
+ // The maximum distance any layout object has moved in the current animation
+ // frame.
+ float frame_max_distance_;
+
+ // The maximum distance any layout object has moved, across all animation
+ // frames.
+ float overall_max_distance_;
+
+ // Sum of all scroll deltas that occurred in the current animation frame.
+ ScrollOffset frame_scroll_delta_;
+
+ // Whether either a user input or document scroll have been observed during
+ // the session. (This is only tracked so UkmPageLoadMetricsObserver to report
+ // LayoutInstability.CumulativeShiftScore.MainFrame.BeforeInputOrScroll. It's
+ // not related to input exclusion or the LayoutShift::had_recent_input_ bit.)
+ bool observed_input_or_scroll_;
+
+ // Most recent timestamp of a user input event that has been observed.
+ // User input includes window resizing but not scrolling.
+ base::TimeTicks most_recent_input_timestamp_;
+ bool most_recent_input_timestamp_initialized_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_LAYOUT_SHIFT_TRACKER_H_
diff --git a/chromium/third_party/blink/renderer/core/layout/jank_tracker_test.cc b/chromium/third_party/blink/renderer/core/layout/layout_shift_tracker_test.cc
index a43e243332c..88d8613823f 100644
--- a/chromium/third_party/blink/renderer/core/layout/jank_tracker_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_shift_tracker_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/core/layout/jank_tracker.h"
+#include "third_party/blink/renderer/core/layout/layout_shift_tracker.h"
#include "third_party/blink/public/platform/web_mouse_event.h"
#include "third_party/blink/renderer/core/frame/web_local_frame_impl.h"
@@ -10,24 +10,29 @@
#include "third_party/blink/renderer/core/testing/core_unit_test_helper.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/core/timing/dom_window_performance.h"
+#include "third_party/blink/renderer/core/timing/layout_shift.h"
+#include "third_party/blink/renderer/core/timing/window_performance.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
namespace blink {
-class JankTrackerTest : public RenderingTest {
+class LayoutShiftTrackerTest : public RenderingTest {
protected:
void SetUp() override {
- RenderingTest::SetUp();
EnableCompositing();
+ RenderingTest::SetUp();
}
LocalFrameView& GetFrameView() { return *GetFrame().View(); }
- JankTracker& GetJankTracker() { return GetFrameView().GetJankTracker(); }
+ LayoutShiftTracker& GetLayoutShiftTracker() {
+ return GetFrameView().GetLayoutShiftTracker();
+ }
void SimulateInput() {
- GetJankTracker().NotifyInput(WebMouseEvent(
+ GetLayoutShiftTracker().NotifyInput(WebMouseEvent(
WebInputEvent::kMouseDown, WebFloatPoint(), WebFloatPoint(),
WebPointerProperties::Button::kLeft, 0,
- WebInputEvent::Modifiers::kLeftButtonDown, CurrentTimeTicks()));
+ WebInputEvent::Modifiers::kLeftButtonDown, base::TimeTicks::Now()));
}
void UpdateAllLifecyclePhases() {
@@ -36,7 +41,7 @@ class JankTrackerTest : public RenderingTest {
}
};
-TEST_F(JankTrackerTest, SimpleBlockMovement) {
+TEST_F(LayoutShiftTrackerTest, SimpleBlockMovement) {
SetBodyInnerHTML(R"HTML(
<style>
#j { position: relative; width: 300px; height: 100px; }
@@ -44,22 +49,18 @@ TEST_F(JankTrackerTest, SimpleBlockMovement) {
<div id='j'></div>
)HTML");
- EXPECT_EQ(0.0, GetJankTracker().Score());
- EXPECT_EQ(0.0, GetJankTracker().OverallMaxDistance());
+ EXPECT_EQ(0.0, GetLayoutShiftTracker().Score());
+ EXPECT_EQ(0.0, GetLayoutShiftTracker().OverallMaxDistance());
GetDocument().getElementById("j")->setAttribute(html_names::kStyleAttr,
AtomicString("top: 60px"));
UpdateAllLifecyclePhases();
- // 300 * (100 + 60) / (default viewport size 800 * 600)
- EXPECT_FLOAT_EQ(0.1, GetJankTracker().Score());
- // ScoreWithMoveDistance should be scaled by the amount that the content moved
- // (60px) relative to the max viewport dimension (width=800px).
- EXPECT_FLOAT_EQ(0.1 * (60.0 / 800.0),
- GetJankTracker().ScoreWithMoveDistance());
- EXPECT_FLOAT_EQ(60.0, GetJankTracker().OverallMaxDistance());
+ // 300 * (100 + 60) * (60 / 800) / (default viewport size 800 * 600)
+ EXPECT_FLOAT_EQ(0.1 * (60.0 / 800.0), GetLayoutShiftTracker().Score());
+ EXPECT_FLOAT_EQ(60.0, GetLayoutShiftTracker().OverallMaxDistance());
}
-TEST_F(JankTrackerTest, GranularitySnapping) {
+TEST_F(LayoutShiftTrackerTest, GranularitySnapping) {
if (RuntimeEnabledFeatures::JankTrackingSweepLineEnabled())
return;
@@ -73,10 +74,10 @@ TEST_F(JankTrackerTest, GranularitySnapping) {
AtomicString("top: 58px"));
UpdateAllLifecyclePhases();
// Rect locations and sizes should snap to multiples of 600 / 60 = 10.
- EXPECT_FLOAT_EQ(0.1, GetJankTracker().Score());
+ EXPECT_FLOAT_EQ(0.1, GetLayoutShiftTracker().Score());
}
-TEST_F(JankTrackerTest, Transform) {
+TEST_F(LayoutShiftTrackerTest, Transform) {
SetBodyInnerHTML(R"HTML(
<style>
body { margin: 0; }
@@ -91,11 +92,11 @@ TEST_F(JankTrackerTest, Transform) {
GetDocument().getElementById("j")->setAttribute(html_names::kStyleAttr,
AtomicString("top: 60px"));
UpdateAllLifecyclePhases();
- // (600 - 300) * (140 - 40 + 60) / (default viewport size 800 * 600)
- EXPECT_FLOAT_EQ(0.1, GetJankTracker().Score());
+ // (600 - 300) * (140 - 40 + 60) * (60 / 800) / (800 * 600)
+ EXPECT_FLOAT_EQ(0.1 * (60.0 / 800.0), GetLayoutShiftTracker().Score());
}
-TEST_F(JankTrackerTest, RtlDistance) {
+TEST_F(LayoutShiftTrackerTest, RtlDistance) {
SetBodyInnerHTML(R"HTML(
<style>
#j { position: relative; width: 100px; height: 100px; direction: rtl; }
@@ -105,10 +106,10 @@ TEST_F(JankTrackerTest, RtlDistance) {
GetDocument().getElementById("j")->setAttribute(
html_names::kStyleAttr, AtomicString("width: 70px; left: 10px"));
UpdateAllLifecyclePhases();
- EXPECT_FLOAT_EQ(20.0, GetJankTracker().OverallMaxDistance());
+ EXPECT_FLOAT_EQ(20.0, GetLayoutShiftTracker().OverallMaxDistance());
}
-TEST_F(JankTrackerTest, SmallMovementIgnored) {
+TEST_F(LayoutShiftTrackerTest, SmallMovementIgnored) {
SetBodyInnerHTML(R"HTML(
<style>
#j { position: relative; width: 300px; height: 100px; }
@@ -118,10 +119,10 @@ TEST_F(JankTrackerTest, SmallMovementIgnored) {
GetDocument().getElementById("j")->setAttribute(html_names::kStyleAttr,
AtomicString("top: 2px"));
UpdateAllLifecyclePhases();
- EXPECT_EQ(0.0, GetJankTracker().Score());
+ EXPECT_EQ(0.0, GetLayoutShiftTracker().Score());
}
-TEST_F(JankTrackerTest, SmallMovementIgnoredWithZoom) {
+TEST_F(LayoutShiftTrackerTest, SmallMovementIgnoredWithZoom) {
GetDocument().GetFrame()->SetPageZoomFactor(2);
SetBodyInnerHTML(R"HTML(
<style>
@@ -132,10 +133,10 @@ TEST_F(JankTrackerTest, SmallMovementIgnoredWithZoom) {
GetDocument().getElementById("j")->setAttribute(html_names::kStyleAttr,
AtomicString("top: 2px"));
UpdateAllLifecyclePhases();
- EXPECT_EQ(0.0, GetJankTracker().Score());
+ EXPECT_EQ(0.0, GetLayoutShiftTracker().Score());
}
-TEST_F(JankTrackerTest, IgnoreAfterInput) {
+TEST_F(LayoutShiftTrackerTest, IgnoreAfterInput) {
SetBodyInnerHTML(R"HTML(
<style>
#j { position: relative; width: 300px; height: 100px; }
@@ -146,11 +147,15 @@ TEST_F(JankTrackerTest, IgnoreAfterInput) {
AtomicString("top: 60px"));
SimulateInput();
UpdateAllLifecyclePhases();
- EXPECT_EQ(0.0, GetJankTracker().Score());
- EXPECT_TRUE(GetJankTracker().ObservedInputOrScroll());
+ EXPECT_EQ(0.0, GetLayoutShiftTracker().Score());
+ EXPECT_TRUE(GetLayoutShiftTracker().ObservedInputOrScroll());
+ EXPECT_TRUE(GetLayoutShiftTracker()
+ .MostRecentInputTimestamp()
+ .since_origin()
+ .InSecondsF() > 0.0);
}
-TEST_F(JankTrackerTest, CompositedElementMovement) {
+TEST_F(LayoutShiftTrackerTest, CompositedElementMovement) {
SetBodyInnerHTML(R"HTML(
<style>
#jank {
@@ -181,11 +186,11 @@ TEST_F(JankTrackerTest, CompositedElementMovement) {
// #jank is 400x200 after viewport intersection with correct application of
// composited #container offset, and 100px lower after janking, so jank score
- // is (400 * 300) / (viewport size 800 * 600)
- EXPECT_FLOAT_EQ(0.25, GetJankTracker().Score());
+ // is (400 * 300) * (100 / 800) / (viewport size 800 * 600)
+ EXPECT_FLOAT_EQ(0.25 * (100.0 / 800.0), GetLayoutShiftTracker().Score());
}
-TEST_F(JankTrackerTest, CompositedJankBeforeFirstPaint) {
+TEST_F(LayoutShiftTrackerTest, CompositedJankBeforeFirstPaint) {
// Tests that we don't crash if a new layer janks during a second compositing
// update before prepaint sets up property tree state. See crbug.com/881735
// (which invokes UpdateLifecycleToCompositingCleanPlusScrolling through
@@ -212,7 +217,7 @@ TEST_F(JankTrackerTest, CompositedJankBeforeFirstPaint) {
UpdateAllLifecyclePhases();
}
-TEST_F(JankTrackerTest, IgnoreFixedAndSticky) {
+TEST_F(LayoutShiftTrackerTest, IgnoreFixedAndSticky) {
SetBodyInnerHTML(R"HTML(
<style>
body { height: 1000px; }
@@ -240,10 +245,10 @@ TEST_F(JankTrackerTest, IgnoreFixedAndSticky) {
GetDocument().scrollingElement()->setScrollTop(50);
UpdateAllLifecyclePhases();
- EXPECT_FLOAT_EQ(0, GetJankTracker().Score());
+ EXPECT_FLOAT_EQ(0, GetLayoutShiftTracker().Score());
}
-TEST_F(JankTrackerTest, IgnoreSVG) {
+TEST_F(LayoutShiftTrackerTest, IgnoreSVG) {
SetBodyInnerHTML(R"HTML(
<svg>
<circle cx="50" cy="50" r="40"
@@ -253,10 +258,10 @@ TEST_F(JankTrackerTest, IgnoreSVG) {
GetDocument().QuerySelector("circle")->setAttribute(svg_names::kCxAttr,
AtomicString("100"));
UpdateAllLifecyclePhases();
- EXPECT_FLOAT_EQ(0, GetJankTracker().Score());
+ EXPECT_FLOAT_EQ(0, GetLayoutShiftTracker().Score());
}
-TEST_F(JankTrackerTest, JankWhileScrolled) {
+TEST_F(LayoutShiftTrackerTest, JankWhileScrolled) {
SetBodyInnerHTML(R"HTML(
<style>
body { height: 1000px; margin: 0; }
@@ -266,17 +271,17 @@ TEST_F(JankTrackerTest, JankWhileScrolled) {
)HTML");
GetDocument().scrollingElement()->setScrollTop(100);
- EXPECT_EQ(0.0, GetJankTracker().Score());
- EXPECT_EQ(0.0, GetJankTracker().OverallMaxDistance());
+ EXPECT_EQ(0.0, GetLayoutShiftTracker().Score());
+ EXPECT_EQ(0.0, GetLayoutShiftTracker().OverallMaxDistance());
GetDocument().getElementById("j")->setAttribute(html_names::kStyleAttr,
AtomicString("top: 60px"));
UpdateAllLifecyclePhases();
- // 300 * (height 200 - scrollY 100 + movement 60) / (800 * 600 viewport)
- EXPECT_FLOAT_EQ(0.1, GetJankTracker().Score());
+ // 300 * (height 200 - scrollY 100 + movement 60) * (60 / 800) / (800 * 600)
+ EXPECT_FLOAT_EQ(0.1 * (60.0 / 800.0), GetLayoutShiftTracker().Score());
}
-TEST_F(JankTrackerTest, FullyClippedVisualRect) {
+TEST_F(LayoutShiftTrackerTest, FullyClippedVisualRect) {
SetBodyInnerHTML(R"HTML(
<style>
body { margin: 0; }
@@ -289,10 +294,10 @@ TEST_F(JankTrackerTest, FullyClippedVisualRect) {
GetDocument().getElementById("j")->setAttribute(html_names::kStyleAttr,
AtomicString("top: 200px"));
UpdateAllLifecyclePhases();
- EXPECT_FLOAT_EQ(0.0, GetJankTracker().Score());
+ EXPECT_FLOAT_EQ(0.0, GetLayoutShiftTracker().Score());
}
-TEST_F(JankTrackerTest, PartiallyClippedVisualRect) {
+TEST_F(LayoutShiftTrackerTest, PartiallyClippedVisualRect) {
SetBodyInnerHTML(R"HTML(
<style>
body { margin: 0; }
@@ -305,11 +310,12 @@ TEST_F(JankTrackerTest, PartiallyClippedVisualRect) {
GetDocument().getElementById("j")->setAttribute(html_names::kStyleAttr,
AtomicString("top: 200px"));
UpdateAllLifecyclePhases();
- // (clipped width 150px) * (height 200 + movement 200) / (800 * 600 viewport)
- EXPECT_FLOAT_EQ(0.125, GetJankTracker().Score());
+ // (clipped width 150px) * (height 200 + movement 200) * (200 / 800) /
+ // (800 * 600)
+ EXPECT_FLOAT_EQ(0.125 * (200.0 / 800.0), GetLayoutShiftTracker().Score());
}
-TEST_F(JankTrackerTest, MultiClipVisualRect) {
+TEST_F(LayoutShiftTrackerTest, MultiClipVisualRect) {
SetBodyInnerHTML(R"HTML(
<style>
body { margin: 0; }
@@ -326,12 +332,12 @@ TEST_F(JankTrackerTest, MultiClipVisualRect) {
// Note that, while the element moves up 200px, its visibility is
// clipped at 0px,150px height, so the additional 200px of vertical
// move distance is not included in the score.
- // (clip width 200) * (clip height 150) / (800 * 600 viewport)
- EXPECT_FLOAT_EQ(0.0625, GetJankTracker().Score());
- EXPECT_FLOAT_EQ(200.0, GetJankTracker().OverallMaxDistance());
+ // (clip width 200) * (clip height 150) * (200 / 800) / (800 * 600 viewport)
+ EXPECT_FLOAT_EQ(0.0625 * (200.0 / 800.0), GetLayoutShiftTracker().Score());
+ EXPECT_FLOAT_EQ(200.0, GetLayoutShiftTracker().OverallMaxDistance());
}
-TEST_F(JankTrackerTest, ShiftOutsideViewport) {
+TEST_F(LayoutShiftTrackerTest, ShiftOutsideViewport) {
SetBodyInnerHTML(R"HTML(
<style>
body { margin: 0; }
@@ -345,10 +351,10 @@ TEST_F(JankTrackerTest, ShiftOutsideViewport) {
UpdateAllLifecyclePhases();
// Since the element moves entirely outside of the viewport, it shouldn't
// generate a score.
- EXPECT_FLOAT_EQ(0.0, GetJankTracker().Score());
+ EXPECT_FLOAT_EQ(0.0, GetLayoutShiftTracker().Score());
}
-TEST_F(JankTrackerTest, ShiftInToViewport) {
+TEST_F(LayoutShiftTrackerTest, ShiftInToViewport) {
SetBodyInnerHTML(R"HTML(
<style>
body { margin: 0; }
@@ -362,11 +368,11 @@ TEST_F(JankTrackerTest, ShiftInToViewport) {
UpdateAllLifecyclePhases();
// The element moves from outside the viewport to within the viewport, which
// should generate jank.
- // (width 600) * (height 0 + move 200) / (800 * 600 viewport)
- EXPECT_FLOAT_EQ(0.25, GetJankTracker().Score());
+ // (width 600) * (height 0 + move 200) * (200 / 800) / (800 * 600 viewport)
+ EXPECT_FLOAT_EQ(0.25 * (200.0 / 800.0), GetLayoutShiftTracker().Score());
}
-TEST_F(JankTrackerTest, ClipWithoutPaintLayer) {
+TEST_F(LayoutShiftTrackerTest, ClipWithoutPaintLayer) {
SetBodyInnerHTML(R"HTML(
<style>
#scroller { overflow: scroll; width: 200px; height: 500px; }
@@ -389,14 +395,39 @@ TEST_F(JankTrackerTest, ClipWithoutPaintLayer) {
UpdateAllLifecyclePhases();
// Make sure no jank score is reported, since the element that moved is fully
// clipped by the scroller.
- EXPECT_FLOAT_EQ(0.0, GetJankTracker().Score());
+ EXPECT_FLOAT_EQ(0.0, GetLayoutShiftTracker().Score());
}
-class JankTrackerSimTest : public SimTest {};
+TEST_F(LayoutShiftTrackerTest, LocalShiftWithoutViewportShift) {
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ #c { position: relative; width: 300px; height: 100px; transform: scale(0.1); }
+ #j { position: relative; width: 100px; height: 10px; }
+ </style>
+ <div id='c'>
+ <div id='j'></div>
+ </div>
+ </div>
+ )HTML");
+
+ GetDocument().getElementById("j")->setAttribute(html_names::kStyleAttr,
+ AtomicString("top: 4px"));
-TEST_F(JankTrackerSimTest, SubframeWeighting) {
- WebView().MainFrameWidget()->Resize(WebSize(800, 600));
+ UpdateAllLifecyclePhases();
+ // Make sure no shift score is reported, since the element didn't move in the
+ // viewport.
+ EXPECT_FLOAT_EQ(0.0, GetLayoutShiftTracker().Score());
+}
+class LayoutShiftTrackerSimTest : public SimTest {
+ protected:
+ void SetUp() override {
+ SimTest::SetUp();
+ WebView().MainFrameWidget()->Resize(WebSize(800, 600));
+ }
+};
+
+TEST_F(LayoutShiftTrackerSimTest, SubframeWeighting) {
// TODO(crbug.com/943668): Test OOPIF path.
SimRequest main_resource("https://example.com/", "text/html");
SimRequest child_resource("https://example.com/sub.html", "text/html");
@@ -429,10 +460,11 @@ TEST_F(JankTrackerSimTest, SubframeWeighting) {
Compositor().BeginFrame();
test::RunPendingTasks();
- // 300 * (100 + 60) / (default viewport size 800 * 600)
- JankTracker& jank_tracker = child_frame.GetFrameView()->GetJankTracker();
- EXPECT_FLOAT_EQ(0.4, jank_tracker.Score());
- EXPECT_FLOAT_EQ(0.1, jank_tracker.WeightedScore());
+ // 300 * (100 + 60) * (60 / 400) / (default viewport size 800 * 600)
+ LayoutShiftTracker& layout_shift_tracker =
+ child_frame.GetFrameView()->GetLayoutShiftTracker();
+ EXPECT_FLOAT_EQ(0.4 * (60.0 / 400.0), layout_shift_tracker.Score());
+ EXPECT_FLOAT_EQ(0.1 * (60.0 / 400.0), layout_shift_tracker.WeightedScore());
// Move subframe halfway outside the viewport.
GetDocument().getElementById("i")->setAttribute(html_names::kStyleAttr,
@@ -443,13 +475,11 @@ TEST_F(JankTrackerSimTest, SubframeWeighting) {
Compositor().BeginFrame();
test::RunPendingTasks();
- EXPECT_FLOAT_EQ(0.8, jank_tracker.Score());
- EXPECT_FLOAT_EQ(0.15, jank_tracker.WeightedScore());
+ EXPECT_FLOAT_EQ(0.8 * (60.0 / 400.0), layout_shift_tracker.Score());
+ EXPECT_FLOAT_EQ(0.15 * (60.0 / 400.0), layout_shift_tracker.WeightedScore());
}
-TEST_F(JankTrackerSimTest, ViewportSizeChange) {
- WebView().MainFrameWidget()->Resize(WebSize(800, 600));
-
+TEST_F(LayoutShiftTrackerSimTest, ViewportSizeChange) {
SimRequest main_resource("https://example.com/", "text/html");
LoadURL("https://example.com/");
main_resource.Complete(R"HTML(
@@ -478,11 +508,94 @@ TEST_F(JankTrackerSimTest, ViewportSizeChange) {
Compositor().BeginFrame();
test::RunPendingTasks();
- JankTracker& jank_tracker = MainFrame().GetFrameView()->GetJankTracker();
- EXPECT_FLOAT_EQ(0.0, jank_tracker.Score());
+ LayoutShiftTracker& layout_shift_tracker =
+ MainFrame().GetFrameView()->GetLayoutShiftTracker();
+ EXPECT_FLOAT_EQ(0.0, layout_shift_tracker.Score());
+}
+
+class LayoutShiftTrackerPointerdownTest : public LayoutShiftTrackerSimTest {
+ protected:
+ void RunTest(WebInputEvent::Type completion_type, bool expect_exclusion);
+};
+
+void LayoutShiftTrackerPointerdownTest::RunTest(
+ WebInputEvent::Type completion_type,
+ bool expect_exclusion) {
+ SimRequest main_resource("https://example.com/", "text/html");
+ LoadURL("https://example.com/");
+ main_resource.Complete(R"HTML(
+ <style>
+ body { margin: 0; height: 1500px; }
+ #box {
+ left: 0px;
+ top: 0px;
+ width: 400px;
+ height: 600px;
+ background: yellow;
+ position: relative;
+ }
+ </style>
+ <div id="box"></div>
+ <script>
+ box.addEventListener("pointerdown", (e) => {
+ box.style.top = "100px";
+ e.preventDefault();
+ });
+ </script>
+ )HTML");
+
+ Compositor().BeginFrame();
+ test::RunPendingTasks();
+
+ WebPointerProperties pointer_properties = WebPointerProperties(
+ 1 /* PointerId */, WebPointerProperties::PointerType::kTouch,
+ WebPointerProperties::Button::kLeft);
+
+ WebPointerEvent event1(WebInputEvent::kPointerDown, pointer_properties, 5, 5);
+ WebPointerEvent event2(completion_type, pointer_properties, 5, 5);
+
+ // Coordinates inside #box.
+ event1.SetPositionInWidget(50, 150);
+ event2.SetPositionInWidget(50, 160);
+
+ WebView().MainFrameWidget()->HandleInputEvent(WebCoalescedInputEvent(event1));
+
+ Compositor().BeginFrame();
+ test::RunPendingTasks();
+
+ WindowPerformance& perf = *DOMWindowPerformance::performance(Window());
+ auto& tracker = MainFrame().GetFrameView()->GetLayoutShiftTracker();
+
+ EXPECT_EQ(0u, perf.getBufferedEntriesByType("layout-shift").size());
+ EXPECT_FLOAT_EQ(0.0, tracker.Score());
+
+ WebView().MainFrameWidget()->HandleInputEvent(WebCoalescedInputEvent(event2));
+
+ // region fraction 50%, distance fraction 1/8
+ const double expected_shift = 0.5 * 0.125;
+
+ auto entries = perf.getBufferedEntriesByType("layout-shift");
+ EXPECT_EQ(1u, entries.size());
+ LayoutShift* shift = static_cast<LayoutShift*>(entries.front().Get());
+
+ EXPECT_EQ(expect_exclusion, shift->hadRecentInput());
+ EXPECT_FLOAT_EQ(expected_shift, shift->value());
+ EXPECT_FLOAT_EQ(expect_exclusion ? 0.0 : expected_shift, tracker.Score());
+}
+
+TEST_F(LayoutShiftTrackerPointerdownTest, PointerdownBecomesTap) {
+ RunTest(WebInputEvent::kPointerUp, true /* expect_exclusion */);
+}
+
+TEST_F(LayoutShiftTrackerPointerdownTest, PointerdownCancelled) {
+ RunTest(WebInputEvent::kPointerCancel, false /* expect_exclusion */);
+}
+
+TEST_F(LayoutShiftTrackerPointerdownTest, PointerdownBecomesScroll) {
+ RunTest(WebInputEvent::kPointerCausedUaAction, false /* expect_exclusion */);
}
-TEST_F(JankTrackerTest, StableCompositingChanges) {
+TEST_F(LayoutShiftTrackerTest, StableCompositingChanges) {
SetBodyInnerHTML(R"HTML(
<style>
body { margin: 0; }
@@ -530,10 +643,10 @@ TEST_F(JankTrackerTest, StableCompositingChanges) {
};
while (advance()) {
}
- EXPECT_FLOAT_EQ(0, GetJankTracker().Score());
+ EXPECT_FLOAT_EQ(0, GetLayoutShiftTracker().Score());
}
-TEST_F(JankTrackerTest, CompositedOverflowExpansion) {
+TEST_F(LayoutShiftTrackerTest, CompositedOverflowExpansion) {
SetBodyInnerHTML(R"HTML(
<style>
@@ -583,7 +696,7 @@ TEST_F(JankTrackerTest, CompositedOverflowExpansion) {
drop->setAttribute(html_names::kStyleAttr, AtomicString("display: none"));
UpdateAllLifecyclePhases();
- EXPECT_FLOAT_EQ(0, GetJankTracker().Score());
+ EXPECT_FLOAT_EQ(0, GetLayoutShiftTracker().Score());
Element* comp = GetDocument().getElementById("comp");
comp->setAttribute(html_names::kClassAttr, AtomicString("sh"));
@@ -592,8 +705,50 @@ TEST_F(JankTrackerTest, CompositedOverflowExpansion) {
// old rect (240 * 120) / (800 * 600) = 0.06
// new rect, 50% clipped by viewport (240 * 60) / (800 * 600) = 0.03
- // final score 0.06 + 0.03 = 0.09
- EXPECT_FLOAT_EQ(0.09, GetJankTracker().Score());
+ // final score 0.06 + 0.03 = 0.09 * (490 move distance / 800)
+ EXPECT_FLOAT_EQ(0.09 * (490.0 / 800.0), GetLayoutShiftTracker().Score());
+}
+
+TEST_F(LayoutShiftTrackerTest, CounterscrollAllowed) {
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ #s {
+ overflow: scroll;
+ position: absolute;
+ left: 20px;
+ top: 20px;
+ width: 200px;
+ height: 200px;
+ }
+ #sp {
+ width: 170px;
+ height: 600px;
+ }
+ #ch {
+ position: relative;
+ background: yellow;
+ left: 10px;
+ top: 100px;
+ width: 150px;
+ height: 150px;
+ }
+ </style>
+ <div id="s">
+ <div id="sp">
+ <div id="ch"></div>
+ </div>
+ </div>
+ )HTML");
+ UpdateAllLifecyclePhases();
+
+ Element* scroller = GetDocument().getElementById("s");
+ Element* changer = GetDocument().getElementById("ch");
+
+ changer->setAttribute(html_names::kStyleAttr, AtomicString("top: 200px"));
+ scroller->setScrollTop(100.0);
+
+ UpdateAllLifecyclePhases();
+ EXPECT_FLOAT_EQ(0, GetLayoutShiftTracker().Score());
}
} // namespace blink
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 db984bd952d..f41bbd8335c 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_slider.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_slider.cc
@@ -59,7 +59,7 @@ void LayoutSlider::ComputeIntrinsicLogicalWidths(
inline SliderThumbElement* LayoutSlider::GetSliderThumbElement() const {
return To<SliderThumbElement>(
- ToElement(GetNode())->UserAgentShadowRoot()->getElementById(
+ To<Element>(GetNode())->UserAgentShadowRoot()->getElementById(
shadow_element_names::SliderThumb()));
}
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_state.h b/chromium/third_party/blink/renderer/core/layout/layout_state.h
index 328897824de..c8ddfb58dca 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_state.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_state.h
@@ -28,7 +28,7 @@
#include "base/macros.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/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
namespace blink {
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 8e732cb69a2..0a6a93afb08 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_table.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_table.cc
@@ -1614,29 +1614,24 @@ PhysicalRect LayoutTable::OverflowClipRect(
}
bool LayoutTable::NodeAtPoint(HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
HitTestAction action) {
- LayoutPoint adjusted_location = accumulated_offset + Location();
-
// Check kids first.
bool skip_children = (result.GetHitTestRequest().GetStopNode() == this);
if (!skip_children &&
(!HasOverflowClip() ||
- location_in_container.Intersects(
- OverflowClipRect(PhysicalOffsetToBeNoop(adjusted_location))
- .ToLayoutRect()))) {
+ hit_test_location.Intersects(OverflowClipRect(accumulated_offset)))) {
for (LayoutObject* child = LastChild(); child;
child = child->PreviousSibling()) {
if (child->IsBox() && !ToLayoutBox(child)->HasSelfPaintingLayer() &&
(child->IsTableSection() || child->IsTableCaption())) {
- LayoutPoint child_point =
- FlipForWritingModeForChild(ToLayoutBox(child), adjusted_location);
- if (child->NodeAtPoint(result, location_in_container, child_point,
- action)) {
- UpdateHitTestResult(
- result,
- ToLayoutPoint(location_in_container.Point() - child_point));
+ PhysicalOffset child_accumulated_offset =
+ accumulated_offset + ToLayoutBox(child)->PhysicalLocation(this);
+ if (child->NodeAtPoint(result, hit_test_location,
+ child_accumulated_offset, action)) {
+ UpdateHitTestResult(result,
+ hit_test_location.Point() - accumulated_offset);
return true;
}
}
@@ -1644,15 +1639,13 @@ bool LayoutTable::NodeAtPoint(HitTestResult& result,
}
// Check our bounds next.
- LayoutRect bounds_rect(adjusted_location, Size());
+ PhysicalRect bounds_rect(accumulated_offset, Size());
if (VisibleToHitTestRequest(result.GetHitTestRequest()) &&
(action == kHitTestBlockBackground ||
action == kHitTestChildBlockBackground) &&
- location_in_container.Intersects(bounds_rect)) {
- UpdateHitTestResult(
- result, DeprecatedFlipForWritingMode(location_in_container.Point() -
- ToLayoutSize(adjusted_location)));
- if (result.AddNodeToListBasedTestResult(GetNode(), location_in_container,
+ hit_test_location.Intersects(bounds_rect)) {
+ UpdateHitTestResult(result, hit_test_location.Point() - accumulated_offset);
+ if (result.AddNodeToListBasedTestResult(GetNode(), hit_test_location,
bounds_rect) == kStopHitTesting)
return true;
}
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 4b1e85325ab..1428eec1440 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_table.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_table.h
@@ -448,8 +448,8 @@ class CORE_EXPORT LayoutTable final : public LayoutBlock {
LayoutUnit& max_width) const override;
void ComputePreferredLogicalWidths() override;
bool NodeAtPoint(HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
HitTestAction) override;
LayoutUnit BaselinePosition(
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 e18a62ef437..7b44e7aaae7 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
@@ -202,7 +202,7 @@ void LayoutTableCell::ComputePreferredLogicalWidths() {
// See if nowrap was set.
Length w = StyleOrColLogicalWidth();
const AtomicString& nowrap =
- ToElement(GetNode())->getAttribute(kNowrapAttr);
+ To<Element>(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
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 263d0f77a48..d073f4f6cbd 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
@@ -291,7 +291,7 @@ TEST_F(LayoutTableCellTest, BorderWidthsWithCollapsedBorders) {
EXPECT_EQ(1u, cell2->CollapsedOuterBorderBefore());
EXPECT_EQ(2u, cell2->CollapsedOuterBorderAfter());
- ToElement(cell1->Table()->GetNode())
+ To<Element>(cell1->Table()->GetNode())
->setAttribute(html_names::kStyleAttr,
"writing-mode: vertical-rl; direction: rtl");
UpdateAllLifecyclePhasesForTest();
@@ -333,22 +333,23 @@ TEST_F(LayoutTableCellTest, HasNonCollapsedBorderDecoration) {
auto* cell = GetCellByElementId("cell");
EXPECT_FALSE(cell->HasNonCollapsedBorderDecoration());
- ToElement(cell->GetNode())
+ To<Element>(cell->GetNode())
->setAttribute(html_names::kStyleAttr, "border: 1px solid black");
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
EXPECT_TRUE(cell->HasNonCollapsedBorderDecoration());
- ToElement(cell->Table()->GetNode())
+ To<Element>(cell->Table()->GetNode())
->setAttribute(html_names::kStyleAttr, "border-collapse: collapse");
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
EXPECT_FALSE(cell->HasNonCollapsedBorderDecoration());
- ToElement(cell->GetNode())
+ To<Element>(cell->GetNode())
->setAttribute(html_names::kStyleAttr, "border: 2px solid black");
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
EXPECT_FALSE(cell->HasNonCollapsedBorderDecoration());
- ToElement(cell->Table()->GetNode())->setAttribute(html_names::kStyleAttr, "");
+ To<Element>(cell->Table()->GetNode())
+ ->setAttribute(html_names::kStyleAttr, "");
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
EXPECT_TRUE(cell->HasNonCollapsedBorderDecoration());
}
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 a330a4b6b7a..82d9a23aeb1 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
@@ -227,25 +227,26 @@ void LayoutTableRow::UpdateLayout() {
// Hit Testing
bool LayoutTableRow::NodeAtPoint(HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
HitTestAction action) {
+ // The row and the cells are all located in the section.
+ const auto* section = Section();
+ PhysicalOffset section_accumulated_offset =
+ accumulated_offset - PhysicalLocation(section);
+
// Table rows cannot ever be hit tested. Effectively they do not exist.
// Just forward to our children always.
for (LayoutTableCell* cell = LastCell(); cell; cell = cell->PreviousCell()) {
- // FIXME: We have to skip over inline flows, since they can show up inside
- // table rows at the moment (a demoted inline <form> for example). If we
- // ever implement a table-specific hit-test method (which we should do for
- // performance reasons anyway), then we can remove this check.
- if (!cell->HasSelfPaintingLayer()) {
- LayoutPoint cell_point =
- FlipForWritingModeForChild(cell, accumulated_offset);
- if (cell->NodeAtPoint(result, location_in_container, cell_point,
- action)) {
- UpdateHitTestResult(
- result, location_in_container.Point() - ToLayoutSize(cell_point));
- return true;
- }
+ if (cell->HasSelfPaintingLayer())
+ continue;
+ PhysicalOffset cell_accumulated_offset =
+ section_accumulated_offset + cell->PhysicalLocation(section);
+ if (cell->NodeAtPoint(result, hit_test_location, cell_accumulated_offset,
+ action)) {
+ UpdateHitTestResult(
+ result, hit_test_location.Point() - section_accumulated_offset);
+ return true;
}
}
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_table_row.h b/chromium/third_party/blink/renderer/core/layout/layout_table_row.h
index 86d8d153d54..8be602317e5 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_table_row.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_table_row.h
@@ -100,8 +100,8 @@ class CORE_EXPORT LayoutTableRow final : public LayoutTableBoxComponent {
}
bool NodeAtPoint(HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
HitTestAction) override;
PaginationBreakability GetPaginationBreakability() const final;
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 c39aa598db9..bccd836a7ab 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
@@ -28,7 +28,6 @@
#include <algorithm>
#include <limits>
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#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_table_cell.h"
@@ -38,6 +37,7 @@
#include "third_party/blink/renderer/core/layout/subtree_layout_scope.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/table_section_painter.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
@@ -1149,20 +1149,6 @@ static bool CellHasExplicitlySpecifiedHeight(const LayoutTableCell& cell) {
return true;
}
-static bool ShouldFlexCellChild(const LayoutTableCell& cell,
- LayoutObject* cell_descendant) {
- if (!CellHasExplicitlySpecifiedHeight(cell))
- return false;
- // TODO(dgrogan): Delete ShouldFlexCellChild. It's only called when
- // CellHasExplicitlySpecifiedHeight is false.
- NOTREACHED() << "This is dead code?";
- if (cell_descendant->StyleRef().OverflowY() == EOverflow::kVisible ||
- cell_descendant->StyleRef().OverflowY() == EOverflow::kHidden)
- return true;
- return cell_descendant->IsBox() &&
- ToLayoutBox(cell_descendant)->ShouldBeConsideredAsReplaced();
-}
-
void LayoutTableSection::LayoutRows() {
#if DCHECK_IS_ON()
SetLayoutNeededForbiddenScope layout_forbidden_scope(*this);
@@ -1512,10 +1498,8 @@ void LayoutTableSection::Paint(const PaintInfo& paint_info) const {
}
LayoutRect LayoutTableSection::LogicalRectForWritingModeAndDirection(
- const LayoutRect& rect) const {
- LayoutRect table_aligned_rect(rect);
-
- DeprecatedFlipForWritingMode(table_aligned_rect);
+ const PhysicalRect& rect) const {
+ LayoutRect table_aligned_rect = FlipForWritingMode(rect);
if (!TableStyle().IsHorizontalWritingMode())
table_aligned_rect = table_aligned_rect.TransposedRect();
@@ -1794,39 +1778,29 @@ void LayoutTableSection::SplitEffectiveColumn(unsigned pos, unsigned first) {
}
// Hit Testing
-bool LayoutTableSection::NodeAtPoint(
- HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
- HitTestAction action) {
+bool LayoutTableSection::NodeAtPoint(HitTestResult& result,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
+ HitTestAction action) {
// If we have no children then we have nothing to do.
if (!FirstRow())
return false;
+ DCHECK(!HasOverflowClip());
+
// Table sections cannot ever be hit tested. Effectively they do not exist.
// Just forward to our children always.
- LayoutPoint adjusted_location = accumulated_offset + Location();
-
- if (HasOverflowClip() &&
- !location_in_container.Intersects(OverflowClipRect(adjusted_location)))
- return false;
-
if (HasVisuallyOverflowingCell()) {
for (LayoutTableRow* row = LastRow(); row; row = row->PreviousRow()) {
- // FIXME: We have to skip over inline flows, since they can show up inside
- // table rows at the moment (a demoted inline <form> for example). If we
- // ever implement a table-specific hit-test method (which we should do for
- // performance reasons anyway), then we can remove this check.
- if (!row->HasSelfPaintingLayer()) {
- LayoutPoint child_point =
- FlipForWritingModeForChild(row, adjusted_location);
- if (row->NodeAtPoint(result, location_in_container, child_point,
- action)) {
- UpdateHitTestResult(
- result,
- ToLayoutPoint(location_in_container.Point() - child_point));
- return true;
- }
+ if (row->HasSelfPaintingLayer())
+ continue;
+ PhysicalOffset row_accumulated_offset =
+ accumulated_offset + row->PhysicalLocation(this);
+ if (row->NodeAtPoint(result, hit_test_location, row_accumulated_offset,
+ action)) {
+ UpdateHitTestResult(result,
+ hit_test_location.Point() - accumulated_offset);
+ return true;
}
}
return false;
@@ -1834,8 +1808,8 @@ bool LayoutTableSection::NodeAtPoint(
RecalcCellsIfNeeded();
- LayoutRect hit_test_rect = LayoutRect(location_in_container.BoundingBox());
- hit_test_rect.MoveBy(-adjusted_location);
+ PhysicalRect hit_test_rect = hit_test_location.BoundingBox();
+ hit_test_rect.Move(-accumulated_offset);
LayoutRect table_aligned_rect =
LogicalRectForWritingModeAndDirection(hit_test_rect);
@@ -1857,12 +1831,12 @@ bool LayoutTableSection::NodeAtPoint(
for (unsigned i = grid_cell.Cells().size(); i;) {
--i;
LayoutTableCell* cell = grid_cell.Cells()[i];
- LayoutPoint cell_point =
- FlipForWritingModeForChild(cell, adjusted_location);
+ PhysicalOffset cell_accumulated_offset =
+ accumulated_offset + cell->PhysicalLocation(this);
if (static_cast<LayoutObject*>(cell)->NodeAtPoint(
- result, location_in_container, cell_point, action)) {
- UpdateHitTestResult(
- result, location_in_container.Point() - ToLayoutSize(cell_point));
+ result, hit_test_location, cell_accumulated_offset, action)) {
+ UpdateHitTestResult(result,
+ hit_test_location.Point() - accumulated_offset);
return true;
}
}
@@ -1912,52 +1886,38 @@ void LayoutTableSection::SetLogicalPositionForCell(
void LayoutTableSection::RelayoutCellIfFlexed(LayoutTableCell& cell,
int row_index,
int row_height) {
- // Force percent height children to lay themselves out again.
- // This will cause these children to grow to fill the cell.
+ // Force percent height children to lay themselves out again now that the
+ // cell's final height is determined.
// FIXME: There is still more work to do here to fully match WinIE (should
// it become necessary to do so). In quirks mode, WinIE behaves like we
// do, but it will clip the cells that spill out of the table section.
// strict mode, Mozilla and WinIE both regrow the table to accommodate the
// new height of the cell (thus letting the percentages cause growth one
// time only). We may also not be handling row-spanning cells correctly.
- //
- // Note also the oddity where replaced elements always flex, and yet blocks/
- // tables do not necessarily flex. WinIE is crazy and inconsistent, and we
- // can't hope to match the behavior perfectly, but we'll continue to refine it
- // as we discover new bugs. :)
- bool cell_children_flex = false;
- bool flex_all_children = CellHasExplicitlySpecifiedHeight(cell) ||
- (!Table()->StyleRef().LogicalHeight().IsAuto() &&
- row_height != cell.LogicalHeight());
-
- for (LayoutObject* child = cell.FirstChild(); child;
- child = child->NextSibling()) {
- if (!child->IsText() &&
- child->StyleRef().LogicalHeight().IsPercentOrCalc() &&
- (flex_all_children || ShouldFlexCellChild(cell, child)) &&
- (!child->IsTable() || ToLayoutTable(child)->HasSections())) {
- cell_children_flex = true;
- break;
- }
- }
- if (!cell_children_flex) {
- if (TrackedLayoutBoxListHashSet* percent_height_descendants =
- cell.PercentHeightDescendants()) {
- for (auto* descendant : *percent_height_descendants) {
- if (flex_all_children || ShouldFlexCellChild(cell, descendant)) {
- cell_children_flex = true;
- break;
- }
+ if (!CellHasExplicitlySpecifiedHeight(cell) &&
+ (Table()->StyleRef().LogicalHeight().IsAuto() ||
+ row_height == cell.LogicalHeight()))
+ return;
+
+ bool any_child_needs_relayout = cell.HasPercentHeightDescendants();
+
+ if (!any_child_needs_relayout) {
+ for (LayoutObject* child = cell.FirstChild(); child;
+ child = child->NextSibling()) {
+ if (!child->IsText() &&
+ child->StyleRef().LogicalHeight().IsPercentOrCalc() &&
+ (!child->IsTable() || (!child->IsOutOfFlowPositioned() &&
+ ToLayoutTable(child)->HasSections()))) {
+ any_child_needs_relayout = true;
+ break;
}
}
}
- if (!cell_children_flex)
+ if (!any_child_needs_relayout)
return;
- // Alignment within a cell is based off the calculated height, which becomes
- // irrelevant once the cell has been resized based off its percentage.
cell.SetOverrideLogicalHeightFromRowHeight(LayoutUnit(row_height));
cell.ForceLayout();
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_table_section.h b/chromium/third_party/blink/renderer/core/layout/layout_table_section.h
index 36e7559ad6b..e9da2c3801e 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_table_section.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_table_section.h
@@ -239,7 +239,7 @@ class CORE_EXPORT LayoutTableSection final : public LayoutTableBoxComponent {
// Flip the rect so it aligns with the coordinates used by the rowPos and
// columnPos vectors.
- LayoutRect LogicalRectForWritingModeAndDirection(const LayoutRect&) const;
+ LayoutRect LogicalRectForWritingModeAndDirection(const PhysicalRect&) const;
// Sets |rows| and |columns| to cover all cells needing repaint in
// |damage_rect|.
@@ -306,8 +306,8 @@ class CORE_EXPORT LayoutTableSection final : public LayoutTableBoxComponent {
protected:
void StyleDidChange(StyleDifference, const ComputedStyle* old_style) override;
bool NodeAtPoint(HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
HitTestAction) override;
private:
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 f155749100a..42393c7a74a 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
@@ -314,7 +314,7 @@ TEST_F(LayoutTableSectionTest, VisualOverflowWithCollapsedBorders) {
static void SetCellsOverflowInRow(LayoutTableRow* row) {
for (auto* cell = row->FirstCell(); cell; cell = cell->NextCell()) {
- ToElement(cell->GetNode())
+ To<Element>(cell->GetNode())
->setAttribute(html_names::kClassAttr, "overflow");
}
}
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 edb14adc271..bbe66c6343e 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
@@ -29,11 +29,11 @@ TEST_F(LayoutTableTest, OverflowViaOutline) {
)HTML");
auto* target = GetTableByElementId("target");
EXPECT_EQ(LayoutRect(0, 0, 100, 200), target->SelfVisualOverflowRect());
- ToElement(target->GetNode())
+ To<Element>(target->GetNode())
->setAttribute(html_names::kStyleAttr, "outline: 2px solid black");
auto* child = GetTableByElementId("child");
- ToElement(child->GetNode())
+ To<Element>(child->GetNode())
->setAttribute(html_names::kStyleAttr, "outline: 2px solid black");
target->GetFrameView()->UpdateAllLifecyclePhases(
@@ -331,7 +331,7 @@ TEST_F(LayoutTableTest, VisualOverflowCleared) {
)HTML");
auto* table = GetTableByElementId("table");
EXPECT_EQ(LayoutRect(-3, -3, 66, 66), table->SelfVisualOverflowRect());
- ToElement(table->GetNode())
+ To<Element>(table->GetNode())
->setAttribute(html_names::kStyleAttr, "box-shadow: initial");
GetDocument().View()->UpdateAllLifecyclePhases(
DocumentLifecycle::LifecycleUpdateReason::kTest);
@@ -343,12 +343,12 @@ TEST_F(LayoutTableTest, HasNonCollapsedBorderDecoration) {
auto* table = GetTableByElementId("table");
EXPECT_FALSE(table->HasNonCollapsedBorderDecoration());
- ToElement(table->GetNode())
+ To<Element>(table->GetNode())
->setAttribute(html_names::kStyleAttr, "border: 1px solid black");
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
EXPECT_TRUE(table->HasNonCollapsedBorderDecoration());
- ToElement(table->GetNode())
+ To<Element>(table->GetNode())
->setAttribute(html_names::kStyleAttr,
"border: 1px solid black; border-collapse: collapse");
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
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 caf5796184e..50b7c300be4 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_text.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_text.cc
@@ -82,7 +82,7 @@ struct SameSizeAsLayoutText : public LayoutObject {
float widths[4];
String text;
void* pointers[2];
- NodeHolder node_holder;
+ DOMNodeId node_id;
};
static_assert(sizeof(LayoutText) == sizeof(SameSizeAsLayoutText),
@@ -103,9 +103,9 @@ class SecureTextTimer final : public TimerBase {
void RestartWithNewText(unsigned last_typed_character_offset) {
last_typed_character_offset_ = last_typed_character_offset;
if (Settings* settings = layout_text_->GetDocument().GetSettings()) {
- StartOneShot(
- TimeDelta::FromSecondsD(settings->GetPasswordEchoDurationInSeconds()),
- FROM_HERE);
+ StartOneShot(base::TimeDelta::FromSecondsD(
+ settings->GetPasswordEchoDurationInSeconds()),
+ FROM_HERE);
}
}
void Invalidate() { last_typed_character_offset_ = -1; }
@@ -159,9 +159,10 @@ LayoutText::~LayoutText() {
#endif
}
-LayoutText* LayoutText::CreateEmptyAnonymous(Document& doc,
- scoped_refptr<ComputedStyle> style,
- LegacyLayout legacy) {
+LayoutText* LayoutText::CreateEmptyAnonymous(
+ Document& doc,
+ scoped_refptr<const ComputedStyle> style,
+ LegacyLayout legacy) {
LayoutText* text =
LayoutObjectFactory::CreateText(nullptr, StringImpl::empty_, legacy);
text->SetDocumentForAnonymous(&doc);
@@ -219,9 +220,17 @@ void LayoutText::RemoveAndDestroyTextBoxes() {
}
for (InlineTextBox* box : TextBoxes())
box->Remove();
- } else if (Parent()) {
- Parent()->DirtyLinesFromChangedChild(this);
+ } else {
+ if (NGPaintFragment* first_inline_fragment = FirstInlineFragment()) {
+ first_inline_fragment->LayoutObjectWillBeDestroyed();
+ SetFirstInlineFragment(nullptr);
+ }
+ if (Parent())
+ Parent()->DirtyLinesFromChangedChild(this);
}
+ } else if (NGPaintFragment* first_inline_fragment = FirstInlineFragment()) {
+ // Still do this to clear the global hash map in NGAbstractInlineTextBox.
+ SetFirstInlineFragment(nullptr);
}
DeleteTextBoxes();
}
@@ -231,11 +240,10 @@ void LayoutText::WillBeDestroyed() {
g_secure_text_timers ? g_secure_text_timers->Take(this) : nullptr)
delete secure_text_timer;
- if (!node_holder_.is_empty) {
+ if (node_id_ != kInvalidDOMNodeId) {
if (auto* manager = GetContentCaptureManager())
- manager->OnLayoutTextWillBeDestroyed(node_holder_);
- node_holder_.text_holder.reset();
- node_holder_.is_empty = true;
+ manager->OnLayoutTextWillBeDestroyed(*GetNode());
+ node_id_ = kInvalidDOMNodeId;
}
RemoveAndDestroyTextBoxes();
@@ -256,9 +264,7 @@ void LayoutText::RemoveTextBox(InlineTextBox* box) {
}
void LayoutText::DeleteTextBoxes() {
- if (IsInLayoutNGInlineFormattingContext())
- SetFirstInlineFragment(nullptr);
- else
+ if (!IsInLayoutNGInlineFormattingContext())
MutableTextBoxes().DeleteLineBoxes();
}
@@ -287,9 +293,17 @@ Vector<LayoutText::TextBoxInfo> LayoutText::GetTextBoxInfo() const {
Vector<TextBoxInfo> results;
if (const NGOffsetMapping* mapping = GetNGOffsetMapping()) {
auto fragments = NGPaintFragment::InlineFragmentsFor(this);
+ bool in_hidden_for_paint = false;
for (const NGPaintFragment* fragment : fragments) {
const auto& text_fragment =
To<NGPhysicalTextFragment>(fragment->PhysicalFragment());
+ if (text_fragment.IsHiddenForPaint()) {
+ in_hidden_for_paint = true;
+ } else if (in_hidden_for_paint) {
+ // Because of we finished original fragments (not painted), we should
+ // ignore truncated fragments (actually painted).
+ break;
+ }
// When the corresponding DOM range contains collapsed whitespaces, NG
// produces one fragment but legacy produces multiple text boxes broken at
// collapsed whitespaces. We break the fragment at collapsed whitespaces
@@ -432,7 +446,11 @@ void LayoutText::CollectLineBoxRects(const PhysicalRectCollector& yield,
const auto children =
NGInlineFragmentTraversal::SelfFragmentsOf(*box_fragment, this);
for (const auto& child : children) {
- // TODO(layout-dev): We should have NG version of |EllipsisRectForBox()|
+ if (UNLIKELY(option != ClippingOption::kNoClipping)) {
+ DCHECK_EQ(option, ClippingOption::kClipToEllipsis);
+ if (child.fragment->IsHiddenForPaint())
+ continue;
+ }
yield(child.RectInContainerBox());
}
return;
@@ -722,7 +740,7 @@ CreatePositionWithAffinityForBoxAfterAdjustingOffsetForBiDi(
} // namespace
PositionWithAffinity LayoutText::PositionForPoint(
- const LayoutPoint& point) const {
+ const PhysicalOffset& point) const {
if (const LayoutBlockFlow* ng_block_flow = ContainingNGBlockFlow())
return ng_block_flow->PositionForPoint(point);
@@ -730,10 +748,11 @@ PositionWithAffinity LayoutText::PositionForPoint(
if (!FirstTextBox() || TextLength() == 0)
return CreatePositionWithAffinity(0);
+ LayoutPoint flipped_point = FlipForWritingMode(point);
LayoutUnit point_line_direction =
- FirstTextBox()->IsHorizontal() ? point.X() : point.Y();
+ IsHorizontalWritingMode() ? flipped_point.X() : flipped_point.Y();
LayoutUnit point_block_direction =
- FirstTextBox()->IsHorizontal() ? point.Y() : point.X();
+ IsHorizontalWritingMode() ? flipped_point.Y() : flipped_point.X();
bool blocks_are_flipped = StyleRef().IsFlippedBlocksWritingMode();
InlineTextBox* last_box = nullptr;
@@ -1612,9 +1631,8 @@ void LayoutText::SetFirstTextBoxLogicalLeft(float text_width) const {
void LayoutText::SetTextWithOffset(scoped_refptr<StringImpl> text,
unsigned offset,
- unsigned len,
- bool force) {
- if (!force && Equal(text_.Impl(), text.get()))
+ unsigned len) {
+ if (Equal(text_.Impl(), text.get()))
return;
// Check that we are replacing the whole text.
@@ -1635,7 +1653,9 @@ void LayoutText::SetTextWithOffset(scoped_refptr<StringImpl> text,
FirstTextBox()->ManuallySetStartLenAndLogicalWidth(
offset, text->length(), LayoutUnit(text_width));
SetFirstTextBoxLogicalLeft(text_width);
- SetText(std::move(text), force, true);
+ const bool force = false;
+ const bool avoid_layout_and_only_paint = true;
+ SetText(std::move(text), force, avoid_layout_and_only_paint);
lines_dirty_ = false;
valid_ng_items_ = false;
return;
@@ -1715,7 +1735,7 @@ void LayoutText::SetTextWithOffset(scoped_refptr<StringImpl> text,
}
lines_dirty_ = dirtied_lines;
- SetText(std::move(text), force || dirtied_lines);
+ SetText(std::move(text), dirtied_lines);
// TODO(layout-dev): Invalidation is currently all or nothing in LayoutNG,
// this is probably fine for NGInlineItem reuse as recreating the individual
@@ -1841,9 +1861,9 @@ void LayoutText::SetText(scoped_refptr<StringImpl> text,
if (text_autosizer)
text_autosizer->Record(this);
- if (HasNodeHolder()) {
+ if (HasNodeId()) {
if (auto* content_capture_manager = GetContentCaptureManager())
- content_capture_manager->OnNodeTextChanged(node_holder_);
+ content_capture_manager->OnNodeTextChanged(*GetNode());
}
valid_ng_items_ = false;
@@ -2381,12 +2401,12 @@ PhysicalRect LayoutText::DebugRect() const {
return PhysicalRect(EnclosingIntRect(PhysicalLinesBoundingBox()));
}
-NodeHolder LayoutText::EnsureNodeHolder() {
- if (node_holder_.is_empty) {
+DOMNodeId LayoutText::EnsureNodeId() {
+ if (node_id_ == kInvalidDOMNodeId) {
if (auto* content_capture_manager = GetContentCaptureManager())
- node_holder_ = content_capture_manager->GetNodeHolder(*GetNode());
+ node_id_ = content_capture_manager->GetNodeId(*GetNode());
}
- return node_holder_;
+ return node_id_;
}
ContentCaptureManager* LayoutText::GetContentCaptureManager() {
@@ -2404,24 +2424,24 @@ void LayoutText::SetInlineItems(NGInlineItem* begin, NGInlineItem* end) {
DCHECK_EQ(item->GetLayoutObject(), this);
}
#endif
- NGInlineItems* items = GetNGInlineItems();
+ base::span<NGInlineItem>* items = GetNGInlineItems();
if (!items)
return;
valid_ng_items_ = true;
- items->SetRange(begin, end);
+ *items = base::make_span(begin, end);
}
void LayoutText::ClearInlineItems() {
has_bidi_control_items_ = false;
valid_ng_items_ = false;
- if (NGInlineItems* items = GetNGInlineItems())
- items->Clear();
+ if (base::span<NGInlineItem>* items = GetNGInlineItems())
+ *items = base::span<NGInlineItem>();
}
-const NGInlineItems& LayoutText::InlineItems() const {
+const base::span<NGInlineItem>& LayoutText::InlineItems() const {
DCHECK(valid_ng_items_);
DCHECK(GetNGInlineItems());
- DCHECK(!GetNGInlineItems()->IsEmpty());
+ DCHECK(!GetNGInlineItems()->empty());
return *GetNGInlineItems();
}
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 05854a741e5..1ec564578de 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_text.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_text.h
@@ -25,13 +25,13 @@
#include <iterator>
#include "base/memory/scoped_refptr.h"
-#include "third_party/blink/renderer/core/content_capture/content_holder.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/dom/text.h"
#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/geometry/length_functions.h"
+#include "third_party/blink/renderer/platform/graphics/dom_node_id.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
namespace blink {
@@ -40,7 +40,6 @@ class AbstractInlineTextBox;
class ContentCaptureManager;
class InlineTextBox;
class NGInlineItem;
-class NGInlineItems;
class NGOffsetMapping;
enum class OnlyWhitespaceOrNbsp : unsigned { kUnknown = 0, kNo = 1, kYes = 2 };
@@ -84,7 +83,7 @@ class CORE_EXPORT LayoutText : public LayoutObject {
~LayoutText() override;
static LayoutText* CreateEmptyAnonymous(Document&,
- scoped_refptr<ComputedStyle>,
+ scoped_refptr<const ComputedStyle>,
LegacyLayout);
const char* GetName() const override { return "LayoutText"; }
@@ -123,7 +122,7 @@ class CORE_EXPORT LayoutText : public LayoutObject {
void LocalQuadsInFlippedBlocksDirection(Vector<FloatQuad>&,
ClippingOption = kNoClipping) const;
- PositionWithAffinity PositionForPoint(const LayoutPoint&) const override;
+ PositionWithAffinity PositionForPoint(const PhysicalOffset&) const override;
bool Is8Bit() const { return text_.Is8Bit(); }
const LChar* Characters8() const { return text_.Impl()->Characters8(); }
@@ -193,8 +192,7 @@ class CORE_EXPORT LayoutText : public LayoutObject {
bool avoid_layout_and_only_paint = false);
void SetTextWithOffset(scoped_refptr<StringImpl>,
unsigned offset,
- unsigned len,
- bool force = false);
+ unsigned len);
virtual void TransformText();
@@ -310,13 +308,13 @@ class CORE_EXPORT LayoutText : public LayoutObject {
bool MapDOMOffsetToTextContentOffset(const NGOffsetMapping&,
unsigned* start,
unsigned* end) const;
- NodeHolder EnsureNodeHolder();
- bool HasNodeHolder() const { return !node_holder_.is_empty; }
+ DOMNodeId EnsureNodeId();
+ bool HasNodeId() const { return node_id_ != kInvalidDOMNodeId; }
void SetInlineItems(NGInlineItem* begin, NGInlineItem* end);
void ClearInlineItems();
bool HasValidInlineItems() const { return valid_ng_items_; }
- const NGInlineItems& InlineItems() const;
+ const base::span<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; }
@@ -326,8 +324,10 @@ class CORE_EXPORT LayoutText : public LayoutObject {
void ClearHasBidiControlInlineItems() { has_bidi_control_items_ = false; }
protected:
- virtual const NGInlineItems* GetNGInlineItems() const { return nullptr; }
- virtual NGInlineItems* GetNGInlineItems() { return nullptr; }
+ virtual const base::span<NGInlineItem>* GetNGInlineItems() const {
+ return nullptr;
+ }
+ virtual base::span<NGInlineItem>* GetNGInlineItems() { return nullptr; }
void WillBeDestroyed() override;
void StyleWillChange(StyleDifference, const ComputedStyle&) final {}
@@ -369,7 +369,7 @@ class CORE_EXPORT LayoutText : public LayoutObject {
void UpdateLayout() final { NOTREACHED(); }
bool NodeAtPoint(HitTestResult&,
const HitTestLocation&,
- const LayoutPoint&,
+ const PhysicalOffset&,
HitTestAction) final {
NOTREACHED();
return false;
@@ -396,10 +396,6 @@ class CORE_EXPORT LayoutText : public LayoutObject {
bool CanOptimizeSetText() const;
void SetFirstTextBoxLogicalLeft(float text_width) const;
- private:
- ContentCaptureManager* GetContentCaptureManager();
- NodeHolder node_holder_;
-
// We put the bitfield first to minimize padding on 64-bit.
protected:
// Whether or not we can be broken into multiple lines.
@@ -435,6 +431,8 @@ class CORE_EXPORT LayoutText : public LayoutObject {
unsigned is_text_fragment_ : 1;
private:
+ ContentCaptureManager* GetContentCaptureManager();
+
// Used for LayoutNG with accessibility. True if inline fragments are
// associated to |NGAbstractInlineTextBox|.
unsigned has_abstract_inline_text_box_ : 1;
@@ -454,6 +452,7 @@ class CORE_EXPORT LayoutText : public LayoutObject {
// Valid only when IsInLayoutNGInlineFormattingContext().
NGPaintFragment* first_paint_fragment_;
};
+ DOMNodeId node_id_ = kInvalidDOMNodeId;
};
inline InlineTextBoxList& LayoutText::MutableTextBoxes() {
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_text_combine.cc b/chromium/third_party/blink/renderer/core/layout/layout_text_combine.cc
index 43fa011a322..a35e7592b42 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_text_combine.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_text_combine.cc
@@ -62,7 +62,7 @@ void LayoutTextCombine::SetTextInternal(scoped_refptr<StringImpl> text) {
// UpdateFontStyleForCombinedText on the original font and not what was
// previously set for combined text. If IsCombined() is now false, we are
// simply resetting the style to the parent style.
- SetStyle(Parent()->MutableStyle());
+ SetStyle(Parent()->Style());
} else if (IsCombined()) {
// If the text was previously not combined, SetStyle would have been a no-op
// since the before and after style would be the same ComputedStyle
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 9b09564007d..05e17b94162 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
@@ -126,19 +126,16 @@ void LayoutTextControl::ComputeLogicalHeight(
void LayoutTextControl::HitInnerEditorElement(
HitTestResult& result,
- const LayoutPoint& point_in_container,
- const LayoutPoint& accumulated_offset) {
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset) {
HTMLElement* inner_editor = InnerEditorElement();
if (!inner_editor->GetLayoutObject())
return;
- LayoutPoint adjusted_location = accumulated_offset + Location();
- LayoutPoint local_point =
- point_in_container -
- ToLayoutSize(adjusted_location +
- inner_editor->GetLayoutBox()->Location());
+ PhysicalOffset local_point = hit_test_location.Point() - accumulated_offset -
+ inner_editor->GetLayoutBox()->PhysicalLocation();
if (HasOverflowClip())
- local_point += ScrolledContentOffset();
+ local_point += PhysicalOffset(ScrolledContentOffset());
result.SetNodeAndPosition(inner_editor, local_point);
}
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_text_control.h b/chromium/third_party/blink/renderer/core/layout/layout_text_control.h
index 1d26fd5f87a..643c76a3601 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_text_control.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_text_control.h
@@ -57,8 +57,8 @@ class CORE_EXPORT LayoutTextControl : public LayoutBlockFlow {
void StyleDidChange(StyleDifference, const ComputedStyle* old_style) override;
void HitInnerEditorElement(HitTestResult&,
- const LayoutPoint& point_in_container,
- const LayoutPoint& accumulated_offset);
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset);
int TextBlockLogicalWidth() const;
int TextBlockLogicalHeight() const;
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_text_control_multi_line.cc b/chromium/third_party/blink/renderer/core/layout/layout_text_control_multi_line.cc
index 0395634b474..ef3a634471d 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_text_control_multi_line.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_text_control_multi_line.cc
@@ -38,21 +38,20 @@ LayoutTextControlMultiLine::~LayoutTextControlMultiLine() = default;
bool LayoutTextControlMultiLine::NodeAtPoint(
HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
HitTestAction hit_test_action) {
- if (!LayoutTextControl::NodeAtPoint(result, location_in_container,
+ if (!LayoutTextControl::NodeAtPoint(result, hit_test_location,
accumulated_offset, hit_test_action))
return false;
+ const LayoutObject* stop_node = result.GetHitTestRequest().GetStopNode();
+ if (stop_node && stop_node->NodeForHitTest() == result.InnerNode())
+ return true;
+
if (result.InnerNode() == GetNode() ||
- result.InnerNode() == InnerEditorElement()) {
- const LayoutObject* stop_node = result.GetHitTestRequest().GetStopNode();
- if (!stop_node || stop_node->NodeForHitTest() != result.InnerNode()) {
- HitInnerEditorElement(result, location_in_container.Point(),
- accumulated_offset);
- }
- }
+ result.InnerNode() == InnerEditorElement())
+ HitInnerEditorElement(result, hit_test_location, accumulated_offset);
return true;
}
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_text_control_multi_line.h b/chromium/third_party/blink/renderer/core/layout/layout_text_control_multi_line.h
index 77a522cc75d..67401f83c24 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_text_control_multi_line.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_text_control_multi_line.h
@@ -40,8 +40,8 @@ class LayoutTextControlMultiLine final : public LayoutTextControl {
}
bool NodeAtPoint(HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
HitTestAction) override;
float GetAvgCharWidth(const AtomicString& family) const override;
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 9173e224134..135c0ce4703 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
@@ -138,13 +138,17 @@ void LayoutTextControlSingleLine::UpdateLayout() {
bool LayoutTextControlSingleLine::NodeAtPoint(
HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
HitTestAction hit_test_action) {
- if (!LayoutTextControl::NodeAtPoint(result, location_in_container,
+ if (!LayoutTextControl::NodeAtPoint(result, hit_test_location,
accumulated_offset, hit_test_action))
return false;
+ const LayoutObject* stop_node = result.GetHitTestRequest().GetStopNode();
+ if (stop_node && stop_node->NodeForHitTest() == result.InnerNode())
+ return true;
+
// Say that we hit the inner text element if
// - we hit a node inside the inner text element,
// - we hit the <input> element (e.g. we're over the border or padding), or
@@ -153,18 +157,18 @@ bool LayoutTextControlSingleLine::NodeAtPoint(
if (result.InnerNode()->IsDescendantOf(InnerEditorElement()) ||
result.InnerNode() == GetNode() ||
(container && container == result.InnerNode())) {
- LayoutPoint point_in_parent = location_in_container.Point();
+ PhysicalOffset inner_editor_accumulated_offset = accumulated_offset;
if (container && EditingViewPortElement()) {
- if (EditingViewPortElement()->GetLayoutBox())
- point_in_parent -=
- ToLayoutSize(EditingViewPortElement()->GetLayoutBox()->Location());
- if (container->GetLayoutBox())
- point_in_parent -= ToLayoutSize(container->GetLayoutBox()->Location());
- }
- const LayoutObject* stop_node = result.GetHitTestRequest().GetStopNode();
- if (!stop_node || stop_node->NodeForHitTest() != result.InnerNode()) {
- HitInnerEditorElement(result, point_in_parent, accumulated_offset);
+ if (EditingViewPortElement()->GetLayoutBox()) {
+ inner_editor_accumulated_offset +=
+ EditingViewPortElement()->GetLayoutBox()->PhysicalLocation();
+ }
+ if (container->GetLayoutBox()) {
+ inner_editor_accumulated_offset +=
+ container->GetLayoutBox()->PhysicalLocation();
+ }
}
+ HitInnerEditorElement(result, hit_test_location, accumulated_offset);
}
return true;
}
@@ -263,7 +267,7 @@ LayoutUnit LayoutTextControlSingleLine::ComputeControlLogicalHeight(
return line_height + non_content_height;
}
-void LayoutTextControlSingleLine::Autoscroll(const LayoutPoint& position) {
+void LayoutTextControlSingleLine::Autoscroll(const PhysicalOffset& position) {
LayoutBox* layout_object = InnerEditorElement()->GetLayoutBox();
if (!layout_object)
return;
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 1f23080990c..89165928b0a 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
@@ -57,11 +57,11 @@ class LayoutTextControlSingleLine : public LayoutTextControl {
void UpdateLayout() override;
bool NodeAtPoint(HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
HitTestAction) final;
- void Autoscroll(const LayoutPoint&) final;
+ void Autoscroll(const PhysicalOffset&) final;
// Subclassed to forward to our inner div.
LayoutUnit ScrollLeft() const final;
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_text_control_single_line_test.cc b/chromium/third_party/blink/renderer/core/layout/layout_text_control_single_line_test.cc
index 562474165cc..a0533fd75c5 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_text_control_single_line_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_text_control_single_line_test.cc
@@ -29,7 +29,7 @@ TEST_F(LayoutTextControlSingleLineTest, VisualOverflowCleared) {
#else
EXPECT_EQ(LayoutRect(-3, -3, 70, 72), input->SelfVisualOverflowRect());
#endif
- ToElement(input->GetNode())
+ To<Element>(input->GetNode())
->setAttribute(html_names::kStyleAttr, "box-shadow: initial");
GetDocument().View()->UpdateAllLifecyclePhases(
DocumentLifecycle::LifecycleUpdateReason::kTest);
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 834270fde6e..4c588764209 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
@@ -186,8 +186,9 @@ LayoutText* LayoutTextFragment::GetFirstLetterPart() const {
return ToLayoutTextFragment(child);
}
-void LayoutTextFragment::UpdateHitTestResult(HitTestResult& result,
- const LayoutPoint& point) const {
+void LayoutTextFragment::UpdateHitTestResult(
+ HitTestResult& result,
+ const PhysicalOffset& point) const {
if (result.InnerNode())
return;
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 c401e00aab5..af2fb502ef0 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
@@ -111,7 +111,8 @@ class CORE_EXPORT LayoutTextFragment : public LayoutText {
LayoutBlock* BlockForAccompanyingFirstLetter() const;
UChar PreviousCharacter() const override;
- void UpdateHitTestResult(HitTestResult&, const LayoutPoint&) const override;
+ void UpdateHitTestResult(HitTestResult&,
+ const PhysicalOffset&) const override;
unsigned start_;
unsigned fragment_length_;
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_text_fragment_test.cc b/chromium/third_party/blink/renderer/core/layout/layout_text_fragment_test.cc
index c0230fbf135..3ab39f38722 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_text_fragment_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_text_fragment_test.cc
@@ -4,6 +4,7 @@
#include "third_party/blink/renderer/core/layout/layout_text_fragment.h"
+#include "third_party/blink/renderer/core/dom/first_letter_pseudo_element.h"
#include "third_party/blink/renderer/core/html/html_head_element.h"
#include "third_party/blink/renderer/core/testing/core_unit_test_helper.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
@@ -392,4 +393,82 @@ TEST_P(ParameterizedLayoutTextFragmentTest,
1)); // "(x |<span>xx</span>"
}
+TEST_P(ParameterizedLayoutTextFragmentTest, SetTextWithFirstLetter) {
+ // Note: |V8TestingScope| is needed for |Text::splitText()|.
+ V8TestingScope scope;
+
+ SetBodyInnerHTML(
+ "<style>div::first-letter {color: red;}</style>"
+ "<div id=sample>a</div>");
+ const Element& sample = *GetElementById("sample");
+ // |letter_x| is "a" then "" finally "x"
+ Text& letter_x = *To<Text>(sample.firstChild());
+ ASSERT_TRUE(letter_x.GetLayoutObject()->IsTextFragment());
+ EXPECT_TRUE(letter_x.GetLayoutObject()->GetFirstLetterPart());
+ EXPECT_TRUE(ToLayoutTextFragment(letter_x.GetLayoutObject())
+ ->IsRemainingTextLayoutObject());
+ ASSERT_TRUE(letter_x.GetLayoutObject()->GetFirstLetterPart());
+ EXPECT_EQ("a", letter_x.GetLayoutObject()->GetFirstLetterPart()->GetText());
+
+ // Make <div>"" "a"</div>
+ Text& letter_a = *letter_x.splitText(0, ASSERT_NO_EXCEPTION);
+ UpdateAllLifecyclePhasesForTest();
+
+ EXPECT_TRUE(letter_a.GetLayoutObject()->IsTextFragment())
+ << "'a' is still first-letter";
+ EXPECT_TRUE(letter_a.GetLayoutObject()->GetFirstLetterPart());
+ EXPECT_TRUE(ToLayoutTextFragment(letter_a.GetLayoutObject())
+ ->IsRemainingTextLayoutObject());
+ ASSERT_TRUE(letter_a.GetLayoutObject()->GetFirstLetterPart());
+ EXPECT_EQ("a", letter_a.GetLayoutObject()->GetFirstLetterPart()->GetText());
+ EXPECT_TRUE(letter_x.GetLayoutObject()->IsTextFragment());
+ EXPECT_FALSE(letter_x.GetLayoutObject()->GetFirstLetterPart());
+
+ // Make <div>"x" "a"</div>
+ letter_x.setTextContent("x");
+ UpdateAllLifecyclePhasesForTest();
+
+ // See |FirstLetterPseudoElement::DetachLayoutTree()| which updates remaining
+ // part |LayoutTextFragment|.
+ EXPECT_TRUE(letter_a.GetLayoutObject()->IsTextFragment())
+ << "We still use LayoutTextFragment for 'a'";
+ EXPECT_FALSE(letter_a.GetLayoutObject()->GetFirstLetterPart());
+ EXPECT_FALSE(ToLayoutTextFragment(letter_a.GetLayoutObject())
+ ->IsRemainingTextLayoutObject());
+ EXPECT_FALSE(ToLayoutTextFragment(letter_a.GetLayoutObject())
+ ->GetFirstLetterPseudoElement());
+ ASSERT_TRUE(letter_x.GetLayoutObject()->IsTextFragment())
+ << "'x' is first letter-part";
+ EXPECT_TRUE(ToLayoutTextFragment(letter_x.GetLayoutObject())
+ ->IsRemainingTextLayoutObject());
+ ASSERT_TRUE(letter_x.GetLayoutObject()->GetFirstLetterPart());
+ EXPECT_EQ("x", letter_x.GetLayoutObject()->GetFirstLetterPart()->GetText());
+}
+
+// For http://crbug.com/984389
+TEST_P(ParameterizedLayoutTextFragmentTest, SplitTextWithZero) {
+ // Note: |V8TestingScope| is needed for |Text::splitText()|.
+ V8TestingScope scope;
+
+ SetBodyInnerHTML(
+ "<style>div::first-letter {color: red;}</style>"
+ "<div><b id=sample> x y</b></div>");
+ const Element& sample = *GetElementById("sample");
+ // Make " " "x y"
+ To<Text>(sample.firstChild())->splitText(1, ASSERT_NO_EXCEPTION);
+ UpdateAllLifecyclePhasesForTest();
+
+ // Make "" " " "x y"
+ To<Text>(sample.firstChild())->splitText(0, ASSERT_NO_EXCEPTION);
+ UpdateAllLifecyclePhasesForTest();
+
+ Text& xy = To<Text>(*sample.lastChild());
+ FirstLetterPseudoElement& first_letter_element =
+ *ToLayoutTextFragment(xy.GetLayoutObject())
+ ->GetFirstLetterPseudoElement();
+ EXPECT_EQ(first_letter_element.GetLayoutObject(),
+ xy.GetLayoutObject()->PreviousSibling())
+ << "first-letter remaining part should be next to first-letter part";
+}
+
} // namespace blink
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 671bb18a44f..14c81719614 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
@@ -431,6 +431,67 @@ TEST_P(ParameterizedLayoutTextTest, GetTextBoxInfoWithGeneratedContent) {
EXPECT_EQ(LayoutRect(20, 0, 20, 10), boxes_remaining[1].local_rect);
}
+// For http://crbug.com/985488
+TEST_P(ParameterizedLayoutTextTest, GetTextBoxInfoWithHidden) {
+ LoadAhem();
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ #target {
+ font: 10px/1 Ahem;
+ overflow-x: hidden;
+ white-space: nowrap;
+ width: 9ch;
+ }
+ </style>
+ <div id="target"> abcde fghij </div>
+ )HTML");
+ const Element& target = *GetElementById("target");
+ const LayoutText& layout_text =
+ *To<Text>(target.firstChild())->GetLayoutObject();
+
+ auto boxes = layout_text.GetTextBoxInfo();
+ EXPECT_EQ(2u, boxes.size());
+
+ EXPECT_EQ(2u, boxes[0].dom_start_offset);
+ EXPECT_EQ(6u, boxes[0].dom_length);
+ EXPECT_EQ(LayoutRect(0, 0, 60, 10), boxes[0].local_rect);
+
+ EXPECT_EQ(9u, boxes[1].dom_start_offset);
+ EXPECT_EQ(5u, boxes[1].dom_length);
+ EXPECT_EQ(LayoutRect(60, 0, 50, 10), boxes[1].local_rect);
+}
+
+// For http://crbug.com/985488
+TEST_P(ParameterizedLayoutTextTest, GetTextBoxInfoWithEllipsis) {
+ LoadAhem();
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ #target {
+ font: 10px/1 Ahem;
+ overflow-x: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ width: 9ch;
+ }
+ </style>
+ <div id="target"> abcde fghij </div>
+ )HTML");
+ const Element& target = *GetElementById("target");
+ const LayoutText& layout_text =
+ *To<Text>(target.firstChild())->GetLayoutObject();
+
+ auto boxes = layout_text.GetTextBoxInfo();
+ EXPECT_EQ(2u, boxes.size());
+
+ EXPECT_EQ(2u, boxes[0].dom_start_offset);
+ EXPECT_EQ(6u, boxes[0].dom_length);
+ EXPECT_EQ(LayoutRect(0, 0, 60, 10), boxes[0].local_rect);
+
+ EXPECT_EQ(9u, boxes[1].dom_start_offset);
+ EXPECT_EQ(5u, boxes[1].dom_length);
+ EXPECT_EQ(LayoutRect(60, 0, 50, 10), boxes[1].local_rect);
+}
+
TEST_P(ParameterizedLayoutTextTest,
IsBeforeAfterNonCollapsedCharacterNoLineWrap) {
// Basic tests
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 50db8d9b888..676c4dd173d 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_theme.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_theme.cc
@@ -351,9 +351,10 @@ bool LayoutTheme::IsIndeterminate(const Node* node) {
}
bool LayoutTheme::IsEnabled(const Node* node) {
- if (!node || !node->IsElementNode())
+ auto* element = DynamicTo<Element>(node);
+ if (!element)
return true;
- return !ToElement(node)->IsDisabledFormControl();
+ return !element->IsDisabledFormControl();
}
bool LayoutTheme::IsFocused(const Node* node) {
@@ -375,36 +376,31 @@ bool LayoutTheme::IsPressed(const Node* node) {
}
bool LayoutTheme::IsSpinUpButtonPartPressed(const Node* node) {
- if (!node || !node->IsActive() || !node->IsElementNode() ||
- !ToElement(node)->IsSpinButtonElement())
+ const auto* element = DynamicTo<SpinButtonElement>(node);
+ if (!element || !element->IsActive())
return false;
- const SpinButtonElement* element = ToSpinButtonElement(node);
return element->GetUpDownState() == SpinButtonElement::kUp;
}
bool LayoutTheme::IsReadOnlyControl(const Node* node) {
- if (!node || !node->IsElementNode() ||
- !ToElement(node)->IsFormControlElement())
- return false;
- const HTMLFormControlElement* element = ToHTMLFormControlElement(node);
- return element->IsReadOnly();
+ auto* form_control_element = DynamicTo<HTMLFormControlElement>(node);
+ return form_control_element && form_control_element->IsReadOnly();
}
bool LayoutTheme::IsHovered(const Node* node) {
if (!node)
return false;
- if (!node->IsElementNode() || !ToElement(node)->IsSpinButtonElement())
+ const auto* element = DynamicTo<SpinButtonElement>(node);
+ if (!element)
return node->IsHovered();
- const SpinButtonElement* element = ToSpinButtonElement(node);
return element->IsHovered() &&
element->GetUpDownState() != SpinButtonElement::kIndeterminate;
}
bool LayoutTheme::IsSpinUpButtonPartHovered(const Node* node) {
- if (!node || !node->IsElementNode() ||
- !ToElement(node)->IsSpinButtonElement())
+ const auto* element = DynamicTo<SpinButtonElement>(node);
+ if (!element)
return false;
- const SpinButtonElement* element = ToSpinButtonElement(node);
return element->GetUpDownState() == SpinButtonElement::kUp;
}
@@ -446,12 +442,12 @@ void LayoutTheme::AdjustInnerSpinButtonStyle(ComputedStyle&) const {}
void LayoutTheme::AdjustMenuListStyle(ComputedStyle&, Element*) const {}
-TimeDelta LayoutTheme::AnimationRepeatIntervalForProgressBar() const {
- return TimeDelta();
+base::TimeDelta LayoutTheme::AnimationRepeatIntervalForProgressBar() const {
+ return base::TimeDelta();
}
-TimeDelta LayoutTheme::AnimationDurationForProgressBar() const {
- return TimeDelta();
+base::TimeDelta LayoutTheme::AnimationDurationForProgressBar() const {
+ return base::TimeDelta();
}
bool LayoutTheme::ShouldHaveSpinButton(HTMLInputElement* input_element) const {
@@ -489,14 +485,14 @@ void LayoutTheme::PlatformColorsDidChange() {
Page::PlatformColorsChanged();
}
-void LayoutTheme::SetCaretBlinkInterval(TimeDelta interval) {
+void LayoutTheme::SetCaretBlinkInterval(base::TimeDelta interval) {
caret_blink_interval_ = interval;
}
-TimeDelta LayoutTheme::CaretBlinkInterval() const {
+base::TimeDelta LayoutTheme::CaretBlinkInterval() const {
// Disable the blinking caret in web test mode, as it introduces
// a race condition for the pixel tests. http://b/1198440
- return WebTestSupport::IsRunningWebTest() ? TimeDelta()
+ return WebTestSupport::IsRunningWebTest() ? base::TimeDelta()
: caret_blink_interval_;
}
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 7a20c4d8c62..86168e319a8 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_theme.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_theme.h
@@ -34,7 +34,7 @@
#include "third_party/blink/renderer/platform/graphics/color.h"
#include "third_party/blink/renderer/platform/graphics/color_scheme.h"
#include "third_party/blink/renderer/platform/theme_types.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.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/time.h"
@@ -180,8 +180,8 @@ class CORE_EXPORT LayoutTheme : public RefCounted<LayoutTheme> {
}
virtual void PlatformColorsDidChange();
- void SetCaretBlinkInterval(TimeDelta);
- virtual TimeDelta CaretBlinkInterval() const;
+ void SetCaretBlinkInterval(base::TimeDelta);
+ virtual base::TimeDelta CaretBlinkInterval() const;
// System fonts and colors for CSS.
virtual void SystemFont(CSSValueID system_font_id,
@@ -222,9 +222,9 @@ class CORE_EXPORT LayoutTheme : public RefCounted<LayoutTheme> {
virtual void AdjustProgressBarBounds(ComputedStyle& style) const {}
// Returns the repeat interval of the animation for the progress bar.
- virtual TimeDelta AnimationRepeatIntervalForProgressBar() const;
+ virtual base::TimeDelta AnimationRepeatIntervalForProgressBar() const;
// Returns the duration of the animation for the progress bar.
- virtual TimeDelta AnimationDurationForProgressBar() const;
+ virtual base::TimeDelta AnimationDurationForProgressBar() const;
// Returns size of one slider tick mark for a horizontal track.
// For vertical tracks we rotate it and use it. i.e. Width is always length
@@ -355,7 +355,8 @@ class CORE_EXPORT LayoutTheme : public RefCounted<LayoutTheme> {
Color custom_focus_ring_color_;
bool has_custom_focus_ring_color_;
- TimeDelta caret_blink_interval_ = TimeDelta::FromMilliseconds(500);
+ base::TimeDelta caret_blink_interval_ =
+ base::TimeDelta::FromMilliseconds(500);
// This color is expected to be drawn on a semi-transparent overlay,
// making it more transparent than its alpha value indicates.
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 c29363d6d6b..5d52d091f13 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
@@ -52,7 +52,7 @@ unsigned LayoutThemeDefault::active_selection_foreground_color_ = Color::kBlack;
unsigned LayoutThemeDefault::inactive_selection_background_color_ = 0xffc8c8c8;
unsigned LayoutThemeDefault::inactive_selection_foreground_color_ = 0xff323232;
-TimeDelta LayoutThemeDefault::caret_blink_interval_;
+base::TimeDelta LayoutThemeDefault::caret_blink_interval_;
LayoutThemeDefault::LayoutThemeDefault() : LayoutTheme(), painter_(*this) {
caret_blink_interval_ = LayoutTheme::CaretBlinkInterval();
@@ -73,8 +73,8 @@ bool LayoutThemeDefault::ThemeDrawsFocusRing(const ComputedStyle& style) const {
}
Color LayoutThemeDefault::SystemColor(CSSValueID css_value_id) const {
- static const Color kDefaultButtonGrayColor(0xffdddddd);
- static const Color kDefaultMenuColor(0xfff7f7f7);
+ constexpr Color kDefaultButtonGrayColor(0xffdddddd);
+ constexpr Color kDefaultMenuColor(0xfff7f7f7);
if (css_value_id == CSSValueID::kButtonface) {
if (UseMockTheme())
@@ -94,13 +94,24 @@ String LayoutThemeDefault::ExtraDefaultStyleSheet() {
? GetDataResourceAsASCIIString("input_multiple_fields.css")
: String();
String windows_style_sheet = GetDataResourceAsASCIIString("win.css");
+ String controls_refresh_style_sheet =
+ RuntimeEnabledFeatures::FormControlsRefreshEnabled()
+ ? GetDataResourceAsASCIIString("controls_refresh.css")
+ : String();
+ String forced_colors_style_sheet =
+ RuntimeEnabledFeatures::ForcedColorsEnabled()
+ ? GetDataResourceAsASCIIString("forced_colors.css")
+ : String();
StringBuilder builder;
- builder.ReserveCapacity(extra_style_sheet.length() +
- multiple_fields_style_sheet.length() +
- windows_style_sheet.length());
+ builder.ReserveCapacity(
+ extra_style_sheet.length() + multiple_fields_style_sheet.length() +
+ windows_style_sheet.length() + controls_refresh_style_sheet.length() +
+ forced_colors_style_sheet.length());
builder.Append(extra_style_sheet);
builder.Append(multiple_fields_style_sheet);
builder.Append(windows_style_sheet);
+ builder.Append(controls_refresh_style_sheet);
+ builder.Append(forced_colors_style_sheet);
return builder.ToString();
}
@@ -249,7 +260,7 @@ bool LayoutThemeDefault::SupportsHover(const ComputedStyle& style) const {
}
Color LayoutThemeDefault::PlatformFocusRingColor() const {
- static Color focus_ring_color(229, 151, 0, 255);
+ constexpr Color focus_ring_color(0xFFE59700);
return focus_ring_color;
}
@@ -386,15 +397,16 @@ int LayoutThemeDefault::MenuListInternalPadding(const ComputedStyle& style,
//
// The following values come from the defaults of GTK+.
//
-static const int kProgressAnimationFrames = 10;
-static constexpr TimeDelta kProgressAnimationInterval =
- TimeDelta::FromMilliseconds(125);
+constexpr int kProgressAnimationFrames = 10;
+constexpr base::TimeDelta kProgressAnimationInterval =
+ base::TimeDelta::FromMilliseconds(125);
-TimeDelta LayoutThemeDefault::AnimationRepeatIntervalForProgressBar() const {
+base::TimeDelta LayoutThemeDefault::AnimationRepeatIntervalForProgressBar()
+ const {
return kProgressAnimationInterval;
}
-TimeDelta LayoutThemeDefault::AnimationDurationForProgressBar() const {
+base::TimeDelta LayoutThemeDefault::AnimationDurationForProgressBar() const {
return kProgressAnimationInterval * kProgressAnimationFrames *
2; // "2" for back and forth
}
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_theme_default.h b/chromium/third_party/blink/renderer/core/layout/layout_theme_default.h
index 101509062dd..6fad09eb7ae 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_theme_default.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_theme_default.h
@@ -111,8 +111,8 @@ class CORE_EXPORT LayoutThemeDefault : public LayoutTheme {
void AdjustMenuListStyle(ComputedStyle&, Element*) const override;
void AdjustMenuListButtonStyle(ComputedStyle&, Element*) const override;
- TimeDelta AnimationRepeatIntervalForProgressBar() const override;
- TimeDelta AnimationDurationForProgressBar() const override;
+ base::TimeDelta AnimationRepeatIntervalForProgressBar() const override;
+ base::TimeDelta AnimationDurationForProgressBar() const override;
// These methods define the padding for the MenuList's inner block.
int PopupInternalPaddingStart(const ComputedStyle&) const override;
@@ -145,7 +145,7 @@ class CORE_EXPORT LayoutThemeDefault : public LayoutTheme {
int MenuListInternalPadding(const ComputedStyle&, int padding) const;
static const RGBA32 kDefaultTapHighlightColor = 0x2e000000; // 18% black.
- static TimeDelta caret_blink_interval_;
+ static base::TimeDelta caret_blink_interval_;
static unsigned active_selection_background_color_;
static unsigned active_selection_foreground_color_;
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_theme_font_provider.h b/chromium/third_party/blink/renderer/core/layout/layout_theme_font_provider.h
index 94a5e3a665c..d76f8905dbf 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_theme_font_provider.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_theme_font_provider.h
@@ -29,7 +29,7 @@
#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/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_theme_mac.h b/chromium/third_party/blink/renderer/core/layout/layout_theme_mac.h
index 8ef370251fe..87bd2a9d66d 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_theme_mac.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_theme_mac.h
@@ -86,9 +86,9 @@ class LayoutThemeMac final : public LayoutTheme {
bool PopsMenuBySpaceKey() const final { return true; }
// Returns the repeat interval of the animation for the progress bar.
- TimeDelta AnimationRepeatIntervalForProgressBar() const override;
+ base::TimeDelta AnimationRepeatIntervalForProgressBar() const override;
// Returns the duration of the animation for the progress bar.
- TimeDelta AnimationDurationForProgressBar() const override;
+ base::TimeDelta AnimationDurationForProgressBar() const override;
Color SystemColor(CSSValueID) const override;
@@ -153,8 +153,8 @@ class LayoutThemeMac final : public LayoutTheme {
// We estimate the animation rate of a Mac OS X progress bar is 33 fps.
// Hard code the value here because we haven't found API for it.
- static constexpr TimeDelta kProgressAnimationFrameRate =
- TimeDelta::FromMilliseconds(33);
+ static constexpr base::TimeDelta kProgressAnimationFrameRate =
+ base::TimeDelta::FromMilliseconds(33);
// Mac OS X progress bar animation seems to have 256 frames.
static constexpr double kProgressAnimationNumFrames = 256;
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 501d389dd96..b759ec74d29 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
@@ -678,13 +678,13 @@ const int* LayoutThemeMac::ProgressBarHeights() const {
return kSizes;
}
-constexpr TimeDelta LayoutThemeMac::kProgressAnimationFrameRate;
+constexpr base::TimeDelta LayoutThemeMac::kProgressAnimationFrameRate;
-TimeDelta LayoutThemeMac::AnimationRepeatIntervalForProgressBar() const {
+base::TimeDelta LayoutThemeMac::AnimationRepeatIntervalForProgressBar() const {
return kProgressAnimationFrameRate;
}
-TimeDelta LayoutThemeMac::AnimationDurationForProgressBar() const {
+base::TimeDelta LayoutThemeMac::AnimationDurationForProgressBar() const {
return kProgressAnimationNumFrames * kProgressAnimationFrameRate;
}
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 c2eef23c97d..b699842f991 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
@@ -17,15 +17,14 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/core/testing/page_test_base.h"
#include "third_party/blink/renderer/platform/graphics/color.h"
+#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
namespace blink {
-class LayoutThemeTest : public PageTestBase {
+class LayoutThemeTest : public PageTestBase,
+ private ScopedCSSColorSchemeForTest {
protected:
- void SetUp() override {
- RuntimeEnabledFeatures::SetCSSColorSchemeEnabled(true);
- PageTestBase::SetUp();
- }
+ LayoutThemeTest() : ScopedCSSColorSchemeForTest(true) {}
void SetHtmlInnerHTML(const char* html_content);
};
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 a7ee036bf62..9c20cd4198a 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
@@ -26,6 +26,7 @@
#include "third_party/blink/renderer/core/layout/layout_tree_as_text.h"
#include "third_party/blink/renderer/core/css/css_property_value_set.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/pseudo_element.h"
#include "third_party/blink/renderer/core/editing/frame_selection.h"
@@ -59,6 +60,7 @@
#include "third_party/blink/renderer/core/page/print_context.h"
#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_paint_order_iterator.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/platform/geometry/layout_unit.h"
#include "third_party/blink/renderer/platform/wtf/text/character_names.h"
@@ -303,18 +305,16 @@ void LayoutTreeAsText::WriteLayoutObject(WTF::TextStream& ts,
}
if (behavior & kLayoutAsTextShowIDAndClass) {
- Node* node = o.GetNode();
- if (node && node->IsElementNode()) {
- Element& element = ToElement(*node);
- if (element.HasID())
- ts << " id=\"" + element.GetIdAttribute() + "\"";
+ if (auto* element = DynamicTo<Element>(o.GetNode())) {
+ if (element->HasID())
+ ts << " id=\"" + element->GetIdAttribute() + "\"";
- if (element.HasClass()) {
+ if (element->HasClass()) {
ts << " class=\"";
- for (wtf_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];
+ ts << element->ClassNames()[i];
}
ts << "\"";
}
@@ -357,6 +357,9 @@ void LayoutTreeAsText::WriteLayoutObject(WTF::TextStream& ts,
if (needs_layout)
ts << ")";
}
+
+ if (o.LayoutBlockedByDisplayLock(DisplayLockContext::kChildren))
+ ts << " (display-locked)";
}
static void WriteInlineBox(WTF::TextStream& ts,
@@ -569,11 +572,13 @@ void Write(WTF::TextStream& ts,
}
}
- for (LayoutObject* child = o.SlowFirstChild(); child;
- child = child->NextSibling()) {
- if (child->HasLayer())
- continue;
- Write(ts, *child, indent + 1, behavior);
+ if (!o.LayoutBlockedByDisplayLock(DisplayLockContext::kChildren)) {
+ for (LayoutObject* child = o.SlowFirstChild(); child;
+ child = child->NextSibling()) {
+ if (child->HasLayer())
+ continue;
+ Write(ts, *child, indent + 1, behavior);
+ }
}
if (o.IsLayoutEmbeddedContent()) {
@@ -689,14 +694,12 @@ static void Write(WTF::TextStream& ts,
Write(ts, layer.GetLayoutObject(), indent + 1, behavior);
}
-static PaintLayerStackingNode::PaintLayers NormalFlowListFor(
- PaintLayerStackingNode* node) {
- PaintLayerStackingNode::PaintLayers vector;
- if (node) {
- PaintLayerStackingNodeIterator it(*node, kNormalFlowChildren);
- while (PaintLayer* normal_flow_child = it.Next())
- vector.push_back(normal_flow_child);
- }
+static Vector<PaintLayer*> ChildLayers(const PaintLayer* layer,
+ PaintLayerIteration which_children) {
+ Vector<PaintLayer*> vector;
+ PaintLayerPaintOrderIterator it(*layer, which_children);
+ while (PaintLayer* child = it.Next())
+ vector.push_back(child);
return vector;
}
@@ -743,29 +746,23 @@ void LayoutTreeAsText::WriteLayers(WTF::TextStream& ts,
}
#endif
- bool paints_background_separately = false;
- if (layer->StackingNode()) {
- PaintLayerStackingNode::PaintLayers* neg_list =
- layer->StackingNode()->NegZOrderList();
- paints_background_separately = neg_list && neg_list->size() > 0;
- if (should_paint && paints_background_separately) {
- Write(ts, *layer, layer_bounds, damage_rect.Rect(),
- clip_rect_to_apply.Rect(), kLayerPaintPhaseBackground, indent,
- behavior, marked_layer);
- }
+ const auto& neg_list = ChildLayers(layer, kNegativeZOrderChildren);
+ bool paints_background_separately = !neg_list.IsEmpty();
+ if (should_paint && paints_background_separately) {
+ Write(ts, *layer, layer_bounds, damage_rect.Rect(),
+ clip_rect_to_apply.Rect(), kLayerPaintPhaseBackground, indent,
+ behavior, marked_layer);
+ }
- if (neg_list) {
- int curr_indent = indent;
- if (behavior & kLayoutAsTextShowLayerNesting) {
- WriteIndent(ts, indent);
- ts << " negative z-order list(" << neg_list->size() << ")\n";
- ++curr_indent;
- }
- for (unsigned i = 0; i != neg_list->size(); ++i) {
- WriteLayers(ts, root_layer, neg_list->at(i), curr_indent, behavior,
- marked_layer);
- }
+ if (!neg_list.IsEmpty()) {
+ int curr_indent = indent;
+ if (behavior & kLayoutAsTextShowLayerNesting) {
+ WriteIndent(ts, indent);
+ ts << " negative z-order list(" << neg_list.size() << ")\n";
+ ++curr_indent;
}
+ for (auto* layer : neg_list)
+ WriteLayers(ts, root_layer, layer, curr_indent, behavior, marked_layer);
}
if (should_paint) {
@@ -776,35 +773,28 @@ void LayoutTreeAsText::WriteLayers(WTF::TextStream& ts,
indent, behavior, marked_layer);
}
- if (layer->StackingNode()) {
- PaintLayerStackingNode::PaintLayers normal_flow_list =
- NormalFlowListFor(layer->StackingNode());
- if (!normal_flow_list.IsEmpty()) {
- int curr_indent = indent;
- if (behavior & kLayoutAsTextShowLayerNesting) {
- WriteIndent(ts, indent);
- ts << " normal flow list(" << normal_flow_list.size() << ")\n";
- ++curr_indent;
- }
- for (unsigned i = 0; i != normal_flow_list.size(); ++i) {
- WriteLayers(ts, root_layer, normal_flow_list.at(i), curr_indent,
- behavior, marked_layer);
- }
+ const auto& normal_flow_list = ChildLayers(layer, kNormalFlowChildren);
+ if (!normal_flow_list.IsEmpty()) {
+ int curr_indent = indent;
+ if (behavior & kLayoutAsTextShowLayerNesting) {
+ WriteIndent(ts, indent);
+ ts << " normal flow list(" << normal_flow_list.size() << ")\n";
+ ++curr_indent;
}
+ for (auto* layer : normal_flow_list)
+ WriteLayers(ts, root_layer, layer, curr_indent, behavior, marked_layer);
+ }
- if (PaintLayerStackingNode::PaintLayers* pos_list =
- layer->StackingNode()->PosZOrderList()) {
- int curr_indent = indent;
- if (behavior & kLayoutAsTextShowLayerNesting) {
- WriteIndent(ts, indent);
- ts << " positive z-order list(" << pos_list->size() << ")\n";
- ++curr_indent;
- }
- for (unsigned i = 0; i != pos_list->size(); ++i) {
- WriteLayers(ts, root_layer, pos_list->at(i), curr_indent, behavior,
- marked_layer);
- }
+ const auto& pos_list = ChildLayers(layer, kPositiveZOrderChildren);
+ if (!pos_list.IsEmpty()) {
+ int curr_indent = indent;
+ if (behavior & kLayoutAsTextShowLayerNesting) {
+ WriteIndent(ts, indent);
+ ts << " positive z-order list(" << pos_list.size() << ")\n";
+ ++curr_indent;
}
+ for (auto* layer : pos_list)
+ WriteLayers(ts, root_layer, layer, curr_indent, behavior, marked_layer);
}
}
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 9b46537c3ec..8a0b9514f20 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
@@ -27,7 +27,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_LAYOUT_TREE_AS_TEXT_H_
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "third_party/blink/renderer/platform/wtf/text/text_stream.h"
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 caf52c8d348..9b8d7b6476b 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_view.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_view.cc
@@ -53,7 +53,7 @@
#include "third_party/blink/renderer/core/svg/svg_document_extensions.h"
#include "third_party/blink/renderer/platform/geometry/float_quad.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_controller.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/traced_value.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
@@ -69,11 +69,11 @@ namespace {
class HitTestLatencyRecorder {
public:
HitTestLatencyRecorder(bool allows_child_frame_content)
- : start_(CurrentTimeTicks()),
+ : start_(base::TimeTicks::Now()),
allows_child_frame_content_(allows_child_frame_content) {}
~HitTestLatencyRecorder() {
- TimeDelta duration = CurrentTimeTicks() - start_;
+ base::TimeDelta duration = base::TimeTicks::Now() - start_;
if (allows_child_frame_content_) {
DEFINE_STATIC_LOCAL(CustomCountHistogram, recursive_latency_histogram,
("Event.Latency.HitTestRecursive", 0, 10000000, 100));
@@ -86,7 +86,7 @@ class HitTestLatencyRecorder {
}
private:
- TimeTicks start_;
+ base::TimeTicks start_;
bool allows_child_frame_content_;
};
@@ -96,6 +96,8 @@ LayoutView::LayoutView(Document* document)
: LayoutBlockFlow(document),
frame_view_(document->View()),
layout_state_(nullptr),
+ // TODO(pdr): This should be null if CompositeAfterPaintEnabled() is true.
+ compositor_(std::make_unique<PaintLayerCompositor>(*this)),
layout_quote_head_(nullptr),
layout_counter_count_(0),
hit_test_count_(0),
@@ -155,14 +157,14 @@ bool LayoutView::HitTestNoLifecycleUpdate(const HitTestLocation& location,
result = cache_result;
} else {
LocalFrameView* frame_view = GetFrameView();
- LayoutRect hit_test_area;
+ PhysicalRect hit_test_area;
if (frame_view) {
// Start with a rect sized to the frame, to ensure we include the
// scrollbars.
- hit_test_area = LayoutRect(LayoutPoint(), LayoutSize(frame_view->Size()));
+ hit_test_area.size = PhysicalSize(frame_view->Size());
if (result.GetHitTestRequest().IgnoreClipping()) {
hit_test_area.Unite(
- frame_view->DocumentToFrame(LayoutRect(DocumentRect())));
+ frame_view->DocumentToFrame(PhysicalRect(DocumentRect())));
}
}
@@ -783,13 +785,15 @@ void LayoutView::UpdateAfterLayout() {
}
void LayoutView::UpdateHitTestResult(HitTestResult& result,
- const LayoutPoint& point) const {
+ const PhysicalOffset& point) const {
if (result.InnerNode())
return;
Node* node = GetDocument().documentElement();
if (node) {
- LayoutPoint adjusted_point = point;
+ PhysicalOffset adjusted_point = point;
+ if (const auto* layout_box = node->GetLayoutBox())
+ adjusted_point -= layout_box->PhysicalLocation();
OffsetForContents(adjusted_point);
result.SetNodeAndPosition(node, adjusted_point);
}
@@ -800,15 +804,13 @@ bool LayoutView::UsesCompositing() const {
}
PaintLayerCompositor* LayoutView::Compositor() {
- if (!compositor_)
- compositor_ = std::make_unique<PaintLayerCompositor>(*this);
-
+ DCHECK(compositor_);
return compositor_.get();
}
-void LayoutView::SetIsInWindow(bool is_in_window) {
- if (compositor_)
- compositor_->SetIsInWindow(is_in_window);
+void LayoutView::CleanUpCompositor() {
+ DCHECK(compositor_);
+ compositor_->CleanUp();
}
IntervalArena* LayoutView::GetIntervalArena() {
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 fd7f8d540b3..ca4d4bb5728 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_view.h
+++ b/chromium/third_party/blink/renderer/core/layout/layout_view.h
@@ -59,8 +59,13 @@ class CORE_EXPORT LayoutView final : public LayoutBlockFlow {
public:
explicit LayoutView(Document*);
~LayoutView() override;
+
void WillBeDestroyed() override;
+ // Called when the Document is shutdown, to have the compositor clean up
+ // during frame detach, while pointers remain valid.
+ void CleanUpCompositor();
+
// hitTest() will update layout, style and compositing first while
// hitTestNoLifecycleUpdate() does not.
bool HitTest(const HitTestLocation& location, HitTestResult&);
@@ -173,7 +178,8 @@ class CORE_EXPORT LayoutView final : public LayoutBlockFlow {
LayoutState* GetLayoutState() const { return layout_state_; }
- void UpdateHitTestResult(HitTestResult&, const LayoutPoint&) const override;
+ void UpdateHitTestResult(HitTestResult&,
+ const PhysicalOffset&) const override;
ViewFragmentationContext* FragmentationContext() const {
return fragmentation_context_.get();
@@ -184,9 +190,6 @@ class CORE_EXPORT LayoutView final : public LayoutBlockFlow {
page_logical_height_ = height;
}
- // Notification that this view moved into or out of a native window.
- void SetIsInWindow(bool);
-
PaintLayerCompositor* Compositor();
bool UsesCompositing() const;
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 ad3694fca3b..e42db57fe42 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
@@ -13,29 +13,13 @@
namespace blink {
-class LayoutViewTest : public testing::WithParamInterface<bool>,
- private ScopedLayoutNGForTest,
- public RenderingTest {
+class LayoutViewTest : public RenderingTest {
public:
LayoutViewTest()
- : ScopedLayoutNGForTest(LayoutNG()),
- RenderingTest(MakeGarbageCollected<SingleChildLocalFrameClient>()) {}
-
- protected:
- bool LayoutNG() { return GetParam(); }
- bool LayoutNGOrAndroidOrWindows() {
- // TODO(crbug.com/966731): Why is the platform difference?
-#if defined(OS_WIN) || defined(OS_ANDROID)
- return true;
-#else
- return LayoutNG();
-#endif
- }
+ : RenderingTest(MakeGarbageCollected<SingleChildLocalFrameClient>()) {}
};
-INSTANTIATE_TEST_SUITE_P(All, LayoutViewTest, testing::Bool());
-
-TEST_P(LayoutViewTest, UpdateCountersLayout) {
+TEST_F(LayoutViewTest, UpdateCountersLayout) {
SetBodyInnerHTML(R"HTML(
<style>
div.incX { counter-increment: x }
@@ -58,7 +42,7 @@ TEST_P(LayoutViewTest, UpdateCountersLayout) {
EXPECT_TRUE(GetDocument().View()->NeedsLayout());
}
-TEST_P(LayoutViewTest, DisplayNoneFrame) {
+TEST_F(LayoutViewTest, DisplayNoneFrame) {
SetBodyInnerHTML(R"HTML(
<iframe id="iframe" style="display:none"></iframe>
)HTML");
@@ -72,19 +56,61 @@ TEST_P(LayoutViewTest, DisplayNoneFrame) {
LayoutObject* view = frame_doc->GetLayoutView();
ASSERT_TRUE(view);
EXPECT_FALSE(view->CanHaveChildren());
+ EXPECT_FALSE(frame_doc->documentElement()->GetComputedStyle());
frame_doc->body()->SetInnerHTMLFromString(R"HTML(
<div id="div"></div>
)HTML");
- frame_doc->Lifecycle().AdvanceTo(DocumentLifecycle::kInStyleRecalc);
- frame_doc->GetStyleEngine().RecalcStyle({});
-
- Element* div = frame_doc->getElementById("div");
- EXPECT_FALSE(div->GetComputedStyle());
+ EXPECT_FALSE(frame_doc->NeedsLayoutTreeUpdate());
}
-TEST_P(LayoutViewTest, HitTestHorizontal) {
+struct HitTestConfig {
+ bool layout_ng;
+ EditingBehaviorType editing_behavior;
+};
+
+class LayoutViewHitTestTest : public testing::WithParamInterface<HitTestConfig>,
+ private ScopedLayoutNGForTest,
+ public RenderingTest {
+ public:
+ LayoutViewHitTestTest()
+ : ScopedLayoutNGForTest(LayoutNG()),
+ RenderingTest(MakeGarbageCollected<SingleChildLocalFrameClient>()) {}
+
+ protected:
+ bool LayoutNG() { return GetParam().layout_ng; }
+ bool IsAndroidOrWindowsEditingBehavior() {
+ // TODO(crbug.com/971414): For now LayoutNG always uses Android/Windows
+ // behavior for ShouldMoveCaretToHorizontalBoundaryWhenPastTopOrBottom().
+ if (LayoutNG())
+ return true;
+ return GetParam().editing_behavior == kEditingAndroidBehavior ||
+ GetParam().editing_behavior == kEditingWindowsBehavior;
+ }
+
+ void SetUp() override {
+ RenderingTest::SetUp();
+ GetFrame().GetSettings()->SetEditingBehaviorType(
+ GetParam().editing_behavior);
+ }
+};
+
+INSTANTIATE_TEST_SUITE_P(All,
+ LayoutViewHitTestTest,
+ ::testing::Values(
+ // Legacy
+ HitTestConfig{false, kEditingMacBehavior},
+ HitTestConfig{false, kEditingWindowsBehavior},
+ HitTestConfig{false, kEditingUnixBehavior},
+ HitTestConfig{false, kEditingAndroidBehavior},
+ // LayoutNG
+ HitTestConfig{true, kEditingMacBehavior},
+ HitTestConfig{true, kEditingWindowsBehavior},
+ HitTestConfig{true, kEditingUnixBehavior},
+ HitTestConfig{true, kEditingAndroidBehavior}));
+
+TEST_P(LayoutViewHitTestTest, HitTestHorizontal) {
LoadAhem();
SetBodyInnerHTML(R"HTML(
<style>body { margin: 0 }</style>
@@ -111,89 +137,95 @@ TEST_P(LayoutViewTest, HitTestHorizontal) {
HitTestResult result;
// In body, but not in any descendants.
- GetLayoutView().HitTest(HitTestLocation(LayoutPoint(1, 1)), result);
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(1, 1)), result);
EXPECT_EQ(GetDocument().body(), result.InnerNode());
- EXPECT_EQ(LayoutPoint(1, 1), result.LocalPoint());
+ EXPECT_EQ(PhysicalOffset(1, 1), result.LocalPoint());
EXPECT_EQ(PositionWithAffinity(Position(text1, 0), TextAffinity::kDownstream),
result.GetPosition());
// Top-left corner of div and span1.
- GetLayoutView().HitTest(HitTestLocation(LayoutPoint(51, 101)), result);
+ result = HitTestResult();
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(51, 101)), result);
EXPECT_EQ(text1, result.InnerNode());
- EXPECT_EQ(LayoutPoint(1, 1), result.LocalPoint());
+ EXPECT_EQ(PhysicalOffset(1, 1), result.LocalPoint());
EXPECT_EQ(PositionWithAffinity(Position(text1, 0), TextAffinity::kDownstream),
result.GetPosition());
// Top-right corner (outside) of div.
- GetLayoutView().HitTest(HitTestLocation(LayoutPoint(251, 101)), result);
+ result = HitTestResult();
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(251, 101)), result);
EXPECT_EQ(GetDocument().documentElement(), result.InnerNode());
- EXPECT_EQ(LayoutPoint(251, 101), result.LocalPoint());
+ EXPECT_EQ(PhysicalOffset(251, 101), result.LocalPoint());
EXPECT_EQ(PositionWithAffinity(Position(text2, 3), TextAffinity::kUpstream),
result.GetPosition());
// Top-right corner (inside) of div.
- GetLayoutView().HitTest(HitTestLocation(LayoutPoint(249, 101)), result);
+ result = HitTestResult();
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(249, 101)), result);
EXPECT_EQ(div, result.InnerNode());
- EXPECT_EQ(LayoutPoint(199, 1), result.LocalPoint());
+ EXPECT_EQ(PhysicalOffset(199, 1), result.LocalPoint());
EXPECT_EQ(PositionWithAffinity(Position(text2, 3), TextAffinity::kUpstream),
result.GetPosition());
// Top-right corner (inside) of span1.
- GetLayoutView().HitTest(HitTestLocation(LayoutPoint(99, 101)), result);
+ result = HitTestResult();
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(99, 101)), result);
EXPECT_EQ(text1, result.InnerNode());
- EXPECT_EQ(LayoutPoint(49, 1), result.LocalPoint());
+ EXPECT_EQ(PhysicalOffset(49, 1), result.LocalPoint());
EXPECT_EQ(PositionWithAffinity(Position(text1, 5), TextAffinity::kUpstream),
result.GetPosition());
// Top-right corner (outside) of span1.
- GetLayoutView().HitTest(HitTestLocation(LayoutPoint(101, 101)), result);
+ result = HitTestResult();
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(101, 101)), result);
EXPECT_EQ(div, result.InnerNode());
- EXPECT_EQ(LayoutPoint(51, 1), result.LocalPoint());
+ EXPECT_EQ(PhysicalOffset(51, 1), result.LocalPoint());
EXPECT_EQ(PositionWithAffinity(Position(text2, 0), TextAffinity::kDownstream),
result.GetPosition());
// Bottom-left corner (outside) of div.
- GetLayoutView().HitTest(HitTestLocation(LayoutPoint(51, 181)), result);
+ result = HitTestResult();
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(51, 181)), result);
EXPECT_EQ(GetDocument().documentElement(), result.InnerNode());
- EXPECT_EQ(LayoutPoint(51, 181), result.LocalPoint());
- // TODO(crbug.com/966731): Verify if the difference reflects any issue.
+ EXPECT_EQ(PhysicalOffset(51, 181), result.LocalPoint());
EXPECT_EQ(
- LayoutNGOrAndroidOrWindows()
+ IsAndroidOrWindowsEditingBehavior()
? PositionWithAffinity(Position(text1, 0), TextAffinity::kDownstream)
: PositionWithAffinity(Position(text2, 3), TextAffinity::kDownstream),
result.GetPosition());
// Bottom-left corner (inside) of div.
- GetLayoutView().HitTest(HitTestLocation(LayoutPoint(51, 179)), result);
+ result = HitTestResult();
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(51, 179)), result);
EXPECT_EQ(div, result.InnerNode());
- EXPECT_EQ(LayoutPoint(1, 79), result.LocalPoint());
- // TODO(crbug.com/966731): Verify if the difference reflects any issue.
+ EXPECT_EQ(PhysicalOffset(1, 79), result.LocalPoint());
EXPECT_EQ(
- LayoutNGOrAndroidOrWindows()
+ IsAndroidOrWindowsEditingBehavior()
? PositionWithAffinity(Position(text1, 0), TextAffinity::kDownstream)
: PositionWithAffinity(Position(text2, 3), TextAffinity::kDownstream),
result.GetPosition());
// Bottom-left corner (outside) of span1.
- GetLayoutView().HitTest(HitTestLocation(LayoutPoint(51, 111)), result);
+ result = HitTestResult();
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(51, 111)), result);
EXPECT_EQ(div, result.InnerNode());
- EXPECT_EQ(LayoutPoint(1, 11), result.LocalPoint());
- // TODO(crbug.com/966731): Verify if the difference reflects any issue.
+ EXPECT_EQ(PhysicalOffset(1, 11), result.LocalPoint());
EXPECT_EQ(
- LayoutNGOrAndroidOrWindows()
+ IsAndroidOrWindowsEditingBehavior()
? PositionWithAffinity(Position(text1, 0), TextAffinity::kDownstream)
: PositionWithAffinity(Position(text2, 3), TextAffinity::kDownstream),
result.GetPosition());
// Top-left corner of span2.
- GetLayoutView().HitTest(HitTestLocation(LayoutPoint(101, 131)), result);
+ result = HitTestResult();
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(101, 131)), result);
EXPECT_EQ(text2, result.InnerNode());
- EXPECT_EQ(LayoutPoint(51, 1), result.LocalPoint());
+ EXPECT_EQ(PhysicalOffset(51, 1), result.LocalPoint());
EXPECT_EQ(PositionWithAffinity(Position(text2, 0), TextAffinity::kDownstream),
result.GetPosition());
}
-TEST_P(LayoutViewTest, HitTestVerticalLR) {
+TEST_P(LayoutViewHitTestTest, HitTestVerticalLR) {
LoadAhem();
SetBodyInnerHTML(R"HTML(
<style>body { margin: 0 }</style>
@@ -223,82 +255,87 @@ TEST_P(LayoutViewTest, HitTestVerticalLR) {
HitTestResult result;
// In body, but not in any descendants.
- GetLayoutView().HitTest(HitTestLocation(LayoutPoint(1, 1)), result);
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(1, 1)), result);
EXPECT_EQ(GetDocument().body(), result.InnerNode());
- EXPECT_EQ(LayoutPoint(1, 1), result.LocalPoint());
+ EXPECT_EQ(PhysicalOffset(1, 1), result.LocalPoint());
EXPECT_EQ(PositionWithAffinity(Position(text1, 0), TextAffinity::kDownstream),
result.GetPosition());
// Top-left corner of div and span1.
- GetLayoutView().HitTest(HitTestLocation(LayoutPoint(51, 101)), result);
+ result = HitTestResult();
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(51, 101)), result);
EXPECT_EQ(text1, result.InnerNode());
- EXPECT_EQ(LayoutPoint(1, 1), result.LocalPoint());
+ EXPECT_EQ(PhysicalOffset(1, 1), result.LocalPoint());
EXPECT_EQ(PositionWithAffinity(Position(text1, 0), TextAffinity::kDownstream),
result.GetPosition());
// Top-right corner (outside) of div.
- GetLayoutView().HitTest(HitTestLocation(LayoutPoint(251, 101)), result);
+ result = HitTestResult();
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(251, 101)), result);
EXPECT_EQ(GetDocument().documentElement(), result.InnerNode());
- EXPECT_EQ(LayoutPoint(251, 101), result.LocalPoint());
- // TODO(crbug.com/966731): Verify if the difference reflects any issue.
+ EXPECT_EQ(PhysicalOffset(251, 101), result.LocalPoint());
EXPECT_EQ(
- LayoutNGOrAndroidOrWindows()
+ IsAndroidOrWindowsEditingBehavior()
? PositionWithAffinity(Position(text1, 0), TextAffinity::kDownstream)
: PositionWithAffinity(Position(text2, 3), TextAffinity::kDownstream),
result.GetPosition());
// Top-right corner (inside) of div.
- GetLayoutView().HitTest(HitTestLocation(LayoutPoint(249, 101)), result);
+ result = HitTestResult();
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(249, 101)), result);
EXPECT_EQ(div, result.InnerNode());
- EXPECT_EQ(LayoutPoint(199, 1), result.LocalPoint());
- // TODO(crbug.com/966731): Verify if the difference reflects any issue.
+ EXPECT_EQ(PhysicalOffset(199, 1), result.LocalPoint());
EXPECT_EQ(
- LayoutNGOrAndroidOrWindows()
+ IsAndroidOrWindowsEditingBehavior()
? PositionWithAffinity(Position(text1, 0), TextAffinity::kDownstream)
: PositionWithAffinity(Position(text2, 3), TextAffinity::kDownstream),
result.GetPosition());
// Top-right corner (inside) of span1.
- GetLayoutView().HitTest(HitTestLocation(LayoutPoint(59, 101)), result);
+ result = HitTestResult();
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(59, 101)), result);
EXPECT_EQ(text1, result.InnerNode());
- EXPECT_EQ(LayoutPoint(9, 1), result.LocalPoint());
+ EXPECT_EQ(PhysicalOffset(9, 1), result.LocalPoint());
EXPECT_EQ(PositionWithAffinity(Position(text1, 0), TextAffinity::kDownstream),
result.GetPosition());
// Top-right corner (outside) of span1.
- GetLayoutView().HitTest(HitTestLocation(LayoutPoint(61, 101)), result);
+ result = HitTestResult();
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(61, 101)), result);
EXPECT_EQ(div, result.InnerNode());
- EXPECT_EQ(LayoutPoint(11, 1), result.LocalPoint());
- // TODO(crbug.com/966731): Verify if the difference reflects any issue.
+ EXPECT_EQ(PhysicalOffset(11, 1), result.LocalPoint());
EXPECT_EQ(
- LayoutNGOrAndroidOrWindows()
+ IsAndroidOrWindowsEditingBehavior()
? PositionWithAffinity(Position(text1, 0), TextAffinity::kDownstream)
: PositionWithAffinity(Position(text2, 3), TextAffinity::kDownstream),
result.GetPosition());
// Bottom-left corner (outside) of span1.
- GetLayoutView().HitTest(HitTestLocation(LayoutPoint(51, 181)), result);
+ result = HitTestResult();
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(51, 181)), result);
EXPECT_EQ(GetDocument().documentElement(), result.InnerNode());
- EXPECT_EQ(LayoutPoint(51, 181), result.LocalPoint());
+ EXPECT_EQ(PhysicalOffset(51, 181), result.LocalPoint());
EXPECT_EQ(PositionWithAffinity(Position(text2, 3), TextAffinity::kUpstream),
result.GetPosition());
// Bottom-left corner (inside) of span1.
- GetLayoutView().HitTest(HitTestLocation(LayoutPoint(51, 179)), result);
+ result = HitTestResult();
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(51, 179)), result);
EXPECT_EQ(div, result.InnerNode());
- EXPECT_EQ(LayoutPoint(1, 79), result.LocalPoint());
+ EXPECT_EQ(PhysicalOffset(1, 79), result.LocalPoint());
EXPECT_EQ(PositionWithAffinity(Position(text2, 3), TextAffinity::kUpstream),
result.GetPosition());
// Top-left corner of span2.
- GetLayoutView().HitTest(HitTestLocation(LayoutPoint(81, 151)), result);
+ result = HitTestResult();
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(81, 151)), result);
EXPECT_EQ(text2, result.InnerNode());
- EXPECT_EQ(LayoutPoint(1, 51), result.LocalPoint());
+ EXPECT_EQ(PhysicalOffset(1, 51), result.LocalPoint());
EXPECT_EQ(PositionWithAffinity(Position(text2, 0), TextAffinity::kDownstream),
result.GetPosition());
}
-TEST_P(LayoutViewTest, HitTestVerticalRL) {
+TEST_P(LayoutViewHitTestTest, HitTestVerticalRL) {
LoadAhem();
SetBodyInnerHTML(R"HTML(
<style>body { margin: 0 }</style>
@@ -328,86 +365,186 @@ TEST_P(LayoutViewTest, HitTestVerticalRL) {
HitTestResult result;
// In body, but not in any descendants.
- GetLayoutView().HitTest(HitTestLocation(LayoutPoint(1, 1)), result);
+ // XXX1
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(1, 1)), result);
EXPECT_EQ(GetDocument().body(), result.InnerNode());
- EXPECT_EQ(LayoutPoint(1, 1), result.LocalPoint());
- EXPECT_EQ(PositionWithAffinity(Position(text1, 0), TextAffinity::kDownstream),
- result.GetPosition());
+ EXPECT_EQ(PhysicalOffset(1, 1), result.LocalPoint());
+ EXPECT_EQ(
+ IsAndroidOrWindowsEditingBehavior()
+ ? PositionWithAffinity(Position(text1, 0), TextAffinity::kDownstream)
+ : PositionWithAffinity(Position(text2, 3), TextAffinity::kDownstream),
+ result.GetPosition());
// Top-left corner of div.
- GetLayoutView().HitTest(HitTestLocation(LayoutPoint(51, 101)), result);
+ result = HitTestResult();
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(51, 101)), result);
EXPECT_EQ(div, result.InnerNode());
- EXPECT_EQ(LayoutPoint(199, 1), result.LocalPoint());
- // TODO(crbug.com/966731): Verify if the difference reflects any issue.
+ EXPECT_EQ(PhysicalOffset(1, 1), result.LocalPoint());
EXPECT_EQ(
- LayoutNGOrAndroidOrWindows()
+ IsAndroidOrWindowsEditingBehavior()
? PositionWithAffinity(Position(text1, 0), TextAffinity::kDownstream)
: PositionWithAffinity(Position(text2, 3), TextAffinity::kDownstream),
result.GetPosition());
// Top-right corner (outside) of div.
- GetLayoutView().HitTest(HitTestLocation(LayoutPoint(251, 101)), result);
+ result = HitTestResult();
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(251, 101)), result);
EXPECT_EQ(GetDocument().documentElement(), result.InnerNode());
- EXPECT_EQ(LayoutPoint(251, 101), result.LocalPoint());
- // TODO(crbug.com/966731): Verify if the difference reflects any issue.
- EXPECT_EQ(
- LayoutNGOrAndroidOrWindows()
- ? PositionWithAffinity(Position(text1, 0), TextAffinity::kDownstream)
- : PositionWithAffinity(Position(text2, 3), TextAffinity::kDownstream),
- result.GetPosition());
+ EXPECT_EQ(PhysicalOffset(251, 101), result.LocalPoint());
+ EXPECT_EQ(PositionWithAffinity(Position(text1, 0), TextAffinity::kDownstream),
+ result.GetPosition());
// Top-right corner (inside) of div and span1.
- GetLayoutView().HitTest(HitTestLocation(LayoutPoint(249, 101)), result);
+ result = HitTestResult();
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(249, 101)), result);
EXPECT_EQ(text1, result.InnerNode());
- EXPECT_EQ(LayoutPoint(1, 1), result.LocalPoint());
+ EXPECT_EQ(PhysicalOffset(199, 1), result.LocalPoint());
EXPECT_EQ(PositionWithAffinity(Position(text1, 0), TextAffinity::kDownstream),
result.GetPosition());
// Bottom-right corner (inside) of span1.
- GetLayoutView().HitTest(HitTestLocation(LayoutPoint(249, 149)), result);
+ result = HitTestResult();
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(249, 149)), result);
EXPECT_EQ(text1, result.InnerNode());
- EXPECT_EQ(LayoutPoint(1, 49), result.LocalPoint());
+ EXPECT_EQ(PhysicalOffset(199, 49), result.LocalPoint());
EXPECT_EQ(PositionWithAffinity(Position(text1, 5), TextAffinity::kUpstream),
result.GetPosition());
// Bottom-right corner (outside) of span1 but inside of div.
- GetLayoutView().HitTest(HitTestLocation(LayoutPoint(249, 151)), result);
+ result = HitTestResult();
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(249, 151)), result);
EXPECT_EQ(div, result.InnerNode());
- EXPECT_EQ(LayoutPoint(1, 51), result.LocalPoint());
+ EXPECT_EQ(PhysicalOffset(199, 51), result.LocalPoint());
EXPECT_EQ(PositionWithAffinity(Position(text2, 0), TextAffinity::kDownstream),
result.GetPosition());
// Bottom-left corner (outside) of div.
- GetLayoutView().HitTest(HitTestLocation(LayoutPoint(51, 181)), result);
+ // XXX2
+ result = HitTestResult();
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(51, 181)), result);
EXPECT_EQ(GetDocument().documentElement(), result.InnerNode());
- EXPECT_EQ(LayoutPoint(51, 181), result.LocalPoint());
- EXPECT_EQ(PositionWithAffinity(Position(text2, 3), TextAffinity::kUpstream),
- result.GetPosition());
+ EXPECT_EQ(PhysicalOffset(51, 181), result.LocalPoint());
+ EXPECT_EQ(
+ IsAndroidOrWindowsEditingBehavior()
+ ? PositionWithAffinity(Position(text2, 3), TextAffinity::kUpstream)
+ : PositionWithAffinity(Position(text2, 3), TextAffinity::kDownstream),
+ result.GetPosition());
// Bottom-left corner (inside) of div.
- GetLayoutView().HitTest(HitTestLocation(LayoutPoint(51, 179)), result);
+ result = HitTestResult();
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(51, 179)), result);
EXPECT_EQ(div, result.InnerNode());
- EXPECT_EQ(LayoutPoint(199, 79), result.LocalPoint());
- // TODO(crbug.com/966731): Verify if the difference reflects any issue.
+ EXPECT_EQ(PhysicalOffset(1, 79), result.LocalPoint());
EXPECT_EQ(
- LayoutNGOrAndroidOrWindows()
+ IsAndroidOrWindowsEditingBehavior()
? PositionWithAffinity(Position(text2, 3), TextAffinity::kUpstream)
: PositionWithAffinity(Position(text2, 3), TextAffinity::kDownstream),
result.GetPosition());
// Bottom-left corner (outside) of span1.
- GetLayoutView().HitTest(HitTestLocation(LayoutPoint(241, 151)), result);
+ result = HitTestResult();
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(241, 151)), result);
EXPECT_EQ(div, result.InnerNode());
- EXPECT_EQ(LayoutPoint(9, 51), result.LocalPoint());
+ EXPECT_EQ(PhysicalOffset(191, 51), result.LocalPoint());
EXPECT_EQ(PositionWithAffinity(Position(text2, 0), TextAffinity::kDownstream),
result.GetPosition());
// Top-right corner (inside) of span2.
- GetLayoutView().HitTest(HitTestLocation(LayoutPoint(219, 151)), result);
+ result = HitTestResult();
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(219, 151)), result);
EXPECT_EQ(text2, result.InnerNode());
- EXPECT_EQ(LayoutPoint(1, 51), result.LocalPoint());
+ EXPECT_EQ(PhysicalOffset(199, 51), result.LocalPoint());
EXPECT_EQ(PositionWithAffinity(Position(text2, 0), TextAffinity::kDownstream),
result.GetPosition());
}
+TEST_P(LayoutViewHitTestTest, HitTestVerticalRLRoot) {
+ LoadAhem();
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ html { writing-mode: vertical-rl; }
+ body { margin: 0 }
+ </style>
+ <div id="div" style="font: 10px/10px Ahem; width: 200px; height: 80px">
+ <span id="span">ABCDE</span>
+ </div>
+ )HTML");
+
+ // (0,0) (600, 0) (800, 0)
+ // +----...----+---------------+
+ // | | A|
+ // | | B|
+ // | | C|
+ // | | (div) D|
+ // | (screen) | E|
+ // | | |
+ // | | |
+ // | +---------------+ (800, 80)
+ // | (600, 80) |
+ // . .
+ // +----...--------------------+ (800, 600)
+
+ auto* div = GetDocument().getElementById("div");
+ auto* text = GetDocument().getElementById("span")->firstChild();
+ HitTestResult result;
+ // Not in any element. Should fallback to documentElement.
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(1, 1)), result);
+ EXPECT_EQ(GetDocument().documentElement(), result.InnerNode());
+ EXPECT_EQ(PhysicalOffset(-599, 1), result.LocalPoint());
+ EXPECT_EQ(
+ IsAndroidOrWindowsEditingBehavior()
+ ? PositionWithAffinity(Position(text, 0), TextAffinity::kDownstream)
+ : PositionWithAffinity(Position(text, 5), TextAffinity::kDownstream),
+ result.GetPosition());
+
+ // Top-left corner (inside) of div.
+ result = HitTestResult();
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(601, 1)), result);
+ EXPECT_EQ(div, result.InnerNode());
+ EXPECT_EQ(PhysicalOffset(1, 1), result.LocalPoint());
+ EXPECT_EQ(
+ IsAndroidOrWindowsEditingBehavior()
+ ? PositionWithAffinity(Position(text, 0), TextAffinity::kDownstream)
+ : PositionWithAffinity(Position(text, 5), TextAffinity::kDownstream),
+ result.GetPosition());
+
+ // Top-right corner (outside) of div. Should fallback to documentElement.
+ result = HitTestResult();
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(801, 1)), result);
+ EXPECT_EQ(GetDocument().documentElement(), result.InnerNode());
+ EXPECT_EQ(PhysicalOffset(201, 1), result.LocalPoint());
+ EXPECT_EQ(
+ IsAndroidOrWindowsEditingBehavior()
+ ? PositionWithAffinity(Position(text, 0), TextAffinity::kDownstream)
+ : PositionWithAffinity(Position(text, 0), TextAffinity::kDownstream),
+ result.GetPosition());
+
+ // Top-right corner (inside) of div and span.
+ result = HitTestResult();
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(799, 1)), result);
+ EXPECT_EQ(text, result.InnerNode());
+ EXPECT_EQ(PhysicalOffset(199, 1), result.LocalPoint());
+ EXPECT_EQ(PositionWithAffinity(Position(text, 0), TextAffinity::kDownstream),
+ result.GetPosition());
+
+ // Bottom-right corner (outside) of span1 but inside of div.
+ result = HitTestResult();
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(799, 51)), result);
+ EXPECT_EQ(div, result.InnerNode());
+ EXPECT_EQ(PhysicalOffset(199, 51), result.LocalPoint());
+ EXPECT_EQ(PositionWithAffinity(Position(text, 5), TextAffinity::kUpstream),
+ result.GetPosition());
+
+ // Bottom-left corner (outside) of div.
+ result = HitTestResult();
+ GetLayoutView().HitTest(HitTestLocation(PhysicalOffset(599, 81)), result);
+ EXPECT_EQ(GetDocument().documentElement(), result.InnerNode());
+ EXPECT_EQ(PhysicalOffset(-1, 81), result.LocalPoint());
+ EXPECT_EQ(
+ IsAndroidOrWindowsEditingBehavior()
+ ? PositionWithAffinity(Position(text, 5), TextAffinity::kUpstream)
+ : PositionWithAffinity(Position(text, 5), TextAffinity::kDownstream),
+ result.GetPosition());
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/layout_vtt_cue.cc b/chromium/third_party/blink/renderer/core/layout/layout_vtt_cue.cc
index 722895a6a52..fa49a3ec625 100644
--- a/chromium/third_party/blink/renderer/core/layout/layout_vtt_cue.cc
+++ b/chromium/third_party/blink/renderer/core/layout/layout_vtt_cue.cc
@@ -117,27 +117,16 @@ LayoutUnit SnapToLinesLayouter::ComputeInitialPositionAdjustment(
// are relative to the same coordinate space. If we didn't the (bounding) boxes
// could be affect by transforms on an ancestor et.c, which could yield
// incorrect results.
-IntRect ContentBoxRelativeToAncestor(const LayoutBox& box,
- const LayoutBoxModelObject& ancestor) {
- PhysicalRect cue_content_box = box.PhysicalContentBoxRect();
+IntRect BorderBoxRelativeToAncestor(const LayoutBox& box,
+ const LayoutBoxModelObject& ancestor) {
+ PhysicalRect border_box = box.PhysicalBorderBoxRect();
// We pass UseTransforms here primarily because we use a transform for
// non-snap-to-lines positioning (see VTTCue.cpp.)
- return EnclosingIntRect(box.LocalToAncestorRect(cue_content_box, &ancestor));
-}
-
-// Similar to above except uses the full bounding box instead of just the
-// context box (which ignores padding). This is used for the timeline since the
-// timeline is mostly padding.
-IntRect PaddingBoxRelativeToAncestor(const LayoutBox& box,
- const LayoutBoxModelObject& ancestor) {
- PhysicalRect cue_content_box = box.PhysicalPaddingBoxRect();
- // We pass UseTransforms here primarily because we use a transform for
- // non-snap-to-lines positioning (see VTTCue.cpp.)
- return EnclosingIntRect(box.LocalToAncestorRect(cue_content_box, &ancestor));
+ return EnclosingIntRect(box.LocalToAncestorRect(border_box, &ancestor));
}
IntRect CueBoundingBox(const LayoutBox& cue_box) {
- return ContentBoxRelativeToAncestor(cue_box, *cue_box.ContainingBlock());
+ return BorderBoxRelativeToAncestor(cue_box, *cue_box.ContainingBlock());
}
bool SnapToLinesLayouter::IsOutside(const IntRect& title_area) const {
@@ -232,7 +221,7 @@ void SnapToLinesLayouter::UpdateLayout() {
// rendering area except for a width of margin at the left of the rendering
// area and a width of margin at the right of the rendering area.
IntRect title_area =
- EnclosingIntRect(cue_box_.ContainingBlock()->PhysicalContentBoxRect());
+ EnclosingIntRect(cue_box_.ContainingBlock()->PhysicalBorderBoxRect());
if (blink::IsHorizontalWritingMode(writing_mode)) {
title_area.Move(0, margin.ToInt());
title_area.Contract(0, (2 * margin).ToInt());
@@ -359,10 +348,10 @@ IntRect LayoutVTTCue::ComputeControlsRect() const {
return IntRect();
}
- IntRect button_panel_box = ContentBoxRelativeToAncestor(
+ IntRect button_panel_box = BorderBoxRelativeToAncestor(
ToLayoutBox(*button_panel_layout_object),
ToLayoutBox(*controls->ContainerLayoutObject()));
- IntRect timeline_box = PaddingBoxRelativeToAncestor(
+ IntRect timeline_box = BorderBoxRelativeToAncestor(
ToLayoutBox(*timeline_layout_object),
ToLayoutBox(*controls->ContainerLayoutObject()));
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 bb4763cb437..982f459df05 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
@@ -45,7 +45,7 @@
#include "third_party/blink/renderer/platform/fonts/character_range.h"
#include "third_party/blink/renderer/platform/text/hyphenation.h"
#include "third_party/blink/renderer/platform/text/text_break_iterator.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
@@ -533,8 +533,14 @@ inline void BreakingContext::HandleFloat() {
// early by skipTrailingWhitespace(), and later on they all get placed by
// the first float here in handleFloat(). Their position may then be wrong,
// but it's too late to do anything about that now. See crbug.com/671577
- if (!floating_object->IsPlaced())
- block_.PositionAndLayoutFloat(*floating_object, block_.LogicalHeight());
+ if (!floating_object->IsPlaced()) {
+ LayoutUnit logical_top = block_.LogicalHeight();
+ if (const FloatingObject* last_placed_float = block_.LastPlacedFloat()) {
+ logical_top = std::max(logical_top,
+ block_.LogicalTopForFloat(*last_placed_float));
+ }
+ block_.PositionAndLayoutFloat(*floating_object, logical_top);
+ }
// Check if it fits in the current line; if it does, place it now,
// otherwise, place it after moving to next line (in newLine() func).
diff --git a/chromium/third_party/blink/renderer/core/layout/line/ellipsis_box.cc b/chromium/third_party/blink/renderer/core/layout/line/ellipsis_box.cc
index 416e2791354..0dc0d846ea7 100644
--- a/chromium/third_party/blink/renderer/core/layout/line/ellipsis_box.cc
+++ b/chromium/third_party/blink/renderer/core/layout/line/ellipsis_box.cc
@@ -49,23 +49,19 @@ IntRect EllipsisBox::SelectionRect() const {
}
bool EllipsisBox::NodeAtPoint(HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
LayoutUnit line_top,
LayoutUnit line_bottom) {
- LayoutPoint adjusted_location = accumulated_offset + Location();
-
- LayoutPoint box_origin = PhysicalLocation();
- box_origin.MoveBy(accumulated_offset);
- LayoutRect bounds_rect(box_origin, Size());
+ PhysicalOffset adjusted_location = accumulated_offset + PhysicalLocation();
+ PhysicalRect bounds_rect(adjusted_location, Size());
if (VisibleToHitTestRequest(result.GetHitTestRequest()) &&
bounds_rect.Intersects(
- HitTestLocation::RectForPoint(location_in_container.Point()))) {
+ HitTestLocation::RectForPoint(hit_test_location.Point()))) {
GetLineLayoutItem().UpdateHitTestResult(
- result,
- location_in_container.Point() - ToLayoutSize(adjusted_location));
+ result, hit_test_location.Point() - adjusted_location);
if (result.AddNodeToListBasedTestResult(GetLineLayoutItem().GetNode(),
- location_in_container,
+ hit_test_location,
bounds_rect) == kStopHitTesting)
return true;
}
diff --git a/chromium/third_party/blink/renderer/core/layout/line/ellipsis_box.h b/chromium/third_party/blink/renderer/core/layout/line/ellipsis_box.h
index d5f4370c05f..a38a07da9a6 100644
--- a/chromium/third_party/blink/renderer/core/layout/line/ellipsis_box.h
+++ b/chromium/third_party/blink/renderer/core/layout/line/ellipsis_box.h
@@ -57,8 +57,8 @@ class EllipsisBox final : public InlineBox {
LayoutUnit line_top,
LayoutUnit line_bottom) const override;
bool NodeAtPoint(HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
LayoutUnit line_top,
LayoutUnit line_bottom) override;
IntRect SelectionRect() const;
diff --git a/chromium/third_party/blink/renderer/core/layout/line/glyph_overflow.h b/chromium/third_party/blink/renderer/core/layout/line/glyph_overflow.h
index 7bd75587dd1..c03a2cda32e 100644
--- a/chromium/third_party/blink/renderer/core/layout/line/glyph_overflow.h
+++ b/chromium/third_party/blink/renderer/core/layout/line/glyph_overflow.h
@@ -27,7 +27,7 @@
#include <algorithm>
#include "third_party/blink/renderer/platform/geometry/float_rect.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 3baa2cb9239..32e388df710 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
@@ -142,7 +142,7 @@ void InlineBox::DumpBox(StringBuilder& string_inlinebox) const {
string_inlinebox.Append(' ');
string_inlinebox.AppendFormat(
"\t%s %p {pos=%g,%g size=%g,%g} baseline=%i/%i",
- GetLineLayoutItem().DecoratedName().Ascii().data(),
+ GetLineLayoutItem().DecoratedName().Ascii().c_str(),
GetLineLayoutItem().DebugPointer(), X().ToFloat(), Y().ToFloat(),
Width().ToFloat(), Height().ToFloat(),
BaselinePosition(kAlphabeticBaseline).ToInt(),
@@ -239,22 +239,20 @@ void InlineBox::Paint(const PaintInfo& paint_info,
}
bool InlineBox::NodeAtPoint(HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
LayoutUnit /* lineTop */,
LayoutUnit /* lineBottom */) {
// Hit test all phases of replaced elements atomically, as though the replaced
// element established its own stacking context. (See Appendix E.2, section
// 6.4 on inline block/table elements in the CSS2.1 specification.)
- LayoutPoint child_point = accumulated_offset;
- // Faster than calling containingBlock().
- if (Parent()->GetLineLayoutItem().HasFlippedBlocksWritingMode())
- child_point =
- GetLineLayoutItem().ContainingBlock().FlipForWritingModeForChild(
- LineLayoutBox(GetLineLayoutItem()), child_point);
-
- return GetLineLayoutItem().HitTestAllPhases(result, location_in_container,
- child_point);
+ PhysicalOffset layout_item_accumulated_offset = accumulated_offset;
+ if (GetLineLayoutItem().IsBox()) {
+ layout_item_accumulated_offset +=
+ LineLayoutBox(GetLineLayoutItem()).PhysicalLocation();
+ }
+ return GetLineLayoutItem().HitTestAllPhases(result, hit_test_location,
+ layout_item_accumulated_offset);
}
const RootInlineBox& InlineBox::Root() const {
@@ -336,10 +334,10 @@ void InlineBox::ClearKnownToHaveNoOverflow() {
Parent()->ClearKnownToHaveNoOverflow();
}
-LayoutPoint InlineBox::PhysicalLocation() const {
+PhysicalOffset InlineBox::PhysicalLocation() const {
LayoutRect rect(Location(), Size());
FlipForWritingMode(rect);
- return rect.Location();
+ return PhysicalOffset(rect.Location());
}
void InlineBox::FlipForWritingMode(LayoutRect& rect) const {
@@ -354,13 +352,14 @@ LayoutPoint InlineBox::FlipForWritingMode(const LayoutPoint& point) const {
return Root().Block().FlipForWritingMode(point);
}
-void InlineBox::SetShouldDoFullPaintInvalidationRecursively() {
+void InlineBox::SetShouldDoFullPaintInvalidationForFirstLine() {
+ GetLineLayoutItem().StyleRef().ClearCachedPseudoStyles();
GetLineLayoutItem().SetShouldDoFullPaintInvalidation();
if (!IsInlineFlowBox())
return;
for (InlineBox* child = ToInlineFlowBox(this)->FirstChild(); child;
child = child->NextOnLine())
- child->SetShouldDoFullPaintInvalidationRecursively();
+ child->SetShouldDoFullPaintInvalidationForFirstLine();
}
void InlineBox::SetLineLayoutItemShouldDoFullPaintInvalidationIfNeeded() {
diff --git a/chromium/third_party/blink/renderer/core/layout/line/inline_box.h b/chromium/third_party/blink/renderer/core/layout/line/inline_box.h
index 96181986e3d..2d5dc2026b9 100644
--- a/chromium/third_party/blink/renderer/core/layout/line/inline_box.h
+++ b/chromium/third_party/blink/renderer/core/layout/line/inline_box.h
@@ -102,8 +102,8 @@ class CORE_EXPORT InlineBox : public DisplayItemClient {
LayoutUnit line_top,
LayoutUnit line_bottom) const;
virtual bool NodeAtPoint(HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
LayoutUnit line_top,
LayoutUnit line_bottom);
@@ -353,7 +353,7 @@ class CORE_EXPORT InlineBox : public DisplayItemClient {
// Physical location of the top-left corner of the box in the containing
// block.
- LayoutPoint PhysicalLocation() const;
+ PhysicalOffset PhysicalLocation() const;
// TODO(szager): The Rect versions should return a rect, not modify the
// argument.
@@ -374,8 +374,8 @@ class CORE_EXPORT InlineBox : public DisplayItemClient {
}
// Set all LineLayoutItems in the inline box subtree should do full paint
- // invalidation.
- void SetShouldDoFullPaintInvalidationRecursively();
+ // invalidation and clear the first line style cache.
+ void SetShouldDoFullPaintInvalidationForFirstLine();
#define ADD_BOOLEAN_BITFIELD(field_name_, MethodNameBase) \
public: \
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 f9767278f3e..909f16a6fed 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
@@ -1354,14 +1354,14 @@ void InlineFlowBox::SetLayoutOverflowFromLogicalRect(
}
bool InlineFlowBox::NodeAtPoint(HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
LayoutUnit line_top,
LayoutUnit line_bottom) {
- LayoutRect overflow_rect(VisualOverflowRect(line_top, line_bottom));
- FlipForWritingMode(overflow_rect);
- overflow_rect.MoveBy(accumulated_offset);
- if (!location_in_container.Intersects(overflow_rect))
+ PhysicalRect overflow_rect =
+ PhysicalVisualOverflowRect(line_top, line_bottom);
+ overflow_rect.Move(accumulated_offset);
+ if (!hit_test_location.Intersects(overflow_rect))
return false;
// We need to hit test both our inline children (Inline Boxes) and culled
@@ -1377,11 +1377,10 @@ bool InlineFlowBox::NodeAtPoint(HitTestResult& result,
// Layers will handle hit testing themselves.
if (!curr->BoxModelObject() ||
!curr->BoxModelObject().HasSelfPaintingLayer()) {
- if (curr->NodeAtPoint(result, location_in_container, accumulated_offset,
+ if (curr->NodeAtPoint(result, hit_test_location, accumulated_offset,
line_top, line_bottom)) {
GetLineLayoutItem().UpdateHitTestResult(
- result,
- location_in_container.Point() - ToLayoutSize(accumulated_offset));
+ result, hit_test_location.Point() - accumulated_offset);
return true;
}
}
@@ -1412,7 +1411,7 @@ bool InlineFlowBox::NodeAtPoint(HitTestResult& result,
if (culled_parent.IsLayoutInline() &&
LineLayoutInline(culled_parent)
- .HitTestCulledInline(result, location_in_container,
+ .HitTestCulledInline(result, hit_test_location,
accumulated_offset))
return true;
@@ -1422,38 +1421,37 @@ bool InlineFlowBox::NodeAtPoint(HitTestResult& result,
if (GetLineLayoutItem().IsBox() &&
ToLayoutBox(LineLayoutAPIShim::LayoutObjectFrom(GetLineLayoutItem()))
- ->HitTestClippedOutByBorder(location_in_container,
- overflow_rect.Location()))
+ ->HitTestClippedOutByBorder(hit_test_location, overflow_rect.offset))
return false;
if (GetLineLayoutItem().StyleRef().HasBorderRadius()) {
+ // TODO(layout-dev): LogicalFrameRect() seems incorrect.
LayoutRect border_rect = LogicalFrameRect();
- border_rect.MoveBy(accumulated_offset);
+ border_rect.MoveBy(accumulated_offset.ToLayoutPoint());
FloatRoundedRect border =
GetLineLayoutItem().StyleRef().GetRoundedBorderFor(
border_rect, IncludeLogicalLeftEdge(), IncludeLogicalRightEdge());
- if (!location_in_container.Intersects(border))
+ if (!hit_test_location.Intersects(border))
return false;
}
// Now check ourselves.
- LayoutRect rect =
+ LayoutRect layout_rect =
InlineFlowBoxPainter(*this).FrameRectClampedToLineTopAndBottomIfNeeded();
-
- FlipForWritingMode(rect);
- rect.MoveBy(accumulated_offset);
+ FlipForWritingMode(layout_rect);
+ PhysicalRect rect(layout_rect);
+ rect.Move(accumulated_offset);
// Pixel snap hit testing.
- rect = LayoutRect(PixelSnappedIntRect(rect));
+ rect = PhysicalRect(PixelSnappedIntRect(rect));
if (VisibleToHitTestRequest(result.GetHitTestRequest()) &&
- location_in_container.Intersects(rect)) {
+ hit_test_location.Intersects(rect)) {
// Don't add in m_topLeft here, we want coords in the containing block's
// coordinate space.
GetLineLayoutItem().UpdateHitTestResult(
- result, FlipForWritingMode(location_in_container.Point() -
- ToLayoutSize(accumulated_offset)));
+ result, hit_test_location.Point() - accumulated_offset);
if (result.AddNodeToListBasedTestResult(GetLineLayoutItem().GetNode(),
- location_in_container,
+ hit_test_location,
rect) == kStopHitTesting)
return true;
}
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 c8b322d2950..4055260939c 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
@@ -129,8 +129,8 @@ class InlineFlowBox : public InlineBox {
LayoutUnit line_top,
LayoutUnit line_bottom) const override;
bool NodeAtPoint(HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
LayoutUnit line_top,
LayoutUnit line_bottom) override;
@@ -318,6 +318,12 @@ class InlineFlowBox : public InlineBox {
? overflow_->visual_overflow->VisualOverflowRect()
: FrameRectIncludingLineHeight(line_top, line_bottom);
}
+ PhysicalRect PhysicalVisualOverflowRect(LayoutUnit line_top,
+ LayoutUnit line_bottom) const {
+ LayoutRect rect = VisualOverflowRect(line_top, line_bottom);
+ FlipForWritingMode(rect);
+ return PhysicalRect(rect);
+ }
LayoutUnit LogicalLeftVisualOverflow() const {
return VisualOverflowIsSet()
? (IsHorizontal()
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 6a481c21487..ef198a493ca 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
@@ -29,7 +29,7 @@
#include "third_party/blink/renderer/core/layout/api/line_layout_text.h"
#include "third_party/blink/renderer/core/layout/bidi_run.h"
#include "third_party/blink/renderer/core/layout/layout_block_flow.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/line/inline_text_box.cc b/chromium/third_party/blink/renderer/core/layout/line/inline_text_box.cc
index 7b5efaccde7..98caacb9488 100644
--- a/chromium/third_party/blink/renderer/core/layout/line/inline_text_box.cc
+++ b/chromium/third_party/blink/renderer/core/layout/line/inline_text_box.cc
@@ -430,23 +430,22 @@ bool InlineTextBox::IsLineBreak() const {
}
bool InlineTextBox::NodeAtPoint(HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
LayoutUnit /* lineTop */,
LayoutUnit /*lineBottom*/) {
if (IsLineBreak() || truncation_ == kCFullTruncation)
return false;
- LayoutPoint box_origin = PhysicalLocation();
- box_origin.MoveBy(accumulated_offset);
- LayoutRect rect(box_origin, Size());
+ PhysicalOffset box_origin = PhysicalLocation();
+ box_origin += accumulated_offset;
+ PhysicalRect rect(box_origin, Size());
if (VisibleToHitTestRequest(result.GetHitTestRequest()) &&
- location_in_container.Intersects(rect)) {
+ hit_test_location.Intersects(rect)) {
GetLineLayoutItem().UpdateHitTestResult(
- result, FlipForWritingMode(location_in_container.Point() -
- ToLayoutSize(accumulated_offset)));
+ result, hit_test_location.Point() - accumulated_offset);
if (result.AddNodeToListBasedTestResult(GetLineLayoutItem().GetNode(),
- location_in_container,
+ hit_test_location,
rect) == kStopHitTesting)
return true;
}
@@ -711,7 +710,7 @@ void InlineTextBox::DumpBox(StringBuilder& string_inlinetextbox) const {
while (string_inlinetextbox.length() < kLayoutObjectCharacterOffset)
string_inlinetextbox.Append(' ');
string_inlinetextbox.AppendFormat("(%d,%d) \"%s\"", Start(), Start() + Len(),
- value.Utf8().data());
+ value.Utf8().c_str());
}
#endif
diff --git a/chromium/third_party/blink/renderer/core/layout/line/inline_text_box.h b/chromium/third_party/blink/renderer/core/layout/line/inline_text_box.h
index 0c97dfea4bb..f2812873467 100644
--- a/chromium/third_party/blink/renderer/core/layout/line/inline_text_box.h
+++ b/chromium/third_party/blink/renderer/core/layout/line/inline_text_box.h
@@ -159,8 +159,8 @@ class CORE_EXPORT InlineTextBox : public InlineBox {
LayoutUnit line_top,
LayoutUnit line_bottom) const override;
bool NodeAtPoint(HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
LayoutUnit line_top,
LayoutUnit line_bottom) override;
diff --git a/chromium/third_party/blink/renderer/core/layout/line/layout_text_info.h b/chromium/third_party/blink/renderer/core/layout/line/layout_text_info.h
index 80979ce2b5e..47b67824755 100644
--- a/chromium/third_party/blink/renderer/core/layout/line/layout_text_info.h
+++ b/chromium/third_party/blink/renderer/core/layout/line/layout_text_info.h
@@ -25,7 +25,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_LINE_LAYOUT_TEXT_INFO_H_
#include "third_party/blink/renderer/platform/text/text_break_iterator.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/line/line_box_list.cc b/chromium/third_party/blink/renderer/core/layout/line/line_box_list.cc
index de4cd29a24a..9d9d861f00c 100644
--- a/chromium/third_party/blink/renderer/core/layout/line/line_box_list.cc
+++ b/chromium/third_party/blink/renderer/core/layout/line/line_box_list.cc
@@ -50,13 +50,13 @@ void InlineBoxList<InlineBoxType>::AssertIsEmpty() {
const LineBoxList& LineBoxList::Empty() {
// Need to use "static" because DISALLOW_NEW.
- static LineBoxList empty;
+ static const LineBoxList empty;
return empty;
}
const InlineTextBoxList& InlineTextBoxList::Empty() {
// Need to use "static" because DISALLOW_NEW.
- static InlineTextBoxList empty;
+ static const InlineTextBoxList empty;
return empty;
}
@@ -145,7 +145,7 @@ bool LineBoxList::RangeIntersectsRect(LineLayoutBoxModel layout_object,
LayoutUnit logical_top,
LayoutUnit logical_bottom,
const CullRect& cull_rect,
- const LayoutPoint& offset) const {
+ const PhysicalOffset& offset) const {
LineLayoutBox block;
if (layout_object.IsBox())
block = LineLayoutBox(layout_object);
@@ -157,11 +157,11 @@ bool LineBoxList::RangeIntersectsRect(LineLayoutBoxModel layout_object,
physical_start = std::min(physical_start, physical_end);
if (layout_object.StyleRef().IsHorizontalWritingMode()) {
- physical_start += offset.Y();
+ physical_start += offset.top;
return cull_rect.IntersectsVerticalRange(physical_start,
physical_start + physical_extent);
} else {
- physical_start += offset.X();
+ physical_start += offset.left;
return cull_rect.IntersectsHorizontalRange(
physical_start, physical_start + physical_extent);
}
@@ -169,7 +169,7 @@ bool LineBoxList::RangeIntersectsRect(LineLayoutBoxModel layout_object,
bool LineBoxList::AnyLineIntersectsRect(LineLayoutBoxModel layout_object,
const CullRect& cull_rect,
- const LayoutPoint& offset) const {
+ const PhysicalOffset& offset) const {
// We can check the first box and last box and avoid painting/hit testing if
// we don't intersect. This is a quick short-circuit that we can take to avoid
// walking any lines.
@@ -190,7 +190,7 @@ bool LineBoxList::AnyLineIntersectsRect(LineLayoutBoxModel layout_object,
bool LineBoxList::LineIntersectsDirtyRect(LineLayoutBoxModel layout_object,
InlineFlowBox* box,
const CullRect& cull_rect,
- const LayoutPoint& offset) const {
+ const PhysicalOffset& offset) const {
RootInlineBox& root = box->Root();
LayoutUnit logical_top = std::min<LayoutUnit>(
box->LogicalTopVisualOverflow(root.LineTop()), root.SelectionTop());
@@ -203,8 +203,8 @@ bool LineBoxList::LineIntersectsDirtyRect(LineLayoutBoxModel layout_object,
bool LineBoxList::HitTest(LineLayoutBoxModel layout_object,
HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
HitTestAction hit_test_action) const {
if (hit_test_action != kHitTestForeground)
return false;
@@ -217,14 +217,14 @@ bool LineBoxList::HitTest(LineLayoutBoxModel layout_object,
if (!First())
return false;
- const LayoutPoint& point = location_in_container.Point();
- IntRect hit_search_bounding_box = location_in_container.EnclosingIntRect();
+ const PhysicalOffset& point = hit_test_location.Point();
+ IntRect hit_search_bounding_box = hit_test_location.EnclosingIntRect();
CullRect cull_rect(
First()->IsHorizontal()
- ? IntRect(point.X().ToInt(), hit_search_bounding_box.Y(), 1,
+ ? IntRect(point.left.ToInt(), hit_search_bounding_box.Y(), 1,
hit_search_bounding_box.Height())
- : IntRect(hit_search_bounding_box.X(), point.Y().ToInt(),
+ : IntRect(hit_search_bounding_box.X(), point.top.ToInt(),
hit_search_bounding_box.Width(), 1));
if (!AnyLineIntersectsRect(layout_object, cull_rect, accumulated_offset))
@@ -240,12 +240,11 @@ bool LineBoxList::HitTest(LineLayoutBoxModel layout_object,
curr->LogicalBottomVisualOverflow(root.LineBottom()), cull_rect,
accumulated_offset)) {
bool inside =
- curr->NodeAtPoint(result, location_in_container, accumulated_offset,
+ curr->NodeAtPoint(result, hit_test_location, accumulated_offset,
root.LineTop(), root.LineBottom());
if (inside) {
layout_object.UpdateHitTestResult(
- result,
- location_in_container.Point() - ToLayoutSize(accumulated_offset));
+ result, hit_test_location.Point() - accumulated_offset);
return true;
}
}
diff --git a/chromium/third_party/blink/renderer/core/layout/line/line_box_list.h b/chromium/third_party/blink/renderer/core/layout/line/line_box_list.h
index 749752d0d47..de7fdd074ce 100644
--- a/chromium/third_party/blink/renderer/core/layout/line/line_box_list.h
+++ b/chromium/third_party/blink/renderer/core/layout/line/line_box_list.h
@@ -31,7 +31,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/layout/api/hit_test_action.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
namespace blink {
@@ -41,10 +41,10 @@ class HitTestLocation;
class HitTestResult;
class InlineFlowBox;
class InlineTextBox;
-class LayoutPoint;
class LayoutUnit;
class LineLayoutBoxModel;
class LineLayoutItem;
+struct PhysicalOffset;
template <typename InlineBoxType>
class InlineBoxList {
@@ -154,23 +154,23 @@ class CORE_EXPORT LineBoxList : public InlineBoxList<InlineFlowBox> {
bool HitTest(LineLayoutBoxModel,
HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
HitTestAction) const;
bool AnyLineIntersectsRect(LineLayoutBoxModel,
const CullRect&,
- const LayoutPoint&) const;
+ const PhysicalOffset&) const;
bool LineIntersectsDirtyRect(LineLayoutBoxModel,
InlineFlowBox*,
const CullRect&,
- const LayoutPoint&) const;
+ const PhysicalOffset&) const;
private:
bool RangeIntersectsRect(LineLayoutBoxModel,
LayoutUnit logical_top,
LayoutUnit logical_bottom,
const CullRect&,
- const LayoutPoint&) const;
+ const PhysicalOffset&) const;
};
class CORE_EXPORT InlineTextBoxList : public InlineBoxList<InlineTextBox> {
diff --git a/chromium/third_party/blink/renderer/core/layout/line/line_breaker.h b/chromium/third_party/blink/renderer/core/layout/line/line_breaker.h
index 3cdc60f3093..0fb96071048 100644
--- a/chromium/third_party/blink/renderer/core/layout/line/line_breaker.h
+++ b/chromium/third_party/blink/renderer/core/layout/line/line_breaker.h
@@ -27,7 +27,7 @@
#include "third_party/blink/renderer/core/layout/api/line_layout_block_flow.h"
#include "third_party/blink/renderer/core/layout/line/inline_iterator.h"
#include "third_party/blink/renderer/core/layout/line/line_info.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/line/line_info.h b/chromium/third_party/blink/renderer/core/layout/line/line_info.h
index 0f737c094fd..f8a87920903 100644
--- a/chromium/third_party/blink/renderer/core/layout/line/line_info.h
+++ b/chromium/third_party/blink/renderer/core/layout/line/line_info.h
@@ -27,7 +27,7 @@
#include "third_party/blink/renderer/core/layout/line/line_width.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/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/line/line_layout_state.h b/chromium/third_party/blink/renderer/core/layout/line/line_layout_state.h
index 1076bc614d3..d37d2348be3 100644
--- a/chromium/third_party/blink/renderer/core/layout/line/line_layout_state.h
+++ b/chromium/third_party/blink/renderer/core/layout/line/line_layout_state.h
@@ -27,7 +27,7 @@
#include "third_party/blink/renderer/core/layout/layout_block_flow.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/allocator/allocator.h"
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 6ca5d0752bd..83081ea7d80 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
@@ -32,7 +32,7 @@
#include "third_party/blink/renderer/core/layout/api/line_layout_block_flow.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/allocator/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 173c2525a24..a60dcafcc26 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
@@ -181,21 +181,20 @@ void RootInlineBox::Paint(const PaintInfo& paint_info,
}
bool RootInlineBox::NodeAtPoint(HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
LayoutUnit line_top,
LayoutUnit line_bottom) {
if (HasEllipsisBox() && VisibleToHitTestRequest(result.GetHitTestRequest())) {
- if (GetEllipsisBox()->NodeAtPoint(result, location_in_container,
+ if (GetEllipsisBox()->NodeAtPoint(result, hit_test_location,
accumulated_offset, line_top,
line_bottom)) {
GetLineLayoutItem().UpdateHitTestResult(
- result,
- location_in_container.Point() - ToLayoutSize(accumulated_offset));
+ result, hit_test_location.Point() - accumulated_offset);
return true;
}
}
- return InlineFlowBox::NodeAtPoint(result, location_in_container,
+ return InlineFlowBox::NodeAtPoint(result, hit_test_location,
accumulated_offset, line_top, line_bottom);
}
diff --git a/chromium/third_party/blink/renderer/core/layout/line/root_inline_box.h b/chromium/third_party/blink/renderer/core/layout/line/root_inline_box.h
index a5660d77128..73b8be82d3a 100644
--- a/chromium/third_party/blink/renderer/core/layout/line/root_inline_box.h
+++ b/chromium/third_party/blink/renderer/core/layout/line/root_inline_box.h
@@ -139,8 +139,8 @@ class RootInlineBox : public InlineFlowBox {
LayoutUnit line_top,
LayoutUnit line_bottom) const override;
bool NodeAtPoint(HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
LayoutUnit line_top,
LayoutUnit line_bottom) override;
diff --git a/chromium/third_party/blink/renderer/core/layout/line/trailing_objects.h b/chromium/third_party/blink/renderer/core/layout/line/trailing_objects.h
index 0da53a2cb71..f929454e873 100644
--- a/chromium/third_party/blink/renderer/core/layout/line/trailing_objects.h
+++ b/chromium/third_party/blink/renderer/core/layout/line/trailing_objects.h
@@ -27,7 +27,7 @@
#include "third_party/blink/renderer/core/layout/api/line_layout_item.h"
#include "third_party/blink/renderer/core/layout/api/line_layout_text.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/line/word_measurement.h b/chromium/third_party/blink/renderer/core/layout/line/word_measurement.h
index b129d8f74eb..3bb1f4bbeb7 100644
--- a/chromium/third_party/blink/renderer/core/layout/line/word_measurement.h
+++ b/chromium/third_party/blink/renderer/core/layout/line/word_measurement.h
@@ -26,7 +26,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_LINE_WORD_MEASUREMENT_H_
#include "third_party/blink/renderer/platform/fonts/simple_font_data.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
namespace blink {
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 6b06dba83df..92998804e2b 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
@@ -15,6 +15,13 @@ class MapCoordinatesTest : public RenderingTest {
public:
MapCoordinatesTest()
: RenderingTest(MakeGarbageCollected<SingleChildLocalFrameClient>()) {}
+
+ void SetUp() override {
+ // This is required to test 3d transforms.
+ EnableCompositing();
+ RenderingTest::SetUp();
+ }
+
PhysicalOffset MapLocalToAncestor(const LayoutObject*,
const LayoutBoxModelObject* ancestor,
PhysicalOffset,
@@ -1621,8 +1628,6 @@ TEST_F(MapCoordinatesTest, LocalToAncestorTransform) {
}
TEST_F(MapCoordinatesTest, LocalToAbsoluteTransformFlattens) {
- // This is required to test 3d transforms.
- EnableCompositing();
SetBodyInnerHTML(R"HTML(
<div style='position: absolute; left: 0; top: 0;'>
<div style='transform: rotateY(45deg); transform-style: preserve-3d;'>
@@ -1668,8 +1673,6 @@ TEST_F(MapCoordinatesTest, LocalToAbsoluteTransformFlattens) {
}
TEST_F(MapCoordinatesTest, Transform3DWithOffset) {
- // This is required to test 3d transforms.
- EnableCompositing();
SetBodyInnerHTML(R"HTML(
<style>
body { margin: 0; }
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 f5f0483c406..1c528915d9c 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
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/layout/layout_multi_column_flow_thread.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 549698b1fbe..25f91345921 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
@@ -26,8 +26,8 @@ void InsertClosedArea(
// We go backwards through the list as there is a higher probability that a
// new area will be at the end of the list.
- for (wtf_size_t j = areas->size() - 1; j >= 0; --j) {
- const NGExclusionSpaceInternal::NGClosedArea& other = areas->at(j);
+ for (wtf_size_t i = areas->size(); i--;) {
+ const NGExclusionSpaceInternal::NGClosedArea& other = areas->at(i);
if (other.opportunity.rect.BlockStartOffset() <=
area.opportunity.rect.BlockStartOffset()) {
#if DCHECK_IS_ON()
@@ -42,12 +42,21 @@ void InsertClosedArea(
}
#endif
- areas->insert(j + 1, area);
+ areas->insert(i + 1, area);
return;
}
}
- NOTREACHED();
+ // The first closed-off area we insert is almost always at LayoutUnit::Min().
+ //
+ // However if a float is placed at LayoutUnit::Min() it is possible to get
+ // into a state where this isn't the case (the first closed-off area might be
+ // directly below that float for example).
+ //
+ // When a subsequent float gets placed, it might create a closed-off area at
+ // LayoutUnit::Min(), and should be inserted at the front of the areas list.
+ DCHECK_EQ(area.opportunity.rect.BlockStartOffset(), LayoutUnit::Min());
+ areas->push_front(area);
}
// Returns true if there is at least one edge between block_start and block_end.
@@ -111,18 +120,19 @@ bool Intersects(const NGLayoutOpportunity& opportunity,
// always intersects.
bool Intersects(const NGExclusionSpaceInternal::NGShelf& shelf,
const NGBfcOffset& offset,
- const LayoutUnit inline_size) {
+ const LayoutUnit inline_size,
+ bool is_inline_level) {
if (shelf.line_right >= offset.line_offset &&
shelf.line_left <= offset.line_offset + inline_size)
return true;
+
// Negative available space creates a zero-width opportunity at the inline-end
// of the shelf. Consider such shelf intersects.
- // TODO(kojii): This is correct to find layout opportunities for zero-width
- // in-flow inline or block objects (e.g., <br>,) but not correct for
- // zero-width floats.
- if (UNLIKELY(shelf.line_left > offset.line_offset ||
- shelf.line_right < offset.line_offset + inline_size))
+ if (UNLIKELY(is_inline_level &&
+ (shelf.line_left > offset.line_offset ||
+ shelf.line_right < offset.line_offset + inline_size)))
return true;
+
return false;
}
@@ -153,8 +163,9 @@ NGLayoutOpportunity CreateLayoutOpportunity(const NGLayoutOpportunity& other,
NGLayoutOpportunity CreateLayoutOpportunity(
const NGExclusionSpaceInternal::NGShelf& shelf,
const NGBfcOffset& offset,
- const LayoutUnit inline_size) {
- DCHECK(Intersects(shelf, offset, inline_size));
+ const LayoutUnit inline_size,
+ bool is_inline_level) {
+ DCHECK(Intersects(shelf, offset, inline_size, is_inline_level));
NGBfcOffset start_offset(std::max(shelf.line_left, offset.line_offset),
std::max(shelf.block_offset, offset.block_offset));
@@ -541,7 +552,7 @@ NGExclusionSpaceInternal::DerivedGeometry::FindLayoutOpportunity(
NGLayoutOpportunity return_opportunity;
IterateAllLayoutOpportunities(
- offset, available_inline_size,
+ offset, available_inline_size, false /* is_inline_level */,
[&return_opportunity, &minimum_size,
&available_inline_size](const NGLayoutOpportunity opportunity) -> bool {
// Determine if this opportunity will fit the given size.
@@ -568,8 +579,9 @@ NGExclusionSpaceInternal::DerivedGeometry::AllLayoutOpportunities(
const LayoutUnit available_inline_size) const {
LayoutOpportunityVector opportunities;
+ // This method is only used for determining the position of line-boxes.
IterateAllLayoutOpportunities(
- offset, available_inline_size,
+ offset, available_inline_size, true /* is_inline_level */,
[&opportunities](const NGLayoutOpportunity opportunity) -> bool {
opportunities.push_back(std::move(opportunity));
return false;
@@ -582,6 +594,7 @@ template <typename LambdaFunc>
void NGExclusionSpaceInternal::DerivedGeometry::IterateAllLayoutOpportunities(
const NGBfcOffset& offset,
const LayoutUnit available_inline_size,
+ bool is_inline_level,
const LambdaFunc& lambda) const {
auto* shelves_it = shelves_.begin();
auto* areas_it = areas_.begin();
@@ -595,7 +608,7 @@ void NGExclusionSpaceInternal::DerivedGeometry::IterateAllLayoutOpportunities(
DCHECK_NE(shelves_it, shelves_end);
const NGShelf& shelf = *shelves_it;
- if (!Intersects(shelf, offset, available_inline_size)) {
+ if (!Intersects(shelf, offset, available_inline_size, is_inline_level)) {
++shelves_it;
continue;
}
@@ -640,7 +653,8 @@ void NGExclusionSpaceInternal::DerivedGeometry::IterateAllLayoutOpportunities(
HasSolidEdges(shelf.line_right_edges, offset.block_offset,
LayoutUnit::Max());
if (has_solid_edges) {
- if (lambda(CreateLayoutOpportunity(shelf, offset, available_inline_size)))
+ if (lambda(CreateLayoutOpportunity(shelf, offset, available_inline_size,
+ is_inline_level)))
return;
}
++shelves_it;
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 0d05cbcdee2..5adea8b8184 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
@@ -12,7 +12,7 @@
#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/geometry/layout_unit.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
@@ -107,9 +107,7 @@ class CORE_EXPORT NGExclusionSpaceInternal {
if (!other.derived_geometry_)
return;
- track_shape_exclusions_ = other.track_shape_exclusions_;
- derived_geometry_ = std::move(other.derived_geometry_);
- other.derived_geometry_ = nullptr;
+ MoveDerivedGeometry(other);
// Iterate through all the exclusions which were added by the layout, and
// update the DerivedGeometry.
@@ -128,6 +126,16 @@ class CORE_EXPORT NGExclusionSpaceInternal {
}
}
+ // See |NGExclusionSpace::MoveDerivedGeometry|.
+ void MoveDerivedGeometry(const NGExclusionSpaceInternal& other) {
+ if (!other.derived_geometry_)
+ return;
+
+ track_shape_exclusions_ = other.track_shape_exclusions_;
+ derived_geometry_ = std::move(other.derived_geometry_);
+ other.derived_geometry_ = nullptr;
+ }
+
// See |NGExclusionSpace::MergeExclusionSpaces|.
void MergeExclusionSpaces(const NGBfcDelta& offset_delta,
const NGExclusionSpaceInternal& previous_output,
@@ -352,6 +360,7 @@ class CORE_EXPORT NGExclusionSpaceInternal {
template <typename LambdaFunc>
void IterateAllLayoutOpportunities(const NGBfcOffset& offset,
const LayoutUnit available_inline_size,
+ bool is_inline_level,
const LambdaFunc&) const;
// See |NGShelf| for a broad description of what shelves are. We always
@@ -479,7 +488,7 @@ class CORE_EXPORT NGExclusionSpace {
exclusion_space_->PreInitialize(*other.exclusion_space_);
}
- // Shifts the DerivedGeometry data-structure to this exclusion space, and
+ // Shifts the |DerivedGeometry| data-structure to this exclusion space, and
// adds any new exclusions.
void MoveAndUpdateDerivedGeometry(const NGExclusionSpace& other) const {
if (!exclusion_space_ || !other.exclusion_space_)
@@ -488,6 +497,15 @@ class CORE_EXPORT NGExclusionSpace {
exclusion_space_->MoveAndUpdateDerivedGeometry(*other.exclusion_space_);
}
+ // Shifts the |DerivedGeometry| data-structure to this exclusion space.
+ void MoveDerivedGeometry(const NGExclusionSpace& other) const {
+ DCHECK(*this == other);
+ if (!exclusion_space_ || !other.exclusion_space_)
+ return;
+
+ exclusion_space_->MoveDerivedGeometry(*other.exclusion_space_);
+ }
+
// This produces a new exclusion space for a |NGLayoutResult| which is being
// re-used for caching purposes.
//
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 a54a2c4e1a0..3824623be68 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
@@ -7,7 +7,7 @@
#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/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_static_position.cc b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_static_position.cc
deleted file mode 100644
index b90c8e35d33..00000000000
--- a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_static_position.cc
+++ /dev/null
@@ -1,75 +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/geometry/ng_static_position.h"
-
-namespace blink {
-
-NGStaticPosition NGStaticPosition::Create(WritingMode writing_mode,
- TextDirection direction,
- PhysicalOffset offset) {
- NGStaticPosition position;
- position.offset = offset;
- switch (writing_mode) {
- case WritingMode::kHorizontalTb:
- position.type = (direction == TextDirection::kLtr) ? kTopLeft : kTopRight;
- break;
- case WritingMode::kVerticalRl:
- case WritingMode::kSidewaysRl:
- position.type =
- (direction == TextDirection::kLtr) ? kTopRight : kBottomRight;
- break;
- case WritingMode::kVerticalLr:
- position.type =
- (direction == TextDirection::kLtr) ? kTopLeft : kBottomLeft;
- break;
- case WritingMode::kSidewaysLr:
- position.type =
- (direction == TextDirection::kLtr) ? kBottomLeft : kTopLeft;
- break;
- }
- return position;
-}
-
-LayoutUnit NGStaticPosition::LeftInset(LayoutUnit container_size,
- LayoutUnit width,
- LayoutUnit margin_left,
- LayoutUnit margin_right) const {
- if (HasLeft())
- return offset.left;
- else
- return offset.left - width - margin_left - margin_right;
-}
-
-LayoutUnit NGStaticPosition::RightInset(LayoutUnit container_size,
- LayoutUnit width,
- LayoutUnit margin_left,
- LayoutUnit margin_right) const {
- if (HasLeft())
- return container_size - offset.left - width - margin_left - margin_right;
- else
- return container_size - offset.left;
-}
-
-LayoutUnit NGStaticPosition::TopInset(LayoutUnit container_size,
- LayoutUnit height,
- LayoutUnit margin_top,
- LayoutUnit margin_bottom) const {
- if (HasTop())
- return offset.top;
- else
- return offset.top - height - margin_bottom - margin_top;
-}
-
-LayoutUnit NGStaticPosition::BottomInset(LayoutUnit container_size,
- LayoutUnit height,
- LayoutUnit margin_top,
- LayoutUnit margin_bottom) const {
- if (HasTop())
- return container_size - offset.top - height - margin_top - margin_bottom;
- else
- return container_size - offset.top;
-}
-
-} // namespace blink
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 68f72b4cd61..2da520c5a7c 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
@@ -6,68 +6,141 @@
#define NGStaticPosition_h
#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/layout/geometry/logical_offset.h"
#include "third_party/blink/renderer/core/layout/geometry/physical_offset.h"
+#include "third_party/blink/renderer/core/layout/geometry/physical_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"
namespace blink {
-// Represents static position of an out of flow descendant.
-struct CORE_EXPORT NGStaticPosition {
- enum Type { kTopLeft, kTopRight, kBottomLeft, kBottomRight };
+struct NGPhysicalStaticPosition;
+
+// Represents the static-position of an OOF-positioned descendant, in the
+// logical coordinate space.
+//
+// |offset| is the position of the descandant's |inline_edge|, and |block_edge|.
+struct CORE_EXPORT NGLogicalStaticPosition {
+ enum InlineEdge { kInlineStart, kInlineEnd };
+ enum BlockEdge { kBlockStart, kBlockEnd };
+
+ inline NGPhysicalStaticPosition
+ ConvertToPhysical(WritingMode, TextDirection, const PhysicalSize& size) const;
+
+ LogicalOffset offset;
+ InlineEdge inline_edge;
+ BlockEdge block_edge;
+};
+
+// Similar to |NGLogicalStaticPosition| but in the physical coordinate space.
+struct CORE_EXPORT NGPhysicalStaticPosition {
+ enum HorizontalEdge { kLeft, kRight };
+ enum VerticalEdge { kTop, kBottom };
- Type type; // Logical corner that corresponds to physical top left.
PhysicalOffset offset;
+ HorizontalEdge horizontal_edge;
+ VerticalEdge vertical_edge;
- // Creates a position with proper type wrt writing mode and direction.
- // It expects physical offset of inline_start/block_start vertex.
- static NGStaticPosition Create(WritingMode, TextDirection, PhysicalOffset);
-
- // Left/Right/TopPosition functions map static position to inset of
- // left/right/top edge wrt container space.
- // The function arguments are required to solve the equation:
- // contaner_size = left + margin_left + width + margin_right + right
- LayoutUnit LeftInset(LayoutUnit container_size,
- LayoutUnit width,
- LayoutUnit margin_left,
- LayoutUnit margin_right) const;
- LayoutUnit RightInset(LayoutUnit container_size,
- LayoutUnit width,
- LayoutUnit margin_left,
- LayoutUnit margin_right) const;
- LayoutUnit TopInset(LayoutUnit container_size,
- LayoutUnit height,
- LayoutUnit margin_top,
- LayoutUnit margin_bottom) const;
- LayoutUnit BottomInset(LayoutUnit container_size,
- LayoutUnit height,
- LayoutUnit margin_top,
- LayoutUnit margin_bottom) const;
-
- LayoutUnit Left() const {
- DCHECK(HasLeft());
- return offset.left;
- }
+ NGLogicalStaticPosition ConvertToLogical(WritingMode writing_mode,
+ TextDirection direction,
+ const PhysicalSize& size) const {
+ LogicalOffset logical_offset =
+ offset.ConvertToLogical(writing_mode, direction, /* outer_size */ size,
+ /* inner_size */ PhysicalSize());
- LayoutUnit Right() const {
- DCHECK(!HasLeft());
- return offset.left;
- }
+ NGLogicalStaticPosition::InlineEdge inline_edge;
+ NGLogicalStaticPosition::BlockEdge block_edge;
+
+ switch (writing_mode) {
+ case WritingMode::kHorizontalTb:
+ inline_edge = ((horizontal_edge == kLeft) == IsLtr(direction))
+ ? NGLogicalStaticPosition::InlineEdge::kInlineStart
+ : NGLogicalStaticPosition::InlineEdge::kInlineEnd;
+ block_edge = (vertical_edge == kTop)
+ ? NGLogicalStaticPosition::BlockEdge::kBlockStart
+ : NGLogicalStaticPosition::BlockEdge::kBlockEnd;
+ break;
+ case WritingMode::kVerticalRl:
+ case WritingMode::kSidewaysRl:
+ inline_edge = ((vertical_edge == kTop) == IsLtr(direction))
+ ? NGLogicalStaticPosition::InlineEdge::kInlineStart
+ : NGLogicalStaticPosition::InlineEdge::kInlineEnd;
+ block_edge = (horizontal_edge == kRight)
+ ? NGLogicalStaticPosition::BlockEdge::kBlockStart
+ : NGLogicalStaticPosition::BlockEdge::kBlockEnd;
+ break;
+ case WritingMode::kVerticalLr:
+ inline_edge = ((vertical_edge == kTop) == IsLtr(direction))
+ ? NGLogicalStaticPosition::InlineEdge::kInlineStart
+ : NGLogicalStaticPosition::InlineEdge::kInlineEnd;
+ block_edge = (horizontal_edge == kLeft)
+ ? NGLogicalStaticPosition::BlockEdge::kBlockStart
+ : NGLogicalStaticPosition::BlockEdge::kBlockEnd;
+ break;
+ case WritingMode::kSidewaysLr:
+ inline_edge = ((vertical_edge == kBottom) == IsLtr(direction))
+ ? NGLogicalStaticPosition::InlineEdge::kInlineStart
+ : NGLogicalStaticPosition::InlineEdge::kInlineEnd;
+ block_edge = (horizontal_edge == kLeft)
+ ? NGLogicalStaticPosition::BlockEdge::kBlockStart
+ : NGLogicalStaticPosition::BlockEdge::kBlockEnd;
+ break;
+ }
- LayoutUnit Top() const {
- DCHECK(HasTop());
- return offset.top;
+ return {logical_offset, inline_edge, block_edge};
}
+};
- LayoutUnit Bottom() const {
- DCHECK(!HasTop());
- return offset.top;
+inline NGPhysicalStaticPosition NGLogicalStaticPosition::ConvertToPhysical(
+ WritingMode writing_mode,
+ TextDirection direction,
+ const PhysicalSize& size) const {
+ PhysicalOffset physical_offset =
+ offset.ConvertToPhysical(writing_mode, direction, /* outer_size */ size,
+ /* inner_size */ PhysicalSize());
+
+ NGPhysicalStaticPosition::HorizontalEdge horizontal_edge;
+ NGPhysicalStaticPosition::VerticalEdge vertical_edge;
+
+ switch (writing_mode) {
+ case WritingMode::kHorizontalTb:
+ horizontal_edge = ((inline_edge == kInlineStart) == IsLtr(direction))
+ ? NGPhysicalStaticPosition::HorizontalEdge::kLeft
+ : NGPhysicalStaticPosition::HorizontalEdge::kRight;
+ vertical_edge = (block_edge == kBlockStart)
+ ? NGPhysicalStaticPosition::VerticalEdge::kTop
+ : NGPhysicalStaticPosition::VerticalEdge::kBottom;
+ break;
+ case WritingMode::kVerticalRl:
+ case WritingMode::kSidewaysRl:
+ horizontal_edge = (block_edge == kBlockEnd)
+ ? NGPhysicalStaticPosition::HorizontalEdge::kLeft
+ : NGPhysicalStaticPosition::HorizontalEdge::kRight;
+ vertical_edge = ((inline_edge == kInlineStart) == IsLtr(direction))
+ ? NGPhysicalStaticPosition::VerticalEdge::kTop
+ : NGPhysicalStaticPosition::VerticalEdge::kBottom;
+ break;
+ case WritingMode::kVerticalLr:
+ horizontal_edge = (block_edge == kBlockStart)
+ ? NGPhysicalStaticPosition::HorizontalEdge::kLeft
+ : NGPhysicalStaticPosition::HorizontalEdge::kRight;
+ vertical_edge = ((inline_edge == kInlineStart) == IsLtr(direction))
+ ? NGPhysicalStaticPosition::VerticalEdge::kTop
+ : NGPhysicalStaticPosition::VerticalEdge::kBottom;
+ break;
+ case WritingMode::kSidewaysLr:
+ horizontal_edge = (block_edge == kBlockStart)
+ ? NGPhysicalStaticPosition::HorizontalEdge::kLeft
+ : NGPhysicalStaticPosition::HorizontalEdge::kRight;
+ vertical_edge = ((inline_edge == kInlineEnd) == IsLtr(direction))
+ ? NGPhysicalStaticPosition::VerticalEdge::kTop
+ : NGPhysicalStaticPosition::VerticalEdge::kBottom;
+ break;
}
- bool HasTop() const { return type == kTopLeft || type == kTopRight; }
- bool HasLeft() const { return type == kTopLeft || type == kBottomLeft; }
-};
+ return {physical_offset, horizontal_edge, vertical_edge};
+}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_static_position_test.cc b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_static_position_test.cc
new file mode 100644
index 00000000000..09b282a01ed
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/layout/ng/geometry/ng_static_position_test.cc
@@ -0,0 +1,194 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/layout/ng/geometry/ng_static_position.h"
+
+#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/renderer/core/testing/core_unit_test_helper.h"
+
+namespace blink {
+namespace {
+
+using InlineEdge = NGLogicalStaticPosition::InlineEdge;
+using BlockEdge = NGLogicalStaticPosition::BlockEdge;
+using HorizontalEdge = NGPhysicalStaticPosition::HorizontalEdge;
+using VerticalEdge = NGPhysicalStaticPosition::VerticalEdge;
+
+struct NGStaticPositionTestData {
+ NGLogicalStaticPosition logical;
+ NGPhysicalStaticPosition physical;
+ WritingMode writing_mode;
+ TextDirection direction;
+
+} ng_static_position_test_data[] = {
+ // |WritingMode::kHorizontalTb|, |TextDirection::kLtr|
+ {{LogicalOffset(20, 30), InlineEdge::kInlineStart, BlockEdge::kBlockStart},
+ {PhysicalOffset(20, 30), HorizontalEdge::kLeft, VerticalEdge::kTop},
+ WritingMode::kHorizontalTb,
+ TextDirection::kLtr},
+ {{LogicalOffset(20, 30), InlineEdge::kInlineEnd, BlockEdge::kBlockStart},
+ {PhysicalOffset(20, 30), HorizontalEdge::kRight, VerticalEdge::kTop},
+ WritingMode::kHorizontalTb,
+ TextDirection::kLtr},
+ {{LogicalOffset(20, 30), InlineEdge::kInlineStart, BlockEdge::kBlockEnd},
+ {PhysicalOffset(20, 30), HorizontalEdge::kLeft, VerticalEdge::kBottom},
+ WritingMode::kHorizontalTb,
+ TextDirection::kLtr},
+ {{LogicalOffset(20, 30), InlineEdge::kInlineEnd, BlockEdge::kBlockEnd},
+ {PhysicalOffset(20, 30), HorizontalEdge::kRight, VerticalEdge::kBottom},
+ WritingMode::kHorizontalTb,
+ TextDirection::kLtr},
+ // |WritingMode::kHorizontalTb|, |TextDirection::kRtl|
+ {{LogicalOffset(20, 30), InlineEdge::kInlineStart, BlockEdge::kBlockStart},
+ {PhysicalOffset(80, 30), HorizontalEdge::kRight, VerticalEdge::kTop},
+ WritingMode::kHorizontalTb,
+ TextDirection::kRtl},
+ {{LogicalOffset(20, 30), InlineEdge::kInlineEnd, BlockEdge::kBlockStart},
+ {PhysicalOffset(80, 30), HorizontalEdge::kLeft, VerticalEdge::kTop},
+ WritingMode::kHorizontalTb,
+ TextDirection::kRtl},
+ {{LogicalOffset(20, 30), InlineEdge::kInlineStart, BlockEdge::kBlockEnd},
+ {PhysicalOffset(80, 30), HorizontalEdge::kRight, VerticalEdge::kBottom},
+ WritingMode::kHorizontalTb,
+ TextDirection::kRtl},
+ {{LogicalOffset(20, 30), InlineEdge::kInlineEnd, BlockEdge::kBlockEnd},
+ {PhysicalOffset(80, 30), HorizontalEdge::kLeft, VerticalEdge::kBottom},
+ WritingMode::kHorizontalTb,
+ TextDirection::kRtl},
+ // |WritingMode::kVerticalRl|, |TextDirection::kLtr|
+ {{LogicalOffset(20, 30), InlineEdge::kInlineStart, BlockEdge::kBlockStart},
+ {PhysicalOffset(70, 20), HorizontalEdge::kRight, VerticalEdge::kTop},
+ WritingMode::kVerticalRl,
+ TextDirection::kLtr},
+ {{LogicalOffset(20, 30), InlineEdge::kInlineEnd, BlockEdge::kBlockStart},
+ {PhysicalOffset(70, 20), HorizontalEdge::kRight, VerticalEdge::kBottom},
+ WritingMode::kVerticalRl,
+ TextDirection::kLtr},
+ {{LogicalOffset(20, 30), InlineEdge::kInlineStart, BlockEdge::kBlockEnd},
+ {PhysicalOffset(70, 20), HorizontalEdge::kLeft, VerticalEdge::kTop},
+ WritingMode::kVerticalRl,
+ TextDirection::kLtr},
+ {{LogicalOffset(20, 30), InlineEdge::kInlineEnd, BlockEdge::kBlockEnd},
+ {PhysicalOffset(70, 20), HorizontalEdge::kLeft, VerticalEdge::kBottom},
+ WritingMode::kVerticalRl,
+ TextDirection::kLtr},
+ // |WritingMode::kVerticalRl|, |TextDirection::kRtl|
+ {{LogicalOffset(20, 30), InlineEdge::kInlineStart, BlockEdge::kBlockStart},
+ {PhysicalOffset(70, 80), HorizontalEdge::kRight, VerticalEdge::kBottom},
+ WritingMode::kVerticalRl,
+ TextDirection::kRtl},
+ {{LogicalOffset(20, 30), InlineEdge::kInlineEnd, BlockEdge::kBlockStart},
+ {PhysicalOffset(70, 80), HorizontalEdge::kRight, VerticalEdge::kTop},
+ WritingMode::kVerticalRl,
+ TextDirection::kRtl},
+ {{LogicalOffset(20, 30), InlineEdge::kInlineStart, BlockEdge::kBlockEnd},
+ {PhysicalOffset(70, 80), HorizontalEdge::kLeft, VerticalEdge::kBottom},
+ WritingMode::kVerticalRl,
+ TextDirection::kRtl},
+ {{LogicalOffset(20, 30), InlineEdge::kInlineEnd, BlockEdge::kBlockEnd},
+ {PhysicalOffset(70, 80), HorizontalEdge::kLeft, VerticalEdge::kTop},
+ WritingMode::kVerticalRl,
+ TextDirection::kRtl},
+ // |WritingMode::kVerticalLr|, |TextDirection::kLtr|
+ {{LogicalOffset(20, 30), InlineEdge::kInlineStart, BlockEdge::kBlockStart},
+ {PhysicalOffset(30, 20), HorizontalEdge::kLeft, VerticalEdge::kTop},
+ WritingMode::kVerticalLr,
+ TextDirection::kLtr},
+ {{LogicalOffset(20, 30), InlineEdge::kInlineEnd, BlockEdge::kBlockStart},
+ {PhysicalOffset(30, 20), HorizontalEdge::kLeft, VerticalEdge::kBottom},
+ WritingMode::kVerticalLr,
+ TextDirection::kLtr},
+ {{LogicalOffset(20, 30), InlineEdge::kInlineStart, BlockEdge::kBlockEnd},
+ {PhysicalOffset(30, 20), HorizontalEdge::kRight, VerticalEdge::kTop},
+ WritingMode::kVerticalLr,
+ TextDirection::kLtr},
+ {{LogicalOffset(20, 30), InlineEdge::kInlineEnd, BlockEdge::kBlockEnd},
+ {PhysicalOffset(30, 20), HorizontalEdge::kRight, VerticalEdge::kBottom},
+ WritingMode::kVerticalLr,
+ TextDirection::kLtr},
+ // |WritingMode::kVerticalLr|, |TextDirection::kRtl|
+ {{LogicalOffset(20, 30), InlineEdge::kInlineStart, BlockEdge::kBlockStart},
+ {PhysicalOffset(30, 80), HorizontalEdge::kLeft, VerticalEdge::kBottom},
+ WritingMode::kVerticalLr,
+ TextDirection::kRtl},
+ {{LogicalOffset(20, 30), InlineEdge::kInlineEnd, BlockEdge::kBlockStart},
+ {PhysicalOffset(30, 80), HorizontalEdge::kLeft, VerticalEdge::kTop},
+ WritingMode::kVerticalLr,
+ TextDirection::kRtl},
+ {{LogicalOffset(20, 30), InlineEdge::kInlineStart, BlockEdge::kBlockEnd},
+ {PhysicalOffset(30, 80), HorizontalEdge::kRight, VerticalEdge::kBottom},
+ WritingMode::kVerticalLr,
+ TextDirection::kRtl},
+ {{LogicalOffset(20, 30), InlineEdge::kInlineEnd, BlockEdge::kBlockEnd},
+ {PhysicalOffset(30, 80), HorizontalEdge::kRight, VerticalEdge::kTop},
+ WritingMode::kVerticalLr,
+ TextDirection::kRtl},
+ // |WritingMode::kSidewaysLr|, |TextDirection::kLtr|
+ {{LogicalOffset(20, 30), InlineEdge::kInlineStart, BlockEdge::kBlockStart},
+ {PhysicalOffset(30, 80), HorizontalEdge::kLeft, VerticalEdge::kBottom},
+ WritingMode::kSidewaysLr,
+ TextDirection::kLtr},
+ {{LogicalOffset(20, 30), InlineEdge::kInlineEnd, BlockEdge::kBlockStart},
+ {PhysicalOffset(30, 80), HorizontalEdge::kLeft, VerticalEdge::kTop},
+ WritingMode::kSidewaysLr,
+ TextDirection::kLtr},
+ {{LogicalOffset(20, 30), InlineEdge::kInlineStart, BlockEdge::kBlockEnd},
+ {PhysicalOffset(30, 80), HorizontalEdge::kRight, VerticalEdge::kBottom},
+ WritingMode::kSidewaysLr,
+ TextDirection::kLtr},
+ {{LogicalOffset(20, 30), InlineEdge::kInlineEnd, BlockEdge::kBlockEnd},
+ {PhysicalOffset(30, 80), HorizontalEdge::kRight, VerticalEdge::kTop},
+ WritingMode::kSidewaysLr,
+ TextDirection::kLtr},
+ // |WritingMode::kSidewaysLr|, |TextDirection::kRtl|
+ {{LogicalOffset(20, 30), InlineEdge::kInlineStart, BlockEdge::kBlockStart},
+ {PhysicalOffset(30, 20), HorizontalEdge::kLeft, VerticalEdge::kTop},
+ WritingMode::kSidewaysLr,
+ TextDirection::kRtl},
+ {{LogicalOffset(20, 30), InlineEdge::kInlineEnd, BlockEdge::kBlockStart},
+ {PhysicalOffset(30, 20), HorizontalEdge::kLeft, VerticalEdge::kBottom},
+ WritingMode::kSidewaysLr,
+ TextDirection::kRtl},
+ {{LogicalOffset(20, 30), InlineEdge::kInlineStart, BlockEdge::kBlockEnd},
+ {PhysicalOffset(30, 20), HorizontalEdge::kRight, VerticalEdge::kTop},
+ WritingMode::kSidewaysLr,
+ TextDirection::kRtl},
+ {{LogicalOffset(20, 30), InlineEdge::kInlineEnd, BlockEdge::kBlockEnd},
+ {PhysicalOffset(30, 20), HorizontalEdge::kRight, VerticalEdge::kBottom},
+ WritingMode::kSidewaysLr,
+ TextDirection::kRtl},
+};
+
+class NGStaticPositionTest
+ : public testing::Test,
+ public testing::WithParamInterface<NGStaticPositionTestData> {};
+
+TEST_P(NGStaticPositionTest, Convert) {
+ const auto& data = GetParam();
+
+ // These tests take the logical static-position, and convert it to a physical
+ // static-position with a 100x100 rect.
+ //
+ // It asserts that it is the same as the expected physical static-position,
+ // then performs the same operation in reverse.
+
+ NGPhysicalStaticPosition physical_result = data.logical.ConvertToPhysical(
+ data.writing_mode, data.direction, PhysicalSize(100, 100));
+ EXPECT_EQ(physical_result.offset, data.physical.offset);
+ EXPECT_EQ(physical_result.horizontal_edge, data.physical.horizontal_edge);
+ EXPECT_EQ(physical_result.vertical_edge, data.physical.vertical_edge);
+
+ NGLogicalStaticPosition logical_result = data.physical.ConvertToLogical(
+ data.writing_mode, data.direction, PhysicalSize(100, 100));
+ EXPECT_EQ(logical_result.offset, data.logical.offset);
+ EXPECT_EQ(logical_result.inline_edge, data.logical.inline_edge);
+ EXPECT_EQ(logical_result.block_edge, data.logical.block_edge);
+}
+
+INSTANTIATE_TEST_SUITE_P(NGStaticPositionTest,
+ NGStaticPositionTest,
+ testing::ValuesIn(ng_static_position_test_data));
+
+} // namespace
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/empty_offset_mapping_builder.h b/chromium/third_party/blink/renderer/core/layout/ng/inline/empty_offset_mapping_builder.h
index b6918488a29..0de484a0885 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/empty_offset_mapping_builder.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/empty_offset_mapping_builder.h
@@ -5,10 +5,12 @@
#ifndef EmptyOffsetMappingBuilder_h
#define EmptyOffsetMappingBuilder_h
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
+class LayoutText;
+
// A mock class providing all APIs of an offset mapping builder, but not doing
// anything. For templates functions/classes that can optionally create an
// offset mapping, this mock class is passed to create an instantiation that
@@ -29,6 +31,7 @@ class EmptyOffsetMappingBuilder {
void CollapseTrailingSpace(unsigned) {}
void Composite(const EmptyOffsetMappingBuilder&) {}
void Concatenate(const EmptyOffsetMappingBuilder&) {}
+ void RestoreTrailingCollapsibleSpace(const LayoutText&, unsigned) {}
private:
DISALLOW_COPY_AND_ASSIGN(EmptyOffsetMappingBuilder);
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 4e2517fba32..a03bdd430a7 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,7 +6,6 @@
#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_items.h"
namespace blink {
@@ -24,10 +23,12 @@ class CORE_EXPORT LayoutNGText : public LayoutText {
bool IsLayoutNGObject() const override { return true; }
private:
- const NGInlineItems* GetNGInlineItems() const final { return &inline_items_; }
- NGInlineItems* GetNGInlineItems() final { return &inline_items_; }
+ const base::span<NGInlineItem>* GetNGInlineItems() const final {
+ return &inline_items_;
+ }
+ base::span<NGInlineItem>* GetNGInlineItems() final { return &inline_items_; }
- NGInlineItems inline_items_;
+ base::span<NGInlineItem> 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
index 130a7b4c8ea..0612bfa8e6d 100644
--- 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
@@ -6,7 +6,6 @@
#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 {
@@ -24,15 +23,17 @@ class CORE_EXPORT LayoutNGTextFragment final : public LayoutTextFragment {
bool IsLayoutNGObject() const final { return true; }
private:
- const NGInlineItems* GetNGInlineItems() const final { return &inline_items_; }
- NGInlineItems* GetNGInlineItems() final { return &inline_items_; }
+ const base::span<NGInlineItem>* GetNGInlineItems() const final {
+ return &inline_items_;
+ }
+ base::span<NGInlineItem>* GetNGInlineItems() final { return &inline_items_; }
void InsertedIntoTree() final {
valid_ng_items_ = false;
LayoutText::InsertedIntoTree();
}
- NGInlineItems inline_items_;
+ base::span<NGInlineItem> inline_items_;
};
} // namespace blink
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 7fe1900ab55..4c1c7ee28da 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
@@ -99,15 +99,18 @@ bool NGAbstractInlineTextBox::NeedsTrailingSpace() const {
return false;
// Check a character in text content after |fragment_| comes from same
// layout text of |fragment_|.
- const NGOffsetMapping& mapping =
- *NGOffsetMapping::GetFor(fragment_->GetLayoutObject());
- const NGMappingUnitRange& mapping_units =
- mapping.GetMappingUnitsForTextContentOffsetRange(
+ const NGOffsetMapping* mapping =
+ NGOffsetMapping::GetFor(fragment_->GetLayoutObject());
+ // TODO(kojii): There's not much we can do for dirty-tree. crbug.com/946004
+ if (!mapping)
+ return false;
+ const base::span<const NGOffsetMappingUnit> mapping_units =
+ mapping->GetMappingUnitsForTextContentOffsetRange(
text_fragment.EndOffset(), text_fragment.EndOffset() + 1);
if (mapping_units.begin() == mapping_units.end())
return false;
- const NGOffsetMappingUnit* const mapping_unit = mapping_units.begin();
- return mapping_unit->GetLayoutObject() == fragment_->GetLayoutObject();
+ const NGOffsetMappingUnit& mapping_unit = mapping_units.front();
+ return mapping_unit.GetLayoutObject() == fragment_->GetLayoutObject();
}
const NGPaintFragment*
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 be83e72efc7..e527615ce8b 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
@@ -8,7 +8,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/geometry/layout_unit.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_bidi_paragraph.h b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_bidi_paragraph.h
index 222bbc81380..ee1c47fba4d 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_bidi_paragraph.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_bidi_paragraph.h
@@ -6,7 +6,7 @@
#define NGBidiParagraph_h
#include "third_party/blink/renderer/platform/text/text_direction.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_caret_position.h b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_caret_position.h
index 5da3eed8254..333934a6b84 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_caret_position.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_caret_position.h
@@ -8,7 +8,7 @@
#include "base/optional.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/editing/forward.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 3fa122f9709..0bdaf394987 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
@@ -11,6 +11,7 @@
#include "third_party/blink/renderer/core/layout/ng/inline/ng_text_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/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"
@@ -323,6 +324,20 @@ void NGInlineLayoutStateStack::AddBoxFragmentPlaceholder(
}
}
+void NGInlineLayoutStateStack::ChildInserted(unsigned index) {
+ for (NGInlineBoxState& state : stack_) {
+ if (state.fragment_start >= index)
+ ++state.fragment_start;
+ DCHECK(state.pending_descendants.IsEmpty());
+ }
+ for (BoxData& box_data : box_data_list_) {
+ if (box_data.fragment_start >= index)
+ ++box_data.fragment_start;
+ if (box_data.fragment_end >= index)
+ ++box_data.fragment_end;
+ }
+}
+
void NGInlineLayoutStateStack::PrepareForReorder(
NGLineBoxFragmentBuilder::ChildList* line_box) {
// There's nothing to do if no boxes.
@@ -583,8 +598,8 @@ NGInlineLayoutStateStack::BoxData::CreateBoxFragment(
const ComputedStyle& style = *item->Style();
NGFragmentGeometry fragment_geometry;
- fragment_geometry.border_box_size = size;
- fragment_geometry.border_box_size.inline_size.ClampNegativeToZero();
+ fragment_geometry.border_box_size = {size.inline_size.ClampNegativeToZero(),
+ size.block_size};
fragment_geometry.padding =
NGBoxStrut(padding, IsFlippedLinesWritingMode(style.GetWritingMode()));
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 2c6d9afb49d..335e04297e0 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
@@ -106,7 +106,7 @@ struct NGInlineBoxState {
// 2) Performs layout when the positin/size of a box was computed.
// 3) Cache common values for a box.
class CORE_EXPORT NGInlineLayoutStateStack {
- DISALLOW_NEW();
+ STACK_ALLOCATED();
public:
// The box state for the line box.
@@ -136,6 +136,9 @@ class CORE_EXPORT NGInlineLayoutStateStack {
bool HasBoxFragments() const { return !box_data_list_.IsEmpty(); }
+ // Notify when child is inserted at |index| to adjust child indexes.
+ void ChildInserted(unsigned index);
+
// This class keeps indexes to fragments in the line box, and that only
// appending is allowed. Call this function to move all such data to the line
// box, so that outside of this class can reorder fragments in the line box.
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_child_layout_context.h b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_child_layout_context.h
index 5992007f223..059776134d3 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_child_layout_context.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_child_layout_context.h
@@ -18,7 +18,7 @@ class NGInlineItem;
// Because this context is in initial state for when fragmentation occurs and
// some other cases, do not add things that are too expensive to rebuild.
class NGInlineChildLayoutContext {
- DISALLOW_NEW();
+ STACK_ALLOCATED();
public:
// Returns the NGInlineLayoutStateStack in this context.
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_fragment_traversal.cc b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_fragment_traversal.cc
index 5e20fc2a028..d9aa540d902 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_fragment_traversal.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_fragment_traversal.cc
@@ -113,27 +113,6 @@ class DescendantCollector final : public NGPhysicalFragmentCollectorBase {
DISALLOW_COPY_AND_ASSIGN(DescendantCollector);
};
-// The visitor emitting all visited fragments.
-class InclusiveDescendantCollector final
- : public NGPhysicalFragmentCollectorBase {
- STACK_ALLOCATED();
-
- public:
- InclusiveDescendantCollector() = default;
-
- Vector<Result> CollectFrom(const NGPhysicalFragment& fragment) final {
- return CollectInclusivelyFrom(fragment);
- }
-
- private:
- void Visit() final {
- Emit();
- VisitChildren();
- }
-
- DISALLOW_COPY_AND_ASSIGN(InclusiveDescendantCollector);
-};
-
// The visitor emitting fragments generated from the given LayoutInline,
// supporting culled inline.
// Note: Since we apply culled inline per line, we have a fragment for
@@ -182,66 +161,6 @@ class LayoutInlineCollector final : public NGPhysicalFragmentCollectorBase {
DISALLOW_COPY_AND_ASSIGN(LayoutInlineCollector);
};
-// The visitor emitting ancestors of the given fragment in bottom-up order.
-class AncestorCollector : public NGPhysicalFragmentCollectorBase {
- STACK_ALLOCATED();
-
- public:
- explicit AncestorCollector(const NGPhysicalFragment& target)
- : target_(target) {}
-
- Vector<Result> CollectFrom(const NGPhysicalFragment& fragment) final {
- // TODO(xiaochengh): Change this into CollectInclusivlyFrom() to include
- // subtree root to align with NodeTraversal::AncestorsOf().
- return CollectExclusivelyFrom(fragment);
- }
-
- private:
- void Visit() final {
- if (&GetFragment() == &target_) {
- SetShouldStopTraversing();
- return;
- }
-
- VisitChildren();
- if (HasStoppedTraversing())
- Emit();
- }
-
- const NGPhysicalFragment& target_;
-};
-
-// The visitor emitting inclusive ancestors of the given fragment in bottom-up
-// order.
-class InclusiveAncestorCollector : public NGPhysicalFragmentCollectorBase {
- STACK_ALLOCATED();
-
- public:
- explicit InclusiveAncestorCollector(const NGPhysicalFragment& target)
- : target_(target) {}
-
- Vector<Result> CollectFrom(const NGPhysicalFragment& fragment) final {
- // TODO(xiaochengh): Change this into CollectInclusivlyFrom() to include
- // subtree root to align with NodeTraversal::InclusiveAncestorsOf().
- return CollectExclusivelyFrom(fragment);
- }
-
- private:
- void Visit() final {
- if (&GetFragment() == &target_) {
- SetShouldStopTraversing();
- Emit();
- return;
- }
-
- VisitChildren();
- if (HasStoppedTraversing())
- Emit();
- }
-
- const NGPhysicalFragment& target_;
-};
-
} // namespace
// static
@@ -271,24 +190,4 @@ Vector<Result> NGInlineFragmentTraversal::DescendantsOf(
return DescendantCollector().CollectFrom(container);
}
-// static
-Vector<Result> NGInlineFragmentTraversal::InclusiveDescendantsOf(
- const NGPhysicalFragment& root) {
- return InclusiveDescendantCollector().CollectFrom(root);
-}
-
-// static
-Vector<Result> NGInlineFragmentTraversal::InclusiveAncestorsOf(
- const NGPhysicalContainerFragment& container,
- const NGPhysicalFragment& target) {
- return InclusiveAncestorCollector(target).CollectFrom(container);
-}
-
-// static
-Vector<Result> NGInlineFragmentTraversal::AncestorsOf(
- const NGPhysicalContainerFragment& container,
- const NGPhysicalFragment& target) {
- return AncestorCollector(target).CollectFrom(container);
-}
-
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_fragment_traversal.h b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_fragment_traversal.h
index 5c063598618..e2ec8c64b45 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_fragment_traversal.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_fragment_traversal.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/layout/ng/ng_physical_fragment.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
@@ -20,28 +20,11 @@ class CORE_EXPORT NGInlineFragmentTraversal {
STATIC_ONLY(NGInlineFragmentTraversal);
public:
- // Return list of ancestors from |target| to |container|. Offsets are relative
- // to |container|.
- static Vector<NGPhysicalFragmentWithOffset> AncestorsOf(
- const NGPhysicalContainerFragment& container,
- const NGPhysicalFragment& target);
-
- // Return list inclusive ancestors from |target| to |container|. Offsets are
- // relative to |container|.
- static Vector<NGPhysicalFragmentWithOffset> InclusiveAncestorsOf(
- const NGPhysicalContainerFragment& container,
- const NGPhysicalFragment& target);
-
// Returns list of descendants in preorder. Offsets are relative to
// specified fragment.
static Vector<NGPhysicalFragmentWithOffset> DescendantsOf(
const NGPhysicalContainerFragment&);
- // Returns list of inclusive descendants in preorder. Offsets are relative to
- // specified fragment.
- static Vector<NGPhysicalFragmentWithOffset> InclusiveDescendantsOf(
- const NGPhysicalFragment&);
-
// Returns list of inline fragments produced from the specified LayoutObject.
// The search is restricted in the subtree of |container|.
// Note: When |target| is a LayoutInline, some/all of its own box fragments
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_fragment_traversal_test.cc b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_fragment_traversal_test.cc
index b0751f82765..43d13c4a3f2 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_fragment_traversal_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_fragment_traversal_test.cc
@@ -76,25 +76,6 @@ TEST_F(NGInlineFragmentTraversalTest, DescendantsOf) {
EXPECT_EQ(iter, descendants.end());
}
-TEST_F(NGInlineFragmentTraversalTest, InclusiveDescendantsOf) {
- SetBodyInnerHTML(
- "<style>* { border: 1px solid}</style>"
- "<div id=t>foo<b id=b>bar</b><br>baz</div>");
- auto descendants = NGInlineFragmentTraversal::InclusiveDescendantsOf(
- GetRootFragmentById("t"));
- auto* iter = descendants.begin();
-
- EXPECT_NEXT_BOX(iter, "t");
- EXPECT_NEXT_LINE_BOX(iter);
- EXPECT_NEXT_TEXT(iter, "foo");
- EXPECT_NEXT_BOX(iter, "b");
- EXPECT_NEXT_TEXT(iter, "bar");
- EXPECT_NEXT_TEXT(iter, "\n");
- EXPECT_NEXT_LINE_BOX(iter);
- EXPECT_NEXT_TEXT(iter, "baz");
- EXPECT_EQ(iter, descendants.end());
-}
-
TEST_F(NGInlineFragmentTraversalTest, SelfFragmentsOf) {
SetBodyInnerHTML(
"<style>* { border: 1px solid}</style>"
@@ -110,44 +91,4 @@ TEST_F(NGInlineFragmentTraversalTest, SelfFragmentsOf) {
EXPECT_EQ(iter, descendants.end());
}
-TEST_F(NGInlineFragmentTraversalTest, AncestorsOf) {
- SetBodyInnerHTML(
- "<style>* { border: 1px solid}</style>"
- "<div id=t>x"
- "<b id=b>y<i id=i>z<u id=target>foo</u>z</i>y</b>"
- "x</div>");
- const NGPhysicalContainerFragment& root = GetRootFragmentById("t");
- const NGPhysicalFragment& target =
- GetFragmentOfNode(root, GetElementById("target")->firstChild());
- auto ancestors = NGInlineFragmentTraversal::AncestorsOf(root, target);
- auto* iter = ancestors.begin();
-
- EXPECT_NEXT_BOX(iter, "target");
- EXPECT_NEXT_BOX(iter, "i");
- EXPECT_NEXT_BOX(iter, "b");
- EXPECT_NEXT_LINE_BOX(iter);
- EXPECT_EQ(iter, ancestors.end());
-}
-
-TEST_F(NGInlineFragmentTraversalTest, InclusiveAncestorsOf) {
- SetBodyInnerHTML(
- "<style>* { border: 1px solid}</style>"
- "<div id=t>x"
- "<b id=b>y<i id=i>z<u id=target>foo</u>z</i>y</b>"
- "x</div>");
- const NGPhysicalContainerFragment& root = GetRootFragmentById("t");
- const NGPhysicalFragment& target =
- GetFragmentOfNode(root, GetElementById("target")->firstChild());
- auto ancestors =
- NGInlineFragmentTraversal::InclusiveAncestorsOf(root, target);
- auto* iter = ancestors.begin();
-
- EXPECT_NEXT_TEXT(iter, "foo");
- EXPECT_NEXT_BOX(iter, "target");
- EXPECT_NEXT_BOX(iter, "i");
- EXPECT_NEXT_BOX(iter, "b");
- EXPECT_NEXT_LINE_BOX(iter);
- EXPECT_EQ(iter, ancestors.end());
-}
-
} // namespace blink
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 faf30b8d38a..1e17b432948 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
@@ -69,11 +69,12 @@ NGInlineItem::NGInlineItem(NGInlineItemType type,
bidi_level_(UBIDI_LTR),
shape_options_(kPreContext | kPostContext),
is_empty_item_(false),
+ is_block_level_(false),
style_variant_(static_cast<unsigned>(NGStyleVariant::kStandard)),
end_collapse_type_(kNotCollapsible),
is_end_collapsible_newline_(false),
is_symbol_marker_(false),
- is_generated_(false) {
+ is_generated_for_line_break_(false) {
DCHECK_GE(end, start);
ComputeBoxProperties();
}
@@ -91,11 +92,12 @@ NGInlineItem::NGInlineItem(const NGInlineItem& other,
bidi_level_(other.bidi_level_),
shape_options_(other.shape_options_),
is_empty_item_(other.is_empty_item_),
+ is_block_level_(other.is_block_level_),
style_variant_(other.style_variant_),
end_collapse_type_(other.end_collapse_type_),
is_end_collapsible_newline_(other.is_end_collapsible_newline_),
is_symbol_marker_(other.is_symbol_marker_),
- is_generated_(other.is_generated_) {
+ is_generated_for_line_break_(other.is_generated_for_line_break_) {
DCHECK_GE(end, start);
}
@@ -125,6 +127,9 @@ void NGInlineItem::ComputeBoxProperties() {
return;
}
+ if (type_ == kOutOfFlowPositioned || type_ == kFloating)
+ is_block_level_ = true;
+
is_empty_item_ = true;
}
@@ -174,7 +179,7 @@ unsigned NGInlineItem::SetBidiLevel(Vector<NGInlineItem>& items,
String NGInlineItem::ToString() const {
return String::Format("NGInlineItem. Type: '%s'. LayoutObject: '%s'",
NGInlineItemTypeToString(Type()),
- GetLayoutObject()->DebugName().Ascii().data());
+ GetLayoutObject()->DebugName().Ascii().c_str());
}
// Split |items[index]| to 2 items at |offset|.
@@ -194,20 +199,4 @@ void NGInlineItem::Split(Vector<NGInlineItem>& items,
items[index + 1].start_offset_ = offset;
}
-const NGInlineItem& NGInlineItemsData::FindItemForTextOffset(
- unsigned offset) const {
- DCHECK_LT(offset, text_content.length());
- const NGInlineItem* item =
- std::lower_bound(items.begin(), items.end(), offset,
- [](const NGInlineItem& item, unsigned offset) {
- if (item.StartOffset() > offset)
- return false;
- return item.EndOffset() <= offset;
- });
- DCHECK_NE(item, items.end());
- DCHECK_LE(item->StartOffset(), offset);
- DCHECK_LT(offset, item->EndOffset());
- return *item;
-}
-
} // namespace blink
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 4b63469e5f2..81be1dd387d 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
@@ -87,6 +87,13 @@ class CORE_EXPORT NGInlineItem {
bool IsEmptyItem() const { return is_empty_item_; }
void SetIsEmptyItem(bool value) { is_empty_item_ = value; }
+ // If this item is either a float or OOF-positioned node. If an inline
+ // formatting-context *only* contains these types of nodes we consider it
+ // block-level, and run the |NGBlockLayoutAlgorithm| instead of the
+ // |NGInlineLayoutAlgorithm|.
+ bool IsBlockLevel() const { return is_block_level_; }
+ void SetIsBlockLevel(bool value) { is_block_level_ = value; }
+
// If this item should create a box fragment. Box fragments can be omitted for
// optimization if this is false.
bool ShouldCreateBoxFragment() const {
@@ -175,8 +182,8 @@ class CORE_EXPORT NGInlineItem {
// context that are lost during the whitespace collapsing. This item is used
// during the line breaking and layout, but is not supposed to generate
// fragments.
- bool IsGenerated() const { return is_generated_; }
- void SetIsGenerated() { is_generated_ = true; }
+ bool IsGeneratedForLineBreak() const { return is_generated_for_line_break_; }
+ void SetIsGeneratedForLineBreak() { is_generated_for_line_break_ = true; }
// Whether the end collapsible space run contains a newline.
// Valid only when kCollapsible or kCollapsed.
@@ -190,10 +197,6 @@ class CORE_EXPORT NGInlineItem {
// RunSegmenter properties.
unsigned SegmentData() const { return segment_data_; }
- void SetSegmentData(unsigned segment_data) {
- DCHECK_EQ(Type(), NGInlineItem::kText);
- segment_data_ = segment_data;
- }
static void SetSegmentData(const RunSegmenter::RunSegmenterRange& range,
Vector<NGInlineItem>* items);
@@ -235,15 +238,17 @@ class CORE_EXPORT NGInlineItem {
LayoutObject* layout_object_;
NGInlineItemType type_;
+ // |segment_data_| is valid only for |type_ == NGInlineItem::kText|.
unsigned segment_data_ : NGInlineItemSegment::kSegmentDataBits;
unsigned bidi_level_ : 8; // UBiDiLevel is defined as uint8_t.
unsigned shape_options_ : 2;
unsigned is_empty_item_ : 1;
+ unsigned is_block_level_ : 1;
unsigned style_variant_ : 2;
unsigned end_collapse_type_ : 2; // NGCollapseType
unsigned is_end_collapsible_newline_ : 1;
unsigned is_symbol_marker_ : 1;
- unsigned is_generated_ : 1;
+ unsigned is_generated_for_line_break_ : 1;
friend class NGInlineNode;
};
@@ -283,11 +288,6 @@ struct CORE_EXPORT NGInlineItemsData {
void AssertEndOffset(unsigned index, unsigned offset) const {
items[index].AssertEndOffset(offset);
}
-
- // Returns the non-zero-length inline item whose |StartOffset() <= offset| and
- // |EndOffset() > offset|, namely, contains the character at |offset|.
- // Note: This function is not a trivial getter, but does a binary search.
- const NGInlineItem& FindItemForTextOffset(unsigned offset) const;
};
} // namespace blink
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 505bf23e4d6..95ba2a64962 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
@@ -12,7 +12,7 @@
#include "third_party/blink/renderer/core/layout/ng/ng_positioned_float.h"
#include "third_party/blink/renderer/platform/fonts/shaping/shape_result.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/allocator/allocator.h"
namespace blink {
@@ -32,6 +32,11 @@ struct CORE_EXPORT NGInlineItemResult {
DISALLOW_NEW();
public:
+ unsigned Length() const {
+ DCHECK_GT(end_offset, start_offset);
+ return end_offset - start_offset;
+ }
+
// The NGInlineItem and its index.
const NGInlineItem* item;
unsigned item_index;
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_item_segment.h b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_item_segment.h
index b22da6db46c..f011dfa9aa1 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_item_segment.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_item_segment.h
@@ -12,7 +12,7 @@
#include "third_party/blink/renderer/platform/fonts/shaping/run_segmenter.h"
#include "third_party/blink/renderer/platform/fonts/shaping/shape_result.h"
#include "third_party/blink/renderer/platform/text/text_direction.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include <unicode/ubidi.h>
#include <unicode/uscript.h>
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
deleted file mode 100644
index 063bebd4dae..00000000000
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_items.h
+++ /dev/null
@@ -1,50 +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_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 SetRange(NGInlineItem* begin, NGInlineItem* end) {
- begin_ = begin;
- end_ = end;
- }
- void Clear() { begin_ = end_ = nullptr; }
-
- bool IsEmpty() const { return begin_ == end_; }
-
- const NGInlineItem& front() const {
- CHECK(!IsEmpty());
- return *begin_;
- }
-
- const NGInlineItem* begin() const { return begin_; }
- const NGInlineItem* end() const { return end_; }
-
- private:
- NGInlineItem* begin_ = nullptr;
- NGInlineItem* end_ = nullptr;
-
- 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 e881df5256a..a3d84fb4390 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
@@ -247,7 +247,9 @@ void NGInlineItemsBuilderTemplate<OffsetMappingBuilder>::AppendTextItem(
mapping_builder_.AppendIdentityMapping(string.length());
AppendItem(items_, type, start_offset, text_.length(), layout_object);
DCHECK(!items_->back().IsEmptyItem());
- is_empty_inline_ = false; // text item is not empty.
+ // text item is not empty.
+ is_empty_inline_ = false;
+ is_block_level_ = false;
}
// Empty text items are not needed for the layout purposes, but all LayoutObject
@@ -262,6 +264,7 @@ void NGInlineItemsBuilderTemplate<OffsetMappingBuilder>::AppendEmptyTextItem(
NGInlineItem& item = items_->back();
item.SetEndCollapseType(NGInlineItem::kOpaqueToCollapsing);
item.SetIsEmptyItem(true);
+ item.SetIsBlockLevel(true);
}
// Same as AppendBreakOpportunity, but mark the item as IsGenerated().
@@ -273,7 +276,7 @@ void NGInlineItemsBuilderTemplate<OffsetMappingBuilder>::
nullptr);
AppendBreakOpportunity(layout_object);
NGInlineItem* item = &items_->back();
- item->SetIsGenerated();
+ item->SetIsGeneratedForLineBreak();
item->SetEndCollapseType(NGInlineItem::kOpaqueToCollapsing);
}
@@ -282,7 +285,7 @@ bool NGInlineItemsBuilderTemplate<OffsetMappingBuilder>::AppendTextReusing(
const NGInlineNodeData& original_data,
LayoutText* layout_text) {
DCHECK(layout_text);
- const NGInlineItems& items = layout_text->InlineItems();
+ const base::span<NGInlineItem>& items = layout_text->InlineItems();
const NGInlineItem& old_item0 = items.front();
if (!old_item0.Length())
return false;
@@ -392,6 +395,7 @@ bool NGInlineItemsBuilderTemplate<OffsetMappingBuilder>::AppendTextReusing(
if (item.StartOffset() == start) {
items_->push_back(item);
is_empty_inline_ &= item.IsEmptyItem();
+ is_block_level_ &= item.IsBlockLevel();
continue;
}
@@ -422,6 +426,7 @@ bool NGInlineItemsBuilderTemplate<OffsetMappingBuilder>::AppendTextReusing(
items_->push_back(adjusted_item);
is_empty_inline_ &= adjusted_item.IsEmptyItem();
+ is_block_level_ &= adjusted_item.IsBlockLevel();
}
return true;
}
@@ -556,7 +561,12 @@ void NGInlineItemsBuilderTemplate<
// removed entirely. However, when the first collapsible space is
// 'nowrap', and the following collapsed space is 'wrap', the
// collapsed space needs to create a break opportunity.
- AppendGeneratedBreakOpportunity(layout_object);
+ // Note that we don't need to generate a break opportunity right
+ // after a forced break.
+ if (item->Type() != NGInlineItem::kControl ||
+ text_[item->StartOffset()] != kNewlineCharacter) {
+ AppendGeneratedBreakOpportunity(layout_object);
+ }
}
}
} else {
@@ -674,17 +684,48 @@ void NGInlineItemsBuilderTemplate<
NGInlineItem& item = items_->back();
item.SetEndCollapseType(end_collapse, space_run_has_newline);
DCHECK(!item.IsEmptyItem());
- is_empty_inline_ = false; // text item is not empty.
+ // text item is not empty.
+ is_empty_inline_ = false;
+ is_block_level_ = false;
}
template <typename OffsetMappingBuilder>
bool NGInlineItemsBuilderTemplate<OffsetMappingBuilder>::
ShouldInsertBreakOpportunityAfterLeadingPreservedSpaces(
const String& string,
- const ComputedStyle& style) const {
- return text_.IsEmpty() && string.length() > 0 &&
- string[0] == kSpaceCharacter && !style.CollapseWhiteSpace() &&
- style.AutoWrap();
+ const ComputedStyle& style,
+ unsigned index) const {
+ DCHECK_LE(index, string.length());
+ // Check if we are at a preserved space character and auto-wrap is enabled.
+ if (style.CollapseWhiteSpace() || !style.AutoWrap() || !string.length() ||
+ index >= string.length() || string[index] != kSpaceCharacter)
+ return false;
+
+ // Preserved leading spaces must be at the beginning of the first line or just
+ // after a forced break.
+ if (index)
+ return string[index - 1] == kNewlineCharacter;
+ return text_.IsEmpty() || text_[text_.length() - 1] == kNewlineCharacter;
+}
+
+template <typename OffsetMappingBuilder>
+void NGInlineItemsBuilderTemplate<OffsetMappingBuilder>::
+ InsertBreakOpportunityAfterLeadingPreservedSpaces(
+ const String& string,
+ const ComputedStyle& style,
+ LayoutText* layout_object,
+ unsigned* start) {
+ DCHECK(start);
+ if (UNLIKELY(ShouldInsertBreakOpportunityAfterLeadingPreservedSpaces(
+ string, style, *start))) {
+ wtf_size_t end = *start;
+ do {
+ ++end;
+ } while (end < string.length() && string[end] == kSpaceCharacter);
+ AppendTextItem(StringView(string, *start, end - *start), layout_object);
+ AppendGeneratedBreakOpportunity(layout_object);
+ *start = end;
+ }
}
// TODO(yosin): We should remove |style| and |string| parameter because of
@@ -704,21 +745,19 @@ void NGInlineItemsBuilderTemplate<
// opportunity after leading preserved spaces needs a special code in the line
// breaker. Generate an opportunity to make it easy.
unsigned start = 0;
- if (UNLIKELY(ShouldInsertBreakOpportunityAfterLeadingPreservedSpaces(
- string, *style))) {
- do {
- ++start;
- } while (start < string.length() && string[start] == kSpaceCharacter);
- AppendTextItem(StringView(string, 0, start), layout_object);
- AppendGeneratedBreakOpportunity(layout_object);
- }
-
+ InsertBreakOpportunityAfterLeadingPreservedSpaces(string, *style,
+ layout_object, &start);
for (; start < string.length();) {
UChar c = string[start];
if (IsControlItemCharacter(c)) {
if (c == kNewlineCharacter) {
AppendForcedBreak(layout_object);
start++;
+ // A forced break is not a collapsible space, but following collapsible
+ // spaces are leading spaces and they need a special code in the line
+ // breaker. Generate an opportunity to make it easy.
+ InsertBreakOpportunityAfterLeadingPreservedSpaces(
+ string, *style, layout_object, &start);
continue;
}
if (c == kTabulationCharacter) {
@@ -832,6 +871,7 @@ void NGInlineItemsBuilderTemplate<OffsetMappingBuilder>::Append(
AppendItem(items_, type, end_offset - 1, end_offset, layout_object);
is_empty_inline_ &= items_->back().IsEmptyItem();
+ is_block_level_ &= items_->back().IsBlockLevel();
}
template <typename OffsetMappingBuilder>
@@ -897,6 +937,7 @@ void NGInlineItemsBuilderTemplate<OffsetMappingBuilder>::AppendOpaque(
NGInlineItem& item = items_->back();
item.SetEndCollapseType(NGInlineItem::kOpaqueToCollapsing);
is_empty_inline_ &= item.IsEmptyItem();
+ is_block_level_ &= item.IsBlockLevel();
}
template <typename OffsetMappingBuilder>
@@ -909,6 +950,7 @@ void NGInlineItemsBuilderTemplate<OffsetMappingBuilder>::AppendOpaque(
NGInlineItem& item = items_->back();
item.SetEndCollapseType(NGInlineItem::kOpaqueToCollapsing);
is_empty_inline_ &= item.IsEmptyItem();
+ is_block_level_ &= item.IsBlockLevel();
}
// Removes the collapsible space at the end of |text_| if exists.
@@ -977,6 +1019,9 @@ void NGInlineItemsBuilderTemplate<
DCHECK(item);
DCHECK(item->EndCollapseType() == NGInlineItem::kCollapsed);
+ mapping_builder_.RestoreTrailingCollapsibleSpace(
+ ToLayoutText(*item->GetLayoutObject()), item->EndOffset());
+
// TODO(kojii): Implement StringBuilder::insert().
if (text_.length() == item->EndOffset()) {
text_.Append(' ');
@@ -1056,8 +1101,10 @@ void NGInlineItemsBuilderTemplate<OffsetMappingBuilder>::EnterBlock(
}
if (style->Display() == EDisplay::kListItem &&
- style->ListStyleType() != EListStyleType::kNone)
+ style->ListStyleType() != EListStyleType::kNone) {
is_empty_inline_ = false;
+ is_block_level_ = false;
+ }
}
template <typename OffsetMappingBuilder>
@@ -1167,7 +1214,6 @@ template <typename OffsetMappingBuilder>
void NGInlineItemsBuilderTemplate<OffsetMappingBuilder>::ClearInlineFragment(
LayoutObject* object) {
object->SetIsInLayoutNGInlineFormattingContext(true);
- object->SetFirstInlineFragment(nullptr);
}
template <typename OffsetMappingBuilder>
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 b7c9530edd1..07abca2e18b 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
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_item.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_offset_mapping_builder.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.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"
@@ -62,6 +62,8 @@ class NGInlineItemsBuilderTemplate {
// <span></span> or <span><float></float></span>.
bool IsEmptyInline() const { return is_empty_inline_; }
+ bool IsBlockLevel() const { return is_block_level_; }
+
// True if changes to an item may affect different layout of earlier lines.
// May not be able to use line caches even when the line or earlier lines are
// not dirty.
@@ -178,6 +180,7 @@ class NGInlineItemsBuilderTemplate {
bool has_bidi_controls_ = false;
bool is_empty_inline_ = true;
+ bool is_block_level_ = true;
bool changes_may_affect_earlier_lines_ = false;
// Append a character.
@@ -220,7 +223,12 @@ class NGInlineItemsBuilderTemplate {
bool ShouldInsertBreakOpportunityAfterLeadingPreservedSpaces(
const String&,
- const ComputedStyle&) const;
+ const ComputedStyle&,
+ unsigned index = 0) const;
+ void InsertBreakOpportunityAfterLeadingPreservedSpaces(const String&,
+ const ComputedStyle&,
+ LayoutText*,
+ unsigned* start);
};
template <>
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 56fa24daadc..df95d2fd3f6 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
@@ -31,6 +31,12 @@ class NGInlineItemsBuilderTest : public NGLayoutTest {
style_->GetFont().Update(nullptr);
}
+ void TearDown() override {
+ for (LayoutObject* anonymous_object : anonymous_objects_)
+ anonymous_object->Destroy();
+ NGLayoutTest::TearDown();
+ }
+
void SetWhiteSpace(EWhiteSpace whitespace) {
style_->SetWhiteSpace(whitespace);
}
@@ -181,7 +187,7 @@ TEST_F(NGInlineItemsBuilderTest, CollapseTabs) {
}
TEST_F(NGInlineItemsBuilderTest, CollapseNewLines) {
- String input("text\ntext \n text\n\ntext");
+ String input("text\ntext \ntext\n\ntext");
String collapsed("text text text text");
TestWhitespaceValue(collapsed, input, EWhiteSpace::kNormal);
TestWhitespaceValue(collapsed, input, EWhiteSpace::kNowrap);
@@ -419,6 +425,9 @@ TEST_F(NGInlineItemsBuilderTest, GenerateBreakOpportunityAfterLeadingSpaces) {
u"\u200B"
"a"),
TestAppend({{" a", EWhiteSpace::kPreWrap}}));
+ EXPECT_EQ(String("a\n"
+ u" \u200B"),
+ TestAppend({{"a\n ", EWhiteSpace::kPreWrap}}));
}
TEST_F(NGInlineItemsBuilderTest, BidiBlockOverride) {
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 f3d4a644b8c..d82beb0fb5d 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
@@ -85,6 +85,13 @@ NGInlineBoxState* NGInlineLayoutAlgorithm::HandleOpenTag(
// https://drafts.csswg.org/css2/visudet.html#line-height
if (!quirks_mode_ || !item.IsEmptyItem())
box->ComputeTextMetrics(*item.Style(), baseline_type_);
+
+ if (item.Style()->HasMask()) {
+ // Layout may change the bounding box, which affects MaskClip.
+ if (LayoutObject* object = item.GetLayoutObject())
+ object->SetNeedsPaintPropertyUpdate();
+ }
+
return box;
}
@@ -188,8 +195,7 @@ void NGInlineLayoutAlgorithm::CreateLine(
// of items, which are needed to compute inline static positions.
LayoutUnit line_offset_for_text_align = ApplyTextAlign(line_info);
- NGTextFragmentBuilder text_builder(Node(),
- ConstraintSpace().GetWritingMode());
+ NGTextFragmentBuilder text_builder(ConstraintSpace().GetWritingMode());
// 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.
@@ -305,8 +311,8 @@ void NGInlineLayoutAlgorithm::CreateLine(
// Truncate the line if 'text-overflow: ellipsis' is set.
if (UNLIKELY(inline_size > line_info->AvailableWidth() &&
node_.GetLayoutBlockFlow()->ShouldTruncateOverflowingText())) {
- inline_size = NGLineTruncator(node_, *line_info)
- .TruncateLine(inline_size, &line_box_);
+ inline_size = NGLineTruncator(*line_info)
+ .TruncateLine(inline_size, &line_box_, box_states_);
}
// Negative margins can make the position negative, but the inline size is
@@ -399,7 +405,7 @@ void NGInlineLayoutAlgorithm::PlaceControlItem(const NGInlineItem& item,
case kZeroWidthSpaceCharacter:
// Don't generate fragments if this is a generated (not in DOM) break
// opportunity during the white space collapsing in NGInlineItemBuilder.
- if (item.IsGenerated())
+ if (item.IsGeneratedForLineBreak())
return;
type = NGPhysicalTextFragment::kFlowControl;
break;
@@ -414,8 +420,7 @@ void NGInlineLayoutAlgorithm::PlaceControlItem(const NGInlineItem& item,
if (UNLIKELY(quirks_mode_ && !box->HasMetrics()))
box->EnsureTextMetrics(*item.Style(), baseline_type_);
- NGTextFragmentBuilder text_builder(Node(),
- ConstraintSpace().GetWritingMode());
+ NGTextFragmentBuilder text_builder(ConstraintSpace().GetWritingMode());
text_builder.SetItem(type, line_info.ItemsData(), item_result,
box->text_height);
line_box_.AddChild(text_builder.ToTextFragment(), box->text_top,
@@ -552,7 +557,7 @@ void NGInlineLayoutAlgorithm::PlaceOutOfFlowObjects(
// yet. Due to this we need to mark this node as having adjoining
// objects, and perform a re-layout if our position shifts.
if (is_empty_inline)
- container_builder_.AddAdjoiningFloatTypes(kAdjoiningInlineOutOfFlow);
+ container_builder_.AddAdjoiningObjectTypes(kAdjoiningInlineOutOfFlow);
} else {
// A block-level OOF element positions itself on the "next" line. However
// only shifts down if there is inline-level content.
@@ -586,19 +591,16 @@ void NGInlineLayoutAlgorithm::PlaceFloatingObjects(
LayoutUnit origin_bfc_block_offset =
opportunity.bfc_block_offset + line_height;
- bool is_empty_inline = Node().IsEmptyInline();
-
- LayoutUnit bfc_block_offset = line_info.BfcOffset().block_offset;
- if (is_empty_inline && ConstraintSpace().ForcedBfcBlockOffset())
- bfc_block_offset = *ConstraintSpace().ForcedBfcBlockOffset();
-
LayoutUnit bfc_line_offset = container_builder_.BfcLineOffset();
+ LayoutUnit bfc_block_offset = Node().IsEmptyInline()
+ ? ConstraintSpace().ExpectedBfcBlockOffset()
+ : line_info.BfcOffset().block_offset;
for (NGLineBoxFragmentBuilder::Child& child : line_box_) {
// We need to position any floats which should be on the "next" line now.
// If this is an empty inline, all floats are positioned during the
// PositionLeadingFloats step.
- if (child.unpositioned_float && !is_empty_inline) {
+ if (child.unpositioned_float) {
NGPositionedFloat positioned_float = PositionFloat(
origin_bfc_block_offset, child.unpositioned_float, exclusion_space);
@@ -656,6 +658,10 @@ bool NGInlineLayoutAlgorithm::ApplyJustify(LayoutUnit space,
if (space <= 0)
return false;
+ // Can't justify an empty string.
+ if (end_offset == line_info->StartOffset())
+ return false;
+
// Construct the line text to compute spacing for.
StringBuilder line_text_builder;
line_text_builder.Append(StringView(line_info->ItemsData().text_content,
@@ -672,6 +678,8 @@ bool NGInlineLayoutAlgorithm::ApplyJustify(LayoutUnit space,
// Compute the spacing to justify.
String line_text = line_text_builder.ToString();
+ DCHECK_GT(line_text.length(), 0u);
+
ShapeResultSpacing<String> spacing(line_text);
spacing.SetExpansion(space, line_info->BaseDirection(),
line_info->LineStyle().GetTextJustify());
@@ -774,11 +782,11 @@ scoped_refptr<const NGLayoutResult> NGInlineLayoutAlgorithm::Layout() {
container_builder_.SetEndMarginStrut(ConstraintSpace().MarginStrut());
// We're just going to collapse through this one, so whatever went in on one
- // side will go out on the other side. The position of the adjoining floats
+ // side will go out on the other side. The position of the adjoining objects
// will be affected by any subsequent block, until the BFC block offset is
// resolved.
- container_builder_.AddAdjoiningFloatTypes(
- ConstraintSpace().AdjoiningFloatTypes());
+ container_builder_.AddAdjoiningObjectTypes(
+ ConstraintSpace().AdjoiningObjectTypes());
// For the empty lines, most of the logic here are not necessary, but in
// some edge cases we still need to create box fragments, such as when it
@@ -787,9 +795,9 @@ scoped_refptr<const NGLayoutResult> NGInlineLayoutAlgorithm::Layout() {
} else {
DCHECK(ConstraintSpace().MarginStrut().IsEmpty());
- // The BFC block offset was determined before entering this algorithm. This
- // means that there should be no adjoining floats.
- DCHECK(!ConstraintSpace().AdjoiningFloatTypes());
+ // The BFC block-offset was determined before entering this algorithm. This
+ // means that there should be no adjoining objects.
+ DCHECK(!ConstraintSpace().AdjoiningObjectTypes());
}
// In order to get the correct list of layout opportunities, we need to
@@ -806,8 +814,8 @@ scoped_refptr<const NGLayoutResult> NGInlineLayoutAlgorithm::Layout() {
const LayoutOpportunityVector opportunities =
initial_exclusion_space.AllLayoutOpportunities(
{ConstraintSpace().BfcOffset().line_offset,
- ConstraintSpace().ForcedBfcBlockOffset().value_or(
- ConstraintSpace().BfcOffset().block_offset)},
+ is_empty_inline ? ConstraintSpace().ExpectedBfcBlockOffset()
+ : ConstraintSpace().BfcOffset().block_offset},
ConstraintSpace().AvailableSize().inline_size);
NGExclusionSpace exclusion_space;
@@ -868,17 +876,19 @@ scoped_refptr<const NGLayoutResult> NGInlineLayoutAlgorithm::Layout() {
!opportunity.IsBlockDeltaBelowShapes(block_delta)) {
block_delta += LayoutUnit(1);
line_block_size = LayoutUnit();
- } else {
- // We've either don't have any shapes, or run out of block-delta space
- // to test, proceed to the next layout opportunity.
+ continue;
+ }
+ // We've either don't have any shapes, or run out of block-delta space
+ // to test, proceed to the next layout opportunity.
+ if (opportunities_it + 1 != opportunities.end()) {
block_delta = LayoutUnit();
line_block_size = LayoutUnit();
++opportunities_it;
+ continue;
}
- // There must be at least one more opportunity, or we fail to call
- // |CreateLine()|.
- DCHECK_NE(opportunities_it, opportunities.end());
- continue;
+ // Normally the last opportunity should fit the line, but arithmetic
+ // overflow can lead to failures for all opportunities. Just let the line
+ // to overflow in that case.
}
PrepareBoxStates(line_info, break_token);
@@ -935,9 +945,9 @@ scoped_refptr<const NGLayoutResult> NGInlineLayoutAlgorithm::Layout() {
ComputeContentSize(line_info, exclusion_space, line_height));
// As we aren't an empty inline we should have correctly placed all
- // our adjoining floats, and shouldn't propagate this information
+ // our adjoining objects, and shouldn't propagate this information
// to siblings.
- container_builder_.ResetAdjoiningFloatTypes();
+ container_builder_.ResetAdjoiningObjectTypes();
if (opportunity.rect.BlockStartOffset() >
ConstraintSpace().BfcOffset().block_offset)
@@ -976,19 +986,16 @@ unsigned NGInlineLayoutAlgorithm::PositionLeadingFloats(
if (item.Type() != NGInlineItem::kFloating || should_ignore_floats)
continue;
- container_builder_.AddAdjoiningFloatTypes(
+ container_builder_.AddAdjoiningObjectTypes(
ResolvedFloating(item.GetLayoutObject()->StyleRef().Floating(),
ConstraintSpace().Direction()) == EFloat::kLeft
- ? kFloatTypeLeft
- : kFloatTypeRight);
-
- // If we are an empty inline, and don't have the special forced BFC
- // block-offset yet, there is no way to position any floats.
- if (is_empty_inline && !ConstraintSpace().ForcedBfcBlockOffset())
- continue;
+ ? kAdjoiningFloatLeft
+ : kAdjoiningFloatRight);
+ // Place any floats at the "expected" BFC block-offset, this may be an
+ // optimistic guess.
LayoutUnit origin_bfc_block_offset =
- is_empty_inline ? *ConstraintSpace().ForcedBfcBlockOffset()
+ is_empty_inline ? ConstraintSpace().ExpectedBfcBlockOffset()
: ConstraintSpace().BfcOffset().block_offset;
NGPositionedFloat positioned_float = PositionFloat(
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 1c01a0a125e..94c4a3258ac 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
@@ -119,9 +119,8 @@ TEST_F(NGInlineLayoutAlgorithmTest, GenerateEllipsis) {
To<NGPhysicalLineBoxFragment>(*block->Children()[0].get());
// The ellipsis is in its own NGPhysicalTextFragment.
- EXPECT_EQ(2u, line1.Children().size());
- EXPECT_EQ(NGPhysicalFragment::kFragmentText, line1.Children()[1]->Type());
- const auto& ellipsis = To<NGPhysicalTextFragment>(*line1.Children()[1].get());
+ EXPECT_EQ(3u, line1.Children().size());
+ const auto& ellipsis = To<NGPhysicalTextFragment>(*line1.Children().back());
EXPECT_EQ(String(u"\u2026"), ellipsis.Text().ToString());
// It should have the same LayoutObject as the clipped word.
EXPECT_EQ(line1.Children()[0]->GetLayoutObject(), ellipsis.GetLayoutObject());
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 846eb8c7ef1..912fa83b133 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
@@ -491,6 +491,7 @@ void NGInlineNode::CollectInlines(NGInlineNodeData* data,
// doesn't contain any RTL characters.
data->is_bidi_enabled_ = MayBeBidiEnabled(data->text_content, builder);
data->is_empty_inline_ = builder.IsEmptyInline();
+ data->is_block_level_ = builder.IsBlockLevel();
data->changes_may_affect_earlier_lines_ =
builder.ChangesMayAffectEarlierLines();
}
@@ -889,13 +890,8 @@ void NGInlineNode::ClearAssociatedFragments(
auto* block_flow = To<LayoutBlockFlow>(fragment.GetMutableLayoutObject());
if (!block_flow->ChildrenInline())
return;
+ DCHECK(AreNGBlockFlowChildrenInline(block_flow));
NGInlineNode node = NGInlineNode(block_flow);
-#if DCHECK_IS_ON()
- // We assume this function is called for the LayoutObject of an NGInlineNode.
- NGLayoutInputNode first_child = NGBlockNode(block_flow).FirstChild();
- DCHECK(first_child && first_child.IsInline());
- DCHECK(first_child == node);
-#endif
DCHECK(node.IsPrepareLayoutFinished());
const Vector<NGInlineItem>& items = node.MaybeDirtyData().items;
@@ -924,9 +920,12 @@ void NGInlineNode::ClearAssociatedFragments(
LayoutObject* last_object = nullptr;
for (unsigned i = start_index; i < items.size(); i++) {
const NGInlineItem& item = items[i];
- if (item.Type() == NGInlineItem::kOutOfFlowPositioned ||
- item.Type() == NGInlineItem::kListMarker)
+ if (item.Type() == NGInlineItem::kFloating ||
+ item.Type() == NGInlineItem::kOutOfFlowPositioned) {
+ // These items are not associated and that no need to clear.
+ DCHECK(!item.GetLayoutObject()->FirstInlineFragment());
continue;
+ }
LayoutObject* object = item.GetLayoutObject();
if (!object || object == last_object)
continue;
@@ -1191,7 +1190,8 @@ static LayoutUnit ComputeContentSize(
is_after_break = true;
}
- void AddTabulationCharacters(const NGInlineItem& item) {
+ void AddTabulationCharacters(const NGInlineItem& item, unsigned length) {
+ DCHECK_GE(length, 1u);
AddTextUntil(&item);
DCHECK(item.Style());
const ComputedStyle& style = *item.Style();
@@ -1199,7 +1199,6 @@ static LayoutUnit ComputeContentSize(
const SimpleFontData* font_data = font.PrimaryFont();
const TabSize& tab_size = style.GetTabSize();
float advance = font.TabWidth(font_data, tab_size, position);
- unsigned length = item.Length();
DCHECK_GE(length, 1u);
if (length > 1u)
advance += font.TabWidth(font_data, tab_size) * (length - 1);
@@ -1242,7 +1241,7 @@ static LayoutUnit ComputeContentSize(
// their widths for the max size may be different from the widths for
// the min size. Fall back to 2 pass for now.
if (c == kTabulationCharacter) {
- AddTabulationCharacters(item);
+ AddTabulationCharacters(item, result.Length());
continue;
}
}
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 a3bcb07a50b..e9f6f1031aa 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
@@ -93,6 +93,8 @@ class CORE_EXPORT NGInlineNode : public NGLayoutInputNode {
bool IsEmptyInline() { return EnsureData().is_empty_inline_; }
+ bool IsBlockLevel() { return EnsureData().is_block_level_; }
+
// @return if this node can contain the "first formatted line".
// https://www.w3.org/TR/CSS22/selector.html#first-formatted-line
bool CanContainFirstFormattedLine() const {
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node_data.h b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node_data.h
index 833d63944c7..b7c04d46b10 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node_data.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node_data.h
@@ -21,6 +21,8 @@ struct CORE_EXPORT NGInlineNodeData : NGInlineItemsData {
bool IsEmptyInline() const { return is_empty_inline_; }
+ bool IsBlockLevel() const { return is_block_level_; }
+
private:
const NGInlineItemsData& ItemsData(bool is_first_line) const {
return !is_first_line || !first_line_items_
@@ -52,6 +54,12 @@ struct CORE_EXPORT NGInlineNodeData : NGInlineItemsData {
// inlines, open/close tags with margins/border/padding this will be false.
unsigned is_empty_inline_ : 1;
+ // We use this flag to determine if we have *only* floats, and OOF-positioned
+ // children. If so we consider them block-level, and run the
+ // |NGBlockLayoutAlgorithm| instead of the |NGInlineLayoutAlgorithm|. This is
+ // done to pick up block-level static-position behaviour.
+ unsigned is_block_level_ : 1;
+
// True if changes to an item may affect different layout of earlier lines.
// May not be able to use line caches even when the line or earlier lines are
// not dirty.
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 4ee6e041cba..2e844d26617 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
@@ -7,9 +7,10 @@
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.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/text.h"
+#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_child_layout_context.h"
-#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_items.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_layout_algorithm.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"
@@ -36,7 +37,7 @@ class NGInlineNodeForTest : public NGInlineNode {
public:
using NGInlineNode::NGInlineNode;
- std::string Text() const { return Data().text_content.Utf8().data(); }
+ std::string Text() const { return Data().text_content.Utf8(); }
Vector<NGInlineItem>& Items() { return MutableData()->items; }
static Vector<NGInlineItem>& Items(NGInlineNodeData& data) {
return data.items;
@@ -521,6 +522,25 @@ TEST_F(NGInlineNodeTest, MinMaxSizeFloatsClearance) {
EXPECT_EQ(160, sizes.max_size);
}
+TEST_F(NGInlineNodeTest, MinMaxSizeTabulationWithBreakWord) {
+ LoadAhem();
+ SetupHtml("t", R"HTML(
+ <style>
+ #t {
+ font: 10px Ahem;
+ white-space: pre-wrap;
+ word-break: break-word;
+ }
+ </style>
+ <div id=t>&#9;&#9;<span>X</span></div>
+ )HTML");
+
+ NGInlineNodeForTest node = CreateInlineNode();
+ MinMaxSize sizes = ComputeMinMaxSize(node);
+ EXPECT_EQ(160, sizes.min_size);
+ EXPECT_EQ(170, sizes.max_size);
+}
+
TEST_F(NGInlineNodeTest, AssociatedItemsWithControlItem) {
SetBodyInnerHTML(
"<pre id=t style='-webkit-rtl-ordering:visual'>ab\nde</pre>");
@@ -732,6 +752,25 @@ TEST_P(NodeInsertTest, NeedsCollectInlinesOnInsert) {
EXPECT_FALSE(next->GetLayoutObject()->NeedsCollectInlines());
}
+TEST_F(NGInlineNodeTest, NeedsCollectInlinesOnInsertToOutOfFlowButton) {
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ #xflex { display: flex; }
+ </style>
+ <div id="container">
+ <button id="flex" style="position: absolute"></button>
+ </div>
+ )HTML");
+
+ Element* container = GetElementById("container");
+ Element* parent = ElementTraversal::FirstChild(*container);
+ Element* child = GetDocument().CreateRawElement(html_names::kDivTag);
+ parent->appendChild(child);
+ GetDocument().UpdateStyleAndLayoutTree();
+
+ EXPECT_FALSE(container->GetLayoutObject()->NeedsCollectInlines());
+}
+
class NodeRemoveTest : public NGInlineNodeTest,
public testing::WithParamInterface<const char*> {};
@@ -804,12 +843,36 @@ TEST_F(NGInlineNodeTest, NeedsCollectInlinesOnForceLayout) {
EXPECT_FALSE(target->NeedsCollectInlines());
}
+TEST_F(NGInlineNodeTest, CollectInlinesShouldNotClearFirstInlineFragment) {
+ SetBodyInnerHTML(R"HTML(
+ <div id="container">
+ text
+ </div>
+ )HTML");
+
+ // Appending a child should set |NeedsCollectInlines|.
+ Element* container = GetElementById("container");
+ container->appendChild(GetDocument().createTextNode("add"));
+ auto* block_flow = To<LayoutBlockFlow>(container->GetLayoutObject());
+ GetDocument().UpdateStyleAndLayoutTree();
+ EXPECT_TRUE(block_flow->NeedsCollectInlines());
+
+ // |IsEmptyInline| should run |CollectInlines|.
+ NGInlineNode node(block_flow);
+ node.IsEmptyInline();
+ EXPECT_FALSE(block_flow->NeedsCollectInlines());
+
+ // Running |CollectInlines| should not clear |FirstInlineFragment|.
+ LayoutObject* first_child = container->firstChild()->GetLayoutObject();
+ EXPECT_NE(first_child->FirstInlineFragment(), nullptr);
+}
+
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());
+ auto* parent = To<Element>(layout_block_flow_->GetNode());
Element* span = GetDocument().CreateRawElement(html_names::kSpanTag);
parent->appendChild(span);
@@ -880,7 +943,7 @@ TEST_F(NGInlineNodeTest, InvalidateAddAbsolute) {
EXPECT_FALSE(layout_block_flow_->NeedsCollectInlines());
unsigned item_count_before = Items().size();
- Element* parent = ToElement(layout_block_flow_->GetNode());
+ auto* parent = To<Element>(layout_block_flow_->GetNode());
Element* span = GetDocument().CreateRawElement(html_names::kSpanTag);
parent->appendChild(span);
@@ -945,7 +1008,7 @@ TEST_F(NGInlineNodeTest, InvalidateAddFloat) {
EXPECT_FALSE(layout_block_flow_->NeedsCollectInlines());
unsigned item_count_before = Items().size();
- Element* parent = ToElement(layout_block_flow_->GetNode());
+ auto* parent = To<Element>(layout_block_flow_->GetNode());
Element* span = GetDocument().CreateRawElement(html_names::kSpanTag);
parent->appendChild(span);
@@ -1458,6 +1521,24 @@ TEST_F(NGInlineNodeTest, InsertedWBRWithLineBreakInRelayout) {
EXPECT_EQ(String(u"foo\u200Bbar"), GetText());
}
+TEST_F(NGInlineNodeTest, CollapsibleSpaceFollowingBRWithNoWrapStyle) {
+ SetupHtml("t", "<div id=t><span style=white-space:pre><br></span> </div>");
+ EXPECT_EQ("\n", GetText());
+
+ GetDocument().QuerySelector("span")->removeAttribute(html_names::kStyleAttr);
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_EQ("\n", GetText());
+}
+
+TEST_F(NGInlineNodeTest, CollapsibleSpaceFollowingNewlineWithPreStyle) {
+ SetupHtml("t", "<div id=t><span style=white-space:pre>\n</span> </div>");
+ EXPECT_EQ("\n", GetText());
+
+ GetDocument().QuerySelector("span")->removeAttribute(html_names::kStyleAttr);
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_EQ("", GetText());
+}
+
#if SEGMENT_BREAK_TRANSFORMATION_FOR_EAST_ASIAN_WIDTH
// https://crbug.com/879088
TEST_F(NGInlineNodeTest, RemoveSegmentBreakFromJapaneseInRelayout) {
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 13d2b5d6e37..55cb128a930 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
@@ -10,6 +10,7 @@
#include "third_party/blink/renderer/core/layout/ng/inline/ng_physical_line_box_fragment.h"
#include "third_party/blink/renderer/core/layout/ng/ng_fragment.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 {
@@ -19,6 +20,7 @@ void NGLineBoxFragmentBuilder::Reset() {
child_break_tokens_.Shrink(0);
inline_break_tokens_.Shrink(0);
oof_positioned_candidates_.Shrink(0);
+ unpositioned_list_marker_ = NGUnpositionedListMarker();
size_.inline_size = LayoutUnit();
metrics_ = NGLineHeightMetrics();
@@ -55,6 +57,10 @@ NGLineBoxFragmentBuilder::ChildList::LastInFlowChild() {
return nullptr;
}
+void NGLineBoxFragmentBuilder::ChildList::InsertChild(unsigned index) {
+ children_.insert(index, Child());
+}
+
void NGLineBoxFragmentBuilder::ChildList::MoveInInlineDirection(
LayoutUnit delta) {
for (auto& child : children_)
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 71c7396ed98..7142082a860 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
@@ -15,7 +15,7 @@
#include "third_party/blink/renderer/core/layout/ng/ng_layout_result.h"
#include "third_party/blink/renderer/core/layout/ng/ng_physical_container_fragment.h"
#include "third_party/blink/renderer/core/layout/ng/ng_positioned_float.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -24,7 +24,7 @@ class NGInlineBreakToken;
class CORE_EXPORT NGLineBoxFragmentBuilder final
: public NGContainerFragmentBuilder {
- DISALLOW_NEW();
+ STACK_ALLOCATED();
public:
NGLineBoxFragmentBuilder(NGInlineNode node,
@@ -173,7 +173,7 @@ class CORE_EXPORT NGLineBoxFragmentBuilder final
// Unlike the fragment builder, chlidren are mutable.
// Callers can add to the fragment builder in a batch once finalized.
class ChildList {
- DISALLOW_NEW();
+ STACK_ALLOCATED();
public:
ChildList() = default;
@@ -213,6 +213,7 @@ class CORE_EXPORT NGLineBoxFragmentBuilder final
void AddChild(Args&&... args) {
children_.emplace_back(std::forward<Args>(args)...);
}
+ void InsertChild(unsigned index);
void InsertChild(unsigned index,
scoped_refptr<const NGLayoutResult> layout_result,
const LogicalOffset& offset,
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 8f60a66ffb1..39d7c563bf0 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
@@ -124,29 +124,31 @@ scoped_refptr<const NGPhysicalTextFragment> CreateHyphenFragment(
HarfBuzzShaper shaper(hyphen_string);
scoped_refptr<ShapeResult> hyphen_result =
shaper.Shape(&style.GetFont(), direction);
- NGTextFragmentBuilder builder(node, writing_mode);
+ NGTextFragmentBuilder builder(writing_mode);
builder.SetText(item.GetLayoutObject(), hyphen_string, &style,
/* is_ellipsis_style */ false,
ShapeResultView::Create(hyphen_result.get()));
return builder.ToTextFragment();
}
-bool IsStickyImage(const NGInlineItem& candidate,
- const NGInlineItemResults& item_results,
- NGLineBreaker::WhitespaceState trailing_whitespace,
- const String& text) {
- if (!IsImage(candidate))
- return false;
+void PreventBreakBeforeStickyImage(
+ NGLineBreaker::WhitespaceState trailing_whitespace,
+ const String& text,
+ NGLineInfo* line_info) {
if (trailing_whitespace != NGLineBreaker::WhitespaceState::kNone &&
trailing_whitespace != NGLineBreaker::WhitespaceState::kUnknown)
- return false;
+ return;
- if (item_results.size() >= 1) {
- // If this image follows a <wbr> the image isn't sticky.
- const auto& last = item_results[item_results.size() - 1];
- return text[last.start_offset] != kZeroWidthSpaceCharacter;
- }
- return true;
+ NGInlineItemResults* results = line_info->MutableResults();
+ if (results->IsEmpty())
+ return;
+
+ // If this image follows a <wbr> the image isn't sticky.
+ NGInlineItemResult* last = &results->back();
+ if (text[last->start_offset] == kZeroWidthSpaceCharacter)
+ return;
+
+ last->can_break_after = false;
}
inline void ClearNeedsLayout(const NGInlineItem& item) {
@@ -412,6 +414,13 @@ void NGLineBreaker::BreakLine(
continue;
return;
}
+ if (item.Type() == NGInlineItem::kAtomicInline) {
+ if (HandleAtomicInline(item, percentage_resolution_block_size_for_min_max,
+ line_info)) {
+ continue;
+ }
+ return;
+ }
if (item.Type() == NGInlineItem::kCloseTag) {
HandleCloseTag(item, line_info);
continue;
@@ -433,24 +442,11 @@ void NGLineBreaker::BreakLine(
// opportunity if we're trailing.
if (state_ == LineBreakState::kTrailing &&
CanBreakAfterLast(item_results)) {
- // If the sticky images quirk is enabled, and this is an image that
- // follows text that doesn't end with something breakable, we cannot break
- // between the two items.
- if (sticky_images_quirk_ &&
- IsStickyImage(item, item_results, trailing_whitespace_, Text())) {
- HandleAtomicInline(item, percentage_resolution_block_size_for_min_max,
- line_info);
- continue;
- }
-
line_info->SetIsLastLine(false);
return;
}
- if (item.Type() == NGInlineItem::kAtomicInline) {
- HandleAtomicInline(item, percentage_resolution_block_size_for_min_max,
- line_info);
- } else if (item.Type() == NGInlineItem::kOutOfFlowPositioned) {
+ if (item.Type() == NGInlineItem::kOutOfFlowPositioned) {
AddItem(item, line_info);
MoveToNextOf(item);
} else if (item.Length()) {
@@ -1082,10 +1078,28 @@ void NGLineBreaker::HandleControlItem(const NGInlineItem& item,
NGInlineItemResult* item_result = AddItem(item, line_info);
item_result->should_create_line_box = true;
item_result->has_only_trailing_spaces = true;
+ MoveToNextOf(item);
+
+ // Include following close tags. The difference is visible when they have
+ // margin/border/padding.
+ //
+ // This is not a defined behavior, but legacy/WebKit do this for preserved
+ // newlines and <br>s. Gecko does this only for preserved newlines (but
+ // not for <br>s).
+ const Vector<NGInlineItem>& items = Items();
+ while (item_index_ < items.size()) {
+ const NGInlineItem& next_item = items[item_index_];
+ if (next_item.Type() == NGInlineItem::kCloseTag) {
+ HandleCloseTag(next_item, line_info);
+ continue;
+ }
+ break;
+ }
+
is_after_forced_break_ = true;
line_info->SetIsLastLine(true);
state_ = LineBreakState::kDone;
- break;
+ return;
}
case kTabulationCharacter: {
DCHECK(item.Style());
@@ -1100,7 +1114,11 @@ void NGLineBreaker::HandleControlItem(const NGInlineItem& item,
case kZeroWidthSpaceCharacter: {
// <wbr> tag creates break opportunities regardless of auto_wrap.
NGInlineItemResult* item_result = AddItem(item, line_info);
- item_result->should_create_line_box = true;
+ // A generated break opportunity doesn't generate fragments, but we still
+ // need to add this for rewind to find this opportunity. This will be
+ // discarded in |NGInlineLayoutAlgorithm| when it generates fragments.
+ if (!item.IsGeneratedForLineBreak())
+ item_result->should_create_line_box = true;
item_result->can_break_after = true;
break;
}
@@ -1109,10 +1127,12 @@ void NGLineBreaker::HandleControlItem(const NGInlineItem& item,
// Ignore carriage return and form feed.
// https://drafts.csswg.org/css-text-3/#white-space-processing
// https://github.com/w3c/csswg-drafts/issues/855
- break;
+ HandleEmptyText(item, line_info);
+ return;
default:
NOTREACHED();
- break;
+ HandleEmptyText(item, line_info);
+ return;
}
MoveToNextOf(item);
}
@@ -1132,8 +1152,16 @@ void NGLineBreaker::HandleBidiControlItem(const NGInlineItem& item,
if (!item_results->IsEmpty()) {
NGInlineItemResult* item_result = AddItem(item, line_info);
NGInlineItemResult* last = &(*item_results)[item_results->size() - 2];
- item_result->can_break_after = last->can_break_after;
- last->can_break_after = false;
+ // Honor the last |can_break_after| if it's true, in case it was
+ // artificially set to true for break-after-space.
+ if (last->can_break_after) {
+ item_result->can_break_after = last->can_break_after;
+ last->can_break_after = false;
+ } else {
+ // Otherwise compute from the text. |LazyLineBreakIterator| knows how to
+ // break around bidi control characters.
+ ComputeCanBreakAfter(item_result, auto_wrap_, break_iterator_);
+ }
} else {
AddItem(item, line_info);
}
@@ -1151,13 +1179,30 @@ void NGLineBreaker::HandleBidiControlItem(const NGInlineItem& item,
MoveToNextOf(item);
}
-void NGLineBreaker::HandleAtomicInline(
+bool NGLineBreaker::HandleAtomicInline(
const NGInlineItem& item,
LayoutUnit percentage_resolution_block_size_for_min_max,
NGLineInfo* line_info) {
DCHECK_EQ(item.Type(), NGInlineItem::kAtomicInline);
DCHECK(item.Style());
const ComputedStyle& style = *item.Style();
+ const NGInlineItemResults& item_results = line_info->Results();
+
+ // If the sticky images quirk is enabled, and this is an image that
+ // follows text that doesn't end with something breakable, we cannot break
+ // between the two items.
+ bool is_sticky_image = sticky_images_quirk_ && IsImage(item);
+ if (UNLIKELY(is_sticky_image)) {
+ PreventBreakBeforeStickyImage(trailing_whitespace_, Text(), line_info);
+ }
+
+ // Atomic inline is handled as if it is trailable, because it can prevent
+ // break-before. Check if the line should break before this item, after the
+ // last item's |can_break_after| is finalized for the quirk above.
+ if (state_ == LineBreakState::kTrailing && CanBreakAfterLast(item_results)) {
+ line_info->SetIsLastLine(false);
+ return false;
+ }
NGInlineItemResult* item_result = AddItem(item, line_info);
item_result->should_create_line_box = true;
@@ -1207,7 +1252,7 @@ void NGLineBreaker::HandleAtomicInline(
position_ += item_result->inline_size;
ComputeCanBreakAfter(item_result, auto_wrap_, break_iterator_);
- if (sticky_images_quirk_ && IsImage(item)) {
+ if (UNLIKELY(is_sticky_image)) {
const auto& items = Items();
if (item_index_ + 1 < items.size()) {
DCHECK_EQ(&item, &items[item_index_]);
@@ -1220,6 +1265,7 @@ void NGLineBreaker::HandleAtomicInline(
}
}
MoveToNextOf(item);
+ return true;
}
// Performs layout and positions a float.
@@ -1467,6 +1513,23 @@ void NGLineBreaker::HandleCloseTag(const NGInlineItem& item,
ComputeCanBreakAfter(item_result, auto_wrap_, break_iterator_);
}
+bool NGLineBreaker::ShouldHangTraillingSpaces(const NGInlineItem& item) {
+ if (!item.Length())
+ return false;
+
+ const ComputedStyle& style = *item.Style();
+ if (!auto_wrap_ || (!style.CollapseWhiteSpace() &&
+ style.WhiteSpace() == EWhiteSpace::kBreakSpaces))
+ return false;
+
+ const String& text = Text();
+ for (unsigned i = item.StartOffset(); i < item.EndOffset(); ++i) {
+ if (!IsBreakableSpace(text[i]))
+ return false;
+ }
+ return true;
+}
+
// Handles when the last item overflows.
// At this point, item_results does not fit into the current line, and there
// are no break opportunities in item_results.back().
@@ -1512,7 +1575,15 @@ void NGLineBreaker::HandleOverflow(NGLineInfo* line_info) {
DCHECK(item_result->shape_result ||
(item_result->break_anywhere_if_overflow &&
!override_break_anywhere_));
- if (width_to_rewind < 0 && item_result->may_break_inside) {
+ if (width_to_rewind <= 0) {
+ if (!width_to_rewind || !item_result->may_break_inside) {
+ if (ShouldHangTraillingSpaces(item)) {
+ Rewind(i, line_info);
+ state_ = LineBreakState::kTrailing;
+ return;
+ }
+ continue;
+ }
// When the text fits but its right margin does not, the break point
// must not be at the end.
LayoutUnit item_available_width =
@@ -1736,6 +1807,14 @@ void NGLineBreaker::SetCurrentStyle(const ComputedStyle& style) {
void NGLineBreaker::MoveToNextOf(const NGInlineItem& item) {
offset_ = item.EndOffset();
item_index_++;
+#if DCHECK_IS_ON()
+ const Vector<NGInlineItem>& items = Items();
+ if (item_index_ < items.size()) {
+ items[item_index_].AssertOffset(offset_);
+ } else {
+ DCHECK_EQ(offset_, Text().length());
+ }
+#endif
}
void NGLineBreaker::MoveToNextOf(const NGInlineItemResult& item_result) {
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 17c3d0545a0..a90313b2f08 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
@@ -13,7 +13,7 @@
#include "third_party/blink/renderer/platform/fonts/shaping/harfbuzz_shaper.h"
#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_spacing.h"
#include "third_party/blink/renderer/platform/text/text_break_iterator.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -134,6 +134,7 @@ class CORE_EXPORT NGLineBreaker {
const ShapeResult&,
LayoutUnit available_width,
NGLineInfo*);
+ bool ShouldHangTraillingSpaces(const NGInlineItem&);
bool HandleTextForFastMinContent(NGInlineItemResult*,
const NGInlineItem&,
const ShapeResult&,
@@ -158,7 +159,7 @@ class CORE_EXPORT NGLineBreaker {
void HandleControlItem(const NGInlineItem&, NGLineInfo*);
void HandleBidiControlItem(const NGInlineItem&, NGLineInfo*);
- void HandleAtomicInline(
+ bool HandleAtomicInline(
const NGInlineItem&,
LayoutUnit percentage_resolution_block_size_for_min_max,
NGLineInfo*);
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 778bb892eec..df93ec3768d 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
@@ -22,8 +22,8 @@ class NGLineBreakerTest : public NGLayoutTest {
NGInlineNode CreateInlineNode(const String& html_content) {
SetBodyInnerHTML(html_content);
- LayoutNGBlockFlow* block_flow =
- ToLayoutNGBlockFlow(GetLayoutObjectByElementId("container"));
+ LayoutBlockFlow* block_flow =
+ To<LayoutBlockFlow>(GetLayoutObjectByElementId("container"));
return NGInlineNode(block_flow);
}
@@ -523,6 +523,29 @@ TEST_F(NGLineBreakerTest, MinMaxWithTrailingSpaces) {
EXPECT_EQ(size.max_size, LayoutUnit(110));
}
+TEST_F(NGLineBreakerTest, TableCellWidthCalculationQuirkOutOfFlow) {
+ NGInlineNode node = CreateInlineNode(R"HTML(
+ <style>
+ table {
+ font-size: 10px;
+ width: 5ch;
+ }
+ </style>
+ <table><tr><td id=container>
+ 1234567
+ <img style="position: absolute">
+ </td></tr></table>
+ )HTML");
+ // |SetBodyInnerHTML| doesn't set compatibility mode.
+ GetDocument().SetCompatibilityMode(Document::kQuirksMode);
+ EXPECT_TRUE(node.GetDocument().InQuirksMode());
+
+ node.ComputeMinMaxSize(
+ WritingMode::kHorizontalTb,
+ MinMaxSizeInput(/* percentage_resolution_block_size */ LayoutUnit()));
+ // Pass if |ComputeMinMaxSize| doesn't hit DCHECK failures.
+}
+
#undef MAYBE_OverflowAtomicInline
} // namespace
} // 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 747f3f13a07..836de6ae3db 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
@@ -4,6 +4,7 @@
#include "third_party/blink/renderer/core/layout/ng/inline/ng_line_truncator.h"
+#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_box_state.h"
#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"
@@ -13,16 +14,15 @@
namespace blink {
-NGLineTruncator::NGLineTruncator(NGInlineNode& node,
- const NGLineInfo& line_info)
- : node_(node),
- line_style_(&line_info.LineStyle()),
+NGLineTruncator::NGLineTruncator(const NGLineInfo& line_info)
+ : line_style_(&line_info.LineStyle()),
available_width_(line_info.AvailableWidth()),
line_direction_(line_info.BaseDirection()) {}
LayoutUnit NGLineTruncator::TruncateLine(
LayoutUnit line_width,
- NGLineBoxFragmentBuilder::ChildList* line_box) {
+ NGLineBoxFragmentBuilder::ChildList* line_box,
+ NGInlineLayoutStateStack* box_states) {
// Shape the ellipsis and compute its inline size.
// The ellipsis is styled according to the line style.
// https://drafts.csswg.org/css-ui/#ellipsing-details
@@ -42,46 +42,74 @@ LayoutUnit NGLineTruncator::TruncateLine(
// Loop children from the logical last to the logical first to determine where
// to place the ellipsis. Children maybe truncated or moved as part of the
// process.
- LayoutUnit ellipsis_inline_offset;
- const NGPhysicalFragment* ellipsized_fragment = nullptr;
+ NGLineBoxFragmentBuilder::Child* ellpisized_child = nullptr;
+ scoped_refptr<const NGPhysicalTextFragment> truncated_fragment;
if (IsLtr(line_direction_)) {
NGLineBoxFragmentBuilder::Child* first_child = line_box->FirstInFlowChild();
for (auto it = line_box->rbegin(); it != line_box->rend(); it++) {
auto& child = *it;
- if (base::Optional<LayoutUnit> candidate = EllipsisOffset(
- line_width, ellipsis_width, &child == first_child, &child)) {
- ellipsis_inline_offset = *candidate;
- ellipsized_fragment = child.PhysicalFragment();
- DCHECK(ellipsized_fragment);
+ if (EllipsizeChild(line_width, ellipsis_width, &child == first_child,
+ &child, &truncated_fragment)) {
+ ellpisized_child = &child;
break;
}
}
} else {
NGLineBoxFragmentBuilder::Child* first_child = line_box->LastInFlowChild();
- ellipsis_inline_offset = available_width_ - ellipsis_width;
for (auto& child : *line_box) {
- if (base::Optional<LayoutUnit> candidate = EllipsisOffset(
- line_width, ellipsis_width, &child == first_child, &child)) {
- ellipsis_inline_offset = *candidate;
- ellipsized_fragment = child.PhysicalFragment();
- DCHECK(ellipsized_fragment);
+ if (EllipsizeChild(line_width, ellipsis_width, &child == first_child,
+ &child, &truncated_fragment)) {
+ ellpisized_child = &child;
break;
}
}
}
// Abort if ellipsis could not be placed.
- if (!ellipsized_fragment)
+ if (!ellpisized_child)
return line_width;
+ // Truncate the text fragment if needed.
+ if (truncated_fragment) {
+ DCHECK(ellpisized_child->fragment);
+ // In order to preserve layout information before truncated, hide the
+ // original fragment and insert a truncated one.
+ size_t child_index_to_truncate = ellpisized_child - line_box->begin();
+ line_box->InsertChild(child_index_to_truncate + 1);
+ box_states->ChildInserted(child_index_to_truncate + 1);
+ NGLineBoxFragmentBuilder::Child* child_to_truncate =
+ &(*line_box)[child_index_to_truncate];
+ ellpisized_child = std::next(child_to_truncate);
+ *ellpisized_child = *child_to_truncate;
+ HideChild(child_to_truncate);
+ LayoutUnit new_inline_size = line_style_->IsHorizontalWritingMode()
+ ? truncated_fragment->Size().width
+ : truncated_fragment->Size().height;
+ DCHECK_LE(new_inline_size, ellpisized_child->inline_size);
+ if (UNLIKELY(IsRtl(line_direction_))) {
+ ellpisized_child->offset.inline_offset +=
+ ellpisized_child->inline_size - new_inline_size;
+ }
+ ellpisized_child->inline_size = new_inline_size;
+ ellpisized_child->fragment = std::move(truncated_fragment);
+ }
+
+ // Create the ellipsis, associating it with the ellipsized child.
+ LayoutObject* ellipsized_layout_object =
+ ellpisized_child->PhysicalFragment()->GetMutableLayoutObject();
+ DCHECK(ellipsized_layout_object && ellipsized_layout_object->IsInline());
+ NGTextFragmentBuilder builder(line_style_->GetWritingMode());
+ builder.SetText(ellipsized_layout_object, ellipsis_text, ellipsis_style,
+ true /* is_ellipsis_style */,
+ std::move(ellipsis_shape_result));
+
// Now the offset of the ellpisis is determined. Place the ellpisis into the
// line box.
- NGTextFragmentBuilder builder(node_, line_style_->GetWritingMode());
- DCHECK(ellipsized_fragment->GetLayoutObject() &&
- ellipsized_fragment->GetLayoutObject()->IsInline());
- builder.SetText(ellipsized_fragment->GetMutableLayoutObject(), ellipsis_text,
- ellipsis_style, true /* is_ellipsis_style */,
- std::move(ellipsis_shape_result));
+ LayoutUnit ellipsis_inline_offset =
+ IsLtr(line_direction_)
+ ? ellpisized_child->offset.inline_offset +
+ ellpisized_child->inline_size
+ : ellpisized_child->offset.inline_offset - ellipsis_width;
FontBaseline baseline_type = line_style_->GetFontBaseline();
NGLineHeightMetrics ellipsis_metrics(font_data->GetFontMetrics(),
baseline_type);
@@ -92,51 +120,56 @@ LayoutUnit NGLineTruncator::TruncateLine(
return std::max(ellipsis_inline_offset + ellipsis_width, line_width);
}
-// Hide this child from being painted.
+// Hide this child from being painted. Leaves a hidden fragment so that layout
+// queries such as |offsetWidth| work as if it is not truncated.
void NGLineTruncator::HideChild(NGLineBoxFragmentBuilder::Child* child) {
DCHECK(child->HasInFlowFragment());
- const NGPhysicalFragment* fragment = nullptr;
+ if (const NGPhysicalTextFragment* text = child->fragment.get()) {
+ child->fragment = text->CloneAsHiddenForPaint();
+ return;
+ }
+
if (const NGLayoutResult* layout_result = child->layout_result.get()) {
// Need to propagate OOF descendants in this inline-block child.
- if (layout_result->PhysicalFragment().HasOutOfFlowPositionedDescendants())
+ const auto& fragment =
+ To<NGPhysicalBoxFragment>(layout_result->PhysicalFragment());
+ if (fragment.HasOutOfFlowPositionedDescendants())
return;
- fragment = &layout_result->PhysicalFragment();
- } else {
- fragment = child->fragment.get();
- }
- DCHECK(fragment);
-
- // 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.
- if (fragment->HasSelfPaintingLayer()) {
- // |available_width_| may not be enough when the containing 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();
+
+ // 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.
+ if (fragment.HasSelfPaintingLayer()) {
+ // |available_width_| may not be enough when the containing 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;
+ }
+
+ child->layout_result = fragment.CloneAsHiddenForPaint();
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.
- child->layout_result = nullptr;
- child->fragment = nullptr;
+ NOTREACHED();
}
// Return the offset to place the ellipsis.
//
// This function may truncate or move the child so that the ellipsis can fit.
-base::Optional<LayoutUnit> NGLineTruncator::EllipsisOffset(
+bool NGLineTruncator::EllipsizeChild(
LayoutUnit line_width,
LayoutUnit ellipsis_width,
bool is_first_child,
- NGLineBoxFragmentBuilder::Child* child) {
+ NGLineBoxFragmentBuilder::Child* child,
+ scoped_refptr<const NGPhysicalTextFragment>* truncated_fragment) {
+ DCHECK(truncated_fragment && !*truncated_fragment);
+
// Leave out-of-flow children as is.
if (!child->HasInFlowFragment())
- return base::nullopt;
+ return false;
// Can't place ellipsis if this child is completely outside of the box.
LayoutUnit child_inline_offset =
@@ -150,24 +183,23 @@ base::Optional<LayoutUnit> NGLineTruncator::EllipsisOffset(
// still inside of the clipping box.
if (!is_first_child)
HideChild(child);
- return base::nullopt;
+ return false;
}
// At least part of this child is in the box.
// If not all of this child can fit, try to truncate.
space_for_child -= ellipsis_width;
if (space_for_child < child->inline_size &&
- !TruncateChild(space_for_child, is_first_child, child)) {
+ !TruncateChild(space_for_child, is_first_child, *child,
+ truncated_fragment)) {
// This child is partially in the box, but it should not be visible because
// earlier sibling will be truncated and ellipsized.
if (!is_first_child)
HideChild(child);
- return base::nullopt;
+ return false;
}
- return IsLtr(line_direction_)
- ? child->offset.inline_offset + child->inline_size
- : child->offset.inline_offset - ellipsis_width;
+ return true;
}
// Truncate the specified child. Returns true if truncated successfully, false
@@ -177,17 +209,21 @@ base::Optional<LayoutUnit> NGLineTruncator::EllipsisOffset(
// |is_first_child|, because the spec defines that the first character or atomic
// inline-level element on a line must be clipped rather than ellipsed.
// https://drafts.csswg.org/css-ui/#text-overflow
-bool NGLineTruncator::TruncateChild(LayoutUnit space_for_child,
- bool is_first_child,
- NGLineBoxFragmentBuilder::Child* child) {
+bool NGLineTruncator::TruncateChild(
+ LayoutUnit space_for_child,
+ bool is_first_child,
+ const NGLineBoxFragmentBuilder::Child& child,
+ scoped_refptr<const NGPhysicalTextFragment>* truncated_fragment) {
+ DCHECK(truncated_fragment && !*truncated_fragment);
+
// If the space is not enough, try the next child.
if (space_for_child <= 0 && !is_first_child)
return false;
// Only text fragments can be truncated.
- if (!child->fragment)
+ if (!child.fragment)
return is_first_child;
- auto& fragment = To<NGPhysicalTextFragment>(*child->fragment);
+ auto& fragment = To<NGPhysicalTextFragment>(*child.fragment);
// No need to truncate empty results.
if (!fragment.TextShapeResult())
@@ -213,18 +249,12 @@ bool NGLineTruncator::TruncateChild(LayoutUnit space_for_child,
}
// Truncate the text fragment.
- child->fragment = line_direction_ == shape_result->Direction()
- ? fragment.TrimText(fragment.StartOffset(),
- fragment.StartOffset() + new_length)
- : fragment.TrimText(fragment.StartOffset() + new_length,
- fragment.EndOffset());
- LayoutUnit new_inline_size = line_style_->IsHorizontalWritingMode()
- ? child->fragment->Size().width
- : child->fragment->Size().height;
- DCHECK_LE(new_inline_size, child->inline_size);
- if (UNLIKELY(IsRtl(line_direction_)))
- child->offset.inline_offset += child->inline_size - new_inline_size;
- child->inline_size = new_inline_size;
+ *truncated_fragment =
+ line_direction_ == shape_result->Direction()
+ ? fragment.TrimText(fragment.StartOffset(),
+ fragment.StartOffset() + new_length)
+ : fragment.TrimText(fragment.StartOffset() + new_length,
+ fragment.EndOffset());
return true;
}
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_truncator.h b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_truncator.h
index 83bfbd120b1..0c507997ad2 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_truncator.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_line_truncator.h
@@ -12,6 +12,7 @@
namespace blink {
+class NGInlineLayoutStateStack;
class NGLineInfo;
// A class to truncate lines and place ellipsis, invoked by the CSS
@@ -21,7 +22,7 @@ class CORE_EXPORT NGLineTruncator final {
STACK_ALLOCATED();
public:
- NGLineTruncator(NGInlineNode& node, const NGLineInfo& line_info);
+ NGLineTruncator(const NGLineInfo& line_info);
// Truncate |line_box| and place ellipsis. Returns the new inline-size of the
// |line_box|.
@@ -29,19 +30,23 @@ class CORE_EXPORT NGLineTruncator final {
// |line_box| should be after bidi reorder, but before box fragments are
// created.
LayoutUnit TruncateLine(LayoutUnit line_width,
- NGLineBoxFragmentBuilder::ChildList* line_box);
+ NGLineBoxFragmentBuilder::ChildList* line_box,
+ NGInlineLayoutStateStack* box_states);
private:
- base::Optional<LayoutUnit> EllipsisOffset(LayoutUnit line_width,
- LayoutUnit ellipsis_width,
- bool is_first_child,
- NGLineBoxFragmentBuilder::Child*);
- bool TruncateChild(LayoutUnit space_for_this_child,
- bool is_first_child,
- NGLineBoxFragmentBuilder::Child* child);
+ bool EllipsizeChild(
+ LayoutUnit line_width,
+ LayoutUnit ellipsis_width,
+ bool is_first_child,
+ NGLineBoxFragmentBuilder::Child*,
+ scoped_refptr<const NGPhysicalTextFragment>* truncated_fragment);
+ bool TruncateChild(
+ LayoutUnit space_for_this_child,
+ bool is_first_child,
+ const NGLineBoxFragmentBuilder::Child& child,
+ scoped_refptr<const NGPhysicalTextFragment>* truncated_fragment);
void HideChild(NGLineBoxFragmentBuilder::Child* child);
- NGInlineNode& node_;
scoped_refptr<const ComputedStyle> line_style_;
LayoutUnit available_width_;
TextDirection line_direction_;
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 1e7fb8e2a92..f8895564880 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
@@ -333,7 +333,7 @@ NGOffsetMapping::UnitVector NGOffsetMapping::GetMappingUnitsForDOMRange(
});
UnitVector result;
- for (const auto& unit : NGMappingUnitRange({result_begin, result_end})) {
+ for (const auto& unit : base::make_span(result_begin, result_end)) {
// If the unit isn't fully within the range, create a new unit that's
// within the range.
const unsigned clamped_start = std::max(unit.DOMStart(), start_offset);
@@ -350,17 +350,19 @@ NGOffsetMapping::UnitVector NGOffsetMapping::GetMappingUnitsForDOMRange(
return result;
}
-NGMappingUnitRange NGOffsetMapping::GetMappingUnitsForNode(
+base::span<const NGOffsetMappingUnit> NGOffsetMapping::GetMappingUnitsForNode(
const Node& node) const {
const auto it = ranges_.find(&node);
if (it == ranges_.end()) {
NOTREACHED() << node;
- return NGMappingUnitRange();
+ return {};
}
- return {units_.begin() + it->value.first, units_.begin() + it->value.second};
+ return base::make_span(units_.begin() + it->value.first,
+ units_.begin() + it->value.second);
}
-NGMappingUnitRange NGOffsetMapping::GetMappingUnitsForLayoutObject(
+base::span<const NGOffsetMappingUnit>
+NGOffsetMapping::GetMappingUnitsForLayoutObject(
const LayoutObject& layout_object) const {
const auto* begin =
std::find_if(units_.begin(), units_.end(),
@@ -374,12 +376,12 @@ NGMappingUnitRange NGOffsetMapping::GetMappingUnitsForLayoutObject(
return unit.GetLayoutObject() != layout_object;
});
DCHECK_LT(begin, end);
- return {begin, end};
+ return base::make_span(begin, end);
}
-NGMappingUnitRange NGOffsetMapping::GetMappingUnitsForTextContentOffsetRange(
- unsigned start,
- unsigned end) const {
+base::span<const NGOffsetMappingUnit>
+NGOffsetMapping::GetMappingUnitsForTextContentOffsetRange(unsigned start,
+ unsigned end) const {
DCHECK_LE(start, end);
if (units_.front().TextContentStart() >= end ||
units_.back().TextContentEnd() <= start)
@@ -400,7 +402,7 @@ NGMappingUnitRange NGOffsetMapping::GetMappingUnitsForTextContentOffsetRange(
[](unsigned offset, const NGOffsetMappingUnit& unit) {
return offset <= unit.TextContentStart();
});
- return {result_begin, result_end};
+ return base::make_span(result_begin, result_end);
}
base::Optional<unsigned> NGOffsetMapping::GetTextContentOffset(
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 743dd9d8757..1a2ad8c41d0 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
@@ -11,7 +11,7 @@
#include "third_party/blink/renderer/core/editing/forward.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/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
@@ -93,23 +93,6 @@ class CORE_EXPORT NGOffsetMappingUnit {
friend class NGOffsetMappingBuilder;
};
-class NGMappingUnitRange {
- STACK_ALLOCATED();
-
- public:
- const NGOffsetMappingUnit* begin() const { return begin_; }
- const NGOffsetMappingUnit* end() const { return end_; }
-
- NGMappingUnitRange() : begin_(nullptr), end_(nullptr) {}
- NGMappingUnitRange(const NGOffsetMappingUnit* begin,
- const NGOffsetMappingUnit* end)
- : begin_(begin), end_(end) {}
-
- private:
- const NGOffsetMappingUnit* begin_;
- const NGOffsetMappingUnit* end_;
-};
-
// Each inline formatting context laid out with LayoutNG has an NGOffsetMapping
// object that stores the mapping information between DOM positions and offsets
// in the text content string of the context.
@@ -175,7 +158,8 @@ class CORE_EXPORT NGOffsetMapping {
// Returns all NGOffsetMappingUnits associated to |node|. When |node| is
// laid out with ::first-letter, this function returns both first-letter part
// and remaining part. Note: |node| should have associated mapping.
- NGMappingUnitRange GetMappingUnitsForNode(const Node& node) const;
+ base::span<const NGOffsetMappingUnit> GetMappingUnitsForNode(
+ const Node& node) const;
// Returns all NGOffsetMappingUnits associated to |layout_object|. This
// function works even if |layout_object| is for CSS generated content
@@ -183,7 +167,7 @@ class CORE_EXPORT NGOffsetMapping {
// Note: Unlike |GetMappingUnitsForNode()|, this function returns units
// for first-letter or remaining part only instead of both parts.
// Note: |layout_object| should have associated mapping.
- NGMappingUnitRange GetMappingUnitsForLayoutObject(
+ base::span<const NGOffsetMappingUnit> GetMappingUnitsForLayoutObject(
const LayoutObject& layout_object) const;
// Returns the text content offset corresponding to the given position.
@@ -228,9 +212,8 @@ class CORE_EXPORT NGOffsetMapping {
// (but possibly collapsed) intersection with (start, end). Note that units
// that only "touch" |start| or |end| are excluded.
// Note: Returned range may include units for generated content.
- NGMappingUnitRange GetMappingUnitsForTextContentOffsetRange(
- unsigned start,
- unsigned end) const;
+ base::span<const NGOffsetMappingUnit>
+ GetMappingUnitsForTextContentOffsetRange(unsigned start, unsigned end) const;
// Returns the last |NGOffsetMappingUnit| where |TextContentStart() >= offset|
// including unit for generated content.
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping_builder.cc b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping_builder.cc
index 9524bfb97ac..aa39b7c863b 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping_builder.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping_builder.cc
@@ -5,6 +5,7 @@
#include "third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping_builder.h"
#include <utility>
+#include "base/containers/adapters.h"
#include "third_party/blink/renderer/core/layout/layout_text.h"
#include "third_party/blink/renderer/core/layout/layout_text_fragment.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping.h"
@@ -174,6 +175,42 @@ void NGOffsetMappingBuilder::CollapseTrailingSpace(unsigned space_offset) {
}
}
+void NGOffsetMappingBuilder::RestoreTrailingCollapsibleSpace(
+ const LayoutText& layout_text,
+ unsigned offset) {
+ ++destination_length_;
+ for (auto& unit : base::Reversed(mapping_units_)) {
+ if (unit.text_content_end_ < offset) {
+ // There are no collapsed unit.
+ NOTREACHED();
+ return;
+ }
+ if (unit.text_content_start_ != offset ||
+ unit.text_content_end_ != offset ||
+ unit.layout_object_ != layout_text) {
+ ++unit.text_content_start_;
+ ++unit.text_content_end_;
+ continue;
+ }
+ DCHECK_EQ(unit.type_, NGOffsetMappingUnitType::kCollapsed);
+ const unsigned original_dom_end = unit.dom_end_;
+ unit.type_ = NGOffsetMappingUnitType::kIdentity;
+ unit.dom_end_ = unit.dom_start_ + 1;
+ unit.text_content_end_ = unit.text_content_start_ + 1;
+ if (original_dom_end - unit.dom_start_ == 1)
+ return;
+ // When we collapsed multiple spaces, e.g. <b> </b>.
+ mapping_units_.insert(
+ std::distance(mapping_units_.begin(), &unit) + 1,
+ NGOffsetMappingUnit(NGOffsetMappingUnitType::kCollapsed, layout_text,
+ unit.dom_end_, original_dom_end,
+ unit.text_content_end_, unit.text_content_end_));
+ return;
+ }
+ NOTREACHED();
+ return;
+}
+
void NGOffsetMappingBuilder::SetDestinationString(String string) {
DCHECK_EQ(destination_length_, string.length());
destination_string_ = string;
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping_builder.h b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping_builder.h
index fe84b2fb32f..652d6033e41 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping_builder.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping_builder.h
@@ -9,13 +9,14 @@
#include "base/auto_reset.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
class LayoutObject;
+class LayoutText;
// This is the helper class for constructing the DOM-to-TextContent offset
// mapping. It holds an offset mapping, and provides APIs to modify the mapping
@@ -106,6 +107,11 @@ class CORE_EXPORT NGOffsetMappingBuilder {
// TODO(xiaochengh): Implement when adding support for 'text-transform'
// void Composite(const NGOffsetMappingBuilder&);
+ // Restore a trailing collapsible space at |offset| of text content. The space
+ // is associated with |layout_text|.
+ void RestoreTrailingCollapsibleSpace(const LayoutText& layout_text,
+ unsigned offset);
+
// Set the destination string of the offset mapping.
void SetDestinationString(String);
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 78b74c7b685..533fb646428 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
@@ -13,7 +13,7 @@
#include "third_party/blink/renderer/core/layout/ng/layout_ng_block_flow.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/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -22,9 +22,9 @@ namespace blink {
// https://github.com/w3c/csswg-drafts/issues/337
#define SEGMENT_BREAK_TRANSFORMATION_FOR_EAST_ASIAN_WIDTH 0
-// Helper functions to use |EXPECT_EQ()| for |NGOffsetMappingUnit| and
-// |NGMappingUnitRange|.
-Vector<NGOffsetMappingUnit> ToVector(const NGMappingUnitRange& range) {
+// Helper functions to use |EXPECT_EQ()| for |NGOffsetMappingUnit| and its span.
+Vector<NGOffsetMappingUnit> ToVector(
+ const base::span<const NGOffsetMappingUnit>& range) {
Vector<NGOffsetMappingUnit> units;
for (const auto& unit : range)
units.push_back(unit);
@@ -68,7 +68,7 @@ bool operator==(const Vector<NGOffsetMappingUnit>& units1,
}
bool operator==(const Vector<NGOffsetMappingUnit>& units,
- const NGMappingUnitRange& range) {
+ const base::span<const NGOffsetMappingUnit>& range) {
return units == ToVector(range);
}
@@ -83,7 +83,8 @@ void PrintTo(const Vector<NGOffsetMappingUnit>& units, std::ostream& ostream) {
ostream << "]";
}
-void PrintTo(const NGMappingUnitRange& range, std::ostream& ostream) {
+void PrintTo(const base::span<const NGOffsetMappingUnit>& range,
+ std::ostream& ostream) {
PrintTo(ToVector(range), ostream);
}
@@ -1252,6 +1253,154 @@ TEST_F(NGOffsetMappingTest, PreWrapAndReusing) {
mapping.GetUnits());
}
+TEST_F(NGOffsetMappingTest, RestoreTrailingCollapsibleSpaceReplace) {
+ // A space inside <b> is collapsed by during handling "\n" then it is restored
+ // by handling a newline. Restored space is removed at end of block.
+ // When RestoreTrailingCollapsibleSpace(), units are:
+ // 0: kIdentity text in <a>, dom=0,1 content=0,1
+ // 1: kCollapsed text in <b>, dom=0,1, content=2,2
+ // 2: kCollapsed "\n", dom=0,1, content=2,2
+ // layout_text is a child of <b> and offset is 2
+ SetupHtml("t",
+ "<div id=t>"
+ "<a style='white-space: pre-wrap;'> </a><b> </b>\n<i> </i>"
+ "</div>");
+ const NGOffsetMapping& result = GetOffsetMapping();
+ const LayoutObject& layout_object_a = *layout_object_;
+ const LayoutObject& layout_object_b = *layout_object_a.NextSibling();
+ const LayoutObject& newline = *layout_object_b.NextSibling();
+ const LayoutObject& layout_object_i = *newline.NextSibling();
+ EXPECT_EQ(
+ (Vector<NGOffsetMappingUnit>{
+ NGOffsetMappingUnit(kIdentity, *layout_object_a.SlowFirstChild(), 0u,
+ 1u, 0u, 1u),
+ NGOffsetMappingUnit(kCollapsed, *layout_object_b.SlowFirstChild(), 0u,
+ 1u, 2u, 2u),
+ NGOffsetMappingUnit(kCollapsed, newline, 0u, 1u, 2u, 2u),
+ NGOffsetMappingUnit(kCollapsed, *layout_object_i.SlowFirstChild(), 0u,
+ 1u, 2u, 2u),
+ }),
+ result.GetUnits());
+}
+
+TEST_F(NGOffsetMappingTest, RestoreTrailingCollapsibleSpaceReplaceKeep) {
+ // A space inside <b> is collapsed by during handling "\n" then it is restored
+ // by handling a newline.
+ // When RestoreTrailingCollapsibleSpace(), units are:
+ // 0: kIdentity text in <a>, dom=0,1 content=0,1
+ // 1: kCollapsed text in <b>, dom=0,1, content=2,2
+ // 2: kCollapsed "\n", dom=0,1, content=2,2
+ // layout_text is a child of <b> and offset is 2
+ SetupHtml("t",
+ "<div id=t>"
+ "<a style='white-space: pre-wrap;'> </a><b> </b>\n<i>x</i>"
+ "</div>");
+ const NGOffsetMapping& result = GetOffsetMapping();
+ const LayoutObject& layout_object_a = *layout_object_;
+ const LayoutObject& layout_object_b = *layout_object_a.NextSibling();
+ const LayoutObject& newline = *layout_object_b.NextSibling();
+ const LayoutObject& layout_object_i = *newline.NextSibling();
+ EXPECT_EQ(
+ (Vector<NGOffsetMappingUnit>{
+ NGOffsetMappingUnit(kIdentity, *layout_object_a.SlowFirstChild(), 0u,
+ 1u, 0u, 1u),
+ NGOffsetMappingUnit(kIdentity, *layout_object_b.SlowFirstChild(), 0u,
+ 1u, 2u, 3u),
+ NGOffsetMappingUnit(kCollapsed, newline, 0u, 1u, 3u, 3u),
+ NGOffsetMappingUnit(kIdentity, *layout_object_i.SlowFirstChild(), 0u,
+ 1u, 3u, 4u),
+ }),
+ result.GetUnits());
+}
+
+TEST_F(NGOffsetMappingTest, RestoreTrailingCollapsibleSpaceNone) {
+ SetupHtml("t",
+ "<div id=t>"
+ "<a>x</a><b> </b>\n<i>y</i>"
+ "</div>");
+ const NGOffsetMapping& result = GetOffsetMapping();
+ const LayoutObject& layout_object_a = *layout_object_;
+ const LayoutObject& layout_object_b = *layout_object_a.NextSibling();
+ const LayoutObject& newline = *layout_object_b.NextSibling();
+ const LayoutObject& layout_object_i = *newline.NextSibling();
+ EXPECT_EQ(
+ (Vector<NGOffsetMappingUnit>{
+ NGOffsetMappingUnit(kIdentity, *layout_object_a.SlowFirstChild(), 0u,
+ 1u, 0u, 1u),
+ // We take the first space character.
+ NGOffsetMappingUnit(kIdentity, *layout_object_b.SlowFirstChild(), 0u,
+ 1u, 1u, 2u),
+ NGOffsetMappingUnit(kCollapsed, *layout_object_b.SlowFirstChild(), 1u,
+ 3u, 2u, 2u),
+ NGOffsetMappingUnit(kCollapsed, newline, 0u, 1u, 2u, 2u),
+ NGOffsetMappingUnit(kIdentity, *layout_object_i.SlowFirstChild(), 0u,
+ 1u, 2u, 3u),
+ }),
+ result.GetUnits());
+}
+
+TEST_F(NGOffsetMappingTest, RestoreTrailingCollapsibleSpaceSplit) {
+ // Spaces inside <b> is collapsed by during handling "\n" then it is restored
+ // by handling a newline. Restored space is removed at end of block.
+ // When RestoreTrailingCollapsibleSpace(), units are:
+ // 0: kIdentity text in <a>, dom=0,1 content=0,1
+ // 1: kCollapsed text in <b>, dom=0,3, content=2,2
+ // 2: kCollapsed "\n", dom=0,1 content=3,3
+ // layout_text is a child of <b> and offset is 2
+ SetupHtml("t",
+ "<div id=t>"
+ "<a style='white-space: pre-wrap;'> </a><b> </b>\n<i> </i>"
+ "</div>");
+ const NGOffsetMapping& result = GetOffsetMapping();
+ const LayoutObject& layout_object_a = *layout_object_;
+ const LayoutObject& layout_object_b = *layout_object_a.NextSibling();
+ const LayoutObject& newline = *layout_object_b.NextSibling();
+ const LayoutObject& layout_object_i = *newline.NextSibling();
+ EXPECT_EQ(
+ (Vector<NGOffsetMappingUnit>{
+ NGOffsetMappingUnit(kIdentity, *layout_object_a.SlowFirstChild(), 0u,
+ 1u, 0u, 1u),
+ NGOffsetMappingUnit(kCollapsed, *layout_object_b.SlowFirstChild(), 0u,
+ 3u, 2u, 2u),
+ NGOffsetMappingUnit(kCollapsed, newline, 0u, 1u, 2u, 2u),
+ NGOffsetMappingUnit(kCollapsed, *layout_object_i.SlowFirstChild(), 0u,
+ 1u, 2u, 2u),
+ }),
+ result.GetUnits());
+}
+
+TEST_F(NGOffsetMappingTest, RestoreTrailingCollapsibleSpaceSplitKeep) {
+ // Spaces inside <b> is collapsed by during handling "\n" then it is restored
+ // by handling a space in <i>.
+ // When RestoreTrailingCollapsibleSpace(), units are:
+ // 0: kIdentity text in <a>, dom=0,1 content=0,1
+ // 1: kCollapsed text in <b>, dom=0,3, content=2,2
+ // 2: kCollapsed "\n", dom=0,1 content=3,3
+ // layout_text is a child of <b> and offset is 2
+ SetupHtml("t",
+ "<div id=t>"
+ "<a style='white-space: pre-wrap;'> </a><b> </b>\n<i>x</i>"
+ "</div>");
+ const NGOffsetMapping& result = GetOffsetMapping();
+ const LayoutObject& layout_object_a = *layout_object_;
+ const LayoutObject& layout_object_b = *layout_object_a.NextSibling();
+ const LayoutObject& newline = *layout_object_b.NextSibling();
+ const LayoutObject& layout_object_i = *newline.NextSibling();
+ EXPECT_EQ(
+ (Vector<NGOffsetMappingUnit>{
+ NGOffsetMappingUnit(kIdentity, *layout_object_a.SlowFirstChild(), 0u,
+ 1u, 0u, 1u),
+ NGOffsetMappingUnit(kIdentity, *layout_object_b.SlowFirstChild(), 0u,
+ 1u, 2u, 3u),
+ NGOffsetMappingUnit(kCollapsed, *layout_object_b.SlowFirstChild(), 1u,
+ 3u, 3u, 3u),
+ NGOffsetMappingUnit(kCollapsed, newline, 0u, 1u, 3u, 3u),
+ NGOffsetMappingUnit(kIdentity, *layout_object_i.SlowFirstChild(), 0u,
+ 1u, 3u, 4u),
+ }),
+ result.GetUnits());
+}
+
TEST_F(NGOffsetMappingTest, TextOverflowEllipsis) {
LoadAhem();
SetupHtml("t",
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 08681856ab1..2c37e28cbdd 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
@@ -120,7 +120,7 @@ PhysicalRect NGPhysicalLineBoxFragment::ScrollableOverflow(
}
const NGPhysicalFragment* NGPhysicalLineBoxFragment::FirstLogicalLeaf() const {
- if (Children().IsEmpty())
+ if (Children().empty())
return nullptr;
// TODO(xiaochengh): This isn't correct for mixed Bidi. Fix it. Besides, we
// should compute and store it during layout.
@@ -130,7 +130,7 @@ const NGPhysicalFragment* NGPhysicalLineBoxFragment::FirstLogicalLeaf() const {
DynamicTo<NGPhysicalContainerFragment>(runner)) {
if (runner->IsBlockFormattingContextRoot())
break;
- if (runner_as_container->Children().IsEmpty())
+ if (runner_as_container->Children().empty())
break;
runner = direction == TextDirection::kLtr
? runner_as_container->Children().front().get()
@@ -141,7 +141,7 @@ const NGPhysicalFragment* NGPhysicalLineBoxFragment::FirstLogicalLeaf() const {
}
const NGPhysicalFragment* NGPhysicalLineBoxFragment::LastLogicalLeaf() const {
- if (Children().IsEmpty())
+ if (Children().empty())
return nullptr;
// TODO(xiaochengh): This isn't correct for mixed Bidi. Fix it. Besides, we
// should compute and store it during layout.
@@ -151,7 +151,7 @@ const NGPhysicalFragment* NGPhysicalLineBoxFragment::LastLogicalLeaf() const {
DynamicTo<NGPhysicalContainerFragment>(runner)) {
if (runner->IsBlockFormattingContextRoot())
break;
- if (runner_as_container->Children().IsEmpty())
+ if (runner_as_container->Children().empty())
break;
runner = direction == TextDirection::kLtr
? runner_as_container->Children().back().get()
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 384bb007a72..b4dc039579c 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
@@ -62,10 +62,10 @@ NGPhysicalTextFragment::NGPhysicalTextFragment(
text_(source.text_),
start_offset_(start_offset),
end_offset_(end_offset),
- shape_result_(shape_result) {
+ shape_result_(std::move(shape_result)) {
DCHECK_GE(start_offset_, source.StartOffset());
DCHECK_LE(end_offset_, source.EndOffset());
- DCHECK(shape_result_ || IsFlowControl()) << ToString();
+ DCHECK(shape_result_ || IsFlowControl()) << *this;
line_orientation_ = source.line_orientation_;
is_generated_text_ = source.is_generated_text_;
ink_overflow_computed_ = false;
@@ -77,7 +77,7 @@ NGPhysicalTextFragment::NGPhysicalTextFragment(NGTextFragmentBuilder* builder)
start_offset_(builder->start_offset_),
end_offset_(builder->end_offset_),
shape_result_(std::move(builder->shape_result_)) {
- DCHECK(shape_result_ || IsFlowControl()) << ToString();
+ DCHECK(shape_result_ || IsFlowControl()) << *this;
line_orientation_ =
static_cast<unsigned>(ToLineOrientation(builder->GetWritingMode()));
is_generated_text_ = builder->IsGeneratedText();
@@ -244,6 +244,13 @@ void NGPhysicalTextFragment::ComputeSelfInkOverflow() const {
self_ink_overflow_ = local_ink_overflow;
}
+scoped_refptr<const NGPhysicalTextFragment>
+NGPhysicalTextFragment::CloneAsHiddenForPaint() const {
+ NGTextFragmentBuilder builder(*this);
+ builder.SetIsHiddenForPaint(true);
+ return builder.ToTextFragment();
+}
+
scoped_refptr<const NGPhysicalTextFragment> NGPhysicalTextFragment::TrimText(
unsigned new_start_offset,
unsigned new_end_offset) const {
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 c46013f2bc8..a0fc73c0160 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
@@ -110,6 +110,8 @@ class CORE_EXPORT NGPhysicalTextFragment final : public NGPhysicalFragment {
// properties, in local coordinates.
PhysicalRect SelfInkOverflow() const;
+ scoped_refptr<const NGPhysicalTextFragment> CloneAsHiddenForPaint() const;
+
// Create a new fragment that has part of the text of this fragment.
// All other properties are the same as this fragment.
scoped_refptr<const NGPhysicalTextFragment> TrimText(
@@ -165,6 +167,8 @@ class CORE_EXPORT NGPhysicalTextFragment final : public NGPhysicalFragment {
// overflow, to be cached as long as it is guaranteed to always recompute to
// the same value.
mutable PhysicalRect self_ink_overflow_;
+
+ friend class NGTextFragmentBuilder;
};
template <>
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 1867897f0d7..7de65ceb791 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
@@ -38,7 +38,7 @@ class NGPhysicalTextFragmentTest : public NGLayoutTest {
}
static std::string GetText(const NGPhysicalTextFragment& fragment) {
- return fragment.Text().ToString().Utf8().data();
+ return fragment.Text().ToString().Utf8();
}
};
@@ -168,15 +168,25 @@ TEST_F(NGPhysicalTextFragmentTest, Ellipsis) {
<p id="sample">abcdef</p>
)HTML");
auto text_fragments = CollectTextFragmentsInContainer("sample");
- ASSERT_EQ(2u, text_fragments.size());
+ ASSERT_EQ(3u, text_fragments.size());
+
+ const NGPhysicalTextFragment& hidden = *text_fragments[0];
+ const NGPhysicalTextFragment& truncated = *text_fragments[1];
+ const NGPhysicalTextFragment& ellipsis = *text_fragments[2];
+
+ EXPECT_EQ(NGPhysicalTextFragment::kNormalText, hidden.TextType());
+ EXPECT_FALSE(hidden.IsGeneratedText());
+ EXPECT_TRUE(hidden.IsHiddenForPaint());
+ EXPECT_EQ(u8"abcdef", GetText(hidden));
+
+ EXPECT_EQ(NGPhysicalTextFragment::kNormalText, truncated.TextType());
+ EXPECT_FALSE(truncated.IsGeneratedText());
+ EXPECT_FALSE(truncated.IsHiddenForPaint());
+ EXPECT_EQ(u8"abc", GetText(truncated));
- const NGPhysicalTextFragment& abcdef = *text_fragments[0];
- const NGPhysicalTextFragment& ellipsis = *text_fragments[1];
- EXPECT_EQ(NGPhysicalTextFragment::kNormalText, abcdef.TextType());
- EXPECT_FALSE(abcdef.IsGeneratedText());
- EXPECT_EQ(u8"abc", GetText(abcdef));
EXPECT_EQ(NGPhysicalTextFragment::kGeneratedText, ellipsis.TextType());
EXPECT_TRUE(ellipsis.IsGeneratedText());
+ EXPECT_FALSE(ellipsis.IsHiddenForPaint());
EXPECT_EQ(u8"\u2026", GetText(ellipsis));
}
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 65b78d5bd1b..ea7efc7acb4 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
@@ -13,6 +13,15 @@
namespace blink {
+NGTextFragmentBuilder::NGTextFragmentBuilder(
+ const NGPhysicalTextFragment& fragment)
+ : NGFragmentBuilder(fragment),
+ text_(fragment.text_),
+ start_offset_(fragment.StartOffset()),
+ end_offset_(fragment.EndOffset()),
+ shape_result_(fragment.TextShapeResult()),
+ text_type_(fragment.TextType()) {}
+
void NGTextFragmentBuilder::SetItem(
NGPhysicalTextFragment::NGTextType text_type,
const NGInlineItemsData& items_data,
@@ -25,12 +34,10 @@ void NGTextFragmentBuilder::SetItem(
text_type_ = text_type;
text_ = items_data.text_content;
- item_index_ = item_result->item_index;
start_offset_ = item_result->start_offset;
end_offset_ = item_result->end_offset;
SetStyle(item_result->item->Style(), item_result->item->StyleVariant());
size_ = {item_result->inline_size, line_height};
- end_effect_ = item_result->text_end_effect;
shape_result_ = std::move(item_result->shape_result);
layout_object_ = item_result->item->GetLayoutObject();
}
@@ -47,7 +54,6 @@ void NGTextFragmentBuilder::SetText(
text_type_ = NGPhysicalTextFragment::kGeneratedText;
text_ = text;
- item_index_ = std::numeric_limits<unsigned>::max();
start_offset_ = shape_result->StartIndex();
end_offset_ = shape_result->EndIndex();
SetStyle(style, is_ellipsis_style ? NGStyleVariant::kEllipsis
@@ -56,7 +62,6 @@ void NGTextFragmentBuilder::SetText(
NGLineHeightMetrics(*style).LineHeight()};
shape_result_ = std::move(shape_result);
layout_object_ = layout_object;
- end_effect_ = NGTextEndEffect::kNone;
}
bool NGTextFragmentBuilder::IsGeneratedText() const {
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 b219736b393..97ec61d1d51 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
@@ -10,7 +10,7 @@
#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_fragment_builder.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -22,9 +22,10 @@ class CORE_EXPORT NGTextFragmentBuilder final : public NGFragmentBuilder {
STACK_ALLOCATED();
public:
- NGTextFragmentBuilder(NGInlineNode node, WritingMode writing_mode)
- : NGFragmentBuilder(writing_mode, TextDirection::kLtr),
- inline_node_(node) {}
+ NGTextFragmentBuilder(WritingMode writing_mode)
+ : NGFragmentBuilder(writing_mode, TextDirection::kLtr) {}
+
+ NGTextFragmentBuilder(const NGPhysicalTextFragment& fragment);
// NOTE: Takes ownership of the shape result within the item result.
void SetItem(NGPhysicalTextFragment::NGTextType,
@@ -47,9 +48,7 @@ class CORE_EXPORT NGTextFragmentBuilder final : public NGFragmentBuilder {
// pseudo-element, ...) instead of from a DOM text node.
bool IsGeneratedText() const;
- NGInlineNode inline_node_;
String text_;
- unsigned item_index_;
unsigned start_offset_;
unsigned end_offset_;
scoped_refptr<const ShapeResultView> shape_result_;
@@ -57,8 +56,6 @@ class CORE_EXPORT NGTextFragmentBuilder final : public NGFragmentBuilder {
NGPhysicalTextFragment::NGTextType text_type_ =
NGPhysicalTextFragment::kNormalText;
- NGTextEndEffect end_effect_ = NGTextEndEffect::kNone;
-
friend class NGPhysicalTextFragment;
};
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/layout_box_utils.cc b/chromium/third_party/blink/renderer/core/layout/ng/layout_box_utils.cc
index e1c609da844..402f5bbe615 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/layout_box_utils.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/layout_box_utils.cc
@@ -66,117 +66,94 @@ LayoutUnit LayoutBoxUtils::AvailableLogicalHeight(const LayoutBox& box,
return box.ContainingBlockLogicalWidthForContent();
}
-NGStaticPosition LayoutBoxUtils::ComputeStaticPositionFromLegacy(
+NGLogicalStaticPosition LayoutBoxUtils::ComputeStaticPositionFromLegacy(
const LayoutBox& box,
+ const NGBoxStrut& container_border_scrollbar,
const NGBoxFragmentBuilder* container_builder) {
- LayoutBoxModelObject* css_container = ToLayoutBoxModelObject(box.Container());
- LayoutBox* container = css_container->IsBox() ? ToLayoutBox(css_container)
- : box.ContainingBlock();
- const ComputedStyle* container_style = container->Style();
- const ComputedStyle* parent_style = box.Parent()->Style();
- const auto writing_mode = container_style->GetWritingMode();
-
- // Calculate the actual size of the containing block for this out-of-flow
- // descendant. This is what's used to size and position us.
+ const LayoutBoxModelObject* css_container =
+ ToLayoutBoxModelObject(box.Container());
+ const TextDirection parent_direction = box.Parent()->StyleRef().Direction();
+
+ // These two values represent the available-size for the OOF-positioned
+ // descandant, in the *descendant's* writing mode.
LayoutUnit containing_block_logical_width =
box.ContainingBlockLogicalWidthForPositioned(css_container);
LayoutUnit containing_block_logical_height =
box.ContainingBlockLogicalHeightForPositioned(css_container);
- // Determine static position.
-
- // static_inline and static_block are inline/block direction offsets from
- // physical origin. This is an unexpected blend of logical and physical in a
- // single variable.
- LayoutUnit static_inline;
- LayoutUnit static_block;
-
Length logical_left;
Length logical_right;
Length logical_top;
Length logical_bottom;
-
box.ComputeInlineStaticDistance(logical_left, logical_right, &box,
css_container, containing_block_logical_width,
container_builder);
box.ComputeBlockStaticDistance(logical_top, logical_bottom, &box,
css_container, container_builder);
- if (parent_style->IsLeftToRightDirection()) {
+ // Determine the static-position.
+ LayoutUnit static_line;
+ LayoutUnit static_block;
+ if (IsLtr(parent_direction)) {
if (!logical_left.IsAuto()) {
- static_inline =
+ static_line =
MinimumValueForLength(logical_left, containing_block_logical_width);
}
} else {
if (!logical_right.IsAuto()) {
- static_inline =
+ static_line =
MinimumValueForLength(logical_right, containing_block_logical_width);
}
+
+ // |logical_right| is an adjustment from the right edge, to keep this
+ // relative to the line-left edge account for the
+ // |containing_block_logical_width|.
+ static_line = containing_block_logical_width - static_line;
}
if (!logical_top.IsAuto()) {
static_block =
MinimumValueForLength(logical_top, containing_block_logical_height);
}
- // Legacy static position is relative to padding box. Convert to border box.
- // Also flip offsets as necessary to make them relative to to the left/top
- // edges.
-
- // First convert the static inline offset to a line-left offset, i.e.
- // physical left or top.
- LayoutUnit inline_left_or_top =
- parent_style->IsLeftToRightDirection()
- ? static_inline
- : containing_block_logical_width - static_inline;
-
- // inline_left_or_top is now relative to the padding box.
- // Make it relative to border box by adding border + scrollbar.
- NGBlockNode container_node(container);
- NGConstraintSpace non_anonymous_space =
- NGConstraintSpaceBuilder(writing_mode, writing_mode,
- /* is_new_fc */ false)
- .ToConstraintSpace();
- NGBoxStrut border_scrollbar =
- ComputeBorders(non_anonymous_space, container_node) +
- ComputeScrollbars(non_anonymous_space, container_node);
-
- // Now make it relative to the left or top border edge of the containing
- // block.
- inline_left_or_top += border_scrollbar.LineLeft(container_style->Direction());
-
- // Make the static block offset relative to the start border edge of the
- // containing block.
- static_block += border_scrollbar.block_start;
-
- // Calculate the border-box size of the object that's the containing block of
- // this out-of-flow positioned descendant. This is needed to correct
- // flipped-blocks coordinates.
- LayoutUnit container_border_box_logical_height;
- if (box.HasOverrideContainingBlockContentLogicalHeight()) {
- container_border_box_logical_height =
- box.OverrideContainingBlockContentLogicalHeight() +
- border_scrollbar.BlockSum();
- } else {
- container_border_box_logical_height = container_builder
- ? container_builder->BlockSize()
- : container->LogicalHeight();
- }
-
- // Then convert it to a physical top or left offset. Since we're already
- // 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 =
- container_style->IsFlippedBlocksWritingMode()
- ? container_border_box_logical_height - static_block
- : static_block;
-
- PhysicalOffset static_location =
- container_style->IsHorizontalWritingMode()
- ? PhysicalOffset(inline_left_or_top, block_top_or_left)
- : PhysicalOffset(block_top_or_left, inline_left_or_top);
-
- return NGStaticPosition::Create(writing_mode, parent_style->Direction(),
- static_location);
+ NGLogicalStaticPosition logical_static_position{
+ {static_line, static_block},
+ IsLtr(parent_direction)
+ ? NGLogicalStaticPosition::InlineEdge::kInlineStart
+ : NGLogicalStaticPosition::InlineEdge::kInlineEnd,
+ NGLogicalStaticPosition::BlockEdge::kBlockStart};
+
+ // Determine the physical available-size, remember that the available-size is
+ // currently in the *descendant's* writing-mode.
+ PhysicalSize container_size =
+ ToPhysicalSize(LogicalSize(containing_block_logical_width,
+ containing_block_logical_height),
+ box.StyleRef().GetWritingMode());
+
+ const LayoutBox* container = css_container->IsBox()
+ ? ToLayoutBox(css_container)
+ : box.ContainingBlock();
+ const WritingMode container_writing_mode =
+ container->StyleRef().GetWritingMode();
+ const TextDirection container_direction = container->StyleRef().Direction();
+
+ // We perform a logical-physical-logical conversion to convert the
+ // static-position into the correct writing-mode, and direction combination.
+ //
+ // At the moment the static-position is in line-relative coordinates which is
+ // why we use |TextDirection::kLtr| for the first conversion.
+ logical_static_position =
+ logical_static_position
+ .ConvertToPhysical(container_writing_mode, TextDirection::kLtr,
+ container_size)
+ .ConvertToLogical(container_writing_mode, container_direction,
+ container_size);
+
+ // Finally we shift the static-position from being relative to the
+ // padding-box, to the border-box.
+ logical_static_position.offset +=
+ LogicalOffset{container_border_scrollbar.inline_start,
+ container_border_scrollbar.block_start};
+ return logical_static_position;
}
bool LayoutBoxUtils::SkipContainingBlockForPercentHeightCalculation(
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/layout_box_utils.h b/chromium/third_party/blink/renderer/core/layout/ng/layout_box_utils.h
index afe98d0d18e..c8ef21f7e60 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/layout_box_utils.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/layout_box_utils.h
@@ -12,7 +12,8 @@ namespace blink {
class LayoutBox;
class LayoutBlock;
class NGBoxFragmentBuilder;
-struct NGStaticPosition;
+struct NGBoxStrut;
+struct NGLogicalStaticPosition;
// This static class should be used for querying information from a |LayoutBox|.
class LayoutBoxUtils {
@@ -27,11 +28,12 @@ class LayoutBoxUtils {
static LayoutUnit AvailableLogicalHeight(const LayoutBox& box,
const LayoutBlock* cb);
- // Produces an |NGStaticPosition| for |box| from the layout-tree.
- // |container_builder| is needed as not all information from current NG
+ // Produces a |NGLogicalStaticPosition| for |box| from the layout-tree.
+ // |container_builder| is needed as not all the information from current NG
// layout is copied to the layout-tree yet.
- static NGStaticPosition ComputeStaticPositionFromLegacy(
+ static NGLogicalStaticPosition ComputeStaticPositionFromLegacy(
const LayoutBox& box,
+ const NGBoxStrut& container_border_scrollbar,
const NGBoxFragmentBuilder* container_builder = nullptr);
static bool SkipContainingBlockForPercentHeightCalculation(
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 ab090971bf4..12123bb9f5a 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,24 +5,17 @@
#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/layout_box_utils.h"
-#include "third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_block_node.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_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_layout_part.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_out_of_flow_positioned_node.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 {
LayoutNGBlockFlow::LayoutNGBlockFlow(Element* element)
- : LayoutNGMixin<LayoutBlockFlow>(element) {}
+ : LayoutNGBlockFlowMixin<LayoutBlockFlow>(element) {}
LayoutNGBlockFlow::~LayoutNGBlockFlow() = default;
@@ -45,131 +38,13 @@ void LayoutNGBlockFlow::UpdateBlockLayout(bool relayout_children) {
scoped_refptr<const NGLayoutResult> result =
NGBlockNode(this).Layout(constraint_space);
- for (const NGOutOfFlowPositionedDescendant& descendant :
+ for (const auto& descendant :
result->PhysicalFragment().OutOfFlowPositionedDescendants())
descendant.node.UseLegacyOutOfFlowPositioning();
UpdateMargins(constraint_space);
}
-void LayoutNGBlockFlow::UpdateOutOfFlowBlockLayout() {
- LayoutBoxModelObject* css_container = ToLayoutBoxModelObject(Container());
- LayoutBox* container =
- css_container->IsBox() ? ToLayoutBox(css_container) : ContainingBlock();
- const ComputedStyle* container_style = container->Style();
- NGConstraintSpace constraint_space =
- NGConstraintSpace::CreateFromLayoutObject(*this);
-
- // As this is part of the Legacy->NG bridge, the container_builder is used
- // for indicating the resolved size of the OOF-positioned containing-block
- // and not used for caching purposes.
- // When we produce a layout result from it, we access its child fragments
- // which must contain *at least* this node. We use the child fragments for
- // copying back position information.
- NGBlockNode container_node(container);
- NGBoxFragmentBuilder container_builder(
- container_node, scoped_refptr<const ComputedStyle>(container_style),
- /* space */ nullptr, container_style->GetWritingMode(),
- container_style->Direction());
- container_builder.SetIsNewFormattingContext(
- container_node.CreatesNewFormattingContext());
-
- // Compute ContainingBlock logical size.
- // OverrideContainingBlockContentLogicalWidth/Height are used by e.g. grid
- // layout. Override sizes are padding box size, not border box, so we must add
- // borders and scrollbars to compensate.
- NGBoxStrut border_scrollbar =
- ComputeBorders(constraint_space, container_node) +
- ComputeScrollbars(constraint_space, container_node);
-
- // Calculate the border-box size of the object that's the containing block of
- // this out-of-flow positioned descendant. Note that this is not to be used as
- // the containing block size to resolve sizes and positions for the
- // descendant, since we're dealing with the border box here (not the padding
- // box, which is where the containing block is established). These sizes are
- // just used to do a fake/partial NG layout pass of the containing block (that
- // object is really managed by legacy layout).
- LayoutUnit container_border_box_logical_width;
- LayoutUnit container_border_box_logical_height;
- if (HasOverrideContainingBlockContentLogicalWidth()) {
- container_border_box_logical_width =
- OverrideContainingBlockContentLogicalWidth() +
- border_scrollbar.InlineSum();
- } else {
- container_border_box_logical_width = container->LogicalWidth();
- }
- if (HasOverrideContainingBlockContentLogicalHeight()) {
- container_border_box_logical_height =
- OverrideContainingBlockContentLogicalHeight() +
- border_scrollbar.BlockSum();
- } else {
- container_border_box_logical_height = container->LogicalHeight();
- }
-
- NGFragmentGeometry fragment_geometry;
- fragment_geometry.border_box_size = {container_border_box_logical_width,
- container_border_box_logical_height};
- fragment_geometry.border = ComputeBorders(constraint_space, container_node);
- fragment_geometry.padding =
- ComputePadding(constraint_space, *container_style);
- container_builder.SetInitialFragmentGeometry(fragment_geometry);
-
- NGStaticPosition static_position =
- LayoutBoxUtils::ComputeStaticPositionFromLegacy(*this);
- // Set correct container for inline containing blocks.
- container_builder.AddOutOfFlowLegacyCandidate(
- NGBlockNode(this), static_position, ToLayoutInlineOrNull(css_container));
-
- base::Optional<LogicalSize> 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());
- PhysicalSize physical_size(size);
- 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
- // should get laid out by the actual containing block.
- NGOutOfFlowLayoutPart(css_container->CanContainAbsolutePositionObjects(),
- css_container->CanContainFixedPositionObjects(),
- *container_style, constraint_space, border_scrollbar,
- &container_builder, initial_containing_block_fixed_size)
- .Run(/* only_layout */ this);
- scoped_refptr<const NGLayoutResult> result =
- container_builder.ToBoxFragment();
- // These are the unpositioned OOF descendants of the current OOF block.
- for (const NGOutOfFlowPositionedDescendant& descendant :
- result->PhysicalFragment().OutOfFlowPositionedDescendants())
- descendant.node.UseLegacyOutOfFlowPositioning();
-
- const auto& fragment = 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
- // container is this node's container.
- // Example: fixed descendant of fixed element.
- for (auto& child : fragment.Children()) {
- const NGPhysicalFragment* child_fragment = child.get();
- DCHECK(child_fragment->GetLayoutObject()->IsBox());
- LayoutBox* child_legacy_box =
- ToLayoutBox(child_fragment->GetMutableLayoutObject());
- PhysicalOffset child_offset = child.Offset();
- if (container_style->IsFlippedBlocksWritingMode()) {
- child_legacy_box->SetX(container_border_box_logical_height -
- child_offset.left - child_fragment->Size().width);
- } else {
- child_legacy_box->SetX(child_offset.left);
- }
- child_legacy_box->SetY(child_offset.top);
- }
- DCHECK_EQ(fragment.Children()[0]->GetLayoutObject(), this);
- SetIsLegacyInitiatedOutOfFlowLayout(true);
-}
-
void LayoutNGBlockFlow::UpdateMargins(const NGConstraintSpace& space) {
const LayoutBlock* containing_block = ContainingBlock();
if (!containing_block || !containing_block->IsLayoutBlockFlow())
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_block_flow.h b/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_block_flow.h
index 07792ae7e14..ae132bba87c 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_block_flow.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_block_flow.h
@@ -7,12 +7,13 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/layout/layout_block_flow.h"
-#include "third_party/blink/renderer/core/layout/ng/layout_ng_mixin.h"
+#include "third_party/blink/renderer/core/layout/ng/layout_ng_block_flow_mixin.h"
namespace blink {
// This overrides the default layout block algorithm to use Layout NG.
-class CORE_EXPORT LayoutNGBlockFlow : public LayoutNGMixin<LayoutBlockFlow> {
+class CORE_EXPORT LayoutNGBlockFlow
+ : public LayoutNGBlockFlowMixin<LayoutBlockFlow> {
public:
explicit LayoutNGBlockFlow(Element*);
~LayoutNGBlockFlow() override;
@@ -25,7 +26,6 @@ class CORE_EXPORT LayoutNGBlockFlow : public LayoutNGMixin<LayoutBlockFlow> {
bool IsOfType(LayoutObjectType) const override;
private:
- void UpdateOutOfFlowBlockLayout();
void UpdateMargins(const NGConstraintSpace&);
};
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_block_flow_mixin.cc b/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_block_flow_mixin.cc
new file mode 100644
index 00000000000..a8ca5a821e7
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_block_flow_mixin.cc
@@ -0,0 +1,331 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/layout/ng/layout_ng_block_flow_mixin.h"
+
+#include <memory>
+#include <utility>
+
+#include "third_party/blink/renderer/core/editing/position_with_affinity.h"
+#include "third_party/blink/renderer/core/layout/hit_test_location.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_physical_line_box_fragment.h"
+#include "third_party/blink/renderer/core/layout/ng/layout_box_utils.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_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_physical_box_fragment.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_relative_utils.h"
+#include "third_party/blink/renderer/core/paint/ng/ng_box_fragment_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 {
+
+template <typename Base>
+LayoutNGBlockFlowMixin<Base>::LayoutNGBlockFlowMixin(Element* element)
+ : LayoutNGMixin<Base>(element) {
+ static_assert(std::is_base_of<LayoutBlockFlow, Base>::value,
+ "Base class of LayoutNGBlockFlowMixin must be LayoutBlockFlow "
+ "or derived class.");
+ DCHECK(!element || !element->ShouldForceLegacyLayout());
+}
+
+template <typename Base>
+LayoutNGBlockFlowMixin<Base>::~LayoutNGBlockFlowMixin() = default;
+
+template <typename Base>
+void LayoutNGBlockFlowMixin<Base>::StyleDidChange(
+ StyleDifference diff,
+ const ComputedStyle* old_style) {
+ Base::StyleDidChange(diff, old_style);
+
+ if (diff.NeedsCollectInlines()) {
+ Base::SetNeedsCollectInlines();
+ }
+}
+
+template <typename Base>
+NGInlineNodeData* LayoutNGBlockFlowMixin<Base>::TakeNGInlineNodeData() {
+ return ng_inline_node_data_.release();
+}
+
+template <typename Base>
+NGInlineNodeData* LayoutNGBlockFlowMixin<Base>::GetNGInlineNodeData() const {
+ DCHECK(ng_inline_node_data_);
+ return ng_inline_node_data_.get();
+}
+
+template <typename Base>
+void LayoutNGBlockFlowMixin<Base>::ResetNGInlineNodeData() {
+ ng_inline_node_data_ = std::make_unique<NGInlineNodeData>();
+}
+
+template <typename Base>
+void LayoutNGBlockFlowMixin<Base>::ClearNGInlineNodeData() {
+ ng_inline_node_data_.reset();
+}
+
+// The current fragment from the last layout cycle for this box.
+// When pre-NG layout calls functions of this block flow, fragment and/or
+// LayoutResult are required to compute the result.
+// TODO(kojii): Use the cached result for now, we may need to reconsider as the
+// cache evolves.
+template <typename Base>
+const NGPhysicalBoxFragment* LayoutNGBlockFlowMixin<Base>::CurrentFragment()
+ const {
+ const NGLayoutResult* cached_layout_result = Base::GetCachedLayoutResult();
+ if (!cached_layout_result)
+ return nullptr;
+
+ return &To<NGPhysicalBoxFragment>(cached_layout_result->PhysicalFragment());
+}
+
+template <typename Base>
+void LayoutNGBlockFlowMixin<Base>::AddLayoutOverflowFromChildren() {
+ // |ComputeOverflow()| calls this, which is called from
+ // |CopyFragmentDataToLayoutBox()| and |RecalcOverflow()|.
+ // Add overflow from the last layout cycle.
+ // TODO(chrishtr): do we need to condition on CurrentFragment()? Why?
+ if (CurrentFragment()) {
+ AddScrollingOverflowFromChildren();
+ }
+ Base::AddLayoutOverflowFromChildren();
+}
+
+template <typename Base>
+void LayoutNGBlockFlowMixin<Base>::AddScrollingOverflowFromChildren() {
+ bool children_inline = Base::ChildrenInline();
+
+ const NGPhysicalBoxFragment* physical_fragment = CurrentFragment();
+ DCHECK(physical_fragment);
+ // inline-end LayoutOverflow padding spec is still undecided:
+ // https://github.com/w3c/csswg-drafts/issues/129
+ // For backwards compatibility, if container clips overflow,
+ // padding is added to the inline-end for inline children.
+ base::Optional<NGPhysicalBoxStrut> padding_strut;
+ if (Base::HasOverflowClip()) {
+ padding_strut =
+ NGBoxStrut(LayoutUnit(), Base::PaddingEnd(), LayoutUnit(), LayoutUnit())
+ .ConvertToPhysical(Base::StyleRef().GetWritingMode(),
+ Base::StyleRef().Direction());
+ }
+
+ PhysicalRect children_overflow;
+
+ // Only add overflow for fragments NG has not reflected into Legacy.
+ // These fragments are:
+ // - inline fragments,
+ // - out of flow fragments whose css container is inline box.
+ // TODO(layout-dev) Transforms also need to be applied to compute overflow
+ // correctly. NG is not yet transform-aware. crbug.com/855965
+ if (!physical_fragment->Children().empty()) {
+ LayoutUnit border_inline_start =
+ LayoutUnit(Base::StyleRef().BorderStartWidth());
+ LayoutUnit border_block_start =
+ LayoutUnit(Base::StyleRef().BorderBeforeWidth());
+ for (const auto& child : physical_fragment->Children()) {
+ PhysicalRect child_scrollable_overflow;
+ if (child->IsFloatingOrOutOfFlowPositioned()) {
+ child_scrollable_overflow =
+ child->ScrollableOverflowForPropagation(this);
+ } else if (children_inline && child->IsLineBox()) {
+ DCHECK(child->IsLineBox());
+ child_scrollable_overflow =
+ To<NGPhysicalLineBoxFragment>(*child).ScrollableOverflow(
+ this, Base::Style(), physical_fragment->Size());
+ if (padding_strut)
+ child_scrollable_overflow.Expand(*padding_strut);
+ } else {
+ continue;
+ }
+ child_scrollable_overflow.offset += child.Offset();
+
+ // Do not add overflow if fragment is not reachable by scrolling.
+ WritingMode writing_mode = Base::StyleRef().GetWritingMode();
+ LogicalOffset child_logical_end =
+ child_scrollable_overflow.offset.ConvertToLogical(
+ writing_mode, Base::StyleRef().Direction(),
+ physical_fragment->Size(), child_scrollable_overflow.size) +
+ child_scrollable_overflow.size.ConvertToLogical(writing_mode);
+
+ if (child_logical_end.inline_offset > border_inline_start &&
+ child_logical_end.block_offset > border_block_start)
+ children_overflow.Unite(child_scrollable_overflow);
+ }
+ }
+
+ // LayoutOverflow takes flipped blocks coordinates, adjust as needed.
+ LayoutRect children_flipped_overflow = children_overflow.ToLayoutFlippedRect(
+ physical_fragment->Style(), physical_fragment->Size());
+ Base::AddLayoutOverflow(children_flipped_overflow);
+}
+
+template <typename Base>
+void LayoutNGBlockFlowMixin<Base>::AddOutlineRects(
+ Vector<PhysicalRect>& rects,
+ const PhysicalOffset& additional_offset,
+ NGOutlineType include_block_overflows) const {
+ if (PaintFragment()) {
+ PaintFragment()->AddSelfOutlineRects(&rects, additional_offset,
+ include_block_overflows);
+ } else {
+ Base::AddOutlineRects(rects, additional_offset, include_block_overflows);
+ }
+}
+
+template <typename Base>
+bool LayoutNGBlockFlowMixin<
+ Base>::PaintedOutputOfObjectHasNoEffectRegardlessOfSize() const {
+ // LayoutNGBlockFlowMixin is in charge of paint invalidation of the first
+ // line.
+ if (PaintFragment())
+ return false;
+
+ return Base::PaintedOutputOfObjectHasNoEffectRegardlessOfSize();
+}
+
+// Retrieve NGBaseline from the current fragment.
+template <typename Base>
+base::Optional<LayoutUnit> LayoutNGBlockFlowMixin<Base>::FragmentBaseline(
+ NGBaselineAlgorithmType type) const {
+ if (Base::ShouldApplyLayoutContainment())
+ return base::nullopt;
+
+ if (const NGPhysicalFragment* physical_fragment = CurrentFragment()) {
+ FontBaseline baseline_type = Base::StyleRef().GetFontBaseline();
+ return To<NGPhysicalBoxFragment>(physical_fragment)
+ ->Baseline({type, baseline_type});
+ }
+ return base::nullopt;
+}
+
+template <typename Base>
+LayoutUnit LayoutNGBlockFlowMixin<Base>::FirstLineBoxBaseline() const {
+ if (Base::ChildrenInline()) {
+ if (base::Optional<LayoutUnit> offset =
+ FragmentBaseline(NGBaselineAlgorithmType::kFirstLine)) {
+ return *offset;
+ }
+ }
+ return Base::FirstLineBoxBaseline();
+}
+
+template <typename Base>
+LayoutUnit LayoutNGBlockFlowMixin<Base>::InlineBlockBaseline(
+ LineDirectionMode line_direction) const {
+ if (Base::ChildrenInline()) {
+ if (base::Optional<LayoutUnit> offset =
+ FragmentBaseline(NGBaselineAlgorithmType::kAtomicInline)) {
+ return *offset;
+ }
+ }
+ return Base::InlineBlockBaseline(line_direction);
+}
+
+template <typename Base>
+void LayoutNGBlockFlowMixin<Base>::SetPaintFragment(
+ const NGBlockBreakToken* break_token,
+ scoped_refptr<const NGPhysicalFragment> fragment) {
+ DCHECK(!break_token || break_token->InputNode().GetLayoutBox() == this);
+
+ scoped_refptr<NGPaintFragment>* current =
+ NGPaintFragment::Find(&paint_fragment_, break_token);
+ DCHECK(current);
+ if (fragment) {
+ *current = NGPaintFragment::Create(std::move(fragment), break_token,
+ std::move(*current));
+ // |NGPaintFragment::Create()| calls |SlowSetPaintingLayerNeedsRepaint()|.
+ } else if (*current) {
+ DCHECK_EQ(this, (*current)->GetLayoutObject());
+ // TODO(kojii): Pass break_token for LayoutObject that spans across block
+ // fragmentation boundaries.
+ (*current)->ClearAssociationWithLayoutObject();
+ *current = nullptr;
+ ObjectPaintInvalidator(*this).SlowSetPaintingLayerNeedsRepaint();
+ }
+}
+
+template <typename Base>
+void LayoutNGBlockFlowMixin<Base>::Paint(const PaintInfo& paint_info) const {
+ if (const NGPaintFragment* paint_fragment = PaintFragment())
+ NGBoxFragmentPainter(*paint_fragment).Paint(paint_info);
+ else
+ LayoutBlockFlow::Paint(paint_info);
+}
+
+template <typename Base>
+bool LayoutNGBlockFlowMixin<Base>::NodeAtPoint(
+ HitTestResult& result,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
+ HitTestAction action) {
+ const NGPaintFragment* paint_fragment = PaintFragment();
+ if (!paint_fragment) {
+ return LayoutBlockFlow::NodeAtPoint(result, hit_test_location,
+ accumulated_offset, action);
+ }
+
+ if (!this->IsEffectiveRootScroller()) {
+ // Check if we need to do anything at all.
+ // If we have clipping, then we can't have any spillout.
+ PhysicalRect overflow_box = Base::HasOverflowClip()
+ ? Base::PhysicalBorderBoxRect()
+ : Base::PhysicalVisualOverflowRect();
+ overflow_box.Move(accumulated_offset);
+ if (!hit_test_location.Intersects(overflow_box))
+ return false;
+ }
+ if (Base::IsInSelfHitTestingPhase(action) && Base::HasOverflowClip() &&
+ Base::HitTestOverflowControl(result, hit_test_location,
+ accumulated_offset))
+ return true;
+
+ return NGBoxFragmentPainter(*paint_fragment)
+ .NodeAtPoint(result, hit_test_location, accumulated_offset, action);
+}
+
+template <typename Base>
+PositionWithAffinity LayoutNGBlockFlowMixin<Base>::PositionForPoint(
+ const PhysicalOffset& point) const {
+ if (Base::IsAtomicInlineLevel()) {
+ const PositionWithAffinity atomic_inline_position =
+ Base::PositionForPointIfOutsideAtomicInlineLevel(point);
+ if (atomic_inline_position.IsNotNull())
+ return atomic_inline_position;
+ }
+
+ if (!Base::ChildrenInline())
+ return LayoutBlock::PositionForPoint(point);
+
+ if (!PaintFragment())
+ return Base::CreatePositionWithAffinity(0);
+
+ const PositionWithAffinity ng_position =
+ PaintFragment()->PositionForPoint(point);
+ if (ng_position.IsNotNull())
+ return ng_position;
+ return Base::CreatePositionWithAffinity(0);
+}
+
+template <typename Base>
+void LayoutNGBlockFlowMixin<Base>::DirtyLinesFromChangedChild(
+ LayoutObject* child,
+ MarkingBehavior marking_behavior) {
+ DCHECK_EQ(marking_behavior, kMarkContainerChain);
+
+ // 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 LayoutNGBlockFlowMixin<LayoutTableCaption>;
+template class CORE_TEMPLATE_EXPORT LayoutNGBlockFlowMixin<LayoutTableCell>;
+template class CORE_TEMPLATE_EXPORT LayoutNGBlockFlowMixin<LayoutBlockFlow>;
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_block_flow_mixin.h b/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_block_flow_mixin.h
new file mode 100644
index 00000000000..926c3395f48
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_block_flow_mixin.h
@@ -0,0 +1,100 @@
+// 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_LAYOUT_NG_LAYOUT_NG_BLOCK_FLOW_MIXIN_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_LAYOUT_NG_BLOCK_FLOW_MIXIN_H_
+
+#include <type_traits>
+
+#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/layout/layout_block_flow.h"
+#include "third_party/blink/renderer/core/layout/layout_box_model_object.h"
+#include "third_party/blink/renderer/core/layout/layout_table_caption.h"
+#include "third_party/blink/renderer/core/layout/layout_table_cell.h"
+#include "third_party/blink/renderer/core/layout/ng/layout_ng_mixin.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space.h"
+
+namespace blink {
+
+enum class NGBaselineAlgorithmType;
+class NGPaintFragment;
+class NGPhysicalFragment;
+struct NGInlineNodeData;
+
+// This mixin holds code shared between LayoutNG subclasses of LayoutBlockFlow.
+template <typename Base>
+class LayoutNGBlockFlowMixin : public LayoutNGMixin<Base> {
+ public:
+ explicit LayoutNGBlockFlowMixin(Element* element);
+ ~LayoutNGBlockFlowMixin() override;
+
+ NGInlineNodeData* TakeNGInlineNodeData() final;
+ NGInlineNodeData* GetNGInlineNodeData() const final;
+ void ResetNGInlineNodeData() final;
+ void ClearNGInlineNodeData() final;
+ bool HasNGInlineNodeData() const final { return ng_inline_node_data_.get(); }
+
+ LayoutUnit FirstLineBoxBaseline() const final;
+ LayoutUnit InlineBlockBaseline(LineDirectionMode) const final;
+
+ void Paint(const PaintInfo&) const final;
+
+ bool NodeAtPoint(HitTestResult&,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
+ HitTestAction) final;
+
+ PositionWithAffinity PositionForPoint(const PhysicalOffset&) const override;
+
+ const NGPaintFragment* PaintFragment() const final {
+ // TODO(layout-dev) crbug.com/963103
+ // Safer option here is to return nullptr only if
+ // Lifecycle > DocumentLifecycle::kAfterPerformLayout, but this breaks
+ // some layout tests.
+ if (Base::NeedsLayout())
+ return nullptr;
+ return paint_fragment_.get();
+ }
+ void SetPaintFragment(const NGBlockBreakToken*,
+ scoped_refptr<const NGPhysicalFragment>) final;
+
+ protected:
+ void StyleDidChange(StyleDifference, const ComputedStyle* old_style) override;
+
+ const NGPhysicalBoxFragment* CurrentFragment() const final;
+
+ void AddLayoutOverflowFromChildren() final;
+
+ void AddOutlineRects(Vector<PhysicalRect>&,
+ const PhysicalOffset& additional_offset,
+ NGOutlineType) const final;
+
+ bool PaintedOutputOfObjectHasNoEffectRegardlessOfSize() const final;
+
+ base::Optional<LayoutUnit> FragmentBaseline(NGBaselineAlgorithmType) const;
+
+ void DirtyLinesFromChangedChild(LayoutObject* child,
+ MarkingBehavior marking_behavior) final;
+
+ std::unique_ptr<NGInlineNodeData> ng_inline_node_data_;
+ scoped_refptr<NGPaintFragment> paint_fragment_;
+
+ friend class NGBaseLayoutAlgorithmTest;
+
+ private:
+ void AddScrollingOverflowFromChildren();
+};
+
+// If you edit these export templates, also update templates in
+// layout_ng_mixin.h.
+extern template class CORE_EXTERN_TEMPLATE_EXPORT
+ LayoutNGBlockFlowMixin<LayoutBlockFlow>;
+extern template class CORE_EXTERN_TEMPLATE_EXPORT
+ LayoutNGBlockFlowMixin<LayoutTableCaption>;
+extern template class CORE_EXTERN_TEMPLATE_EXPORT
+ LayoutNGBlockFlowMixin<LayoutTableCell>;
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_LAYOUT_NG_BLOCK_FLOW_MIXIN_H_
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 5b1bfac5755..51594e3093c 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
@@ -8,19 +8,21 @@
#include "third_party/blink/renderer/core/layout/ng/ng_block_node.h"
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space.h"
#include "third_party/blink/renderer/core/layout/ng/ng_layout_result.h"
-#include "third_party/blink/renderer/core/layout/ng/ng_out_of_flow_positioned_descendant.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_out_of_flow_positioned_node.h"
#include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h"
namespace blink {
LayoutNGFlexibleBox::LayoutNGFlexibleBox(Element* element)
- : LayoutBlock(element) {}
+ : LayoutNGMixin<LayoutBlock>(element) {}
void LayoutNGFlexibleBox::UpdateBlockLayout(bool relayout_children) {
LayoutAnalyzer::BlockScope analyzer(*this);
- // TODO(dgrogan): Reuse logic from LayoutNGBlockFlow's
- // UpdateOutOfFlowBlockLayout when this flexbox is out of flow.
+ if (IsOutOfFlowPositioned()) {
+ UpdateOutOfFlowBlockLayout();
+ return;
+ }
NGConstraintSpace constraint_space =
NGConstraintSpace::CreateFromLayoutObject(*this);
@@ -28,7 +30,7 @@ void LayoutNGFlexibleBox::UpdateBlockLayout(bool relayout_children) {
scoped_refptr<const NGLayoutResult> result =
NGBlockNode(this).Layout(constraint_space);
- for (NGOutOfFlowPositionedDescendant descendant :
+ for (const auto& descendant :
result->PhysicalFragment().OutOfFlowPositionedDescendants())
descendant.node.UseLegacyOutOfFlowPositioning();
}
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_flexible_box.h b/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_flexible_box.h
index 3f258fecb3b..c4c0fcfd227 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_flexible_box.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_flexible_box.h
@@ -6,12 +6,12 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_LAYOUT_NG_FLEXIBLE_BOX_H_
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/core/layout/layout_block_flow.h"
+#include "third_party/blink/renderer/core/layout/layout_block.h"
#include "third_party/blink/renderer/core/layout/ng/layout_ng_mixin.h"
namespace blink {
-class CORE_EXPORT LayoutNGFlexibleBox : public LayoutBlock {
+class CORE_EXPORT LayoutNGFlexibleBox : public LayoutNGMixin<LayoutBlock> {
public:
explicit LayoutNGFlexibleBox(Element*);
@@ -19,12 +19,12 @@ class CORE_EXPORT LayoutNGFlexibleBox : public LayoutBlock {
bool IsFlexibleBoxIncludingDeprecatedAndNG() const final { return true; }
bool IsFlexibleBoxIncludingNG() const final { return true; }
- bool IsLayoutNGObject() const override { return true; }
const char* GetName() const override { return "LayoutNGFlexibleBox"; }
protected:
bool IsOfType(LayoutObjectType type) const override {
- return type == kLayoutObjectNGFlexibleBox || LayoutBlock::IsOfType(type);
+ return type == kLayoutObjectNGFlexibleBox ||
+ LayoutNGMixin<LayoutBlock>::IsOfType(type);
}
};
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 cd9887971db..329b58b1f6d 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
@@ -7,29 +7,22 @@
#include <memory>
#include <utility>
-#include "third_party/blink/renderer/core/editing/position_with_affinity.h"
-#include "third_party/blink/renderer/core/layout/hit_test_location.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_physical_line_box_fragment.h"
+#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/layout/ng/layout_box_utils.h"
-#include "third_party/blink/renderer/core/layout/ng/ng_block_break_token.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_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_physical_box_fragment.h"
-#include "third_party/blink/renderer/core/layout/ng/ng_relative_utils.h"
-#include "third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.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/core/layout/ng/ng_out_of_flow_layout_part.h"
+#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
namespace blink {
template <typename Base>
LayoutNGMixin<Base>::LayoutNGMixin(Element* element) : Base(element) {
static_assert(
- std::is_base_of<LayoutBlockFlow, Base>::value,
- "Base class of LayoutNGMixin must be LayoutBlockFlow or derived class.");
+ std::is_base_of<LayoutBlock, Base>::value,
+ "Base class of LayoutNGMixin must be LayoutBlock or derived class.");
DCHECK(!element || !element->ShouldForceLegacyLayout());
}
@@ -42,51 +35,6 @@ bool LayoutNGMixin<Base>::IsOfType(LayoutObject::LayoutObjectType type) const {
}
template <typename Base>
-void LayoutNGMixin<Base>::StyleDidChange(StyleDifference diff,
- const ComputedStyle* old_style) {
- Base::StyleDidChange(diff, old_style);
-
- if (diff.NeedsCollectInlines()) {
- Base::SetNeedsCollectInlines();
- }
-}
-
-template <typename Base>
-NGInlineNodeData* LayoutNGMixin<Base>::TakeNGInlineNodeData() {
- return ng_inline_node_data_.release();
-}
-
-template <typename Base>
-NGInlineNodeData* LayoutNGMixin<Base>::GetNGInlineNodeData() const {
- DCHECK(ng_inline_node_data_);
- return ng_inline_node_data_.get();
-}
-
-template <typename Base>
-void LayoutNGMixin<Base>::ResetNGInlineNodeData() {
- ng_inline_node_data_ = std::make_unique<NGInlineNodeData>();
-}
-
-template <typename Base>
-void LayoutNGMixin<Base>::ClearNGInlineNodeData() {
- ng_inline_node_data_.reset();
-}
-
-// The current fragment from the last layout cycle for this box.
-// When pre-NG layout calls functions of this block flow, fragment and/or
-// LayoutResult are required to compute the result.
-// TODO(kojii): Use the cached result for now, we may need to reconsider as the
-// cache evolves.
-template <typename Base>
-const NGPhysicalBoxFragment* LayoutNGMixin<Base>::CurrentFragment() const {
- const NGLayoutResult* cached_layout_result = Base::GetCachedLayoutResult();
- if (!cached_layout_result)
- return nullptr;
-
- return &To<NGPhysicalBoxFragment>(cached_layout_result->PhysicalFragment());
-}
-
-template <typename Base>
void LayoutNGMixin<Base>::ComputeIntrinsicLogicalWidths(
LayoutUnit& min_logical_width,
LayoutUnit& max_logical_width) const {
@@ -123,249 +71,126 @@ void LayoutNGMixin<Base>::ComputeIntrinsicLogicalWidths(
}
template <typename Base>
-void LayoutNGMixin<Base>::AddLayoutOverflowFromChildren() {
- // |ComputeOverflow()| calls this, which is called from
- // |CopyFragmentDataToLayoutBox()| and |RecalcOverflow()|.
- // Add overflow from the last layout cycle.
- // TODO(chrishtr): do we need to condition on CurrentFragment()? Why?
- if (CurrentFragment()) {
- AddScrollingOverflowFromChildren();
- }
- Base::AddLayoutOverflowFromChildren();
-}
-
-template <typename Base>
-void LayoutNGMixin<Base>::AddScrollingOverflowFromChildren() {
- bool children_inline = Base::ChildrenInline();
-
- const NGPhysicalBoxFragment* physical_fragment = CurrentFragment();
- DCHECK(physical_fragment);
- // inline-end LayoutOverflow padding spec is still undecided:
- // https://github.com/w3c/csswg-drafts/issues/129
- // For backwards compatibility, if container clips overflow,
- // padding is added to the inline-end for inline children.
- base::Optional<NGPhysicalBoxStrut> padding_strut;
- if (Base::HasOverflowClip()) {
- padding_strut =
- NGBoxStrut(LayoutUnit(), Base::PaddingEnd(), LayoutUnit(), LayoutUnit())
- .ConvertToPhysical(Base::StyleRef().GetWritingMode(),
- Base::StyleRef().Direction());
- }
-
- PhysicalRect children_overflow;
-
- // Only add overflow for fragments NG has not reflected into Legacy.
- // These fragments are:
- // - inline fragments,
- // - out of flow fragments whose css container is inline box.
- // TODO(layout-dev) Transfroms also need to be applied to compute overflow
- // correctly. NG is not yet transform-aware. crbug.com/855965
- if (!physical_fragment->Children().IsEmpty()) {
- LayoutUnit border_inline_start =
- LayoutUnit(Base::StyleRef().BorderStartWidth());
- LayoutUnit border_block_start =
- LayoutUnit(Base::StyleRef().BorderBeforeWidth());
- for (const auto& child : physical_fragment->Children()) {
- PhysicalRect child_scrollable_overflow;
- if (child->IsOutOfFlowPositioned()) {
- child_scrollable_overflow =
- child->ScrollableOverflowForPropagation(this);
- } else if (children_inline && child->IsLineBox()) {
- DCHECK(child->IsLineBox());
- child_scrollable_overflow =
- To<NGPhysicalLineBoxFragment>(*child).ScrollableOverflow(
- this, Base::Style(), physical_fragment->Size());
- if (padding_strut)
- child_scrollable_overflow.Expand(*padding_strut);
- } else {
- continue;
- }
- child_scrollable_overflow.offset += child.Offset();
-
- // Do not add overflow if fragment is not reachable by scrolling.
- WritingMode writing_mode = Base::StyleRef().GetWritingMode();
- LogicalOffset child_logical_end =
- child_scrollable_overflow.offset.ConvertToLogical(
- writing_mode, Base::StyleRef().Direction(),
- physical_fragment->Size(), child_scrollable_overflow.size) +
- child_scrollable_overflow.size.ConvertToLogical(writing_mode);
-
- if (child_logical_end.inline_offset > border_inline_start &&
- child_logical_end.block_offset > border_block_start)
- children_overflow.Unite(child_scrollable_overflow);
- }
- }
-
- // LayoutOverflow takes flipped blocks coordinates, adjust as needed.
- LayoutRect children_flipped_overflow = children_overflow.ToLayoutFlippedRect(
- physical_fragment->Style(), physical_fragment->Size());
- Base::AddLayoutOverflow(children_flipped_overflow);
-}
-
-template <typename Base>
-void LayoutNGMixin<Base>::AddOutlineRects(
- Vector<PhysicalRect>& rects,
- const PhysicalOffset& additional_offset,
- NGOutlineType include_block_overflows) const {
- if (PaintFragment()) {
- PaintFragment()->AddSelfOutlineRects(&rects, additional_offset,
- include_block_overflows);
+void LayoutNGMixin<Base>::UpdateOutOfFlowBlockLayout() {
+ LayoutBoxModelObject* css_container =
+ ToLayoutBoxModelObject(Base::Container());
+ LayoutBox* container = css_container->IsBox() ? ToLayoutBox(css_container)
+ : Base::ContainingBlock();
+ const ComputedStyle* container_style = container->Style();
+ NGConstraintSpace constraint_space =
+ NGConstraintSpace::CreateFromLayoutObject(*this);
+
+ // As this is part of the Legacy->NG bridge, the container_builder is used
+ // for indicating the resolved size of the OOF-positioned containing-block
+ // and not used for caching purposes.
+ // When we produce a layout result from it, we access its child fragments
+ // which must contain *at least* this node. We use the child fragments for
+ // copying back position information.
+ NGBlockNode container_node(container);
+ NGBoxFragmentBuilder container_builder(
+ container_node, scoped_refptr<const ComputedStyle>(container_style),
+ /* space */ nullptr, container_style->GetWritingMode(),
+ container_style->Direction());
+ container_builder.SetIsNewFormattingContext(
+ container_node.CreatesNewFormattingContext());
+
+ NGFragmentGeometry fragment_geometry;
+ fragment_geometry.border = ComputeBorders(constraint_space, container_node);
+ fragment_geometry.scrollbar =
+ ComputeScrollbars(constraint_space, container_node);
+ fragment_geometry.padding =
+ ComputePadding(constraint_space, *container_style);
+
+ NGBoxStrut border_scrollbar =
+ fragment_geometry.border + fragment_geometry.scrollbar;
+
+ // Calculate the border-box size of the object that's the containing block of
+ // this out-of-flow positioned descendant. Note that this is not to be used as
+ // the containing block size to resolve sizes and positions for the
+ // descendant, since we're dealing with the border box here (not the padding
+ // box, which is where the containing block is established). These sizes are
+ // just used to do a fake/partial NG layout pass of the containing block (that
+ // object is really managed by legacy layout).
+ LayoutUnit container_border_box_logical_width;
+ LayoutUnit container_border_box_logical_height;
+ if (Base::HasOverrideContainingBlockContentLogicalWidth()) {
+ container_border_box_logical_width =
+ Base::OverrideContainingBlockContentLogicalWidth() +
+ border_scrollbar.InlineSum();
} else {
- Base::AddOutlineRects(rects, additional_offset, include_block_overflows);
+ container_border_box_logical_width = container->LogicalWidth();
}
-}
-
-template <typename Base>
-bool LayoutNGMixin<Base>::PaintedOutputOfObjectHasNoEffectRegardlessOfSize()
- const {
- // LayoutNGMixin is in charge of paint invalidation of the first line.
- if (PaintFragment())
- return false;
-
- return Base::PaintedOutputOfObjectHasNoEffectRegardlessOfSize();
-}
-
-// Retrieve NGBaseline from the current fragment.
-template <typename Base>
-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 To<NGPhysicalBoxFragment>(physical_fragment)
- ->Baseline({type, baseline_type});
+ if (Base::HasOverrideContainingBlockContentLogicalHeight()) {
+ container_border_box_logical_height =
+ Base::OverrideContainingBlockContentLogicalHeight() +
+ border_scrollbar.BlockSum();
+ } else {
+ container_border_box_logical_height = container->LogicalHeight();
}
- return base::nullopt;
-}
-template <typename Base>
-LayoutUnit LayoutNGMixin<Base>::FirstLineBoxBaseline() const {
- if (Base::ChildrenInline()) {
- if (base::Optional<LayoutUnit> offset =
- FragmentBaseline(NGBaselineAlgorithmType::kFirstLine)) {
- return *offset;
+ fragment_geometry.border_box_size = {container_border_box_logical_width,
+ container_border_box_logical_height};
+ container_builder.SetInitialFragmentGeometry(fragment_geometry);
+
+ NGLogicalStaticPosition static_position =
+ LayoutBoxUtils::ComputeStaticPositionFromLegacy(*this, border_scrollbar);
+ // Set correct container for inline containing blocks.
+ container_builder.AddOutOfFlowLegacyCandidate(
+ NGBlockNode(this), static_position, ToLayoutInlineOrNull(css_container));
+
+ base::Optional<LogicalSize> initial_containing_block_fixed_size;
+ if (container->IsLayoutView() && !Base::GetDocument().Printing()) {
+ if (LocalFrameView* frame_view = ToLayoutView(container)->GetFrameView()) {
+ IntSize size =
+ frame_view->LayoutViewport()->ExcludeScrollbars(frame_view->Size());
+ PhysicalSize physical_size(size);
+ initial_containing_block_fixed_size =
+ physical_size.ConvertToLogical(container->Style()->GetWritingMode());
}
}
- return Base::FirstLineBoxBaseline();
-}
-
-template <typename Base>
-LayoutUnit LayoutNGMixin<Base>::InlineBlockBaseline(
- LineDirectionMode line_direction) const {
- if (Base::ChildrenInline()) {
- if (base::Optional<LayoutUnit> offset =
- FragmentBaseline(NGBaselineAlgorithmType::kAtomicInline)) {
- return *offset;
+ // 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
+ // should get laid out by the actual containing block.
+ NGOutOfFlowLayoutPart(css_container->CanContainAbsolutePositionObjects(),
+ css_container->CanContainFixedPositionObjects(),
+ *container_style, constraint_space, border_scrollbar,
+ &container_builder, initial_containing_block_fixed_size)
+ .Run(/* only_layout */ this);
+ scoped_refptr<const NGLayoutResult> result =
+ container_builder.ToBoxFragment();
+ // These are the unpositioned OOF descendants of the current OOF block.
+ for (const auto& descendant :
+ result->PhysicalFragment().OutOfFlowPositionedDescendants())
+ descendant.node.UseLegacyOutOfFlowPositioning();
+
+ const auto& fragment = 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
+ // container is this node's container.
+ // Example: fixed descendant of fixed element.
+ for (auto& child : fragment.Children()) {
+ const NGPhysicalFragment* child_fragment = child.get();
+ DCHECK(child_fragment->GetLayoutObject()->IsBox());
+ LayoutBox* child_legacy_box =
+ ToLayoutBox(child_fragment->GetMutableLayoutObject());
+ PhysicalOffset child_offset = child.Offset();
+ if (container_style->IsFlippedBlocksWritingMode()) {
+ child_legacy_box->SetX(container_border_box_logical_height -
+ child_offset.left - child_fragment->Size().width);
+ } else {
+ child_legacy_box->SetX(child_offset.left);
}
+ child_legacy_box->SetY(child_offset.top);
}
- return Base::InlineBlockBaseline(line_direction);
-}
-
-template <typename Base>
-void LayoutNGMixin<Base>::SetPaintFragment(
- const NGBlockBreakToken* break_token,
- scoped_refptr<const NGPhysicalFragment> fragment) {
- DCHECK(!break_token || break_token->InputNode().GetLayoutBox() == this);
-
- scoped_refptr<NGPaintFragment>* current =
- NGPaintFragment::Find(&paint_fragment_, break_token);
- DCHECK(current);
- if (fragment) {
- *current = NGPaintFragment::Create(std::move(fragment), break_token,
- std::move(*current));
- // |NGPaintFragment::Create()| calls |SlowSetPaintingLayerNeedsRepaint()|.
- } else if (*current) {
- DCHECK_EQ(this, (*current)->GetLayoutObject());
- *current = nullptr;
- ObjectPaintInvalidator(*this).SlowSetPaintingLayerNeedsRepaint();
- }
-}
-
-template <typename Base>
-void LayoutNGMixin<Base>::Paint(const PaintInfo& paint_info) const {
- if (const NGPaintFragment* paint_fragment = PaintFragment())
- NGBoxFragmentPainter(*paint_fragment).Paint(paint_info);
- else
- LayoutBlockFlow::Paint(paint_info);
-}
-
-template <typename Base>
-bool LayoutNGMixin<Base>::NodeAtPoint(
- HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
- HitTestAction action) {
- const NGPaintFragment* paint_fragment = PaintFragment();
- if (!paint_fragment) {
- return LayoutBlockFlow::NodeAtPoint(result, location_in_container,
- accumulated_offset, action);
- }
- // In LayoutBox::NodeAtPoint() and subclass overrides, it is guaranteed that
- // |accumulated_offset + Location()| equals the physical offset of the current
- // LayoutBox in the paint layer, regardless of writing mode or whether the box
- // was placed by NG or legacy.
- const LayoutPoint physical_offset = accumulated_offset + Base::Location();
- if (!this->IsEffectiveRootScroller()) {
- // Check if we need to do anything at all.
- // If we have clipping, then we can't have any spillout.
- LayoutRect overflow_box = Base::HasOverflowClip()
- ? Base::BorderBoxRect()
- : Base::VisualOverflowRect();
- overflow_box.MoveBy(physical_offset);
- if (!location_in_container.Intersects(overflow_box))
- return false;
- }
- if (Base::IsInSelfHitTestingPhase(action) && Base::HasOverflowClip() &&
- Base::HitTestOverflowControl(result, location_in_container,
- physical_offset))
- return true;
-
- return NGBoxFragmentPainter(*paint_fragment)
- .NodeAtPoint(result, location_in_container, physical_offset, action);
-}
-
-template <typename Base>
-PositionWithAffinity LayoutNGMixin<Base>::PositionForPoint(
- const LayoutPoint& point) const {
- if (Base::IsAtomicInlineLevel()) {
- const PositionWithAffinity atomic_inline_position =
- Base::PositionForPointIfOutsideAtomicInlineLevel(point);
- if (atomic_inline_position.IsNotNull())
- return atomic_inline_position;
- }
-
- if (!Base::ChildrenInline())
- return LayoutBlock::PositionForPoint(point);
-
- if (!PaintFragment())
- return Base::CreatePositionWithAffinity(0);
-
- // Flip because |point| is in flipped physical coordinates while
- // NGPaintFragment::PositionForPoint() requires pure physical coordinates.
- const PositionWithAffinity ng_position =
- PaintFragment()->PositionForPoint(Base::FlipForWritingMode(point));
- if (ng_position.IsNotNull())
- return ng_position;
- return Base::CreatePositionWithAffinity(0);
-}
-
-template <typename Base>
-void LayoutNGMixin<Base>::DirtyLinesFromChangedChild(
- LayoutObject* child,
- MarkingBehavior marking_behavior) {
- DCHECK_EQ(marking_behavior, kMarkContainerChain);
-
- // 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);
+ DCHECK_EQ(fragment.Children()[0]->GetLayoutObject(), this);
+ Base::SetIsLegacyInitiatedOutOfFlowLayout(true);
}
+template class CORE_TEMPLATE_EXPORT LayoutNGMixin<LayoutBlock>;
+template class CORE_TEMPLATE_EXPORT LayoutNGMixin<LayoutBlockFlow>;
template class CORE_TEMPLATE_EXPORT LayoutNGMixin<LayoutTableCaption>;
template class CORE_TEMPLATE_EXPORT LayoutNGMixin<LayoutTableCell>;
-template class CORE_TEMPLATE_EXPORT LayoutNGMixin<LayoutBlockFlow>;
} // namespace blink
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 7f45d582c85..57eea646a14 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
@@ -9,21 +9,13 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/layout/layout_block_flow.h"
-#include "third_party/blink/renderer/core/layout/layout_box_model_object.h"
#include "third_party/blink/renderer/core/layout/layout_table_caption.h"
#include "third_party/blink/renderer/core/layout/layout_table_cell.h"
-#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space.h"
namespace blink {
-enum class NGBaselineAlgorithmType;
-class NGPaintFragment;
-class NGPhysicalFragment;
-struct NGInlineNodeData;
-
// This mixin holds code shared between LayoutNG subclasses of
-// LayoutBlockFlow.
-
+// LayoutBlock.
template <typename Base>
class LayoutNGMixin : public Base {
public:
@@ -32,69 +24,17 @@ class LayoutNGMixin : public Base {
bool IsLayoutNGObject() const final { return true; }
- NGInlineNodeData* TakeNGInlineNodeData() final;
- NGInlineNodeData* GetNGInlineNodeData() const final;
- void ResetNGInlineNodeData() final;
- void ClearNGInlineNodeData() final;
- bool HasNGInlineNodeData() const final { return ng_inline_node_data_.get(); }
-
- LayoutUnit FirstLineBoxBaseline() const final;
- LayoutUnit InlineBlockBaseline(LineDirectionMode) const final;
-
- void Paint(const PaintInfo&) const final;
-
- bool NodeAtPoint(HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
- HitTestAction) final;
-
- PositionWithAffinity PositionForPoint(const LayoutPoint&) const override;
-
- const NGPaintFragment* PaintFragment() const final {
- // TODO(layout-dev) crbug.com/963103
- // Safer option here is to return nullptr only if
- // Lifecycle > DocumentLifecycle::kAfterPerformLayout, but this breaks
- // some layout tests.
- if (Base::NeedsLayout())
- return nullptr;
- return paint_fragment_.get();
- }
- void SetPaintFragment(const NGBlockBreakToken*,
- scoped_refptr<const NGPhysicalFragment>) final;
-
protected:
bool IsOfType(LayoutObject::LayoutObjectType) const override;
- void StyleDidChange(StyleDifference, const ComputedStyle* old_style) override;
-
void ComputeIntrinsicLogicalWidths(
LayoutUnit& min_logical_width,
LayoutUnit& max_logical_width) const override;
- void AddLayoutOverflowFromChildren() final;
-
- void AddOutlineRects(Vector<PhysicalRect>&,
- const PhysicalOffset& additional_offset,
- NGOutlineType) const final;
-
- bool PaintedOutputOfObjectHasNoEffectRegardlessOfSize() const final;
-
- const NGPhysicalBoxFragment* CurrentFragment() const final;
-
- base::Optional<LayoutUnit> FragmentBaseline(NGBaselineAlgorithmType) const;
-
- void DirtyLinesFromChangedChild(LayoutObject* child,
- MarkingBehavior marking_behavior) final;
-
- std::unique_ptr<NGInlineNodeData> ng_inline_node_data_;
- scoped_refptr<NGPaintFragment> paint_fragment_;
-
- friend class NGBaseLayoutAlgorithmTest;
-
- private:
- void AddScrollingOverflowFromChildren();
+ void UpdateOutOfFlowBlockLayout();
};
+extern template class CORE_EXTERN_TEMPLATE_EXPORT LayoutNGMixin<LayoutBlock>;
extern template class CORE_EXTERN_TEMPLATE_EXPORT
LayoutNGMixin<LayoutBlockFlow>;
extern template class CORE_EXTERN_TEMPLATE_EXPORT
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 d6756cc09ba..e1fbe037fa9 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
@@ -10,13 +10,13 @@
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space.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"
+#include "third_party/blink/renderer/core/layout/ng/ng_out_of_flow_positioned_node.h"
#include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h"
namespace blink {
LayoutNGTableCaption::LayoutNGTableCaption(Element* element)
- : LayoutNGMixin<LayoutTableCaption>(element) {}
+ : LayoutNGBlockFlowMixin<LayoutTableCaption>(element) {}
void LayoutNGTableCaption::CalculateAndSetMargins(
const NGConstraintSpace& constraint_space,
@@ -69,7 +69,7 @@ void LayoutNGTableCaption::UpdateBlockLayout(bool relayout_children) {
// point to LayoutNG. If our parent were LayoutNG, it wouldn't have called
// UpdateBlockLayout, it would have packaged this LayoutObject into
// NGBlockNode and called Layout on that.
- for (NGOutOfFlowPositionedDescendant descendant :
+ for (const auto& descendant :
result->PhysicalFragment().OutOfFlowPositionedDescendants())
descendant.node.UseLegacyOutOfFlowPositioning();
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_table_caption.h b/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_table_caption.h
index 1ea6e5994ee..35ee8e2d78e 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_table_caption.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_table_caption.h
@@ -7,12 +7,12 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/layout/layout_table_caption.h"
-#include "third_party/blink/renderer/core/layout/ng/layout_ng_mixin.h"
+#include "third_party/blink/renderer/core/layout/ng/layout_ng_block_flow_mixin.h"
namespace blink {
class CORE_EXPORT LayoutNGTableCaption final
- : public LayoutNGMixin<LayoutTableCaption> {
+ : public LayoutNGBlockFlowMixin<LayoutTableCaption> {
public:
explicit LayoutNGTableCaption(Element*);
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 d38d1a2bc23..6b8c2da3872 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
@@ -9,13 +9,13 @@
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space.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"
+#include "third_party/blink/renderer/core/layout/ng/ng_out_of_flow_positioned_node.h"
#include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h"
namespace blink {
LayoutNGTableCell::LayoutNGTableCell(Element* element)
- : LayoutNGMixin<LayoutTableCell>(element) {}
+ : LayoutNGBlockFlowMixin<LayoutTableCell>(element) {}
void LayoutNGTableCell::UpdateBlockLayout(bool relayout_children) {
LayoutAnalyzer::BlockScope analyzer(*this);
@@ -28,7 +28,7 @@ void LayoutNGTableCell::UpdateBlockLayout(bool relayout_children) {
scoped_refptr<const NGLayoutResult> result =
NGBlockNode(this).Layout(constraint_space);
- for (NGOutOfFlowPositionedDescendant descendant :
+ for (const auto& descendant :
result->PhysicalFragment().OutOfFlowPositionedDescendants())
descendant.node.UseLegacyOutOfFlowPositioning();
}
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_table_cell.h b/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_table_cell.h
index eb8c2cc19c9..d51ed533865 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_table_cell.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/layout_ng_table_cell.h
@@ -7,12 +7,12 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/layout/layout_table_cell.h"
-#include "third_party/blink/renderer/core/layout/ng/layout_ng_mixin.h"
+#include "third_party/blink/renderer/core/layout/ng/layout_ng_block_flow_mixin.h"
namespace blink {
class CORE_EXPORT LayoutNGTableCell final
- : public LayoutNGMixin<LayoutTableCell> {
+ : public LayoutNGBlockFlowMixin<LayoutTableCell> {
public:
explicit LayoutNGTableCell(Element*);
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/legacy_layout_tree_walking.h b/chromium/third_party/blink/renderer/core/layout/ng/legacy_layout_tree_walking.h
index 7d8327a8375..82ea95eb171 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/legacy_layout_tree_walking.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/legacy_layout_tree_walking.h
@@ -90,14 +90,13 @@ inline bool AreNGBlockFlowChildrenInline(const LayoutBlock* block) {
inline bool IsLayoutNGContainingBlock(const LayoutBlock* containing_block) {
if (UNLIKELY(containing_block->IsLayoutFlowThread()))
containing_block = containing_block->ContainingBlock();
- return containing_block && (containing_block->IsLayoutNGMixin() ||
- containing_block->IsLayoutNGFlexibleBox());
+ return containing_block && containing_block->IsLayoutNGMixin();
}
// Return true if the layout object is a LayoutNG object that is managed by the
// LayoutNG engine (i.e. its containing block is a LayoutNG object as well).
inline bool IsManagedByLayoutNG(const LayoutObject& object) {
- if (!object.IsLayoutNGMixin() && !object.IsLayoutNGFlexibleBox())
+ if (!object.IsLayoutNGMixin())
return false;
const auto* containing_block = object.ContainingBlock();
if (UNLIKELY(!containing_block))
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/list/layout_ng_inside_list_marker.cc b/chromium/third_party/blink/renderer/core/layout/ng/list/layout_ng_inside_list_marker.cc
index 6938996dcdf..5cdeb8d9124 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/list/layout_ng_inside_list_marker.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/list/layout_ng_inside_list_marker.cc
@@ -25,7 +25,7 @@ bool LayoutNGInsideListMarker::IsOfType(LayoutObjectType type) const {
}
PositionWithAffinity LayoutNGInsideListMarker::PositionForPoint(
- const LayoutPoint&) const {
+ const PhysicalOffset&) const {
return CreatePositionWithAffinity(0);
}
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/list/layout_ng_inside_list_marker.h b/chromium/third_party/blink/renderer/core/layout/ng/list/layout_ng_inside_list_marker.h
index 9197de75027..ec19ee390b2 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/list/layout_ng_inside_list_marker.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/list/layout_ng_inside_list_marker.h
@@ -30,7 +30,7 @@ class CORE_EXPORT LayoutNGInsideListMarker final : public LayoutInline {
private:
bool IsOfType(LayoutObjectType) const override;
- PositionWithAffinity PositionForPoint(const LayoutPoint&) const override;
+ PositionWithAffinity PositionForPoint(const PhysicalOffset&) const override;
};
DEFINE_LAYOUT_OBJECT_TYPE_CASTS(LayoutNGInsideListMarker,
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 7a6416b5e15..1bfde5ae9cc 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
@@ -52,6 +52,22 @@ void LayoutNGListItem::StyleDidChange(StyleDifference diff,
LayoutNGBlockFlow::StyleDidChange(diff, old_style);
UpdateMarker();
+
+ if (old_style && old_style->ListStyleType() != StyleRef().ListStyleType())
+ ListStyleTypeChanged();
+}
+
+// If the value of ListStyleType changed, we need to the marker text has been
+// updated.
+void LayoutNGListItem::ListStyleTypeChanged() {
+ if (!is_marker_text_updated_)
+ return;
+
+ is_marker_text_updated_ = false;
+ if (marker_) {
+ marker_->SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
+ layout_invalidation_reason::kListStyleTypeChange);
+ }
}
void LayoutNGListItem::OrdinalValueChanged() {
@@ -322,18 +338,24 @@ void LayoutNGListItem::UpdateMarkerContentIfNeeded() {
} else {
// Create a LayoutText in it.
LayoutText* text = nullptr;
+ // |text_style| should be as same as style propagated in
+ // |LayoutObject::PropagateStyleToAnonymousChildren()| to avoid unexpected
+ // full layout due by style difference. See http://crbug.com/980399
+ scoped_refptr<ComputedStyle> text_style =
+ ComputedStyle::CreateAnonymousStyleWithDisplay(
+ marker_->StyleRef(), marker_->StyleRef().Display());
if (child) {
if (child->IsText()) {
text = ToLayoutText(child);
- text->SetStyle(marker_->MutableStyle());
+ text->SetStyle(text_style);
} else {
child->Destroy();
child = nullptr;
}
}
if (!child) {
- text = LayoutText::CreateEmptyAnonymous(
- GetDocument(), marker_->MutableStyle(), LegacyLayout::kAuto);
+ text = LayoutText::CreateEmptyAnonymous(GetDocument(), text_style,
+ LegacyLayout::kAuto);
marker_->AddChild(text);
is_marker_text_updated_ = false;
}
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 c56eaa614e6..6da8999fe4c 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
@@ -67,6 +67,8 @@ class CORE_EXPORT LayoutNGListItem final : public LayoutNGBlockFlow {
void UpdateMarker();
void DestroyMarker();
+ void ListStyleTypeChanged();
+
ListItemOrdinal ordinal_;
LayoutObject* marker_ = nullptr;
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 bf9f4090fc3..06b77320f05 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
@@ -10,7 +10,7 @@
namespace blink {
LayoutNGListMarker::LayoutNGListMarker(Element* element)
- : LayoutNGMixin<LayoutBlockFlow>(element) {}
+ : LayoutNGBlockFlowMixin<LayoutBlockFlow>(element) {}
LayoutNGListMarker* LayoutNGListMarker::CreateAnonymous(Document* document) {
LayoutNGListMarker* object = new LayoutNGListMarker(nullptr);
@@ -54,7 +54,7 @@ bool LayoutNGListMarker::NeedsOccupyWholeLine() const {
}
PositionWithAffinity LayoutNGListMarker::PositionForPoint(
- const LayoutPoint&) const {
+ const PhysicalOffset&) const {
return CreatePositionWithAffinity(0);
}
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/list/layout_ng_list_marker.h b/chromium/third_party/blink/renderer/core/layout/ng/list/layout_ng_list_marker.h
index 74eb29ed096..d317122a3a8 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/list/layout_ng_list_marker.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/list/layout_ng_list_marker.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/layout/layout_block_flow.h"
-#include "third_party/blink/renderer/core/layout/ng/layout_ng_mixin.h"
+#include "third_party/blink/renderer/core/layout/ng/layout_ng_block_flow_mixin.h"
namespace blink {
@@ -15,7 +15,7 @@ class Document;
// A LayoutObject subclass for outside-positioned list markers in LayoutNG.
class CORE_EXPORT LayoutNGListMarker final
- : public LayoutNGMixin<LayoutBlockFlow> {
+ : public LayoutNGBlockFlowMixin<LayoutBlockFlow> {
public:
explicit LayoutNGListMarker(Element*);
static LayoutNGListMarker* CreateAnonymous(Document*);
@@ -32,7 +32,7 @@ class CORE_EXPORT LayoutNGListMarker final
private:
bool IsOfType(LayoutObjectType) const override;
- PositionWithAffinity PositionForPoint(const LayoutPoint&) const override;
+ PositionWithAffinity PositionForPoint(const PhysicalOffset&) const override;
};
DEFINE_LAYOUT_OBJECT_TYPE_CASTS(LayoutNGListMarker, IsLayoutNGListMarker());
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 0231815b925..8a4ff041b84 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
@@ -51,19 +51,18 @@ scoped_refptr<const NGLayoutResult> NGUnpositionedListMarker::Layout(
return marker_layout_result;
}
-bool NGUnpositionedListMarker::AddToBox(
+bool NGUnpositionedListMarker::CanAddToBox(
const NGConstraintSpace& space,
FontBaseline baseline_type,
const NGPhysicalFragment& content,
- LogicalOffset* content_offset,
- NGBoxFragmentBuilder* container_builder,
- const NGBoxStrut& border_scrollbar_padding) const {
+ NGLineHeightMetrics* content_metrics) const {
+ DCHECK(content_metrics);
+
// Baselines from two different writing-mode cannot be aligned.
if (UNLIKELY(space.GetWritingMode() != content.Style().GetWritingMode()))
return false;
// Compute the baseline of the child content.
- NGLineHeightMetrics content_metrics;
if (content.IsLineBox()) {
const auto& line_box = To<NGPhysicalLineBoxFragment>(content);
@@ -73,26 +72,35 @@ bool NGUnpositionedListMarker::AddToBox(
if (line_box.IsEmptyLineBox() && !line_box.BreakToken()->IsFinished())
return false;
- content_metrics = line_box.Metrics();
+ *content_metrics = line_box.Metrics();
} else {
NGBoxFragment content_fragment(space.GetWritingMode(), space.Direction(),
To<NGPhysicalBoxFragment>(content));
- content_metrics = content_fragment.BaselineMetricsWithoutSynthesize(
+ *content_metrics = content_fragment.BaselineMetricsWithoutSynthesize(
{NGBaselineAlgorithmType::kFirstLine, baseline_type});
// If this child content does not have any line boxes, the list marker
// should be aligned to the first line box of next child.
// https://github.com/w3c/csswg-drafts/issues/2417
- if (content_metrics.IsEmpty())
+ if (content_metrics->IsEmpty())
return false;
}
+ return true;
+}
+
+void NGUnpositionedListMarker::AddToBox(
+ const NGConstraintSpace& space,
+ FontBaseline baseline_type,
+ const NGPhysicalFragment& content,
+ const NGBoxStrut& border_scrollbar_padding,
+ const NGLineHeightMetrics& content_metrics,
+ const NGLayoutResult& marker_layout_result,
+ LogicalOffset* content_offset,
+ NGBoxFragmentBuilder* container_builder) const {
+ DCHECK(!content_metrics.IsEmpty());
- // Layout the list marker.
- scoped_refptr<const NGLayoutResult> marker_layout_result =
- Layout(space, container_builder->Style(), baseline_type);
- DCHECK(marker_layout_result);
const NGPhysicalBoxFragment& marker_physical_fragment =
- To<NGPhysicalBoxFragment>(marker_layout_result->PhysicalFragment());
+ To<NGPhysicalBoxFragment>(marker_layout_result.PhysicalFragment());
// Compute the inline offset of the marker.
NGBoxFragment marker_fragment(space.GetWritingMode(), space.Direction(),
@@ -117,20 +125,15 @@ bool NGUnpositionedListMarker::AddToBox(
DCHECK(container_builder);
container_builder->AddChild(marker_physical_fragment, marker_offset);
-
- return true;
}
LayoutUnit NGUnpositionedListMarker::AddToBoxWithoutLineBoxes(
const NGConstraintSpace& space,
FontBaseline baseline_type,
+ const NGLayoutResult& marker_layout_result,
NGBoxFragmentBuilder* container_builder) const {
- // Layout the list marker.
- scoped_refptr<const NGLayoutResult> marker_layout_result =
- Layout(space, container_builder->Style(), baseline_type);
- DCHECK(marker_layout_result);
const NGPhysicalBoxFragment& marker_physical_fragment =
- To<NGPhysicalBoxFragment>(marker_layout_result->PhysicalFragment());
+ To<NGPhysicalBoxFragment>(marker_layout_result.PhysicalFragment());
// When there are no line boxes, marker is top-aligned to the list item.
// https://github.com/w3c/csswg-drafts/issues/2417
@@ -152,6 +155,10 @@ LayoutUnit NGUnpositionedListMarker::ComputeIntrudedFloatOffset(
const NGBoxStrut& border_scrollbar_padding,
LayoutUnit marker_block_offset) const {
DCHECK(container_builder);
+ // If the BFC block-offset isn't resolved, the intruded offset isn't
+ // available either.
+ if (!container_builder->BfcBlockOffset())
+ return LayoutUnit();
// Because opportunity.rect is in the content area of LI, so origin_offset
// should plus border_scrollbar_padding.inline_start, and available_size
// should minus border_scrollbar_padding.
@@ -177,7 +184,19 @@ LayoutUnit NGUnpositionedListMarker::ComputeIntrudedFloatOffset(
return origin_offset.line_offset + available_size -
opportunity.rect.LineEndOffset();
}
- return LayoutUnit(0);
+ return LayoutUnit();
+}
+
+#if DCHECK_IS_ON()
+// TODO: Currently we haven't supported ::marker, so the margin-top of marker
+// should always be zero. And this make us could resolve LI's BFC block-offset
+// in NGBlockLayoutAlgorithm::PositionOrPropagateListMarker and
+// NGBlockLayoutAlgorithm::PositionListMarkerWithoutLineBoxes without consider
+// marker's margin-top.
+void NGUnpositionedListMarker::CheckMargin() const {
+ DCHECK(marker_layout_object_);
+ DCHECK(marker_layout_object_->StyleRef().MarginBefore().IsZero());
}
+#endif
} // namespace blink
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 166b5b09a4b..8305cac2cf6 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
@@ -9,7 +9,7 @@
#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/platform/fonts/font_baseline.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -23,6 +23,7 @@ class NGLayoutResult;
class NGPhysicalFragment;
struct LogicalOffset;
+struct NGLineHeightMetrics;
// Represents an unpositioned list marker.
//
@@ -33,6 +34,19 @@ struct LogicalOffset;
// To handle these two cases consistently, when list markers appear in these
// algorithm, they are set as "unpositioned", and are propagated to ancestors
// through NGLayoutResult until they meet the corresponding list items.
+//
+// In order to adjust with the other content of LI, marker will be handled
+// after other children.
+// First, try to find the adjusted content_metrics for the marker. See
+// |CanAddToBox()| for details.
+// If found, layout marker, compute the content adjusted offset and float
+// intuded offset. See |AddToBox()| for details.
+// If not, layout marker and deal with it in |AddToBoxWithoutLineBoxes()|.
+//
+// In addition, marker makes LI non self-collapsing. If the BFC block-offset of
+// LI isn't resolved after layout marker, we'll resolve it. See
+// |NGBlockLayoutAlgorithm::PositionOrPropagateListMarker()| and
+// |NGBlockLayoutAlgorithm::PositionListMarkerWithoutLineBoxes()| for details.
class CORE_EXPORT NGUnpositionedListMarker final {
DISALLOW_NEW();
@@ -43,36 +57,49 @@ class CORE_EXPORT NGUnpositionedListMarker final {
explicit operator bool() const { return marker_layout_object_; }
- // Add a fragment for an outside list marker.
- // Returns true if the list marker was successfully added. False indicates
+ // Returns true if the list marker can be added to box. False indicates
// that the child content does not have a baseline to align to, and that
// caller should try next child, or "WithoutLineBoxes" version.
- bool AddToBox(const NGConstraintSpace&,
+ bool CanAddToBox(const NGConstraintSpace&,
+ FontBaseline,
+ const NGPhysicalFragment& content,
+ NGLineHeightMetrics* content_metrics) const;
+ // Add a fragment for an outside list marker.
+ void AddToBox(const NGConstraintSpace&,
FontBaseline,
const NGPhysicalFragment& content,
+ const NGBoxStrut&,
+ const NGLineHeightMetrics& content_metrics,
+ const NGLayoutResult& marker_layout_result,
LogicalOffset* content_offset,
- NGBoxFragmentBuilder*,
- const NGBoxStrut&) const;
+ NGBoxFragmentBuilder*) const;
// Add a fragment for an outside list marker when the list item has no line
// boxes.
// Returns the block size of the list marker.
- LayoutUnit AddToBoxWithoutLineBoxes(const NGConstraintSpace&,
- FontBaseline,
- NGBoxFragmentBuilder*) const;
+ LayoutUnit AddToBoxWithoutLineBoxes(
+ const NGConstraintSpace&,
+ FontBaseline,
+ const NGLayoutResult& marker_layout_result,
+ NGBoxFragmentBuilder*) const;
LayoutUnit InlineOffset(const LayoutUnit marker_inline_size) const;
bool operator==(const NGUnpositionedListMarker& other) const {
return marker_layout_object_ == other.marker_layout_object_;
}
- private:
- bool IsImage() const;
-
scoped_refptr<const NGLayoutResult> Layout(
const NGConstraintSpace& parent_space,
const ComputedStyle& parent_style,
FontBaseline) const;
+
+#if DCHECK_IS_ON()
+ void CheckMargin() const;
+#endif
+
+ private:
+ bool IsImage() const;
+
LayoutUnit ComputeIntrudedFloatOffset(const NGConstraintSpace&,
const NGBoxFragmentBuilder*,
const NGBoxStrut&,
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 1a04dc32ac9..50493e523cd 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
@@ -19,39 +19,20 @@ namespace blink {
namespace {
-// Tables need special handling, unfortunately. The code in this file assumes
-// that if an element has a height or width specified, that's what its final
-// height/width will be. Tables don't follow this pattern though; they treat
-// specified height/width as a second min-height or min-width.
+// Tables require special handling. The width/height is always considered as
+// 'auto', and the value for width/height is treated as an additional
+// min-width/min-height.
bool IsTable(const ComputedStyle& style) {
return style.Display() == EDisplay::kTable ||
style.Display() == EDisplay::kInlineTable;
}
-inline Length TableAwareHeight(const ComputedStyle& style) {
- if (IsTable(style))
- return Length::Auto();
- return style.Height();
+bool IsLogicalWidthTreatedAsAuto(const ComputedStyle& style) {
+ return IsTable(style) || style.LogicalWidth().IsAuto();
}
-inline Length TableAwareWidth(const ComputedStyle& style) {
- if (IsTable(style))
- return Length::Auto();
- return style.Width();
-}
-
-bool AbsoluteHorizontalNeedsEstimate(const ComputedStyle& style) {
- const Length& width = TableAwareWidth(style);
- return width.IsIntrinsic() || style.MinWidth().IsIntrinsic() ||
- style.MaxWidth().IsIntrinsic() ||
- (width.IsAuto() && (style.Left().IsAuto() || style.Right().IsAuto()));
-}
-
-bool AbsoluteVerticalNeedsEstimate(const ComputedStyle& style) {
- const Length& height = TableAwareHeight(style);
- return height.IsIntrinsic() || style.MinHeight().IsIntrinsic() ||
- style.MaxHeight().IsIntrinsic() ||
- (height.IsAuto() && (style.Top().IsAuto() || style.Bottom().IsAuto()));
+bool IsLogicalHeightTreatAsAuto(const ComputedStyle& style) {
+ return IsTable(style) || style.LogicalHeight().IsAuto();
}
// Dominant side:
@@ -74,527 +55,230 @@ bool IsTopDominant(const WritingMode container_writing_mode,
(container_direction != TextDirection::kRtl);
}
-LayoutUnit ResolveMinWidth(const NGConstraintSpace& space,
- const ComputedStyle& style,
- const NGBoxStrut& border_padding,
- const base::Optional<MinMaxSize>& child_minmax) {
- const Length& min_width = style.MinWidth();
- if (space.GetWritingMode() == WritingMode::kHorizontalTb) {
- LayoutUnit resolved_min_width =
- ResolveMinInlineLength(space, style, border_padding, child_minmax,
- min_width, LengthResolvePhase::kLayout);
- if (!IsTable(style))
- return resolved_min_width;
- Length table_width = style.Width();
- if (table_width.IsAuto())
- return resolved_min_width;
- LayoutUnit resolved_width = ResolveMainInlineLength(
- space, style, border_padding, child_minmax, table_width);
- return std::max(resolved_min_width, resolved_width);
- }
- LayoutUnit computed_width =
- child_minmax.has_value() ? child_minmax->max_size : LayoutUnit();
- return ResolveMinBlockLength(space, style, border_padding, min_width,
- computed_width, LengthResolvePhase::kLayout);
-}
-
-LayoutUnit ResolveMaxWidth(const NGConstraintSpace& space,
- const ComputedStyle& style,
- const NGBoxStrut& border_padding,
- const base::Optional<MinMaxSize>& child_minmax,
- const Length& width) {
- if (space.GetWritingMode() == WritingMode::kHorizontalTb) {
- return ResolveMaxInlineLength(space, style, border_padding, child_minmax,
- width, LengthResolvePhase::kLayout);
- }
- LayoutUnit computed_width =
- child_minmax.has_value() ? child_minmax->max_size : LayoutUnit();
- return ResolveMaxBlockLength(space, style, border_padding, width,
- computed_width, LengthResolvePhase::kLayout);
-}
-
-LayoutUnit ResolveMainWidth(const NGConstraintSpace& space,
- const ComputedStyle& style,
- const NGBoxStrut& border_padding,
- const base::Optional<MinMaxSize>& child_minmax,
- const Length& width) {
- if (space.GetWritingMode() == WritingMode::kHorizontalTb) {
- return ResolveMainInlineLength(space, style, border_padding, child_minmax,
- width);
- }
- LayoutUnit computed_width =
- child_minmax.has_value() ? child_minmax->max_size : LayoutUnit();
- return ResolveMainBlockLength(space, style, border_padding, width,
- computed_width, LengthResolvePhase::kLayout);
+inline LayoutUnit StaticPositionStartInset(bool is_static_position_start,
+ LayoutUnit static_position_offset,
+ LayoutUnit size) {
+ return is_static_position_start ? static_position_offset
+ : static_position_offset - size;
}
-LayoutUnit ResolveMinHeight(const NGConstraintSpace& space,
- const ComputedStyle& style,
- const NGBoxStrut& border_padding,
- const base::Optional<MinMaxSize>& child_minmax) {
- const Length& min_height = style.MinHeight();
- if (space.GetWritingMode() != WritingMode::kHorizontalTb) {
- LayoutUnit resolved_min_height =
- ResolveMinInlineLength(space, style, border_padding, child_minmax,
- min_height, LengthResolvePhase::kLayout);
- if (!IsTable(style))
- return resolved_min_height;
- LayoutUnit resolved_height = ResolveMainInlineLength(
- space, style, border_padding, child_minmax, style.Height());
- return std::max(resolved_min_height, resolved_height);
- }
- LayoutUnit computed_height =
- child_minmax.has_value() ? child_minmax->max_size : LayoutUnit();
- return ResolveMinBlockLength(space, style, border_padding, min_height,
- computed_height, LengthResolvePhase::kLayout);
+inline LayoutUnit StaticPositionEndInset(bool is_static_position_start,
+ LayoutUnit static_position_offset,
+ LayoutUnit available_size,
+ LayoutUnit size) {
+ return available_size - static_position_offset -
+ (is_static_position_start ? size : LayoutUnit());
}
-LayoutUnit ResolveMaxHeight(const NGConstraintSpace& space,
- const ComputedStyle& style,
- const NGBoxStrut& border_padding,
- const base::Optional<MinMaxSize>& child_minmax,
- const Length& height) {
- if (space.GetWritingMode() != WritingMode::kHorizontalTb) {
- return ResolveMaxInlineLength(space, style, border_padding, child_minmax,
- height, LengthResolvePhase::kLayout);
+// Implement the absolute size resolution algorithm.
+// https://www.w3.org/TR/css-position-3/#abs-non-replaced-width
+// https://www.w3.org/TR/css-position-3/#abs-non-replaced-height
+void ComputeAbsoluteSize(const LayoutUnit border_padding_size,
+ const base::Optional<MinMaxSize>& child_minmax,
+ const LayoutUnit margin_percentage_resolution_size,
+ const LayoutUnit available_size,
+ const Length& margin_start_length,
+ const Length& margin_end_length,
+ const Length& inset_start_length,
+ const Length& inset_end_length,
+ const LayoutUnit min_size,
+ const LayoutUnit max_size,
+ const LayoutUnit static_position_offset,
+ bool is_static_position_start,
+ bool is_start_dominant,
+ bool is_block_direction,
+ base::Optional<LayoutUnit> size,
+ LayoutUnit* size_out,
+ LayoutUnit* inset_start_out,
+ LayoutUnit* inset_end_out,
+ LayoutUnit* margin_start_out,
+ LayoutUnit* margin_end_out) {
+ DCHECK_NE(available_size, kIndefiniteSize);
+
+ base::Optional<LayoutUnit> margin_start;
+ if (!margin_start_length.IsAuto()) {
+ margin_start = MinimumValueForLength(margin_start_length,
+ margin_percentage_resolution_size);
}
- LayoutUnit computed_height =
- child_minmax.has_value() ? child_minmax->max_size : LayoutUnit();
- return ResolveMaxBlockLength(space, style, border_padding, height,
- computed_height, LengthResolvePhase::kLayout);
-}
-
-LayoutUnit ResolveMainHeight(const NGConstraintSpace& space,
- const ComputedStyle& style,
- const NGBoxStrut& border_padding,
- const base::Optional<MinMaxSize>& child_minmax,
- const Length& height) {
- if (space.GetWritingMode() != WritingMode::kHorizontalTb) {
- return ResolveMainInlineLength(space, style, border_padding, child_minmax,
- height);
+ base::Optional<LayoutUnit> margin_end;
+ if (!margin_end_length.IsAuto()) {
+ margin_end = MinimumValueForLength(margin_end_length,
+ margin_percentage_resolution_size);
}
- LayoutUnit computed_height =
- child_minmax.has_value() ? child_minmax->max_size : LayoutUnit();
- return ResolveMainBlockLength(space, style, border_padding, height,
- computed_height, LengthResolvePhase::kLayout);
-}
-
-inline LayoutUnit ResolveMargin(const NGConstraintSpace& space,
- const Length& length) {
- DCHECK(!length.IsAuto());
- return MinimumValueForLength(
- length, space.PercentageResolutionInlineSizeForParentWritingMode());
-}
-
-// Available size can is maximum length Element can have without overflowing
-// container bounds. The position of Element's edges will determine
-// how much space there is available.
-LayoutUnit ComputeAvailableWidth(LayoutUnit container_width,
- const base::Optional<LayoutUnit>& left,
- const base::Optional<LayoutUnit>& right,
- const base::Optional<LayoutUnit>& margin_left,
- const base::Optional<LayoutUnit>& margin_right,
- const NGStaticPosition& static_position) {
- LayoutUnit available_width = container_width;
- DCHECK(!left || !right);
- if (!left && !right) {
- if (static_position.HasLeft())
- available_width -= static_position.Left();
- else
- available_width = static_position.Right();
- } else if (!right) {
- available_width -= *left;
- } else { // !left
- available_width -= *right;
+ base::Optional<LayoutUnit> inset_start;
+ if (!inset_start_length.IsAuto()) {
+ inset_start = MinimumValueForLength(inset_start_length, available_size);
}
- LayoutUnit margins = (margin_left ? *margin_left : LayoutUnit()) +
- (margin_right ? *margin_right : LayoutUnit());
- return (available_width - margins).ClampNegativeToZero();
-}
-
-LayoutUnit ComputeAvailableHeight(
- LayoutUnit container_height,
- const base::Optional<LayoutUnit>& top,
- const base::Optional<LayoutUnit>& bottom,
- const base::Optional<LayoutUnit>& margin_top,
- const base::Optional<LayoutUnit>& margin_bottom,
- const NGStaticPosition& static_position) {
- LayoutUnit available_height = container_height;
- DCHECK(!top || !bottom);
- if (!top && !bottom) {
- if (static_position.HasTop())
- available_height -= static_position.Top();
- else
- available_height = static_position.Bottom();
- } else if (!bottom) {
- available_height -= *top;
- } else { // !top
- available_height -= *bottom;
+ base::Optional<LayoutUnit> inset_end;
+ if (!inset_end_length.IsAuto()) {
+ inset_end = MinimumValueForLength(inset_end_length, available_size);
}
- LayoutUnit margins = (margin_top ? *margin_top : LayoutUnit()) +
- (margin_bottom ? *margin_bottom : LayoutUnit());
- return (available_height - margins).ClampNegativeToZero();
-}
-
-// Implement absolute horizontal size resolution algorithm.
-// https://www.w3.org/TR/css-position-3/#abs-non-replaced-width
-void ComputeAbsoluteHorizontal(const NGConstraintSpace& space,
- const ComputedStyle& style,
- const NGBoxStrut& border_padding,
- const base::Optional<LayoutUnit>& incoming_width,
- const NGStaticPosition& static_position,
- const base::Optional<MinMaxSize>& child_minmax,
- const WritingMode container_writing_mode,
- const TextDirection container_direction,
- NGAbsolutePhysicalPosition* position) {
- LayoutUnit percentage_width =
- LIKELY(space.GetWritingMode() == WritingMode::kHorizontalTb)
- ? space.PercentageResolutionInlineSize()
- : space.PercentageResolutionBlockSize();
-
- base::Optional<LayoutUnit> margin_left;
- if (!style.MarginLeft().IsAuto())
- margin_left = ResolveMargin(space, style.MarginLeft());
- base::Optional<LayoutUnit> margin_right;
- if (!style.MarginRight().IsAuto())
- margin_right = ResolveMargin(space, style.MarginRight());
- base::Optional<LayoutUnit> left;
- if (!style.Left().IsAuto())
- left = MinimumValueForLength(style.Left(), percentage_width);
- base::Optional<LayoutUnit> right;
- if (!style.Right().IsAuto())
- right = MinimumValueForLength(style.Right(), percentage_width);
- base::Optional<LayoutUnit> width = incoming_width;
- PhysicalSize container_size =
- ToPhysicalSize(space.AvailableSize(), space.GetWritingMode());
- DCHECK_NE(container_size.width, kIndefiniteSize);
// Solving the equation:
- // left + marginLeft + width + marginRight + right = container width
- if (!left && !right && !width) {
- // Standard: "If all three of left, width, and right are auto:"
- if (!margin_left)
- margin_left = LayoutUnit();
- if (!margin_right)
- margin_right = LayoutUnit();
+ // |inset_start| + |margin_start| + |size| + |margin_end| + |inset_end| =
+ // |available_size|
+ if (!inset_start && !inset_end && !size) {
+ // "If all three of left, width, and right are auto:"
+ if (!margin_start)
+ margin_start = LayoutUnit();
+ if (!margin_end)
+ margin_end = LayoutUnit();
DCHECK(child_minmax.has_value());
- width = child_minmax->ShrinkToFit(
- ComputeAvailableWidth(container_size.width, left, right, margin_left,
- margin_right, static_position));
- if (IsLeftDominant(container_writing_mode, container_direction)) {
- left = static_position.LeftInset(container_size.width, *width,
- *margin_left, *margin_right);
+ LayoutUnit computed_available_size =
+ is_static_position_start ? available_size - static_position_offset
+ : static_position_offset;
+ size = child_minmax->ShrinkToFit(
+ (computed_available_size - *margin_start - *margin_end)
+ .ClampNegativeToZero());
+ LayoutUnit margin_size = *size + *margin_start + *margin_end;
+ if (is_start_dominant) {
+ inset_start = StaticPositionStartInset(
+ is_static_position_start, static_position_offset, margin_size);
} else {
- right = static_position.RightInset(container_size.width, *width,
- *margin_left, *margin_right);
+ inset_end = StaticPositionEndInset(is_static_position_start,
+ static_position_offset, available_size,
+ margin_size);
}
- } else if (left && right && width) {
- // Standard: "If left, right, and width are not auto:"
+ } else if (inset_start && inset_end && size) {
+ // "If left, right, and width are not auto:"
// Compute margins.
- LayoutUnit margin_space = container_size.width - *left - *right - *width;
- // When both margins are auto.
- if (!margin_left && !margin_right) {
- if (margin_space > 0) {
- margin_left = margin_space / 2;
- margin_right = margin_space - *margin_left;
+ LayoutUnit margin_space =
+ available_size - *inset_start - *inset_end - *size;
+ if (!margin_start && !margin_end) {
+ // When both margins are auto.
+ if (margin_space > 0 || is_block_direction) {
+ margin_start = margin_space / 2;
+ margin_end = margin_space - *margin_start;
} else {
// Margins are negative.
- if (IsLeftDominant(container_writing_mode, container_direction)) {
- margin_left = LayoutUnit();
- margin_right = margin_space;
+ if (is_start_dominant) {
+ margin_start = LayoutUnit();
+ margin_end = margin_space;
} else {
- margin_right = LayoutUnit();
- margin_left = margin_space;
+ margin_start = margin_space;
+ margin_end = LayoutUnit();
}
}
- } else if (!margin_left) {
- margin_left = margin_space - *margin_right;
- } else if (!margin_right) {
- margin_right = margin_space - *margin_left;
+ } else if (!margin_start) {
+ margin_start = margin_space - *margin_end;
+ } else if (!margin_end) {
+ margin_end = margin_space - *margin_start;
} else {
- // Are values overconstrained?
- LayoutUnit margin_extra = margin_space - *margin_left - *margin_right;
+ // Are the values over-constrained?
+ LayoutUnit margin_extra = margin_space - *margin_start - *margin_end;
if (margin_extra) {
// Relax the end.
- if (IsLeftDominant(container_writing_mode, container_direction))
- right = *right + margin_extra;
+ if (is_start_dominant)
+ inset_end = *inset_end + margin_extra;
else
- left = *left + margin_extra;
+ inset_start = *inset_start + margin_extra;
}
}
}
- // Set unknown margins.
- if (!margin_left)
- margin_left = LayoutUnit();
- if (!margin_right)
- margin_right = LayoutUnit();
+ // Set any unknown margins.
+ if (!margin_start)
+ margin_start = LayoutUnit();
+ if (!margin_end)
+ margin_end = LayoutUnit();
- // Rules 1 through 3, 2 out of 3 are unknown.
- if (!left && !width) {
+ // Rules 1 through 3: 2 out of 3 are unknown.
+ if (!inset_start && !size) {
// Rule 1: left/width are unknown.
- DCHECK(right.has_value());
+ DCHECK(inset_end.has_value());
DCHECK(child_minmax.has_value());
- width = child_minmax->ShrinkToFit(
- ComputeAvailableWidth(container_size.width, left, right, margin_left,
- margin_right, static_position));
- } else if (!left && !right) {
+ LayoutUnit computed_available_size = available_size - *inset_end;
+ size = child_minmax->ShrinkToFit(
+ (computed_available_size - *margin_start - *margin_end)
+ .ClampNegativeToZero());
+ } else if (!inset_start && !inset_end) {
// Rule 2.
- DCHECK(width.has_value());
- if (IsLeftDominant(container_writing_mode, container_direction))
- left = static_position.LeftInset(container_size.width, *width,
- *margin_left, *margin_right);
- else
- right = static_position.RightInset(container_size.width, *width,
- *margin_left, *margin_right);
- } else if (!width && !right) {
- // Rule 3.
- DCHECK(child_minmax.has_value());
- width = child_minmax->ShrinkToFit(
- ComputeAvailableWidth(container_size.width, left, right, margin_left,
- margin_right, static_position));
- }
-
- // Rules 4 through 6, 1 out of 3 are unknown.
- if (!left) {
- left =
- container_size.width - *width - *right - *margin_left - *margin_right;
- } else if (!right) {
- right =
- container_size.width - *width - *left - *margin_left - *margin_right;
- } else if (!width) {
- width =
- container_size.width - *left - *right - *margin_left - *margin_right;
- }
-
-#if DCHECK_IS_ON()
- // The DCHECK is useful, but only holds true when not saturated.
- if (!(left->MightBeSaturated() || right->MightBeSaturated() ||
- width->MightBeSaturated() || margin_left->MightBeSaturated() ||
- margin_right->MightBeSaturated() ||
- container_size.width.MightBeSaturated())) {
- DCHECK_EQ(container_size.width,
- *left + *right + *margin_left + *margin_right + *width);
- }
-#endif // #if DCHECK_IS_ON()
-
- // If calculated width is outside of min/max constraints,
- // rerun the algorithm with constrained width.
- LayoutUnit min = ResolveMinWidth(space, style, border_padding, child_minmax);
- LayoutUnit max = ResolveMaxWidth(space, style, border_padding, child_minmax,
- style.MaxWidth());
- LayoutUnit constrained_width = ConstrainByMinMax(*width, min, max);
- if (width != constrained_width) {
- width = constrained_width;
- // Because this function only changes "width" when it's not already
- // set, it is safe to recursively call ourselves here because on the
- // second call it is guaranteed to be within min..max.
- ComputeAbsoluteHorizontal(
- space, style, border_padding, width, static_position, child_minmax,
- container_writing_mode, container_direction, position);
- return;
- }
-
- // Negative widths are not allowed.
- LayoutUnit horizontal_border_padding =
- border_padding
- .ConvertToPhysical(space.GetWritingMode(), space.Direction())
- .HorizontalSum();
- width = std::max(*width, horizontal_border_padding);
-
- position->inset.left = *left + *margin_left;
- position->inset.right = *right + *margin_right;
- position->margins.left = *margin_left;
- position->margins.right = *margin_right;
- position->size.width = *width;
-}
-
-// Implements absolute vertical size resolution algorithm.
-// https://www.w3.org/TR/css-position-3/#abs-non-replaced-height
-void ComputeAbsoluteVertical(const NGConstraintSpace& space,
- const ComputedStyle& style,
- const NGBoxStrut& border_padding,
- const base::Optional<LayoutUnit>& incoming_height,
- const NGStaticPosition& static_position,
- const base::Optional<MinMaxSize>& child_minmax,
- const WritingMode container_writing_mode,
- const TextDirection container_direction,
- NGAbsolutePhysicalPosition* position) {
- LayoutUnit percentage_height =
- LIKELY(space.GetWritingMode() == WritingMode::kHorizontalTb)
- ? space.PercentageResolutionBlockSize()
- : space.PercentageResolutionInlineSize();
-
- base::Optional<LayoutUnit> margin_top;
- if (!style.MarginTop().IsAuto())
- margin_top = ResolveMargin(space, style.MarginTop());
- base::Optional<LayoutUnit> margin_bottom;
- if (!style.MarginBottom().IsAuto())
- margin_bottom = ResolveMargin(space, style.MarginBottom());
- base::Optional<LayoutUnit> top;
- if (!style.Top().IsAuto())
- top = MinimumValueForLength(style.Top(), percentage_height);
- base::Optional<LayoutUnit> bottom;
- if (!style.Bottom().IsAuto())
- bottom = MinimumValueForLength(style.Bottom(), percentage_height);
- base::Optional<LayoutUnit> height = incoming_height;
-
- PhysicalSize container_size =
- ToPhysicalSize(space.AvailableSize(), space.GetWritingMode());
- DCHECK_NE(container_size.height, kIndefiniteSize);
-
- // Solving the equation:
- // top + marginTop + height + marginBottom + bottom
- // + border_padding = container height
- if (!top && !bottom && !height) {
- // Standard: "If all three of top, height, and bottom are auto:"
- if (!margin_top)
- margin_top = LayoutUnit();
- if (!margin_bottom)
- margin_bottom = LayoutUnit();
- DCHECK(child_minmax.has_value());
- height = child_minmax->ShrinkToFit(
- ComputeAvailableHeight(container_size.height, top, bottom, margin_top,
- margin_bottom, static_position));
- if (IsTopDominant(container_writing_mode, container_direction)) {
- top = static_position.TopInset(container_size.height, *height,
- *margin_top, *margin_bottom);
- } else {
- bottom = static_position.BottomInset(container_size.height, *height,
- *margin_top, *margin_bottom);
- }
- } else if (top && bottom && height) {
- // Standard: "If top, bottom, and height are not auto:"
- // Compute margins.
- LayoutUnit margin_space = container_size.height - *top - *bottom - *height;
- if (!margin_top && !margin_bottom) {
- // When both margins are auto.
- margin_top = margin_space / 2;
- margin_bottom = margin_space - *margin_top;
- } else if (!margin_top) {
- margin_top = margin_space - *margin_bottom;
- } else if (!margin_bottom) {
- margin_bottom = margin_space - *margin_top;
- } else {
- // Since none of the margins are auto (and we have non-auto top, bottom
- // and height), we are over-constrained. Keep the dominant inset and
- // override the other.
- LayoutUnit margin_extra = margin_space - *margin_top - *margin_bottom;
- if (margin_extra) {
- if (IsTopDominant(container_writing_mode, container_direction))
- bottom = *bottom + margin_extra;
- else
- top = *top + margin_extra;
- }
- }
- }
-
- // Set unknown margins.
- if (!margin_top)
- margin_top = LayoutUnit();
- if (!margin_bottom)
- margin_bottom = LayoutUnit();
-
- // Rules 1 through 3, 2 out of 3 are unknown, fix 1.
- if (!top && !height) {
- // Rule 1.
- DCHECK(bottom.has_value());
- DCHECK(child_minmax.has_value());
- height = child_minmax->ShrinkToFit(
- ComputeAvailableHeight(container_size.height, top, bottom, margin_top,
- margin_bottom, static_position));
- } else if (!top && !bottom) {
- // Rule 2.
- DCHECK(height.has_value());
- if (IsTopDominant(container_writing_mode, container_direction)) {
- top = static_position.TopInset(container_size.height, *height,
- *margin_top, *margin_bottom);
+ DCHECK(size.has_value());
+ LayoutUnit margin_size = *size + *margin_start + *margin_end;
+ if (is_start_dominant) {
+ inset_start = StaticPositionStartInset(
+ is_static_position_start, static_position_offset, margin_size);
} else {
- bottom = static_position.BottomInset(container_size.height, *height,
- *margin_top, *margin_bottom);
+ inset_end = StaticPositionEndInset(is_static_position_start,
+ static_position_offset, available_size,
+ margin_size);
}
- } else if (!height && !bottom) {
+ } else if (!size && !inset_end) {
// Rule 3.
DCHECK(child_minmax.has_value());
- height = child_minmax->ShrinkToFit(
- ComputeAvailableHeight(container_size.height, top, bottom, margin_top,
- margin_bottom, static_position));
+ LayoutUnit computed_available_size = available_size - *inset_start;
+ size = child_minmax->ShrinkToFit(
+ (computed_available_size - *margin_start - *margin_end)
+ .ClampNegativeToZero());
}
- // Rules 4 through 6, 1 out of 3 are unknown.
- if (!top) {
- top = container_size.height - *height - *bottom - *margin_top -
- *margin_bottom;
- } else if (!bottom) {
- bottom =
- container_size.height - *height - *top - *margin_top - *margin_bottom;
- } else if (!height) {
- height =
- container_size.height - *top - *bottom - *margin_top - *margin_bottom;
+ // Rules 4 through 6: 1 out of 3 are unknown.
+ if (!inset_start) {
+ inset_start =
+ available_size - *size - *inset_end - *margin_start - *margin_end;
+ } else if (!inset_end) {
+ inset_end =
+ available_size - *size - *inset_start - *margin_start - *margin_end;
+ } else if (!size) {
+ size = available_size - *inset_start - *inset_end - *margin_start -
+ *margin_end;
}
#if DCHECK_IS_ON()
- // The DCHECK is useful, but only holds true when not saturated.
- if (!(top->MightBeSaturated() || bottom->MightBeSaturated() ||
- height->MightBeSaturated() || margin_top->MightBeSaturated() ||
- margin_bottom->MightBeSaturated() ||
- container_size.height.MightBeSaturated())) {
- DCHECK_EQ(container_size.height,
- *top + *bottom + *margin_top + *margin_bottom + *height);
+ // The DCHECK is useful, but only holds true if the values aren't saturated.
+ if (!inset_start->MightBeSaturated() && !inset_end->MightBeSaturated() &&
+ !size->MightBeSaturated() && !margin_start->MightBeSaturated() &&
+ !margin_end->MightBeSaturated() && !available_size.MightBeSaturated()) {
+ DCHECK_EQ(available_size,
+ *inset_start + *inset_end + *margin_start + *margin_end + *size);
}
#endif // #if DCHECK_IS_ON()
- // If calculated height is outside of min/max constraints,
- // rerun the algorithm with constrained width.
- LayoutUnit min = ResolveMinHeight(space, style, border_padding, child_minmax);
- LayoutUnit max = ResolveMaxHeight(space, style, border_padding, child_minmax,
- style.MaxHeight());
- if (height != ConstrainByMinMax(*height, min, max)) {
- height = ConstrainByMinMax(*height, min, max);
- // Because this function only changes "height" when it's not already
- // set, it is safe to recursively call ourselves here because on the
- // second call it is guaranteed to be within min..max.
- ComputeAbsoluteVertical(
- space, style, border_padding, height, static_position, child_minmax,
- container_writing_mode, container_direction, position);
+ // If calculated |size| is outside of min/max constraints, rerun the
+ // algorithm with the constrained |size|.
+ LayoutUnit constrained_size = ConstrainByMinMax(*size, min_size, max_size);
+ if (size != constrained_size) {
+ // Because this function only changes "size" when it's not already set, it
+ // is safe to recursively call ourselves here because on the second call it
+ // is guaranteed to be within |min_size| and |max_size|.
+ ComputeAbsoluteSize(
+ border_padding_size, child_minmax, margin_percentage_resolution_size,
+ available_size, margin_start_length, margin_end_length,
+ inset_start_length, inset_end_length, min_size, max_size,
+ static_position_offset, is_static_position_start, is_start_dominant,
+ is_block_direction, constrained_size, size_out, inset_start_out,
+ inset_end_out, margin_start_out, margin_end_out);
return;
}
- // Negative heights are not allowed.
- LayoutUnit vertical_border_padding =
- border_padding
- .ConvertToPhysical(space.GetWritingMode(), space.Direction())
- .VerticalSum();
- height = std::max(*height, vertical_border_padding);
-
- position->inset.top = *top + *margin_top;
- position->inset.bottom = *bottom + *margin_bottom;
- position->margins.top = *margin_top;
- position->margins.bottom = *margin_bottom;
- position->size.height = *height;
+
+ // Negative sizes are not allowed.
+ *size_out = std::max(*size, border_padding_size);
+ *inset_start_out = *inset_start + *margin_start;
+ *inset_end_out = *inset_end + *margin_end;
+ *margin_start_out = *margin_start;
+ *margin_end_out = *margin_end;
}
} // namespace
-String NGAbsolutePhysicalPosition::ToString() const {
- return String::Format("INSET(LRTB):%d,%d,%d,%d SIZE:%dx%d",
- inset.left.ToInt(), inset.right.ToInt(),
- inset.top.ToInt(), inset.bottom.ToInt(),
- size.width.ToInt(), size.height.ToInt());
+bool AbsoluteNeedsChildInlineSize(const ComputedStyle& style) {
+ bool is_logical_width_intrinsic =
+ !IsTable(style) && style.LogicalWidth().IsIntrinsic();
+ return is_logical_width_intrinsic || style.LogicalMinWidth().IsIntrinsic() ||
+ style.LogicalMaxWidth().IsIntrinsic() ||
+ (IsLogicalWidthTreatedAsAuto(style) &&
+ (style.LogicalLeft().IsAuto() || style.LogicalRight().IsAuto()));
}
bool AbsoluteNeedsChildBlockSize(const ComputedStyle& style) {
- if (style.IsHorizontalWritingMode())
- return AbsoluteVerticalNeedsEstimate(style);
- else
- return AbsoluteHorizontalNeedsEstimate(style);
-}
-
-bool AbsoluteNeedsChildInlineSize(const ComputedStyle& style) {
- if (style.IsHorizontalWritingMode())
- return AbsoluteHorizontalNeedsEstimate(style);
- else
- return AbsoluteVerticalNeedsEstimate(style);
+ bool is_logical_height_intrinsic =
+ !IsTable(style) && style.LogicalHeight().IsIntrinsic();
+ return is_logical_height_intrinsic ||
+ style.LogicalMinHeight().IsIntrinsic() ||
+ style.LogicalMaxHeight().IsIntrinsic() ||
+ (IsLogicalHeightTreatAsAuto(style) &&
+ (style.LogicalTop().IsAuto() || style.LogicalBottom().IsAuto()));
}
base::Optional<LayoutUnit> ComputeAbsoluteDialogYPosition(
@@ -603,8 +287,8 @@ base::Optional<LayoutUnit> ComputeAbsoluteDialogYPosition(
if (!IsHTMLDialogElement(dialog.GetNode()))
return base::nullopt;
- // This code implements <dialog> static position spec.
- // //
+ // This code implements <dialog> static-position spec.
+ //
// https://html.spec.whatwg.org/C/#the-dialog-element
HTMLDialogElement* dialog_node = ToHTMLDialogElement(dialog.GetNode());
if (dialog_node->GetCenteringMode() == HTMLDialogElement::kNotCentered)
@@ -641,39 +325,64 @@ base::Optional<LayoutUnit> ComputeAbsoluteDialogYPosition(
return top;
}
-NGAbsolutePhysicalPosition ComputePartialAbsoluteWithChildInlineSize(
+NGLogicalOutOfFlowPosition ComputePartialAbsoluteWithChildInlineSize(
const NGConstraintSpace& space,
const ComputedStyle& style,
const NGBoxStrut& border_padding,
- const NGStaticPosition& static_position,
+ const NGLogicalStaticPosition& static_position,
const base::Optional<MinMaxSize>& child_minmax,
const base::Optional<LogicalSize>& replaced_size,
const WritingMode container_writing_mode,
const TextDirection container_direction) {
- NGAbsolutePhysicalPosition position;
- if (style.IsHorizontalWritingMode()) {
- base::Optional<LayoutUnit> width;
- if (!TableAwareWidth(style).IsAuto()) {
- width = ResolveMainWidth(space, style, border_padding, child_minmax,
- style.Width());
- } else if (replaced_size.has_value()) {
- width = replaced_size->inline_size;
- }
- ComputeAbsoluteHorizontal(
- space, style, border_padding, width, static_position, child_minmax,
- container_writing_mode, container_direction, &position);
+ NGLogicalOutOfFlowPosition position;
+
+ base::Optional<LayoutUnit> inline_size;
+ if (!IsLogicalWidthTreatedAsAuto(style)) {
+ inline_size = ResolveMainInlineLength(space, style, border_padding,
+ child_minmax, style.LogicalWidth());
+ } else if (replaced_size.has_value()) {
+ inline_size = replaced_size->inline_size;
+ }
+
+ LayoutUnit min_inline_size = ResolveMinInlineLength(
+ space, style, border_padding, child_minmax, style.LogicalMinWidth(),
+ LengthResolvePhase::kLayout);
+ LayoutUnit max_inline_size = ResolveMaxInlineLength(
+ space, style, border_padding, child_minmax, style.LogicalMaxWidth(),
+ LengthResolvePhase::kLayout);
+
+ // Tables use the inline-size as a minimum.
+ if (IsTable(style) && !style.LogicalWidth().IsAuto()) {
+ min_inline_size =
+ std::max(min_inline_size,
+ ResolveMainInlineLength(space, style, border_padding,
+ child_minmax, style.LogicalWidth()));
+ }
+
+ bool is_start_dominant;
+ if (style.GetWritingMode() == WritingMode::kHorizontalTb) {
+ is_start_dominant =
+ IsLeftDominant(container_writing_mode, container_direction) ==
+ IsLeftDominant(style.GetWritingMode(), style.Direction());
} else {
- base::Optional<LayoutUnit> height;
- if (!TableAwareHeight(style).IsAuto()) {
- height = ResolveMainHeight(space, style, border_padding, child_minmax,
- style.Height());
- } else if (replaced_size.has_value()) {
- height = replaced_size->inline_size;
- }
- ComputeAbsoluteVertical(
- space, style, border_padding, height, static_position, child_minmax,
- container_writing_mode, container_direction, &position);
+ is_start_dominant =
+ IsTopDominant(container_writing_mode, container_direction) ==
+ IsTopDominant(style.GetWritingMode(), style.Direction());
}
+
+ ComputeAbsoluteSize(
+ border_padding.InlineSum(), child_minmax,
+ space.PercentageResolutionInlineSizeForParentWritingMode(),
+ space.AvailableSize().inline_size, style.MarginStart(), style.MarginEnd(),
+ style.LogicalInlineStart(), style.LogicalInlineEnd(), min_inline_size,
+ max_inline_size, static_position.offset.inline_offset,
+ static_position.inline_edge ==
+ NGLogicalStaticPosition::InlineEdge::kInlineStart,
+ is_start_dominant, false /* is_block_direction */, inline_size,
+ &position.size.inline_size, &position.inset.inline_start,
+ &position.inset.inline_end, &position.margins.inline_start,
+ &position.margins.inline_end);
+
return position;
}
@@ -681,43 +390,62 @@ void ComputeFullAbsoluteWithChildBlockSize(
const NGConstraintSpace& space,
const ComputedStyle& style,
const NGBoxStrut& border_padding,
- const NGStaticPosition& static_position,
+ const NGLogicalStaticPosition& static_position,
const base::Optional<LayoutUnit>& child_block_size,
const base::Optional<LogicalSize>& replaced_size,
const WritingMode container_writing_mode,
const TextDirection container_direction,
- NGAbsolutePhysicalPosition* position) {
- // After partial size has been computed, child block size is either
- // unknown, or fully computed, there is no minmax.
- // To express this, a 'fixed' minmax is created where
- // min and max are the same.
+ NGLogicalOutOfFlowPosition* position) {
+ // After partial size has been computed, child block size is either unknown,
+ // or fully computed, there is no minmax. To express this, a 'fixed' minmax
+ // is created where min and max are the same.
base::Optional<MinMaxSize> child_minmax;
if (child_block_size.has_value()) {
child_minmax = MinMaxSize{*child_block_size, *child_block_size};
}
- if (style.IsHorizontalWritingMode()) {
- base::Optional<LayoutUnit> height;
- if (!TableAwareHeight(style).IsAuto()) {
- height = ResolveMainHeight(space, style, border_padding, child_minmax,
- style.Height());
- } else if (replaced_size.has_value()) {
- height = replaced_size->block_size;
- }
- ComputeAbsoluteVertical(
- space, style, border_padding, height, static_position, child_minmax,
- container_writing_mode, container_direction, position);
+
+ LayoutUnit child_block_size_or_indefinite =
+ child_block_size.value_or(kIndefiniteSize);
+
+ base::Optional<LayoutUnit> block_size;
+ if (!IsLogicalHeightTreatAsAuto(style)) {
+ block_size = ResolveMainBlockLength(
+ space, style, border_padding, style.LogicalHeight(),
+ child_block_size_or_indefinite, LengthResolvePhase::kLayout);
+ } else if (replaced_size.has_value()) {
+ block_size = replaced_size->block_size;
+ }
+
+ LayoutUnit min_block_size = ResolveMinBlockLength(
+ space, style, border_padding, style.LogicalMinHeight(),
+ child_block_size_or_indefinite, LengthResolvePhase::kLayout);
+ LayoutUnit max_block_size = ResolveMaxBlockLength(
+ space, style, border_padding, style.LogicalMaxHeight(),
+ child_block_size_or_indefinite, LengthResolvePhase::kLayout);
+
+ bool is_start_dominant;
+ if (style.GetWritingMode() == WritingMode::kHorizontalTb) {
+ is_start_dominant =
+ IsTopDominant(container_writing_mode, container_direction) ==
+ IsTopDominant(style.GetWritingMode(), style.Direction());
} else {
- base::Optional<LayoutUnit> width;
- if (!TableAwareWidth(style).IsAuto()) {
- width = ResolveMainWidth(space, style, border_padding, child_minmax,
- style.Width());
- } else if (replaced_size.has_value()) {
- width = replaced_size->block_size;
- }
- ComputeAbsoluteHorizontal(
- space, style, border_padding, width, static_position, child_minmax,
- container_writing_mode, container_direction, position);
+ is_start_dominant =
+ IsLeftDominant(container_writing_mode, container_direction) ==
+ IsLeftDominant(style.GetWritingMode(), style.Direction());
}
+
+ ComputeAbsoluteSize(
+ border_padding.BlockSum(), child_minmax,
+ space.PercentageResolutionInlineSizeForParentWritingMode(),
+ space.AvailableSize().block_size, style.MarginBefore(),
+ style.MarginAfter(), style.LogicalTop(), style.LogicalBottom(),
+ min_block_size, max_block_size, static_position.offset.block_offset,
+ static_position.block_edge ==
+ NGLogicalStaticPosition::BlockEdge::kBlockStart,
+ is_start_dominant, true /* is_block_direction */, block_size,
+ &position->size.block_size, &position->inset.block_start,
+ &position->inset.block_end, &position->margins.block_start,
+ &position->margins.block_end);
}
} // namespace blink
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 67029cd9917..f6d237aa201 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
@@ -17,69 +17,71 @@ namespace blink {
class ComputedStyle;
class LayoutObject;
class NGConstraintSpace;
-struct NGStaticPosition;
+struct NGLogicalStaticPosition;
-struct CORE_EXPORT NGAbsolutePhysicalPosition {
- NGPhysicalBoxStrut inset;
- PhysicalSize size;
- NGPhysicalBoxStrut margins;
- String ToString() const;
+struct CORE_EXPORT NGLogicalOutOfFlowPosition {
+ NGBoxStrut inset;
+ LogicalSize size;
+ NGBoxStrut margins;
};
-// Implements <dialog> special case abspos static positining.
-// Returns new dialog top position if layout_dialog requires
-// <dialog> abspos centering.
+// Implements <dialog> static positioning.
+//
+// Returns new dialog top position if layout_dialog requires <dialog>
+// OOF-positioned centering.
CORE_EXPORT base::Optional<LayoutUnit> ComputeAbsoluteDialogYPosition(
const LayoutObject& layout_dialog,
LayoutUnit height);
-// The following routines implement absolute size resolution algorithm.
+// The following routines implement the absolute size resolution algorithm.
// https://www.w3.org/TR/css-position-3/#abs-non-replaced-width
//
-// The size is computed as NGAbsolutePhysicalPosition.
+// The size is computed as |NGLogicalOutOfFlowPosition|.
// It needs to be computed in 4 stages:
-// 1. If AbsoluteNeedsChildInlineSize compute estimated inline_size using
-// MinMaxSize.ShrinkToFit.
-// 2. Compute part of PhysicalPosition that depends upon child inline size
-// with ComputePartialAbsoluteWithChildInlineSize.
-// 3. If AbsoluteNeedsChildBlockSize compute estimated block_size by
+// 1. If |AbsoluteNeedsChildInlineSize| is true, compute estimated inline_size
+// using |NGBlockNode::MinMaxSize|.
+// 2. Compute part of the |NGLogicalOutOfFlowPosition| which depends on the
+// child inline-size with |ComputePartialAbsoluteWithChildInlineSize|.
+// 3. If |AbsoluteNeedsChildBlockSize| is true, compute estimated block_size by
// performing layout with the inline_size calculated from (2).
-// 4. Compute full PhysicalPosition by filling it in with parts that depend
-// upon child's block_size.
+// 4. Compute the full |NGLogicalOutOfFlowPosition| with
+// |ComputeFullAbsoluteWithChildBlockSize|.
-// True if ComputePartialAbsoluteWithChildInlineSize will need
-// estimated inline size.
+// Returns true if |ComputePartialAbsoluteWithChildInlineSize| will need an
+// estimated inline-size.
CORE_EXPORT bool AbsoluteNeedsChildInlineSize(const ComputedStyle&);
-// True if ComputeFullAbsoluteWithChildBlockSize will need
-// estimated block size.
+// Returns true if |ComputeFullAbsoluteWithChildBlockSize| will need an
+// estimated block-size.
CORE_EXPORT bool AbsoluteNeedsChildBlockSize(const ComputedStyle&);
-// Compute part of position that depends on child's inline_size.
-// replaced_size should be set if and only if element is replaced element.
-// Returns partially filled position.
-CORE_EXPORT NGAbsolutePhysicalPosition
+// Computes part of the absolute position which depends on the child's
+// inline-size.
+// |replaced_size| should be set if and only if element is replaced element.
+// Returns the partially filled position.
+CORE_EXPORT NGLogicalOutOfFlowPosition
ComputePartialAbsoluteWithChildInlineSize(
const NGConstraintSpace&,
const ComputedStyle&,
const NGBoxStrut& border_padding,
- const NGStaticPosition&,
+ const NGLogicalStaticPosition&,
const base::Optional<MinMaxSize>& child_minmax,
const base::Optional<LogicalSize>& replaced_size,
const WritingMode container_writing_mode,
const TextDirection container_direction);
-// Compute rest of PhysicalRect that depends on child's block_size.
+// Computes the rest of the absolute position which depends on child's
+// block-size.
CORE_EXPORT void ComputeFullAbsoluteWithChildBlockSize(
const NGConstraintSpace&,
const ComputedStyle&,
const NGBoxStrut& border_padding,
- const NGStaticPosition&,
+ const NGLogicalStaticPosition&,
const base::Optional<LayoutUnit>& child_block_size,
const base::Optional<LogicalSize>& replaced_size,
const WritingMode container_writing_mode,
const TextDirection container_direction,
- NGAbsolutePhysicalPosition* position);
+ NGLogicalOutOfFlowPosition* position);
} // 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 20c8a4a4a50..52d1557a553 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
@@ -141,16 +141,20 @@ TEST_F(NGAbsoluteUtilsTest, Horizontal) {
NGBoxStrut vrl_border_padding =
ComputeBordersForTest(*style_) + ComputePadding(vrl_space_, *style_);
- NGStaticPosition static_position{NGStaticPosition::kTopLeft,
- {LayoutUnit(), LayoutUnit()}};
- // Same as regular static position, but with right edge.
- NGStaticPosition static_right_position{NGStaticPosition::kTopRight,
- {LayoutUnit(), LayoutUnit()}};
+ NGLogicalStaticPosition static_position = {
+ {LayoutUnit(), LayoutUnit()},
+ NGLogicalStaticPosition::kInlineStart,
+ NGLogicalStaticPosition::kBlockStart};
+ // Same as regular static position, but with the inline-end edge.
+ NGLogicalStaticPosition static_position_inline_end = {
+ {LayoutUnit(), LayoutUnit()},
+ NGLogicalStaticPosition::kInlineEnd,
+ NGLogicalStaticPosition::kBlockStart};
//
// Tests.
//
- NGAbsolutePhysicalPosition p;
+ NGLogicalOutOfFlowPosition p;
// All auto => width is estimated_inline, left is 0.
SetHorizontalStyle(NGAuto, NGAuto, NGAuto, NGAuto, NGAuto);
@@ -160,27 +164,28 @@ TEST_F(NGAbsoluteUtilsTest, Horizontal) {
ltr_space_, *style_, ltr_border_padding, static_position,
estimated_inline, base::nullopt, WritingMode::kHorizontalTb,
TextDirection::kLtr);
- EXPECT_EQ(minmax_60.min_size, p.size.width);
- EXPECT_EQ(LayoutUnit(0), p.inset.left);
+ EXPECT_EQ(minmax_60.min_size, p.size.inline_size);
+ EXPECT_EQ(LayoutUnit(0), p.inset.inline_start);
// All auto => width is estimated_inline, static_position is right
SetHorizontalStyle(NGAuto, NGAuto, NGAuto, NGAuto, NGAuto);
EXPECT_EQ(AbsoluteNeedsChildInlineSize(*style_), true);
estimated_inline = minmax_60;
p = ComputePartialAbsoluteWithChildInlineSize(
- ltr_space_, *style_, ltr_border_padding, static_right_position,
+ ltr_space_, *style_, ltr_border_padding, static_position_inline_end,
estimated_inline, base::nullopt, WritingMode::kHorizontalTb,
TextDirection::kLtr);
- EXPECT_EQ(minmax_60.min_size, p.size.width);
- EXPECT_EQ(container_size_.inline_size, p.inset.right);
+ EXPECT_EQ(minmax_60.min_size, p.size.inline_size);
+ EXPECT_EQ(container_size_.inline_size, p.inset.inline_end);
// All auto + RTL.
p = ComputePartialAbsoluteWithChildInlineSize(
rtl_space_, *style_, rtl_border_padding, static_position,
estimated_inline, base::nullopt, WritingMode::kHorizontalTb,
TextDirection::kLtr);
- EXPECT_EQ(minmax_60.min_size, p.size.width);
- EXPECT_EQ(container_size_.inline_size - minmax_60.min_size, p.inset.right);
+ EXPECT_EQ(minmax_60.min_size, p.size.inline_size);
+ EXPECT_EQ(container_size_.inline_size - minmax_60.min_size,
+ p.inset.inline_end);
// left, right, and left are known, compute margins.
SetHorizontalStyle(left, NGAuto, width, NGAuto, right);
@@ -191,9 +196,9 @@ TEST_F(NGAbsoluteUtilsTest, Horizontal) {
estimated_inline, base::nullopt, WritingMode::kHorizontalTb,
TextDirection::kLtr);
LayoutUnit margin_space =
- (container_size_.inline_size - left - right - p.size.width) / 2;
- EXPECT_EQ(left + margin_space, p.inset.left);
- EXPECT_EQ(right + margin_space, p.inset.right);
+ (container_size_.inline_size - left - right - p.size.inline_size) / 2;
+ EXPECT_EQ(left + margin_space, p.inset.inline_start);
+ EXPECT_EQ(right + margin_space, p.inset.inline_end);
// left, right, and left are known, compute margins, writing mode vertical_lr.
SetHorizontalStyle(left, NGAuto, width, NGAuto, right,
@@ -203,8 +208,8 @@ TEST_F(NGAbsoluteUtilsTest, Horizontal) {
ComputeFullAbsoluteWithChildBlockSize(
vlr_space_, *style_, vlr_border_padding, static_position, estimated_block,
base::nullopt, WritingMode::kHorizontalTb, TextDirection::kLtr, &p);
- EXPECT_EQ(left + margin_space, p.inset.left);
- EXPECT_EQ(right + margin_space, p.inset.right);
+ EXPECT_EQ(left + margin_space, p.inset.block_start);
+ EXPECT_EQ(right + margin_space, p.inset.block_end);
// left, right, and left are known, compute margins, writing mode vertical_rl.
SetHorizontalStyle(left, NGAuto, width, NGAuto, right,
@@ -214,8 +219,8 @@ TEST_F(NGAbsoluteUtilsTest, Horizontal) {
ComputeFullAbsoluteWithChildBlockSize(
vrl_space_, *style_, vrl_border_padding, static_position, estimated_block,
base::nullopt, WritingMode::kHorizontalTb, TextDirection::kLtr, &p);
- EXPECT_EQ(left + margin_space, p.inset.left);
- EXPECT_EQ(right + margin_space, p.inset.right);
+ EXPECT_EQ(left + margin_space, p.inset.block_end);
+ EXPECT_EQ(right + margin_space, p.inset.block_start);
// left, right, and width are known, not enough space for margins LTR.
SetHorizontalStyle(left, NGAuto, LayoutUnit(200), NGAuto, right);
@@ -224,8 +229,8 @@ TEST_F(NGAbsoluteUtilsTest, Horizontal) {
ltr_space_, *style_, ltr_border_padding, static_position,
estimated_inline, base::nullopt, WritingMode::kHorizontalTb,
TextDirection::kLtr);
- EXPECT_EQ(left, p.inset.left);
- EXPECT_EQ(-left, p.inset.right);
+ EXPECT_EQ(left, p.inset.inline_start);
+ EXPECT_EQ(-left, p.inset.inline_end);
// left, right, and left are known, not enough space for margins RTL.
SetHorizontalStyle(left, NGAuto, LayoutUnit(200), NGAuto, right,
@@ -235,8 +240,8 @@ TEST_F(NGAbsoluteUtilsTest, Horizontal) {
rtl_space_, *style_, rtl_border_padding, static_position,
estimated_inline, base::nullopt, WritingMode::kHorizontalTb,
TextDirection::kRtl);
- EXPECT_EQ(-right, p.inset.left);
- EXPECT_EQ(right, p.inset.right);
+ EXPECT_EQ(-right, p.inset.inline_start);
+ EXPECT_EQ(right, p.inset.inline_end);
// Rule 1 left and width are auto.
SetHorizontalStyle(NGAuto, margin_left, NGAuto, margin_right, right);
@@ -246,7 +251,7 @@ TEST_F(NGAbsoluteUtilsTest, Horizontal) {
ltr_space_, *style_, ltr_border_padding, static_position,
estimated_inline, base::nullopt, WritingMode::kHorizontalTb,
TextDirection::kLtr);
- EXPECT_EQ(minmax_60.min_size, p.size.width);
+ EXPECT_EQ(minmax_60.min_size, p.size.inline_size);
// Rule 2 left and right are auto LTR.
SetHorizontalStyle(NGAuto, margin_left, width, margin_right, NGAuto);
@@ -256,8 +261,9 @@ TEST_F(NGAbsoluteUtilsTest, Horizontal) {
ltr_space_, *style_, ltr_border_padding, static_position,
estimated_inline, base::nullopt, WritingMode::kHorizontalTb,
TextDirection::kLtr);
- EXPECT_EQ(margin_left, p.inset.left);
- EXPECT_EQ(container_size_.inline_size - margin_left - width, p.inset.right);
+ EXPECT_EQ(margin_left, p.inset.inline_start);
+ EXPECT_EQ(container_size_.inline_size - margin_left - width,
+ p.inset.inline_end);
// Rule 2 left and right are auto RTL.
SetHorizontalStyle(NGAuto, margin_left, width, margin_right, NGAuto);
@@ -267,8 +273,9 @@ TEST_F(NGAbsoluteUtilsTest, Horizontal) {
rtl_space_, *style_, rtl_border_padding, static_position,
estimated_inline, base::nullopt, WritingMode::kHorizontalTb,
TextDirection::kLtr);
- EXPECT_EQ(margin_left, p.inset.left);
- EXPECT_EQ(container_size_.inline_size - margin_left - width, p.inset.right);
+ EXPECT_EQ(margin_left, p.inset.inline_start);
+ EXPECT_EQ(container_size_.inline_size - margin_left - width,
+ p.inset.inline_end);
// Rule 3 width and right are auto.
SetHorizontalStyle(left, margin_left, NGAuto, margin_right, NGAuto);
@@ -280,8 +287,8 @@ TEST_F(NGAbsoluteUtilsTest, Horizontal) {
TextDirection::kLtr);
EXPECT_EQ(
container_size_.inline_size - minmax_60.min_size - left - margin_left,
- p.inset.right);
- EXPECT_EQ(minmax_60.min_size, p.size.width);
+ p.inset.inline_end);
+ EXPECT_EQ(minmax_60.min_size, p.size.inline_size);
// Rule 4: left is auto.
SetHorizontalStyle(NGAuto, margin_left, width, margin_right, right);
@@ -291,7 +298,7 @@ TEST_F(NGAbsoluteUtilsTest, Horizontal) {
ltr_space_, *style_, ltr_border_padding, static_position,
estimated_inline, base::nullopt, WritingMode::kHorizontalTb,
TextDirection::kLtr);
- EXPECT_EQ(left + margin_left, p.inset.left);
+ EXPECT_EQ(left + margin_left, p.inset.inline_start);
// Rule 4: left is auto, EBoxSizing::kContentBox
style_->SetBoxSizing(EBoxSizing::kContentBox);
@@ -304,7 +311,7 @@ TEST_F(NGAbsoluteUtilsTest, Horizontal) {
ltr_space_, *style_, ltr_border_padding, static_position,
estimated_inline, base::nullopt, WritingMode::kHorizontalTb,
TextDirection::kLtr);
- EXPECT_EQ(left + margin_left, p.inset.left);
+ EXPECT_EQ(left + margin_left, p.inset.inline_start);
style_->SetBoxSizing(EBoxSizing::kBorderBox);
// Rule 5: right is auto.
@@ -315,7 +322,7 @@ TEST_F(NGAbsoluteUtilsTest, Horizontal) {
ltr_space_, *style_, ltr_border_padding, static_position,
estimated_inline, base::nullopt, WritingMode::kHorizontalTb,
TextDirection::kLtr);
- EXPECT_EQ(right + margin_right, p.inset.right);
+ EXPECT_EQ(right + margin_right, p.inset.inline_end);
// Rule 6: width is auto.
SetHorizontalStyle(left, margin_left, NGAuto, margin_right, right);
@@ -325,7 +332,7 @@ TEST_F(NGAbsoluteUtilsTest, Horizontal) {
ltr_space_, *style_, ltr_border_padding, static_position,
estimated_inline, base::nullopt, WritingMode::kHorizontalTb,
TextDirection::kLtr);
- EXPECT_EQ(width, p.size.width);
+ EXPECT_EQ(width, p.size.inline_size);
}
TEST_F(NGAbsoluteUtilsTest, Vertical) {
@@ -357,7 +364,6 @@ TEST_F(NGAbsoluteUtilsTest, Vertical) {
style_->SetBorderLeftWidth(0);
style_->SetBorderRightWidth(0);
- NGAbsolutePhysicalPosition p;
base::Optional<LayoutUnit> auto_height;
MinMaxSize minmax_60{LayoutUnit(60), LayoutUnit(60)};
@@ -368,15 +374,21 @@ TEST_F(NGAbsoluteUtilsTest, Vertical) {
NGBoxStrut vrl_border_padding =
ComputeBordersForTest(*style_) + ComputePadding(vrl_space_, *style_);
- NGStaticPosition static_position{NGStaticPosition::kTopLeft,
- {LayoutUnit(), LayoutUnit()}};
- NGStaticPosition static_position_bottom{NGStaticPosition::kBottomLeft,
- {LayoutUnit(), LayoutUnit()}};
+ NGLogicalStaticPosition static_position = {
+ {LayoutUnit(), LayoutUnit()},
+ NGLogicalStaticPosition::kInlineStart,
+ NGLogicalStaticPosition::kBlockStart};
+ NGLogicalStaticPosition static_position_block_end = {
+ {LayoutUnit(), LayoutUnit()},
+ NGLogicalStaticPosition::kInlineStart,
+ NGLogicalStaticPosition::kBlockEnd};
//
// Tests
//
+ NGLogicalOutOfFlowPosition p;
+
// All auto, compute margins.
SetVerticalStyle(NGAuto, NGAuto, NGAuto, NGAuto, NGAuto);
EXPECT_EQ(AbsoluteNeedsChildBlockSize(*style_), true);
@@ -384,15 +396,15 @@ TEST_F(NGAbsoluteUtilsTest, Vertical) {
ComputeFullAbsoluteWithChildBlockSize(
ltr_space_, *style_, ltr_border_padding, static_position, auto_height,
base::nullopt, WritingMode::kHorizontalTb, TextDirection::kLtr, &p);
- EXPECT_EQ(*auto_height, p.size.height);
- EXPECT_EQ(LayoutUnit(0), p.inset.top);
+ EXPECT_EQ(*auto_height, p.size.block_size);
+ EXPECT_EQ(LayoutUnit(0), p.inset.block_start);
// All auto, static position bottom
ComputeFullAbsoluteWithChildBlockSize(
- ltr_space_, *style_, ltr_border_padding, static_position_bottom,
+ ltr_space_, *style_, ltr_border_padding, static_position_block_end,
auto_height, base::nullopt, WritingMode::kHorizontalTb,
TextDirection::kLtr, &p);
- EXPECT_EQ(container_size_.block_size, p.inset.bottom);
+ EXPECT_EQ(container_size_.block_size, p.inset.block_end);
// If top, bottom, and height are known, compute margins.
SetVerticalStyle(top, NGAuto, height, NGAuto, bottom);
@@ -403,8 +415,8 @@ TEST_F(NGAbsoluteUtilsTest, Vertical) {
base::nullopt, WritingMode::kHorizontalTb, TextDirection::kLtr, &p);
LayoutUnit margin_space =
(container_size_.block_size - top - height - bottom) / 2;
- EXPECT_EQ(top + margin_space, p.inset.top);
- EXPECT_EQ(bottom + margin_space, p.inset.bottom);
+ EXPECT_EQ(top + margin_space, p.inset.block_start);
+ EXPECT_EQ(bottom + margin_space, p.inset.block_end);
// If top, bottom, and height are known, writing mode vertical_lr.
SetVerticalStyle(top, NGAuto, height, NGAuto, bottom,
@@ -413,8 +425,8 @@ TEST_F(NGAbsoluteUtilsTest, Vertical) {
p = ComputePartialAbsoluteWithChildInlineSize(
vlr_space_, *style_, vlr_border_padding, static_position, minmax_60,
base::nullopt, WritingMode::kHorizontalTb, TextDirection::kLtr);
- EXPECT_EQ(top + margin_space, p.inset.top);
- EXPECT_EQ(bottom + margin_space, p.inset.bottom);
+ EXPECT_EQ(top + margin_space, p.inset.inline_start);
+ EXPECT_EQ(bottom + margin_space, p.inset.inline_end);
// If top, bottom, and height are known, writing mode vertical_rl.
SetVerticalStyle(top, NGAuto, height, NGAuto, bottom,
@@ -423,8 +435,8 @@ TEST_F(NGAbsoluteUtilsTest, Vertical) {
p = ComputePartialAbsoluteWithChildInlineSize(
vrl_space_, *style_, vrl_border_padding, static_position, minmax_60,
base::nullopt, WritingMode::kHorizontalTb, TextDirection::kLtr);
- EXPECT_EQ(top + margin_space, p.inset.top);
- EXPECT_EQ(bottom + margin_space, p.inset.bottom);
+ EXPECT_EQ(top + margin_space, p.inset.inline_start);
+ EXPECT_EQ(bottom + margin_space, p.inset.inline_end);
// If top, bottom, and height are known, negative auto margins.
LayoutUnit negative_margin_space =
@@ -434,8 +446,8 @@ TEST_F(NGAbsoluteUtilsTest, Vertical) {
ComputeFullAbsoluteWithChildBlockSize(
ltr_space_, *style_, ltr_border_padding, static_position, auto_height,
base::nullopt, WritingMode::kHorizontalTb, TextDirection::kLtr, &p);
- EXPECT_EQ(top + negative_margin_space, p.inset.top);
- EXPECT_EQ(bottom + negative_margin_space, p.inset.bottom);
+ EXPECT_EQ(top + negative_margin_space, p.inset.block_start);
+ EXPECT_EQ(bottom + negative_margin_space, p.inset.block_end);
// Rule 1: top and height are unknown.
SetVerticalStyle(NGAuto, margin_top, NGAuto, margin_bottom, bottom);
@@ -444,7 +456,7 @@ TEST_F(NGAbsoluteUtilsTest, Vertical) {
ComputeFullAbsoluteWithChildBlockSize(
ltr_space_, *style_, ltr_border_padding, static_position, auto_height,
base::nullopt, WritingMode::kHorizontalTb, TextDirection::kLtr, &p);
- EXPECT_EQ(*auto_height, p.size.height);
+ EXPECT_EQ(*auto_height, p.size.block_size);
// Rule 2: top and bottom are unknown.
SetVerticalStyle(NGAuto, margin_top, height, margin_bottom, NGAuto);
@@ -453,8 +465,9 @@ TEST_F(NGAbsoluteUtilsTest, Vertical) {
ComputeFullAbsoluteWithChildBlockSize(
ltr_space_, *style_, ltr_border_padding, static_position, auto_height,
base::nullopt, WritingMode::kHorizontalTb, TextDirection::kLtr, &p);
- EXPECT_EQ(margin_top, p.inset.top);
- EXPECT_EQ(container_size_.block_size - margin_top - height, p.inset.bottom);
+ EXPECT_EQ(margin_top, p.inset.block_start);
+ EXPECT_EQ(container_size_.block_size - margin_top - height,
+ p.inset.block_end);
// Rule 3: height and bottom are unknown, auto_height <
// horizontal_border_padding.
@@ -464,7 +477,7 @@ TEST_F(NGAbsoluteUtilsTest, Vertical) {
ComputeFullAbsoluteWithChildBlockSize(
ltr_space_, *style_, ltr_border_padding, static_position, auto_height,
base::nullopt, WritingMode::kHorizontalTb, TextDirection::kLtr, &p);
- EXPECT_EQ(horizontal_border_padding, p.size.height);
+ EXPECT_EQ(horizontal_border_padding, p.size.block_size);
// Rule 3: height and bottom are unknown.
SetVerticalStyle(top, margin_top, NGAuto, margin_bottom, NGAuto);
@@ -473,7 +486,7 @@ TEST_F(NGAbsoluteUtilsTest, Vertical) {
ComputeFullAbsoluteWithChildBlockSize(
ltr_space_, *style_, ltr_border_padding, static_position, auto_height,
base::nullopt, WritingMode::kHorizontalTb, TextDirection::kLtr, &p);
- EXPECT_EQ(*auto_height, p.size.height);
+ EXPECT_EQ(*auto_height, p.size.block_size);
// Rule 4: top is unknown.
SetVerticalStyle(NGAuto, margin_top, height, margin_bottom, bottom);
@@ -482,7 +495,7 @@ TEST_F(NGAbsoluteUtilsTest, Vertical) {
ComputeFullAbsoluteWithChildBlockSize(
ltr_space_, *style_, ltr_border_padding, static_position, auto_height,
base::nullopt, WritingMode::kHorizontalTb, TextDirection::kLtr, &p);
- EXPECT_EQ(top + margin_top, p.inset.top);
+ EXPECT_EQ(top + margin_top, p.inset.block_start);
// Rule 5: bottom is unknown.
SetVerticalStyle(top, margin_top, height, margin_bottom, NGAuto);
@@ -491,7 +504,7 @@ TEST_F(NGAbsoluteUtilsTest, Vertical) {
ComputeFullAbsoluteWithChildBlockSize(
ltr_space_, *style_, ltr_border_padding, static_position, auto_height,
base::nullopt, WritingMode::kHorizontalTb, TextDirection::kLtr, &p);
- EXPECT_EQ(bottom + margin_bottom, p.inset.bottom);
+ EXPECT_EQ(bottom + margin_bottom, p.inset.block_end);
// Rule 6: height is unknown.
SetVerticalStyle(top, margin_top, NGAuto, margin_bottom, bottom);
@@ -500,7 +513,7 @@ TEST_F(NGAbsoluteUtilsTest, Vertical) {
ComputeFullAbsoluteWithChildBlockSize(
ltr_space_, *style_, ltr_border_padding, static_position, auto_height,
base::nullopt, WritingMode::kHorizontalTb, TextDirection::kLtr, &p);
- EXPECT_EQ(height, p.size.height);
+ EXPECT_EQ(height, p.size.block_size);
}
TEST_F(NGAbsoluteUtilsTest, MinMax) {
@@ -515,10 +528,12 @@ TEST_F(NGAbsoluteUtilsTest, MinMax) {
NGBoxStrut ltr_border_padding =
ComputeBordersForTest(*style_) + ComputePadding(ltr_space_, *style_);
- NGStaticPosition static_position{NGStaticPosition::kTopLeft,
- {LayoutUnit(), LayoutUnit()}};
+ NGLogicalStaticPosition static_position = {
+ {LayoutUnit(), LayoutUnit()},
+ NGLogicalStaticPosition::kInlineStart,
+ NGLogicalStaticPosition::kBlockStart};
MinMaxSize estimated_inline{LayoutUnit(20), LayoutUnit(20)};
- NGAbsolutePhysicalPosition p;
+ NGLogicalOutOfFlowPosition p;
// WIDTH TESTS
@@ -528,7 +543,7 @@ TEST_F(NGAbsoluteUtilsTest, MinMax) {
ltr_space_, *style_, ltr_border_padding, static_position,
estimated_inline, base::nullopt, WritingMode::kHorizontalTb,
TextDirection::kLtr);
- EXPECT_EQ(min, p.size.width);
+ EXPECT_EQ(min, p.size.inline_size);
// width > max gets set to max.
SetHorizontalStyle(NGAuto, NGAuto, LayoutUnit(200), NGAuto, NGAuto);
@@ -536,7 +551,7 @@ TEST_F(NGAbsoluteUtilsTest, MinMax) {
ltr_space_, *style_, ltr_border_padding, static_position,
estimated_inline, base::nullopt, WritingMode::kHorizontalTb,
TextDirection::kLtr);
- EXPECT_EQ(max, p.size.width);
+ EXPECT_EQ(max, p.size.inline_size);
// Unspecified width becomes minmax, gets clamped to min.
SetHorizontalStyle(NGAuto, NGAuto, NGAuto, NGAuto, NGAuto);
@@ -544,7 +559,7 @@ TEST_F(NGAbsoluteUtilsTest, MinMax) {
ltr_space_, *style_, ltr_border_padding, static_position,
estimated_inline, base::nullopt, WritingMode::kHorizontalTb,
TextDirection::kLtr);
- EXPECT_EQ(min, p.size.width);
+ EXPECT_EQ(min, p.size.inline_size);
// HEIGHT TESTS
@@ -555,14 +570,14 @@ TEST_F(NGAbsoluteUtilsTest, MinMax) {
ComputeFullAbsoluteWithChildBlockSize(
ltr_space_, *style_, ltr_border_padding, static_position, auto_height,
base::nullopt, WritingMode::kHorizontalTb, TextDirection::kLtr, &p);
- EXPECT_EQ(min, p.size.height);
+ EXPECT_EQ(min, p.size.block_size);
// height > max gets set to max.
SetVerticalStyle(NGAuto, NGAuto, LayoutUnit(200), NGAuto, NGAuto);
ComputeFullAbsoluteWithChildBlockSize(
ltr_space_, *style_, ltr_border_padding, static_position, auto_height,
base::nullopt, WritingMode::kHorizontalTb, TextDirection::kLtr, &p);
- EXPECT_EQ(max, p.size.height);
+ EXPECT_EQ(max, p.size.block_size);
// // Unspecified height becomes estimated, gets clamped to min.
SetVerticalStyle(NGAuto, NGAuto, NGAuto, NGAuto, NGAuto);
@@ -570,7 +585,7 @@ TEST_F(NGAbsoluteUtilsTest, MinMax) {
ComputeFullAbsoluteWithChildBlockSize(
ltr_space_, *style_, ltr_border_padding, static_position, auto_height,
base::nullopt, WritingMode::kHorizontalTb, TextDirection::kLtr, &p);
- EXPECT_EQ(min, p.size.width);
+ EXPECT_EQ(min, p.size.block_size);
}
} // namespace
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 bbc33e3ecf2..a618a18e00d 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
@@ -16,8 +16,8 @@
namespace blink {
void NGBaseLayoutAlgorithmTest::SetUp() {
- NGLayoutTest::SetUp();
EnableCompositing();
+ NGLayoutTest::SetUp();
}
void NGBaseLayoutAlgorithmTest::AdvanceToLayoutPhase() {
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_base_layout_algorithm_test.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_base_layout_algorithm_test.h
index 8459fe2838a..702637ee1bb 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_base_layout_algorithm_test.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_base_layout_algorithm_test.h
@@ -12,7 +12,7 @@
#include "third_party/blink/renderer/core/testing/core_unit_test_helper.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/allocator/allocator.h"
namespace blink {
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 18a44a94fee..3f61073a6d4 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
@@ -19,24 +19,6 @@ class NGInlineBreakToken;
// Represents a break token for a block node.
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.
//
@@ -106,8 +88,8 @@ class CORE_EXPORT NGBlockBreakToken final : public NGBreakToken {
// this child).
//
// A child which we haven't visited yet doesn't have a break token here.
- const ChildTokenList ChildBreakTokens() const {
- return ChildTokenList(num_children_, &child_break_tokens_[0]);
+ const base::span<NGBreakToken* const> ChildBreakTokens() const {
+ return base::make_span(child_break_tokens_, num_children_);
}
// Find the child NGInlineBreakToken for the specified node.
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 9cce428b4f7..12e37f57e61 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
@@ -46,16 +46,34 @@ inline scoped_refptr<const NGLayoutResult> LayoutInflow(
: To<NGBlockNode>(node)->Layout(space, break_token);
}
+NGAdjoiningObjectTypes ToAdjoiningObjectTypes(EClear clear) {
+ switch (clear) {
+ default:
+ NOTREACHED();
+ FALLTHROUGH;
+ case EClear::kNone:
+ return kAdjoiningNone;
+ case EClear::kLeft:
+ return kAdjoiningFloatLeft;
+ case EClear::kRight:
+ return kAdjoiningFloatRight;
+ case EClear::kBoth:
+ return kAdjoiningFloatBoth;
+ };
+}
+
// Return true if a child is to be cleared past adjoining floats. These are
// floats that would otherwise (if 'clear' were 'none') be pulled down by the
// BFC block offset of the child. If the child is to clear floats, though, we
// obviously need separate the child from the floats and move it past them,
// 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,
- const ComputedStyle& cb_style) {
- return ToFloatTypes(ResolvedClear(child_style, cb_style)) & adjoining_floats;
+inline bool HasClearancePastAdjoiningFloats(
+ NGAdjoiningObjectTypes adjoining_object_types,
+ const ComputedStyle& child_style,
+ const ComputedStyle& cb_style) {
+ return ToAdjoiningObjectTypes(ResolvedClear(child_style, cb_style)) &
+ adjoining_object_types;
}
// Adjust BFC block offset for clearance, if applicable. Return true of
@@ -344,7 +362,7 @@ NGBlockLayoutAlgorithm::LayoutWithInlineChildLayoutContext() {
inline scoped_refptr<const NGLayoutResult> NGBlockLayoutAlgorithm::Layout(
NGInlineChildLayoutContext* inline_child_layout_context) {
- LogicalSize border_box_size = container_builder_.InitialBorderBoxSize();
+ const LogicalSize border_box_size = container_builder_.InitialBorderBoxSize();
child_available_size_ =
ShrinkAvailableSize(border_box_size, border_scrollbar_padding_);
@@ -364,17 +382,18 @@ inline scoped_refptr<const NGLayoutResult> NGBlockLayoutAlgorithm::Layout(
container_builder_.SetBfcLineOffset(
ConstraintSpace().BfcOffset().line_offset);
- if (NGFloatTypes float_types = ConstraintSpace().AdjoiningFloatTypes()) {
+ if (NGAdjoiningObjectTypes adjoining_object_types =
+ ConstraintSpace().AdjoiningObjectTypes()) {
DCHECK(!ConstraintSpace().IsNewFormattingContext());
DCHECK(!container_builder_.BfcBlockOffset());
- // If there were preceding adjoining floats, they will be affected when the
- // BFC block offset gets resolved or updated. We then need to roll back and
- // re-layout those floats with the new BFC block offset, once the BFC block
- // offset is updated.
+ // If there were preceding adjoining objects, they will be affected when the
+ // BFC block-offset gets resolved or updated. We then need to roll back and
+ // re-layout those objects with the new BFC block-offset, once the BFC
+ // block-offset is updated.
abort_when_bfc_block_offset_updated_ = true;
- container_builder_.SetAdjoiningFloatTypes(float_types);
+ container_builder_.SetAdjoiningObjectTypes(adjoining_object_types);
}
// If we are resuming from a break token our start border and padding is
@@ -465,13 +484,14 @@ inline scoped_refptr<const NGLayoutResult> NGBlockLayoutAlgorithm::Layout(
// |previous_inflow_position| and |BreakToken()|.
scoped_refptr<const NGInlineBreakToken> previous_inline_break_token;
+ NGBlockChildIterator child_iterator(Node().FirstChild(), BreakToken());
+
// If this layout is blocked by a display-lock, then we pretend this node has
- // no children. Due to this, we skip layout on these children.
- NGBlockChildIterator child_iterator(
- Node().LayoutBlockedByDisplayLock(DisplayLockContext::kChildren)
- ? NGBlockNode(nullptr)
- : Node().FirstChild(),
- BreakToken());
+ // no children and that there are no break tokens. Due to this, we skip layout
+ // on these children.
+ if (Node().LayoutBlockedByDisplayLock(DisplayLockContext::kChildren))
+ child_iterator = NGBlockChildIterator(NGBlockNode(nullptr), nullptr);
+
for (auto entry = child_iterator.NextChild();
NGLayoutInputNode child = entry.node;
entry = child_iterator.NextChild(previous_inline_break_token.get())) {
@@ -527,16 +547,12 @@ inline scoped_refptr<const NGLayoutResult> NGBlockLayoutAlgorithm::Layout(
// To save space of the stack when we recurse into children, the rest of this
// function is continued within |FinishLayout|. However it should be read as
// one function.
- return FinishLayout(&previous_inflow_position, border_box_size,
- container_builder_.Borders(),
- container_builder_.Scrollbar());
+ return FinishLayout(&previous_inflow_position);
}
scoped_refptr<const NGLayoutResult> NGBlockLayoutAlgorithm::FinishLayout(
- NGPreviousInflowPosition* previous_inflow_position,
- LogicalSize border_box_size,
- const NGBoxStrut& borders,
- const NGBoxStrut& scrollbars) {
+ NGPreviousInflowPosition* previous_inflow_position) {
+ LogicalSize border_box_size = container_builder_.InitialBorderBoxSize();
NGMarginStrut end_margin_strut = previous_inflow_position->margin_strut;
// If the current layout is a new formatting context, we need to encapsulate
@@ -639,16 +655,18 @@ scoped_refptr<const NGLayoutResult> NGBlockLayoutAlgorithm::FinishLayout(
// List markers should have been positioned if we had line boxes, or boxes
// that have line boxes. If there were no line boxes, position without line
// boxes.
- if (container_builder_.UnpositionedListMarker() && node_.IsListItem())
- PositionListMarkerWithoutLineBoxes();
+ if (container_builder_.UnpositionedListMarker() && node_.IsListItem()) {
+ if (!PositionListMarkerWithoutLineBoxes(previous_inflow_position))
+ return container_builder_.Abort(NGLayoutResult::kBfcBlockOffsetResolved);
+ }
container_builder_.SetEndMarginStrut(end_margin_strut);
container_builder_.SetIntrinsicBlockSize(intrinsic_block_size_);
if (container_builder_.BfcBlockOffset()) {
// If we know our BFC block-offset we should have correctly placed all
- // adjoining floats, and shouldn't propagate this information to siblings.
- container_builder_.ResetAdjoiningFloatTypes();
+ // adjoining objects, and shouldn't propagate this information to siblings.
+ container_builder_.ResetAdjoiningObjectTypes();
} else {
// If we don't know our BFC block-offset yet, we know that for
// margin-collapsing purposes we are self-collapsing.
@@ -658,7 +676,6 @@ scoped_refptr<const NGLayoutResult> NGBlockLayoutAlgorithm::FinishLayout(
// clearance past adjoining floats, or a re-layout), we can safely set our
// BFC block-offset now.
if (ConstraintSpace().ForcedBfcBlockOffset()) {
- DCHECK(unpositioned_floats_.IsEmpty());
container_builder_.SetBfcBlockOffset(
*ConstraintSpace().ForcedBfcBlockOffset());
}
@@ -671,23 +688,13 @@ scoped_refptr<const NGLayoutResult> NGBlockLayoutAlgorithm::FinishLayout(
ConstraintSpace().HasBlockFragmentation())
FinalizeForFragmentation();
- // Only layout absolute and fixed children if we aren't going to revisit this
- // layout.
- if (unpositioned_floats_.IsEmpty()) {
- NGOutOfFlowLayoutPart(Node(), ConstraintSpace(), borders + scrollbars,
- &container_builder_)
- .Run();
- }
+ NGOutOfFlowLayoutPart(
+ Node(), ConstraintSpace(),
+ container_builder_.Borders() + container_builder_.Scrollbar(),
+ &container_builder_)
+ .Run();
#if DCHECK_IS_ON()
- // If we have any unpositioned floats at this stage, our parent will pick up
- // this by examining adjoining float types returned, so that we get relayout
- // with a forced BFC block offset once it's known.
- if (!unpositioned_floats_.IsEmpty()) {
- DCHECK(!container_builder_.BfcBlockOffset());
- DCHECK(container_builder_.AdjoiningFloatTypes());
- }
-
// If we're not participating in a fragmentation context, no block
// fragmentation related fields should have been set.
if (!ConstraintSpace().HasBlockFragmentation())
@@ -717,7 +724,7 @@ const NGInlineBreakToken* NGBlockLayoutAlgorithm::TryReuseFragmentsFromCache(
return nullptr;
// If floats are intruding into this node, re-layout may be needed.
- if (!exclusion_space_.IsEmpty() || !unpositioned_floats_.IsEmpty())
+ if (!exclusion_space_.IsEmpty())
return nullptr;
// Laying out from a break token is not supported yet, because this logic
@@ -807,14 +814,13 @@ void NGBlockLayoutAlgorithm::HandleOutOfFlowPositioned(
// Due to this we need to mark this node as having adjoining objects, and
// perform a re-layout if our position shifts.
if (!container_builder_.BfcBlockOffset()) {
- container_builder_.AddAdjoiningFloatTypes(kAdjoiningInlineOutOfFlow);
+ container_builder_.AddAdjoiningObjectTypes(kAdjoiningInlineOutOfFlow);
abort_when_bfc_block_offset_updated_ = true;
}
LayoutUnit origin_bfc_block_offset =
container_builder_.BfcBlockOffset().value_or(
- ConstraintSpace().ForcedBfcBlockOffset().value_or(
- ConstraintSpace().BfcOffset().block_offset)) +
+ ConstraintSpace().ExpectedBfcBlockOffset()) +
static_offset.block_offset;
NGBfcOffset origin_bfc_offset = {
@@ -840,29 +846,47 @@ void NGBlockLayoutAlgorithm::HandleFloat(
NGUnpositionedFloat unpositioned_float(child, child_break_token);
- // We shouldn't have seen this float yet.
- DCHECK(!unpositioned_floats_.Contains(unpositioned_float));
-
if (!container_builder_.BfcBlockOffset()) {
- container_builder_.AddAdjoiningFloatTypes(
+ container_builder_.AddAdjoiningObjectTypes(
unpositioned_float.IsLineLeft(ConstraintSpace().Direction())
- ? kFloatTypeLeft
- : kFloatTypeRight);
- }
- unpositioned_floats_.push_back(std::move(unpositioned_float));
-
- // No need to postpone the positioning if we know the correct offset.
- if (container_builder_.BfcBlockOffset() ||
- ConstraintSpace().ForcedBfcBlockOffset()) {
- // Adjust origin point to the margins of the last child.
- // Example: <div style="margin-bottom: 20px"><float></div>
- // <div style="margin-bottom: 30px"></div>
- LayoutUnit origin_block_offset =
- container_builder_.BfcBlockOffset()
- ? NextBorderEdge(previous_inflow_position)
- : *ConstraintSpace().ForcedBfcBlockOffset();
- PositionPendingFloats(origin_block_offset);
+ ? kAdjoiningFloatLeft
+ : kAdjoiningFloatRight);
+ // If we don't have a forced BFC block-offset yet, we'll optimistically
+ // place floats at the "expected" BFC block-offset. If this differs from
+ // our final BFC block-offset we'll need to re-layout.
+ if (!ConstraintSpace().ForcedBfcBlockOffset())
+ abort_when_bfc_block_offset_updated_ = true;
}
+
+ // If we don't have a BFC block-offset yet, the "expected" BFC block-offset
+ // is used to optimistically place floats.
+ NGBfcOffset origin_bfc_offset = {
+ ConstraintSpace().BfcOffset().line_offset +
+ border_scrollbar_padding_.LineLeft(ConstraintSpace().Direction()),
+ container_builder_.BfcBlockOffset()
+ ? NextBorderEdge(previous_inflow_position)
+ : ConstraintSpace().ExpectedBfcBlockOffset()};
+
+ NGPositionedFloat positioned_float = PositionFloat(
+ child_available_size_, child_percentage_size_,
+ replaced_child_percentage_size_, origin_bfc_offset, &unpositioned_float,
+ ConstraintSpace(), Style(), &exclusion_space_);
+
+ const auto& physical_fragment =
+ positioned_float.layout_result->PhysicalFragment();
+ LayoutUnit float_inline_size =
+ NGFragment(ConstraintSpace().GetWritingMode(), physical_fragment)
+ .InlineSize();
+
+ NGBfcOffset bfc_offset = {ConstraintSpace().BfcOffset().line_offset,
+ container_builder_.BfcBlockOffset().value_or(
+ ConstraintSpace().ExpectedBfcBlockOffset())};
+
+ LogicalOffset logical_offset = LogicalFromBfcOffsets(
+ positioned_float.bfc_offset, bfc_offset, float_inline_size,
+ container_builder_.Size().inline_size, ConstraintSpace().Direction());
+
+ container_builder_.AddResult(*positioned_float.layout_result, logical_offset);
}
bool NGBlockLayoutAlgorithm::HandleNewFormattingContext(
@@ -908,10 +932,11 @@ bool NGBlockLayoutAlgorithm::HandleNewFormattingContext(
bool bfc_offset_already_resolved = false;
bool child_determined_bfc_offset = false;
bool child_margin_got_separated = false;
- bool had_pending_floats = false;
+ bool has_adjoining_floats = false;
if (!container_builder_.BfcBlockOffset()) {
- had_pending_floats = !unpositioned_floats_.IsEmpty();
+ has_adjoining_floats =
+ container_builder_.AdjoiningObjectTypes() & kAdjoiningFloatBoth;
// If this node, or an arbitrary ancestor had clearance past adjoining
// floats, we consider the margin "separated". We should *never* attempt to
@@ -919,7 +944,7 @@ bool NGBlockLayoutAlgorithm::HandleNewFormattingContext(
bool has_clearance_past_adjoining_floats =
ConstraintSpace().AncestorHasClearancePastAdjoiningFloats() ||
HasClearancePastAdjoiningFloats(
- container_builder_.AdjoiningFloatTypes(), child_style, Style());
+ container_builder_.AdjoiningObjectTypes(), child_style, Style());
if (has_clearance_past_adjoining_floats) {
child_bfc_offset_estimate = NextBorderEdge(*previous_inflow_position);
@@ -997,7 +1022,7 @@ bool NGBlockLayoutAlgorithm::HandleNewFormattingContext(
non_adjoining_bfc_offset_estimate,
/* forced_bfc_block_offset */ base::nullopt);
- if ((bfc_offset_already_resolved || had_pending_floats) &&
+ if ((bfc_offset_already_resolved || has_adjoining_floats) &&
old_offset != *container_builder_.BfcBlockOffset()) {
// The first BFC block offset resolution turned out to be wrong, and we
// positioned preceding adjacent floats based on that. Now we have to
@@ -1033,8 +1058,20 @@ bool NGBlockLayoutAlgorithm::HandleNewFormattingContext(
// Deal with marker's margin. It happens only when marker needs to occupy
// the whole line.
DCHECK(child.ListMarkerOccupiesWholeLine());
+ // Because the marker is laid out as a normal block child, its inline size
+ // is extended to fill up the space. Compute the regular marker size from
+ // the first child.
+ const NGPhysicalContainerFragment& marker_fragment =
+ layout_result->PhysicalFragment();
+ DCHECK(!marker_fragment.Children().empty());
+ const NGPhysicalFragment& marker_child_fragment =
+ *marker_fragment.Children().front();
+ LayoutUnit marker_inline_size =
+ marker_child_fragment.Size()
+ .ConvertToLogical(ConstraintSpace().GetWritingMode())
+ .inline_size;
auto_margins.inline_start = NGUnpositionedListMarker(To<NGBlockNode>(child))
- .InlineOffset(fragment.InlineSize());
+ .InlineOffset(marker_inline_size);
auto_margins.inline_end = opportunity.rect.InlineSize() -
fragment.InlineSize() - auto_margins.inline_start;
} else {
@@ -1087,11 +1124,11 @@ bool NGBlockLayoutAlgorithm::HandleNewFormattingContext(
container_builder_.SetPreviousBreakAfter(break_after);
}
- PositionOrPropagateListMarker(*layout_result, &logical_offset);
+ if (!PositionOrPropagateListMarker(*layout_result, &logical_offset,
+ previous_inflow_position))
+ return false;
- container_builder_.AddChild(layout_result->PhysicalFragment(),
- logical_offset);
- container_builder_.PropagateBreak(*layout_result);
+ container_builder_.AddResult(*layout_result, logical_offset);
// The margins we store will be used by e.g. getComputedStyle().
// When calculating these values, ignore any floats that might have
@@ -1233,7 +1270,7 @@ bool NGBlockLayoutAlgorithm::HandleInflow(
child_inline_node && !child_inline_node->IsEmptyInline();
bool has_clearance_past_adjoining_floats =
!container_builder_.BfcBlockOffset() && child.IsBlock() &&
- HasClearancePastAdjoiningFloats(container_builder_.AdjoiningFloatTypes(),
+ HasClearancePastAdjoiningFloats(container_builder_.AdjoiningObjectTypes(),
child.Style(), Style());
base::Optional<LayoutUnit> forced_bfc_block_offset;
@@ -1387,29 +1424,24 @@ bool NGBlockLayoutAlgorithm::FinishInflow(
// positioned in the incorrect position.
//
// TODO(layout-dev): A more optimal version of this is to set this flag
- // only if the child tree *added* any floats which it failed to position.
- // Currently, we risk relaying out the sub-tree for no reason, because
- // we're not able to make this distinction.
- if (layout_result->AdjoiningFloatTypes() &&
+ // only if the child tree *added* any adjoining objects which it failed
+ // to position. Currently, we risk relaying out the sub-tree for no
+ // reason, because we're not able to make this distinction.
+ if (layout_result->AdjoiningObjectTypes() &&
!child_space.ForcedBfcBlockOffset())
self_collapsing_child_needs_relayout = true;
}
- } else if (!child_had_clearance) {
- // We shouldn't have any pending floats here, since an in-flow child found
- // its BFC block offset.
- DCHECK(unpositioned_floats_.IsEmpty());
-
- // Only non self-collapsing children are allowed resolve the BFC
+ } else if (!child_had_clearance && !is_self_collapsing) {
+ // Only non self-collapsing children are allowed resolve their parent's BFC
// block-offset. We check the BFC block-offset at the end of layout
// determine if this fragment is self-collapsing.
- if (!is_self_collapsing) {
- // The child's BFC block offset is known, and since there's no clearance,
- // this container will get the same offset, unless it has already been
- // resolved.
- if (!ResolveBfcBlockOffset(previous_inflow_position,
- *child_bfc_block_offset))
- return false;
- }
+ //
+ // The child's BFC block-offset is known, and since there's no clearance,
+ // this container will get the same offset, unless it has already been
+ // resolved.
+ if (!ResolveBfcBlockOffset(previous_inflow_position,
+ *child_bfc_block_offset))
+ return false;
}
// We need to re-layout a self-collapsing child if it was affected by
@@ -1476,10 +1508,10 @@ bool NGBlockLayoutAlgorithm::FinishInflow(
// propagated adjoining floats.
exclusion_space_ = layout_result->ExclusionSpace();
- // Only self-collapsing children should have adjoining floats.
- DCHECK(!layout_result->AdjoiningFloatTypes() || is_self_collapsing);
- container_builder_.SetAdjoiningFloatTypes(
- layout_result->AdjoiningFloatTypes());
+ // Only self-collapsing children should have adjoining objects.
+ DCHECK(!layout_result->AdjoiningObjectTypes() || is_self_collapsing);
+ container_builder_.SetAdjoiningObjectTypes(
+ layout_result->AdjoiningObjectTypes());
// If we don't know our BFC block-offset yet, and the child stumbled into
// something that needs it (unable to position floats yet), we need abort
@@ -1497,7 +1529,7 @@ bool NGBlockLayoutAlgorithm::FinishInflow(
// has been positioned.
if (!container_builder_.BfcBlockOffset()) {
abort_when_bfc_block_offset_updated_ |=
- layout_result->AdjoiningFloatTypes();
+ layout_result->AdjoiningObjectTypes();
// If our BFC block offset is unknown, and the child got pushed down by
// floats, so will we.
if (layout_result->IsPushedByFloats())
@@ -1520,11 +1552,11 @@ bool NGBlockLayoutAlgorithm::FinishInflow(
container_builder_.SetPreviousBreakAfter(break_after);
}
- PositionOrPropagateListMarker(*layout_result, &logical_offset);
+ if (!PositionOrPropagateListMarker(*layout_result, &logical_offset,
+ previous_inflow_position))
+ return false;
- container_builder_.AddChild(physical_fragment, logical_offset);
- if (child.IsBlock())
- container_builder_.PropagateBreak(*layout_result);
+ container_builder_.AddResult(*layout_result, logical_offset);
if (auto* block_child = DynamicTo<NGBlockNode>(child)) {
// We haven't yet resolved margins wrt. overconstrainedness, unless that was
@@ -1575,11 +1607,27 @@ NGInflowChildData NGBlockLayoutAlgorithm::ComputeChildData(
LayoutUnit logical_block_offset =
previous_inflow_position.logical_block_offset;
- if (child.Style().MarginBeforeCollapse() != EMarginCollapse::kCollapse) {
+ EMarginCollapse margin_before_collapse = child.Style().MarginBeforeCollapse();
+ if (margin_before_collapse != EMarginCollapse::kCollapse) {
// Stop margin collapsing on the block-start side of the child.
StopMarginCollapsing(child.Style().MarginBeforeCollapse(),
margins.block_start, &logical_block_offset,
&margin_strut);
+
+ if (margin_before_collapse == EMarginCollapse::kSeparate) {
+ UseCounter::Count(Node().GetDocument(),
+ WebFeature::kWebkitMarginBeforeCollapseSeparate);
+ if (margin_strut != previous_inflow_position.margin_strut ||
+ logical_block_offset !=
+ previous_inflow_position.logical_block_offset) {
+ UseCounter::Count(
+ Node().GetDocument(),
+ WebFeature::kWebkitMarginBeforeCollapseSeparateMaybeDoesSomething);
+ }
+ } else if (margin_before_collapse == EMarginCollapse::kDiscard) {
+ UseCounter::Count(Node().GetDocument(),
+ WebFeature::kWebkitMarginBeforeCollapseDiscard);
+ }
} else {
margin_strut.Append(margins.block_start,
child.Style().HasMarginBeforeQuirk());
@@ -1670,11 +1718,26 @@ NGPreviousInflowPosition NGBlockLayoutAlgorithm::ComputeInflowPosition(
NGMarginStrut margin_strut = layout_result.EndMarginStrut();
- if (child.Style().MarginAfterCollapse() != EMarginCollapse::kCollapse) {
+ EMarginCollapse margin_after_collapse = child.Style().MarginAfterCollapse();
+ if (margin_after_collapse != EMarginCollapse::kCollapse) {
+ LayoutUnit logical_block_offset_copy = logical_block_offset;
// Stop margin collapsing on the block-end side of the child.
- StopMarginCollapsing(child.Style().MarginAfterCollapse(),
- child_data.margins.block_end, &logical_block_offset,
- &margin_strut);
+ StopMarginCollapsing(margin_after_collapse, child_data.margins.block_end,
+ &logical_block_offset, &margin_strut);
+
+ if (margin_after_collapse == EMarginCollapse::kSeparate) {
+ UseCounter::Count(Node().GetDocument(),
+ WebFeature::kWebkitMarginAfterCollapseSeparate);
+ if (margin_strut != layout_result.EndMarginStrut() ||
+ logical_block_offset != logical_block_offset_copy) {
+ UseCounter::Count(
+ Node().GetDocument(),
+ WebFeature::kWebkitMarginAfterCollapseSeparateMaybeDoesSomething);
+ }
+ } else if (margin_after_collapse == EMarginCollapse::kDiscard) {
+ UseCounter::Count(Node().GetDocument(),
+ WebFeature::kWebkitMarginAfterCollapseDiscard);
+ }
} else {
// Self collapsing child's end margin can "inherit" quirkiness from its
// start margin. E.g.
@@ -2127,7 +2190,38 @@ NGConstraintSpace NGBlockLayoutAlgorithm::CreateConstraintSpaceForChild(
if (!has_bfc_block_offset && ConstraintSpace().ForcedBfcBlockOffset())
builder.SetForcedBfcBlockOffset(*ConstraintSpace().ForcedBfcBlockOffset());
if (forced_bfc_block_offset)
- builder.SetForcedBfcBlockOffset(forced_bfc_block_offset);
+ builder.SetForcedBfcBlockOffset(*forced_bfc_block_offset);
+
+ if (has_bfc_block_offset && child.IsBlock()) {
+ // Typically we aren't allowed to look at the previous layout result within
+ // a layout algorithm. However this is fine (honest), as it is just a hint
+ // to the child algorithm for where floats should be placed. If it doesn't
+ // have this flag, or gets this estimate wrong, it'll relayout with the
+ // appropriate "forced" BFC block-offset.
+ if (const NGLayoutResult* previous_result =
+ child.GetLayoutBox()->GetCachedLayoutResult()) {
+ const NGConstraintSpace& prev_space =
+ previous_result->GetConstraintSpaceForCaching();
+
+ // To increase the hit-rate we adjust the previous "optimistic"/"forced"
+ // BFC block-offset by how much the child has shifted from the previous
+ // layout.
+ LayoutUnit bfc_block_delta = child_data.bfc_offset_estimate.block_offset -
+ prev_space.BfcOffset().block_offset;
+ if (prev_space.ForcedBfcBlockOffset()) {
+ builder.SetOptimisticBfcBlockOffset(*prev_space.ForcedBfcBlockOffset() +
+ bfc_block_delta);
+ } else if (prev_space.OptimisticBfcBlockOffset()) {
+ builder.SetOptimisticBfcBlockOffset(
+ *prev_space.OptimisticBfcBlockOffset() + bfc_block_delta);
+ }
+ }
+ } else if (ConstraintSpace().OptimisticBfcBlockOffset()) {
+ // Propagate the |NGConstraintSpace::OptimisticBfcBlockOffset| down to our
+ // children.
+ builder.SetOptimisticBfcBlockOffset(
+ *ConstraintSpace().OptimisticBfcBlockOffset());
+ }
// Propagate the |NGConstraintSpace::AncestorHasClearancePastAdjoiningFloats|
// flag down to our children.
@@ -2158,30 +2252,22 @@ NGConstraintSpace NGBlockLayoutAlgorithm::CreateConstraintSpaceForChild(
if (!is_new_fc) {
builder.SetExclusionSpace(exclusion_space_);
- if (!has_bfc_block_offset)
- builder.SetAdjoiningFloatTypes(container_builder_.AdjoiningFloatTypes());
+ if (!has_bfc_block_offset) {
+ builder.SetAdjoiningObjectTypes(
+ container_builder_.AdjoiningObjectTypes());
+ }
}
- LayoutUnit space_available;
if (ConstraintSpace().HasBlockFragmentation()) {
- space_available = ConstraintSpace().FragmentainerSpaceAtBfcStart();
- // If a block establishes a new formatting context we must know our
- // position in the formatting context, and are able to adjust the
+ LayoutUnit new_bfc_block_offset;
+ // If a block establishes a new formatting context, we must know our
+ // position in the formatting context, to be able to adjust the
// fragmentation line.
if (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).
- builder.SetSeparateLeadingFragmentainerMargins(
- ConstraintSpace().HasSeparateLeadingFragmentainerMargins());
- builder.SetFragmentainerBlockSize(
- ConstraintSpace().FragmentainerBlockSize());
- builder.SetFragmentainerSpaceAtBfcStart(space_available);
- builder.SetFragmentationType(ConstraintSpace().BlockFragmentationType());
+ new_bfc_block_offset = child_data.bfc_offset_estimate.block_offset;
+ SetupFragmentation(ConstraintSpace(), new_bfc_block_offset, &builder);
}
+
return builder.ToConstraintSpace();
}
@@ -2256,8 +2342,14 @@ void NGBlockLayoutAlgorithm::PropagateBaselinesFromChildren() {
for (const auto& request : requests) {
switch (request.AlgorithmType()) {
case NGBaselineAlgorithmType::kAtomicInline: {
- if (Node().UseLogicalBottomMarginEdgeForInlineBlockBaseline())
+ if (Node().UseLogicalBottomMarginEdgeForInlineBlockBaseline()) {
+ LayoutUnit block_end = container_builder_.BlockSize();
+ NGBoxStrut margins =
+ ComputeMarginsForSelf(ConstraintSpace(), Style());
+ container_builder_.AddBaseline(request,
+ block_end + margins.block_end);
break;
+ }
const auto& children = container_builder_.Children();
for (auto it = children.rbegin(); it != children.rend(); ++it) {
@@ -2280,10 +2372,8 @@ bool NGBlockLayoutAlgorithm::ResolveBfcBlockOffset(
NGPreviousInflowPosition* previous_inflow_position,
LayoutUnit bfc_block_offset,
base::Optional<LayoutUnit> forced_bfc_block_offset) {
- if (container_builder_.BfcBlockOffset()) {
- DCHECK(unpositioned_floats_.IsEmpty());
+ if (container_builder_.BfcBlockOffset())
return true;
- }
bfc_block_offset = forced_bfc_block_offset.value_or(bfc_block_offset);
@@ -2295,11 +2385,6 @@ bool NGBlockLayoutAlgorithm::ResolveBfcBlockOffset(
if (NeedsAbortOnBfcBlockOffsetChange())
return false;
- // If our BFC block offset was updated, we may have been affected by
- // clearance ourselves. We need to adjust the origin point to accomodate
- // this.
- PositionPendingFloats(bfc_block_offset);
-
// Reset the previous inflow position. Clear the margin strut and set the
// offset to our block-start border edge.
//
@@ -2319,90 +2404,47 @@ bool NGBlockLayoutAlgorithm::NeedsAbortOnBfcBlockOffsetChange() const {
DCHECK(container_builder_.BfcBlockOffset());
if (!abort_when_bfc_block_offset_updated_)
return false;
- // If no previous BFC block offset was set, we need to abort.
- if (!ConstraintSpace().ForcedBfcBlockOffset())
- return true;
- // If the previous BFC block offset matches the new one, we can continue.
- // Otherwise, we need to abort.
+ // If our position differs from our (potentially optimistic) estimate, abort.
return *container_builder_.BfcBlockOffset() !=
- *ConstraintSpace().ForcedBfcBlockOffset();
-}
-
-void NGBlockLayoutAlgorithm::PositionPendingFloats(
- LayoutUnit origin_block_offset) {
- DCHECK(container_builder_.BfcBlockOffset() ||
- ConstraintSpace().ForcedBfcBlockOffset())
- << "The parent BFC block offset should be known here.";
-
- NGBfcOffset origin_bfc_offset = {
- ConstraintSpace().BfcOffset().line_offset +
- border_scrollbar_padding_.LineLeft(ConstraintSpace().Direction()),
- origin_block_offset};
-
- LayoutUnit bfc_block_offset = container_builder_.BfcBlockOffset()
- ? *container_builder_.BfcBlockOffset()
- : *ConstraintSpace().ForcedBfcBlockOffset();
-
- NGBfcOffset bfc_offset = {ConstraintSpace().BfcOffset().line_offset,
- bfc_block_offset};
-
- for (auto& unpositioned_float : unpositioned_floats_) {
- NGPositionedFloat positioned_float = PositionFloat(
- child_available_size_, child_percentage_size_,
- replaced_child_percentage_size_, origin_bfc_offset, &unpositioned_float,
- ConstraintSpace(), Style(), &exclusion_space_);
-
- const auto& physical_fragment =
- positioned_float.layout_result->PhysicalFragment();
- LayoutUnit float_inline_size =
- NGFragment(ConstraintSpace().GetWritingMode(), physical_fragment)
- .InlineSize();
-
- LogicalOffset logical_offset = LogicalFromBfcOffsets(
- positioned_float.bfc_offset, bfc_offset, float_inline_size,
- container_builder_.Size().inline_size, ConstraintSpace().Direction());
-
- container_builder_.AddChild(physical_fragment, logical_offset);
- container_builder_.PropagateBreak(*positioned_float.layout_result);
- }
-
- unpositioned_floats_.Shrink(0);
+ ConstraintSpace().ExpectedBfcBlockOffset();
}
LayoutUnit NGBlockLayoutAlgorithm::CalculateMinimumBlockSize(
const NGMarginStrut& end_margin_strut) {
- if (!Node().GetDocument().InQuirksMode())
+ if (!Node().IsQuirkyAndFillsViewport())
return kIndefiniteSize;
- if (Node().IsDocumentElement() && Node().Style().LogicalHeight().IsAuto()) {
- return ConstraintSpace().AvailableSize().block_size -
- ComputeMarginsForSelf(ConstraintSpace(), Style()).BlockSum();
- }
- if (Node().IsBody() && Node().Style().LogicalHeight().IsAuto()) {
- LayoutUnit body_block_end_margin =
- ComputeMarginsForSelf(ConstraintSpace(), Style()).block_end;
- LayoutUnit margin_sum;
+ if (!Style().LogicalHeight().IsAuto())
+ return kIndefiniteSize;
+
+ NGBoxStrut margins = ComputeMarginsForSelf(ConstraintSpace(), Style());
+ LayoutUnit margin_sum;
+ if (Node().CreatesNewFormattingContext()) {
+ margin_sum = margins.BlockSum();
+ } else {
+ DCHECK(Node().IsBody());
if (container_builder_.BfcBlockOffset()) {
NGMarginStrut body_strut = end_margin_strut;
- body_strut.Append(body_block_end_margin, /* is_quirky */ false);
+ body_strut.Append(margins.block_end, Style().HasMarginAfterQuirk());
margin_sum = *container_builder_.BfcBlockOffset() -
ConstraintSpace().BfcOffset().block_offset +
body_strut.Sum();
} else {
- // end_margin_strut is top margin when we have no BfcOffset.
- margin_sum = end_margin_strut.Sum() + body_block_end_margin;
+ // The |end_margin_strut| is the block-start margin if the body doesn't
+ // have a BFC block-offset.
+ margin_sum = end_margin_strut.Sum() + margins.block_end;
}
- LayoutUnit minimum_block_size =
- ConstraintSpace().AvailableSize().block_size - margin_sum;
- return minimum_block_size.ClampNegativeToZero();
}
- return kIndefiniteSize;
+
+ return (ConstraintSpace().AvailableSize().block_size - margin_sum)
+ .ClampNegativeToZero();
}
-void NGBlockLayoutAlgorithm::PositionOrPropagateListMarker(
+bool NGBlockLayoutAlgorithm::PositionOrPropagateListMarker(
const NGLayoutResult& layout_result,
- LogicalOffset* content_offset) {
+ LogicalOffset* content_offset,
+ NGPreviousInflowPosition* previous_inflow_position) {
// If this is not a list-item, propagate unpositioned list markers to
// ancestors.
if (!node_.IsListItem()) {
@@ -2411,7 +2453,7 @@ void NGBlockLayoutAlgorithm::PositionOrPropagateListMarker(
container_builder_.SetUnpositionedListMarker(
layout_result.UnpositionedListMarker());
}
- return;
+ return true;
}
// If this is a list item, add the unpositioned list marker as a child.
@@ -2419,44 +2461,91 @@ void NGBlockLayoutAlgorithm::PositionOrPropagateListMarker(
if (!list_marker) {
list_marker = container_builder_.UnpositionedListMarker();
if (!list_marker)
- return;
+ return true;
container_builder_.SetUnpositionedListMarker(NGUnpositionedListMarker());
}
- if (list_marker.AddToBox(ConstraintSpace(), Style().GetFontBaseline(),
- layout_result.PhysicalFragment(), content_offset,
- &container_builder_, border_scrollbar_padding_))
- return;
+
+ NGLineHeightMetrics content_metrics;
+ const NGConstraintSpace& space = ConstraintSpace();
+ const NGPhysicalFragment& content = layout_result.PhysicalFragment();
+ FontBaseline baseline_type = Style().GetFontBaseline();
+ if (list_marker.CanAddToBox(space, baseline_type, content,
+ &content_metrics)) {
+ // TODO: We are reusing the ConstraintSpace for LI here. It works well for
+ // now because authors cannot style list-markers currently. If we want to
+ // support `::marker` pseudo, we need to create ConstraintSpace for marker
+ // separately.
+ scoped_refptr<const NGLayoutResult> marker_layout_result =
+ list_marker.Layout(space, container_builder_.Style(), baseline_type);
+ DCHECK(marker_layout_result);
+ // If the BFC block-offset of li is still not resolved, resolved it now.
+ if (!container_builder_.BfcBlockOffset() &&
+ marker_layout_result->BfcBlockOffset()) {
+ // TODO: Currently the margin-top of marker is always zero. To support
+ // `::marker` pseudo, we should count marker's margin-top in.
+#if DCHECK_IS_ON()
+ list_marker.CheckMargin();
+#endif
+ if (!ResolveBfcBlockOffset(previous_inflow_position))
+ return false;
+ }
+
+ list_marker.AddToBox(space, baseline_type, content,
+ border_scrollbar_padding_, content_metrics,
+ *marker_layout_result, content_offset,
+ &container_builder_);
+ return true;
+ }
// If the list marker could not be positioned against this child because it
// does not have the baseline to align to, keep it as unpositioned and try
// the next child.
container_builder_.SetUnpositionedListMarker(list_marker);
+ return true;
}
-void NGBlockLayoutAlgorithm::PositionListMarkerWithoutLineBoxes() {
+bool NGBlockLayoutAlgorithm::PositionListMarkerWithoutLineBoxes(
+ NGPreviousInflowPosition* previous_inflow_position) {
DCHECK(node_.IsListItem());
DCHECK(container_builder_.UnpositionedListMarker());
+ NGUnpositionedListMarker list_marker =
+ container_builder_.UnpositionedListMarker();
+ const NGConstraintSpace& space = ConstraintSpace();
+ FontBaseline baseline_type = Style().GetFontBaseline();
+ // Layout the list marker.
+ scoped_refptr<const NGLayoutResult> marker_layout_result =
+ list_marker.Layout(space, container_builder_.Style(), baseline_type);
+ DCHECK(marker_layout_result);
+ // If the BFC block-offset of li is still not resolved, resolve it now.
+ if (!container_builder_.BfcBlockOffset() &&
+ marker_layout_result->BfcBlockOffset()) {
+ // TODO: Currently the margin-top of marker is always zero. To support
+ // `::marker` pseudo, we should count marker's margin-top in.
+#if DCHECK_IS_ON()
+ list_marker.CheckMargin();
+#endif
+ if (!ResolveBfcBlockOffset(previous_inflow_position))
+ return false;
+ }
// Position the list marker without aligning to line boxes.
- LayoutUnit marker_block_size =
- container_builder_.UnpositionedListMarker().AddToBoxWithoutLineBoxes(
- ConstraintSpace(), Style().GetFontBaseline(), &container_builder_);
+ LayoutUnit marker_block_size = list_marker.AddToBoxWithoutLineBoxes(
+ space, baseline_type, *marker_layout_result, &container_builder_);
container_builder_.SetUnpositionedListMarker(NGUnpositionedListMarker());
// Whether the list marker should affect the block size or not is not
// well-defined, but 3 out of 4 impls do.
// https://github.com/w3c/csswg-drafts/issues/2418
//
- // TODO(kojii): Since this makes this block non self-collapsing, it's
- // probably better to resolve BFC block-offset if not done yet, but that
- // involves additional complexity without knowing how much this is needed.
- // For now, include the marker into the block-size only if BFC was resolved.
+ // The BFC block-offset has been resolved after layout marker. We'll always
+ // include the marker into the block-size.
if (container_builder_.BfcBlockOffset()) {
intrinsic_block_size_ = std::max(marker_block_size, intrinsic_block_size_);
container_builder_.SetIntrinsicBlockSize(intrinsic_block_size_);
container_builder_.SetBlockSize(
std::max(marker_block_size, container_builder_.Size().block_size));
}
+ return true;
}
} // namespace blink
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 70db5f9ab8a..12ab493218d 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
@@ -66,11 +66,7 @@ class CORE_EXPORT NGBlockLayoutAlgorithm
inline scoped_refptr<const NGLayoutResult> Layout(
NGInlineChildLayoutContext* inline_child_layout_context);
- scoped_refptr<const NGLayoutResult> FinishLayout(
- NGPreviousInflowPosition*,
- LogicalSize border_box_size,
- const NGBoxStrut& borders,
- const NGBoxStrut& scrollbars);
+ scoped_refptr<const NGLayoutResult> FinishLayout(NGPreviousInflowPosition*);
// Return the BFC block offset of this block.
LayoutUnit BfcBlockOffset() const {
@@ -288,14 +284,15 @@ class CORE_EXPORT NGBlockLayoutAlgorithm
// need to abort layout.
bool NeedsAbortOnBfcBlockOffsetChange() const;
- // Positions pending floats starting from {@origin_block_offset}.
- void PositionPendingFloats(LayoutUnit origin_block_offset);
-
// Positions a list marker for the specified block content.
- void PositionOrPropagateListMarker(const NGLayoutResult&, LogicalOffset*);
+ // Return false if it aborts when resolving BFC block offset for LI.
+ bool PositionOrPropagateListMarker(const NGLayoutResult&,
+ LogicalOffset*,
+ NGPreviousInflowPosition*);
// Positions a list marker when the block does not have any line boxes.
- void PositionListMarkerWithoutLineBoxes();
+ // Return false if it aborts when resolving BFC block offset for LI.
+ bool PositionListMarkerWithoutLineBoxes(NGPreviousInflowPosition*);
// Calculates logical offset for the current fragment using either {@code
// intrinsic_block_size_} when the fragment doesn't know it's offset or
@@ -344,7 +341,6 @@ class CORE_EXPORT NGBlockLayoutAlgorithm
bool has_processed_first_child_ = false;
NGExclusionSpace exclusion_space_;
- Vector<NGUnpositionedFloat, 1> unpositioned_floats_;
};
} // namespace blink
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 986c3484c6f..52f95e1655e 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
@@ -1361,21 +1361,15 @@ TEST_F(NGBlockLayoutAlgorithmTest, PositionFloatInsideEmptyBlocks) {
// 35 = empty1's padding(20) + empty2's padding(15)
EXPECT_THAT(offset.left, LayoutUnit(35));
- const auto* linebox_fragment = empty2_fragment->Children()[0].fragment;
-
- offset =
- To<NGPhysicalLineBoxFragment>(linebox_fragment)->Children()[0].offset;
- // The floats are positioned outside the line-box as the line-box is
- // "avoiding" these floats.
- // inline -35 = inline-size of left-float (including margins).
+ offset = empty2_fragment->Children()[0].offset;
+ // inline 25 = left float's margin(10) + empty2's padding(15).
// block 10 = left float's margin
- EXPECT_THAT(offset, PhysicalOffset(-35, 10));
+ EXPECT_THAT(offset, PhysicalOffset(25, 10));
- offset =
- To<NGPhysicalLineBoxFragment>(linebox_fragment)->Children()[1].offset;
- // inline offset 90 = right float's margin(10) + right float offset(80)
+ offset = empty2_fragment->Children()[1].offset;
+ // inline offset 140 = right float's margin(10) + right float offset(140)
// block offset 15 = right float's margin
- LayoutUnit right_float_offset = LayoutUnit(80);
+ LayoutUnit right_float_offset = LayoutUnit(140);
EXPECT_THAT(offset, PhysicalOffset(LayoutUnit(10) + right_float_offset,
LayoutUnit(15)));
@@ -2275,10 +2269,7 @@ TEST_F(NGBlockLayoutAlgorithmTest, FloatFragmentationOrthogonalFlows) {
EXPECT_EQ(PhysicalSize(150, 60), fragment->Size());
ASSERT_TRUE(!fragment->BreakToken() || fragment->BreakToken()->IsFinished());
- const auto* linebox =
- To<NGPhysicalBoxFragment>(fragment.get())->Children()[0].fragment;
- const auto* float2 =
- To<NGPhysicalLineBoxFragment>(linebox)->Children()[1].fragment;
+ const auto* float2 = fragment->Children()[1].fragment;
// float2 should only have one fragment.
EXPECT_EQ(PhysicalSize(60, 200), float2->Size());
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm_utils.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm_utils.cc
index 4b3ad59b933..3841774a43f 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm_utils.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm_utils.cc
@@ -43,6 +43,10 @@ LayoutUnit CalculateOutOfFlowStaticInlineLevelOffset(
else
inline_offset += opportunity.rect.InlineSize() - line_offset;
+ // Adjust for the text-indent.
+ inline_offset += MinimumValueForLength(container_style.TextIndent(),
+ child_available_inline_size);
+
return inline_offset;
}
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 533c2b01271..15980a27bae 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
@@ -43,7 +43,7 @@
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.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/allocator/allocator.h"
namespace blink {
@@ -66,13 +66,13 @@ inline LayoutMultiColumnFlowThread* GetFlowThread(const LayoutBox& box) {
template <typename Algorithm, typename Callback>
NOINLINE void CreateAlgorithmAndRun(const NGLayoutAlgorithmParams& params,
const Callback& callback) {
- std::unique_ptr<Algorithm> algorithm = std::make_unique<Algorithm>(params);
- callback(algorithm.get());
+ Algorithm algorithm(params);
+ callback(&algorithm);
}
-inline void DetermineAlgorithmAndRun(
- const NGLayoutAlgorithmParams& params,
- const std::function<void(NGLayoutAlgorithmOperations*)>& callback) {
+template <typename Callback>
+NOINLINE void DetermineAlgorithmAndRun(const NGLayoutAlgorithmParams& params,
+ const Callback& callback) {
const ComputedStyle& style = params.node.Style();
const LayoutBox& box = *params.node.GetLayoutBox();
if (box.IsLayoutNGFlexibleBox()) {
@@ -232,7 +232,17 @@ scoped_refptr<const NGLayoutResult> NGBlockNode::Layout(
UpdateShapeOutsideInfoIfNeeded(
*layout_result, constraint_space.PercentageResolutionInlineSize());
- return layout_result;
+ // Even if we can reuse the result, we may still need to recalculate our
+ // overflow. TODO(crbug.com/919415): Explain why.
+ if (box_->NeedsLayoutOverflowRecalc())
+ box_->RecalcLayoutOverflow();
+
+ // Return the cached result unless we're marked for layout. We may have
+ // added or removed scrollbars during overflow recalculation, which may have
+ // marked us for layout. In that case the cached result is unusable, and we
+ // need to re-lay out now.
+ if (!box_->NeedsLayout())
+ return layout_result;
}
if (!fragment_geometry) {
@@ -266,24 +276,33 @@ scoped_refptr<const NGLayoutResult> NGBlockNode::Layout(
// be used for comparison with their after layout size.
NGBoxStrut before_layout_scrollbars =
ComputeScrollbars(constraint_space, *this);
+ bool before_layout_preferred_logical_widths_dirty =
+ box_->PreferredLogicalWidthsDirty();
if (!layout_result)
layout_result = LayoutWithAlgorithm(params);
FinishLayout(block_flow, constraint_space, break_token, layout_result);
- if (before_layout_scrollbars != ComputeScrollbars(constraint_space, *this)) {
- // If our scrollbars have changed, we need to relayout because either:
- // - Our size has changed (if shrinking to fit), or
- // - Space available to our children has changed.
- // This mirrors legacy code in PaintLayerScrollableArea::UpdateAfterLayout.
- // TODO(cbiesinger): It seems that we should also check if
- // PreferredLogicalWidthsDirty() has changed from false to true during
- // layout, so that we correctly size ourselves when shrinking to fit
- // and a child gained a vertical scrollbar. However, no test fails
- // without that check.
+ // We may need to relayout if:
+ // - Our scrollbars have changed causing our size to change (shrink-to-fit)
+ // or the available space to our children changing.
+ // - A child changed scrollbars causing our size to change (shrink-to-fit).
+ //
+ // This mirrors legacy code in PaintLayerScrollableArea::UpdateAfterLayout.
+ if ((before_layout_scrollbars !=
+ ComputeScrollbars(constraint_space, *this)) ||
+ (!before_layout_preferred_logical_widths_dirty &&
+ box_->PreferredLogicalWidthsDirty())) {
PaintLayerScrollableArea::FreezeScrollbarsScope freeze_scrollbars;
+#if DCHECK_IS_ON()
+ // Ensure turning on/off scrollbars only once at most, when we call
+ // |LayoutWithAlgorithm| recursively.
+ DEFINE_STATIC_LOCAL(HashSet<LayoutBox*>, scrollbar_changed, ());
+ DCHECK(scrollbar_changed.insert(box_).is_new_entry);
+#endif
+
// Must not call SetNeedsLayout in intermediate layout. If we do,
// the NeedsLayout flag might not be cleared. crbug.com/967361
DCHECK(!constraint_space.IsIntermediateLayout() || box_->NeedsLayout());
@@ -296,6 +315,10 @@ scoped_refptr<const NGLayoutResult> NGBlockNode::Layout(
CalculateInitialFragmentGeometry(constraint_space, *this);
layout_result = LayoutWithAlgorithm(params);
FinishLayout(block_flow, constraint_space, break_token, layout_result);
+
+#if DCHECK_IS_ON()
+ scrollbar_changed.erase(box_);
+#endif
}
// We always need to update the ShapeOutsideInfo even if the layout is
@@ -322,7 +345,8 @@ scoped_refptr<const NGLayoutResult> NGBlockNode::SimplifiedLayout() {
if (!box_->NeedsLayout())
return previous_result;
- DCHECK(box_->NeedsSimplifiedLayoutOnly());
+ DCHECK(box_->NeedsSimplifiedLayoutOnly() ||
+ box_->LayoutBlockedByDisplayLock(DisplayLockContext::kChildren));
// Perform layout on ourselves using the previous constraint space.
const NGConstraintSpace space(
@@ -405,8 +429,9 @@ void NGBlockNode::FinishLayout(
box_->SetCachedLayoutResult(*layout_result, break_token);
if (block_flow) {
- NGLayoutInputNode first_child = FirstChild();
- bool has_inline_children = first_child && first_child.IsInline();
+ auto* child = GetLayoutObjectForFirstChildNode(block_flow);
+ bool has_inline_children =
+ child && AreNGBlockFlowChildrenInline(block_flow);
// Don't consider display-locked objects as having any children.
if (has_inline_children &&
@@ -576,11 +601,23 @@ MinMaxSize NGBlockNode::ComputeMinMaxSizeFromLegacy(
NGLayoutInputNode NGBlockNode::NextSibling() const {
LayoutObject* next_sibling = GetLayoutObjectForNextSiblingNode(box_);
- if (next_sibling) {
- DCHECK(!next_sibling->IsInline());
- return NGBlockNode(ToLayoutBox(next_sibling));
+
+ // We may have some LayoutInline(s) still within the tree (due to treating
+ // inline-level floats and/or OOF-positioned nodes as block-level), we need
+ // to skip them and clear layout.
+ while (next_sibling && next_sibling->IsInline()) {
+ // TODO(layout-dev): Clearing needs-layout within this accessor is an
+ // unexpected side-effect. There may be additional invalidations that need
+ // to be performed.
+ DCHECK(next_sibling->IsText());
+ next_sibling->ClearNeedsLayout();
+ next_sibling = next_sibling->NextSibling();
}
- return nullptr;
+
+ if (!next_sibling)
+ return nullptr;
+
+ return NGBlockNode(ToLayoutBox(next_sibling));
}
NGLayoutInputNode NGBlockNode::FirstChild() const {
@@ -588,8 +625,33 @@ NGLayoutInputNode NGBlockNode::FirstChild() const {
auto* child = GetLayoutObjectForFirstChildNode(block);
if (!child)
return nullptr;
- if (AreNGBlockFlowChildrenInline(block))
- return NGInlineNode(To<LayoutBlockFlow>(block));
+ if (!AreNGBlockFlowChildrenInline(block))
+ return NGBlockNode(ToLayoutBox(child));
+
+ NGInlineNode inline_node(To<LayoutBlockFlow>(block));
+ if (!inline_node.IsBlockLevel())
+ return inline_node;
+
+ // At this point we have a node which is empty or only has floats and
+ // OOF-positioned nodes. We treat all children as block-level, even though
+ // they are within a inline-level LayoutBlockFlow.
+
+ // We may have some LayoutInline(s) still within the tree (due to treating
+ // inline-level floats and/or OOF-positioned nodes as block-level), we need
+ // to skip them and clear layout.
+ while (child && child->IsInline()) {
+ // TODO(layout-dev): Clearing needs-layout within this accessor is an
+ // unexpected side-effect. There may be additional invalidations that need
+ // to be performed.
+ DCHECK(child->IsText());
+ child->ClearNeedsLayout();
+ child = child->NextSibling();
+ }
+
+ if (!child)
+ return nullptr;
+
+ DCHECK(child->IsFloatingOrOutOfFlowPositioned());
return NGBlockNode(ToLayoutBox(child));
}
@@ -612,7 +674,7 @@ bool NGBlockNode::CanUseNewLayout(const LayoutBox& box) {
DCHECK(RuntimeEnabledFeatures::LayoutNGEnabled());
if (box.ForceLegacyLayout())
return false;
- return box.IsLayoutNGMixin() || box.IsLayoutNGFlexibleBox();
+ return box.IsLayoutNGMixin();
}
bool NGBlockNode::CanUseNewLayout() const {
@@ -621,7 +683,7 @@ bool NGBlockNode::CanUseNewLayout() const {
String NGBlockNode::ToString() const {
return String::Format("NGBlockNode: '%s'",
- GetLayoutBox()->DebugName().Ascii().data());
+ GetLayoutBox()->DebugName().Ascii().c_str());
}
void NGBlockNode::CopyFragmentDataToLayoutBox(
@@ -725,14 +787,19 @@ void NGBlockNode::CopyFragmentDataToLayoutBox(
}
box_->UpdateAfterLayout();
- // We should only clear the child layout bits if display-locking has not
- // prevented us from laying the children out.
- box_->ClearNeedsLayout(
- !box_->LayoutBlockedByDisplayLock(DisplayLockContext::kChildren));
+ box_->ClearNeedsLayout();
// Overflow computation depends on this being set.
if (LIKELY(block_flow))
block_flow->UpdateIsSelfCollapsing();
+
+ // We should notify the display lock that we've done layout on self, and if
+ // it's not blocked, on children.
+ if (auto* context = box_->GetDisplayLockContext()) {
+ context->DidLayout(DisplayLockContext::kSelf);
+ if (!LayoutBlockedByDisplayLock(DisplayLockContext::kChildren))
+ context->DidLayout(DisplayLockContext::kChildren);
+ }
}
void NGBlockNode::PlaceChildrenInLayoutBox(
@@ -949,11 +1016,14 @@ scoped_refptr<const NGLayoutResult> NGBlockNode::RunLegacyLayout(
DCHECK(!box_->IsLayoutBlock() ||
To<LayoutBlock>(box_)->CreatesNewFormattingContext());
+ // We cannot enter legacy layout for something fragmentable if we're inside an
+ // NG block fragmentation context. LayoutNG and legacy block fragmentation
+ // cannot cooperate within the same fragmentation context.
+ DCHECK(!constraint_space.HasBlockFragmentation() ||
+ box_->GetPaginationBreakability() == LayoutBox::kForbidBreaks);
+
scoped_refptr<const NGLayoutResult> layout_result =
- box_->IsOutOfFlowPositioned()
- ? CachedLayoutResultForOutOfFlowPositioned(
- constraint_space.PercentageResolutionSize())
- : box_->GetCachedLayoutResult();
+ box_->GetCachedLayoutResult();
// We need to force a layout on the child if the constraint space given will
// change the layout.
@@ -1004,6 +1074,7 @@ scoped_refptr<const NGLayoutResult> NGBlockNode::RunLegacyLayout(
// Using |LayoutObject::LayoutIfNeeded| save us a little bit of overhead,
// compared to |LayoutObject::ForceLayout|.
DCHECK(!box_->IsLayoutNGMixin());
+ bool needed_layout = box_->NeedsLayout();
if (box_->NeedsLayout() && !needs_force_relayout)
box_->LayoutIfNeeded();
else
@@ -1031,6 +1102,20 @@ scoped_refptr<const NGLayoutResult> NGBlockNode::RunLegacyLayout(
layout_result = builder.ToBoxFragment();
box_->SetCachedLayoutResult(*layout_result, /* break_token */ nullptr);
+
+ // If |SetCachedLayoutResult| did not update cached |LayoutResult|,
+ // |NeedsLayout()| flag should not be cleared.
+ if (needed_layout) {
+ if (constraint_space.IsIntermediateLayout()) {
+ DCHECK_NE(layout_result, box_->GetCachedLayoutResult());
+ box_->SetNeedsLayout(layout_invalidation_reason::kUnknown);
+ } else if (layout_result != box_->GetCachedLayoutResult()) {
+ // TODO(kojii): If we failed to update CachedLayoutResult for other
+ // reasons, we'd like to review it.
+ NOTREACHED();
+ box_->SetNeedsLayout(layout_invalidation_reason::kUnknown);
+ }
+ }
} else if (layout_result) {
// OOF-positioned nodes have a two-tier cache, and their layout results
// must always contain the correct percentage resolution size.
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 89b39fa7356..06999d98cfe 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
@@ -92,6 +92,23 @@ class CORE_EXPORT NGBlockNode final : public NGLayoutInputNode {
bool IsInlineLevel() const;
bool IsAtomicInlineLevel() const;
+ // Returns true if this node should fill the viewport.
+ // This occurs when we are in quirks-mode and we are *not* OOF-positioned,
+ // floating, or inline-level.
+ //
+ // https://quirks.spec.whatwg.org/#the-body-element-fills-the-html-element-quirk
+ bool IsQuirkyAndFillsViewport() const {
+ if (!GetDocument().InQuirksMode())
+ return false;
+ if (IsOutOfFlowPositioned())
+ return false;
+ if (IsFloating())
+ return false;
+ if (IsAtomicInlineLevel())
+ return false;
+ return (IsDocumentElement() || IsBody());
+ }
+
// CSS defines certain cases to synthesize inline block baselines from box.
// See comments in UseLogicalBottomMarginEdgeForInlineBlockBaseline().
bool UseLogicalBottomMarginEdgeForInlineBlockBaseline() const;
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_block_node_test.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_block_node_test.cc
index 52327cf7a2e..8190b808e58 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_block_node_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_block_node_test.cc
@@ -12,6 +12,21 @@ namespace {
using NGBlockNodeForTest = NGLayoutTest;
+TEST_F(NGBlockNodeForTest, IsFloatingForOutOfFlowFloating) {
+ SetBodyInnerHTML(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ #container {
+ float: left;
+ position: absolute;
+ }
+ </style>
+ <div id=container></div>
+ )HTML");
+ NGBlockNode container(ToLayoutBox(GetLayoutObjectByElementId("container")));
+ EXPECT_FALSE(container.IsFloating());
+}
+
TEST_F(NGBlockNodeForTest, ChildInlineAndBlock) {
SetBodyInnerHTML(R"HTML(
<!DOCTYPE html>
@@ -97,7 +112,7 @@ TEST_F(NGBlockNodeForTest, ChildFloatOnly) {
)HTML");
NGBlockNode container(ToLayoutBox(GetLayoutObjectByElementId("container")));
NGLayoutInputNode child1 = container.FirstChild();
- EXPECT_TRUE(child1 && child1.IsInline());
+ EXPECT_TRUE(child1 && child1.IsBlock());
NGLayoutInputNode child2 = child1.NextSibling();
EXPECT_EQ(child2, nullptr);
}
@@ -114,7 +129,7 @@ TEST_F(NGBlockNodeForTest, ChildFloatWithSpaces) {
)HTML");
NGBlockNode container(ToLayoutBox(GetLayoutObjectByElementId("container")));
NGLayoutInputNode child1 = container.FirstChild();
- EXPECT_TRUE(child1 && child1.IsInline());
+ EXPECT_TRUE(child1 && child1.IsBlock());
NGLayoutInputNode child2 = child1.NextSibling();
EXPECT_EQ(child2, nullptr);
}
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 53be16265c6..d282938bb87 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
@@ -61,13 +61,6 @@ class CORE_EXPORT NGBoxFragment final : public NGFragment {
TextDirection direction_;
};
-template <>
-struct DowncastTraits<NGBoxFragment> {
- static bool AllowFrom(const NGFragment& fragment) {
- return fragment.Type() == NGPhysicalFragment::kFragmentBox;
- }
-};
-
} // namespace blink
#endif // NGBoxFragment_h
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
index 21b54f6c1d1..29d36cefa97 100644
--- 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
@@ -139,67 +139,25 @@ NGBoxFragmentBuilder& NGBoxFragmentBuilder::AddBreakBeforeLine(
return *this;
}
-NGBoxFragmentBuilder& NGBoxFragmentBuilder::PropagateBreak(
- const NGLayoutResult& child_layout_result) {
- if (LIKELY(!has_block_fragmentation_))
- return *this;
- 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 NGPhysicalContainerFragment& child_fragment) {
- DCHECK(has_block_fragmentation_);
- if (!did_break_) {
- const auto* token = child_fragment.BreakToken();
- did_break_ = token && !token->IsFinished();
- }
+NGBoxFragmentBuilder& NGBoxFragmentBuilder::AddResult(
+ const NGLayoutResult& child_layout_result,
+ const LogicalOffset offset,
+ const LayoutInline* inline_container) {
+ const auto& fragment = child_layout_result.PhysicalFragment();
+ AddChild(fragment, offset, inline_container);
+ if (fragment.IsBox())
+ PropagateBreak(child_layout_result);
return *this;
}
void NGBoxFragmentBuilder::AddOutOfFlowLegacyCandidate(
NGBlockNode node,
- const NGStaticPosition& static_position,
+ const NGLogicalStaticPosition& static_position,
const LayoutInline* inline_container) {
- DCHECK_GE(InlineSize(), LayoutUnit());
- DCHECK_GE(BlockSize(), LayoutUnit());
-
- NGOutOfFlowPositionedDescendant descendant(
+ oof_positioned_candidates_.emplace_back(
node, static_position,
inline_container ? ToLayoutInline(inline_container->ContinuationRoot())
: nullptr);
- // Need 0,0 physical coordinates as child offset. Because offset
- // is stored as logical, must convert physical 0,0 to logical.
- LogicalOffset zero_offset;
- switch (GetWritingMode()) {
- case WritingMode::kHorizontalTb:
- if (IsLtr(Direction()))
- zero_offset = LogicalOffset();
- else
- zero_offset = LogicalOffset(InlineSize(), LayoutUnit());
- break;
- case WritingMode::kVerticalRl:
- case WritingMode::kSidewaysRl:
- if (IsLtr(Direction()))
- zero_offset = LogicalOffset(LayoutUnit(), BlockSize());
- else
- zero_offset = LogicalOffset(InlineSize(), BlockSize());
- break;
- case WritingMode::kVerticalLr:
- case WritingMode::kSidewaysLr:
- if (IsLtr(Direction()))
- zero_offset = LogicalOffset();
- else
- zero_offset = LogicalOffset(InlineSize(), LayoutUnit());
- break;
- }
- oof_positioned_candidates_.push_back(
- NGOutOfFlowPositionedCandidate{descendant, zero_offset});
}
NGPhysicalFragment::NGBoxType NGBoxFragmentBuilder::BoxType() const {
@@ -212,10 +170,13 @@ NGPhysicalFragment::NGBoxType NGBoxFragmentBuilder::BoxType() const {
return NGPhysicalFragment::NGBoxType::kFloating;
if (layout_object_->IsOutOfFlowPositioned())
return NGPhysicalFragment::NGBoxType::kOutOfFlowPositioned;
- if (layout_object_->IsAtomicInlineLevel())
- return NGPhysicalFragment::NGBoxType::kAtomicInline;
- if (layout_object_->IsInline())
+ if (layout_object_->IsInline()) {
+ // Check |IsAtomicInlineLevel()| after |IsInline()| because |LayoutReplaced|
+ // sets |IsAtomicInlineLevel()| even when it's block-level. crbug.com/567964
+ if (layout_object_->IsAtomicInlineLevel())
+ return NGPhysicalFragment::NGBoxType::kAtomicInline;
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";
@@ -238,6 +199,21 @@ EBreakBetween NGBoxFragmentBuilder::JoinedBreakBetweenValue(
return JoinFragmentainerBreakValues(previous_break_after_, break_before);
}
+NGBoxFragmentBuilder& NGBoxFragmentBuilder::PropagateBreak(
+ const NGLayoutResult& child_layout_result) {
+ if (LIKELY(!has_block_fragmentation_))
+ return *this;
+ if (!did_break_) {
+ const auto* token = child_layout_result.PhysicalFragment().BreakToken();
+ did_break_ = token && !token->IsFinished();
+ }
+ if (child_layout_result.HasForcedBreak())
+ SetHasForcedBreak();
+ else
+ PropagateSpaceShortage(child_layout_result.MinimalSpaceShortage());
+ return *this;
+}
+
scoped_refptr<const NGLayoutResult> NGBoxFragmentBuilder::ToBoxFragment(
WritingMode block_or_line_writing_mode) {
if (UNLIKELY(node_ && has_block_fragmentation_)) {
@@ -258,6 +234,7 @@ scoped_refptr<const NGLayoutResult> NGBoxFragmentBuilder::ToBoxFragment(
scoped_refptr<const NGPhysicalBoxFragment> fragment =
NGPhysicalBoxFragment::Create(this, block_or_line_writing_mode);
+ fragment->CheckType();
return base::AdoptRef(new NGLayoutResult(std::move(fragment), this));
}
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
index 29ffa6702be..e529b37e331 100644
--- 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
@@ -14,7 +14,7 @@
#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/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
namespace blink {
@@ -95,12 +95,12 @@ class CORE_EXPORT NGBoxFragmentBuilder final
// 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 NGPhysicalContainerFragment&);
+ NGBoxFragmentBuilder& AddResult(const NGLayoutResult&,
+ const LogicalOffset,
+ const LayoutInline* = nullptr);
void AddOutOfFlowLegacyCandidate(NGBlockNode,
- const NGStaticPosition&,
+ const NGLogicalStaticPosition&,
const LayoutInline* inline_container);
// Set how much of the block size we've used so far for this box.
@@ -232,6 +232,9 @@ class CORE_EXPORT NGBoxFragmentBuilder final
#endif
private:
+ // Update whether we have fragmented in this flow.
+ NGBoxFragmentBuilder& PropagateBreak(const NGLayoutResult&);
+
scoped_refptr<const NGLayoutResult> ToBoxFragment(WritingMode);
const NGFragmentGeometry* initial_fragment_geometry_ = nullptr;
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 3d272e1a1a7..a810bfe5878 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
@@ -60,7 +60,7 @@ void NGBreakToken::ShowBreakTokenTree() const {
StringBuilder string_builder;
string_builder.Append(".:: LayoutNG Break Token Tree ::.\n");
AppendBreakTokenToString(this, &string_builder);
- fprintf(stderr, "%s\n", string_builder.ToString().Utf8().data());
+ fprintf(stderr, "%s\n", string_builder.ToString().Utf8().c_str());
}
#endif // DCHECK_IS_ON()
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 53c7163688b..24b26541d1c 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
@@ -7,7 +7,7 @@
#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/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
namespace blink {
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 d2d3a04034a..c91c05b42e0 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
@@ -9,23 +9,21 @@
#include "third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.h"
#include "third_party/blink/renderer/core/layout/ng/ng_length_utils.h"
#include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h"
+#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
namespace blink {
namespace {
-class NGColumnLayoutAlgorithmTest : public NGBaseLayoutAlgorithmTest {
+class NGColumnLayoutAlgorithmTest
+ : public NGBaseLayoutAlgorithmTest,
+ private ScopedLayoutNGBlockFragmentationForTest {
protected:
+ NGColumnLayoutAlgorithmTest()
+ : ScopedLayoutNGBlockFragmentationForTest(true) {}
+
void SetUp() override {
NGBaseLayoutAlgorithmTest::SetUp();
style_ = ComputedStyle::Create();
- was_block_fragmentation_enabled_ =
- RuntimeEnabledFeatures::LayoutNGBlockFragmentationEnabled();
- RuntimeEnabledFeatures::SetLayoutNGBlockFragmentationEnabled(true);
- }
-
- void TearDown() override {
- RuntimeEnabledFeatures::SetLayoutNGBlockFragmentationEnabled(
- was_block_fragmentation_enabled_);
}
scoped_refptr<const NGPhysicalBoxFragment> RunBlockLayoutAlgorithm(
@@ -52,7 +50,6 @@ class NGColumnLayoutAlgorithmTest : public NGBaseLayoutAlgorithmTest {
}
scoped_refptr<ComputedStyle> style_;
- bool was_block_fragmentation_enabled_ = false;
};
TEST_F(NGColumnLayoutAlgorithmTest, EmptyMulticol) {
@@ -2923,5 +2920,31 @@ TEST_F(NGColumnLayoutAlgorithmTest, NestedLimitedHeight) {
EXPECT_EQ(expectation, dump);
}
+TEST_F(NGColumnLayoutAlgorithmTest, AbsposFitsInOneColumn) {
+ SetBodyInnerHTML(R"HTML(
+ <div id="container">
+ <div style="columns:3; width:320px; height:100px; column-gap:10px; column-fill:auto;">
+ <div style="position:relative; width:222px; height:250px;">
+ <div style="position:absolute; width:111px; height:50px;"></div>
+ </div>
+ </div>
+ </div>
+ )HTML");
+
+ String dump = DumpFragmentTree(GetElementById("container"));
+ String expectation = R"DUMP(.:: LayoutNG Physical Fragment Tree ::.
+ offset:unplaced size:1000x100
+ offset:0,0 size:320x100
+ offset:0,0 size:100x100
+ offset:0,0 size:222x100
+ offset:0,0 size:111x50
+ offset:110,0 size:100x100
+ offset:0,0 size:222x100
+ offset:220,0 size:100x50
+ offset:0,0 size:222x50
+)DUMP";
+ EXPECT_EQ(expectation, dump);
+}
+
} // anonymous namespace
} // namespace blink
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 bc8d8bbb5f7..6b7084eaa4b 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
@@ -102,12 +102,12 @@ NGConstraintSpace NGConstraintSpace::CreateFromLayoutObject(
String NGConstraintSpace::ToString() const {
return String::Format("Offset: %s,%s Size: %sx%s Clearance: %s",
- bfc_offset_.line_offset.ToString().Ascii().data(),
- bfc_offset_.block_offset.ToString().Ascii().data(),
- AvailableSize().inline_size.ToString().Ascii().data(),
- AvailableSize().block_size.ToString().Ascii().data(),
+ bfc_offset_.line_offset.ToString().Ascii().c_str(),
+ bfc_offset_.block_offset.ToString().Ascii().c_str(),
+ AvailableSize().inline_size.ToString().Ascii().c_str(),
+ AvailableSize().block_size.ToString().Ascii().c_str(),
HasClearanceOffset()
- ? ClearanceOffset().ToString().Ascii().data()
+ ? ClearanceOffset().ToString().Ascii().c_str()
: "none");
}
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 0464c66e683..965a32bdb91 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
@@ -31,6 +31,19 @@ enum NGFragmentationType {
kFragmentRegion
};
+// "adjoining" objects (either floats or inline-level OOF-positioned nodes) are
+// used to indicate that a particular node might need a relayout once its BFC
+// block-offset is resvoled. E.g. their position depends on the final BFC
+// block-offset being known.
+enum NGAdjoiningObjectTypeValue {
+ kAdjoiningNone = 0b000,
+ kAdjoiningFloatLeft = 0b001,
+ kAdjoiningFloatRight = 0b010,
+ kAdjoiningFloatBoth = 0b011,
+ kAdjoiningInlineOutOfFlow = 0b100
+};
+typedef int NGAdjoiningObjectTypes;
+
// Tables have two passes, a "measure" phase (for determining the table row
// height), and a "layout" phase.
// See: https://drafts.csswg.org/css-tables-3/#row-layout
@@ -361,13 +374,13 @@ class CORE_EXPORT NGConstraintSpace final {
}
// If present, and the current layout hasn't resolved its BFC block-offset
- // yet (see BfcOffset), the layout should position all of its unpositioned
- // floats at this offset.
+ // yet (see BfcOffset), the layout should position all of its floats at this
+ // offset.
//
// This value is present if:
// - An ancestor had clearance past adjoining floats. In this case this
// value is calculated ahead of time.
- // - A second layout pass is required as there were unpositioned floats
+ // - A second layout pass is required as there were adjoining-floats
// within the tree, and an arbitrary sibling determined their BFC
// block-offset.
//
@@ -377,17 +390,46 @@ class CORE_EXPORT NGConstraintSpace final {
return HasRareData() ? rare_data_->forced_bfc_block_offset : base::nullopt;
}
- // Return the types (none, left, right, both) of preceding adjoining
- // floats. These are floats that are added while the in-flow BFC offset is
- // still unknown. The floats may or may not be unpositioned (pending). That
- // depends on which layout pass we're in. They are typically positioned if
- // ForcedBfcOffset() is known. Adjoining floats should be treated differently
- // when calculating clearance on a block with adjoining block-start margin.
- // (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 bitfields_.adjoining_floats;
+ // If present, this is a hint as to where place any adjoining objects. This
+ // isn't necessarily the final position, just where they ended up in a
+ // previous layout pass.
+ base::Optional<LayoutUnit> OptimisticBfcBlockOffset() const {
+ return HasRareData() ? rare_data_->optimistic_bfc_block_offset
+ : base::nullopt;
+ }
+
+ // The "expected" BFC block-offset is:
+ // - The |ForcedBfcBlockOffset| if set.
+ // - The |OptimisticBfcBlockOffset| if set.
+ // - Otherwise the |BfcOffset|.
+ //
+ // This represents where any adjoining-objects should be placed (potentially
+ // optimistically)
+ LayoutUnit ExpectedBfcBlockOffset() const {
+ // A short-circuit optimization (must equivalent to below).
+ if (!HasRareData()) {
+ DCHECK(!ForcedBfcBlockOffset());
+ DCHECK(!OptimisticBfcBlockOffset());
+ return bfc_offset_.block_offset;
+ }
+
+ return ForcedBfcBlockOffset().value_or(
+ OptimisticBfcBlockOffset().value_or(BfcOffset().block_offset));
+ }
+
+ // Returns the types of preceding adjoining objects.
+ // See |NGAdjoiningObjectTypes|.
+ //
+ // Adjoining floats are positioned at their correct position if the
+ // |ForcedBfcBlockOffset()| is known.
+ //
+ // Adjoining floats should be treated differently when calculating clearance
+ // on a block with adjoining block-start margin (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).
+ NGAdjoiningObjectTypes AdjoiningObjectTypes() const {
+ return bitfields_.adjoining_object_types;
}
// Return true if there were any earlier floats that may affect the current
@@ -510,6 +552,7 @@ class CORE_EXPORT NGConstraintSpace final {
NGBfcOffset bfc_offset;
NGMarginStrut margin_strut;
+ base::Optional<LayoutUnit> optimistic_bfc_block_offset;
base::Optional<LayoutUnit> forced_bfc_block_offset;
LayoutUnit clearance_offset = LayoutUnit::Min();
@@ -549,7 +592,7 @@ class CORE_EXPORT NGConstraintSpace final {
explicit Bitfields(WritingMode writing_mode)
: has_rare_data(false),
- adjoining_floats(static_cast<unsigned>(kFloatTypeNone)),
+ adjoining_object_types(static_cast<unsigned>(kAdjoiningNone)),
writing_mode(static_cast<unsigned>(writing_mode)),
direction(static_cast<unsigned>(TextDirection::kLtr)),
is_shrink_to_fit(false),
@@ -564,7 +607,7 @@ class CORE_EXPORT NGConstraintSpace final {
replaced_percentage_block_storage(kSameAsAvailable) {}
bool MaySkipLayout(const Bitfields& other) const {
- return adjoining_floats == other.adjoining_floats &&
+ return adjoining_object_types == other.adjoining_object_types &&
writing_mode == other.writing_mode && flags == other.flags &&
baseline_requests == other.baseline_requests;
}
@@ -580,7 +623,7 @@ class CORE_EXPORT NGConstraintSpace final {
}
unsigned has_rare_data : 1;
- unsigned adjoining_floats : 3; // NGFloatTypes
+ unsigned adjoining_object_types : 3; // NGAdjoiningObjectTypes
unsigned writing_mode : 3;
unsigned direction : 1;
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 c3c57444888..ad673637afc 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
@@ -30,6 +30,7 @@ NGConstraintSpaceBuilder& NGConstraintSpaceBuilder::SetPercentageResolutionSize(
LogicalSize percentage_resolution_size) {
#if DCHECK_IS_ON()
DCHECK(is_available_size_set_);
+ is_percentage_resolution_size_set_ = true;
#endif
if (LIKELY(is_in_parallel_flow_)) {
space_.bitfields_.percentage_inline_storage =
@@ -76,6 +77,7 @@ NGConstraintSpaceBuilder::SetReplacedPercentageResolutionSize(
LogicalSize replaced_percentage_resolution_size) {
#if DCHECK_IS_ON()
DCHECK(is_available_size_set_);
+ DCHECK(is_percentage_resolution_size_set_);
#endif
if (LIKELY(is_in_parallel_flow_)) {
// We don't store the replaced percentage resolution inline size, so we need
@@ -92,20 +94,21 @@ NGConstraintSpaceBuilder::SetReplacedPercentageResolutionSize(
replaced_percentage_resolution_size.block_size;
}
} else {
- AdjustInlineSizeIfNeeded(&replaced_percentage_resolution_size.block_size);
-
- // We don't store the replaced percentage resolution inline size, so we need
- // it to be the same as the regular percentage resolution inline size.
- DCHECK_EQ(replaced_percentage_resolution_size.block_size,
- space_.PercentageResolutionInlineSize());
+ // There should be no need to handle quirky percentage block-size resolution
+ // if this is an orthogonal writing mode root. The quirky percentage
+ // block-size resolution size that may have been calculated on an ancestor
+ // will be used to resolve inline-sizes of the child, and will therefore now
+ // be lost (since we don't store the quirky replaced percentage resolution
+ // *inline* size, only the *block* size). Just copy whatever was set as a
+ // regular percentage resolution block-size.
+ LayoutUnit block_size = space_.PercentageResolutionBlockSize();
space_.bitfields_.replaced_percentage_block_storage =
- GetPercentageStorage(replaced_percentage_resolution_size.inline_size,
- space_.available_size_.block_size);
+ GetPercentageStorage(block_size, space_.available_size_.block_size);
if (space_.bitfields_.replaced_percentage_block_storage ==
kRareDataPercentage) {
space_.EnsureRareData()->replaced_percentage_resolution_block_size =
- replaced_percentage_resolution_size.inline_size;
+ block_size;
}
}
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 09a7f0b5770..06ede827d49 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
@@ -12,7 +12,7 @@
#include "third_party/blink/renderer/core/layout/ng/ng_floats_utils.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/allocator/allocator.h"
namespace blink {
@@ -83,9 +83,22 @@ class CORE_EXPORT NGConstraintSpaceBuilder final {
return *this;
}
+ // Set percentage resolution size. Prior to calling this method,
+ // SetAvailableSize() must have been called, since we'll compare the input
+ // against the available size set, because if they are equal in either
+ // dimension, we won't have to store the values separately.
NGConstraintSpaceBuilder& SetPercentageResolutionSize(
LogicalSize percentage_resolution_size);
+ // Set percentage resolution size for replaced content (a special quirk inside
+ // tables). Only honored if the writing modes (container vs. child) are
+ // parallel. In orthogonal writing modes, we'll use whatever regular
+ // percentage resolution size is already set. Prior to calling this method,
+ // SetAvailableSize() must have been called, since we'll compare the input
+ // against the available size set, because if they are equal in either
+ // dimension, we won't have to store the values separately. Additionally,
+ // SetPercentageResolutionSize() must have been called, since we'll override
+ // with that value on orthogonal writing mode roots.
NGConstraintSpaceBuilder& SetReplacedPercentageResolutionSize(
LogicalSize replaced_percentage_resolution_size);
@@ -189,9 +202,12 @@ class CORE_EXPORT NGConstraintSpaceBuilder final {
return *this;
}
- NGConstraintSpaceBuilder& SetAdjoiningFloatTypes(NGFloatTypes floats) {
- if (!is_new_fc_)
- space_.bitfields_.adjoining_floats = static_cast<unsigned>(floats);
+ NGConstraintSpaceBuilder& SetAdjoiningObjectTypes(
+ NGAdjoiningObjectTypes adjoining_object_types) {
+ if (!is_new_fc_) {
+ space_.bitfields_.adjoining_object_types =
+ static_cast<unsigned>(adjoining_object_types);
+ }
return *this;
}
@@ -217,13 +233,28 @@ class CORE_EXPORT NGConstraintSpaceBuilder final {
return *this;
}
+
+ NGConstraintSpaceBuilder& SetOptimisticBfcBlockOffset(
+ LayoutUnit optimistic_bfc_block_offset) {
+#if DCHECK_IS_ON()
+ DCHECK(!is_optimistic_bfc_block_offset_set_);
+ is_optimistic_bfc_block_offset_set_ = true;
+#endif
+ if (LIKELY(!is_new_fc_)) {
+ space_.EnsureRareData()->optimistic_bfc_block_offset =
+ optimistic_bfc_block_offset;
+ }
+
+ return *this;
+ }
+
NGConstraintSpaceBuilder& SetForcedBfcBlockOffset(
- const base::Optional<LayoutUnit>& forced_bfc_block_offset) {
+ LayoutUnit forced_bfc_block_offset) {
#if DCHECK_IS_ON()
DCHECK(!is_forced_bfc_block_offset_set_);
is_forced_bfc_block_offset_set_ = true;
#endif
- if (LIKELY(!is_new_fc_ && forced_bfc_block_offset != base::nullopt)) {
+ if (LIKELY(!is_new_fc_)) {
space_.EnsureRareData()->forced_bfc_block_offset =
forced_bfc_block_offset;
}
@@ -280,7 +311,7 @@ class CORE_EXPORT NGConstraintSpaceBuilder final {
to_constraint_space_called_ = true;
#endif
- DCHECK(!is_new_fc_ || !space_.bitfields_.adjoining_floats);
+ DCHECK(!is_new_fc_ || !space_.bitfields_.adjoining_object_types);
DCHECK_EQ(space_.HasFlag(NGConstraintSpace::kOrthogonalWritingModeRoot),
!is_in_parallel_flow_ || force_orthogonal_writing_mode_root_);
@@ -313,10 +344,12 @@ class CORE_EXPORT NGConstraintSpaceBuilder final {
#if DCHECK_IS_ON()
bool is_available_size_set_ = false;
+ bool is_percentage_resolution_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_optimistic_bfc_block_offset_set_ = false;
bool is_forced_bfc_block_offset_set_ = false;
bool is_clearance_offset_set_ = false;
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 e62ccbc378e..d738e141db1 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
@@ -14,16 +14,14 @@
namespace blink {
namespace {
-// This routine returns true if inline_container should replace descendant's
-// inline container.
-bool IsInlineContainerForDescendant(
- const NGOutOfFlowPositionedDescendant& descendant,
- const LayoutObject* inline_container) {
- return !descendant.inline_container && inline_container &&
- inline_container->IsLayoutInline() &&
+
+bool IsInlineContainerForNode(const NGBlockNode& node,
+ const LayoutObject* inline_container) {
+ return inline_container && inline_container->IsLayoutInline() &&
inline_container->CanContainOutOfFlowPositionedElement(
- descendant.node.Style().GetPosition());
+ node.Style().GetPosition());
}
+
} // namespace
NGContainerFragmentBuilder& NGContainerFragmentBuilder::AddChild(
@@ -36,34 +34,7 @@ NGContainerFragmentBuilder& NGContainerFragmentBuilder::AddChild(
if (child.HasOutOfFlowPositionedDescendants()) {
const auto& out_of_flow_descendants =
child.OutOfFlowPositionedDescendants();
- LogicalOffset top_left_offset;
PhysicalSize child_size = child.Size();
- switch (GetWritingMode()) {
- case WritingMode::kHorizontalTb:
- top_left_offset =
- (IsRtl(Direction()))
- ? LogicalOffset{child_offset.inline_offset + child_size.width,
- child_offset.block_offset}
- : child_offset;
- break;
- case WritingMode::kVerticalRl:
- case WritingMode::kSidewaysRl:
- top_left_offset =
- (IsRtl(Direction()))
- ? LogicalOffset{child_offset.inline_offset + child_size.height,
- child_offset.block_offset + child_size.width}
- : LogicalOffset{child_offset.inline_offset,
- child_offset.block_offset + child_size.width};
- break;
- case WritingMode::kVerticalLr:
- case WritingMode::kSidewaysLr:
- top_left_offset =
- (IsRtl(Direction()))
- ? LogicalOffset{child_offset.inline_offset + child_size.height,
- child_offset.block_offset}
- : child_offset;
- break;
- }
// We can end up in a case where we need to account for the relative
// position of an element to correctly determine the static position of a
@@ -75,20 +46,27 @@ NGContainerFragmentBuilder& NGContainerFragmentBuilder::AddChild(
// </div>
// TODO(layout-dev): This code should eventually be removed once we handle
// relative positioned objects directly in the fragment tree.
+ LogicalOffset offset = child_offset;
if (const LayoutBox* child_box =
ToLayoutBoxOrNull(child.GetLayoutObject())) {
- top_left_offset += PhysicalOffset(child_box->OffsetForInFlowPosition())
- .ConvertToLogical(GetWritingMode(), Direction(),
- PhysicalSize(), PhysicalSize());
+ offset += PhysicalOffset(child_box->OffsetForInFlowPosition())
+ .ConvertToLogical(GetWritingMode(), Direction(),
+ PhysicalSize(), PhysicalSize());
}
- for (NGOutOfFlowPositionedDescendant& descendant :
- out_of_flow_descendants) {
- if (IsInlineContainerForDescendant(descendant, inline_container)) {
- descendant.inline_container = inline_container;
- }
- oof_positioned_candidates_.push_back(
- NGOutOfFlowPositionedCandidate(descendant, top_left_offset));
+ for (const auto& descendant : out_of_flow_descendants) {
+ NGLogicalStaticPosition static_position =
+ descendant.static_position.ConvertToLogical(GetWritingMode(),
+ Direction(), child_size);
+ static_position.offset += offset;
+
+ const LayoutInline* new_inline_container = descendant.inline_container;
+ if (!descendant.inline_container &&
+ IsInlineContainerForNode(descendant.node, inline_container))
+ new_inline_container = inline_container;
+
+ oof_positioned_candidates_.emplace_back(descendant.node, static_position,
+ new_inline_container);
}
}
@@ -207,78 +185,59 @@ NGContainerFragmentBuilder::AddOutOfFlowChildCandidate(
// As all inline-level fragments are built in the line-logical coordinate
// system (Direction() is kLtr), we need to know the direction of the
// parent element to correctly determine an OOF childs static position.
- TextDirection direction = container_direction.value_or(Direction());
+ TextDirection direction = container_direction.value_or(TextDirection::kLtr);
- oof_positioned_candidates_.push_back(NGOutOfFlowPositionedCandidate(
- NGOutOfFlowPositionedDescendant(
- child, NGStaticPosition::Create(GetWritingMode(), direction,
- PhysicalOffset())),
- child_offset));
+ oof_positioned_candidates_.emplace_back(
+ child,
+ NGLogicalStaticPosition{
+ child_offset,
+ IsLtr(direction) ? NGLogicalStaticPosition::InlineEdge::kInlineStart
+ : NGLogicalStaticPosition::InlineEdge::kInlineEnd,
+ NGLogicalStaticPosition::BlockEdge::kBlockStart});
return *this;
}
NGContainerFragmentBuilder& NGContainerFragmentBuilder::AddOutOfFlowDescendant(
- NGOutOfFlowPositionedDescendant descendant) {
+ const NGLogicalOutOfFlowPositionedNode& descendant) {
oof_positioned_descendants_.push_back(descendant);
return *this;
}
-void NGContainerFragmentBuilder::GetAndClearOutOfFlowDescendantCandidates(
- Vector<NGOutOfFlowPositionedDescendant>* descendant_candidates,
+void NGContainerFragmentBuilder::SwapOutOfFlowPositionedCandidates(
+ Vector<NGLogicalOutOfFlowPositionedNode>* candidates,
const LayoutObject* current_container) {
- DCHECK(descendant_candidates->IsEmpty());
-
- if (oof_positioned_candidates_.size() == 0)
- return;
-
- descendant_candidates->ReserveCapacity(oof_positioned_candidates_.size());
+ DCHECK(candidates->IsEmpty());
- DCHECK_GE(InlineSize(), LayoutUnit());
- DCHECK_GE(BlockSize(), LayoutUnit());
- PhysicalSize builder_physical_size = ToPhysicalSize(Size(), GetWritingMode());
-
- for (NGOutOfFlowPositionedCandidate& candidate : oof_positioned_candidates_) {
- PhysicalOffset child_offset = candidate.child_offset.ConvertToPhysical(
- GetWritingMode(), Direction(), builder_physical_size, PhysicalSize());
-
- NGStaticPosition builder_relative_position;
- builder_relative_position.type = candidate.descendant.static_position.type;
- builder_relative_position.offset =
- child_offset + candidate.descendant.static_position.offset;
+ // The |oof_positioned_candidates_| list may get additional candidates, in the
+ // following case:
+ // - If an absolute-positioned element gets added to the builder, and it has
+ // a fixed-positioned descendant.
+ std::swap(oof_positioned_candidates_, *candidates);
+ for (auto& candidate : *candidates) {
// 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.
- const LayoutInline* inline_container =
- candidate.descendant.inline_container;
- if (IsInlineContainerForDescendant(candidate.descendant, layout_object_)) {
- inline_container = ToLayoutInline(layout_object_);
+ if (!candidate.inline_container &&
+ IsInlineContainerForNode(candidate.node, layout_object_))
+ candidate.inline_container = ToLayoutInline(layout_object_);
+
+ // Ensure that the inline_container is a continuation root.
+ if (candidate.inline_container) {
+ candidate.inline_container =
+ ToLayoutInline(candidate.inline_container->ContinuationRoot());
}
- descendant_candidates->push_back(NGOutOfFlowPositionedDescendant(
- candidate.descendant.node, builder_relative_position,
- inline_container ? ToLayoutInline(inline_container->ContinuationRoot())
- : nullptr));
-
- LogicalOffset container_offset =
- builder_relative_position.offset.ConvertToLogical(
- GetWritingMode(), Direction(), builder_physical_size,
- PhysicalSize());
- candidate.descendant.node.SaveStaticOffsetForLegacy(container_offset,
- current_container);
+
+ // Copy-back the static-position for legacy.
+ candidate.node.SaveStaticOffsetForLegacy(candidate.static_position.offset,
+ current_container);
}
- // Clear our current canidate list. This may get modified again if the
- // current fragment is a containing block, and AddChild is called with a
- // descendant from this list.
- //
- // 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_.Shrink(0);
+ DCHECK(oof_positioned_candidates_.IsEmpty());
}
#if DCHECK_IS_ON()
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 bd692e43df1..b7b1d38ee74 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
@@ -16,11 +16,11 @@
#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/layout/ng/ng_out_of_flow_positioned_node.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/allocator/allocator.h"
namespace blink {
@@ -28,7 +28,7 @@ class NGExclusionSpace;
class NGPhysicalFragment;
class CORE_EXPORT NGContainerFragmentBuilder : public NGFragmentBuilder {
- DISALLOW_NEW();
+ STACK_ALLOCATED();
public:
struct ChildWithOffset {
@@ -104,11 +104,8 @@ class CORE_EXPORT NGContainerFragmentBuilder : public NGFragmentBuilder {
// Warning: Do not call unless necessary.
LogicalOffset GetChildOffset(const LayoutObject* child) const;
- // Builder has non-trivial out-of-flow descendant methods.
- // These methods are building blocks for implementation of
- // out-of-flow descendants by layout algorithms.
- //
- // They are intended to be used by layout algorithm like this:
+ // Builder has non-trivial OOF-positioned methods.
+ // They are intended to be used by a layout algorithm like this:
//
// Part 1: layout algorithm positions in-flow children.
// out-of-flow children, and out-of-flow descendants of fragments
@@ -124,7 +121,7 @@ class CORE_EXPORT NGContainerFragmentBuilder : public NGFragmentBuilder {
//
// builder->SetSize
//
- // Part 2: Out-of-flow layout part positions out-of-flow descendants.
+ // Part 2: Out-of-flow layout part positions OOF-positioned nodes.
//
// NGOutOfFlowLayoutPart(container_style, builder).Run();
//
@@ -138,26 +135,25 @@ class CORE_EXPORT NGContainerFragmentBuilder : public NGFragmentBuilder {
base::Optional<TextDirection> container_direction = base::nullopt);
NGContainerFragmentBuilder& AddOutOfFlowDescendant(
- NGOutOfFlowPositionedDescendant descendant);
+ const NGLogicalOutOfFlowPositionedNode& descendant);
- void GetAndClearOutOfFlowDescendantCandidates(
- Vector<NGOutOfFlowPositionedDescendant>* descendant_candidates,
- const LayoutObject* container);
+ void SwapOutOfFlowPositionedCandidates(
+ Vector<NGLogicalOutOfFlowPositionedNode>* candidates,
+ const LayoutObject* current_container);
- bool HasOutOfFlowDescendantCandidates() const {
+ bool HasOutOfFlowPositionedCandidates() 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.
+ // used to convert all OOF-positioned 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() {
- GetAndClearOutOfFlowDescendantCandidates(&oof_positioned_descendants_,
- nullptr);
+ SwapOutOfFlowPositionedCandidates(&oof_positioned_descendants_, nullptr);
}
NGContainerFragmentBuilder& SetIsSelfCollapsing() {
@@ -171,19 +167,23 @@ class CORE_EXPORT NGContainerFragmentBuilder : public NGFragmentBuilder {
}
bool IsPushedByFloats() const { return is_pushed_by_floats_; }
- NGContainerFragmentBuilder& ResetAdjoiningFloatTypes() {
- adjoining_floats_ = kFloatTypeNone;
+ NGContainerFragmentBuilder& ResetAdjoiningObjectTypes() {
+ adjoining_object_types_ = kAdjoiningNone;
return *this;
}
- NGContainerFragmentBuilder& AddAdjoiningFloatTypes(NGFloatTypes floats) {
- adjoining_floats_ |= floats;
+ NGContainerFragmentBuilder& AddAdjoiningObjectTypes(
+ NGAdjoiningObjectTypes adjoining_object_types) {
+ adjoining_object_types_ |= adjoining_object_types;
return *this;
}
- NGContainerFragmentBuilder& SetAdjoiningFloatTypes(NGFloatTypes floats) {
- adjoining_floats_ = floats;
+ NGContainerFragmentBuilder& SetAdjoiningObjectTypes(
+ NGAdjoiningObjectTypes adjoining_object_types) {
+ adjoining_object_types_ = adjoining_object_types;
return *this;
}
- NGFloatTypes AdjoiningFloatTypes() const { return adjoining_floats_; }
+ NGAdjoiningObjectTypes AdjoiningObjectTypes() const {
+ return adjoining_object_types_;
+ }
NGContainerFragmentBuilder& SetHasBlockFragmentation() {
has_block_fragmentation_ = true;
@@ -200,30 +200,6 @@ class CORE_EXPORT NGContainerFragmentBuilder : public NGFragmentBuilder {
friend class NGPhysicalContainerFragment;
friend class NGLayoutResult;
- // An out-of-flow positioned-candidate is a temporary data structure used
- // within the NGBoxFragmentBuilder.
- //
- // A positioned-candidate can be:
- // 1. A direct out-of-flow positioned child. The child_offset is (0,0).
- // 2. A fragment containing an out-of-flow positioned-descendant. The
- // child_offset in this case is the containing fragment's offset.
- //
- // The child_offset is stored as a LogicalOffset as the physical offset
- // cannot be computed until we know the current fragment's size.
- //
- // When returning the positioned-candidates (from
- // GetAndClearOutOfFlowDescendantCandidates), the NGBoxFragmentBuilder will
- // convert the positioned-candidate to a positioned-descendant using the
- // physical size the fragment builder.
- struct NGOutOfFlowPositionedCandidate {
- NGOutOfFlowPositionedDescendant descendant;
- LogicalOffset child_offset; // Logical offset of child's top left vertex.
-
- NGOutOfFlowPositionedCandidate(NGOutOfFlowPositionedDescendant descendant,
- LogicalOffset child_offset)
- : descendant(descendant), child_offset(child_offset) {}
- };
-
NGContainerFragmentBuilder(NGLayoutInputNode node,
scoped_refptr<const ComputedStyle> style,
const NGConstraintSpace* space,
@@ -246,8 +222,8 @@ class CORE_EXPORT NGContainerFragmentBuilder : public NGFragmentBuilder {
NGMarginStrut end_margin_strut_;
NGExclusionSpace exclusion_space_;
- Vector<NGOutOfFlowPositionedCandidate> oof_positioned_candidates_;
- Vector<NGOutOfFlowPositionedDescendant> oof_positioned_descendants_;
+ Vector<NGLogicalOutOfFlowPositionedNode> oof_positioned_candidates_;
+ Vector<NGLogicalOutOfFlowPositionedNode> oof_positioned_descendants_;
NGUnpositionedListMarker unpositioned_list_marker_;
@@ -258,7 +234,7 @@ class CORE_EXPORT NGContainerFragmentBuilder : public NGFragmentBuilder {
NGBreakTokenVector child_break_tokens_;
NGBreakTokenVector inline_break_tokens_;
- NGFloatTypes adjoining_floats_ = kFloatTypeNone;
+ NGAdjoiningObjectTypes adjoining_object_types_ = kAdjoiningNone;
bool is_self_collapsing_ = false;
bool is_pushed_by_floats_ = false;
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 d1aae7b5fef..ab1718db0e4 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
@@ -8,26 +8,22 @@
#include "third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.h"
#include "third_party/blink/renderer/core/layout/ng/ng_length_utils.h"
#include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h"
+#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
namespace blink {
namespace {
-class NGFieldsetLayoutAlgorithmTest : public NGBaseLayoutAlgorithmTest {
+class NGFieldsetLayoutAlgorithmTest
+ : public NGBaseLayoutAlgorithmTest,
+ private ScopedLayoutNGFieldsetForTest,
+ private ScopedLayoutNGBlockFragmentationForTest {
protected:
+ NGFieldsetLayoutAlgorithmTest()
+ : ScopedLayoutNGFieldsetForTest(true),
+ ScopedLayoutNGBlockFragmentationForTest(true) {}
void SetUp() override {
NGBaseLayoutAlgorithmTest::SetUp();
style_ = ComputedStyle::Create();
- was_fieldset_enabled_ = RuntimeEnabledFeatures::LayoutNGFieldsetEnabled();
- was_block_fragmentation_enabled_ =
- RuntimeEnabledFeatures::LayoutNGBlockFragmentationEnabled();
- RuntimeEnabledFeatures::SetLayoutNGFieldsetEnabled(true);
- RuntimeEnabledFeatures::SetLayoutNGBlockFragmentationEnabled(true);
- }
-
- void TearDown() override {
- RuntimeEnabledFeatures::SetLayoutNGFieldsetEnabled(was_fieldset_enabled_);
- RuntimeEnabledFeatures::SetLayoutNGBlockFragmentationEnabled(
- was_block_fragmentation_enabled_);
}
scoped_refptr<const NGPhysicalBoxFragment> RunBlockLayoutAlgorithm(
@@ -75,8 +71,6 @@ class NGFieldsetLayoutAlgorithmTest : public NGBaseLayoutAlgorithmTest {
}
scoped_refptr<ComputedStyle> style_;
- bool was_fieldset_enabled_ = false;
- bool was_block_fragmentation_enabled_ = false;
};
TEST_F(NGFieldsetLayoutAlgorithmTest, Empty) {
@@ -268,9 +262,8 @@ TEST_F(NGFieldsetLayoutAlgorithmTest, LegendAutoSize) {
offset:unplaced size:1000x323
offset:0,0 size:126x323
offset:13,0 size:50x200
- offset:50,0 size:0x0
- offset:-50,0 size:25x200
- offset:-25,0 size:25x200
+ offset:0,0 size:25x200
+ offset:25,0 size:25x200
offset:3,200 size:120x120
offset:10,10 size:100x100
)DUMP";
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 e3127d0e7a9..637fa10e1c9 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
@@ -78,11 +78,7 @@ NGConstraintSpace CreateConstraintSpaceForFloat(
DCHECK(parent_space.HasBlockFragmentation());
DCHECK_EQ(style.GetWritingMode(), parent_space.GetWritingMode());
- LayoutUnit fragmentation_offset =
- parent_space.FragmentainerSpaceAtBfcStart() - *origin_block_offset;
- builder.SetFragmentainerBlockSize(parent_space.FragmentainerBlockSize());
- builder.SetFragmentainerSpaceAtBfcStart(fragmentation_offset);
- builder.SetFragmentationType(parent_space.BlockFragmentationType());
+ SetupFragmentation(parent_space, *origin_block_offset, &builder);
} else {
builder.SetFragmentationType(NGFragmentationType::kFragmentNone);
}
@@ -307,20 +303,4 @@ NGPositionedFloat PositionFloat(
return NGPositionedFloat(std::move(layout_result), float_bfc_offset);
}
-NGFloatTypes ToFloatTypes(EClear clear) {
- switch (clear) {
- default:
- NOTREACHED();
- FALLTHROUGH;
- case EClear::kNone:
- return kFloatTypeNone;
- case EClear::kLeft:
- return kFloatTypeLeft;
- case EClear::kRight:
- return kFloatTypeRight;
- case EClear::kBoth:
- return kFloatTypeBoth;
- };
-}
-
} // namespace blink
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 1b6d9cb3eb2..bc75b013129 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
@@ -23,16 +23,6 @@ struct NGUnpositionedFloat;
typedef Vector<NGPositionedFloat, 8> NGPositionedFloatVector;
-// TODO(ikilpatrick): Rename this to NGAdjoiningObjectTypes.
-enum NGFloatTypeValue {
- kFloatTypeNone = 0b000,
- kFloatTypeLeft = 0b001,
- kFloatTypeRight = 0b010,
- kFloatTypeBoth = 0b011,
- kAdjoiningInlineOutOfFlow = 0b100
-};
-typedef int NGFloatTypes;
-
// Returns the inline size (relative to {@code parent_space}) of the
// unpositioned float.
LayoutUnit ComputeMarginBoxInlineSizeForUnpositionedFloat(
@@ -52,8 +42,6 @@ PositionFloat(const LogicalSize& float_available_size,
const ComputedStyle& parent_style,
NGExclusionSpace* exclusion_space);
-NGFloatTypes ToFloatTypes(EClear clear);
-
} // namespace blink
#endif // NGFloatsUtils_h
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 ec3b02fc22d..03aa4a40c3b 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
@@ -13,14 +13,14 @@
#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/allocator/allocator.h"
namespace blink {
class LayoutObject;
class CORE_EXPORT NGFragmentBuilder {
- DISALLOW_NEW();
+ STACK_ALLOCATED();
public:
const ComputedStyle& Style() const {
@@ -47,6 +47,8 @@ class CORE_EXPORT NGFragmentBuilder {
const LogicalSize& Size() const { return size_; }
void SetBlockSize(LayoutUnit block_size) { size_.block_size = block_size; }
+ void SetIsHiddenForPaint(bool value) { is_hidden_for_paint_ = value; }
+
const LayoutObject* GetLayoutObject() const { return layout_object_; }
protected:
@@ -62,6 +64,15 @@ class CORE_EXPORT NGFragmentBuilder {
NGFragmentBuilder(WritingMode writing_mode, TextDirection direction)
: writing_mode_(writing_mode), direction_(direction) {}
+ NGFragmentBuilder(const NGPhysicalFragment& fragment)
+ : style_(&fragment.Style()),
+ writing_mode_(style_->GetWritingMode()),
+ direction_(style_->Direction()),
+ style_variant_(fragment.StyleVariant()),
+ size_(fragment.Size().ConvertToLogical(writing_mode_)),
+ layout_object_(fragment.GetMutableLayoutObject()),
+ is_hidden_for_paint_(fragment.IsHiddenForPaint()) {}
+
protected:
scoped_refptr<const ComputedStyle> style_;
WritingMode writing_mode_;
@@ -70,6 +81,7 @@ class CORE_EXPORT NGFragmentBuilder {
LogicalSize size_;
LayoutObject* layout_object_ = nullptr;
scoped_refptr<NGBreakToken> break_token_;
+ bool is_hidden_for_paint_ = false;
friend class NGPhysicalFragment;
};
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 9c556e3468b..9fd9dd41a5e 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
@@ -7,6 +7,7 @@
#include "third_party/blink/renderer/core/layout/ng/ng_block_break_token.h"
#include "third_party/blink/renderer/core/layout/ng/ng_box_fragment.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_physical_box_fragment.h"
namespace blink {
@@ -111,4 +112,23 @@ bool ShouldIgnoreBlockStartMargin(const NGConstraintSpace& constraint_space,
return !child.IsFloating() && !child.IsOutOfFlowPositioned();
}
+void SetupFragmentation(const NGConstraintSpace& parent_space,
+ LayoutUnit new_bfc_block_offset,
+ NGConstraintSpaceBuilder* builder) {
+ DCHECK(parent_space.HasBlockFragmentation());
+
+ LayoutUnit space_available =
+ parent_space.FragmentainerSpaceAtBfcStart() - new_bfc_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).
+ builder->SetSeparateLeadingFragmentainerMargins(
+ parent_space.HasSeparateLeadingFragmentainerMargins());
+ builder->SetFragmentainerBlockSize(parent_space.FragmentainerBlockSize());
+ builder->SetFragmentainerSpaceAtBfcStart(space_available);
+ builder->SetFragmentationType(parent_space.BlockFragmentationType());
+}
+
} // namespace blink
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 31ead905d04..0656d92c8df 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
@@ -71,6 +71,16 @@ inline bool IsResumingLayout(const NGBlockBreakToken* token) {
return token && !token->IsBreakBefore();
}
+// Set up a child's constraint space builder for block fragmentation. The child
+// participates in the same fragmentation context as parent_space. If the child
+// establishes a new formatting context, new_bfc_block_offset must be set to the
+// offset from the parent block formatting context, or, if the parent formatting
+// context starts in a previous fragmentainer; the offset from the current
+// fragmentainer block-start.
+void SetupFragmentation(const NGConstraintSpace& parent_space,
+ LayoutUnit new_bfc_block_offset,
+ NGConstraintSpaceBuilder*);
+
} // namespace blink
#endif // NGFragmentationUtils_h
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 003277b57ef..972af291482 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
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/layout/min_max_size.h"
#include "third_party/blink/renderer/core/layout/ng/ng_block_node.h"
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -63,8 +63,7 @@ template <typename NGInputNodeType,
typename NGBoxFragmentBuilderType,
typename NGBreakTokenType>
class CORE_EXPORT NGLayoutAlgorithm : public NGLayoutAlgorithmOperations {
- USING_FAST_MALLOC(NGLayoutAlgorithm);
-
+ STACK_ALLOCATED();
public:
NGLayoutAlgorithm(NGInputNodeType node,
scoped_refptr<const ComputedStyle> style,
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 c6cc9856596..b848caa6f12 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
@@ -139,7 +139,7 @@ void NGLayoutInputNode::ShowNodeTree() const {
StringBuilder string_builder;
string_builder.Append(".:: LayoutNG Node Tree ::.\n");
AppendNodeToString(*this, &string_builder);
- fprintf(stderr, "%s\n", string_builder.ToString().Utf8().data());
+ fprintf(stderr, "%s\n", string_builder.ToString().Utf8().c_str());
}
#endif
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 0c1c0d40168..1ef92d054c8 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
@@ -83,9 +83,9 @@ class CORE_EXPORT NGLayoutInputNode {
bool IsBlockFlow() const { return IsBlock() && box_->IsLayoutBlockFlow(); }
bool IsColumnSpanAll() const { return IsBlock() && box_->IsColumnSpanAll(); }
- bool IsFloating() const { return IsBlock() && Style().IsFloating(); }
+ bool IsFloating() const { return IsBlock() && box_->IsFloating(); }
bool IsOutOfFlowPositioned() const {
- return IsBlock() && Style().HasOutOfFlowPosition();
+ return IsBlock() && box_->IsOutOfFlowPositioned();
}
bool IsReplaced() const { return box_->IsLayoutReplaced(); }
bool IsAbsoluteContainer() const {
@@ -132,14 +132,6 @@ 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_->CreatesNewFormattingContext();
}
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 f2d5ddb46c2..2cec25d3df5 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
@@ -15,19 +15,41 @@
namespace blink {
+namespace {
+
+struct SameSizeAsNGLayoutResult : public RefCounted<SameSizeAsNGLayoutResult> {
+ const NGConstraintSpace space;
+ void* physical_fragment;
+ union {
+ NGBfcOffset bfc_offset;
+ LogicalOffset oof_positioned_offset;
+ void* rare_data;
+ };
+ LayoutUnit intrinsic_block_size;
+ unsigned bitfields[1];
+};
+
+static_assert(sizeof(NGLayoutResult) == sizeof(SameSizeAsNGLayoutResult),
+ "NGLayoutResult should stay small.");
+
+} // namespace
+
NGLayoutResult::NGLayoutResult(
scoped_refptr<const NGPhysicalContainerFragment> physical_fragment,
NGBoxFragmentBuilder* builder)
: NGLayoutResult(std::move(physical_fragment),
builder,
/* cache_space */ true) {
- is_initial_block_size_indefinite_ =
+ bitfields_.is_initial_block_size_indefinite =
builder->is_initial_block_size_indefinite_;
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_;
+ if (builder->minimal_space_shortage_ != LayoutUnit::Max())
+ EnsureRareData()->minimal_space_shortage = builder->minimal_space_shortage_;
+ bitfields_.initial_break_before =
+ static_cast<unsigned>(builder->initial_break_before_);
+ bitfields_.final_break_after =
+ static_cast<unsigned>(builder->previous_break_after_);
+ bitfields_.has_forced_break = builder->has_forced_break_;
}
NGLayoutResult::NGLayoutResult(
@@ -42,9 +64,7 @@ NGLayoutResult::NGLayoutResult(NGLayoutResultStatus status,
: NGLayoutResult(/* physical_fragment */ nullptr,
builder,
/* cache_space */ false) {
- adjoining_floats_ = kFloatTypeNone;
- has_descendant_that_depends_on_percentage_block_size_ = false;
- status_ = status;
+ bitfields_.status = status;
DCHECK_NE(status, kSuccess)
<< "Use the other constructor for successful layout";
}
@@ -55,53 +75,50 @@ NGLayoutResult::NGLayoutResult(const NGLayoutResult& other,
base::Optional<LayoutUnit> bfc_block_offset)
: space_(new_space),
physical_fragment_(other.physical_fragment_),
- unpositioned_list_marker_(other.unpositioned_list_marker_),
- exclusion_space_(MergeExclusionSpaces(other,
- space_.ExclusionSpace(),
- bfc_line_offset,
- bfc_block_offset)),
- bfc_line_offset_(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_valid_space_(other.has_valid_space_),
- has_forced_break_(other.has_forced_break_),
- is_self_collapsing_(other.is_self_collapsing_),
- is_pushed_by_floats_(other.is_pushed_by_floats_),
- adjoining_floats_(other.adjoining_floats_),
- is_initial_block_size_indefinite_(
- other.is_initial_block_size_indefinite_),
- has_descendant_that_depends_on_percentage_block_size_(
- other.has_descendant_that_depends_on_percentage_block_size_),
- status_(other.status_) {}
+ bitfields_(other.bitfields_) {
+ if (HasRareData()) {
+ rare_data_ = new RareData(*other.rare_data_);
+ rare_data_->bfc_line_offset = bfc_line_offset;
+ rare_data_->bfc_block_offset = bfc_block_offset;
+ } else if (!bitfields_.has_oof_positioned_offset) {
+ bfc_offset_.line_offset = bfc_line_offset;
+ bfc_offset_.block_offset = bfc_block_offset.value_or(LayoutUnit());
+ bitfields_.is_bfc_block_offset_nullopt = !bfc_block_offset.has_value();
+ } else {
+ DCHECK(physical_fragment_->IsOutOfFlowPositioned());
+ DCHECK_EQ(bfc_line_offset, LayoutUnit());
+ DCHECK(bfc_block_offset && bfc_block_offset.value() == LayoutUnit());
+ oof_positioned_offset_ = LogicalOffset();
+ }
+
+ NGExclusionSpace new_exclusion_space = MergeExclusionSpaces(
+ other, space_.ExclusionSpace(), bfc_line_offset, bfc_block_offset);
+
+ if (new_exclusion_space != space_.ExclusionSpace()) {
+ bitfields_.has_rare_data_exclusion_space = true;
+ EnsureRareData()->exclusion_space = std::move(new_exclusion_space);
+ } else {
+ space_.ExclusionSpace().MoveDerivedGeometry(new_exclusion_space);
+ }
+}
NGLayoutResult::NGLayoutResult(
scoped_refptr<const NGPhysicalContainerFragment> physical_fragment,
NGContainerFragmentBuilder* builder,
bool cache_space)
- : space_(cache_space && builder->space_
- ? NGConstraintSpace(*builder->space_)
- : NGConstraintSpace()),
+ : space_(builder->space_ ? NGConstraintSpace(*builder->space_)
+ : NGConstraintSpace()),
physical_fragment_(std::move(physical_fragment)),
- 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_),
- has_valid_space_(cache_space && builder->space_),
- has_forced_break_(false),
- is_self_collapsing_(builder->is_self_collapsing_),
- is_pushed_by_floats_(builder->is_pushed_by_floats_),
- adjoining_floats_(builder->adjoining_floats_),
- is_initial_block_size_indefinite_(false),
- has_descendant_that_depends_on_percentage_block_size_(
- builder->has_descendant_that_depends_on_percentage_block_size_),
- status_(kSuccess) {
+ bitfields_(
+ /* has_valid_space */ cache_space && builder->space_,
+ /* is_self_collapsing */ builder->is_self_collapsing_,
+ /* is_pushed_by_floats */ builder->is_pushed_by_floats_,
+ /* adjoining_object_types */ builder->adjoining_object_types_,
+ /* has_descendant_that_depends_on_percentage_block_size */
+ builder->has_descendant_that_depends_on_percentage_block_size_) {
#if DCHECK_IS_ON()
- if (is_self_collapsing_ && physical_fragment_) {
+ if (bitfields_.is_self_collapsing && physical_fragment_) {
// A new formatting-context shouldn't be self-collapsing.
DCHECK(!physical_fragment_->IsBlockFormattingContextRoot());
@@ -111,11 +128,36 @@ NGLayoutResult::NGLayoutResult(
DCHECK_EQ(LayoutUnit(), fragment.BlockSize());
}
#endif
+
+ if (builder->end_margin_strut_ != NGMarginStrut())
+ EnsureRareData()->end_margin_strut = builder->end_margin_strut_;
+ if (builder->unpositioned_list_marker_) {
+ EnsureRareData()->unpositioned_list_marker =
+ builder->unpositioned_list_marker_;
+ }
+ if (builder->exclusion_space_ != space_.ExclusionSpace()) {
+ bitfields_.has_rare_data_exclusion_space = true;
+ EnsureRareData()->exclusion_space = std::move(builder->exclusion_space_);
+ } else {
+ space_.ExclusionSpace().MoveDerivedGeometry(builder->exclusion_space_);
+ }
+
+ if (HasRareData()) {
+ rare_data_->bfc_line_offset = builder->bfc_line_offset_;
+ rare_data_->bfc_block_offset = builder->bfc_block_offset_;
+ } else {
+ bfc_offset_.line_offset = builder->bfc_line_offset_;
+ bfc_offset_.block_offset =
+ builder->bfc_block_offset_.value_or(LayoutUnit());
+ bitfields_.is_bfc_block_offset_nullopt =
+ !builder->bfc_block_offset_.has_value();
+ }
}
-// Define the destructor here, so that we can forward-declare more in the
-// header.
-NGLayoutResult::~NGLayoutResult() = default;
+NGLayoutResult::~NGLayoutResult() {
+ if (HasRareData())
+ delete rare_data_;
+}
NGExclusionSpace NGLayoutResult::MergeExclusionSpaces(
const NGLayoutResult& other,
@@ -127,19 +169,31 @@ NGExclusionSpace NGLayoutResult::MergeExclusionSpaces(
// value, and the result which we are copying doesn't (or visa versa).
// This would imply the result has switched its "empty" state for margin
// collapsing, which would mean it isn't possible to reuse the result.
- DCHECK_EQ(bfc_block_offset.has_value(), other.bfc_block_offset_.has_value());
+ DCHECK_EQ(bfc_block_offset.has_value(), other.BfcBlockOffset().has_value());
- NGBfcDelta offset_delta = {bfc_line_offset - other.bfc_line_offset_,
- bfc_block_offset && other.bfc_block_offset_
- ? *bfc_block_offset - *other.bfc_block_offset_
+ NGBfcDelta offset_delta = {bfc_line_offset - other.BfcLineOffset(),
+ bfc_block_offset && other.BfcBlockOffset()
+ ? *bfc_block_offset - *other.BfcBlockOffset()
: LayoutUnit()};
return NGExclusionSpace::MergeExclusionSpaces(
- /* old_output */ other.exclusion_space_,
+ /* old_output */ other.ExclusionSpace(),
/* old_input */ other.space_.ExclusionSpace(),
/* new_input */ new_input_exclusion_space, offset_delta);
}
+NGLayoutResult::RareData* NGLayoutResult::EnsureRareData() {
+ if (!HasRareData()) {
+ base::Optional<LayoutUnit> bfc_block_offset;
+ if (!bitfields_.is_bfc_block_offset_nullopt)
+ bfc_block_offset = bfc_offset_.block_offset;
+ rare_data_ = new RareData(bfc_offset_.line_offset, bfc_block_offset);
+ bitfields_.has_rare_data = true;
+ }
+
+ return rare_data_;
+}
+
#if DCHECK_IS_ON()
void NGLayoutResult::CheckSameForSimplifiedLayout(
const NGLayoutResult& other,
@@ -149,34 +203,38 @@ void NGLayoutResult::CheckSameForSimplifiedLayout(
To<NGPhysicalBoxFragment>(*other.physical_fragment_),
check_same_block_size);
- DCHECK(unpositioned_list_marker_ == other.unpositioned_list_marker_);
- exclusion_space_.CheckSameForSimplifiedLayout(other.exclusion_space_);
+ DCHECK(UnpositionedListMarker() == other.UnpositionedListMarker());
+ ExclusionSpace().CheckSameForSimplifiedLayout(other.ExclusionSpace());
- // We ignore bfc_block_offset_, and bfc_line_offset_ as "simplified" layout
+ // We ignore |BfcBlockOffset|, and |BfcLineOffset| as "simplified" layout
// will move the layout result if required.
- // We ignore the intrinsic_block_size_ as if a scrollbar gets added/removed
+ // We ignore the |intrinsic_block_size_| as if a scrollbar gets added/removed
// this may change (even if the size of the fragment remains the same).
- DCHECK(end_margin_strut_ == other.end_margin_strut_);
- DCHECK_EQ(minimal_space_shortage_, other.minimal_space_shortage_);
+ DCHECK(EndMarginStrut() == other.EndMarginStrut());
+ DCHECK_EQ(MinimalSpaceShortage(), other.MinimalSpaceShortage());
- DCHECK_EQ(initial_break_before_, other.initial_break_before_);
- DCHECK_EQ(final_break_after_, other.final_break_after_);
+ DCHECK_EQ(bitfields_.has_valid_space, other.bitfields_.has_valid_space);
+ DCHECK_EQ(bitfields_.has_forced_break, other.bitfields_.has_forced_break);
+ DCHECK_EQ(bitfields_.is_self_collapsing, other.bitfields_.is_self_collapsing);
+ DCHECK_EQ(bitfields_.is_pushed_by_floats,
+ other.bitfields_.is_pushed_by_floats);
+ DCHECK_EQ(bitfields_.adjoining_object_types,
+ other.bitfields_.adjoining_object_types);
- DCHECK_EQ(has_valid_space_, other.has_valid_space_);
- DCHECK_EQ(has_forced_break_, other.has_forced_break_);
- DCHECK_EQ(is_self_collapsing_, other.is_self_collapsing_);
- DCHECK_EQ(is_pushed_by_floats_, other.is_pushed_by_floats_);
- DCHECK_EQ(adjoining_floats_, other.adjoining_floats_);
+ DCHECK_EQ(bitfields_.initial_break_before,
+ other.bitfields_.initial_break_before);
+ DCHECK_EQ(bitfields_.final_break_after, other.bitfields_.final_break_after);
if (check_same_block_size) {
- DCHECK_EQ(is_initial_block_size_indefinite_,
- other.is_initial_block_size_indefinite_);
+ DCHECK_EQ(bitfields_.is_initial_block_size_indefinite,
+ other.bitfields_.is_initial_block_size_indefinite);
}
- DCHECK_EQ(has_descendant_that_depends_on_percentage_block_size_,
- other.has_descendant_that_depends_on_percentage_block_size_);
- DCHECK_EQ(status_, other.status_);
+ DCHECK_EQ(
+ bitfields_.has_descendant_that_depends_on_percentage_block_size,
+ other.bitfields_.has_descendant_that_depends_on_percentage_block_size);
+ DCHECK_EQ(bitfields_.status, other.bitfields_.status);
}
#endif
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 e9aeb01dbee..126a2ec22f5 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
@@ -36,8 +36,8 @@ class CORE_EXPORT NGLayoutResult : public RefCounted<NGLayoutResult> {
enum NGLayoutResultStatus {
kSuccess = 0,
kBfcBlockOffsetResolved = 1,
- // When adding new values, make sure the bit size of |status_| is large
- // enough to store.
+ // When adding new values, make sure the bit size of |Bitfields::status| is
+ // large enough to store.
};
// Create a copy of NGLayoutResult with |BfcBlockOffset| replaced by the given
@@ -56,25 +56,59 @@ class CORE_EXPORT NGLayoutResult : public RefCounted<NGLayoutResult> {
}
LogicalOffset OutOfFlowPositionedOffset() const {
- return oof_positioned_offset_;
+ DCHECK(bitfields_.has_oof_positioned_offset);
+ return HasRareData() ? rare_data_->oof_positioned_offset
+ : oof_positioned_offset_;
}
- const NGUnpositionedListMarker& UnpositionedListMarker() const {
- return unpositioned_list_marker_;
+ const NGUnpositionedListMarker UnpositionedListMarker() const {
+ return HasRareData() ? rare_data_->unpositioned_list_marker
+ : NGUnpositionedListMarker();
}
- const NGExclusionSpace& ExclusionSpace() const { return exclusion_space_; }
+ const NGExclusionSpace& ExclusionSpace() const {
+ if (bitfields_.has_rare_data_exclusion_space) {
+ DCHECK(HasRareData());
+ return rare_data_->exclusion_space;
+ }
+
+ return space_.ExclusionSpace();
+ }
NGLayoutResultStatus Status() const {
- return static_cast<NGLayoutResultStatus>(status_);
+ return static_cast<NGLayoutResultStatus>(bitfields_.status);
}
- LayoutUnit BfcLineOffset() const { return bfc_line_offset_; }
- const base::Optional<LayoutUnit>& BfcBlockOffset() const {
- return bfc_block_offset_;
+ LayoutUnit BfcLineOffset() const {
+ if (HasRareData())
+ return rare_data_->bfc_line_offset;
+
+ if (bitfields_.has_oof_positioned_offset) {
+ DCHECK(physical_fragment_->IsOutOfFlowPositioned());
+ return LayoutUnit();
+ }
+
+ return bfc_offset_.line_offset;
}
- const NGMarginStrut EndMarginStrut() const { return end_margin_strut_; }
+ const base::Optional<LayoutUnit> BfcBlockOffset() const {
+ if (HasRareData())
+ return rare_data_->bfc_block_offset;
+
+ if (bitfields_.has_oof_positioned_offset) {
+ DCHECK(physical_fragment_->IsOutOfFlowPositioned());
+ return LayoutUnit();
+ }
+
+ if (bitfields_.is_bfc_block_offset_nullopt)
+ return base::nullopt;
+
+ return bfc_offset_.block_offset;
+ }
+
+ const NGMarginStrut EndMarginStrut() const {
+ return HasRareData() ? rare_data_->end_margin_strut : NGMarginStrut();
+ }
const LayoutUnit IntrinsicBlockSize() const {
DCHECK(physical_fragment_->Type() == NGPhysicalFragment::kFragmentBox ||
@@ -83,41 +117,50 @@ class CORE_EXPORT NGLayoutResult : public RefCounted<NGLayoutResult> {
return intrinsic_block_size_;
}
- LayoutUnit MinimalSpaceShortage() const { return minimal_space_shortage_; }
+ LayoutUnit MinimalSpaceShortage() const {
+ return HasRareData() ? rare_data_->minimal_space_shortage
+ : LayoutUnit::Max();
+ }
// The break-before value on the first child needs to be propagated to the
// container, in search of a valid class A break point.
- EBreakBetween InitialBreakBefore() const { return initial_break_before_; }
+ EBreakBetween InitialBreakBefore() const {
+ return static_cast<EBreakBetween>(bitfields_.initial_break_before);
+ }
// The break-after value on the last child needs to be propagated to the
// container, in search of a valid class A break point.
- EBreakBetween FinalBreakAfter() const { return final_break_after_; }
+ EBreakBetween FinalBreakAfter() const {
+ return static_cast<EBreakBetween>(bitfields_.final_break_after);
+ }
// Return true if the fragment broke because a forced break before a child.
- bool HasForcedBreak() const { return has_forced_break_; }
+ bool HasForcedBreak() const { return bitfields_.has_forced_break; }
// Returns true if the fragment should be considered empty for margin
// collapsing purposes (e.g. margins "collapse through").
- bool IsSelfCollapsing() const { return is_self_collapsing_; }
+ bool IsSelfCollapsing() const { return bitfields_.is_self_collapsing; }
// Return true if this fragment got its block offset increased by the presence
// of floats.
- bool IsPushedByFloats() const { return is_pushed_by_floats_; }
-
- // Return the types (none, left, right, both) of preceding adjoining
- // floats. These are floats that are added while the in-flow BFC block offset
- // is still unknown. The floats may or may not be unpositioned (pending). That
- // depends on which layout pass we're in. Adjoining floats should be treated
- // differently when calculating clearance on a block with adjoining
- // block-start margin (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_; }
+ bool IsPushedByFloats() const { return bitfields_.is_pushed_by_floats; }
+
+ // Returns the types of preceding adjoining objects.
+ // See |NGAdjoiningObjectTypes|.
+ //
+ // Adjoining floats should be treated differently when calculating clearance
+ // on a block with adjoining block-start margin (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).
+ NGAdjoiningObjectTypes AdjoiningObjectTypes() const {
+ return bitfields_.adjoining_object_types;
+ }
// Returns true if the initial (pre-layout) block-size of this fragment was
// indefinite. (e.g. it has "height: auto").
bool IsInitialBlockSizeIndefinite() const {
- return is_initial_block_size_indefinite_;
+ return bitfields_.is_initial_block_size_indefinite;
}
// Returns true if there is a descendant that depends on percentage
@@ -126,15 +169,17 @@ class CORE_EXPORT NGLayoutResult : public RefCounted<NGLayoutResult> {
// percentage sizing behaviour (typically when their parent layout forces a
// block-size on them).
bool HasDescendantThatDependsOnPercentageBlockSize() const {
- return has_descendant_that_depends_on_percentage_block_size_;
+ return bitfields_.has_descendant_that_depends_on_percentage_block_size;
}
// Returns true if the space stored with this layout result, is valid.
- bool HasValidConstraintSpaceForCaching() const { return has_valid_space_; }
+ bool HasValidConstraintSpaceForCaching() const {
+ return bitfields_.has_valid_space;
+ }
// Returns the space which generated this object for caching purposes.
const NGConstraintSpace& GetConstraintSpaceForCaching() const {
- DCHECK(has_valid_space_);
+ DCHECK(bitfields_.has_valid_space);
return space_;
}
@@ -147,7 +192,17 @@ class CORE_EXPORT NGLayoutResult : public RefCounted<NGLayoutResult> {
friend class NGOutOfFlowLayoutPart;
void SetOutOfFlowPositionedOffset(const LogicalOffset& offset) {
- layout_result_->oof_positioned_offset_ = offset;
+ // OOF-positioned nodes *must* always have an initial BFC-offset.
+ DCHECK(layout_result_->physical_fragment_->IsOutOfFlowPositioned());
+ DCHECK_EQ(layout_result_->BfcLineOffset(), LayoutUnit());
+ DCHECK_EQ(layout_result_->BfcBlockOffset().value_or(LayoutUnit()),
+ LayoutUnit());
+
+ layout_result_->bitfields_.has_oof_positioned_offset = true;
+ if (layout_result_->HasRareData())
+ layout_result_->rare_data_->oof_positioned_offset = offset;
+ else
+ layout_result_->oof_positioned_offset_ = offset;
}
private:
@@ -183,9 +238,18 @@ class CORE_EXPORT NGLayoutResult : public RefCounted<NGLayoutResult> {
// This constructor is for a non-success status.
NGLayoutResult(NGLayoutResultStatus, NGBoxFragmentBuilder*);
- // 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.
+ // We don't need the copy constructor, move constructor, copy
+ // assigmnment-operator, or move assignment-operator today.
+ // Delete these to clarify that they will not work because a |RefCounted|
+ // object can't be copied directly.
+ //
+ // If at some point we do need these constructors particular care will need
+ // to be taken with the |rare_data_| field which is manually memory managed.
NGLayoutResult(const NGLayoutResult&) = delete;
+ NGLayoutResult(NGLayoutResult&&) = delete;
+ NGLayoutResult& operator=(const NGLayoutResult& other) = delete;
+ NGLayoutResult& operator=(NGLayoutResult&& other) = delete;
+ NGLayoutResult() = delete;
// Delegate constructor that sets up what it can, based on the builder.
NGLayoutResult(
@@ -199,40 +263,109 @@ class CORE_EXPORT NGLayoutResult : public RefCounted<NGLayoutResult> {
LayoutUnit bfc_line_offset,
base::Optional<LayoutUnit> bfc_block_offset);
- // The constraint space which generated this layout result, may not be valid
- // as indicated by |has_valid_space_|.
- const NGConstraintSpace space_;
+ struct RareData {
+ USING_FAST_MALLOC(RareData);
- scoped_refptr<const NGPhysicalContainerFragment> physical_fragment_;
+ public:
+ RareData(LayoutUnit bfc_line_offset,
+ base::Optional<LayoutUnit> bfc_block_offset)
+ : bfc_line_offset(bfc_line_offset),
+ bfc_block_offset(bfc_block_offset) {}
- // This is the final position of an OOF-positioned object in its parent's
- // writing-mode. This is set by the |NGOutOfFlowLayoutPart| while generating
- // this layout result.
- // This field is unused for other objects.
- LogicalOffset oof_positioned_offset_;
- NGUnpositionedListMarker unpositioned_list_marker_;
-
- const NGExclusionSpace exclusion_space_;
- const LayoutUnit bfc_line_offset_;
- const base::Optional<LayoutUnit> bfc_block_offset_;
- const NGMarginStrut end_margin_strut_;
- LayoutUnit intrinsic_block_size_;
- LayoutUnit minimal_space_shortage_ = LayoutUnit::Max();
+ LayoutUnit bfc_line_offset;
+ base::Optional<LayoutUnit> bfc_block_offset;
- EBreakBetween initial_break_before_ = EBreakBetween::kAuto;
- EBreakBetween final_break_after_ = EBreakBetween::kAuto;
+ LogicalOffset oof_positioned_offset;
+ NGMarginStrut end_margin_strut;
+ NGUnpositionedListMarker unpositioned_list_marker;
+ LayoutUnit minimal_space_shortage = LayoutUnit::Max();
+ NGExclusionSpace exclusion_space;
+ };
- unsigned has_valid_space_ : 1;
- unsigned has_forced_break_ : 1;
+ bool HasRareData() const { return bitfields_.has_rare_data; }
+ RareData* EnsureRareData();
+
+ struct Bitfields {
+ DISALLOW_NEW();
+
+ public:
+ // We define the default constructor so that the |has_rare_data| bit is
+ // never uninitialized (potentially allowing a dangling pointer).
+ Bitfields()
+ : Bitfields(
+ /* has_valid_space */ false,
+ /* is_self_collapsing */ false,
+ /* is_pushed_by_floats */ false,
+ /* adjoining_object_types */ kAdjoiningNone,
+ /* has_descendant_that_depends_on_percentage_block_size */
+ false) {}
+ Bitfields(bool has_valid_space,
+ bool is_self_collapsing,
+ bool is_pushed_by_floats,
+ NGAdjoiningObjectTypes adjoining_object_types,
+ bool has_descendant_that_depends_on_percentage_block_size)
+ : has_rare_data(false),
+ has_rare_data_exclusion_space(false),
+ has_oof_positioned_offset(false),
+ is_bfc_block_offset_nullopt(false),
+ has_valid_space(has_valid_space),
+ has_forced_break(false),
+ is_self_collapsing(is_self_collapsing),
+ is_pushed_by_floats(is_pushed_by_floats),
+ adjoining_object_types(static_cast<unsigned>(adjoining_object_types)),
+ is_initial_block_size_indefinite(false),
+ has_descendant_that_depends_on_percentage_block_size(
+ has_descendant_that_depends_on_percentage_block_size),
+ initial_break_before(static_cast<unsigned>(EBreakBetween::kAuto)),
+ final_break_after(static_cast<unsigned>(EBreakBetween::kAuto)),
+ status(static_cast<unsigned>(kSuccess)) {}
+
+ unsigned has_rare_data : 1;
+ unsigned has_rare_data_exclusion_space : 1;
+ unsigned has_oof_positioned_offset : 1;
+ unsigned is_bfc_block_offset_nullopt : 1;
+
+ unsigned has_valid_space : 1;
+ unsigned has_forced_break : 1;
+
+ unsigned is_self_collapsing : 1;
+ unsigned is_pushed_by_floats : 1;
+ unsigned adjoining_object_types : 3; // NGAdjoiningObjectTypes
+
+ unsigned is_initial_block_size_indefinite : 1;
+ unsigned has_descendant_that_depends_on_percentage_block_size : 1;
+
+ unsigned initial_break_before : 4; // EBreakBetween
+ unsigned final_break_after : 4; // EBreakBetween
+
+ unsigned status : 1; // NGLayoutResultStatus
+ };
- unsigned is_self_collapsing_ : 1;
- unsigned is_pushed_by_floats_ : 1;
- unsigned adjoining_floats_ : 3; // NGFloatTypes
+ // The constraint space which generated this layout result, may not be valid
+ // as indicated by |Bitfields::has_valid_space|.
+ const NGConstraintSpace space_;
- unsigned is_initial_block_size_indefinite_ : 1;
- unsigned has_descendant_that_depends_on_percentage_block_size_ : 1;
+ scoped_refptr<const NGPhysicalContainerFragment> physical_fragment_;
- unsigned status_ : 1;
+ // To save space, we union these fields.
+ // - |rare_data_| is valid if the |Bitfields::has_rare_data| bit is set.
+ // |bfc_offset_| and |oof_positioned_offset_| are stored within the
+ // |RareData| object for this case.
+ // - |oof_positioned_offset_| is valid if the
+ // |Bitfields::has_oof_positioned_offset| bit is set. As the node is
+ // OOF-positioned the |bfc_offset_| is *always* the initial value.
+ // - Otherwise |bfc_offset_| is valid.
+ union {
+ NGBfcOffset bfc_offset_;
+ // This is the final position of an OOF-positioned object in its parent's
+ // writing-mode. This is set by the |NGOutOfFlowLayoutPart| while
+ // generating this layout result.
+ LogicalOffset oof_positioned_offset_;
+ RareData* rare_data_;
+ };
+
+ LayoutUnit intrinsic_block_size_;
+ Bitfields bitfields_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_layout_utils.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_layout_utils.cc
index 165908d0206..1b483aa6c82 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_layout_utils.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_layout_utils.cc
@@ -448,8 +448,7 @@ bool IsBlockLayoutComplete(const NGConstraintSpace& space,
return false;
if (space.IsIntermediateLayout())
return false;
- // Check that we're done positioning pending floats.
- return !result.AdjoiningFloatTypes() || result.BfcBlockOffset();
+ return true;
}
} // namespace blink
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 57d100f7344..fe2b09b97a8 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
@@ -18,7 +18,7 @@
#include "third_party/blink/renderer/core/layout/ng/ng_fragment.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"
+#include "third_party/blink/renderer/core/layout/ng/ng_out_of_flow_positioned_node.h"
#include "third_party/blink/renderer/core/layout/ng/ng_physical_fragment.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
@@ -33,7 +33,7 @@ bool IsAnonymousContainer(const LayoutObject* layout_object) {
}
// When the containing block is a split inline, Legacy and NG use different
-// containers to place the OOF descendant:
+// containers to place the OOF-positioned nodes:
// - Legacy uses the anonymous block generated by inline.
// - NG uses the anonymous' parent block, that contains all the anonymous
// continuations.
@@ -79,22 +79,24 @@ NGOutOfFlowLayoutPart::NGOutOfFlowLayoutPart(
container_builder) {}
NGOutOfFlowLayoutPart::NGOutOfFlowLayoutPart(
- bool contains_absolute,
- bool contains_fixed,
+ bool is_absolute_container,
+ bool is_fixed_container,
const ComputedStyle& container_style,
const NGConstraintSpace& container_space,
const NGBoxStrut& border_scrollbar,
NGBoxFragmentBuilder* container_builder,
base::Optional<LogicalSize> initial_containing_block_fixed_size)
- : container_builder_(container_builder),
- contains_absolute_(contains_absolute),
- contains_fixed_(contains_fixed) {
- if (!container_builder->HasOutOfFlowDescendantCandidates() &&
+ : container_space_(container_space),
+ container_builder_(container_builder),
+ writing_mode_(container_style.GetWritingMode()),
+ is_absolute_container_(is_absolute_container),
+ is_fixed_container_(is_fixed_container) {
+ if (!container_builder->HasOutOfFlowPositionedCandidates() &&
!To<LayoutBlock>(container_builder_->GetLayoutObject())
->HasPositionedObjects())
return;
- default_containing_block_.style = &container_style;
+ default_containing_block_.direction = container_style.Direction();
default_containing_block_.content_size_for_absolute =
ShrinkAvailableSize(container_builder_->Size(), border_scrollbar);
default_containing_block_.content_size_for_fixed =
@@ -104,42 +106,36 @@ NGOutOfFlowLayoutPart::NGOutOfFlowLayoutPart(
default_containing_block_.container_offset = LogicalOffset(
border_scrollbar.inline_start, border_scrollbar.block_start);
-
- NGPhysicalBoxStrut physical_border_scrollbar =
- border_scrollbar.ConvertToPhysical(container_style.GetWritingMode(),
- container_style.Direction());
- default_containing_block_.physical_container_offset = PhysicalOffset(
- physical_border_scrollbar.left, physical_border_scrollbar.top);
}
void NGOutOfFlowLayoutPart::Run(const LayoutBox* only_layout) {
- Vector<NGOutOfFlowPositionedDescendant> descendant_candidates;
+ Vector<NGLogicalOutOfFlowPositionedNode> candidates;
const LayoutObject* current_container = container_builder_->GetLayoutObject();
- container_builder_->GetAndClearOutOfFlowDescendantCandidates(
- &descendant_candidates, current_container);
+ container_builder_->SwapOutOfFlowPositionedCandidates(&candidates,
+ current_container);
- if (descendant_candidates.IsEmpty() &&
+ if (candidates.IsEmpty() &&
!To<LayoutBlock>(current_container)->HasPositionedObjects())
return;
// Special case: containing block is a split inline.
// If current container was generated by a split inline, do not position
- // descendants inside this container. Let its non-anonymous parent handle it.
- // Only parent has geometry information needed to compute containing block
- // geometry.
+ // OOF-positioned nodes inside this container. Let its non-anonymous parent
+ // handle it. Only the parent has geometry information needed to compute
+ // containing block geometry.
// See "Special case: oof css container" comment for detailed description.
- if (descendant_candidates.size() > 0 && current_container && !only_layout &&
+ if (candidates.size() > 0 && current_container && !only_layout &&
IsAnonymousContainer(current_container)) {
const LayoutInline* absolute_containing_block =
- contains_absolute_ ? GetOOFContainingBlockFromAnonymous(
- current_container, EPosition::kAbsolute)
- : nullptr;
+ is_absolute_container_ ? GetOOFContainingBlockFromAnonymous(
+ current_container, EPosition::kAbsolute)
+ : nullptr;
const LayoutInline* fixed_containing_block =
- contains_fixed_ ? GetOOFContainingBlockFromAnonymous(current_container,
- EPosition::kFixed)
- : nullptr;
- for (auto& candidate : descendant_candidates) {
+ is_fixed_container_ ? GetOOFContainingBlockFromAnonymous(
+ current_container, EPosition::kFixed)
+ : nullptr;
+ for (auto& candidate : candidates) {
if (absolute_containing_block &&
absolute_containing_block->CanContainOutOfFlowPositionedElement(
candidate.node.Style().GetPosition())) {
@@ -155,24 +151,29 @@ void NGOutOfFlowLayoutPart::Run(const LayoutBox* only_layout) {
}
HashSet<const LayoutObject*> placed_objects;
- LayoutDescendantCandidates(&descendant_candidates, only_layout,
- &placed_objects);
+ LayoutCandidates(&candidates, only_layout, &placed_objects);
if (only_layout)
return;
+ // If we're in a block fragmentation context, we've already ruled out the
+ // possibility of having legacy objects in here. The code below would pick up
+ // every OOF candidate not in placed_objects, and treat them as a legacy
+ // object (even if they aren't one), while in fact it could be an NG object
+ // that we have finished laying out in an earlier fragmentainer. Just bail.
+ if (container_space_.HasBlockFragmentation())
+ return;
wtf_size_t prev_placed_objects_size = placed_objects.size();
- while (SweepLegacyDescendants(&placed_objects)) {
- container_builder_->GetAndClearOutOfFlowDescendantCandidates(
- &descendant_candidates, current_container);
+ while (SweepLegacyCandidates(&placed_objects)) {
+ container_builder_->SwapOutOfFlowPositionedCandidates(&candidates,
+ current_container);
// We must have at least one new candidate, otherwise we shouldn't have
// entered this branch.
- DCHECK_GT(descendant_candidates.size(), 0u);
+ DCHECK_GT(candidates.size(), 0u);
- LayoutDescendantCandidates(&descendant_candidates, only_layout,
- &placed_objects);
+ LayoutCandidates(&candidates, only_layout, &placed_objects);
// Legacy currently has a bug where an OOF-positioned node is present
// within the current node's |LayoutBlock::PositionedObjects|, however it
@@ -198,7 +199,7 @@ void NGOutOfFlowLayoutPart::Run(const LayoutBox* only_layout) {
// </div>
// </div>
// Returns false if no new candidates were found.
-bool NGOutOfFlowLayoutPart::SweepLegacyDescendants(
+bool NGOutOfFlowLayoutPart::SweepLegacyCandidates(
HashSet<const LayoutObject*>* placed_objects) {
const auto* container_block =
DynamicTo<LayoutBlock>(container_builder_->GetLayoutObject());
@@ -224,22 +225,25 @@ bool NGOutOfFlowLayoutPart::SweepLegacyDescendants(
if (layout_box->Parent()->IsFlexibleBox()) {
LayoutFlexibleBox* parent = ToLayoutFlexibleBox(layout_box->Parent());
if (parent->SetStaticPositionForPositionedLayout(*layout_box)) {
- NGOutOfFlowPositionedDescendant descendant((NGBlockNode(layout_box)),
- NGStaticPosition());
- LayoutDescendant(descendant, /* only_layout */ nullptr);
+ NGLogicalOutOfFlowPositionedNode candidate((NGBlockNode(layout_box)),
+ NGLogicalStaticPosition());
+ LayoutCandidate(candidate, /* only_layout */ nullptr);
parent->SetStaticPositionForPositionedLayout(*layout_box);
}
}
- NGStaticPosition static_position =
- LayoutBoxUtils::ComputeStaticPositionFromLegacy(*layout_box,
- container_builder_);
+ NGLogicalStaticPosition static_position =
+ LayoutBoxUtils::ComputeStaticPositionFromLegacy(
+ *layout_box,
+ container_builder_->Borders() + container_builder_->Scrollbar(),
+ container_builder_);
const LayoutObject* css_container = layout_box->Container();
if (IsAnonymousContainer(css_container)) {
css_container = GetOOFContainingBlockFromAnonymous(
css_container, layout_box->Style()->GetPosition());
}
+
container_builder_->AddOutOfFlowLegacyCandidate(
NGBlockNode(layout_box), static_position,
ToLayoutInlineOrNull(css_container));
@@ -249,9 +253,9 @@ bool NGOutOfFlowLayoutPart::SweepLegacyDescendants(
const NGOutOfFlowLayoutPart::ContainingBlockInfo&
NGOutOfFlowLayoutPart::GetContainingBlockInfo(
- const NGOutOfFlowPositionedDescendant& descendant) const {
- if (descendant.inline_container) {
- const auto it = containing_blocks_map_.find(descendant.inline_container);
+ const NGLogicalOutOfFlowPositionedNode& candidate) const {
+ if (candidate.inline_container) {
+ const auto it = containing_blocks_map_.find(candidate.inline_container);
DCHECK(it != containing_blocks_map_.end());
return it->value;
}
@@ -259,14 +263,14 @@ NGOutOfFlowLayoutPart::GetContainingBlockInfo(
}
void NGOutOfFlowLayoutPart::ComputeInlineContainingBlocks(
- const Vector<NGOutOfFlowPositionedDescendant>& descendants) {
+ const Vector<NGLogicalOutOfFlowPositionedNode>& candidates) {
NGBoxFragmentBuilder::InlineContainingBlockMap inline_container_fragments;
- for (auto& descendant : descendants) {
- if (descendant.inline_container &&
- !inline_container_fragments.Contains(descendant.inline_container)) {
+ for (auto& candidate : candidates) {
+ if (candidate.inline_container &&
+ !inline_container_fragments.Contains(candidate.inline_container)) {
NGBoxFragmentBuilder::InlineContainingBlockGeometry inline_geometry = {};
- inline_container_fragments.insert(descendant.inline_container,
+ inline_container_fragments.insert(candidate.inline_container,
inline_geometry);
}
}
@@ -275,15 +279,13 @@ void NGOutOfFlowLayoutPart::ComputeInlineContainingBlocks(
&inline_container_fragments);
LogicalSize container_builder_size = container_builder_->Size();
PhysicalSize container_builder_physical_size =
- ToPhysicalSize(container_builder_size,
- default_containing_block_.style->GetWritingMode());
+ ToPhysicalSize(container_builder_size, writing_mode_);
// Translate start/end fragments into ContainingBlockInfo.
for (auto& block_info : inline_container_fragments) {
// Variables needed to describe ContainingBlockInfo
const ComputedStyle* inline_cb_style = block_info.key->Style();
LogicalSize inline_cb_size;
LogicalOffset container_offset;
- PhysicalOffset physical_container_offset;
DCHECK(block_info.value.has_value());
DCHECK(inline_cb_style);
@@ -341,10 +343,7 @@ void NGOutOfFlowLayoutPart::ComputeInlineContainingBlocks(
//
// Note in cases [2a, 2b] we don't allow a "negative" containing block size,
// we clamp negative sizes to zero.
- WritingMode container_writing_mode =
- default_containing_block_.style->GetWritingMode();
- TextDirection container_direction =
- default_containing_block_.style->Direction();
+ TextDirection container_direction = default_containing_block_.direction;
bool is_same_direction =
container_direction == inline_cb_style->Direction();
@@ -353,8 +352,8 @@ void NGOutOfFlowLayoutPart::ComputeInlineContainingBlocks(
const PhysicalRect& start_rect =
block_info.value->start_fragment_union_rect;
LogicalOffset start_offset = start_rect.offset.ConvertToLogical(
- container_writing_mode, container_direction,
- container_builder_physical_size, start_rect.size);
+ writing_mode_, container_direction, container_builder_physical_size,
+ start_rect.size);
// Make sure we add the inline borders, we don't need to do this in the
// inline direction if the blocks are in opposite directions.
@@ -365,11 +364,11 @@ void NGOutOfFlowLayoutPart::ComputeInlineContainingBlocks(
// Step 2 - determine the end_offset.
const PhysicalRect& end_rect = block_info.value->end_fragment_union_rect;
LogicalOffset end_offset = end_rect.offset.ConvertToLogical(
- container_writing_mode, container_direction,
- container_builder_physical_size, end_rect.size);
+ writing_mode_, container_direction, container_builder_physical_size,
+ end_rect.size);
// Add in the size of the fragment to get the logical end of the fragment.
- end_offset += end_rect.size.ConvertToLogical(container_writing_mode);
+ end_offset += end_rect.size.ConvertToLogical(writing_mode_);
// Make sure we subtract the inline borders, we don't need to do this in the
// inline direction if the blocks are in opposite directions.
@@ -380,7 +379,8 @@ void NGOutOfFlowLayoutPart::ComputeInlineContainingBlocks(
// Make sure we don't end up with a rectangle with "negative" size.
end_offset.inline_offset =
std::max(end_offset.inline_offset, start_offset.inline_offset);
-
+ end_offset.block_offset =
+ std::max(end_offset.block_offset, start_offset.block_offset);
// Step 3 - determine the logical rectangle.
// Determine the logical size of the containing block.
@@ -389,30 +389,27 @@ void NGOutOfFlowLayoutPart::ComputeInlineContainingBlocks(
DCHECK_GE(inline_cb_size.inline_size, LayoutUnit());
DCHECK_GE(inline_cb_size.block_size, LayoutUnit());
- // Determine the container offsets.
+ // Set the container padding-box offset.
container_offset = start_offset;
- physical_container_offset = container_offset.ConvertToPhysical(
- container_writing_mode, container_direction,
- container_builder_physical_size,
- ToPhysicalSize(inline_cb_size, container_writing_mode));
+
containing_blocks_map_.insert(
block_info.key,
- ContainingBlockInfo{inline_cb_style, inline_cb_size, inline_cb_size,
- container_offset, physical_container_offset});
+ ContainingBlockInfo{inline_cb_style->Direction(), inline_cb_size,
+ inline_cb_size, container_offset});
}
}
-void NGOutOfFlowLayoutPart::LayoutDescendantCandidates(
- Vector<NGOutOfFlowPositionedDescendant>* descendant_candidates,
+void NGOutOfFlowLayoutPart::LayoutCandidates(
+ Vector<NGLogicalOutOfFlowPositionedNode>* candidates,
const LayoutBox* only_layout,
HashSet<const LayoutObject*>* placed_objects) {
- while (descendant_candidates->size() > 0) {
- ComputeInlineContainingBlocks(*descendant_candidates);
- for (auto& candidate : *descendant_candidates) {
- if (IsContainingBlockForDescendant(candidate) &&
+ while (candidates->size() > 0) {
+ ComputeInlineContainingBlocks(*candidates);
+ for (auto& candidate : *candidates) {
+ if (IsContainingBlockForCandidate(candidate) &&
(!only_layout || candidate.node.GetLayoutBox() == only_layout)) {
scoped_refptr<const NGLayoutResult> result =
- LayoutDescendant(candidate, only_layout);
+ LayoutCandidate(candidate, only_layout);
container_builder_->AddChild(result->PhysicalFragment(),
result->OutOfFlowPositionedOffset(),
candidate.inline_container);
@@ -423,18 +420,18 @@ void NGOutOfFlowLayoutPart::LayoutDescendantCandidates(
container_builder_->AddOutOfFlowDescendant(candidate);
}
}
- // Sweep any descendants that might have been added.
+ // Sweep any candidates that might have been added.
// This happens when an absolute container has a fixed child.
- descendant_candidates->Shrink(0);
- container_builder_->GetAndClearOutOfFlowDescendantCandidates(
- descendant_candidates, container_builder_->GetLayoutObject());
+ candidates->Shrink(0);
+ container_builder_->SwapOutOfFlowPositionedCandidates(
+ candidates, container_builder_->GetLayoutObject());
}
}
-scoped_refptr<const NGLayoutResult> NGOutOfFlowLayoutPart::LayoutDescendant(
- const NGOutOfFlowPositionedDescendant& descendant,
+scoped_refptr<const NGLayoutResult> NGOutOfFlowLayoutPart::LayoutCandidate(
+ const NGLogicalOutOfFlowPositionedNode& candidate,
const LayoutBox* only_layout) {
- NGBlockNode node = descendant.node;
+ NGBlockNode node = candidate.node;
// "NGOutOfFlowLayoutPart container is ContainingBlock" invariant cannot
// be enforced for tables. Tables are special, in that the ContainingBlock is
@@ -444,19 +441,16 @@ scoped_refptr<const NGLayoutResult> NGOutOfFlowLayoutPart::LayoutDescendant(
node.GetLayoutBox()->ContainingBlock()) ||
node.GetLayoutBox()->ContainingBlock()->IsTable());
- const ContainingBlockInfo& container_info =
- GetContainingBlockInfo(descendant);
- const ComputedStyle& container_style = *container_info.style;
- const ComputedStyle& descendant_style = node.Style();
-
- WritingMode container_writing_mode = container_style.GetWritingMode();
- WritingMode descendant_writing_mode = descendant_style.GetWritingMode();
+ const ContainingBlockInfo& container_info = GetContainingBlockInfo(candidate);
+ const TextDirection default_direction = default_containing_block_.direction;
+ const ComputedStyle& candidate_style = node.Style();
+ const WritingMode candidate_writing_mode = candidate_style.GetWritingMode();
+ const TextDirection candidate_direction = candidate_style.Direction();
LogicalSize container_content_size =
- container_info.ContentSize(descendant_style.GetPosition());
- LogicalSize container_content_size_in_child_writing_mode =
- ToPhysicalSize(container_content_size, container_writing_mode)
- .ConvertToLogical(descendant_writing_mode);
+ container_info.ContentSize(candidate_style.GetPosition());
+ PhysicalSize container_physical_content_size =
+ ToPhysicalSize(container_content_size, writing_mode_);
// Determine if we need to actually run the full OOF-positioned sizing, and
// positioning algorithm.
@@ -464,23 +458,34 @@ scoped_refptr<const NGLayoutResult> NGOutOfFlowLayoutPart::LayoutDescendant(
// When this candidate has an inline container, the container may move without
// setting |NeedsLayout()| to the candidate and that there are cases where the
// cache validity cannot be determined.
- if (!descendant.inline_container) {
+ if (!candidate.inline_container) {
+ LogicalSize container_content_size_in_candidate_writing_mode =
+ container_physical_content_size.ConvertToLogical(
+ candidate_writing_mode);
if (scoped_refptr<const NGLayoutResult> cached_result =
node.CachedLayoutResultForOutOfFlowPositioned(
- container_content_size_in_child_writing_mode))
+ container_content_size_in_candidate_writing_mode))
return cached_result;
}
// Adjust the |static_position| (which is currently relative to the default
// container's border-box). ng_absolute_utils expects the static position to
// be relative to the container's padding-box.
- NGStaticPosition static_position(descendant.static_position);
- static_position.offset -= container_info.physical_container_offset;
-
- NGConstraintSpace descendant_constraint_space =
- NGConstraintSpaceBuilder(container_writing_mode, descendant_writing_mode,
+ NGLogicalStaticPosition static_position = candidate.static_position;
+ static_position.offset -= container_info.container_offset;
+
+ NGLogicalStaticPosition candidate_static_position =
+ static_position
+ .ConvertToPhysical(writing_mode_, default_direction,
+ container_physical_content_size)
+ .ConvertToLogical(candidate_writing_mode, candidate_direction,
+ container_physical_content_size);
+
+ // Need a constraint space to resolve offsets.
+ NGConstraintSpace candidate_constraint_space =
+ NGConstraintSpaceBuilder(writing_mode_, candidate_writing_mode,
/* is_new_fc */ true)
- .SetTextDirection(descendant_style.Direction())
+ .SetTextDirection(candidate_direction)
.SetAvailableSize(container_content_size)
.SetPercentageResolutionSize(container_content_size)
.ToConstraintSpace();
@@ -489,7 +494,7 @@ scoped_refptr<const NGLayoutResult> NGOutOfFlowLayoutPart::LayoutDescendant(
freeze_scrollbars;
do {
scoped_refptr<const NGLayoutResult> layout_result =
- Layout(node, descendant_constraint_space, static_position,
+ Layout(node, candidate_constraint_space, candidate_static_position,
container_content_size, container_info, only_layout);
if (!freeze_scrollbars.has_value()) {
@@ -502,7 +507,7 @@ scoped_refptr<const NGLayoutResult> NGOutOfFlowLayoutPart::LayoutDescendant(
// have the same logic in legacy layout in
// |LayoutBlockFlow::UpdateBlockLayout()|.
if (node.GetLayoutBox()->PreferredLogicalWidthsDirty() &&
- AbsoluteNeedsChildInlineSize(descendant_style)) {
+ AbsoluteNeedsChildInlineSize(candidate_style)) {
// Freeze the scrollbars for this layout pass. We don't want them to
// change *again*.
freeze_scrollbars.emplace();
@@ -516,83 +521,160 @@ scoped_refptr<const NGLayoutResult> NGOutOfFlowLayoutPart::LayoutDescendant(
scoped_refptr<const NGLayoutResult> NGOutOfFlowLayoutPart::Layout(
NGBlockNode node,
- const NGConstraintSpace& descendant_constraint_space,
- const NGStaticPosition& static_position,
+ const NGConstraintSpace& candidate_constraint_space,
+ const NGLogicalStaticPosition& candidate_static_position,
LogicalSize container_content_size,
const ContainingBlockInfo& container_info,
const LayoutBox* only_layout) {
- const ComputedStyle& container_style = *container_info.style;
- const ComputedStyle& descendant_style = node.Style();
- WritingMode container_writing_mode = container_style.GetWritingMode();
- WritingMode descendant_writing_mode = descendant_style.GetWritingMode();
-
- LogicalSize container_content_size_in_child_writing_mode =
- ToPhysicalSize(container_content_size, container_writing_mode)
- .ConvertToLogical(descendant_writing_mode);
+ const TextDirection default_direction = default_containing_block_.direction;
+ const ComputedStyle& candidate_style = node.Style();
+ const WritingMode candidate_writing_mode = candidate_style.GetWritingMode();
+ const TextDirection candidate_direction = candidate_style.Direction();
+ const TextDirection container_direction = container_info.direction;
+
+ PhysicalSize container_physical_content_size =
+ ToPhysicalSize(container_content_size, writing_mode_);
+ LogicalSize container_content_size_in_candidate_writing_mode =
+ container_physical_content_size.ConvertToLogical(candidate_writing_mode);
NGBoxStrut border_padding =
- ComputeBorders(descendant_constraint_space, node) +
- ComputePadding(descendant_constraint_space, descendant_style);
+ ComputeBorders(candidate_constraint_space, node) +
+ ComputePadding(candidate_constraint_space, candidate_style);
- // The |block_estimate| is wrt. the descendant's writing mode.
+ // The |block_estimate| is wrt. the candidate's writing mode.
base::Optional<LayoutUnit> block_estimate;
base::Optional<MinMaxSize> min_max_size;
scoped_refptr<const NGLayoutResult> layout_result = nullptr;
+ // In order to calculate the offsets, we may need to know the size.
+
+ // In some cases we will need the fragment size in order to calculate the
+ // offset. We may have to lay out to get the fragment size. For block
+ // fragmentation, we *need* to know the block-offset before layout. In other
+ // words, in that case, we may have to lay out, calculate the offset, and
+ // then lay out again at the correct block-offset.
+
bool is_replaced = node.IsReplaced();
bool should_be_considered_as_replaced = node.ShouldBeConsideredAsReplaced();
- if (AbsoluteNeedsChildInlineSize(descendant_style) ||
- NeedMinMaxSize(descendant_style) || should_be_considered_as_replaced) {
+ if (AbsoluteNeedsChildInlineSize(candidate_style) ||
+ NeedMinMaxSize(candidate_style) || should_be_considered_as_replaced) {
// This is a new formatting context, so whatever happened on the outside
// doesn't concern us.
MinMaxSizeInput input(container_content_size.block_size);
min_max_size = ComputeMinAndMaxContentSizeForOutOfFlow(
- descendant_constraint_space, node, border_padding, input);
+ candidate_constraint_space, node, border_padding, input);
}
base::Optional<LogicalSize> replaced_size;
if (is_replaced) {
replaced_size =
- ComputeReplacedSize(node, descendant_constraint_space, min_max_size);
+ ComputeReplacedSize(node, candidate_constraint_space, min_max_size);
} else if (should_be_considered_as_replaced) {
- replaced_size = LogicalSize{
- min_max_size->ShrinkToFit(
- descendant_constraint_space.AvailableSize().inline_size),
- kIndefiniteSize};
+ replaced_size =
+ LogicalSize{min_max_size->ShrinkToFit(
+ candidate_constraint_space.AvailableSize().inline_size),
+ kIndefiniteSize};
}
- NGAbsolutePhysicalPosition node_position =
+ NGLogicalOutOfFlowPosition node_position =
ComputePartialAbsoluteWithChildInlineSize(
- descendant_constraint_space, descendant_style, border_padding,
- static_position, min_max_size, replaced_size, container_writing_mode,
- container_style.Direction());
+ candidate_constraint_space, candidate_style, border_padding,
+ candidate_static_position, min_max_size, replaced_size, writing_mode_,
+ container_direction);
// |should_be_considered_as_replaced| sets the inline-size.
// It does not set the block-size. This is a compatibility quirk.
if (!is_replaced && should_be_considered_as_replaced)
replaced_size.reset();
- if (AbsoluteNeedsChildBlockSize(descendant_style)) {
+ if (AbsoluteNeedsChildBlockSize(candidate_style)) {
layout_result =
- GenerateFragment(node, container_content_size_in_child_writing_mode,
+ GenerateFragment(node, container_content_size_in_candidate_writing_mode,
block_estimate, node_position);
- NGFragment fragment(descendant_writing_mode,
+ NGFragment fragment(candidate_writing_mode,
layout_result->PhysicalFragment());
block_estimate = fragment.BlockSize();
}
+ // Calculate the offsets.
+
ComputeFullAbsoluteWithChildBlockSize(
- descendant_constraint_space, descendant_style, border_padding,
- static_position, block_estimate, replaced_size, container_writing_mode,
- container_style.Direction(), &node_position);
+ candidate_constraint_space, candidate_style, border_padding,
+ candidate_static_position, block_estimate, replaced_size, writing_mode_,
+ container_direction, &node_position);
+
+ NGBoxStrut inset =
+ node_position.inset
+ .ConvertToPhysical(candidate_writing_mode, candidate_direction)
+ .ConvertToLogical(writing_mode_, default_direction);
+
+ // |inset| is relative to the container's padding-box. Convert this to being
+ // relative to the default container's border-box.
+ LogicalOffset offset = container_info.container_offset;
+ offset.inline_offset += inset.inline_start;
+ offset.block_offset += inset.block_start;
+
+ if (!only_layout) {
+ // Special case: oof css container is a split inline.
+ // When css container spans multiple anonymous blocks, its dimensions can
+ // only be computed by a block that is an ancestor of all fragments
+ // generated by css container. That block is parent of anonymous containing
+ // block.
+ // That is why instead of OOF being placed by its anonymous container,
+ // they get placed by anonymous container's parent.
+ // This is different from all other OOF blocks, and requires special
+ // handling in several places in the OOF code.
+ // There is an exception to special case: if anonymous block is Legacy, we
+ // cannot do the fancy multiple anonymous block traversal, and we handle it
+ // like regular blocks.
+ //
+ // Detailed example:
+ //
+ // If Layout tree looks like this:
+ // LayoutNGBlockFlow#container
+ // LayoutNGBlockFlow (anonymous#1)
+ // LayoutInline#1 (relative)
+ // LayoutNGBlockFlow (anonymous#2 relative)
+ // LayoutNGBlockFlow#oof (positioned)
+ // LayoutNGBlockFlow (anonymous#3)
+ // LayoutInline#3 (continuation)
+ //
+ // The containing block geometry is defined by split inlines,
+ // LayoutInline#1, LayoutInline#3.
+ // Css container anonymous#2 does not have information needed
+ // to compute containing block geometry.
+ // Therefore, #oof cannot be placed by anonymous#2. NG handles this case
+ // by placing #oof in parent of anonymous (#container).
+ //
+ // But, PaintPropertyTreeBuilder expects #oof.Location() to be wrt css
+ // container, #anonymous2. This is why the code below adjusts the legacy
+ // offset from being wrt #container to being wrt #anonymous2.
+ const LayoutObject* container = node.GetLayoutBox()->Container();
+ if (container->IsAnonymousBlock()) {
+ LogicalOffset container_offset =
+ container_builder_->GetChildOffset(container);
+ offset -= container_offset;
+ } else if (container->IsLayoutInline() &&
+ container->ContainingBlock()->IsAnonymousBlock()) {
+ // Location of OOF with inline container, and anonymous containing block
+ // is wrt container.
+ LogicalOffset container_offset =
+ container_builder_->GetChildOffset(container->ContainingBlock());
+ offset -= container_offset;
+ }
+ }
+
+ // We have calculated the offsets, and if we need to lay out, we can do so at
+ // the correct block-start offset now.
+
+ // TODO(mstensho): Actually pass the block-start offset to layout.
// Skip this step if we produced a fragment when estimating the block-size.
if (!layout_result) {
- block_estimate =
- node_position.size.ConvertToLogical(descendant_writing_mode).block_size;
+ block_estimate = node_position.size.block_size;
layout_result =
- GenerateFragment(node, container_content_size_in_child_writing_mode,
+ GenerateFragment(node, container_content_size_in_candidate_writing_mode,
block_estimate, node_position);
}
@@ -606,123 +688,65 @@ scoped_refptr<const NGLayoutResult> NGOutOfFlowLayoutPart::Layout(
// break if we set them here.
if (!container_builder_->GetLayoutObject()
->Style()
- ->IsDisplayFlexibleOrGridBox())
- node.GetLayoutBox()->SetMargin(node_position.margins);
-
- NGBoxStrut inset = node_position.inset.ConvertToLogical(
- container_writing_mode, default_containing_block_.style->Direction());
-
- // |inset| is relative to the container's padding-box. Convert this to being
- // relative to the default container's border-box.
- LogicalOffset offset = container_info.container_offset;
- offset.inline_offset += inset.inline_start;
- offset.block_offset += inset.block_start;
+ ->IsDisplayFlexibleOrGridBox()) {
+ node.GetLayoutBox()->SetMargin(node_position.margins.ConvertToPhysical(
+ candidate_writing_mode, candidate_direction));
+ }
+ // Adjusting the offset for a dialog after layout is fine, since we cannot
+ // have dialogs needing alignment inside block fragmentation.
base::Optional<LayoutUnit> y = ComputeAbsoluteDialogYPosition(
*node.GetLayoutBox(), layout_result->PhysicalFragment().Size().height);
if (y.has_value()) {
- if (IsHorizontalWritingMode(container_writing_mode))
+ DCHECK(!container_space_.HasBlockFragmentation());
+ if (IsHorizontalWritingMode(writing_mode_))
offset.block_offset = *y;
else
offset.inline_offset = *y;
}
- if (only_layout) {
- layout_result->GetMutableForOutOfFlow().SetOutOfFlowPositionedOffset(
- offset);
- return layout_result;
- }
-
- // Special case: oof css container is a split inline.
- // When css container spans multiple anonymous blocks, its dimensions
- // can only be computed by a block that is an ancestor of all fragments
- // generated by css container. That block is parent of anonymous containing
- // block.
- // That is why instead of OOF being placed by its anonymous container,
- // they get placed by anonymous container's parent.
- // This is different from all other OOF blocks, and requires special
- // handling in several places in the OOF code.
- // There is an exception to special case: if anonymous block is Legacy,
- // we cannot do the fancy multiple anonymous block traversal, and we handle
- // it like regular blocks.
- //
- // Detailed example:
- //
- // If Layout tree looks like this:
- // LayoutNGBlockFlow#container
- // LayoutNGBlockFlow (anonymous#1)
- // LayoutInline#1 (relative)
- // LayoutNGBlockFlow (anonymous#2 relative)
- // LayoutNGBlockFlow#oof (positioned)
- // LayoutNGBlockFlow (anonymous#3)
- // LayoutInline#3 (continuation)
- //
- // The containing block geometry is defined by split inlines,
- // LayoutInline#1, LayoutInline#3.
- // Css container anonymous#2 does not have information needed
- // to compute containing block geometry.
- // Therefore, #oof cannot be placed by anonymous#2. NG handles this case
- // by placing #oof in parent of anonymous (#container).
- //
- // But, PaintPropertyTreeBuilder expects #oof.Location() to be wrt
- // css container, #anonymous2. This is why the code below adjusts
- // the legacy offset from being wrt #container to being wrt #anonymous2.
- const LayoutObject* container = node.GetLayoutBox()->Container();
- if (container->IsAnonymousBlock()) {
- LogicalOffset container_offset =
- container_builder_->GetChildOffset(container);
- offset -= container_offset;
- } else if (container->IsLayoutInline() &&
- container->ContainingBlock()->IsAnonymousBlock()) {
- // Location of OOF with inline container, and anonymous containing block
- // is wrt container.
- LogicalOffset container_offset =
- container_builder_->GetChildOffset(container->ContainingBlock());
- offset -= container_offset;
- }
-
layout_result->GetMutableForOutOfFlow().SetOutOfFlowPositionedOffset(offset);
return layout_result;
}
-bool NGOutOfFlowLayoutPart::IsContainingBlockForDescendant(
- const NGOutOfFlowPositionedDescendant& descendant) {
- EPosition position = descendant.node.Style().GetPosition();
+bool NGOutOfFlowLayoutPart::IsContainingBlockForCandidate(
+ const NGLogicalOutOfFlowPositionedNode& candidate) {
+ EPosition position = candidate.node.Style().GetPosition();
- // Descendants whose containing block is inline are always positioned
+ // Candidates whose containing block is inline are always positioned
// inside closest parent block flow.
- if (descendant.inline_container) {
+ if (candidate.inline_container) {
DCHECK(
- descendant.node.Style().GetPosition() == EPosition::kAbsolute &&
- descendant.inline_container->CanContainAbsolutePositionObjects() ||
- (descendant.node.Style().GetPosition() == EPosition::kFixed &&
- descendant.inline_container->CanContainFixedPositionObjects()));
+ candidate.node.Style().GetPosition() == EPosition::kAbsolute &&
+ candidate.inline_container->CanContainAbsolutePositionObjects() ||
+ (candidate.node.Style().GetPosition() == EPosition::kFixed &&
+ candidate.inline_container->CanContainFixedPositionObjects()));
return container_builder_->GetLayoutObject() ==
- descendant.node.GetLayoutBox()->ContainingBlock();
+ candidate.node.GetLayoutBox()->ContainingBlock();
}
- return (contains_absolute_ && position == EPosition::kAbsolute) ||
- (contains_fixed_ && position == EPosition::kFixed);
+ return (is_absolute_container_ && position == EPosition::kAbsolute) ||
+ (is_fixed_container_ && position == EPosition::kFixed);
}
// The fragment is generated in one of these two scenarios:
-// 1. To estimate descendant's block size, in this case block_size is
+// 1. To estimate candidate's block size, in this case block_size is
// container's available size.
// 2. To compute final fragment, when block size is known from the absolute
// position calculation.
scoped_refptr<const NGLayoutResult> NGOutOfFlowLayoutPart::GenerateFragment(
- NGBlockNode descendant,
- const LogicalSize& container_content_size_in_child_writing_mode,
+ NGBlockNode node,
+ const LogicalSize& container_content_size_in_candidate_writing_mode,
const base::Optional<LayoutUnit>& block_estimate,
- const NGAbsolutePhysicalPosition& node_position) {
- // As the |block_estimate| is always in the descendant's writing mode, we
- // build the constraint space in the descendant's writing mode.
- WritingMode writing_mode = descendant.Style().GetWritingMode();
+ const NGLogicalOutOfFlowPosition& node_position) {
+ // As the |block_estimate| is always in the node's writing mode, we
+ // build the constraint space in the node's writing mode.
+ WritingMode writing_mode = node.Style().GetWritingMode();
- LayoutUnit inline_size =
- node_position.size.ConvertToLogical(writing_mode).inline_size;
+ LayoutUnit inline_size = node_position.size.inline_size;
LayoutUnit block_size =
- block_estimate ? *block_estimate
- : container_content_size_in_child_writing_mode.block_size;
+ block_estimate
+ ? *block_estimate
+ : container_content_size_in_candidate_writing_mode.block_size;
LogicalSize available_size(inline_size, block_size);
@@ -730,14 +754,15 @@ scoped_refptr<const NGLayoutResult> NGOutOfFlowLayoutPart::GenerateFragment(
NGConstraintSpaceBuilder builder(writing_mode, writing_mode,
/* is_new_fc */ true);
builder.SetAvailableSize(available_size)
- .SetTextDirection(descendant.Style().Direction())
- .SetPercentageResolutionSize(container_content_size_in_child_writing_mode)
+ .SetTextDirection(node.Style().Direction())
+ .SetPercentageResolutionSize(
+ container_content_size_in_candidate_writing_mode)
.SetIsFixedSizeInline(true);
if (block_estimate)
builder.SetIsFixedSizeBlock(true);
NGConstraintSpace space = builder.ToConstraintSpace();
- return descendant.Layout(space);
+ return node.Layout(space);
}
} // namespace blink
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 e414289366a..dc32c3e1d40 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
@@ -23,7 +23,7 @@ class NGBlockNode;
class NGBoxFragmentBuilder;
class NGConstraintSpace;
class NGLayoutResult;
-struct NGOutOfFlowPositionedDescendant;
+struct NGLogicalOutOfFlowPositionedNode;
// Helper class for positioning of out-of-flow blocks.
// It should be used together with NGBoxFragmentBuilder.
@@ -45,8 +45,8 @@ class CORE_EXPORT NGOutOfFlowLayoutPart {
// (e.g. a relatively positioned inline instead), the containing block here is
// the containing block of said non-block.
NGOutOfFlowLayoutPart(
- bool contains_absolute,
- bool contains_fixed,
+ bool is_absolute_container,
+ bool is_fixed_container,
const ComputedStyle& container_style,
const NGConstraintSpace& container_space,
const NGBoxStrut& border_scrollbar,
@@ -77,17 +77,15 @@ class CORE_EXPORT NGOutOfFlowLayoutPart {
STACK_ALLOCATED();
public:
- // Containing block style.
- const ComputedStyle* style;
+ // The direction of the container.
+ TextDirection direction;
// Logical in containing block coordinates.
LogicalSize content_size_for_absolute;
// Content size for fixed is different for the ICB.
LogicalSize content_size_for_fixed;
- // Offsets (both logical and physical) of the container's padding-box, wrt.
- // the default container's border-box.
+ // Offset of the container's padding-box.
LogicalOffset container_offset;
- PhysicalOffset physical_container_offset;
LogicalSize ContentSize(EPosition position) const {
return position == EPosition::kAbsolute ? content_size_for_absolute
@@ -95,44 +93,44 @@ class CORE_EXPORT NGOutOfFlowLayoutPart {
}
};
- bool SweepLegacyDescendants(HashSet<const LayoutObject*>* placed_objects);
+ bool SweepLegacyCandidates(HashSet<const LayoutObject*>* placed_objects);
const ContainingBlockInfo& GetContainingBlockInfo(
- const NGOutOfFlowPositionedDescendant&) const;
+ const NGLogicalOutOfFlowPositionedNode&) const;
void ComputeInlineContainingBlocks(
- const Vector<NGOutOfFlowPositionedDescendant>&);
+ const Vector<NGLogicalOutOfFlowPositionedNode>&);
- void LayoutDescendantCandidates(
- Vector<NGOutOfFlowPositionedDescendant>* descendant_candidates,
- const LayoutBox* only_layout,
- HashSet<const LayoutObject*>* placed_objects);
+ void LayoutCandidates(Vector<NGLogicalOutOfFlowPositionedNode>* candidates,
+ const LayoutBox* only_layout,
+ HashSet<const LayoutObject*>* placed_objects);
- scoped_refptr<const NGLayoutResult> LayoutDescendant(
- const NGOutOfFlowPositionedDescendant&,
+ scoped_refptr<const NGLayoutResult> LayoutCandidate(
+ const NGLogicalOutOfFlowPositionedNode&,
const LayoutBox* only_layout);
scoped_refptr<const NGLayoutResult> Layout(NGBlockNode,
const NGConstraintSpace&,
- const NGStaticPosition&,
+ const NGLogicalStaticPosition&,
LogicalSize container_content_size,
const ContainingBlockInfo&,
const LayoutBox* only_layout);
- bool IsContainingBlockForDescendant(
- const NGOutOfFlowPositionedDescendant& descendant);
+ bool IsContainingBlockForCandidate(const NGLogicalOutOfFlowPositionedNode&);
scoped_refptr<const NGLayoutResult> GenerateFragment(
NGBlockNode node,
const LogicalSize& container_content_size_in_child_writing_mode,
const base::Optional<LayoutUnit>& block_estimate,
- const NGAbsolutePhysicalPosition& node_position);
+ const NGLogicalOutOfFlowPosition& node_position);
+ const NGConstraintSpace& container_space_;
NGBoxFragmentBuilder* container_builder_;
ContainingBlockInfo default_containing_block_;
HashMap<const LayoutObject*, ContainingBlockInfo> containing_blocks_map_;
- bool contains_absolute_;
- bool contains_fixed_;
+ const WritingMode writing_mode_;
+ bool is_absolute_container_;
+ bool is_fixed_container_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_positioned_descendant.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_positioned_descendant.h
deleted file mode 100644
index cab4bdc6ce5..00000000000
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_positioned_descendant.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 NGOutOfFlowPositionedDescendant_h
-#define NGOutOfFlowPositionedDescendant_h
-
-#include "third_party/blink/renderer/core/core_export.h"
-
-#include "third_party/blink/renderer/core/layout/layout_inline.h"
-#include "third_party/blink/renderer/core/layout/ng/geometry/ng_static_position.h"
-#include "third_party/blink/renderer/core/layout/ng/ng_block_node.h"
-
-namespace blink {
-
-// An out-of-flow positioned-descendant is an element with the style "postion:
-// absolute" or "position: fixed" which hasn't been bubbled up to its
-// containing block yet, e.g. an element with "position: relative". As soon as
-// a descendant reaches its containing block, it gets placed, and doesn't bubble
-// up the tree.
-//
-// This needs its static position [1] to be placed correcting in its containing
-// block.
-//
-// [1] https://www.w3.org/TR/CSS2/visudet.html#abs-non-replaced-width
-struct CORE_EXPORT NGOutOfFlowPositionedDescendant {
- NGBlockNode node;
- NGStaticPosition static_position;
- // Continuation root of the optional inline container.
- const LayoutInline* inline_container;
-
- NGOutOfFlowPositionedDescendant(
- NGBlockNode node,
- NGStaticPosition static_position,
- const LayoutInline* inline_container = nullptr)
- : node(node),
- static_position(static_position),
- inline_container(inline_container) {
- DCHECK(!inline_container ||
- inline_container == inline_container->ContinuationRoot());
- }
-};
-
-} // namespace blink
-
-#endif // NGOutOfFlowPositionedDescendant_h
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_positioned_node.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_positioned_node.h
new file mode 100644
index 00000000000..1037e23bca2
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_positioned_node.h
@@ -0,0 +1,72 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_NG_OUT_OF_FLOW_POSITIONED_NODE_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_NG_OUT_OF_FLOW_POSITIONED_NODE_H_
+
+#include "third_party/blink/renderer/core/core_export.h"
+
+#include "third_party/blink/renderer/core/layout/layout_inline.h"
+#include "third_party/blink/renderer/core/layout/ng/geometry/ng_static_position.h"
+#include "third_party/blink/renderer/core/layout/ng/ng_block_node.h"
+
+namespace blink {
+
+// A physical out-of-flow positioned-node is an element with the style
+// "postion: absolute" or "position: fixed" which hasn't been bubbled up to its
+// containing block yet, (e.g. an element with "position: relative"). As soon
+// as a positioned-node reaches its containing block, it gets placed, and
+// doesn't bubble further up the tree.
+//
+// This needs its static position [1] to be placed correctly in its containing
+// block.
+//
+// This is struct is allowed to be stored/persisted.
+//
+// [1] https://www.w3.org/TR/CSS2/visudet.html#abs-non-replaced-width
+struct CORE_EXPORT NGPhysicalOutOfFlowPositionedNode {
+ NGBlockNode node;
+ NGPhysicalStaticPosition static_position;
+ // Continuation root of the optional inline container.
+ const LayoutInline* inline_container;
+
+ NGPhysicalOutOfFlowPositionedNode(
+ NGBlockNode node,
+ NGPhysicalStaticPosition static_position,
+ const LayoutInline* inline_container = nullptr)
+ : node(node),
+ static_position(static_position),
+ inline_container(inline_container) {
+ DCHECK(!inline_container ||
+ inline_container == inline_container->ContinuationRoot());
+ }
+};
+
+// The logical version of above. It is used within a an algorithm pass (within
+// an |NGContainerFragmentBuilder|), and its logical coordinate system is wrt.
+// the container builder's writing-mode.
+//
+// It is *only* used within an algorithm pass, (it is temporary, and should not
+// be stored/persisted).
+struct NGLogicalOutOfFlowPositionedNode {
+ NGBlockNode node;
+ NGLogicalStaticPosition static_position;
+ // Continuation root of the optional inline container.
+ const LayoutInline* inline_container;
+
+ NGLogicalOutOfFlowPositionedNode(
+ NGBlockNode node,
+ NGLogicalStaticPosition static_position,
+ const LayoutInline* inline_container = nullptr)
+ : node(node),
+ static_position(static_position),
+ inline_container(inline_container) {
+ DCHECK(!inline_container ||
+ inline_container == inline_container->ContinuationRoot());
+ }
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_NG_OUT_OF_FLOW_POSITIONED_NODE_H_
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_outline_utils.h b/chromium/third_party/blink/renderer/core/layout/ng/ng_outline_utils.h
index 0822b8382b8..09107f93607 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_outline_utils.h
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_outline_utils.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_NG_OUTLINE_UTILS_H_
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 5fd401f8e02..0d3e2b52d38 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
@@ -93,6 +93,19 @@ NGPhysicalBoxFragment::NGPhysicalBoxFragment(
builder->layout_object_ && builder->layout_object_->ChildrenInline();
}
+scoped_refptr<const NGLayoutResult>
+NGPhysicalBoxFragment::CloneAsHiddenForPaint() const {
+ const ComputedStyle& style = Style();
+ NGBoxFragmentBuilder builder(GetMutableLayoutObject(), &style,
+ style.GetWritingMode(), style.Direction());
+ builder.SetBoxType(BoxType());
+ NGFragmentGeometry initial_fragment_geometry{
+ Size().ConvertToLogical(style.GetWritingMode())};
+ builder.SetInitialFragmentGeometry(initial_fragment_geometry);
+ builder.SetIsHiddenForPaint(true);
+ return builder.ToBoxFragment();
+}
+
bool NGPhysicalBoxFragment::HasSelfPaintingLayer() const {
SECURITY_DCHECK(GetLayoutObject() && GetLayoutObject()->IsBoxModelObject());
return (static_cast<const LayoutBoxModelObject*>(GetLayoutObject()))
@@ -139,7 +152,7 @@ PhysicalRect NGPhysicalBoxFragment::ScrollableOverflow() const {
return PhysicalRect({}, Size());
}
-IntSize NGPhysicalBoxFragment::ScrolledContentOffset() const {
+LayoutSize NGPhysicalBoxFragment::ScrolledContentOffset() const {
DCHECK(GetLayoutObject() && GetLayoutObject()->IsBox());
const LayoutBox* box = ToLayoutBox(GetLayoutObject());
return box->ScrolledContentOffset();
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 ada1b07cd39..2c7cf70dd22 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
@@ -24,6 +24,8 @@ class CORE_EXPORT NGPhysicalBoxFragment final
NGBoxFragmentBuilder* builder,
WritingMode block_or_line_writing_mode);
+ scoped_refptr<const NGLayoutResult> CloneAsHiddenForPaint() const;
+
~NGPhysicalBoxFragment() {
for (const NGLink& child : Children())
child.fragment->Release();
@@ -62,7 +64,7 @@ class CORE_EXPORT NGPhysicalBoxFragment final
PhysicalRect OverflowClipRect(
const PhysicalOffset& location,
OverlayScrollbarClipBehavior = kIgnorePlatformOverlayScrollbarSize) const;
- IntSize ScrolledContentOffset() const;
+ LayoutSize ScrolledContentOffset() const;
PhysicalSize ScrollSize() const;
// Compute visual overflow of this box in the local coordinate.
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment_test.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment_test.cc
index aee364305bf..71829d7028c 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment_test.cc
@@ -148,4 +148,17 @@ TEST_F(NGPhysicalBoxFragmentTest,
EXPECT_TRUE(fragment->IsBlockFormattingContextRoot());
}
+TEST_F(NGPhysicalBoxFragmentTest, ReplacedBlock) {
+ SetBodyInnerHTML(R"HTML(
+ <img id="target" style="display: block">
+ )HTML");
+ const NGPhysicalBoxFragment& body = GetBodyFragment();
+ const NGPhysicalFragment& fragment = *body.Children().front();
+ EXPECT_EQ(fragment.Type(), NGPhysicalFragment::kFragmentBox);
+ // |LayoutReplaced| sets |IsAtomicInlineLevel()| even when it is block-level.
+ // crbug.com/567964
+ EXPECT_FALSE(fragment.IsAtomicInline());
+ EXPECT_EQ(fragment.BoxType(), NGPhysicalFragment::kBlockFlowRoot);
+}
+
} // namespace blink
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 16af3f47c2f..7527c249d53 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
@@ -18,7 +18,7 @@ namespace {
struct SameSizeAsNGPhysicalContainerFragment : NGPhysicalFragment {
void* break_token;
- std::unique_ptr<Vector<NGOutOfFlowPositionedDescendant>>
+ std::unique_ptr<Vector<NGPhysicalOutOfFlowPositionedNode>>
oof_positioned_descendants_;
void* pointer;
wtf_size_t size;
@@ -41,8 +41,7 @@ NGPhysicalContainerFragment::NGPhysicalContainerFragment(
oof_positioned_descendants_(
builder->oof_positioned_descendants_.IsEmpty()
? nullptr
- : new Vector<NGOutOfFlowPositionedDescendant>(
- std::move(builder->oof_positioned_descendants_))),
+ : new Vector<NGPhysicalOutOfFlowPositionedNode>()),
buffer_(buffer),
num_children_(builder->children_.size()) {
has_floating_descendants_ = builder->has_floating_descendants_;
@@ -51,6 +50,19 @@ NGPhysicalContainerFragment::NGPhysicalContainerFragment(
builder->may_have_descendant_above_block_start_;
depends_on_percentage_block_size_ = DependsOnPercentageBlockSize(*builder);
+ PhysicalSize size = Size();
+ if (oof_positioned_descendants_) {
+ oof_positioned_descendants_->ReserveCapacity(
+ builder->oof_positioned_descendants_.size());
+ for (const auto& descendant : builder->oof_positioned_descendants_) {
+ oof_positioned_descendants_->emplace_back(
+ descendant.node,
+ descendant.static_position.ConvertToPhysical(
+ builder->Style().GetWritingMode(), builder->Direction(), size),
+ descendant.inline_container);
+ }
+ }
+
// 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.
@@ -59,7 +71,7 @@ NGPhysicalContainerFragment::NGPhysicalContainerFragment(
buffer[i].fragment = child.fragment.get();
buffer[i].fragment->AddRef();
buffer[i].offset = child.offset.ConvertToPhysical(
- block_or_line_writing_mode, builder->Direction(), Size(),
+ block_or_line_writing_mode, builder->Direction(), size,
child.fragment->Size());
++i;
}
@@ -160,7 +172,7 @@ void NGPhysicalContainerFragment::AddOutlineRectsForDescendant(
if (!descendant_line_box->Size().IsEmpty()) {
outline_rects->emplace_back(additional_offset,
descendant_line_box->Size().ToLayoutSize());
- } else if (descendant_line_box->Children().IsEmpty()) {
+ } else if (descendant_line_box->Children().empty()) {
// Special-case for when the first continuation does not generate
// fragments. NGInlineLayoutAlgorithm suppresses box fragments when the
// line is "empty". When there is a continuation from the LayoutInline,
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 8b5c9f878f6..9feddca9fcc 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
@@ -17,43 +17,19 @@
namespace blink {
class NGContainerFragmentBuilder;
-struct NGOutOfFlowPositionedDescendant;
+struct NGPhysicalOutOfFlowPositionedNode;
enum class NGOutlineType;
class CORE_EXPORT NGPhysicalContainerFragment : public NGPhysicalFragment {
public:
- class ChildLinkListBase {
+ // Same as |base::span<const NGLink>|, except that each |NGLink| has the
+ // latest generation of post-layout. See
+ // |NGPhysicalFragment::UpdatedFragment()| for more details.
+ class PostLayoutChildLinkList {
public:
- ChildLinkListBase(wtf_size_t count, const NGLink* buffer)
+ PostLayoutChildLinkList(wtf_size_t count, const NGLink* buffer)
: count_(count), buffer_(buffer) {}
- wtf_size_t size() const { return count_; }
- bool IsEmpty() const { return count_ == 0; }
-
- protected:
- wtf_size_t count_;
- const NGLink* buffer_;
- };
-
- class ChildLinkList : public ChildLinkListBase {
- public:
- using ChildLinkListBase::ChildLinkListBase;
-
- const NGLink& operator[](wtf_size_t idx) const { return buffer_[idx]; }
- const NGLink& front() const { return buffer_[0]; }
- const NGLink& back() const { return buffer_[count_ - 1]; }
-
- const NGLink* begin() const { return buffer_; }
- const NGLink* end() const { return begin() + count_; }
- };
-
- // Same as |ChildLinkList|, except that each |NGLink| has the latest
- // generation of post-layout. See |NGPhysicalFragment::UpdatedFragment()| for
- // more details.
- class PostLayoutChildLinkList : public ChildLinkListBase {
- public:
- using ChildLinkListBase::ChildLinkListBase;
-
class ConstIterator {
STACK_ALLOCATED();
@@ -97,6 +73,13 @@ class CORE_EXPORT NGPhysicalContainerFragment : public NGPhysicalFragment {
}
const NGLink front() const { return (*this)[0]; }
const NGLink back() const { return (*this)[count_ - 1]; }
+
+ wtf_size_t size() const { return count_; }
+ bool empty() const { return count_ == 0; }
+
+ private:
+ wtf_size_t count_;
+ const NGLink* buffer_;
};
~NGPhysicalContainerFragment();
@@ -108,8 +91,8 @@ class CORE_EXPORT NGPhysicalContainerFragment : public NGPhysicalFragment {
// Note, children in this collection maybe old generations. Items in this
// collection are safe, but their children (grandchildren of |this|) maybe
// from deleted nodes or LayoutObjects. Also see |PostLayoutChildren()|.
- ChildLinkList Children() const {
- return ChildLinkList(num_children_, buffer_);
+ base::span<const NGLink> Children() const {
+ return base::make_span(buffer_, num_children_);
}
// Similar to |Children()| but all children are the latest generation of
@@ -140,10 +123,10 @@ class CORE_EXPORT NGPhysicalContainerFragment : public NGPhysicalFragment {
return oof_positioned_descendants_.get();
}
- base::span<NGOutOfFlowPositionedDescendant> OutOfFlowPositionedDescendants()
+ base::span<NGPhysicalOutOfFlowPositionedNode> OutOfFlowPositionedDescendants()
const {
if (!HasOutOfFlowPositionedDescendants())
- return base::span<NGOutOfFlowPositionedDescendant>();
+ return base::span<NGPhysicalOutOfFlowPositionedNode>();
return {oof_positioned_descendants_->data(),
oof_positioned_descendants_->size()};
}
@@ -171,7 +154,7 @@ class CORE_EXPORT NGPhysicalContainerFragment : public NGPhysicalFragment {
static bool DependsOnPercentageBlockSize(const NGContainerFragmentBuilder&);
scoped_refptr<NGBreakToken> break_token_;
- const std::unique_ptr<Vector<NGOutOfFlowPositionedDescendant>>
+ const std::unique_ptr<Vector<NGPhysicalOutOfFlowPositionedNode>>
oof_positioned_descendants_;
// Because flexible arrays need to be the last member in a class, the actual
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 b81af6f690c..4d88bbcf1c8 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
@@ -223,6 +223,7 @@ NGPhysicalFragment::NGPhysicalFragment(NGFragmentBuilder* builder,
type_(type),
sub_type_(sub_type),
style_variant_((unsigned)builder->style_variant_),
+ is_hidden_for_paint_(builder->is_hidden_for_paint_),
has_floating_descendants_(false),
is_fieldset_container_(false),
is_legacy_layout_root_(false) {
@@ -239,6 +240,7 @@ NGPhysicalFragment::NGPhysicalFragment(LayoutObject* layout_object,
type_(type),
sub_type_(sub_type),
style_variant_((unsigned)style_variant),
+ is_hidden_for_paint_(false),
has_floating_descendants_(false),
is_fieldset_container_(false),
is_legacy_layout_root_(false) {
@@ -340,7 +342,7 @@ bool NGPhysicalFragment::IsPlacedByLayoutNG() const {
const LayoutBlock* container = layout_object_.ContainingBlock();
if (!container)
return false;
- return container->IsLayoutNGMixin() || container->IsLayoutNGFlexibleBox();
+ return container->IsLayoutNGMixin();
}
const NGPhysicalFragment* NGPhysicalFragment::PostLayout() const {
@@ -357,6 +359,66 @@ const NGPhysicalFragment* NGPhysicalFragment::PostLayout() const {
}
#if DCHECK_IS_ON()
+void NGPhysicalFragment::CheckType() const {
+ switch (Type()) {
+ case kFragmentBox:
+ case kFragmentRenderedLegend:
+ if (IsInlineBox()) {
+ DCHECK(layout_object_.IsLayoutInline());
+ } else {
+ DCHECK(layout_object_.IsBox());
+ }
+ if (IsColumnBox()) {
+ // Column fragments are associated with the same layout object as their
+ // multicol container. The fragments themselves are regular in-flow
+ // block container fragments for most purposes.
+ DCHECK(layout_object_.IsLayoutBlockFlow());
+ DCHECK(IsBox());
+ DCHECK(!IsFloating());
+ DCHECK(!IsOutOfFlowPositioned());
+ DCHECK(!IsAtomicInline());
+ DCHECK(!IsBlockFormattingContextRoot());
+ break;
+ }
+ if (layout_object_.IsLayoutNGListMarker()) {
+ // List marker is an atomic inline if it appears in a line box, or a
+ // block box.
+ DCHECK(!IsFloating());
+ DCHECK(!IsOutOfFlowPositioned());
+ DCHECK(IsAtomicInline() || (IsBox() && BoxType() == kBlockFlowRoot));
+ break;
+ }
+ DCHECK_EQ(IsFloating(), layout_object_.IsFloating());
+ DCHECK_EQ(IsOutOfFlowPositioned(),
+ layout_object_.IsOutOfFlowPositioned());
+ DCHECK_EQ(IsAtomicInline(), layout_object_.IsInline() &&
+ layout_object_.IsAtomicInlineLevel());
+ break;
+ case kFragmentText:
+ if (To<NGPhysicalTextFragment>(this)->IsGeneratedText()) {
+ // Ellipsis has the truncated in-flow LayoutObject.
+ DCHECK(layout_object_.IsText() ||
+ (layout_object_.IsInline() &&
+ layout_object_.IsAtomicInlineLevel()) ||
+ layout_object_.IsLayoutInline());
+ } else {
+ DCHECK(layout_object_.IsText());
+ }
+ DCHECK(!IsFloating());
+ DCHECK(!IsOutOfFlowPositioned());
+ DCHECK(!IsInlineBox());
+ DCHECK(!IsAtomicInline());
+ break;
+ case kFragmentLineBox:
+ DCHECK(layout_object_.IsLayoutBlockFlow());
+ DCHECK(!IsFloating());
+ DCHECK(!IsOutOfFlowPositioned());
+ DCHECK(!IsInlineBox());
+ DCHECK(!IsAtomicInline());
+ break;
+ }
+}
+
void NGPhysicalFragment::CheckCanUpdateInkOverflow() const {
if (!GetLayoutObject())
return;
@@ -470,12 +532,12 @@ bool NGPhysicalFragment::ShouldPaintDragCaret() const {
String NGPhysicalFragment::ToString() const {
StringBuilder output;
output.AppendFormat("Type: '%d' Size: '%s'", Type(),
- Size().ToString().Ascii().data());
+ Size().ToString().Ascii().c_str());
switch (Type()) {
case kFragmentBox:
case kFragmentRenderedLegend:
output.AppendFormat(", BoxType: '%s'",
- StringForBoxType(*this).Ascii().data());
+ StringForBoxType(*this).Ascii().c_str());
break;
case kFragmentText: {
const auto& text = To<NGPhysicalTextFragment>(*this);
@@ -505,7 +567,7 @@ String NGPhysicalFragment::DumpFragmentTree(
#if DCHECK_IS_ON()
void NGPhysicalFragment::ShowFragmentTree() const {
DumpFlags dump_flags = DumpAll;
- LOG(INFO) << "\n" << DumpFragmentTree(dump_flags).Utf8().data();
+ LOG(INFO) << "\n" << DumpFragmentTree(dump_flags).Utf8();
}
#endif
@@ -513,4 +575,16 @@ PhysicalRect NGPhysicalFragmentWithOffset::RectInContainerBox() const {
return {offset_to_container_box, fragment->Size()};
}
+std::ostream& operator<<(std::ostream& out,
+ const NGPhysicalFragment& fragment) {
+ return out << fragment.ToString();
+}
+
+std::ostream& operator<<(std::ostream& out,
+ const NGPhysicalFragment* fragment) {
+ if (!fragment)
+ return out << "<null>";
+ return out << *fragment;
+}
+
} // namespace blink
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 8ed0c068d70..3a58be8c058 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
@@ -101,6 +101,9 @@ class CORE_EXPORT NGPhysicalFragment
bool IsInlineBox() const {
return IsBox() && BoxType() == NGBoxType::kInlineBox;
}
+ bool IsColumnBox() const {
+ return IsBox() && BoxType() == NGBoxType::kColumnBox;
+ }
// An atomic inline is represented as a kFragmentBox, such as inline block and
// replaced elements.
bool IsAtomicInline() const {
@@ -188,6 +191,10 @@ class CORE_EXPORT NGPhysicalFragment
bool HasOverflowClip() const;
bool ShouldClipOverflow() const;
+ // This fragment is hidden for paint purpose, but exists for querying layout
+ // information. Used for `text-overflow: ellipsis`.
+ bool IsHiddenForPaint() const { return is_hidden_for_paint_; }
+
// GetLayoutObject should only be used when necessary for compatibility
// with LegacyLayout.
//
@@ -239,6 +246,7 @@ class CORE_EXPORT NGPhysicalFragment
String ToString() const;
+ void CheckType() const;
void CheckCanUpdateInkOverflow() const;
enum DumpFlag {
@@ -284,6 +292,7 @@ class CORE_EXPORT NGPhysicalFragment
const unsigned type_ : 2; // NGFragmentType
const unsigned sub_type_ : 3; // NGBoxType, NGTextType, or NGLineBoxType
const unsigned style_variant_ : 2; // NGStyleVariant
+ const unsigned is_hidden_for_paint_ : 1;
// The following bitfields are only to be used by NGPhysicalContainerFragment
// (it's defined here to save memory, since that class has no bitfields).
@@ -331,7 +340,11 @@ struct CORE_EXPORT NGPhysicalFragmentWithOffset {
PhysicalRect RectInContainerBox() const;
};
+CORE_EXPORT std::ostream& operator<<(std::ostream&, const NGPhysicalFragment*);
+CORE_EXPORT std::ostream& operator<<(std::ostream&, const NGPhysicalFragment&);
+
#if !DCHECK_IS_ON()
+inline void NGPhysicalFragment::CheckType() const {}
inline void NGPhysicalFragment::CheckCanUpdateInkOverflow() const {}
#endif
diff --git a/chromium/third_party/blink/renderer/core/layout/ng/ng_simplified_layout_algorithm.cc b/chromium/third_party/blink/renderer/core/layout/ng/ng_simplified_layout_algorithm.cc
index ed81dd98250..662e76a1c19 100644
--- a/chromium/third_party/blink/renderer/core/layout/ng/ng_simplified_layout_algorithm.cc
+++ b/chromium/third_party/blink/renderer/core/layout/ng/ng_simplified_layout_algorithm.cc
@@ -4,6 +4,7 @@
#include "third_party/blink/renderer/core/layout/ng/ng_simplified_layout_algorithm.h"
+#include "third_party/blink/renderer/core/layout/logical_values.h"
#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_utils.h"
#include "third_party/blink/renderer/core/layout/ng/ng_box_fragment.h"
@@ -60,7 +61,7 @@ NGSimplifiedLayoutAlgorithm::NGSimplifiedLayoutAlgorithm(
container_builder_.SetIsSelfCollapsing();
if (result.IsPushedByFloats())
container_builder_.SetIsPushedByFloats();
- container_builder_.AddAdjoiningFloatTypes(result.AdjoiningFloatTypes());
+ container_builder_.SetAdjoiningObjectTypes(result.AdjoiningObjectTypes());
for (const auto& request : ConstraintSpace().BaselineRequests()) {
base::Optional<LayoutUnit> baseline = physical_fragment.Baseline(request);
@@ -84,11 +85,16 @@ NGSimplifiedLayoutAlgorithm::NGSimplifiedLayoutAlgorithm(
}
scoped_refptr<const NGLayoutResult> NGSimplifiedLayoutAlgorithm::Layout() {
+ // Since simplified layout's |Layout()| function deals with laying out
+ // children, we can early out if we are display-locked.
+ if (Node().LayoutBlockedByDisplayLock(DisplayLockContext::kChildren))
+ return container_builder_.ToBoxFragment();
+
const auto previous_child_fragments =
To<NGPhysicalBoxFragment>(previous_result_.PhysicalFragment()).Children();
- const auto* it = previous_child_fragments.begin();
- const auto* end = previous_child_fragments.end();
+ auto it = previous_child_fragments.begin();
+ auto end = previous_child_fragments.end();
// We may have a list-marker as our first child. This may have been
// propagated up to this container by an arbitrary child. As we don't know
@@ -141,16 +147,19 @@ scoped_refptr<const NGLayoutResult> NGSimplifiedLayoutAlgorithm::Layout() {
const NGPhysicalContainerFragment& fragment = result->PhysicalFragment();
AddChildFragment(*it, fragment);
- const ComputedStyle& child_style = child.Style();
-
- // Calculate the static block-offset for any OOF-positioned children.
- NGMarginStrut margin_strut = result->EndMarginStrut();
- NGBoxStrut child_margins = ComputeMarginsFor(
- child_style, child_available_inline_size_, writing_mode_, direction_);
- margin_strut.Append(child_margins.block_end,
- child_style.HasMarginBeforeQuirk());
-
- static_block_offset_ += margin_strut.Sum();
+ // Update the static block-offset for any OOF-positioned children.
+ // Only consider inflow children (floats don't contribute to the intrinsic
+ // block-size).
+ if (!child.IsFloating()) {
+ const ComputedStyle& child_style = child.Style();
+ NGBoxStrut child_margins = ComputeMarginsFor(
+ child_style, child_available_inline_size_, writing_mode_, direction_);
+
+ NGMarginStrut margin_strut = result->EndMarginStrut();
+ margin_strut.Append(child_margins.block_end,
+ child_style.HasMarginBeforeQuirk());
+ static_block_offset_ += margin_strut.Sum();
+ }
// Only take exclusion spaces from children which don't establish their own
// formatting context.
@@ -177,9 +186,8 @@ void NGSimplifiedLayoutAlgorithm::HandleOutOfFlowPositioned(
NGBfcOffset origin_bfc_offset = {
container_builder_.BfcLineOffset() +
border_scrollbar_padding_.LineLeft(direction_),
- (container_builder_.BfcBlockOffset()
- ? *container_builder_.BfcBlockOffset()
- : ConstraintSpace().BfcOffset().block_offset) +
+ container_builder_.BfcBlockOffset().value_or(
+ ConstraintSpace().ExpectedBfcBlockOffset()) +
static_block_offset_};
static_offset.inline_offset += CalculateOutOfFlowStaticInlineLevelOffset(
@@ -203,11 +211,50 @@ void NGSimplifiedLayoutAlgorithm::AddChildFragment(
writing_mode_, direction_, previous_physical_container_size_,
physical_child_size);
- // Add the new fragemnt to the builder.
+ // Add the new fragment to the builder.
container_builder_.AddChild(new_fragment, child_offset);
- // Update the static block-offset for any OOF-positioned children.
- static_block_offset_ = child_offset.block_offset + child_size.block_size;
+ if (!new_fragment.IsFloating()) {
+ // Update the static block-offset for any OOF-positioned children.
+ // Only consider inflow children (floats don't contribute to the intrinsic
+ // block-size).
+ static_block_offset_ = child_offset.block_offset + child_size.block_size;
+ } else {
+ // We need to add the float to the exclusion space so that any inline-level
+ // OOF-positioned nodes can correctly determine their static-position.
+ const ComputedStyle& child_style = new_fragment.Style();
+ NGBoxStrut child_margins = ComputeMarginsFor(
+ child_style, child_available_inline_size_, writing_mode_, direction_);
+
+ LayoutUnit child_line_offset = IsLtr(direction_)
+ ? child_offset.inline_offset
+ : container_builder_.InlineSize() -
+ child_size.inline_size -
+ child_offset.inline_offset;
+
+ NGBfcOffset container_bfc_offset = {
+ container_builder_.BfcLineOffset(),
+ container_builder_.BfcBlockOffset().value_or(
+ ConstraintSpace().ExpectedBfcBlockOffset())};
+
+ // Determine the offsets for the exclusion (the margin-box of the float).
+ NGBfcOffset start_offset = {
+ container_bfc_offset.line_offset + child_line_offset -
+ child_margins.LineLeft(direction_),
+ container_bfc_offset.block_offset + child_offset.block_offset -
+ child_margins.block_start};
+ NGBfcOffset end_offset = {
+ start_offset.line_offset +
+ (child_size.inline_size + child_margins.InlineSum())
+ .ClampNegativeToZero(),
+ start_offset.block_offset +
+ (child_size.block_size + child_margins.BlockSum())
+ .ClampNegativeToZero()};
+
+ exclusion_space_.Add(
+ NGExclusion::Create(NGBfcRect(start_offset, end_offset),
+ ResolvedFloating(child_style, Style()), nullptr));
+ }
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/order_iterator.h b/chromium/third_party/blink/renderer/core/layout/order_iterator.h
index 5f79d126e48..989db7e34eb 100644
--- a/chromium/third_party/blink/renderer/core/layout/order_iterator.h
+++ b/chromium/third_party/blink/renderer/core/layout/order_iterator.h
@@ -32,7 +32,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_ORDER_ITERATOR_H_
#include "base/macros.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include <set>
diff --git a/chromium/third_party/blink/renderer/core/layout/paint_containment_test.cc b/chromium/third_party/blink/renderer/core/layout/paint_containment_test.cc
index 3b3ba26ed50..ed44fd54edb 100644
--- a/chromium/third_party/blink/renderer/core/layout/paint_containment_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/paint_containment_test.cc
@@ -13,8 +13,8 @@ namespace blink {
class PaintContainmentTest : public RenderingTest {
private:
void SetUp() override {
- RenderingTest::SetUp();
EnableCompositing();
+ RenderingTest::SetUp();
}
};
@@ -28,8 +28,7 @@ static void CheckIsClippingStackingContextAndContainer(
// clipping and stacking performed by paint containment.
DCHECK(obj.Layer());
PaintLayer* layer = obj.Layer();
- EXPECT_TRUE(layer->StackingNode() &&
- layer->GetLayoutObject().StyleRef().IsStackingContext());
+ EXPECT_TRUE(layer->GetLayoutObject().StyleRef().IsStackingContext());
}
TEST_F(PaintContainmentTest, BlockPaintContainment) {
diff --git a/chromium/third_party/blink/renderer/core/layout/pointer_events_hit_rules.h b/chromium/third_party/blink/renderer/core/layout/pointer_events_hit_rules.h
index ff73512d193..e7429c5ae56 100644
--- a/chromium/third_party/blink/renderer/core/layout/pointer_events_hit_rules.h
+++ b/chromium/third_party/blink/renderer/core/layout/pointer_events_hit_rules.h
@@ -22,7 +22,7 @@
#include "third_party/blink/renderer/core/layout/hit_test_request.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/allocator/allocator.h"
namespace blink {
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 ab63740e7b3..85e2f09dedc 100644
--- a/chromium/third_party/blink/renderer/core/layout/scroll_anchor.cc
+++ b/chromium/third_party/blink/renderer/core/layout/scroll_anchor.cc
@@ -13,14 +13,14 @@
#include "third_party/blink/renderer/core/dom/static_node_list.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/frame/root_frame_viewport.h"
-#include "third_party/blink/renderer/core/frame/use_counter.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/core/layout/layout_table.h"
#include "third_party/blink/renderer/core/layout/line/inline_text_box.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/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
@@ -230,7 +230,7 @@ static const String ComputeUniqueSelector(Node* anchor_node) {
SCOPED_BLINK_UMA_HISTOGRAM_TIMER(
"Layout.ScrollAnchor.TimeToComputeAnchorNodeSelector");
- std::vector<String> selector_list;
+ Vector<String> selector_list;
for (Element* element = ElementTraversal::FirstAncestorOrSelf(*anchor_node);
element; element = ElementTraversal::FirstAncestor(*element)) {
selector_list.push_back(UniqueSimpleSelectorAmongSiblings(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 412d5c74130..943518b90ea 100644
--- a/chromium/third_party/blink/renderer/core/layout/scrollbars_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/scrollbars_test.cc
@@ -49,7 +49,7 @@ class ScrollbarsTest : public SimTest {
WebMouseEvent event(WebInputEvent::kMouseMove, WebFloatPoint(x, y),
WebFloatPoint(x, y),
WebPointerProperties::Button::kNoButton, 0,
- WebInputEvent::kNoModifiers, CurrentTimeTicks());
+ WebInputEvent::kNoModifiers, base::TimeTicks::Now());
event.SetFrameScale(1);
GetEventHandler().HandleMouseMoveEvent(event, Vector<WebMouseEvent>(),
Vector<WebMouseEvent>());
@@ -59,7 +59,7 @@ class ScrollbarsTest : public SimTest {
WebMouseEvent event(
WebInputEvent::kMouseDown, WebFloatPoint(x, y), WebFloatPoint(x, y),
WebPointerProperties::Button::kLeft, 0,
- WebInputEvent::Modifiers::kLeftButtonDown, CurrentTimeTicks());
+ WebInputEvent::Modifiers::kLeftButtonDown, base::TimeTicks::Now());
event.SetFrameScale(1);
GetEventHandler().HandleMousePressEvent(event);
}
@@ -68,7 +68,7 @@ class ScrollbarsTest : public SimTest {
WebMouseEvent event(
WebInputEvent::kMouseDown, WebFloatPoint(x, y), WebFloatPoint(x, y),
WebPointerProperties::Button::kNoButton, 0,
- WebInputEvent::Modifiers::kNoModifiers, CurrentTimeTicks());
+ WebInputEvent::Modifiers::kNoModifiers, base::TimeTicks::Now());
event.SetFrameScale(1);
GetEventHandler().SendContextMenuEvent(event);
}
@@ -77,7 +77,7 @@ class ScrollbarsTest : public SimTest {
WebMouseEvent event(
WebInputEvent::kMouseUp, WebFloatPoint(x, y), WebFloatPoint(x, y),
WebPointerProperties::Button::kLeft, 0,
- WebInputEvent::Modifiers::kNoModifiers, CurrentTimeTicks());
+ WebInputEvent::Modifiers::kNoModifiers, base::TimeTicks::Now());
event.SetFrameScale(1);
GetEventHandler().HandleMouseReleaseEvent(event);
}
@@ -86,7 +86,7 @@ class ScrollbarsTest : public SimTest {
WebMouseEvent event(
WebInputEvent::kMouseDown, WebFloatPoint(x, y), WebFloatPoint(x, y),
WebPointerProperties::Button::kMiddle, 0,
- WebInputEvent::Modifiers::kMiddleButtonDown, CurrentTimeTicks());
+ WebInputEvent::Modifiers::kMiddleButtonDown, base::TimeTicks::Now());
event.SetFrameScale(1);
GetEventHandler().HandleMousePressEvent(event);
}
@@ -95,7 +95,7 @@ class ScrollbarsTest : public SimTest {
WebMouseEvent event(
WebInputEvent::kMouseUp, WebFloatPoint(x, y), WebFloatPoint(x, y),
WebPointerProperties::Button::kMiddle, 0,
- WebInputEvent::Modifiers::kMiddleButtonDown, CurrentTimeTicks());
+ WebInputEvent::Modifiers::kMiddleButtonDown, base::TimeTicks::Now());
event.SetFrameScale(1);
GetEventHandler().HandleMouseReleaseEvent(event);
}
@@ -104,7 +104,7 @@ class ScrollbarsTest : public SimTest {
WebMouseEvent event(
WebInputEvent::kMouseMove, WebFloatPoint(1, 1), WebFloatPoint(1, 1),
WebPointerProperties::Button::kLeft, 0,
- WebInputEvent::Modifiers::kLeftButtonDown, CurrentTimeTicks());
+ WebInputEvent::Modifiers::kLeftButtonDown, base::TimeTicks::Now());
event.SetFrameScale(1);
GetEventHandler().HandleMouseLeaveEvent(event);
}
@@ -125,7 +125,7 @@ class ScrollbarsTest : public SimTest {
offset);
}
- Cursor::Type CursorType() {
+ ui::CursorType CursorType() {
return GetDocument()
.GetFrame()
->GetChromeClient()
@@ -142,8 +142,8 @@ class ScrollbarsTest : public SimTest {
WebGestureDevice device,
const IntPoint& position,
ScrollOffset offset) {
- WebGestureEvent event(type, WebInputEvent::kNoModifiers, CurrentTimeTicks(),
- device);
+ WebGestureEvent event(type, WebInputEvent::kNoModifiers,
+ base::TimeTicks::Now(), device);
event.SetPositionInWidget(WebFloatPoint(position.X(), position.Y()));
@@ -185,7 +185,7 @@ class ScrollbarsTestWithVirtualTimer : public ScrollbarsTest {
// Some task queues may have repeating v8 tasks that run forever so we impose
// a hard (virtual) time limit.
- void RunTasksForPeriod(TimeDelta delay) {
+ void RunTasksForPeriod(base::TimeDelta delay) {
TimeAdvance();
scheduler::GetSingleThreadTaskRunnerForTesting()->PostDelayedTask(
FROM_HERE,
@@ -243,16 +243,19 @@ class ScrollbarsWebWidgetClient
float device_scale_factor_;
};
-TEST_F(ScrollbarsTest, ScrollbarSizeForUseZoomDSF) {
+TEST(ScrollbarsTestWithOwnWebViewHelper, ScrollbarSizeForUseZoomDSF) {
ScrollbarsWebWidgetClient client;
client.set_device_scale_factor(1.f);
frame_test_helpers::WebViewHelper web_view_helper;
+ // Needed so visual viewport supplies its own scrollbars. We don't support
+ // this setting changing after initialization, so we must set it through
+ // WebViewHelper.
+ web_view_helper.set_viewport_enabled(true);
+
WebViewImpl* web_view_impl =
web_view_helper.Initialize(nullptr, nullptr, &client);
- // Needed so visual viewport supplies its own scrollbars.
- web_view_impl->GetSettings()->SetViewportEnabled(true);
web_view_impl->MainFrameWidget()->Resize(IntSize(800, 600));
WebURL base_url = url_test_helpers::ToKURL("http://example.com/");
@@ -503,9 +506,9 @@ TEST_F(ScrollbarsTest, scrollbarIsNotHandlingTouchpadScroll) {
ScrollableArea* scrollable_area =
ToLayoutBox(scrollable->GetLayoutObject())->GetScrollableArea();
DCHECK(scrollable_area->VerticalScrollbar());
- WebGestureEvent scroll_begin(WebInputEvent::kGestureScrollBegin,
- WebInputEvent::kNoModifiers, CurrentTimeTicks(),
- WebGestureDevice::kTouchpad);
+ WebGestureEvent scroll_begin(
+ WebInputEvent::kGestureScrollBegin, WebInputEvent::kNoModifiers,
+ base::TimeTicks::Now(), WebGestureDevice::kTouchpad);
scroll_begin.SetPositionInWidget(
WebFloatPoint(scrollable->OffsetLeft() + scrollable->OffsetWidth() - 2,
scrollable->OffsetTop()));
@@ -629,7 +632,7 @@ TEST_F(ScrollbarsTest, MouseOverScrollbarInCustomCursorElement) {
HandleMouseMoveEvent(195, 5);
- EXPECT_EQ(Cursor::Type::kPointer, CursorType());
+ EXPECT_EQ(ui::CursorType::kPointer, CursorType());
}
// Ensure mouse cursor should be override when hovering over the custom
@@ -681,7 +684,7 @@ TEST_F(ScrollbarsTest, MouseOverCustomScrollbarInCustomCursorElement) {
HandleMouseMoveEvent(195, 5);
- EXPECT_EQ(Cursor::Type::kMove, CursorType());
+ EXPECT_EQ(ui::CursorType::kMove, CursorType());
}
// Makes sure that mouse hover over an overlay scrollbar doesn't activate
@@ -727,13 +730,13 @@ TEST_F(ScrollbarsTest, MouseOverLinkAndOverlayScrollbar) {
// Mouse over link. Mouse cursor should be hand.
HandleMouseMoveEvent(a_tag->OffsetLeft(), a_tag->OffsetTop());
- EXPECT_EQ(Cursor::Type::kHand, CursorType());
+ EXPECT_EQ(ui::CursorType::kHand, CursorType());
// Mouse over enabled overlay scrollbar. Mouse cursor should be pointer and no
// active hover element.
HandleMouseMoveEvent(18, a_tag->OffsetTop());
- EXPECT_EQ(Cursor::Type::kPointer, CursorType());
+ EXPECT_EQ(ui::CursorType::kPointer, CursorType());
HandleMousePressEvent(18, a_tag->OffsetTop());
@@ -759,7 +762,7 @@ TEST_F(ScrollbarsTest, MouseOverLinkAndOverlayScrollbar) {
HandleMouseMoveEvent(18, a_tag->OffsetTop());
- EXPECT_EQ(Cursor::Type::kHand, CursorType());
+ EXPECT_EQ(ui::CursorType::kHand, CursorType());
HandleMousePressEvent(18, a_tag->OffsetTop());
@@ -1332,7 +1335,8 @@ TEST_F(ScrollbarsTestWithVirtualTimer,
TEST_F(ScrollbarsTestWithVirtualTimer, TestNonCompositedOverlayScrollbarsFade) {
#endif
TimeAdvance();
- constexpr TimeDelta kMockOverlayFadeOutDelay = TimeDelta::FromSeconds(5);
+ constexpr base::TimeDelta kMockOverlayFadeOutDelay =
+ base::TimeDelta::FromSeconds(5);
ScrollbarTheme& theme = GetScrollbarTheme();
// This test relies on mock overlay scrollbars.
@@ -1416,19 +1420,32 @@ TEST_F(ScrollbarsTestWithVirtualTimer, TestNonCompositedOverlayScrollbarsFade) {
RunTasksForPeriod(kMockOverlayFadeOutDelay);
EXPECT_TRUE(scrollable_area->ScrollbarsHiddenIfOverlay());
- mock_overlay_theme.SetOverlayScrollbarFadeOutDelay(TimeDelta());
+ mock_overlay_theme.SetOverlayScrollbarFadeOutDelay(base::TimeDelta());
}
-typedef bool TestParamOverlayScrollbar;
class ScrollbarAppearanceTest
: public SimTest,
- public testing::WithParamInterface<TestParamOverlayScrollbar> {
+ public testing::WithParamInterface</*use_real_overlay_scrollbars=*/bool> {
public:
- // Use real scrollbars to ensure we're testing the real ScrollbarThemes.
- ScrollbarAppearanceTest() : mock_scrollbars_(false, GetParam()) {}
+ void SetUp() override {
+ SimTest::SetUp();
+ // Use real scrollbars to ensure we're testing the real ScrollbarThemes.
+ // TODO(bokan): For some reason this has to happen *after* the WebViewImpl
+ // loads and everything or the test fails. But not doing it also fails.
+ // However this changes a runtime feature and should go *before* anything
+ // is set up!! Otherwise blink sees inconsistent values which doesn't happen
+ // in reality.
+ mock_scrollbars_ =
+ std::make_unique<UseMockScrollbarSettings>(false, GetParam());
+ }
+
+ void TearDown() override {
+ mock_scrollbars_.reset();
+ SimTest::TearDown();
+ }
private:
- UseMockScrollbarSettings mock_scrollbars_;
+ std::unique_ptr<UseMockScrollbarSettings> mock_scrollbars_;
};
class StubWebThemeEngine : public WebThemeEngine {
@@ -1444,8 +1461,8 @@ class StubWebThemeEngine : public WebThemeEngine {
}
}
void GetOverlayScrollbarStyle(ScrollbarStyle* style) override {
- style->fade_out_delay = TimeDelta();
- style->fade_out_duration = TimeDelta();
+ style->fade_out_delay = base::TimeDelta();
+ style->fade_out_duration = base::TimeDelta();
style->thumb_thickness = 3;
style->scrollbar_margin = 0;
style->color = SkColorSetARGB(128, 64, 64, 64);
@@ -2222,7 +2239,7 @@ TEST_F(ScrollbarsTest, MiddleDownShouldNotAffectScrollbarPress) {
WebMouseEvent event(WebInputEvent::kMouseMove, WebFloatPoint(5, 5),
WebFloatPoint(5, 5), WebPointerProperties::Button::kLeft,
0, WebInputEvent::Modifiers::kLeftButtonDown,
- CurrentTimeTicks());
+ base::TimeTicks::Now());
event.SetFrameScale(1);
GetEventHandler().HandleMouseLeaveEvent(event);
EXPECT_EQ(scrollbar->PressedPart(), ScrollbarPart::kThumbPart);
@@ -2481,7 +2498,7 @@ TEST_F(ScrollbarsTestWithVirtualTimer,
SimRequest request("https://example.com/test.html", "text/html");
LoadURL("https://example.com/test.html");
- RunTasksForPeriod(TimeDelta::FromMilliseconds(1000));
+ RunTasksForPeriod(base::TimeDelta::FromMilliseconds(1000));
request.Complete(R"HTML(
<!DOCTYPE html>
<style>
@@ -2527,20 +2544,20 @@ TEST_F(ScrollbarsTestWithVirtualTimer,
ASSERT_EQ(scrollbar->PressedPart(), ScrollbarPart::kForwardButtonEndPart);
// Wait for 2 delay.
- RunTasksForPeriod(TimeDelta::FromMilliseconds(1000));
- RunTasksForPeriod(TimeDelta::FromMilliseconds(1000));
+ RunTasksForPeriod(base::TimeDelta::FromMilliseconds(1000));
+ RunTasksForPeriod(base::TimeDelta::FromMilliseconds(1000));
// Change #big size.
MainFrame().ExecuteScript(WebScriptSource(
"document.getElementById('big').style.height = '1000px';"));
Compositor().BeginFrame();
- RunTasksForPeriod(TimeDelta::FromMilliseconds(1000));
- RunTasksForPeriod(TimeDelta::FromMilliseconds(1000));
+ RunTasksForPeriod(base::TimeDelta::FromMilliseconds(1000));
+ RunTasksForPeriod(base::TimeDelta::FromMilliseconds(1000));
// Verify that the scrollbar autopress timer requested some scrolls via
// gestures. The button was pressed for 2 seconds and the timer fires
// every 250ms - we should have at least 7 injected gesture updates.
- EXPECT_GT(WebWidgetClient().InjectedGestureScrollCount(), 6);
+ EXPECT_GT(WebWidgetClient().GetInjectedScrollGestureData().size(), 6u);
}
class ScrollbarTrackMarginsTest : public ScrollbarsTest {
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 c6f299e1319..41f2a5498f2 100644
--- a/chromium/third_party/blink/renderer/core/layout/shapes/shape.cc
+++ b/chromium/third_party/blink/renderer/core/layout/shapes/shape.cc
@@ -310,13 +310,10 @@ static std::unique_ptr<RasterShapeIntervals> ExtractIntervalsFromImageData(
}
static bool IsValidRasterShapeSize(const IntSize& size) {
- static size_t max_image_size_bytes = 0;
- if (!max_image_size_bytes) {
- size_t size32_max_bytes =
- 0xFFFFFFFF / 4; // Some platforms don't limit MaxDecodedImageBytes.
- max_image_size_bytes =
- std::min(size32_max_bytes, Platform::Current()->MaxDecodedImageBytes());
- }
+ // Some platforms don't limit MaxDecodedImageBytes.
+ constexpr size_t size32_max_bytes = 0xFFFFFFFF / 4;
+ static const size_t max_image_size_bytes =
+ std::min(size32_max_bytes, Platform::Current()->MaxDecodedImageBytes());
return size.Area() * 4 < max_image_size_bytes;
}
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 ce121a48030..3f18e6f3618 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
@@ -31,7 +31,6 @@
#include <memory>
#include "base/auto_reset.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/layout/api/line_layout_block_flow.h"
#include "third_party/blink/renderer/core/layout/floating_objects.h"
@@ -39,6 +38,7 @@
#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/geometry/length_functions.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/style_retain_scope.h b/chromium/third_party/blink/renderer/core/layout/style_retain_scope.h
index 6ff00c2c993..cbb93578fcb 100644
--- a/chromium/third_party/blink/renderer/core/layout/style_retain_scope.h
+++ b/chromium/third_party/blink/renderer/core/layout/style_retain_scope.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_STYLE_RETAIN_SCOPE_H_
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/subtree_layout_scope.h b/chromium/third_party/blink/renderer/core/layout/subtree_layout_scope.h
index d5f506c7d16..ae5b4c9e8c4 100644
--- a/chromium/third_party/blink/renderer/core/layout/subtree_layout_scope.h
+++ b/chromium/third_party/blink/renderer/core/layout/subtree_layout_scope.h
@@ -32,7 +32,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_SUBTREE_LAYOUT_SCOPE_H_
#include "third_party/blink/renderer/core/inspector/inspector_trace_events.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
// This is the way to mark a subtree as needing layout during layout,
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 934918edb6e..3d6fea7918c 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
@@ -131,7 +131,7 @@ bool LayoutSVGBlock::MapToVisualRectInAncestorSpaceInternal(
bool LayoutSVGBlock::NodeAtPoint(HitTestResult&,
const HitTestLocation&,
- const LayoutPoint&,
+ const PhysicalOffset&,
HitTestAction) {
NOTREACHED();
return false;
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_block.h b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_block.h
index 739c40a9c89..8c8dfbfff4a 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_block.h
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_block.h
@@ -79,8 +79,8 @@ class LayoutSVGBlock : public LayoutBlockFlow {
void UpdateFromStyle() final;
bool NodeAtPoint(HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
HitTestAction) override;
// The inherited version doesn't check for SVG effects.
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 fed5ecfb637..5974869fbac 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
@@ -174,13 +174,12 @@ void LayoutSVGContainer::UpdateCachedBoundaries() {
GetElement()->SetNeedsResizeObserverUpdate();
}
-bool LayoutSVGContainer::NodeAtPoint(
- HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
- HitTestAction hit_test_action) {
- DCHECK_EQ(accumulated_offset, LayoutPoint());
- TransformedHitTestLocation local_location(location_in_container,
+bool LayoutSVGContainer::NodeAtPoint(HitTestResult& result,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
+ HitTestAction hit_test_action) {
+ DCHECK_EQ(accumulated_offset, PhysicalOffset());
+ TransformedHitTestLocation local_location(hit_test_location,
LocalToSVGParentTransform());
if (!local_location)
return false;
@@ -188,7 +187,8 @@ bool LayoutSVGContainer::NodeAtPoint(
*local_location))
return false;
- if (SVGLayoutSupport::HitTestChildren(LastChild(), result, *local_location,
+ if (!PaintBlockedByDisplayLock(DisplayLockContext::kChildren) &&
+ SVGLayoutSupport::HitTestChildren(LastChild(), result, *local_location,
accumulated_offset, hit_test_action))
return true;
@@ -199,9 +199,8 @@ bool LayoutSVGContainer::NodeAtPoint(
// containers.
if (IsObjectBoundingBoxValid() &&
local_location->Intersects(ObjectBoundingBox())) {
- const LayoutPoint& local_layout_point =
- LayoutPoint(local_location->TransformedPoint());
- UpdateHitTestResult(result, local_layout_point);
+ UpdateHitTestResult(result, PhysicalOffset::FromFloatPointRound(
+ local_location->TransformedPoint()));
if (result.AddNodeToListBasedTestResult(GetElement(), *local_location) ==
kStopHitTesting)
return true;
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_container.h b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_container.h
index a12b7cfa94a..ba23efa422d 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_container.h
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_container.h
@@ -83,8 +83,8 @@ class LayoutSVGContainer : public LayoutSVGModelObject {
FloatRect StrokeBoundingBox() const final { return stroke_bounding_box_; }
bool NodeAtPoint(HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
HitTestAction) override;
// Called during layout to update the local transform.
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 cd3401bbce7..f494825d511 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
@@ -127,22 +127,22 @@ void LayoutSVGForeignObject::UpdateLayout() {
bool LayoutSVGForeignObject::NodeAtPointFromSVG(
HitTestResult& result,
- const HitTestLocation& location_in_parent,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
HitTestAction) {
- DCHECK_EQ(accumulated_offset, LayoutPoint());
- TransformedHitTestLocation local_location(location_in_parent,
+ DCHECK_EQ(accumulated_offset, PhysicalOffset());
+ TransformedHitTestLocation local_location(hit_test_location,
LocalSVGTransform());
if (!local_location)
return false;
// |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()));
+ HitTestLocation local_without_offset(*local_location, -PhysicalLocation());
HitTestResult layer_result(result.GetHitTestRequest(), local_without_offset);
+ layer_result.SetInertNode(result.InertNode());
bool retval = Layer()->HitTest(local_without_offset, layer_result,
- LayoutRect(LayoutRect::InfiniteIntRect()));
+ PhysicalRect(PhysicalRect::InfiniteIntRect()));
// Preserve the "point in inner node frame" from the original request,
// since |layer_result| is a hit test rooted at the <foreignObject> element,
@@ -150,7 +150,7 @@ bool LayoutSVGForeignObject::NodeAtPointFromSVG(
// |point_in_foreign_object| as its "point in inner node frame".
// TODO(chrishtr): refactor the PaintLayer and HitTestResults code around
// this, to better support hit tests that don't start at frame boundaries.
- LayoutPoint original_point_in_inner_node_frame =
+ PhysicalOffset original_point_in_inner_node_frame =
result.PointInInnerNodeFrame();
if (result.GetHitTestRequest().ListBased())
result.Append(layer_result);
@@ -162,11 +162,11 @@ bool LayoutSVGForeignObject::NodeAtPointFromSVG(
bool LayoutSVGForeignObject::NodeAtPoint(
HitTestResult& result,
- const HitTestLocation& location_in_parent,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
HitTestAction hit_test_action) {
// Skip LayoutSVGBlock's override.
- return LayoutBlockFlow::NodeAtPoint(result, location_in_parent,
+ return LayoutBlockFlow::NodeAtPoint(result, hit_test_location,
accumulated_offset, hit_test_action);
}
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 6d11b4249a2..838ac43a38f 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
@@ -63,7 +63,7 @@ class LayoutSVGForeignObject final : public LayoutSVGBlock {
bool NodeAtPoint(HitTestResult&,
const HitTestLocation&,
- const LayoutPoint&,
+ const PhysicalOffset&,
HitTestAction) override;
// A method to call when recursively hit testing from an SVG parent.
@@ -72,7 +72,7 @@ class LayoutSVGForeignObject final : public LayoutSVGBlock {
// on this object. This is why there are two methods.
bool NodeAtPointFromSVG(HitTestResult&,
const HitTestLocation&,
- const LayoutPoint&,
+ const PhysicalOffset&,
HitTestAction);
bool IsOfType(LayoutObjectType type) const override {
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 f680a1bae07..b804814fb8f 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
@@ -64,7 +64,7 @@ TEST_F(LayoutSVGForeignObjectTest, DivInForeignObject) {
EXPECT_EQ(svg, HitTest(450, 350));
// Rect based hit testing
- auto results = RectBasedHitTest(LayoutRect(0, 0, 300, 300));
+ auto results = RectBasedHitTest(PhysicalRect(0, 0, 300, 300));
int count = 0;
EXPECT_EQ(3u, results.size());
for (auto result : results) {
@@ -138,7 +138,7 @@ TEST_F(LayoutSVGForeignObjectTest, IframeInForeignObject) {
EXPECT_EQ(svg, HitTest(450, 400));
// Rect based hit testing
- auto results = RectBasedHitTest(LayoutRect(0, 0, 300, 300));
+ auto results = RectBasedHitTest(PhysicalRect(0, 0, 300, 300));
int count = 0;
EXPECT_EQ(7u, results.size());
for (auto result : results) {
@@ -194,7 +194,7 @@ TEST_F(LayoutSVGForeignObjectTest, HitTestZoomedForeignObject) {
EXPECT_EQ(div, HitTest(290, 290));
// Rect based hit testing
- auto results = RectBasedHitTest(LayoutRect(0, 0, 300, 300));
+ auto results = RectBasedHitTest(PhysicalRect(0, 0, 300, 300));
int count = 0;
EXPECT_EQ(3u, results.size());
for (auto result : results) {
@@ -298,11 +298,11 @@ TEST_F(LayoutSVGForeignObjectTest,
EXPECT_EQ(foreignObject, GetDocument().ElementFromPoint(205, 255));
HitTestRequest request(HitTestRequest::kReadOnly | HitTestRequest::kActive);
- HitTestLocation location((LayoutPoint(206, 206)));
+ HitTestLocation location((PhysicalOffset(206, 206)));
HitTestResult result(request, location);
GetDocument().GetLayoutView()->HitTest(location, result);
EXPECT_EQ(target, result.InnerNode());
- EXPECT_EQ(LayoutPoint(206, 206), result.PointInInnerNodeFrame());
+ EXPECT_EQ(PhysicalOffset(206, 206), result.PointInInnerNodeFrame());
}
TEST_F(LayoutSVGForeignObjectTest,
@@ -332,11 +332,11 @@ TEST_F(LayoutSVGForeignObjectTest,
EXPECT_EQ(foreign_object, GetDocument().ElementFromPoint(235, 255));
HitTestRequest request(HitTestRequest::kReadOnly | HitTestRequest::kActive);
- HitTestLocation location((LayoutPoint(236, 206)));
+ HitTestLocation location((PhysicalOffset(236, 206)));
HitTestResult result(request, location);
GetDocument().GetLayoutView()->HitTest(location, result);
EXPECT_EQ(target, result.InnerNode());
- EXPECT_EQ(LayoutPoint(236, 206), result.PointInInnerNodeFrame());
+ EXPECT_EQ(PhysicalOffset(236, 206), result.PointInInnerNodeFrame());
}
TEST_F(LayoutSVGForeignObjectTest, HitTestUnderScrollingAncestor) {
@@ -362,11 +362,11 @@ TEST_F(LayoutSVGForeignObjectTest, HitTestUnderScrollingAncestor) {
EXPECT_EQ(target, GetDocument().ElementFromPoint(450, 450));
HitTestRequest request(HitTestRequest::kReadOnly | HitTestRequest::kActive);
- HitTestLocation location((LayoutPoint(450, 450)));
+ HitTestLocation location((PhysicalOffset(450, 450)));
HitTestResult result(request, location);
GetDocument().GetLayoutView()->HitTest(location, result);
EXPECT_EQ(target, result.InnerNode());
- EXPECT_EQ(LayoutPoint(450, 450), result.PointInInnerNodeFrame());
+ EXPECT_EQ(PhysicalOffset(450, 450), result.PointInInnerNodeFrame());
scroller.setScrollTop(3000);
@@ -374,7 +374,7 @@ TEST_F(LayoutSVGForeignObjectTest, HitTestUnderScrollingAncestor) {
GetDocument().GetLayoutView()->HitTest(location, result);
EXPECT_EQ(target, result.InnerNode());
- EXPECT_EQ(LayoutPoint(450, 450), result.PointInInnerNodeFrame());
+ EXPECT_EQ(PhysicalOffset(450, 450), result.PointInInnerNodeFrame());
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_hidden_container.cc b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_hidden_container.cc
index 40afa1ffd8b..c2c57a79d98 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_hidden_container.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_hidden_container.cc
@@ -45,7 +45,7 @@ void LayoutSVGHiddenContainer::UpdateLayout() {
bool LayoutSVGHiddenContainer::NodeAtPoint(HitTestResult&,
const HitTestLocation&,
- const LayoutPoint&,
+ const PhysicalOffset&,
HitTestAction) {
return false;
}
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_hidden_container.h b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_hidden_container.h
index 4d2bc9bc920..6f01462ff3c 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_hidden_container.h
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_hidden_container.h
@@ -58,8 +58,8 @@ class LayoutSVGHiddenContainer : public LayoutSVGContainer {
MapCoordinatesFlags mode = 0) const final {}
bool NodeAtPoint(HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
HitTestAction) final;
};
} // namespace blink
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 5fd87cc08db..9e472948d77 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
@@ -56,11 +56,6 @@ LayoutSVGImage::~LayoutSVGImage() = default;
void LayoutSVGImage::WillBeDestroyed() {
image_resource_->Shutdown();
- if (RuntimeEnabledFeatures::ElementTimingEnabled(&GetDocument())) {
- if (LocalDOMWindow* window = GetDocument().domWindow())
- ImageElementTiming::From(*window).NotifyWillBeDestroyed(this);
- }
-
LayoutSVGModelObject::WillBeDestroyed();
}
@@ -175,10 +170,10 @@ void LayoutSVGImage::Paint(const PaintInfo& paint_info) const {
}
bool LayoutSVGImage::NodeAtPoint(HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
HitTestAction hit_test_action) {
- DCHECK_EQ(accumulated_offset, LayoutPoint());
+ DCHECK_EQ(accumulated_offset, PhysicalOffset());
// We only draw in the forground phase, so we only hit-test then.
if (hit_test_action != kHitTestForeground)
return false;
@@ -190,7 +185,7 @@ bool LayoutSVGImage::NodeAtPoint(HitTestResult& result,
if (hit_rules.require_visible && style.Visibility() != EVisibility::kVisible)
return false;
- TransformedHitTestLocation local_location(location_in_container,
+ TransformedHitTestLocation local_location(hit_test_location,
LocalToSVGParentTransform());
if (!local_location)
return false;
@@ -200,9 +195,8 @@ bool LayoutSVGImage::NodeAtPoint(HitTestResult& result,
if (hit_rules.can_hit_fill || hit_rules.can_hit_bounding_box) {
if (local_location->Intersects(object_bounding_box_)) {
- const LayoutPoint& local_layout_point =
- LayoutPoint(local_location->TransformedPoint());
- UpdateHitTestResult(result, local_layout_point);
+ UpdateHitTestResult(result, PhysicalOffset::FromFloatPointRound(
+ local_location->TransformedPoint()));
if (result.AddNodeToListBasedTestResult(GetElement(), *local_location) ==
kStopHitTesting)
return true;
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 863c6fffec7..b28f212dce2 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
@@ -70,8 +70,8 @@ class LayoutSVGImage final : public LayoutSVGModelObject {
bool UpdateBoundingBox();
bool NodeAtPoint(HitTestResult&,
- const HitTestLocation& location_in_parent,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
HitTestAction) override;
AffineTransform LocalSVGTransform() const override {
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 eca55d1583a..20cf37c9c53 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
@@ -151,7 +151,7 @@ bool LayoutSVGInlineText::CharacterStartsNewTextChunk(int position) const {
}
PositionWithAffinity LayoutSVGInlineText::PositionForPoint(
- const LayoutPoint& point) const {
+ const PhysicalOffset& point) const {
if (!HasTextBoxes() || !TextLength())
return CreatePositionWithAffinity(0);
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_inline_text.h b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_inline_text.h
index 47c881e2308..8714fa3b027 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_inline_text.h
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_inline_text.h
@@ -70,7 +70,7 @@ class LayoutSVGInlineText final : public LayoutText {
LayoutText::IsOfType(type);
}
- PositionWithAffinity PositionForPoint(const LayoutPoint&) const override;
+ PositionWithAffinity PositionForPoint(const PhysicalOffset&) const override;
LayoutRect LocalCaretRect(
const InlineBox*,
int caret_offset,
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 96428abd09e..93a507f3272 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
@@ -60,7 +60,7 @@ void LayoutSVGPath::UpdateMarkers() {
marker_positions_.clear();
if (!StyleRef().SvgStyle().HasMarkers() ||
- !SVGResources::SupportsMarkers(*ToSVGGraphicsElement(GetElement())))
+ !SVGResources::SupportsMarkers(*To<SVGGraphicsElement>(GetElement())))
return;
SVGResources* resources =
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 f1797c621b3..0c23bf6f284 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
@@ -84,9 +84,10 @@ ClipStrategy DetermineClipStrategy(const SVGElement& element) {
return ModifyStrategyForClipPath(use_layout_object->StyleRef(),
shape_strategy);
}
- if (!element.IsSVGGraphicsElement())
+ auto* svg_graphics_element = DynamicTo<SVGGraphicsElement>(element);
+ if (!svg_graphics_element)
return ClipStrategy::kNone;
- return DetermineClipStrategy(ToSVGGraphicsElement(element));
+ return DetermineClipStrategy(*svg_graphics_element);
}
bool ContributesToClip(const SVGElement& element) {
@@ -257,7 +258,7 @@ bool LayoutSVGResourceClipper::HitTestClipContent(
DCHECK(!layout_object->IsBoxModelObject() ||
!ToLayoutBoxModelObject(layout_object)->HasSelfPaintingLayer());
- if (layout_object->NodeAtPoint(result, *local_location, LayoutPoint(),
+ if (layout_object->NodeAtPoint(result, *local_location, PhysicalOffset(),
kHitTestForeground))
return true;
}
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 de5aacbe153..f697338d420 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
@@ -59,8 +59,7 @@ void LayoutSVGResourceFilterPrimitive::StyleDidChange(
if (!old_style)
return;
DCHECK(GetElement());
- SVGFilterPrimitiveStandardAttributes& element =
- ToSVGFilterPrimitiveStandardAttributes(*GetElement());
+ auto& element = To<SVGFilterPrimitiveStandardAttributes>(*GetElement());
const SVGComputedStyle& new_style = StyleRef().SvgStyle();
if (IsSVGFEFloodElement(element) || IsSVGFEDropShadowElement(element)) {
CheckForColorChange(element, svg_names::kFloodColorAttr, diff,
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 66a23138953..62d1617857a 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
@@ -35,7 +35,7 @@ void LayoutSVGResourceGradient::RemoveAllClientsFromCache(
bool mark_for_invalidation) {
gradient_map_->clear();
should_collect_gradient_attributes_ = true;
- ToSVGGradientElement(*GetElement()).InvalidateDependentGradients();
+ To<SVGGradientElement>(*GetElement()).InvalidateDependentGradients();
MarkAllClientsForInvalidation(
mark_for_invalidation ? SVGResourceClient::kPaintInvalidation
: SVGResourceClient::kParentOnlyInvalidation);
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_paint_server.cc b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_paint_server.cc
index 7dead57bf3a..fdc8bc00edd 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_paint_server.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_paint_server.cc
@@ -72,8 +72,8 @@ static SVGPaintDescription RequestPaint(const LayoutObject& object,
const SVGPaint& paint =
apply_to_fill ? svg_style.FillPaint() : svg_style.StrokePaint();
const SVGPaint& visited_paint = apply_to_fill
- ? svg_style.VisitedLinkFillPaint()
- : svg_style.VisitedLinkStrokePaint();
+ ? svg_style.InternalVisitedFillPaint()
+ : svg_style.InternalVisitedStrokePaint();
// If we have no, ignore it.
if (paint.IsNone())
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_paint_server.h b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_paint_server.h
index e0a7f6de546..fad76f41cb6 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_paint_server.h
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_resource_paint_server.h
@@ -25,7 +25,7 @@
#include "third_party/blink/renderer/platform/graphics/gradient.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/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 671631334dc..a3152eb79a3 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
@@ -264,6 +264,8 @@ LayoutRect LayoutSVGRoot::ComputeContentsVisualOverflow() const {
void LayoutSVGRoot::PaintReplaced(const PaintInfo& paint_info,
const PhysicalOffset& paint_offset) const {
+ if (PaintBlockedByDisplayLock(DisplayLockContext::kChildren))
+ return;
SVGRootPainter(*this).PaintReplaced(paint_info, paint_offset);
}
@@ -296,7 +298,9 @@ bool LayoutSVGRoot::StyleChangeAffectsIntrinsicSize(
return false;
}
-void LayoutSVGRoot::IntrinsicSizingInfoChanged() const {
+void LayoutSVGRoot::IntrinsicSizingInfoChanged() {
+ SetPreferredLogicalWidthsDirty();
+
// TODO(fs): Merge with IntrinsicSizeChanged()? (from LayoutReplaced)
// Ignore changes to intrinsic dimensions if the <svg> is not in an SVG
// document, or not embedded in a way that supports/allows size negotiation.
@@ -387,7 +391,7 @@ void LayoutSVGRoot::WillBeRemovedFromTree() {
}
PositionWithAffinity LayoutSVGRoot::PositionForPoint(
- const LayoutPoint& point) const {
+ const PhysicalOffset& point) const {
FloatPoint absolute_point = FloatPoint(point);
absolute_point =
local_to_border_box_transform_.Inverse().MapPoint(absolute_point);
@@ -410,7 +414,8 @@ PositionWithAffinity LayoutSVGRoot::PositionForPoint(
absolute_point = transform.Inverse().MapPoint(absolute_point);
- return closest_descendant->PositionForPoint(LayoutPoint(absolute_point));
+ return closest_descendant->PositionForPoint(
+ PhysicalOffset::FromFloatPointRound(absolute_point));
}
// LayoutBox methods will expect coordinates w/o any transforms in coordinates
@@ -464,13 +469,11 @@ void LayoutSVGRoot::UpdateCachedBoundaries() {
}
bool LayoutSVGRoot::NodeAtPoint(HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
HitTestAction hit_test_action) {
- LayoutPoint adjusted_location = accumulated_offset + Location();
-
- HitTestLocation local_border_box_location(location_in_container,
- ToLayoutSize(-adjusted_location));
+ HitTestLocation local_border_box_location(hit_test_location,
+ -accumulated_offset);
// Only test SVG content if the point is in our content box, or in case we
// don't clip to the viewport, the visual overflow rect.
@@ -478,14 +481,13 @@ bool LayoutSVGRoot::NodeAtPoint(HitTestResult& result,
// supported by nodeAtFloatPoint.
bool skip_children = (result.GetHitTestRequest().GetStopNode() == this);
if (!skip_children &&
- (local_border_box_location.Intersects(
- PhysicalContentBoxRect().ToLayoutRect()) ||
+ (local_border_box_location.Intersects(PhysicalContentBoxRect()) ||
(!ShouldApplyViewportClip() &&
- local_border_box_location.Intersects(VisualOverflowRect())))) {
+ local_border_box_location.Intersects(PhysicalVisualOverflowRect())))) {
TransformedHitTestLocation local_location(local_border_box_location,
LocalToBorderBoxTransform());
if (local_location) {
- LayoutPoint accumulated_offset_for_children;
+ PhysicalOffset accumulated_offset_for_children;
if (SVGLayoutSupport::HitTestChildren(
LastChild(), result, *local_location,
accumulated_offset_for_children, hit_test_action))
@@ -506,10 +508,10 @@ bool LayoutSVGRoot::NodeAtPoint(HitTestResult& result,
// detect hits on the background of a <div> element.
// If we'd return true here in the 'Foreground' phase, we are not able to
// detect these hits anymore.
- LayoutRect bounds_rect(accumulated_offset + Location(), Size());
- if (location_in_container.Intersects(bounds_rect)) {
+ PhysicalRect bounds_rect(accumulated_offset, Size());
+ if (hit_test_location.Intersects(bounds_rect)) {
UpdateHitTestResult(result, local_border_box_location.Point());
- if (result.AddNodeToListBasedTestResult(GetNode(), location_in_container,
+ if (result.AddNodeToListBasedTestResult(GetNode(), hit_test_location,
bounds_rect) == kStopHitTesting)
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 ff3fc5a5a6a..3246ac260bf 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
@@ -38,7 +38,7 @@ class CORE_EXPORT LayoutSVGRoot final : public LayoutReplaced {
bool IsEmbeddedThroughSVGImage() const;
bool IsEmbeddedThroughFrameContainingSVGDocument() const;
- void IntrinsicSizingInfoChanged() const;
+ void IntrinsicSizingInfoChanged();
void UnscaledIntrinsicSizingInfo(IntrinsicSizingInfo&) const;
// If you have a LayoutSVGRoot, use firstChild or lastChild instead.
@@ -138,8 +138,8 @@ class CORE_EXPORT LayoutSVGRoot final : public LayoutReplaced {
}
bool NodeAtPoint(HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
HitTestAction) override;
void MapLocalToAncestor(const LayoutBoxModelObject* ancestor,
@@ -159,7 +159,7 @@ class CORE_EXPORT LayoutSVGRoot final : public LayoutReplaced {
void UpdateCachedBoundaries();
SVGTransformChange BuildLocalToBorderBoxTransform();
- PositionWithAffinity PositionForPoint(const LayoutPoint&) const final;
+ PositionWithAffinity PositionForPoint(const PhysicalOffset&) const final;
LayoutObjectChildList children_;
IntSize container_size_;
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 b6f99daab80..cc0f2983d0b 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
@@ -13,7 +13,12 @@
namespace blink {
-using LayoutSVGRootTest = RenderingTest;
+class LayoutSVGRootTest : public RenderingTest {
+ void SetUp() override {
+ EnableCompositing();
+ RenderingTest::SetUp();
+ }
+};
TEST_F(LayoutSVGRootTest, VisualRectMappingWithoutViewportClipWithBorder) {
SetBodyInnerHTML(R"HTML(
@@ -43,7 +48,6 @@ TEST_F(LayoutSVGRootTest, VisualRectMappingWithoutViewportClipWithBorder) {
}
TEST_F(LayoutSVGRootTest, VisualOverflowExpandsLayer) {
- EnableCompositing();
SetBodyInnerHTML(R"HTML(
<svg id='root' style='width: 100px; will-change: transform; height:
100px; overflow: visible; position: absolute;'>
@@ -143,7 +147,7 @@ TEST_F(LayoutSVGRootTest, RectBasedHitTestPartialOverlap) {
// The center of this rect does not overlap the SVG element, but the
// rect itself does.
- auto results = RectBasedHitTest(LayoutRect(0, 0, 300, 300));
+ auto results = RectBasedHitTest(PhysicalRect(0, 0, 300, 300));
int count = 0;
EXPECT_EQ(2u, results.size());
for (auto result : results) {
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 11d4e5dc3fd..4418ac862ac 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
@@ -235,7 +235,7 @@ static inline bool TransformDependsOnReferenceBox(const ComputedStyle& style) {
}
bool LayoutSVGShape::UpdateLocalTransform() {
- SVGGraphicsElement* graphics_element = ToSVGGraphicsElement(GetElement());
+ auto* graphics_element = To<SVGGraphicsElement>(GetElement());
if (graphics_element->HasTransform(SVGElement::kIncludeMotionTransform)) {
local_transform_.SetTransform(graphics_element->CalculateTransform(
SVGElement::kIncludeMotionTransform));
@@ -349,10 +349,10 @@ void LayoutSVGShape::Paint(const PaintInfo& paint_info) const {
}
bool LayoutSVGShape::NodeAtPoint(HitTestResult& result,
- const HitTestLocation& location_in_parent,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
HitTestAction hit_test_action) {
- DCHECK_EQ(accumulated_offset, LayoutPoint());
+ DCHECK_EQ(accumulated_offset, PhysicalOffset());
// We only draw in the foreground phase, so we only hit-test then.
if (hit_test_action != kHitTestForeground)
return false;
@@ -365,7 +365,7 @@ bool LayoutSVGShape::NodeAtPoint(HitTestResult& result,
if (hit_rules.require_visible && style.Visibility() != EVisibility::kVisible)
return false;
- TransformedHitTestLocation local_location(location_in_parent,
+ TransformedHitTestLocation local_location(hit_test_location,
LocalToSVGParentTransform());
if (!local_location)
return false;
@@ -374,8 +374,8 @@ bool LayoutSVGShape::NodeAtPoint(HitTestResult& result,
return false;
if (HitTestShape(result.GetHitTestRequest(), *local_location, hit_rules)) {
- const LayoutPoint local_layout_point(local_location->TransformedPoint());
- UpdateHitTestResult(result, local_layout_point);
+ UpdateHitTestResult(result, PhysicalOffset::FromFloatPointRound(
+ local_location->TransformedPoint()));
if (result.AddNodeToListBasedTestResult(GetElement(), *local_location) ==
kStopHitTesting)
return true;
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 b105d77182c..b2563c7a1b8 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
@@ -160,8 +160,8 @@ class LayoutSVGShape : public LayoutSVGModelObject {
void Paint(const PaintInfo&) const final;
bool NodeAtPoint(HitTestResult&,
- const HitTestLocation& location_in_parent,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
HitTestAction) final;
bool HitTestShape(const HitTestRequest&,
const HitTestLocation&,
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 334d7644fca..34c734ab14f 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
@@ -317,15 +317,15 @@ RootInlineBox* LayoutSVGText::CreateRootInlineBox() {
}
bool LayoutSVGText::NodeAtPoint(HitTestResult& result,
- const HitTestLocation& location_in_parent,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
HitTestAction hit_test_action) {
- DCHECK_EQ(accumulated_offset, LayoutPoint());
+ DCHECK_EQ(accumulated_offset, PhysicalOffset());
// We only draw in the foreground phase, so we only hit-test then.
if (hit_test_action != kHitTestForeground)
return false;
- TransformedHitTestLocation local_location(location_in_parent,
+ TransformedHitTestLocation local_location(hit_test_location,
LocalToSVGParentTransform());
if (!local_location)
return false;
@@ -341,9 +341,8 @@ bool LayoutSVGText::NodeAtPoint(HitTestResult& result,
if (StyleRef().PointerEvents() == EPointerEvents::kBoundingBox) {
if (IsObjectBoundingBoxValid() &&
local_location->Intersects(ObjectBoundingBox())) {
- const LayoutPoint& local_layout_point =
- LayoutPoint(local_location->TransformedPoint());
- UpdateHitTestResult(result, local_layout_point);
+ UpdateHitTestResult(result, PhysicalOffset::FromFloatPointRound(
+ local_location->TransformedPoint()));
if (result.AddNodeToListBasedTestResult(GetElement(), *local_location) ==
kStopHitTesting)
return true;
@@ -353,15 +352,15 @@ bool LayoutSVGText::NodeAtPoint(HitTestResult& result,
}
PositionWithAffinity LayoutSVGText::PositionForPoint(
- const LayoutPoint& point_in_contents) const {
+ const PhysicalOffset& point_in_contents) const {
RootInlineBox* root_box = FirstRootBox();
if (!root_box)
return CreatePositionWithAffinity(0);
- LayoutPoint clipped_point_in_contents(point_in_contents);
- clipped_point_in_contents.MoveBy(-root_box->Location());
+ PhysicalOffset clipped_point_in_contents(point_in_contents);
+ clipped_point_in_contents -= root_box->PhysicalLocation();
clipped_point_in_contents.ClampNegativeToZero();
- clipped_point_in_contents.MoveBy(root_box->Location());
+ clipped_point_in_contents += root_box->PhysicalLocation();
DCHECK(!root_box->NextRootBox());
DCHECK(ChildrenInline());
@@ -373,7 +372,7 @@ PositionWithAffinity LayoutSVGText::PositionForPoint(
return CreatePositionWithAffinity(0);
return closest_box->GetLineLayoutItem().PositionForPoint(
- LayoutPoint(clipped_point_in_contents.X(), closest_box->Y()));
+ PhysicalOffset(clipped_point_in_contents.left, closest_box->Y()));
}
void LayoutSVGText::AbsoluteQuads(Vector<FloatQuad>& quads,
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_text.h b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_text.h
index 852d90e209e..2360fe04afd 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_text.h
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_text.h
@@ -75,10 +75,10 @@ class LayoutSVGText final : public LayoutSVGBlock {
void Paint(const PaintInfo&) const override;
bool NodeAtPoint(HitTestResult&,
- const HitTestLocation& location_in_parent,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
HitTestAction) override;
- PositionWithAffinity PositionForPoint(const LayoutPoint&) const override;
+ PositionWithAffinity PositionForPoint(const PhysicalOffset&) const override;
void UpdateLayout() override;
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_text_path.cc b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_text_path.cc
index 7a6692aaf19..9b48551d5d5 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_text_path.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_text_path.cc
@@ -99,8 +99,7 @@ std::unique_ptr<PathPositionMapper> LayoutSVGTextPath::LayoutPath() const {
const SVGLength& start_offset =
*text_path_element.startOffset()->CurrentValue();
float path_start_offset = start_offset.ValueAsPercentage();
- if (start_offset.TypeWithCalcResolved() ==
- CSSPrimitiveValue::UnitType::kPercentage)
+ if (start_offset.IsPercentage())
path_start_offset *= author_path_length;
path_start_offset *= offset_scale;
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_text_test.cc b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_text_test.cc
index e295cb85ce2..a177ec7049e 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_text_test.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_text_test.cc
@@ -28,7 +28,7 @@ TEST_F(LayoutSVGTextTest, RectBasedHitTest) {
const auto& text = *GetDocument().getElementById("text")->firstChild();
// Rect based hit testing
- auto results = RectBasedHitTest(LayoutRect(0, 0, 300, 300));
+ auto results = RectBasedHitTest(PhysicalRect(0, 0, 300, 300));
int count = 0;
EXPECT_EQ(2u, results.size());
for (auto result : results) {
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_viewport_container.cc b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_viewport_container.cc
index 99fd0f01562..7e4fc9e0c0f 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_viewport_container.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_viewport_container.cc
@@ -77,15 +77,15 @@ SVGTransformChange LayoutSVGViewportContainer::CalculateLocalTransform() {
bool LayoutSVGViewportContainer::NodeAtPoint(
HitTestResult& result,
- const HitTestLocation& location_in_parent,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
HitTestAction action) {
// Respect the viewport clip which is in parent coordinates.
if (SVGLayoutSupport::IsOverflowHidden(*this)) {
- if (!location_in_parent.Intersects(viewport_))
+ if (!hit_test_location.Intersects(viewport_))
return false;
}
- return LayoutSVGContainer::NodeAtPoint(result, location_in_parent,
+ return LayoutSVGContainer::NodeAtPoint(result, hit_test_location,
accumulated_offset, action);
}
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_viewport_container.h b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_viewport_container.h
index 40bc37598c3..c7a32b46865 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_viewport_container.h
+++ b/chromium/third_party/blink/renderer/core/layout/svg/layout_svg_viewport_container.h
@@ -57,8 +57,8 @@ class LayoutSVGViewportContainer final : public LayoutSVGContainer {
SVGTransformChange CalculateLocalTransform() override;
bool NodeAtPoint(HitTestResult&,
- const HitTestLocation& location_in_parent,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
HitTestAction) final;
void StyleDidChange(StyleDifference, const ComputedStyle* old_style) override;
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 a01d1679d82..632ab791244 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
@@ -277,7 +277,7 @@ FloatRect SVGInlineTextBox::CalculateBoundaries() const {
}
bool SVGInlineTextBox::HitTestFragments(
- const HitTestLocation& location_in_container) const {
+ const HitTestLocation& hit_test_location) const {
auto line_layout_item = LineLayoutSVGInlineText(GetLineLayoutItem());
const SimpleFontData* font_data = line_layout_item.ScaledFont().PrimaryFont();
DCHECK(font_data);
@@ -289,15 +289,15 @@ bool SVGInlineTextBox::HitTestFragments(
line_layout_item.ScalingFactor();
for (const SVGTextFragment& fragment : text_fragments_) {
FloatQuad fragment_quad = fragment.BoundingQuad(baseline);
- if (location_in_container.Intersects(fragment_quad))
+ if (hit_test_location.Intersects(fragment_quad))
return true;
}
return false;
}
bool SVGInlineTextBox::NodeAtPoint(HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
LayoutUnit,
LayoutUnit) {
// FIXME: integrate with InlineTextBox::nodeAtPoint better.
@@ -315,15 +315,15 @@ bool SVGInlineTextBox::NodeAtPoint(HitTestResult& result,
(style.SvgStyle().HasStroke() || !hit_rules.require_stroke)) ||
(hit_rules.can_hit_fill &&
(style.SvgStyle().HasFill() || !hit_rules.require_fill))) {
- LayoutRect rect(Location(), Size());
- rect.MoveBy(accumulated_offset);
- if (location_in_container.Intersects(rect)) {
- if (HitTestFragments(location_in_container)) {
+ // Currently SVGInlineTextBox doesn't flip in blocks direction.
+ PhysicalRect rect{PhysicalOffset(Location()), PhysicalSize(Size())};
+ rect.Move(accumulated_offset);
+ if (hit_test_location.Intersects(rect)) {
+ if (HitTestFragments(hit_test_location)) {
line_layout_item.UpdateHitTestResult(
- result,
- location_in_container.Point() - ToLayoutSize(accumulated_offset));
+ result, hit_test_location.Point() - accumulated_offset);
if (result.AddNodeToListBasedTestResult(line_layout_item.GetNode(),
- location_in_container,
+ hit_test_location,
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 320ea2c6d68..e2fd77f4ddc 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,10 +97,10 @@ class SVGInlineTextBox final : public InlineTextBox {
const ComputedStyle&,
const Font&) const final;
- bool HitTestFragments(const HitTestLocation& location_in_container) const;
+ bool HitTestFragments(const HitTestLocation& hit_test_location) const;
bool NodeAtPoint(HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
LayoutUnit line_top,
LayoutUnit line_bottom) override;
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/line/svg_root_inline_box.cc b/chromium/third_party/blink/renderer/core/layout/svg/line/svg_root_inline_box.cc
index 7e61e2b2209..240be07bf5c 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/line/svg_root_inline_box.cc
+++ b/chromium/third_party/blink/renderer/core/layout/svg/line/svg_root_inline_box.cc
@@ -112,7 +112,7 @@ FloatRect SVGRootInlineBox::LayoutInlineBoxes(InlineBox& box) {
}
InlineBox* SVGRootInlineBox::ClosestLeafChildForPosition(
- const LayoutPoint& point) {
+ const PhysicalOffset& point) {
InlineBox* first_leaf = FirstLeafChild();
InlineBox* last_leaf = LastLeafChild();
if (first_leaf == last_leaf)
@@ -123,13 +123,13 @@ InlineBox* SVGRootInlineBox::ClosestLeafChildForPosition(
for (InlineBox* leaf = first_leaf; leaf; leaf = leaf->NextLeafChild()) {
if (!leaf->IsSVGInlineTextBox())
continue;
- if (point.Y() < leaf->Y())
+ if (point.top < leaf->Y())
continue;
- if (point.Y() > leaf->Y() + leaf->VirtualLogicalHeight())
+ if (point.left > leaf->Y() + leaf->VirtualLogicalHeight())
continue;
closest_leaf = leaf;
- if (point.X() < leaf->X() + leaf->LogicalWidth())
+ if (point.left < leaf->X() + leaf->LogicalWidth())
return leaf;
}
@@ -195,15 +195,15 @@ void SVGRootInlineBox::ReorderValueLists() {
}
bool SVGRootInlineBox::NodeAtPoint(HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
LayoutUnit line_top,
LayoutUnit line_bottom) {
// Iterate the text boxes in reverse so that the top-most node will be considered first.
for (InlineBox* leaf = LastLeafChild(); leaf; leaf = leaf->PrevLeafChild()) {
if (!leaf->IsSVGInlineTextBox())
continue;
- if (leaf->NodeAtPoint(result, location_in_container, accumulated_offset,
+ if (leaf->NodeAtPoint(result, hit_test_location, accumulated_offset,
line_top, line_bottom))
return true;
}
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/line/svg_root_inline_box.h b/chromium/third_party/blink/renderer/core/layout/svg/line/svg_root_inline_box.h
index d5a7e3dd4e0..8f741b84c92 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/line/svg_root_inline_box.h
+++ b/chromium/third_party/blink/renderer/core/layout/svg/line/svg_root_inline_box.h
@@ -45,11 +45,11 @@ class SVGRootInlineBox final : public RootInlineBox {
void ComputePerCharacterLayoutInformation();
- InlineBox* ClosestLeafChildForPosition(const LayoutPoint&);
+ InlineBox* ClosestLeafChildForPosition(const PhysicalOffset&);
bool NodeAtPoint(HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation&,
+ const PhysicalOffset& accumulated_offset,
LayoutUnit line_top,
LayoutUnit line_bottom) final;
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/svg_character_data.h b/chromium/third_party/blink/renderer/core/layout/svg/svg_character_data.h
index 51d8992472f..bdc5b2d240c 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/svg_character_data.h
+++ b/chromium/third_party/blink/renderer/core/layout/svg/svg_character_data.h
@@ -20,7 +20,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_SVG_SVG_CHARACTER_DATA_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_SVG_SVG_CHARACTER_DATA_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
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 22bb64f4308..40000a9c319 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
@@ -438,7 +438,7 @@ bool SVGLayoutSupport::IntersectsClipPath(const LayoutObject& object,
bool SVGLayoutSupport::HitTestChildren(LayoutObject* last_child,
HitTestResult& result,
const HitTestLocation& location,
- const LayoutPoint& accumulated_offset,
+ const PhysicalOffset& accumulated_offset,
HitTestAction hit_test_action) {
for (LayoutObject* child = last_child; child;
child = child->PreviousSibling()) {
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 ddd5082c70e..249f9fa383c 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
@@ -28,7 +28,7 @@
#include "third_party/blink/renderer/core/style/svg_computed_style_defs.h"
#include "third_party/blink/renderer/platform/graphics/dash_array.h"
#include "third_party/blink/renderer/platform/transforms/affine_transform.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -83,7 +83,7 @@ class CORE_EXPORT SVGLayoutSupport {
static bool HitTestChildren(LayoutObject* last_child,
HitTestResult&,
const HitTestLocation&,
- const LayoutPoint& accumulated_offset,
+ const PhysicalOffset& accumulated_offset,
HitTestAction);
static void ComputeContainerBoundingBoxes(const LayoutObject* container,
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 19c8fcfb805..bd1373febee 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
@@ -545,7 +545,7 @@ void WriteSVGResourceContainer(WTF::TextStream& ts,
int indent) {
WriteStandardPrefix(ts, object, indent);
- Element* element = ToElement(object.GetNode());
+ auto* element = To<Element>(object.GetNode());
const AtomicString& id = element->GetIdAttribute();
WriteNameAndQuotedValue(ts, "id", id);
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/svg_marker_data.h b/chromium/third_party/blink/renderer/core/layout/svg/svg_marker_data.h
index 33822360607..26d5061489f 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/svg_marker_data.h
+++ b/chromium/third_party/blink/renderer/core/layout/svg/svg_marker_data.h
@@ -21,7 +21,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_SVG_SVG_MARKER_DATA_H_
#include "third_party/blink/renderer/platform/graphics/path.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
namespace blink {
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 c2933d40a9e..32620578038 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
@@ -565,7 +565,8 @@ void SVGResources::Dump(const LayoutObject* object) {
fprintf(stderr, "-> this=%p, SVGResources(layoutObject=%p, node=%p)\n", this,
object, object->GetNode());
fprintf(stderr, " | DOM Tree:\n");
- fprintf(stderr, "%s", object->GetNode()->ToTreeStringForThis().Utf8().data());
+ fprintf(stderr, "%s",
+ object->GetNode()->ToTreeStringForThis().Utf8().c_str());
fprintf(stderr, "\n | List of resources:\n");
if (clipper_filter_masker_data_) {
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/svg_resources.h b/chromium/third_party/blink/renderer/core/layout/svg/svg_resources.h
index 9c6e12a91d4..5a158e2c60d 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/svg_resources.h
+++ b/chromium/third_party/blink/renderer/core/layout/svg/svg_resources.h
@@ -26,7 +26,7 @@
#include "base/memory/ptr_util.h"
#include "third_party/blink/renderer/core/layout/svg/layout_svg_resource_container.h"
#include "third_party/blink/renderer/core/svg/svg_resource_client.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/svg_resources_cache.h b/chromium/third_party/blink/renderer/core/layout/svg/svg_resources_cache.h
index 42b85c7edba..c44ec39599f 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/svg_resources_cache.h
+++ b/chromium/third_party/blink/renderer/core/layout/svg/svg_resources_cache.h
@@ -23,7 +23,7 @@
#include <memory>
#include "base/macros.h"
#include "third_party/blink/renderer/core/style/style_difference.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/svg_resources_cycle_solver.h b/chromium/third_party/blink/renderer/core/layout/svg/svg_resources_cycle_solver.h
index d220b7f90d1..bf44ebdde60 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/svg_resources_cycle_solver.h
+++ b/chromium/third_party/blink/renderer/core/layout/svg/svg_resources_cycle_solver.h
@@ -21,7 +21,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_SVG_SVG_RESOURCES_CYCLE_SOLVER_H_
#include "base/macros.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/svg_text_chunk_builder.h b/chromium/third_party/blink/renderer/core/layout/svg/svg_text_chunk_builder.h
index e071c61720c..4e8da8976a3 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/svg_text_chunk_builder.h
+++ b/chromium/third_party/blink/renderer/core/layout/svg/svg_text_chunk_builder.h
@@ -21,7 +21,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_SVG_SVG_TEXT_CHUNK_BUILDER_H_
#include "base/macros.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/svg_text_fragment.h b/chromium/third_party/blink/renderer/core/layout/svg/svg_text_fragment.h
index 99e63978ef7..0887fb715e0 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/svg_text_fragment.h
+++ b/chromium/third_party/blink/renderer/core/layout/svg/svg_text_fragment.h
@@ -22,7 +22,7 @@
#include "third_party/blink/renderer/core/layout/line/glyph_overflow.h"
#include "third_party/blink/renderer/platform/transforms/affine_transform.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 75f374bfa86..c2c41825bda 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
@@ -106,8 +106,7 @@ static SVGTextPositioningElement* PositioningElementFromLayoutObject(
DCHECK(node);
DCHECK(node->IsSVGElement());
- return IsSVGTextPositioningElement(*node) ? ToSVGTextPositioningElement(node)
- : nullptr;
+ return DynamicTo<SVGTextPositioningElement>(node);
}
void SVGTextLayoutAttributesBuilder::CollectTextPositioningElements(
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/svg_text_layout_attributes_builder.h b/chromium/third_party/blink/renderer/core/layout/svg/svg_text_layout_attributes_builder.h
index 3b879096927..37d9ed65f2e 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/svg_text_layout_attributes_builder.h
+++ b/chromium/third_party/blink/renderer/core/layout/svg/svg_text_layout_attributes_builder.h
@@ -23,7 +23,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/layout/svg/svg_character_data.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/svg_text_layout_engine.h b/chromium/third_party/blink/renderer/core/layout/svg/svg_text_layout_engine.h
index 4b5d1e93197..56dbf5acba6 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/svg_text_layout_engine.h
+++ b/chromium/third_party/blink/renderer/core/layout/svg/svg_text_layout_engine.h
@@ -25,7 +25,7 @@
#include "third_party/blink/renderer/core/layout/api/line_layout_svg_inline_text.h"
#include "third_party/blink/renderer/core/layout/svg/layout_svg_inline_text.h"
#include "third_party/blink/renderer/core/layout/svg/svg_text_fragment.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/svg_text_layout_engine_baseline.h b/chromium/third_party/blink/renderer/core/layout/svg/svg_text_layout_engine_baseline.h
index 68994d70553..718b6f0f1d6 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/svg_text_layout_engine_baseline.h
+++ b/chromium/third_party/blink/renderer/core/layout/svg/svg_text_layout_engine_baseline.h
@@ -23,7 +23,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/layout/api/line_layout_item.h"
#include "third_party/blink/renderer/core/style/svg_computed_style_defs.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/unicode.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/svg_text_layout_engine_spacing.h b/chromium/third_party/blink/renderer/core/layout/svg/svg_text_layout_engine_spacing.h
index d628d7817b4..ef87631fb4e 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/svg_text_layout_engine_spacing.h
+++ b/chromium/third_party/blink/renderer/core/layout/svg/svg_text_layout_engine_spacing.h
@@ -21,7 +21,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_SVG_SVG_TEXT_LAYOUT_ENGINE_SPACING_H_
#include "base/macros.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/unicode.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/svg_text_metrics.h b/chromium/third_party/blink/renderer/core/layout/svg/svg_text_metrics.h
index aa6e87b597a..6bc143857cc 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/svg_text_metrics.h
+++ b/chromium/third_party/blink/renderer/core/layout/svg/svg_text_metrics.h
@@ -20,7 +20,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_SVG_SVG_TEXT_METRICS_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_SVG_SVG_TEXT_METRICS_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/svg/svg_text_query.h b/chromium/third_party/blink/renderer/core/layout/svg/svg_text_query.h
index b806fefd7ce..e5fab8c5ba2 100644
--- a/chromium/third_party/blink/renderer/core/layout/svg/svg_text_query.h
+++ b/chromium/third_party/blink/renderer/core/layout/svg/svg_text_query.h
@@ -22,7 +22,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/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/layout/table_grid_cell.h b/chromium/third_party/blink/renderer/core/layout/table_grid_cell.h
index 5d0d076d724..13e88e1e26e 100644
--- a/chromium/third_party/blink/renderer/core/layout/table_grid_cell.h
+++ b/chromium/third_party/blink/renderer/core/layout/table_grid_cell.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_TABLE_GRID_CELL_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_TABLE_GRID_CELL_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.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.h b/chromium/third_party/blink/renderer/core/layout/table_layout_algorithm.h
index 6679dbf838c..467076e0ddb 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
@@ -23,7 +23,7 @@
#include "base/macros.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/allocator/allocator.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 a0945ffed6f..6118e1a1dd7 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
@@ -21,12 +21,12 @@
#include "third_party/blink/renderer/core/layout/table_layout_algorithm_fixed.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/layout/layout_table.h"
#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/geometry/layout_unit.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
/*
The text below is from the CSS 2.1 specs.
@@ -324,7 +324,7 @@ void TableLayoutAlgorithmFixed::UpdateLayout() {
if (width_[i].IsAuto()) {
unsigned span = table_->SpanOfEffectiveColumn(i);
int w = remaining_width * span / auto_span;
- calc_width[i] = w + hspacing * (span - 1);
+ calc_width[i] = std::max<int>((w + hspacing * (span - 1)), 0);
remaining_width -= w;
if (!remaining_width)
break;
@@ -334,8 +334,10 @@ void TableLayoutAlgorithmFixed::UpdateLayout() {
}
}
// Last one gets the remainder.
- if (remaining_width)
- calc_width[last_auto] += remaining_width;
+ if (remaining_width) {
+ calc_width[last_auto] =
+ std::max(calc_width[last_auto] + remaining_width, 0);
+ }
total_width = table_logical_width;
}
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 0030297f1c0..7b7a58c8b30 100644
--- a/chromium/third_party/blink/renderer/core/layout/text_autosizer.cc
+++ b/chromium/third_party/blink/renderer/core/layout/text_autosizer.cc
@@ -61,6 +61,19 @@
namespace blink {
+namespace {
+
+inline int GetLayoutInlineSize(const Document& document,
+ const LocalFrameView& main_frame_view) {
+ IntSize size = main_frame_view.GetLayoutSize();
+ const LayoutView* layout_view = document.GetLayoutView();
+ if (IsHorizontalWritingMode(layout_view->StyleRef().GetWritingMode()))
+ return size.Width();
+ return size.Height();
+}
+
+} // namespace
+
static LayoutObject* ParentElementLayoutObject(
const LayoutObject* layout_object) {
// At style recalc, the layoutObject's parent may not be attached,
@@ -77,9 +90,9 @@ static LayoutObject* ParentElementLayoutObject(
static bool IsNonTextAreaFormControl(const LayoutObject* layout_object) {
const Node* node = layout_object ? layout_object->GetNode() : nullptr;
- if (!node || !node->IsElementNode())
+ const auto* element = DynamicTo<Element>(node);
+ if (!element)
return false;
- const Element* element = ToElement(node);
return (element->IsFormControlElement() && !IsHTMLTextAreaElement(element));
}
@@ -549,11 +562,17 @@ void TextAutosizer::MarkSuperclusterForConsistencyCheck(LayoutObject* object) {
}
}
-void TextAutosizer::UpdatePageInfoInAllFrames() {
- DCHECK(!document_->GetFrame() || document_->GetFrame()->IsMainFrame());
+bool TextAutosizer::HasLayoutInlineSizeChanged() const {
+ DCHECK(document_->GetFrame()->IsMainFrame());
+ int new_inline_size =
+ GetLayoutInlineSize(*document_, *document_->GetFrame()->View());
+ return new_inline_size != page_info_.shared_info_.main_frame_layout_width;
+}
- for (Frame* frame = document_->GetFrame(); frame;
- frame = frame->Tree().TraverseNext()) {
+// Static.
+void TextAutosizer::UpdatePageInfoInAllFrames(Frame* main_frame) {
+ DCHECK(main_frame && main_frame == main_frame->Tree().Top());
+ for (Frame* frame = main_frame; frame; frame = frame->Tree().TraverseNext()) {
auto* local_frame = DynamicTo<LocalFrame>(frame);
if (!local_frame)
continue;
@@ -562,8 +581,25 @@ void TextAutosizer::UpdatePageInfoInAllFrames() {
// If document is being detached, skip updatePageInfo.
if (!document || !document->IsActive())
continue;
- if (TextAutosizer* text_autosizer = document->GetTextAutosizer())
+ if (TextAutosizer* text_autosizer = document->GetTextAutosizer()) {
text_autosizer->UpdatePageInfo();
+
+ // Share the page information from the local mainframe with remote ones.
+ // TODO(wjmaclean): Refactor this code into a non-static class function
+ // called UpdateWebTextAutosizerPageInfoIfNecessary().
+ if (frame->IsMainFrame()) {
+ const PageInfo& page_info = text_autosizer->page_info_;
+ const WebTextAutosizerPageInfo& old_page_info =
+ document->GetPage()->TextAutosizerPageInfo();
+ if (page_info.shared_info_ != old_page_info) {
+ document->GetPage()->GetChromeClient().DidUpdateTextAutosizerPageInfo(
+ page_info.shared_info_);
+ // Remember the RemotePageSettings in the mainframe's renderer so we
+ // know when they change.
+ document->GetPage()->SetTextAutosizePageInfo(page_info.shared_info_);
+ }
+ }
+ }
}
}
@@ -583,63 +619,60 @@ void TextAutosizer::UpdatePageInfo() {
bool horizontal_writing_mode =
IsHorizontalWritingMode(layout_view->StyleRef().GetWritingMode());
- // FIXME: With out-of-process iframes, the top frame can be remote and
- // doesn't have sizing information. Just return if this is the case.
Frame& frame = document_->GetFrame()->Tree().Top();
- if (frame.IsRemoteFrame())
- return;
-
- LocalFrame& main_frame = To<LocalFrame>(frame);
- IntSize frame_size =
- document_->GetSettings()->TextAutosizingWindowSizeOverride();
- if (frame_size.IsEmpty())
- frame_size = WindowSize();
-
- page_info_.frame_width_ =
- horizontal_writing_mode ? frame_size.Width() : frame_size.Height();
-
- IntSize layout_size = main_frame.View()->GetLayoutSize();
- page_info_.layout_width_ =
- horizontal_writing_mode ? layout_size.Width() : layout_size.Height();
-
- // TODO(pdr): Accessibility should be moved out of the text autosizer. See:
- // crbug.com/645717.
- page_info_.accessibility_font_scale_factor_ =
- document_->GetSettings()->GetAccessibilityFontScaleFactor();
-
- // If the page has a meta viewport or @viewport, don't apply the device
- // scale adjustment.
- if (!main_frame.GetDocument()
- ->GetViewportData()
- .GetViewportDescription()
- .IsSpecifiedByAuthor()) {
- page_info_.device_scale_adjustment_ =
- document_->GetSettings()->GetDeviceScaleAdjustment();
+ if (frame.IsRemoteFrame()) {
+ // When the frame is remote, the local main frame is responsible for
+ // computing shared_info_ and passing them down to the OOPIF renderers.
+ page_info_.shared_info_ = document_->GetPage()->TextAutosizerPageInfo();
} else {
- page_info_.device_scale_adjustment_ = 1.0f;
+ LocalFrame& main_frame = To<LocalFrame>(frame);
+ IntSize frame_size =
+ document_->GetSettings()->TextAutosizingWindowSizeOverride();
+ if (frame_size.IsEmpty())
+ frame_size = WindowSize();
+
+ page_info_.shared_info_.main_frame_width =
+ horizontal_writing_mode ? frame_size.Width() : frame_size.Height();
+
+ page_info_.shared_info_.main_frame_layout_width =
+ GetLayoutInlineSize(*document_, *main_frame.View());
+
+ // If the page has a meta viewport or @viewport, don't apply the device
+ // scale adjustment.
+ if (!main_frame.GetDocument()
+ ->GetViewportData()
+ .GetViewportDescription()
+ .IsSpecifiedByAuthor()) {
+ page_info_.shared_info_.device_scale_adjustment =
+ document_->GetSettings()->GetDeviceScaleAdjustment();
+ } else {
+ page_info_.shared_info_.device_scale_adjustment = 1.0f;
+ }
}
+ // TODO(pdr): Accessibility should be moved out of the text autosizer.
+ // See: crbug.com/645717.
+ page_info_.accessibility_font_scale_factor_ =
+ document_->GetSettings()->GetAccessibilityFontScaleFactor();
// TODO(pdr): pageNeedsAutosizing should take into account whether
// text-size-adjust is used anywhere on the page because that also needs to
// trigger autosizing. See: crbug.com/646237.
page_info_.page_needs_autosizing_ =
- !!page_info_.frame_width_ &&
+ !!page_info_.shared_info_.main_frame_width &&
(page_info_.accessibility_font_scale_factor_ *
- page_info_.device_scale_adjustment_ *
- (static_cast<float>(page_info_.layout_width_) /
- page_info_.frame_width_) >
+ page_info_.shared_info_.device_scale_adjustment *
+ (static_cast<float>(
+ page_info_.shared_info_.main_frame_layout_width) /
+ page_info_.shared_info_.main_frame_width) >
1.0f);
}
if (page_info_.page_needs_autosizing_) {
// If page info has changed, multipliers may have changed. Force a layout to
// recompute them.
- if (page_info_.frame_width_ != previous_page_info.frame_width_ ||
- page_info_.layout_width_ != previous_page_info.layout_width_ ||
+ if (page_info_.shared_info_ != previous_page_info.shared_info_ ||
page_info_.accessibility_font_scale_factor_ !=
previous_page_info.accessibility_font_scale_factor_ ||
- page_info_.device_scale_adjustment_ !=
- previous_page_info.device_scale_adjustment_ ||
page_info_.setting_enabled_ != previous_page_info.setting_enabled_)
SetAllTextNeedsLayout();
} else if (previous_page_info.has_autosized_) {
@@ -796,16 +829,15 @@ TextAutosizer::Fingerprint TextAutosizer::GetFingerprint(
TextAutosizer::Fingerprint TextAutosizer::ComputeFingerprint(
const LayoutObject* layout_object) {
- Node* node = layout_object->GeneratingNode();
- if (!node || !node->IsElementNode())
+ auto* element = DynamicTo<Element>(layout_object->GeneratingNode());
+ if (!element)
return 0;
FingerprintSourceData data;
if (LayoutObject* parent = ParentElementLayoutObject(layout_object))
data.parent_hash_ = GetFingerprint(parent);
- data.qualified_name_hash_ =
- QualifiedNameHash::GetHash(ToElement(node)->TagQName());
+ data.qualified_name_hash_ = QualifiedNameHash::GetHash(element->TagQName());
if (const ComputedStyle* style = layout_object->Style()) {
data.packed_style_properties_ = static_cast<unsigned>(style->Direction());
@@ -1025,12 +1057,15 @@ float TextAutosizer::MultiplierFromBlock(const LayoutBlock* block) {
#endif
// Block width, in CSS pixels.
float block_width = WidthFromBlock(block);
- float layout_width =
- std::min(block_width, static_cast<float>(page_info_.layout_width_));
+ float layout_width = std::min(
+ block_width,
+ static_cast<float>(page_info_.shared_info_.main_frame_layout_width));
float multiplier =
- page_info_.frame_width_ ? layout_width / page_info_.frame_width_ : 1.0f;
+ page_info_.shared_info_.main_frame_width
+ ? layout_width / page_info_.shared_info_.main_frame_width
+ : 1.0f;
multiplier *= page_info_.accessibility_font_scale_factor_ *
- page_info_.device_scale_adjustment_;
+ page_info_.shared_info_.device_scale_adjustment;
return std::max(multiplier, 1.0f);
}
@@ -1249,8 +1284,8 @@ bool TextAutosizer::IsWiderOrNarrowerDescendant(Cluster* cluster) {
// Clusters with a root that is significantly narrower than the
// deepestBlockContainingAllText of their parent autosize independently of
// their parent.
- static float narrow_width_difference = 200;
- if (cluster_text_width - content_width > narrow_width_difference)
+ constexpr float kNarrowWidthDifference = 200;
+ if (cluster_text_width - content_width > kNarrowWidthDifference)
return true;
return false;
@@ -1387,6 +1422,10 @@ TextAutosizer::TableLayoutScope::TableLayoutScope(LayoutTable* table)
TextAutosizer::DeferUpdatePageInfo::DeferUpdatePageInfo(Page* page)
: main_frame_(page->DeprecatedLocalMainFrame()) {
+ // TODO(wjmaclean): see if we need to try and extend deferred updates to
+ // renderers for remote main frames or not. For now, it's safe to assume
+ // main_frame_ will be local, see WebViewImpl::ResizeViewWhileAnchored().
+ DCHECK(main_frame_);
if (TextAutosizer* text_autosizer =
main_frame_->GetDocument()->GetTextAutosizer()) {
DCHECK(!text_autosizer->update_page_info_deferred_);
@@ -1428,7 +1467,7 @@ TextAutosizer::DeferUpdatePageInfo::~DeferUpdatePageInfo() {
main_frame_->GetDocument()->GetTextAutosizer()) {
DCHECK(text_autosizer->update_page_info_deferred_);
text_autosizer->update_page_info_deferred_ = false;
- text_autosizer->UpdatePageInfoInAllFrames();
+ TextAutosizer::UpdatePageInfoInAllFrames(main_frame_);
}
}
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 b4127ab77e9..92ad9de3fbc 100644
--- a/chromium/third_party/blink/renderer/core/layout/text_autosizer.h
+++ b/chromium/third_party/blink/renderer/core/layout/text_autosizer.h
@@ -34,6 +34,7 @@
#include <unicode/uchar.h>
#include <memory>
#include "base/macros.h"
+#include "third_party/blink/public/platform/web_text_autosizer_page_info.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"
@@ -43,6 +44,7 @@
namespace blink {
class Document;
+class Frame;
class IntSize;
class LayoutBlock;
class LayoutObject;
@@ -66,8 +68,12 @@ class CORE_EXPORT TextAutosizer final
static float ComputeAutosizedFontSize(float computed_size,
float multiplier,
float effective_zoom);
+ // Static to allow starting updates from the frame tree root when it's a
+ // remote frame, though this function is called for all main frames, local
+ // or remote.
+ static void UpdatePageInfoInAllFrames(Frame* root_frame);
- void UpdatePageInfoInAllFrames();
+ bool HasLayoutInlineSizeChanged() const;
void UpdatePageInfo();
void Record(LayoutBlock*);
void Record(LayoutText*);
@@ -275,19 +281,10 @@ class CORE_EXPORT TextAutosizer final
struct PageInfo {
DISALLOW_NEW();
- PageInfo()
- : frame_width_(0),
- layout_width_(0),
- accessibility_font_scale_factor_(1),
- device_scale_adjustment_(1),
- page_needs_autosizing_(false),
- has_autosized_(false),
- setting_enabled_(false) {}
-
- int frame_width_; // LocalFrame width in density-independent pixels (DIPs).
- int layout_width_; // Layout width in CSS pixels.
+ PageInfo() = default;
+
+ WebTextAutosizerPageInfo shared_info_;
float accessibility_font_scale_factor_;
- float device_scale_adjustment_;
bool page_needs_autosizing_;
bool has_autosized_;
bool setting_enabled_;
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 30a93f3002f..e1aa7348e17 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
@@ -24,14 +24,13 @@ void DumpToTracedValue(const LayoutObject& object,
traced_value->SetString("name", object.GetName());
if (Node* node = object.GetNode()) {
traced_value->SetString("tag", node->nodeName());
- if (node->IsElementNode()) {
- Element& element = ToElement(*node);
- if (element.HasID())
- traced_value->SetString("htmlId", element.GetIdAttribute());
- if (element.HasClass()) {
+ if (auto* element = DynamicTo<Element>(node)) {
+ if (element->HasID())
+ traced_value->SetString("htmlId", element->GetIdAttribute());
+ if (element->HasClass()) {
traced_value->BeginArray("classNames");
- for (wtf_size_t i = 0; i < element.ClassNames().size(); ++i)
- traced_value->PushString(element.ClassNames()[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/vertical_position_cache.h b/chromium/third_party/blink/renderer/core/layout/vertical_position_cache.h
index bd7d9c72536..6cf00a1b613 100644
--- a/chromium/third_party/blink/renderer/core/layout/vertical_position_cache.h
+++ b/chromium/third_party/blink/renderer/core/layout/vertical_position_cache.h
@@ -29,7 +29,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/layout/api/line_layout_item.h"
#include "third_party/blink/renderer/platform/fonts/font_baseline.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
namespace blink {
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 cfada8e1a01..a938d0ac85e 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
@@ -21,10 +21,15 @@ class VisualRectMappingTest : public PaintTestConfigurations,
: RenderingTest(MakeGarbageCollected<SingleChildLocalFrameClient>()) {}
protected:
- LayoutView& GetLayoutView() const { return *GetDocument().GetLayoutView(); }
-
enum Flags { kContainsEnclosingIntRect = 1 << 0 };
+ void SetUp() override {
+ EnableCompositing();
+ RenderingTest::SetUp();
+ }
+
+ LayoutView& GetLayoutView() const { return *GetDocument().GetLayoutView(); }
+
void CheckPaintInvalidationVisualRect(
const LayoutObject& object,
const LayoutBoxModelObject& ancestor,
@@ -671,7 +676,6 @@ TEST_P(VisualRectMappingTest, ContainerAndTargetDifferentFlippedWritingMode) {
TEST_P(VisualRectMappingTest,
DifferentPaintInvalidaitionContainerForAbsolutePosition) {
- EnableCompositing();
GetDocument().GetFrame()->GetSettings()->SetPreferCompositingToLCDTextEnabled(
true);
@@ -718,7 +722,6 @@ TEST_P(VisualRectMappingTest,
TEST_P(VisualRectMappingTest,
ContainerOfAbsoluteAbovePaintInvalidationContainer) {
- EnableCompositing();
GetDocument().GetFrame()->GetSettings()->SetPreferCompositingToLCDTextEnabled(
true);
@@ -976,7 +979,6 @@ TEST_P(VisualRectMappingTest, AbsoluteUnderRelativeInlineVerticalRL) {
}
TEST_P(VisualRectMappingTest, ShouldAccountForPreserve3d) {
- EnableCompositing();
SetBodyInnerHTML(R"HTML(
<style>
* { margin: 0; }
@@ -1007,7 +1009,6 @@ TEST_P(VisualRectMappingTest, ShouldAccountForPreserve3d) {
}
TEST_P(VisualRectMappingTest, ShouldAccountForPreserve3dNested) {
- EnableCompositing();
SetBodyInnerHTML(R"HTML(
<style>
* { margin: 0; }
@@ -1037,7 +1038,6 @@ TEST_P(VisualRectMappingTest, ShouldAccountForPreserve3dNested) {
}
TEST_P(VisualRectMappingTest, ShouldAccountForPerspective) {
- EnableCompositing();
SetBodyInnerHTML(R"HTML(
<style>
* { margin: 0; }
@@ -1071,7 +1071,6 @@ TEST_P(VisualRectMappingTest, ShouldAccountForPerspective) {
}
TEST_P(VisualRectMappingTest, ShouldAccountForPerspectiveNested) {
- EnableCompositing();
SetBodyInnerHTML(R"HTML(
<style>
* { margin: 0; }
@@ -1104,7 +1103,6 @@ TEST_P(VisualRectMappingTest, ShouldAccountForPerspectiveNested) {
}
TEST_P(VisualRectMappingTest, PerspectivePlusScroll) {
- EnableCompositing();
SetBodyInnerHTML(R"HTML(
<style>
* { margin: 0; }
@@ -1128,7 +1126,7 @@ TEST_P(VisualRectMappingTest, PerspectivePlusScroll) {
</div>
)HTML");
auto* container = To<LayoutBlock>(GetLayoutObjectByElementId("container"));
- ToElement(container->GetNode())->scrollTo(0, 5);
+ To<Element>(container->GetNode())->scrollTo(0, 5);
UpdateAllLifecyclePhasesForTest();
auto* target = To<LayoutBlock>(GetLayoutObjectByElementId("target"));
diff --git a/chromium/third_party/blink/renderer/core/loader/BUILD.gn b/chromium/third_party/blink/renderer/core/loader/BUILD.gn
index d50908b0f09..dbefedeaab4 100644
--- a/chromium/third_party/blink/renderer/core/loader/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/loader/BUILD.gn
@@ -12,6 +12,10 @@ blink_core_sources("loader") {
"appcache/application_cache.h",
"appcache/application_cache_host.cc",
"appcache/application_cache_host.h",
+ "appcache/application_cache_host_for_frame.cc",
+ "appcache/application_cache_host_for_frame.h",
+ "appcache/application_cache_host_for_shared_worker.cc",
+ "appcache/application_cache_host_for_shared_worker.h",
"base_fetch_context.cc",
"base_fetch_context.h",
"cookie_jar.cc",
@@ -142,6 +146,10 @@ blink_core_sources("loader") {
"threadable_loader.cc",
"threadable_loader.h",
"threadable_loader_client.h",
+ "threaded_icon_loader.cc",
+ "threaded_icon_loader.h",
+ "web_associated_url_loader_impl.cc",
+ "web_associated_url_loader_impl.h",
"worker_fetch_context.cc",
"worker_fetch_context.h",
"worker_resource_fetcher_properties.cc",
diff --git a/chromium/third_party/blink/renderer/core/loader/DEPS b/chromium/third_party/blink/renderer/core/loader/DEPS
new file mode 100644
index 00000000000..0d1f45e4ad4
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/loader/DEPS
@@ -0,0 +1,5 @@
+specific_include_rules = {
+ "alternate_signed_exchange_resource_info.cc" : [
+ "+net/http/http_request_headers.h"
+ ],
+}
diff --git a/chromium/third_party/blink/renderer/core/loader/alternate_signed_exchange_resource_info.cc b/chromium/third_party/blink/renderer/core/loader/alternate_signed_exchange_resource_info.cc
index 5867f426104..96ab51b7ab1 100644
--- a/chromium/third_party/blink/renderer/core/loader/alternate_signed_exchange_resource_info.cc
+++ b/chromium/third_party/blink/renderer/core/loader/alternate_signed_exchange_resource_info.cc
@@ -4,8 +4,11 @@
#include "third_party/blink/renderer/core/loader/alternate_signed_exchange_resource_info.h"
+#include "net/http/http_request_headers.h"
#include "third_party/blink/public/common/web_package/signed_exchange_consts.h"
+#include "third_party/blink/public/common/web_package/signed_exchange_request_matcher.h"
#include "third_party/blink/public/platform/web_url.h"
+#include "third_party/blink/renderer/platform/loader/fetch/resource.h"
#include "third_party/blink/renderer/platform/loader/link_header.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/wtf/hash_functions.h"
@@ -18,6 +21,12 @@ namespace {
constexpr char kAlternate[] = "alternate";
constexpr char kAllowedAltSxg[] = "allowed-alt-sxg";
+// These accept header values are also defined in web_url_loader_impl.h and
+// loader_util.h. TODO(horo): Move somewhere and use shared constant value.
+const char kDefaultAcceptHeader[] = "*/*";
+const char kStylesheetAcceptHeader[] = "text/css,*/*;q=0.1";
+const char kImageAcceptHeader[] = "image/webp,image/apng,image/*,*/*;q=0.8";
+
using AlternateSignedExchangeMachingKey =
std::pair<String /* anchor */,
std::pair<String /* variants */, String /* variant_key */>>;
@@ -113,12 +122,67 @@ AlternateSignedExchangeResourceInfo::AlternateSignedExchangeResourceInfo(
: alternative_resources_(std::move(alternative_resources)) {}
AlternateSignedExchangeResourceInfo::Entry*
-AlternateSignedExchangeResourceInfo::FindMatchingEntry(const KURL& url) const {
+AlternateSignedExchangeResourceInfo::FindMatchingEntry(
+ const KURL& url,
+ base::Optional<ResourceType> resource_type,
+ const Vector<String>& languages) const {
+ const char* accept_header = kDefaultAcceptHeader;
+ if (resource_type == ResourceType::kCSSStyleSheet) {
+ accept_header = kStylesheetAcceptHeader;
+ } else if (resource_type == ResourceType::kImage) {
+ accept_header = kImageAcceptHeader;
+ }
+ return FindMatchingEntry(url, accept_header, languages);
+}
+
+AlternateSignedExchangeResourceInfo::Entry*
+AlternateSignedExchangeResourceInfo::FindMatchingEntry(
+ const KURL& url,
+ mojom::RequestContextType request_context,
+ const Vector<String>& languages) const {
+ const char* accept_header = kDefaultAcceptHeader;
+ if (request_context == mojom::RequestContextType::STYLE) {
+ accept_header = kStylesheetAcceptHeader;
+ } else if (request_context == mojom::RequestContextType::IMAGE) {
+ accept_header = kImageAcceptHeader;
+ }
+ return FindMatchingEntry(url, accept_header, languages);
+}
+
+AlternateSignedExchangeResourceInfo::Entry*
+AlternateSignedExchangeResourceInfo::FindMatchingEntry(
+ const KURL& url,
+ const char* accept_header,
+ const Vector<String>& languages) const {
const auto it = alternative_resources_.find(url);
if (it == alternative_resources_.end())
return nullptr;
- // TODO(crbug.com/935267): Support variants and variant_key checking.
- return it->value.back().get();
+ const Vector<std::unique_ptr<Entry>>& entries = it->value;
+ DCHECK(!entries.IsEmpty());
+ if (entries[0]->variants().IsNull())
+ return entries[0].get();
+
+ const std::string variants = entries[0]->variants().Utf8();
+ std::vector<std::string> variant_keys_list;
+ for (const auto& entry : entries) {
+ variant_keys_list.emplace_back(entry->variant_key().Utf8());
+ }
+ std::string accept_langs;
+ for (const auto& language : languages) {
+ if (!accept_langs.empty())
+ accept_langs += ",";
+ accept_langs += language.Utf8();
+ }
+ net::HttpRequestHeaders request_headers;
+ request_headers.SetHeader("accept", accept_header);
+
+ SignedExchangeRequestMatcher matcher(request_headers, accept_langs);
+ const auto variant_keys_list_it =
+ matcher.FindBestMatchingVariantKey(variants, variant_keys_list);
+ if (variant_keys_list_it == variant_keys_list.end())
+ return nullptr;
+ return (entries.begin() + (variant_keys_list_it - variant_keys_list.begin()))
+ ->get();
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/loader/alternate_signed_exchange_resource_info.h b/chromium/third_party/blink/renderer/core/loader/alternate_signed_exchange_resource_info.h
index 15ef7f24766..c1fe8c0ad68 100644
--- a/chromium/third_party/blink/renderer/core/loader/alternate_signed_exchange_resource_info.h
+++ b/chromium/third_party/blink/renderer/core/loader/alternate_signed_exchange_resource_info.h
@@ -6,6 +6,8 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_ALTERNATE_SIGNED_EXCHANGE_RESOURCE_INFO_H_
#include "base/macros.h"
+#include "base/optional.h"
+#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/weborigin/kurl_hash.h"
@@ -16,6 +18,8 @@
namespace blink {
+enum class ResourceType : uint8_t;
+
// AlternateSignedExchangeResourceInfo keeps the alternate signed exchange
// resource information which is extracted from "alternate" link headers in the
// outer response and "allowed-alt-sxg" link headers in the inner response while
@@ -91,14 +95,27 @@ class CORE_EXPORT AlternateSignedExchangeResourceInfo {
AlternateSignedExchangeResourceInfo(EntryMap alternative_resources);
~AlternateSignedExchangeResourceInfo() = default;
- // Returns the best matching alternate resource. Currently this method just
- // returns the last one. TODO(crbug.com/935267): Support variants and
- // variant_key checking.
- Entry* FindMatchingEntry(const KURL& url) const;
+ // Returns the best matching alternate resource. If the first entry which
+ // |anchor_url| is |url| has non-null |variants| value, this method use the
+ // preference order of the result of "Cache Behaviour" [1] to find the best
+ // matching entry. Otherwise returns the first entry which |anchor_url| is
+ // |url|.
+ // [1]
+ // https://httpwg.org/http-extensions/draft-ietf-httpbis-variants.html#cache
+ Entry* FindMatchingEntry(const KURL& url,
+ base::Optional<ResourceType> resource_type,
+ const Vector<String>& languages) const;
+ Entry* FindMatchingEntry(const KURL& url,
+ mojom::RequestContextType request_context,
+ const Vector<String>& languages) const;
private:
friend class AlternateSignedExchangeResourceInfoTest;
+ Entry* FindMatchingEntry(const KURL& url,
+ const char* accept_header,
+ const Vector<String>& languages) const;
+
const EntryMap alternative_resources_;
DISALLOW_COPY_AND_ASSIGN(AlternateSignedExchangeResourceInfo);
diff --git a/chromium/third_party/blink/renderer/core/loader/alternate_signed_exchange_resource_info_test.cc b/chromium/third_party/blink/renderer/core/loader/alternate_signed_exchange_resource_info_test.cc
index 3787c9a6bec..9ac6dbb59de 100644
--- a/chromium/third_party/blink/renderer/core/loader/alternate_signed_exchange_resource_info_test.cc
+++ b/chromium/third_party/blink/renderer/core/loader/alternate_signed_exchange_resource_info_test.cc
@@ -6,15 +6,16 @@
#include "base/macros.h"
#include "testing/gtest/include/gtest/gtest.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 AlternateSignedExchangeResourceInfoTest : public testing::Test {
+class AlternateSignedExchangeResourceInfoTest
+ : public testing::Test,
+ private ScopedSignedExchangeSubresourcePrefetchForTest {
public:
- AlternateSignedExchangeResourceInfoTest() {
- RuntimeEnabledFeatures::SetSignedExchangeSubresourcePrefetchEnabled(true);
- }
+ AlternateSignedExchangeResourceInfoTest()
+ : ScopedSignedExchangeSubresourcePrefetchForTest(true) {}
~AlternateSignedExchangeResourceInfoTest() override = default;
protected:
@@ -62,10 +63,12 @@ TEST_F(AlternateSignedExchangeResourceInfoTest, Simple) {
EXPECT_TRUE(resource->variants().IsEmpty());
EXPECT_TRUE(resource->variant_key().IsEmpty());
- EXPECT_EQ(resource.get(), info->FindMatchingEntry(
- KURL("https://publisher.example/script.js")));
+ EXPECT_EQ(resource.get(),
+ info->FindMatchingEntry(KURL("https://publisher.example/script.js"),
+ base::nullopt, {"en"}));
EXPECT_EQ(nullptr,
- info->FindMatchingEntry(KURL("https://publisher.example/image")));
+ info->FindMatchingEntry(KURL("https://publisher.example/image"),
+ base::nullopt, {"en"}));
}
TEST_F(AlternateSignedExchangeResourceInfoTest, MultipleResources) {
@@ -109,7 +112,8 @@ TEST_F(AlternateSignedExchangeResourceInfoTest, MultipleResources) {
EXPECT_TRUE(resource->variants().IsEmpty());
EXPECT_TRUE(resource->variant_key().IsEmpty());
EXPECT_EQ(resource.get(), info->FindMatchingEntry(
- KURL("https://publisher.example/script.js")));
+ KURL("https://publisher.example/script.js"),
+ base::nullopt, {"en"}));
}
{
const auto& it = entries.find(KURL("https://publisher.example/image"));
@@ -124,7 +128,8 @@ TEST_F(AlternateSignedExchangeResourceInfoTest, MultipleResources) {
EXPECT_TRUE(resource->variants().IsEmpty());
EXPECT_TRUE(resource->variant_key().IsEmpty());
EXPECT_EQ(resource.get(),
- info->FindMatchingEntry(KURL("https://publisher.example/image")));
+ info->FindMatchingEntry(KURL("https://publisher.example/image"),
+ base::nullopt, {"en"}));
}
}
@@ -154,8 +159,9 @@ TEST_F(AlternateSignedExchangeResourceInfoTest,
EXPECT_TRUE(resource->variants().IsEmpty());
EXPECT_TRUE(resource->variant_key().IsEmpty());
- EXPECT_EQ(resource.get(), info->FindMatchingEntry(
- KURL("https://publisher.example/script.js")));
+ EXPECT_EQ(resource.get(),
+ info->FindMatchingEntry(KURL("https://publisher.example/script.js"),
+ base::nullopt, {"en"}));
}
TEST_F(AlternateSignedExchangeResourceInfoTest, NoType) {
@@ -187,10 +193,12 @@ TEST_F(AlternateSignedExchangeResourceInfoTest, NoType) {
EXPECT_TRUE(resource->variants().IsEmpty());
EXPECT_TRUE(resource->variant_key().IsEmpty());
- EXPECT_EQ(resource.get(), info->FindMatchingEntry(
- KURL("https://publisher.example/script.js")));
+ EXPECT_EQ(resource.get(),
+ info->FindMatchingEntry(KURL("https://publisher.example/script.js"),
+ base::nullopt, {"en"}));
EXPECT_EQ(nullptr,
- info->FindMatchingEntry(KURL("https://publisher.example/image")));
+ info->FindMatchingEntry(KURL("https://publisher.example/image"),
+ base::nullopt, {"en"}));
}
TEST_F(AlternateSignedExchangeResourceInfoTest, InvalidOuterURL) {
@@ -221,8 +229,9 @@ TEST_F(AlternateSignedExchangeResourceInfoTest, InvalidOuterURL) {
EXPECT_TRUE(resource->variants().IsEmpty());
EXPECT_TRUE(resource->variant_key().IsEmpty());
- EXPECT_EQ(resource.get(), info->FindMatchingEntry(
- KURL("https://publisher.example/script.js")));
+ EXPECT_EQ(resource.get(),
+ info->FindMatchingEntry(KURL("https://publisher.example/script.js"),
+ base::nullopt, {"en"}));
}
TEST_F(AlternateSignedExchangeResourceInfoTest, InvalidInnerURL) {
@@ -248,27 +257,27 @@ TEST_F(AlternateSignedExchangeResourceInfoTest, Variants) {
"<https://distributor.example/publisher.example/image_jpeg.sxg>;"
"rel=\"alternate\";"
"type=\"application/signed-exchange;v=b3\";"
- "variants-04=\"accept;image/jpeg,image/webp\";"
+ "variants-04=\"accept;image/jpeg;image/webp\";"
"variant-key-04=\"image/jpeg\";"
"anchor=\"https://publisher.example/image\";,"
// The second outer link header
"<https://distributor.example/publisher.example/image_webp.sxg>;"
"rel=\"alternate\";"
"type=\"application/signed-exchange;v=b3\";"
- "variants-04=\"accept;image/jpeg,image/webp\";"
+ "variants-04=\"accept;image/jpeg;image/webp\";"
"variant-key-04=\"image/webp\";"
"anchor=\"https://publisher.example/image\"",
// The first inner link header
"<https://publisher.example/image>;"
"rel=\"allowed-alt-sxg\";"
- "variants-04=\"accept;image/jpeg,image/webp\";"
+ "variants-04=\"accept;image/jpeg;image/webp\";"
"variant-key-04=\"image/jpeg\";"
"header-integrity="
"\"sha256-q1phjFcR+umcl0zBaEz6E5AGVlnc9yF0zOjDYi5c6aM=\","
// The second inner link header
"<https://publisher.example/image>;"
"rel=\"allowed-alt-sxg\";"
- "variants-04=\"accept;image/jpeg,image/webp\";"
+ "variants-04=\"accept;image/jpeg;image/webp\";"
"variant-key-04=\"image/webp\";"
"header-integrity="
"\"sha256-KRcYU+BZK8Sb2ccJfDPz+uUKXDdB1PVToPugItdzRXY=\"");
@@ -286,7 +295,7 @@ TEST_F(AlternateSignedExchangeResourceInfoTest, Variants) {
resource->alternative_url());
EXPECT_EQ("sha256-q1phjFcR+umcl0zBaEz6E5AGVlnc9yF0zOjDYi5c6aM=",
resource->header_integrity());
- EXPECT_EQ("accept;image/jpeg,image/webp", resource->variants());
+ EXPECT_EQ("accept;image/jpeg;image/webp", resource->variants());
EXPECT_EQ("image/jpeg", resource->variant_key());
}
{
@@ -297,13 +306,12 @@ TEST_F(AlternateSignedExchangeResourceInfoTest, Variants) {
resource->alternative_url());
EXPECT_EQ("sha256-KRcYU+BZK8Sb2ccJfDPz+uUKXDdB1PVToPugItdzRXY=",
resource->header_integrity());
- EXPECT_EQ("accept;image/jpeg,image/webp", resource->variants());
+ EXPECT_EQ("accept;image/jpeg;image/webp", resource->variants());
EXPECT_EQ("image/webp", resource->variant_key());
- // Currently FindMatchingEntry() just returns the last
- // matching resource without checking variants and variant-key.
- EXPECT_EQ(resource.get(),
- info->FindMatchingEntry(KURL("https://publisher.example/image")));
+ EXPECT_EQ(resource.get(), info->FindMatchingEntry(
+ KURL("https://publisher.example/image"),
+ mojom::RequestContextType::IMAGE, {"en"}));
}
}
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 d833043cd81..d0e14b8d225 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
@@ -32,10 +32,10 @@
#include "third_party/blink/renderer/core/frame/deprecation.h"
#include "third_party/blink/renderer/core/frame/hosts_using_features.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/loader/document_loader.h"
#include "third_party/blink/renderer/core/loader/frame_loader.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/loader/appcache/application_cache.idl b/chromium/third_party/blink/renderer/core/loader/appcache/application_cache.idl
index e5826d202d7..b2d793b7846 100644
--- a/chromium/third_party/blink/renderer/core/loader/appcache/application_cache.idl
+++ b/chromium/third_party/blink/renderer/core/loader/appcache/application_cache.idl
@@ -26,6 +26,7 @@
// https://html.spec.whatwg.org/C/#application-cache-api
[
+ Exposed=Window,
DoNotCheckConstants,
SecureContext=RestrictAppCacheToSecureContexts
// TODO(foolip): Exposed=(Window,SharedWorker)
diff --git a/chromium/third_party/blink/renderer/core/loader/appcache/application_cache_host.cc b/chromium/third_party/blink/renderer/core/loader/appcache/application_cache_host.cc
index 6ca47a24490..e52f3cf0544 100644
--- a/chromium/third_party/blink/renderer/core/loader/appcache/application_cache_host.cc
+++ b/chromium/third_party/blink/renderer/core/loader/appcache/application_cache_host.cc
@@ -30,14 +30,13 @@
#include "third_party/blink/renderer/core/loader/appcache/application_cache_host.h"
+#include <utility>
+
+#include "mojo/public/cpp/bindings/pending_remote.h"
#include "third_party/blink/public/mojom/appcache/appcache.mojom-blink.h"
#include "third_party/blink/public/mojom/appcache/appcache_info.mojom-blink.h"
-#include "third_party/blink/public/platform/web_url.h"
-#include "third_party/blink/public/platform/web_url_error.h"
-#include "third_party/blink/public/platform/web_url_request.h"
-#include "third_party/blink/public/platform/web_url_response.h"
-#include "third_party/blink/public/platform/web_vector.h"
-#include "third_party/blink/public/web/web_application_cache_host.h"
+#include "third_party/blink/public/platform/interface_provider.h"
+#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/core/events/application_cache_error_event.h"
#include "third_party/blink/renderer/core/events/progress_event.h"
#include "third_party/blink/renderer/core/frame/deprecation.h"
@@ -45,43 +44,77 @@
#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/inspector_application_cache_agent.h"
#include "third_party/blink/renderer/core/loader/appcache/application_cache.h"
+#include "third_party/blink/renderer/core/loader/appcache/application_cache_host_for_frame.h"
+#include "third_party/blink/renderer/core/loader/appcache/application_cache_host_for_shared_worker.h"
#include "third_party/blink/renderer/core/loader/document_loader.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/page/frame_tree.h"
-#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.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/weborigin/security_origin.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
namespace blink {
+namespace {
+
+// Note: the order of the elements in this array must match those
+// of the EventID enum in appcache_interfaces.h.
+const char* const kEventNames[] = {"Checking", "Error", "NoUpdate",
+ "Downloading", "Progress", "UpdateReady",
+ "Cached", "Obsolete"};
+
+mojom::blink::DocumentInterfaceBroker* GetDocumentInterfaceBroker(
+ LocalFrame* local_frame) {
+ return local_frame->Client()->GetDocumentInterfaceBroker();
+}
+
+} // namespace
+
+ApplicationCacheHost* ApplicationCacheHost::Create(
+ DocumentLoader* document_loader) {
+ DCHECK(document_loader);
+ DCHECK(document_loader->GetFrame());
+ LocalFrame* local_frame = document_loader->GetFrame();
+
+ DCHECK(local_frame->Client());
+ WebLocalFrameClient::AppCacheType type =
+ local_frame->Client()->GetAppCacheType();
+ switch (type) {
+ case WebLocalFrameClient::AppCacheType::kAppCacheForFrame:
+ return MakeGarbageCollected<ApplicationCacheHostForFrame>(
+ document_loader, GetDocumentInterfaceBroker(local_frame),
+ local_frame->GetTaskRunner(TaskType::kNetworking));
+ case WebLocalFrameClient::AppCacheType::kAppCacheForSharedWorker:
+ return MakeGarbageCollected<ApplicationCacheHostForSharedWorker>(
+ document_loader, Thread::Current()->GetTaskRunner());
+ default:
+ return MakeGarbageCollected<ApplicationCacheHost>(document_loader,
+ nullptr, nullptr);
+ }
+ return nullptr;
+}
+
// We provide a custom implementation of this class that calls out to the
// embedding application instead of using WebCore's built in appcache system.
// This file replaces webcore/appcache/ApplicationCacheHost.cpp in our build.
-ApplicationCacheHost::ApplicationCacheHost(DocumentLoader* document_loader)
- : dom_application_cache_(nullptr),
- document_loader_(document_loader),
- defers_events_(true) {
- DCHECK(document_loader_);
-}
+ApplicationCacheHost::ApplicationCacheHost(
+ DocumentLoader* document_loader,
+ mojom::blink::DocumentInterfaceBroker* interface_broker,
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner)
+ : document_loader_(document_loader),
+ task_runner_(std::move(task_runner)),
+ interface_broker_(interface_broker) {}
-ApplicationCacheHost::~ApplicationCacheHost() {
- // Verify that detachFromDocumentLoader() has been performed already.
- DCHECK(!host_);
-}
+ApplicationCacheHost::~ApplicationCacheHost() = default;
void ApplicationCacheHost::WillStartLoading(ResourceRequest& request) {
- if (!IsApplicationCacheEnabled() || !host_)
+ if (!IsApplicationCacheEnabled() || !backend_host_.is_bound())
return;
- const base::UnguessableToken& host_id = host_->GetHostID();
+ const base::UnguessableToken& host_id = GetHostID();
if (!host_id.is_empty())
request.SetAppCacheHostID(host_id);
}
@@ -91,83 +124,11 @@ void ApplicationCacheHost::WillStartLoadingMainResource(DocumentLoader* loader,
const String& method) {
if (!IsApplicationCacheEnabled())
return;
- // We defer creating the outer host object to avoid spurious
- // creation/destruction around creating empty documents. At this point, we're
- // initiating a main resource load for the document, so its for real.
-
- DCHECK(document_loader_->GetFrame());
- LocalFrame& frame = *document_loader_->GetFrame();
- host_ = frame.Client()->CreateApplicationCacheHost(loader, this);
- if (!host_)
- return;
-
- const WebApplicationCacheHost* spawning_host = nullptr;
- Frame* spawning_frame = frame.Tree().Parent();
- if (!spawning_frame || !IsA<LocalFrame>(spawning_frame))
- spawning_frame = frame.Loader().Opener();
- if (!spawning_frame || !IsA<LocalFrame>(spawning_frame))
- spawning_frame = &frame;
- if (DocumentLoader* spawning_doc_loader =
- To<LocalFrame>(spawning_frame)->Loader().GetDocumentLoader()) {
- spawning_host =
- spawning_doc_loader->GetApplicationCacheHost()
- ? spawning_doc_loader->GetApplicationCacheHost()->host_.get()
- : nullptr;
- }
-
- host_->WillStartMainResourceRequest(url, method, spawning_host);
-
- // NOTE: The semantics of this method, and others in this interface, are
- // subtly different than the method names would suggest. For example, in this
- // method never returns an appcached response in the SubstituteData out
- // argument, instead we return the appcached response thru the usual resource
- // loading pipeline.
-}
-
-void ApplicationCacheHost::SelectCacheWithoutManifest() {
- if (host_)
- host_->SelectCacheWithoutManifest();
-}
-
-void ApplicationCacheHost::SelectCacheWithManifest(const KURL& manifest_url) {
- DCHECK(document_loader_);
-
- LocalFrame* frame = document_loader_->GetFrame();
- Document* document = frame->GetDocument();
- if (document->IsSandboxed(WebSandboxFlags::kOrigin)) {
- // Prevent sandboxes from establishing application caches.
- SelectCacheWithoutManifest();
- return;
- }
- if (document->IsSecureContext()) {
- UseCounter::Count(document,
- WebFeature::kApplicationCacheManifestSelectSecureOrigin);
- } else {
- Deprecation::CountDeprecation(
- document, WebFeature::kApplicationCacheManifestSelectInsecureOrigin);
- Deprecation::CountDeprecationCrossOriginIframe(
- *document, WebFeature::kApplicationCacheManifestSelectInsecureOrigin);
- HostsUsingFeatures::CountAnyWorld(
- *document, HostsUsingFeatures::Feature::
- kApplicationCacheManifestSelectInsecureHost);
- }
- if (host_ && !host_->SelectCacheWithManifest(manifest_url)) {
- // It's a foreign entry, restart the current navigation from the top of the
- // navigation algorithm. The navigation will not result in the same resource
- // being loaded, because "foreign" entries are never picked during
- // navigation. see ApplicationCacheGroup::selectCache()
- FrameLoadRequest request(document, ResourceRequest(document->Url()));
- request.SetClientRedirectReason(ClientNavigationReason::kReload);
- frame->Navigate(request, WebFrameLoadType::kReplaceCurrentItem);
- }
-}
-void ApplicationCacheHost::DidReceiveResponseForMainResource(
- const ResourceResponse& response) {
- if (host_) {
- WrappedResourceResponse wrapped(response);
- host_->DidReceiveResponseForMainResource(wrapped);
- }
+ // We defer binding to backend to avoid unnecessary binding around creating
+ // empty documents. At this point, we're initiating a main resource load for
+ // the document, so its for real.
+ BindBackend();
}
void ApplicationCacheHost::SetApplicationCache(
@@ -177,10 +138,10 @@ void ApplicationCacheHost::SetApplicationCache(
}
void ApplicationCacheHost::DetachFromDocumentLoader() {
- // Detach from the owning DocumentLoader and let go of
- // WebApplicationCacheHost.
+ // Detach from the owning DocumentLoader and close mojo pipes.
SetApplicationCache(nullptr);
- host_.reset();
+ receiver_.reset();
+ backend_host_.reset();
document_loader_ = nullptr;
}
@@ -208,35 +169,43 @@ void ApplicationCacheHost::NotifyApplicationCache(
}
ApplicationCacheHost::CacheInfo ApplicationCacheHost::ApplicationCacheInfo() {
- if (!host_)
- return CacheInfo(NullURL(), 0, 0, 0, 0);
-
- WebApplicationCacheHost::CacheInfo web_info;
- host_->GetAssociatedCacheInfo(&web_info);
- return CacheInfo(web_info.manifest_url, web_info.creation_time,
- web_info.update_time, web_info.response_sizes,
- web_info.padding_sizes);
+ if (!backend_host_.is_bound())
+ return CacheInfo();
+
+ ApplicationCacheHost::CacheInfo cache_info;
+ GetAssociatedCacheInfo(&cache_info);
+ return cache_info;
}
const base::UnguessableToken& ApplicationCacheHost::GetHostID() const {
- if (!host_)
+ if (!backend_host_.is_bound())
return base::UnguessableToken::Null();
- return host_->GetHostID();
+ return host_id_;
}
-void ApplicationCacheHost::FillResourceList(ResourceInfoList* resources) {
- if (!host_)
+void ApplicationCacheHost::SelectCacheForSharedWorker(
+ int64_t app_cache_id,
+ base::OnceClosure completion_callback) {
+ if (!backend_host_.is_bound())
return;
- WebVector<WebApplicationCacheHost::ResourceInfo> web_resources;
- host_->GetResourceList(&web_resources);
- for (size_t i = 0; i < web_resources.size(); ++i) {
- resources->push_back(ResourceInfo(
- web_resources[i].url, web_resources[i].is_master,
- web_resources[i].is_manifest, web_resources[i].is_fallback,
- web_resources[i].is_foreign, web_resources[i].is_explicit,
- web_resources[i].response_size, web_resources[i].padding_size));
- }
+ select_cache_for_shared_worker_completion_callback_ =
+ std::move(completion_callback);
+ backend_host_->SelectCacheForSharedWorker(app_cache_id);
+}
+
+void ApplicationCacheHost::FillResourceList(
+ Vector<mojom::blink::AppCacheResourceInfo>* resources) {
+ DCHECK(resources);
+ if (!backend_host_.is_bound())
+ return;
+
+ if (!cache_info_.is_complete)
+ return;
+ Vector<mojom::blink::AppCacheResourceInfoPtr> boxed_infos;
+ backend_host_->GetResourceList(&boxed_infos);
+ for (auto& b : boxed_infos)
+ resources->emplace_back(std::move(*b));
}
void ApplicationCacheHost::StopDeferringEvents() {
@@ -280,25 +249,13 @@ void ApplicationCacheHost::DispatchDOMEvent(
}
mojom::AppCacheStatus ApplicationCacheHost::GetStatus() const {
- return host_ ? host_->GetStatus()
- : mojom::AppCacheStatus::APPCACHE_STATUS_UNCACHED;
-}
-
-bool ApplicationCacheHost::Update() {
- return host_ ? host_->StartUpdate() : false;
-}
-
-bool ApplicationCacheHost::SwapCache() {
- bool success = host_ ? host_->SwapCache() : false;
- if (success) {
- probe::UpdateApplicationCacheStatus(document_loader_->GetFrame());
- }
- return success;
+ if (!backend_host_.is_bound())
+ return mojom::AppCacheStatus::APPCACHE_STATUS_UNCACHED;
+ return status_;
}
void ApplicationCacheHost::Abort() {
- if (host_)
- host_->Abort();
+ // This is not implemented intentionally. See https://crbug.com/175063
}
bool ApplicationCacheHost::IsApplicationCacheEnabled() {
@@ -309,34 +266,160 @@ bool ApplicationCacheHost::IsApplicationCacheEnabled() {
->GetOfflineWebApplicationCacheEnabled();
}
-void ApplicationCacheHost::DidChangeCacheAssociation() {
+void ApplicationCacheHost::CacheSelected(mojom::blink::AppCacheInfoPtr info) {
+ if (!backend_host_.is_bound())
+ return;
+
+ cache_info_ = *info;
// FIXME: Prod the inspector to update its notion of what cache the page is
// using.
+ if (select_cache_for_shared_worker_completion_callback_)
+ std::move(select_cache_for_shared_worker_completion_callback_).Run();
}
-void ApplicationCacheHost::NotifyEventListener(
- mojom::AppCacheEventID event_id) {
+void ApplicationCacheHost::EventRaised(mojom::blink::AppCacheEventID event_id) {
+ if (!backend_host_.is_bound())
+ return;
+
+ DCHECK_NE(event_id,
+ mojom::blink::AppCacheEventID::
+ APPCACHE_PROGRESS_EVENT); // See OnProgressEventRaised.
+ DCHECK_NE(event_id,
+ mojom::blink::AppCacheEventID::
+ APPCACHE_ERROR_EVENT); // See OnErrorEventRaised.
+
+ // Emit logging output prior to calling out to script as we can get
+ // deleted within the script event handler.
+ const char kFormatString[] = "Application Cache %s event";
+ String message =
+ String::Format(kFormatString, kEventNames[static_cast<int>(event_id)]);
+ LogMessage(mojom::blink::ConsoleMessageLevel::kInfo, message);
+
+ switch (event_id) {
+ case mojom::blink::AppCacheEventID::APPCACHE_CHECKING_EVENT:
+ status_ = mojom::blink::AppCacheStatus::APPCACHE_STATUS_CHECKING;
+ break;
+ case mojom::blink::AppCacheEventID::APPCACHE_DOWNLOADING_EVENT:
+ status_ = mojom::blink::AppCacheStatus::APPCACHE_STATUS_DOWNLOADING;
+ break;
+ case mojom::blink::AppCacheEventID::APPCACHE_UPDATE_READY_EVENT:
+ status_ = mojom::blink::AppCacheStatus::APPCACHE_STATUS_UPDATE_READY;
+ break;
+ case mojom::blink::AppCacheEventID::APPCACHE_CACHED_EVENT:
+ case mojom::blink::AppCacheEventID::APPCACHE_NO_UPDATE_EVENT:
+ status_ = mojom::blink::AppCacheStatus::APPCACHE_STATUS_IDLE;
+ break;
+ case mojom::blink::AppCacheEventID::APPCACHE_OBSOLETE_EVENT:
+ status_ = mojom::blink::AppCacheStatus::APPCACHE_STATUS_OBSOLETE;
+ break;
+ default:
+ NOTREACHED();
+ break;
+ }
+
NotifyApplicationCache(event_id, 0, 0,
mojom::AppCacheErrorReason::APPCACHE_UNKNOWN_ERROR,
String(), 0, String());
}
-void ApplicationCacheHost::NotifyProgressEventListener(const WebURL&,
- int progress_total,
- int progress_done) {
+void ApplicationCacheHost::ProgressEventRaised(const KURL& url,
+ int num_total,
+ int num_complete) {
+ if (!backend_host_.is_bound())
+ return;
+
+ // Emit logging output prior to calling out to script as we can get
+ // deleted within the script event handler.
+ const char kFormatString[] = "Application Cache Progress event (%d of %d) %s";
+ String message = String::Format(kFormatString, num_complete, num_total,
+ url.GetString().Utf8().c_str());
+ LogMessage(mojom::blink::ConsoleMessageLevel::kInfo, message);
+ status_ = mojom::blink::AppCacheStatus::APPCACHE_STATUS_DOWNLOADING;
NotifyApplicationCache(mojom::AppCacheEventID::APPCACHE_PROGRESS_EVENT,
- progress_total, progress_done,
+ num_total, num_complete,
mojom::AppCacheErrorReason::APPCACHE_UNKNOWN_ERROR,
String(), 0, String());
}
-void ApplicationCacheHost::NotifyErrorEventListener(
- mojom::AppCacheErrorReason reason,
- const WebURL& url,
- int status,
- const WebString& message) {
- NotifyApplicationCache(mojom::AppCacheEventID::APPCACHE_ERROR_EVENT, 0, 0,
- reason, url.GetString(), status, message);
+void ApplicationCacheHost::ErrorEventRaised(
+ mojom::blink::AppCacheErrorDetailsPtr details) {
+ if (!backend_host_.is_bound())
+ return;
+
+ // Emit logging output prior to calling out to script as we can get
+ // deleted within the script event handler.
+ const char kFormatString[] = "Application Cache Error event: %s";
+ String full_message =
+ String::Format(kFormatString, details->message.Utf8().c_str());
+ LogMessage(mojom::blink::ConsoleMessageLevel::kError, full_message);
+
+ status_ = cache_info_.is_complete
+ ? mojom::blink::AppCacheStatus::APPCACHE_STATUS_IDLE
+ : mojom::blink::AppCacheStatus::APPCACHE_STATUS_UNCACHED;
+ if (details->is_cross_origin) {
+ // Don't leak detailed information to script for cross-origin resources.
+ DCHECK_EQ(mojom::blink::AppCacheErrorReason::APPCACHE_RESOURCE_ERROR,
+ details->reason);
+ NotifyApplicationCache(mojom::AppCacheEventID::APPCACHE_ERROR_EVENT, 0, 0,
+ details->reason, details->url.GetString(), 0,
+ String());
+ } else {
+ NotifyApplicationCache(mojom::AppCacheEventID::APPCACHE_ERROR_EVENT, 0, 0,
+ details->reason, details->url.GetString(),
+ details->status, details->message);
+ }
+}
+
+void ApplicationCacheHost::GetAssociatedCacheInfo(
+ ApplicationCacheHost::CacheInfo* info) {
+ if (!backend_host_.is_bound())
+ return;
+
+ info->manifest_ = cache_info_.manifest_url;
+ if (!cache_info_.is_complete)
+ return;
+ info->creation_time_ = cache_info_.creation_time.ToDoubleT();
+ info->update_time_ = cache_info_.last_update_time.ToDoubleT();
+ info->response_sizes_ = cache_info_.response_sizes;
+ info->padding_sizes_ = cache_info_.padding_sizes;
+}
+
+bool ApplicationCacheHost::BindBackend() {
+ if (!task_runner_)
+ return false;
+
+ // PlzNavigate: The browser passes the ID to be used.
+ if (!document_loader_->AppcacheHostId().is_empty())
+ host_id_ = document_loader_->AppcacheHostId();
+ else
+ host_id_ = base::UnguessableToken::Create();
+
+ mojo::PendingRemote<mojom::blink::AppCacheFrontend> frontend_remote;
+ receiver_.Bind(frontend_remote.InitWithNewPipeAndPassReceiver(),
+ task_runner_);
+
+ if (interface_broker_) {
+ interface_broker_->RegisterAppCacheHost(
+ backend_host_.BindNewPipeAndPassReceiver(std::move(task_runner_)),
+ std::move(frontend_remote), host_id_);
+ return true;
+ }
+
+ DEFINE_STATIC_LOCAL(
+ const mojo::Remote<mojom::blink::AppCacheBackend>, backend_remote, ([] {
+ mojo::Remote<mojom::blink::AppCacheBackend> result;
+ Platform::Current()->GetInterfaceProvider()->GetInterface(
+ result.BindNewPipeAndPassReceiver());
+ return result;
+ }()));
+
+ // Once we have 'WebContextInterfaceBroker', we can call this function through
+ // it like render frame.
+ // Refer to the design document, 'https://bit.ly/2GT0rZv'.
+ backend_remote->RegisterHost(
+ backend_host_.BindNewPipeAndPassReceiver(std::move(task_runner_)),
+ std::move(frontend_remote), host_id_);
+ return true;
}
void ApplicationCacheHost::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/loader/appcache/application_cache_host.h b/chromium/third_party/blink/renderer/core/loader/appcache/application_cache_host.h
index c66d1603cfb..edc2f1cd00c 100644
--- a/chromium/third_party/blink/renderer/core/loader/appcache/application_cache_host.h
+++ b/chromium/third_party/blink/renderer/core/loader/appcache/application_cache_host.h
@@ -35,26 +35,35 @@
#include "base/gtest_prod_util.h"
#include "base/macros.h"
+#include "mojo/public/cpp/bindings/receiver.h"
+#include "mojo/public/cpp/bindings/remote.h"
#include "third_party/blink/public/mojom/appcache/appcache.mojom-blink.h"
-#include "third_party/blink/public/web/web_application_cache_host_client.h"
+#include "third_party/blink/public/mojom/appcache/appcache_info.mojom-blink.h"
+#include "third_party/blink/public/mojom/devtools/console_message.mojom-blink.h"
+#include "third_party/blink/public/mojom/frame/document_interface_broker.mojom-blink.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
+#include "third_party/blink/renderer/platform/loader/fetch/resource_response.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/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
class ApplicationCache;
class DocumentLoader;
class ResourceRequest;
-class ResourceResponse;
-class WebApplicationCacheHost;
-class CORE_EXPORT ApplicationCacheHost final
+class CORE_EXPORT ApplicationCacheHost
: public GarbageCollectedFinalized<ApplicationCacheHost>,
- public WebApplicationCacheHostClient {
+ public mojom::blink::AppCacheFrontend {
public:
- explicit ApplicationCacheHost(DocumentLoader*);
+ static ApplicationCacheHost* Create(DocumentLoader* document_loader);
+ // |interface_broker| can be null for workers and |task_runner| is null for
+ // kAppCacheForNone.
+ explicit ApplicationCacheHost(
+ DocumentLoader* document_loader,
+ mojom::blink::DocumentInterfaceBroker* interface_broker,
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner);
~ApplicationCacheHost() override;
void DetachFromDocumentLoader();
@@ -72,94 +81,82 @@ class CORE_EXPORT ApplicationCacheHost final
update_time_(update_time),
response_sizes_(response_sizes),
padding_sizes_(padding_sizes) {}
+ CacheInfo() = default;
KURL manifest_;
- double creation_time_;
- double update_time_;
- int64_t response_sizes_;
- int64_t padding_sizes_;
+ double creation_time_ = 0;
+ double update_time_ = 0;
+ int64_t response_sizes_ = 0;
+ int64_t padding_sizes_ = 0;
};
- struct ResourceInfo {
- DISALLOW_NEW();
- ResourceInfo(const KURL& resource,
- bool is_master,
- bool is_manifest,
- bool is_fallback,
- bool is_foreign,
- bool is_explicit,
- int64_t response_size,
- int64_t padding_size)
- : resource_(resource),
- is_master_(is_master),
- is_manifest_(is_manifest),
- is_fallback_(is_fallback),
- is_foreign_(is_foreign),
- is_explicit_(is_explicit),
- response_size_(response_size),
- padding_size_(padding_size) {}
- KURL resource_;
- bool is_master_;
- bool is_manifest_;
- bool is_fallback_;
- bool is_foreign_;
- bool is_explicit_;
- int64_t response_size_;
- int64_t padding_size_;
- };
-
- typedef Vector<ResourceInfo> ResourceInfoList;
-
- void SelectCacheWithoutManifest();
- void SelectCacheWithManifest(const KURL& manifest_url);
-
- // Annotate request for ApplicationCache. This internally calls
- // willStartLoadingMainResource if it's for frame resource or
- // willStartLoadingResource for subresource requests.
+ // Annotate request for ApplicationCache.
void WillStartLoading(ResourceRequest&);
- void WillStartLoadingMainResource(DocumentLoader*,
- const KURL&,
- const String& method);
-
- void DidReceiveResponseForMainResource(const ResourceResponse&);
- void MainResourceDataReceived(const char* data, size_t length);
- mojom::AppCacheStatus GetStatus() const;
- bool Update();
- bool SwapCache();
+ mojom::blink::AppCacheStatus GetStatus() const;
+ virtual bool Update() { return false; }
+ virtual bool SwapCache() { return false; }
void Abort();
void SetApplicationCache(ApplicationCache*);
- void NotifyApplicationCache(mojom::AppCacheEventID,
- int progress_total,
- int progress_done,
- mojom::AppCacheErrorReason,
- const String& error_url,
- int error_status,
- const String& error_message);
void
StopDeferringEvents(); // Also raises the events that have been queued up.
- void FillResourceList(ResourceInfoList*);
+ void FillResourceList(Vector<mojom::blink::AppCacheResourceInfo>*);
CacheInfo ApplicationCacheInfo();
const base::UnguessableToken& GetHostID() const;
+ void SelectCacheForSharedWorker(int64_t app_cache_id,
+ base::OnceClosure completion_callback);
+
+ // mojom::blink::AppCacheFrontend
+ void CacheSelected(mojom::blink::AppCacheInfoPtr info) override;
+ void EventRaised(mojom::blink::AppCacheEventID event_id) override;
+ void ProgressEventRaised(const KURL& url,
+ int32_t num_total,
+ int32_t num_complete) override;
+ void ErrorEventRaised(mojom::blink::AppCacheErrorDetailsPtr details) override;
+ void LogMessage(mojom::blink::ConsoleMessageLevel log_level,
+ const String& message) override {}
+ void SetSubresourceFactory(
+ network::mojom::blink::URLLoaderFactoryPtr url_loader_factory) override {}
+
+ // TODO(nhiroki): Move these virtual functions into
+ // ApplicationCacheHostForFrame after making DocumentLoader own only
+ // ApplicationCacheHostForFrame (not own ApplicationCacheHostForSharedWorker).
+ virtual void WillStartLoadingMainResource(DocumentLoader* loader,
+ const KURL& url,
+ const String& method);
+ virtual void SelectCacheWithoutManifest() {}
+ virtual void SelectCacheWithManifest(const KURL& manifest_url) {}
+ virtual void DidReceiveResponseForMainResource(const ResourceResponse&) {}
+ virtual void Trace(blink::Visitor*);
+
+ protected:
+ DocumentLoader* GetDocumentLoader() const { return document_loader_; }
- void Trace(blink::Visitor*);
+ mojo::Remote<mojom::blink::AppCacheHost> backend_host_;
+ mojom::blink::AppCacheStatus status_ =
+ mojom::blink::AppCacheStatus::APPCACHE_STATUS_UNCACHED;
private:
- // WebApplicationCacheHostClient implementation
- void DidChangeCacheAssociation() final;
- void NotifyEventListener(mojom::AppCacheEventID) final;
- void NotifyProgressEventListener(const WebURL&,
- int progress_total,
- int progress_done) final;
- void NotifyErrorEventListener(mojom::AppCacheErrorReason,
- const WebURL&,
- int status,
- const WebString& message) final;
+ void NotifyApplicationCache(mojom::AppCacheEventID,
+ int progress_total,
+ int progress_done,
+ mojom::AppCacheErrorReason,
+ const String& error_url,
+ int error_status,
+ const String& error_message);
+ void GetAssociatedCacheInfo(CacheInfo* info);
bool IsApplicationCacheEnabled();
- DocumentLoader* GetDocumentLoader() const { return document_loader_; }
+ bool BindBackend();
+ void DispatchDOMEvent(mojom::AppCacheEventID,
+ int progress_total,
+ int progress_done,
+ mojom::AppCacheErrorReason,
+ const String& error_url,
+ int error_status,
+ const String& error_message);
struct DeferredEvent {
mojom::AppCacheEventID event_id;
@@ -185,20 +182,21 @@ class CORE_EXPORT ApplicationCacheHost final
error_message(error_message) {}
};
- WeakMember<ApplicationCache> dom_application_cache_;
- Member<DocumentLoader> document_loader_;
- bool defers_events_; // Events are deferred until after document onload.
- Vector<DeferredEvent> deferred_events_;
+ WeakMember<ApplicationCache> dom_application_cache_ = nullptr;
- void DispatchDOMEvent(mojom::AppCacheEventID,
- int progress_total,
- int progress_done,
- mojom::AppCacheErrorReason,
- const String& error_url,
- int error_status,
- const String& error_message);
+ // TODO(https://crbug.com/982996): Move this to ApplicationCacheHostForFrame.
+ Member<DocumentLoader> document_loader_;
- std::unique_ptr<WebApplicationCacheHost> host_;
+ bool defers_events_ =
+ true; // Events are deferred until after document onload.
+ Vector<DeferredEvent> deferred_events_;
+ mojo::Receiver<mojom::blink::AppCacheFrontend> receiver_{this};
+ base::UnguessableToken host_id_;
+ mojom::blink::AppCacheInfo cache_info_;
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
+ mojom::blink::DocumentInterfaceBroker* interface_broker_;
+ // Invoked when CacheSelected() is called.
+ base::OnceClosure select_cache_for_shared_worker_completion_callback_;
FRIEND_TEST_ALL_PREFIXES(DocumentTest, SandboxDisablesAppCache);
diff --git a/chromium/third_party/blink/renderer/core/loader/appcache/application_cache_host_for_frame.cc b/chromium/third_party/blink/renderer/core/loader/appcache/application_cache_host_for_frame.cc
new file mode 100644
index 00000000000..5b1123ef8f5
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/loader/appcache/application_cache_host_for_frame.cc
@@ -0,0 +1,254 @@
+// Copyright 2012 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/loader/appcache/application_cache_host_for_frame.h"
+
+#include "third_party/blink/public/common/loader/url_loader_factory_bundle.h"
+#include "third_party/blink/public/platform/platform.h"
+#include "third_party/blink/renderer/core/dom/document.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/page/page.h"
+#include "third_party/blink/renderer/core/probe/core_probes.h"
+#include "third_party/blink/renderer/platform/web_test_support.h"
+
+namespace blink {
+
+namespace {
+
+const char kHttpGETMethod[] = "GET";
+
+KURL ClearUrlRef(const KURL& input_url) {
+ KURL url(input_url);
+ if (!url.HasFragmentIdentifier())
+ return url;
+ url.RemoveFragmentIdentifier();
+ return url;
+}
+
+void RestartNavigation(LocalFrame* frame) {
+ Document* document = frame->GetDocument();
+ FrameLoadRequest request(document, ResourceRequest(document->Url()));
+ request.SetClientRedirectReason(ClientNavigationReason::kReload);
+ frame->Navigate(request, WebFrameLoadType::kReplaceCurrentItem);
+}
+
+} // namespace
+
+ApplicationCacheHostForFrame::ApplicationCacheHostForFrame(
+ DocumentLoader* document_loader,
+ mojom::blink::DocumentInterfaceBroker* interface_broker,
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner)
+ : ApplicationCacheHost(document_loader,
+ interface_broker,
+ std::move(task_runner)),
+ local_frame_(document_loader->GetFrame()) {}
+
+bool ApplicationCacheHostForFrame::Update() {
+ if (!backend_host_.is_bound())
+ return false;
+
+ bool result = false;
+ backend_host_->StartUpdate(&result);
+ if (!result)
+ return false;
+ if (status_ == mojom::blink::AppCacheStatus::APPCACHE_STATUS_IDLE ||
+ status_ == mojom::blink::AppCacheStatus::APPCACHE_STATUS_UPDATE_READY) {
+ status_ = mojom::blink::AppCacheStatus::APPCACHE_STATUS_CHECKING;
+ } else {
+ status_ = mojom::blink::AppCacheStatus::APPCACHE_STATUS_UNCACHED;
+ backend_host_->GetStatus(&status_);
+ }
+ return true;
+}
+
+bool ApplicationCacheHostForFrame::SwapCache() {
+ if (!backend_host_.is_bound())
+ return false;
+
+ bool success = false;
+ backend_host_->SwapCache(&success);
+ if (!success)
+ return false;
+ backend_host_->GetStatus(&status_);
+ probe::UpdateApplicationCacheStatus(GetDocumentLoader()->GetFrame());
+ return true;
+}
+
+void ApplicationCacheHostForFrame::LogMessage(
+ mojom::blink::ConsoleMessageLevel log_level,
+ const String& message) {
+ if (WebTestSupport::IsRunningWebTest())
+ return;
+
+ if (!local_frame_ || !local_frame_->IsMainFrame())
+ return;
+
+ Frame* main_frame = local_frame_->GetPage()->MainFrame();
+ if (!main_frame->IsLocalFrame())
+ return;
+ // TODO(michaeln): Make app cache host per-frame and correctly report to the
+ // involved frame.
+ auto* local_frame = DynamicTo<LocalFrame>(main_frame);
+ local_frame->GetDocument()->AddConsoleMessage(ConsoleMessage::Create(
+ mojom::ConsoleMessageSource::kOther, log_level, message));
+}
+
+void ApplicationCacheHostForFrame::SetSubresourceFactory(
+ network::mojom::blink::URLLoaderFactoryPtr url_loader_factory) {
+ auto pending_factories = std::make_unique<URLLoaderFactoryBundleInfo>();
+ pending_factories->pending_appcache_factory() =
+ mojo::PendingRemote<network::mojom::URLLoaderFactory>(
+ url_loader_factory.PassInterface().PassHandle(),
+ url_loader_factory.version());
+ local_frame_->Client()->UpdateSubresourceFactory(
+ std::move(pending_factories));
+}
+
+void ApplicationCacheHostForFrame::WillStartLoadingMainResource(
+ DocumentLoader* loader,
+ const KURL& url,
+ const String& method) {
+ ApplicationCacheHost::WillStartLoadingMainResource(loader, url, method);
+ if (!backend_host_.is_bound())
+ return;
+
+ original_main_resource_url_ = ClearUrlRef(url);
+ is_get_method_ = (method == kHttpGETMethod);
+ DCHECK(method == method.UpperASCII());
+
+ const ApplicationCacheHost* spawning_host = nullptr;
+
+ DCHECK(loader->GetFrame());
+ LocalFrame* frame = loader->GetFrame();
+ Frame* spawning_frame = frame->Tree().Parent();
+ if (!spawning_frame || !IsA<LocalFrame>(spawning_frame))
+ spawning_frame = frame->Loader().Opener();
+ if (!spawning_frame || !IsA<LocalFrame>(spawning_frame))
+ spawning_frame = frame;
+ if (DocumentLoader* spawning_doc_loader =
+ To<LocalFrame>(spawning_frame)->Loader().GetDocumentLoader()) {
+ spawning_host = spawning_doc_loader->GetApplicationCacheHost();
+ }
+
+ if (spawning_host && (spawning_host != this) &&
+ (spawning_host->GetStatus() !=
+ mojom::blink::AppCacheStatus::APPCACHE_STATUS_UNCACHED)) {
+ backend_host_->SetSpawningHostId(spawning_host->GetHostID());
+ }
+}
+
+void ApplicationCacheHostForFrame::SelectCacheWithoutManifest() {
+ if (!backend_host_.is_bound())
+ return;
+
+ if (was_select_cache_called_)
+ return;
+ was_select_cache_called_ = true;
+
+ status_ =
+ (document_response_.AppCacheID() == mojom::blink::kAppCacheNoCacheId)
+ ? mojom::blink::AppCacheStatus::APPCACHE_STATUS_UNCACHED
+ : mojom::blink::AppCacheStatus::APPCACHE_STATUS_CHECKING;
+ is_new_master_entry_ = OLD_ENTRY;
+ backend_host_->SelectCache(document_url_, document_response_.AppCacheID(),
+ KURL());
+}
+
+void ApplicationCacheHostForFrame::SelectCacheWithManifest(
+ const KURL& manifest_url) {
+ LocalFrame* frame = GetDocumentLoader()->GetFrame();
+ Document* document = frame->GetDocument();
+ if (document->IsSandboxed(WebSandboxFlags::kOrigin)) {
+ // Prevent sandboxes from establishing application caches.
+ SelectCacheWithoutManifest();
+ return;
+ }
+ if (document->IsSecureContext()) {
+ UseCounter::Count(document,
+ WebFeature::kApplicationCacheManifestSelectSecureOrigin);
+ } else {
+ Deprecation::CountDeprecation(
+ document, WebFeature::kApplicationCacheManifestSelectInsecureOrigin);
+ Deprecation::CountDeprecationCrossOriginIframe(
+ *document, WebFeature::kApplicationCacheManifestSelectInsecureOrigin);
+ HostsUsingFeatures::CountAnyWorld(
+ *document, HostsUsingFeatures::Feature::
+ kApplicationCacheManifestSelectInsecureHost);
+ }
+
+ if (!backend_host_.is_bound())
+ return;
+
+ if (was_select_cache_called_)
+ return;
+ was_select_cache_called_ = true;
+
+ KURL manifest_kurl(ClearUrlRef(manifest_url));
+
+ // 6.9.6 The application cache selection algorithm
+ // Check for new 'master' entries.
+ if (document_response_.AppCacheID() == mojom::blink::kAppCacheNoCacheId) {
+ if (is_scheme_supported_ && is_get_method_ &&
+ SecurityOrigin::AreSameSchemeHostPort(manifest_kurl, document_url_)) {
+ status_ = mojom::blink::AppCacheStatus::APPCACHE_STATUS_CHECKING;
+ is_new_master_entry_ = NEW_ENTRY;
+ } else {
+ status_ = mojom::blink::AppCacheStatus::APPCACHE_STATUS_UNCACHED;
+ is_new_master_entry_ = OLD_ENTRY;
+ manifest_kurl = KURL();
+ }
+ backend_host_->SelectCache(document_url_, mojom::blink::kAppCacheNoCacheId,
+ manifest_kurl);
+ return;
+ }
+
+ DCHECK_EQ(OLD_ENTRY, is_new_master_entry_);
+
+ // 6.9.6 The application cache selection algorithm
+ // Check for 'foreign' entries.
+ KURL document_manifest_kurl(document_response_.AppCacheManifestURL());
+ if (document_manifest_kurl != manifest_kurl) {
+ backend_host_->MarkAsForeignEntry(document_url_,
+ document_response_.AppCacheID());
+ status_ = mojom::blink::AppCacheStatus::APPCACHE_STATUS_UNCACHED;
+ // It's a foreign entry, restart the current navigation from the top of the
+ // navigation algorithm. The navigation will not result in the same resource
+ // being loaded, because "foreign" entries are never picked during
+ // navigation. see ApplicationCacheGroup::selectCache()
+ RestartNavigation(local_frame_); // the navigation will be restarted
+ return;
+ }
+
+ status_ = mojom::blink::AppCacheStatus::APPCACHE_STATUS_CHECKING;
+
+ // It's a 'master' entry that's already in the cache.
+ backend_host_->SelectCache(document_url_, document_response_.AppCacheID(),
+ manifest_kurl);
+}
+
+void ApplicationCacheHostForFrame::DidReceiveResponseForMainResource(
+ const ResourceResponse& response) {
+ if (!backend_host_.is_bound())
+ return;
+
+ document_response_ = response;
+ document_url_ = ClearUrlRef(document_response_.CurrentRequestUrl());
+ if (document_url_ != original_main_resource_url_)
+ is_get_method_ = true; // A redirect was involved.
+ original_main_resource_url_ = KURL();
+
+ is_scheme_supported_ =
+ Platform::Current()->IsURLSupportedForAppCache(document_url_);
+ if ((document_response_.AppCacheID() != mojom::blink::kAppCacheNoCacheId) ||
+ !is_scheme_supported_ || !is_get_method_)
+ is_new_master_entry_ = OLD_ENTRY;
+}
+
+void ApplicationCacheHostForFrame::Trace(blink::Visitor* visitor) {
+ visitor->Trace(local_frame_);
+ ApplicationCacheHost::Trace(visitor);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/loader/appcache/application_cache_host_for_frame.h b/chromium/third_party/blink/renderer/core/loader/appcache/application_cache_host_for_frame.h
new file mode 100644
index 00000000000..79188428345
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/loader/appcache/application_cache_host_for_frame.h
@@ -0,0 +1,55 @@
+// Copyright 2012 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_APPCACHE_APPLICATION_CACHE_HOST_FOR_FRAME_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_APPCACHE_APPLICATION_CACHE_HOST_FOR_FRAME_H_
+
+#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/loader/appcache/application_cache_host.h"
+
+namespace blink {
+
+class LocalFrame;
+
+class CORE_EXPORT ApplicationCacheHostForFrame : public ApplicationCacheHost {
+ public:
+ ApplicationCacheHostForFrame(
+ DocumentLoader* document_loader,
+ mojom::blink::DocumentInterfaceBroker* interface_broker,
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner);
+
+ // ApplicationCacheHost:
+ bool Update() override;
+ bool SwapCache() override;
+ void LogMessage(mojom::blink::ConsoleMessageLevel log_level,
+ const String& message) override;
+
+ void SetSubresourceFactory(
+ network::mojom::blink::URLLoaderFactoryPtr url_loader_factory) override;
+
+ void WillStartLoadingMainResource(DocumentLoader* loader,
+ const KURL& url,
+ const String& method) override;
+ void SelectCacheWithoutManifest() override;
+ void SelectCacheWithManifest(const KURL& manifest_url) override;
+ void DidReceiveResponseForMainResource(const ResourceResponse&) override;
+
+ void Trace(blink::Visitor*) override;
+
+ private:
+ enum IsNewMasterEntry { MAYBE_NEW_ENTRY, NEW_ENTRY, OLD_ENTRY };
+
+ Member<LocalFrame> local_frame_;
+ bool is_get_method_ = false;
+ bool was_select_cache_called_ = false;
+ IsNewMasterEntry is_new_master_entry_ = MAYBE_NEW_ENTRY;
+ bool is_scheme_supported_ = false;
+ ResourceResponse document_response_;
+ KURL document_url_;
+ KURL original_main_resource_url_; // Used to detect redirection.
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_APPCACHE_APPLICATION_CACHE_HOST_FOR_FRAME_H_
diff --git a/chromium/third_party/blink/renderer/core/loader/appcache/application_cache_host_for_shared_worker.cc b/chromium/third_party/blink/renderer/core/loader/appcache/application_cache_host_for_shared_worker.cc
new file mode 100644
index 00000000000..291fe2f6955
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/loader/appcache/application_cache_host_for_shared_worker.cc
@@ -0,0 +1,55 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/loader/appcache/application_cache_host_for_shared_worker.h"
+
+namespace blink {
+
+ApplicationCacheHostForSharedWorker::ApplicationCacheHostForSharedWorker(
+ DocumentLoader* document_loader,
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner)
+ : ApplicationCacheHost(document_loader,
+ nullptr, /* interface_broker */
+ std::move(task_runner)) {}
+
+ApplicationCacheHostForSharedWorker::~ApplicationCacheHostForSharedWorker() =
+ default;
+
+bool ApplicationCacheHostForSharedWorker::Update() {
+ // ApplicationCacheHost::Update() is called from JavaScript's
+ // applicationCache.update() that is not exposed to workers.
+ // https://html.spec.whatwg.org/C/#application-cache-api
+ NOTREACHED();
+ return false;
+}
+
+bool ApplicationCacheHostForSharedWorker::SwapCache() {
+ // ApplicationCacheHost::SwapCache() is called from JavaScript's
+ // applicationCache.swapCache() that is not exposed to workers.
+ // https://html.spec.whatwg.org/C/#application-cache-api
+ NOTREACHED();
+ return false;
+}
+
+void ApplicationCacheHostForSharedWorker::LogMessage(
+ mojom::blink::ConsoleMessageLevel log_level,
+ const String& message) {}
+
+void ApplicationCacheHostForSharedWorker::SetSubresourceFactory(
+ network::mojom::blink::URLLoaderFactoryPtr url_loader_factory) {}
+
+void ApplicationCacheHostForSharedWorker::SelectCacheWithoutManifest() {
+ // This can be called during WorkerShadowPage initialization.
+ // TODO(https://crbug.com/538751): Add NOTREACHED() here after
+ // WorkerShadowPage is removed.
+}
+
+void ApplicationCacheHostForSharedWorker::SelectCacheWithManifest(
+ const KURL& manifest_url) {
+ // This can be called during WorkerShadowPage initialization.
+ // TODO(https://crbug.com/538751): Add NOTREACHED() here after
+ // WorkerShadowPage is removed.
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/loader/appcache/application_cache_host_for_shared_worker.h b/chromium/third_party/blink/renderer/core/loader/appcache/application_cache_host_for_shared_worker.h
new file mode 100644
index 00000000000..4cdc57f38e2
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/loader/appcache/application_cache_host_for_shared_worker.h
@@ -0,0 +1,32 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_APPCACHE_APPLICATION_CACHE_HOST_FOR_SHARED_WORKER_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_APPCACHE_APPLICATION_CACHE_HOST_FOR_SHARED_WORKER_H_
+
+#include "third_party/blink/renderer/core/loader/appcache/application_cache_host.h"
+
+namespace blink {
+
+class ApplicationCacheHostForSharedWorker final : public ApplicationCacheHost {
+ public:
+ ApplicationCacheHostForSharedWorker(
+ DocumentLoader* document_loader,
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner);
+ ~ApplicationCacheHostForSharedWorker() override;
+
+ // ApplicationCacheHost:
+ bool Update() override;
+ bool SwapCache() override;
+ void LogMessage(mojom::blink::ConsoleMessageLevel log_level,
+ const String& message) override;
+ void SetSubresourceFactory(
+ network::mojom::blink::URLLoaderFactoryPtr url_loader_factory) override;
+ void SelectCacheWithoutManifest() override;
+ void SelectCacheWithManifest(const KURL& manifest_url) override;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_APPCACHE_APPLICATION_CACHE_HOST_FOR_SHARED_WORKER_H_
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 fe107dca934..7917b62f5c7 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
@@ -132,12 +132,12 @@ BaseFetchContext::CanRequestInternal(
scoped_refptr<const SecurityOrigin> origin =
resource_request.RequestorOrigin();
- const auto request_mode = resource_request.GetFetchRequestMode();
+ const auto request_mode = resource_request.GetMode();
// On navigation cases, Context().GetSecurityOrigin() may return nullptr, so
// the request's origin may be nullptr.
// TODO(yhirano): Figure out if it's actually fine.
- DCHECK(request_mode == network::mojom::FetchRequestMode::kNavigate || origin);
- if (request_mode != network::mojom::FetchRequestMode::kNavigate &&
+ DCHECK(request_mode == network::mojom::RequestMode::kNavigate || origin);
+ if (request_mode != network::mojom::RequestMode::kNavigate &&
!origin->CanDisplay(url)) {
if (reporting_policy == SecurityViolationReportingPolicy::kReport) {
AddConsoleMessage(ConsoleMessage::Create(
@@ -150,7 +150,7 @@ BaseFetchContext::CanRequestInternal(
return ResourceRequestBlockedReason::kOther;
}
- if (request_mode == network::mojom::FetchRequestMode::kSameOrigin &&
+ if (request_mode == network::mojom::RequestMode::kSameOrigin &&
cors::CalculateCorsFlag(url, origin.get(), request_mode)) {
PrintAccessDeniedMessage(url);
return ResourceRequestBlockedReason::kOrigin;
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 de0334694e6..1f3fc31ece6 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,7 +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 "services/network/public/mojom/referrer_policy.mojom-blink.h"
#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"
@@ -51,6 +51,8 @@ class CORE_EXPORT BaseFetchContext : public FetchContext {
return *fetcher_properties_;
}
+ virtual void CountUsage(mojom::WebFeature) const = 0;
+ virtual void CountDeprecation(mojom::WebFeature) const = 0;
virtual KURL GetSiteForCookies() const = 0;
// Returns the origin of the top frame in the document.
diff --git a/chromium/third_party/blink/renderer/core/loader/cookie_jar.cc b/chromium/third_party/blink/renderer/core/loader/cookie_jar.cc
index b8fb8ff1d8f..2445b749b3c 100644
--- a/chromium/third_party/blink/renderer/core/loader/cookie_jar.cc
+++ b/chromium/third_party/blink/renderer/core/loader/cookie_jar.cc
@@ -1,76 +1,59 @@
-/*
- * 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.
- */
+// Copyright (c) 2010 The Chromium Authors. 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/cookie_jar.h"
-#include "third_party/blink/public/platform/platform.h"
-#include "third_party/blink/public/platform/web_cookie_jar.h"
-#include "third_party/blink/public/platform/web_url.h"
+#include "services/service_manager/public/cpp/interface_provider.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_client.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
+#include "third_party/blink/renderer/platform/weborigin/kurl.h"
namespace blink {
-static WebCookieJar* ToCookieJar(const Document* document) {
- if (!document || !document->GetFrame())
- return nullptr;
- return document->GetFrame()->Client()->CookieJar();
+CookieJar::CookieJar(blink::Document* document) : document_(document) {}
+
+CookieJar::~CookieJar() = default;
+
+void CookieJar::SetCookie(const String& value) {
+ KURL cookie_url = document_->CookieURL();
+ if (cookie_url.IsEmpty())
+ return;
+
+ RequestRestrictedCookieManagerIfNeeded();
+ SCOPED_BLINK_UMA_HISTOGRAM_TIMER("Blink.CookieJar.SyncCookiesSetTime");
+ backend_->SetCookieFromString(cookie_url, document_->SiteForCookies(), value);
}
-String Cookies(const Document* document, const KURL& url) {
- WebCookieJar* cookie_jar = ToCookieJar(document);
- if (!cookie_jar)
+String CookieJar::Cookies() {
+ KURL cookie_url = document_->CookieURL();
+ if (cookie_url.IsEmpty())
return String();
SCOPED_BLINK_UMA_HISTOGRAM_TIMER("Blink.CookieJar.SyncCookiesTime");
- return cookie_jar->Cookies(url, document->SiteForCookies());
+ RequestRestrictedCookieManagerIfNeeded();
+ String value;
+ backend_->GetCookiesString(cookie_url, document_->SiteForCookies(), &value);
+ return value;
}
-void SetCookies(Document* document,
- const KURL& url,
- const String& cookie_string) {
- WebCookieJar* cookie_jar = ToCookieJar(document);
- if (!cookie_jar)
- return;
- SCOPED_BLINK_UMA_HISTOGRAM_TIMER("Blink.CookieJar.SyncCookiesSetTime");
- cookie_jar->SetCookie(url, document->SiteForCookies(), cookie_string);
+bool CookieJar::CookiesEnabled() {
+ KURL cookie_url = document_->CookieURL();
+ if (cookie_url.IsEmpty())
+ return false;
+
+ RequestRestrictedCookieManagerIfNeeded();
+ bool cookies_enabled = false;
+ backend_->CookiesEnabledFor(cookie_url, document_->SiteForCookies(),
+ &cookies_enabled);
+ return cookies_enabled;
}
-bool CookiesEnabled(const Document* document) {
- WebCookieJar* cookie_jar = ToCookieJar(document);
- if (!cookie_jar)
- return false;
- return cookie_jar->CookiesEnabled(document->CookieURL(),
- document->SiteForCookies());
+void CookieJar::RequestRestrictedCookieManagerIfNeeded() {
+ if (!backend_.is_bound() || backend_.encountered_error()) {
+ document_->GetInterfaceProvider()->GetInterface(
+ mojo::MakeRequest(&backend_));
+ }
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/loader/cookie_jar.h b/chromium/third_party/blink/renderer/core/loader/cookie_jar.h
index ea658d18184..bd2fd5ad306 100644
--- a/chromium/third_party/blink/renderer/core/loader/cookie_jar.h
+++ b/chromium/third_party/blink/renderer/core/loader/cookie_jar.h
@@ -1,43 +1,34 @@
-/*
- * Copyright (C) 2003, 2006, 2008, 2012 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.
- */
+// Copyright (c) 2012 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_COOKIE_JAR_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_COOKIE_JAR_H_
-#include "third_party/blink/renderer/platform/wtf/forward.h"
+#include "services/network/public/mojom/restricted_cookie_manager.mojom-blink.h"
+
+#include "third_party/blink/renderer/platform/heap/persistent.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
-
class Document;
-class KURL;
-String Cookies(const Document*, const KURL&);
-void SetCookies(Document*, const KURL&, const String& cookie_string);
-bool CookiesEnabled(const Document*);
+class CookieJar {
+ public:
+ explicit CookieJar(blink::Document* document);
+ ~CookieJar();
+
+ void SetCookie(const String& value);
+ String Cookies();
+ bool CookiesEnabled();
+
+ private:
+ void RequestRestrictedCookieManagerIfNeeded();
+
+ network::mojom::blink::RestrictedCookieManagerPtr backend_;
+ WeakPersistent<blink::Document> document_; // Document owns |this|.
+};
} // namespace blink
-#endif
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_COOKIE_JAR_H_
diff --git a/chromium/third_party/blink/renderer/core/loader/document_load_timing.cc b/chromium/third_party/blink/renderer/core/loader/document_load_timing.cc
index fdf9dba283d..2a5fee87e9b 100644
--- a/chromium/third_party/blink/renderer/core/loader/document_load_timing.cc
+++ b/chromium/third_party/blink/renderer/core/loader/document_load_timing.cc
@@ -68,23 +68,25 @@ void DocumentLoadTiming::NotifyDocumentTimingChanged() {
}
void DocumentLoadTiming::EnsureReferenceTimesSet() {
- if (reference_wall_time_.is_zero())
- reference_wall_time_ = TimeDelta::FromSecondsD(clock_->Now().ToDoubleT());
+ if (reference_wall_time_.is_zero()) {
+ reference_wall_time_ =
+ base::TimeDelta::FromSecondsD(clock_->Now().ToDoubleT());
+ }
if (reference_monotonic_time_.is_null())
reference_monotonic_time_ = tick_clock_->NowTicks();
}
-TimeDelta DocumentLoadTiming::MonotonicTimeToZeroBasedDocumentTime(
- TimeTicks monotonic_time) const {
+base::TimeDelta DocumentLoadTiming::MonotonicTimeToZeroBasedDocumentTime(
+ base::TimeTicks monotonic_time) const {
if (monotonic_time.is_null() || reference_monotonic_time_.is_null())
- return TimeDelta();
+ return base::TimeDelta();
return monotonic_time - reference_monotonic_time_;
}
-TimeDelta DocumentLoadTiming::MonotonicTimeToPseudoWallTime(
- TimeTicks monotonic_time) const {
+base::TimeDelta DocumentLoadTiming::MonotonicTimeToPseudoWallTime(
+ base::TimeTicks monotonic_time) const {
if (monotonic_time.is_null() || reference_monotonic_time_.is_null())
- return TimeDelta();
+ return base::TimeDelta();
return monotonic_time + reference_wall_time_ - reference_monotonic_time_;
}
@@ -118,7 +120,7 @@ std::unique_ptr<TracedValue> DocumentLoadTiming::GetNavigationStartTracingData()
return data;
}
-void DocumentLoadTiming::SetNavigationStart(TimeTicks navigation_start) {
+void DocumentLoadTiming::SetNavigationStart(base::TimeTicks navigation_start) {
// |m_referenceMonotonicTime| and |m_referenceWallTime| represent
// navigationStart. We must set these to the current time if they haven't
// been set yet in order to have a valid reference time in both units.
@@ -136,7 +138,7 @@ void DocumentLoadTiming::SetNavigationStart(TimeTicks navigation_start) {
NotifyDocumentTimingChanged();
}
-void DocumentLoadTiming::SetInputStart(TimeTicks input_start) {
+void DocumentLoadTiming::SetInputStart(base::TimeTicks input_start) {
input_start_ = input_start;
NotifyDocumentTimingChanged();
}
@@ -156,7 +158,7 @@ void DocumentLoadTiming::AddRedirect(const KURL& redirecting_url,
!redirected_security_origin->CanRequest(redirecting_url);
}
-void DocumentLoadTiming::SetRedirectStart(TimeTicks redirect_start) {
+void DocumentLoadTiming::SetRedirectStart(base::TimeTicks redirect_start) {
redirect_start_ = redirect_start;
TRACE_EVENT_MARK_WITH_TIMESTAMP1("blink.user_timing", "redirectStart",
redirect_start_, "frame",
@@ -164,7 +166,7 @@ void DocumentLoadTiming::SetRedirectStart(TimeTicks redirect_start) {
NotifyDocumentTimingChanged();
}
-void DocumentLoadTiming::SetRedirectEnd(TimeTicks redirect_end) {
+void DocumentLoadTiming::SetRedirectEnd(base::TimeTicks redirect_end) {
redirect_end_ = redirect_end;
TRACE_EVENT_MARK_WITH_TIMESTAMP1("blink.user_timing", "redirectEnd",
redirect_end_, "frame",
@@ -172,7 +174,7 @@ void DocumentLoadTiming::SetRedirectEnd(TimeTicks redirect_end) {
NotifyDocumentTimingChanged();
}
-void DocumentLoadTiming::MarkUnloadEventStart(TimeTicks start_time) {
+void DocumentLoadTiming::MarkUnloadEventStart(base::TimeTicks start_time) {
unload_event_start_ = start_time;
TRACE_EVENT_MARK_WITH_TIMESTAMP1("blink.user_timing", "unloadEventStart",
start_time, "frame",
@@ -180,7 +182,7 @@ void DocumentLoadTiming::MarkUnloadEventStart(TimeTicks start_time) {
NotifyDocumentTimingChanged();
}
-void DocumentLoadTiming::MarkUnloadEventEnd(TimeTicks end_time) {
+void DocumentLoadTiming::MarkUnloadEventEnd(base::TimeTicks end_time) {
unload_event_end_ = end_time;
TRACE_EVENT_MARK_WITH_TIMESTAMP1("blink.user_timing", "unloadEventEnd",
end_time, "frame", ToTraceValue(GetFrame()));
@@ -191,7 +193,7 @@ void DocumentLoadTiming::MarkFetchStart() {
SetFetchStart(tick_clock_->NowTicks());
}
-void DocumentLoadTiming::SetFetchStart(TimeTicks fetch_start) {
+void DocumentLoadTiming::SetFetchStart(base::TimeTicks fetch_start) {
fetch_start_ = fetch_start;
TRACE_EVENT_MARK_WITH_TIMESTAMP1("blink.user_timing", "fetchStart",
fetch_start_, "frame",
@@ -199,7 +201,7 @@ void DocumentLoadTiming::SetFetchStart(TimeTicks fetch_start) {
NotifyDocumentTimingChanged();
}
-void DocumentLoadTiming::SetResponseEnd(TimeTicks response_end) {
+void DocumentLoadTiming::SetResponseEnd(base::TimeTicks response_end) {
response_end_ = response_end;
TRACE_EVENT_MARK_WITH_TIMESTAMP1("blink.user_timing", "responseEnd",
response_end_, "frame",
diff --git a/chromium/third_party/blink/renderer/core/loader/document_load_timing.h b/chromium/third_party/blink/renderer/core/loader/document_load_timing.h
index 20d973c861f..4a3583a1b04 100644
--- a/chromium/third_party/blink/renderer/core/loader/document_load_timing.h
+++ b/chromium/third_party/blink/renderer/core/loader/document_load_timing.h
@@ -49,29 +49,29 @@ class CORE_EXPORT DocumentLoadTiming final {
public:
explicit DocumentLoadTiming(DocumentLoader&);
- TimeDelta MonotonicTimeToZeroBasedDocumentTime(TimeTicks) const;
- TimeDelta MonotonicTimeToPseudoWallTime(TimeTicks) const;
+ base::TimeDelta MonotonicTimeToZeroBasedDocumentTime(base::TimeTicks) const;
+ base::TimeDelta MonotonicTimeToPseudoWallTime(base::TimeTicks) const;
void MarkNavigationStart();
- void SetNavigationStart(TimeTicks);
+ void SetNavigationStart(base::TimeTicks);
- void SetInputStart(TimeTicks);
+ void SetInputStart(base::TimeTicks);
void AddRedirect(const KURL& redirecting_url, const KURL& redirected_url);
- void SetRedirectStart(TimeTicks);
- void SetRedirectEnd(TimeTicks);
+ void SetRedirectStart(base::TimeTicks);
+ void SetRedirectEnd(base::TimeTicks);
void SetRedirectCount(uint16_t value) { redirect_count_ = value; }
void SetHasCrossOriginRedirect(bool value) {
has_cross_origin_redirect_ = value;
}
- void MarkUnloadEventStart(TimeTicks);
- void MarkUnloadEventEnd(TimeTicks);
+ void MarkUnloadEventStart(base::TimeTicks);
+ void MarkUnloadEventEnd(base::TimeTicks);
void MarkFetchStart();
- void SetFetchStart(TimeTicks);
+ void SetFetchStart(base::TimeTicks);
- void SetResponseEnd(TimeTicks);
+ void SetResponseEnd(base::TimeTicks);
void MarkLoadEventStart();
void MarkLoadEventEnd();
@@ -80,23 +80,25 @@ class CORE_EXPORT DocumentLoadTiming final {
has_same_origin_as_previous_document_ = value;
}
- TimeTicks InputStart() const { return input_start_; }
- TimeTicks NavigationStart() const { return navigation_start_; }
- TimeTicks UnloadEventStart() const { return unload_event_start_; }
- TimeTicks UnloadEventEnd() const { return unload_event_end_; }
- TimeTicks RedirectStart() const { return redirect_start_; }
- TimeTicks RedirectEnd() const { return redirect_end_; }
+ base::TimeTicks InputStart() const { return input_start_; }
+ base::TimeTicks NavigationStart() const { return navigation_start_; }
+ base::TimeTicks UnloadEventStart() const { return unload_event_start_; }
+ base::TimeTicks UnloadEventEnd() const { return unload_event_end_; }
+ base::TimeTicks RedirectStart() const { return redirect_start_; }
+ base::TimeTicks RedirectEnd() const { return redirect_end_; }
uint16_t RedirectCount() const { return redirect_count_; }
- TimeTicks FetchStart() const { return fetch_start_; }
- TimeTicks ResponseEnd() const { return response_end_; }
- TimeTicks LoadEventStart() const { return load_event_start_; }
- TimeTicks LoadEventEnd() const { return load_event_end_; }
+ base::TimeTicks FetchStart() const { return fetch_start_; }
+ base::TimeTicks ResponseEnd() const { return response_end_; }
+ base::TimeTicks LoadEventStart() const { return load_event_start_; }
+ base::TimeTicks LoadEventEnd() const { return load_event_end_; }
bool HasCrossOriginRedirect() const { return has_cross_origin_redirect_; }
bool HasSameOriginAsPreviousDocument() const {
return has_same_origin_as_previous_document_;
}
- TimeTicks ReferenceMonotonicTime() const { return reference_monotonic_time_; }
+ base::TimeTicks ReferenceMonotonicTime() const {
+ return reference_monotonic_time_;
+ }
void Trace(blink::Visitor*);
@@ -110,19 +112,19 @@ class CORE_EXPORT DocumentLoadTiming final {
LocalFrame* GetFrame() const;
std::unique_ptr<TracedValue> GetNavigationStartTracingData() const;
- TimeTicks reference_monotonic_time_;
- TimeDelta reference_wall_time_;
- TimeTicks input_start_;
- TimeTicks navigation_start_;
- TimeTicks unload_event_start_;
- TimeTicks unload_event_end_;
- TimeTicks redirect_start_;
- TimeTicks redirect_end_;
+ base::TimeTicks reference_monotonic_time_;
+ base::TimeDelta reference_wall_time_;
+ base::TimeTicks input_start_;
+ base::TimeTicks navigation_start_;
+ base::TimeTicks unload_event_start_;
+ base::TimeTicks unload_event_end_;
+ base::TimeTicks redirect_start_;
+ base::TimeTicks redirect_end_;
uint16_t redirect_count_;
- TimeTicks fetch_start_;
- TimeTicks response_end_;
- TimeTicks load_event_start_;
- TimeTicks load_event_end_;
+ base::TimeTicks fetch_start_;
+ base::TimeTicks response_end_;
+ base::TimeTicks load_event_start_;
+ base::TimeTicks load_event_end_;
bool has_cross_origin_redirect_;
bool has_same_origin_as_previous_document_;
diff --git a/chromium/third_party/blink/renderer/core/loader/document_load_timing_test.cc b/chromium/third_party/blink/renderer/core/loader/document_load_timing_test.cc
index a524ad0d664..bf97e47a592 100644
--- a/chromium/third_party/blink/renderer/core/loader/document_load_timing_test.cc
+++ b/chromium/third_party/blink/renderer/core/loader/document_load_timing_test.cc
@@ -18,12 +18,13 @@ TEST_F(DocumentLoadTimingTest, ensureValidNavigationStartAfterEmbedder) {
DocumentLoadTiming timing(*(dummy_page->GetDocument().Loader()));
double delta = -1000;
- double embedder_navigation_start = CurrentTimeTicksInSeconds() + delta;
+ double embedder_navigation_start =
+ base::TimeTicks::Now().since_origin().InSecondsF() + delta;
timing.SetNavigationStart(base::TimeTicks() + base::TimeDelta::FromSecondsD(
embedder_navigation_start));
- double real_wall_time = CurrentTime();
- TimeDelta adjusted_wall_time =
+ double real_wall_time = base::Time::Now().ToDoubleT();
+ base::TimeDelta adjusted_wall_time =
timing.MonotonicTimeToPseudoWallTime(timing.NavigationStart());
EXPECT_NEAR(adjusted_wall_time.InSecondsF(), real_wall_time + delta, .001);
@@ -34,7 +35,8 @@ TEST_F(DocumentLoadTimingTest, correctTimingDeltas) {
DocumentLoadTiming timing(*(dummy_page->GetDocument().Loader()));
double navigation_start_delta = -456;
- double current_monotonic_time = CurrentTimeTicksInSeconds();
+ double current_monotonic_time =
+ base::TimeTicks::Now().since_origin().InSecondsF();
double embedder_navigation_start =
current_monotonic_time + navigation_start_delta;
@@ -44,14 +46,14 @@ TEST_F(DocumentLoadTimingTest, correctTimingDeltas) {
// Super quick load! Expect the wall time reported by this event to be
// dominated by the navigationStartDelta, but similar to currentTime().
timing.MarkLoadEventEnd();
- double real_wall_load_event_end = CurrentTime();
- TimeDelta adjusted_load_event_end =
+ double real_wall_load_event_end = base::Time::Now().ToDoubleT();
+ base::TimeDelta adjusted_load_event_end =
timing.MonotonicTimeToPseudoWallTime(timing.LoadEventEnd());
EXPECT_NEAR(adjusted_load_event_end.InSecondsF(), real_wall_load_event_end,
.001);
- TimeDelta adjusted_navigation_start =
+ base::TimeDelta adjusted_navigation_start =
timing.MonotonicTimeToPseudoWallTime(timing.NavigationStart());
EXPECT_NEAR(
(adjusted_load_event_end - adjusted_navigation_start).InSecondsF(),
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 39f97194058..89397e087af 100644
--- a/chromium/third_party/blink/renderer/core/loader/document_loader.cc
+++ b/chromium/third_party/blink/renderer/core/loader/document_loader.cc
@@ -37,7 +37,7 @@
#include "services/metrics/public/cpp/ukm_builders.h"
#include "services/metrics/public/cpp/ukm_recorder.h"
#include "third_party/blink/public/common/origin_policy/origin_policy.h"
-#include "third_party/blink/public/mojom/commit_result/commit_result.mojom-shared.h"
+#include "third_party/blink/public/mojom/commit_result/commit_result.mojom-blink.h"
#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_network_provider.h"
#include "third_party/blink/public/platform/web_url_request.h"
#include "third_party/blink/public/web/web_history_commit_type.h"
@@ -133,6 +133,7 @@ DocumentLoader::DocumentLoader(
data_buffer_(SharedBuffer::Create()),
devtools_navigation_token_(params_->devtools_navigation_token),
had_sticky_activation_(params_->is_user_activated),
+ is_browser_initiated_(params_->is_browser_initiated),
was_discarded_(params_->was_discarded),
use_counter_(),
clock_(params_->tick_clock ? params_->tick_clock
@@ -167,6 +168,7 @@ DocumentLoader::DocumentLoader(
unreachable_url_ = params_->unreachable_url;
error_code_ = params_->error_code;
previews_state_ = params_->previews_state;
+ appcache_host_id_ = params_->appcache_host_id;
WebNavigationTimings& timings = params_->navigation_timings;
if (!timings.input_start.is_null())
@@ -459,6 +461,10 @@ EncodedFormData* DocumentLoader::HttpBody() const {
return http_body_.get();
}
+const base::UnguessableToken& DocumentLoader::AppcacheHostId() const {
+ return appcache_host_id_;
+}
+
void DocumentLoader::FillNavigationParamsForErrorPage(
WebNavigationParams* params) {
params->http_method = http_method_;
@@ -543,7 +549,7 @@ void DocumentLoader::BodyDataReceived(base::span<const char> data) {
}
void DocumentLoader::BodyLoadingFinished(
- TimeTicks completion_time,
+ base::TimeTicks completion_time,
int64_t total_encoded_data_length,
int64_t total_encoded_body_length,
int64_t total_decoded_body_length,
@@ -613,7 +619,7 @@ void DocumentLoader::LoadFailed(const ResourceError& error) {
params_ = nullptr;
}
-void DocumentLoader::FinishedLoading(TimeTicks finish_time) {
+void DocumentLoader::FinishedLoading(base::TimeTicks finish_time) {
body_loader_.reset();
virtual_time_pauser_.UnpauseVirtualTime();
@@ -628,52 +634,19 @@ void DocumentLoader::FinishedLoading(TimeTicks finish_time) {
CommitData(span.data(), span.size());
}
- if (loading_mhtml_archive_) {
- ArchiveResource* main_resource = nullptr;
- if (!frame_->IsMainFrame()) {
- // Only the top-frame can load MHTML.
- frame_->Console().AddMessage(ConsoleMessage::Create(
- mojom::ConsoleMessageSource::kJavaScript,
- mojom::ConsoleMessageLevel::kError,
- "Attempted to load a multipart archive into an subframe: " +
- url_.GetString()));
- } else {
- archive_ = MHTMLArchive::Create(url_, data_buffer_);
- archive_load_result_ = archive_->LoadResult();
- if (archive_load_result_ != mojom::MHTMLLoadResult::kSuccess) {
- archive_.Clear();
- // Log if attempting to load an invalid archive resource.
- frame_->Console().AddMessage(ConsoleMessage::Create(
- mojom::ConsoleMessageSource::kJavaScript,
- mojom::ConsoleMessageLevel::kError,
- "Malformed multipart archive: " + url_.GetString()));
- } else {
- main_resource = archive_->MainResource();
- }
- }
- data_buffer_ = nullptr;
- if (main_resource) {
- // The origin is the MHTML file, we need to set the base URL to the
- // document encoded in the MHTML so relative URLs are resolved properly.
- CommitNavigation(main_resource->MimeType(), main_resource->Url());
- // CommitNavigation runs unload listeners which can detach the frame.
- if (!frame_)
- return;
- scoped_refptr<SharedBuffer> data(main_resource->Data());
- for (const auto& span : *data)
- CommitData(span.data(), span.size());
- } else {
- // Cannot parse mhtml archive - load empty document instead.
- CommitNavigation(response_.MimeType());
- }
+ if (loading_mhtml_archive_ && state_ < kCommitted) {
+ FinalizeMHTMLArchiveLoad();
}
// We should not call FinishedLoading before committing navigation,
- // except for the mhtml case, which is forcefully committed above.
- // In any way, by this point we should have already committed.
- DCHECK_GE(state_, kCommitted);
+ // except for the mhtml case. When loading an MHTML archive, the whole archive
+ // has to be validated before committing the navigation. The validation
+ // process loads the entire body of the archive, which will move the state to
+ // FinishedLoading.
+ if (!loading_mhtml_archive_)
+ DCHECK_GE(state_, kCommitted);
- TimeTicks response_end_time = finish_time;
+ base::TimeTicks response_end_time = finish_time;
if (response_end_time.is_null())
response_end_time = time_of_last_data_received_;
if (response_end_time.is_null())
@@ -693,6 +666,29 @@ void DocumentLoader::FinishedLoading(TimeTicks finish_time) {
}
}
+void DocumentLoader::FinalizeMHTMLArchiveLoad() {
+ if (!frame_->IsMainFrame()) {
+ // Only the top-frame can load MHTML.
+ frame_->Console().AddMessage(ConsoleMessage::Create(
+ mojom::ConsoleMessageSource::kJavaScript,
+ mojom::ConsoleMessageLevel::kError,
+ "Attempted to load a multipart archive into an subframe: " +
+ url_.GetString()));
+ } else {
+ archive_ = MHTMLArchive::Create(url_, data_buffer_);
+ archive_load_result_ = archive_->LoadResult();
+ if (archive_load_result_ != mojom::MHTMLLoadResult::kSuccess) {
+ archive_.Clear();
+ // Log if attempting to load an invalid archive resource.
+ frame_->Console().AddMessage(ConsoleMessage::Create(
+ mojom::ConsoleMessageSource::kJavaScript,
+ mojom::ConsoleMessageLevel::kError,
+ "Malformed multipart archive: " + url_.GetString()));
+ }
+ }
+ data_buffer_ = nullptr;
+}
+
void DocumentLoader::HandleRedirect(const KURL& current_request_url) {
// Browser process should have already checked that redirecting url is
// allowed to display content from the target origin.
@@ -733,7 +729,7 @@ bool DocumentLoader::ShouldReportTimingInfoToParent() {
ContentSecurityPolicy* DocumentLoader::CreateCSP(
const ResourceResponse& response,
- const String& origin_policy_string) {
+ const base::Optional<WebOriginPolicy>& origin_policy) {
auto* csp = MakeGarbageCollected<ContentSecurityPolicy>();
csp->SetOverrideURLForSelf(response.CurrentRequestUrl());
@@ -742,19 +738,18 @@ ContentSecurityPolicy* DocumentLoader::CreateCSP(
// Handle OriginPolicy. We can skip the entire block if the OP policies have
// already been passed down.
- if (!csp->HasPolicyFromSource(
+ if (origin_policy.has_value() &&
+ !csp->HasPolicyFromSource(
kContentSecurityPolicyHeaderSourceOriginPolicy)) {
- std::unique_ptr<OriginPolicy> origin_policy = OriginPolicy::From(
- StringUTF8Adaptor(origin_policy_string).AsStringPiece());
- if (origin_policy) {
- for (auto policy : origin_policy->GetContentSecurityPolicies()) {
- csp->DidReceiveHeader(WTF::String::FromUTF8(policy.policy.data(),
- policy.policy.length()),
- policy.report_only
- ? kContentSecurityPolicyHeaderTypeReport
- : kContentSecurityPolicyHeaderTypeEnforce,
- kContentSecurityPolicyHeaderSourceOriginPolicy);
- }
+ for (const auto& policy : origin_policy->content_security_policies) {
+ csp->DidReceiveHeader(policy, kContentSecurityPolicyHeaderTypeEnforce,
+ kContentSecurityPolicyHeaderSourceOriginPolicy);
+ }
+
+ for (const auto& policy :
+ origin_policy->content_security_policies_report_only) {
+ csp->DidReceiveHeader(policy, kContentSecurityPolicyHeaderTypeReport,
+ kContentSecurityPolicyHeaderSourceOriginPolicy);
}
}
}
@@ -820,8 +815,7 @@ void DocumentLoader::HandleResponse() {
frame_->Owner()->RenderFallbackContent(frame_);
}
-void DocumentLoader::CommitNavigation(const AtomicString& mime_type,
- const KURL& overriding_url) {
+void DocumentLoader::PrepareForNavigationCommit() {
if (state_ != kProvisional)
return;
@@ -835,10 +829,10 @@ void DocumentLoader::CommitNavigation(const AtomicString& mime_type,
}
DCHECK_EQ(state_, kProvisional);
- GetFrameLoader().CommitProvisionalLoad();
- if (!frame_)
- return;
+}
+void DocumentLoader::FinishNavigationCommit(const AtomicString& mime_type,
+ const KURL& overriding_url) {
const AtomicString& encoding = GetResponse().TextEncodingName();
// Prepare a DocumentInit before clearing the frame, because it may need to
@@ -848,7 +842,9 @@ void DocumentLoader::CommitNavigation(const AtomicString& mime_type,
// TODO(dcheng): This differs from the behavior of both IE and Firefox: the
// origin is inherited from the document that loaded the URL.
- if (Document::ShouldInheritSecurityOriginFromOwner(Url())) {
+ if (loading_url_as_javascript_) {
+ owner_document = frame_->GetDocument();
+ } else if (Document::ShouldInheritSecurityOriginFromOwner(Url())) {
Frame* owner_frame = frame_->Tree().Parent();
if (!owner_frame)
owner_frame = frame_->Loader().Opener();
@@ -860,12 +856,13 @@ void DocumentLoader::CommitNavigation(const AtomicString& mime_type,
DCHECK(frame_->GetPage());
ParserSynchronizationPolicy parsing_policy = kAllowAsynchronousParsing;
- if (!Document::ThreadedParsingEnabledForTesting())
+ if (loading_url_as_javascript_ ||
+ !Document::ThreadedParsingEnabledForTesting()) {
parsing_policy = kForceSynchronousParsing;
+ }
- InstallNewDocument(Url(), initiator_origin, owner_document,
- mime_type, encoding, InstallNewDocumentReason::kNavigation,
- parsing_policy, overriding_url);
+ InstallNewDocument(Url(), initiator_origin, owner_document, mime_type,
+ encoding, parsing_policy, overriding_url);
parser_->SetDocumentWasLoadedAsPartOfNavigation();
if (was_discarded_)
frame_->GetDocument()->SetWasDiscarded(true);
@@ -1108,24 +1105,15 @@ bool DocumentLoader::WillLoadUrlAsEmpty(const KURL& url) {
return SchemeRegistry::ShouldLoadURLSchemeAsEmptyDocument(url.Protocol());
}
-void DocumentLoader::LoadEmpty() {
- if (url_.IsEmpty() &&
- !GetFrameLoader().StateMachine()->CreatingInitialEmptyDocument()) {
- url_ = BlankURL();
- }
+void DocumentLoader::InitializeEmptyResponse() {
response_ = ResourceResponse(url_);
response_.SetMimeType("text/html");
response_.SetTextEncodingName("utf-8");
- CommitNavigation(response_.MimeType());
- // Committing can run unload handlers, which can detach this frame or
- // stop this loader.
- if (!frame_)
- return;
- FinishedLoading(clock_->NowTicks());
}
void DocumentLoader::StartLoading() {
- probe::LifecycleEvent(frame_, this, "init", CurrentTimeTicksInSeconds());
+ probe::LifecycleEvent(frame_, this, "init",
+ base::TimeTicks::Now().since_origin().InSecondsF());
StartLoadingInternal();
params_ = nullptr;
}
@@ -1135,10 +1123,16 @@ void DocumentLoader::StartLoadingInternal() {
DCHECK_EQ(state_, kNotStarted);
DCHECK(params_);
state_ = kProvisional;
- application_cache_host_ = MakeGarbageCollected<ApplicationCacheHost>(this);
+ application_cache_host_ = ApplicationCacheHost::Create(this);
+
+ if (url_.IsEmpty() &&
+ !GetFrameLoader().StateMachine()->CreatingInitialEmptyDocument()) {
+ url_ = BlankURL();
+ }
if (loading_url_as_empty_document_) {
- LoadEmpty();
+ InitializeEmptyResponse();
+ PrepareForNavigationCommit();
return;
}
@@ -1190,7 +1184,7 @@ void DocumentLoader::StartLoadingInternal() {
}
http_content_type_ = g_null_atom;
// TODO(dgozman): check whether clearing origin policy is intended behavior.
- origin_policy_ = String();
+ origin_policy_ = base::nullopt;
probe::WillSendNavigationRequest(probe::ToCoreProbeSink(GetFrame()),
main_resource_identifier_, this, url_,
http_method_, http_body_.get());
@@ -1240,11 +1234,14 @@ void DocumentLoader::StartLoadingInternal() {
// from StartLoadingBody().
body_loader_->StartLoadingBody(this, false /* use_isolated_code_cache */);
if (body_loader_) {
- // If we did not finish synchronously, load empty document instead.
- FinishedLoading(clock_->NowTicks());
+ // Finalize the load of the MHTML archive. If the load fail (ie. did not
+ // finish synchronously), |body_loader_| will be null amd the load will
+ // not be finalized. When StartLoadingResponse is called later, an empty
+ // document will be loaded instead of the MHTML archive.
+ // TODO(clamy): Simplify this code path.
+ FinalizeMHTMLArchiveLoad();
}
- // FinishedLoading call above must commit navigation for mhtml archive.
- CHECK_GE(state_, kCommitted);
+ PrepareForNavigationCommit();
return;
}
@@ -1253,9 +1250,36 @@ void DocumentLoader::StartLoadingInternal() {
if (defers_loading_)
body_loader_->SetDefersLoading(true);
- CommitNavigation(response_.MimeType());
+ PrepareForNavigationCommit();
+}
+
+void DocumentLoader::StartLoadingResponse() {
+ if (!frame_)
+ return;
+
+ ArchiveResource* main_resource =
+ loading_mhtml_archive_ && archive_ ? archive_->MainResource() : nullptr;
+ if (main_resource)
+ FinishNavigationCommit(main_resource->MimeType(), main_resource->Url());
+ else
+ FinishNavigationCommit(response_.MimeType());
+
CHECK_GE(state_, kCommitted);
+ // Finish load of MHTML archives and empty documents.
+ if (main_resource) {
+ scoped_refptr<SharedBuffer> data(main_resource->Data());
+ for (const auto& span : *data)
+ CommitData(span.data(), span.size());
+ }
+
+ if (loading_mhtml_archive_ || loading_url_as_empty_document_) {
+ // Finish the load of an empty document if the URL was meant to load as an
+ // empty document or the load of the MHTML archive failed.
+ FinishedLoading(base::TimeTicks::Now());
+ return;
+ }
+
// TODO(dgozman): why do we stop loading for media documents?
// This seems like a hack.
if (frame_ && frame_->GetDocument()->IsMediaDocument()) {
@@ -1295,11 +1319,8 @@ void DocumentLoader::StartLoadingInternal() {
void DocumentLoader::DidInstallNewDocument(Document* document) {
document->SetReadyState(Document::kLoading);
- if (content_security_policy_) {
- document->InitContentSecurityPolicy(
- content_security_policy_.Release(),
- GetFrameLoader().GetLastOriginDocumentCSP());
- }
+ if (content_security_policy_)
+ document->BindContentSecurityPolicy();
if (history_item_ && IsBackForwardLoadType(load_type_))
document->SetStateForNewFormElements(history_item_->GetDocumentState());
@@ -1397,7 +1418,7 @@ void DocumentLoader::DidCommitNavigation(
// DidObserveLoadingBehavior() must be called after DispatchDidCommitLoad() is
// called for the metrics tracking logic to handle it properly.
if (service_worker_network_provider_ &&
- service_worker_network_provider_->IsControlledByServiceWorker() ==
+ service_worker_network_provider_->GetControllerServiceWorkerMode() ==
blink::mojom::ControllerServiceWorkerMode::kControlled) {
GetLocalFrameClient().DidObserveLoadingBehavior(
kWebLoadingBehaviorServiceWorkerControlled);
@@ -1432,7 +1453,19 @@ void DocumentLoader::DidCommitNavigation(
GetLocalFrameClient().ReportLegacyTLSVersion(response_.CurrentRequestUrl());
if (!frame_->Tree().Parent()) {
ukm::builders::Net_LegacyTLSVersion(document->UkmSourceID())
+ .SetIsMainFrame(true)
+ .SetIsSubresource(false)
+ .SetIsAdResource(frame_->IsAdSubframe() || frame_->IsAdRoot())
.Record(document->UkmRecorder());
+ } else {
+ // For non-main-frame loads, we have to use the main frame's document for
+ // the UKM recorder and source ID.
+ auto& root = frame_->LocalFrameRoot();
+ ukm::builders::Net_LegacyTLSVersion(root.GetDocument()->UkmSourceID())
+ .SetIsMainFrame(false)
+ .SetIsSubresource(false)
+ .SetIsAdResource(frame_->IsAdSubframe())
+ .Record(root.GetDocument()->UkmRecorder());
}
}
}
@@ -1442,21 +1475,12 @@ void DocumentLoader::DidCommitNavigation(
// Headers go first, which means that the per-page headers override the
// origin policy features.
void MergeFeaturesFromOriginPolicy(WTF::StringBuilder& 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()) {
+ const WebOriginPolicy& origin_policy) {
+ for (const auto& policy : origin_policy.features) {
if (!feature_policy.IsEmpty()) {
feature_policy.Append(',');
}
- feature_policy.Append(
- WTF::String::FromUTF8(policy.data(), policy.length()));
+ feature_policy.Append(policy);
}
}
@@ -1466,27 +1490,40 @@ void DocumentLoader::InstallNewDocument(
Document* owner_document,
const AtomicString& mime_type,
const AtomicString& encoding,
- InstallNewDocumentReason reason,
ParserSynchronizationPolicy parsing_policy,
const KURL& overriding_url) {
DCHECK(!frame_->GetDocument() || !frame_->GetDocument()->IsActive());
DCHECK_EQ(frame_->Tree().ChildCount(), 0u);
- DocumentInit init = DocumentInit::Create()
- .WithDocumentLoader(this)
- .WithURL(url)
- .WithOwnerDocument(owner_document)
- .WithInitiatorOrigin(initiator_origin)
- .WithOriginToCommit(origin_to_commit_)
- .WithSrcdocDocument(loading_srcdoc_)
- .WithNewRegistrationContext();
-
- ContentSecurityPolicy* csp = content_security_policy_.Get();
- // The only case where there should be nullptr content_security_policy_
- // besides empty loads is a javascript: url, which inherits its CSP from the
- // document in which it was executed.
- if (!csp && !loading_url_as_empty_document_)
- csp = frame_->GetDocument()->GetContentSecurityPolicy();
+ // 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().
+ WTF::StringBuilder feature_policy;
+ feature_policy.Append(response_.HttpHeaderField(http_names::kFeaturePolicy));
+ if (origin_policy_.has_value()) {
+ MergeFeaturesFromOriginPolicy(feature_policy, origin_policy_.value());
+ }
+
+ DocumentInit init =
+ DocumentInit::Create()
+ .WithDocumentLoader(this)
+ .WithURL(url)
+ .WithOwnerDocument(owner_document)
+ .WithInitiatorOrigin(initiator_origin)
+ .WithOriginToCommit(origin_to_commit_)
+ .WithSrcdocDocument(loading_srcdoc_)
+ .WithNewRegistrationContext()
+ .WithFeaturePolicyHeader(feature_policy.ToString())
+ .WithOriginTrialsHeader(
+ response_.HttpHeaderField(http_names::kOriginTrial))
+ .WithContentSecurityPolicy(content_security_policy_.Get());
+
+ // A javascript: url inherits CSP from the document in which it was
+ // executed.
+ ContentSecurityPolicy* csp =
+ loading_url_as_javascript_
+ ? frame_->GetDocument()->GetContentSecurityPolicy()
+ : content_security_policy_.Get();
GlobalObjectReusePolicy global_object_reuse_policy =
GetFrameLoader().ShouldReuseDefaultView(init.GetDocumentOrigin(), csp)
? GlobalObjectReusePolicy::kUseExisting
@@ -1510,10 +1547,13 @@ void DocumentLoader::InstallNewDocument(
// commits. To make that happen, we "securely transition" the existing
// LocalDOMWindow to the Document that results from the network load. See also
// Document::IsSecureTransitionTo.
- if (global_object_reuse_policy != GlobalObjectReusePolicy::kUseExisting)
+ if (global_object_reuse_policy != GlobalObjectReusePolicy::kUseExisting) {
+ if (frame_->GetDocument())
+ frame_->GetDocument()->RemoveAllEventListenersRecursively();
frame_->SetDOMWindow(MakeGarbageCollected<LocalDOMWindow>(*frame_));
+ }
- if (reason == InstallNewDocumentReason::kNavigation)
+ if (!loading_url_as_javascript_)
WillCommitNavigation();
Document* document =
@@ -1555,7 +1595,7 @@ void DocumentLoader::InstallNewDocument(
// This must be called before the document is opened, otherwise HTML parser
// will use stale values from HTMLParserOption.
- if (reason == InstallNewDocumentReason::kNavigation)
+ if (!loading_url_as_javascript_)
DidCommitNavigation(global_object_reuse_policy);
// Initializing origin trials might force window proxy initialization,
@@ -1565,7 +1605,7 @@ void DocumentLoader::InstallNewDocument(
if (GetFrameLoader().StateMachine()->CommittedFirstRealDocumentLoad()) {
if (document->GetSettings()
->GetForceTouchEventFeatureDetectionForInspector()) {
- OriginTrialContext::FromOrCreate(document)->AddFeature(
+ document->GetOriginTrialContext()->AddFeature(
OriginTrialFeature::kTouchEventFeatureDetection);
}
@@ -1576,14 +1616,11 @@ void DocumentLoader::InstallNewDocument(
if (origin.scheme() == "chrome-extension" &&
origin.DomainIs("jcgeabjmjgoblfofpppfkcoakmfobdko") &&
origin.port() == 0) {
- OriginTrialContext::FromOrCreate(document)->AddFeature(
+ document->GetOriginTrialContext()->AddFeature(
OriginTrialFeature::kAutoPictureInPicture);
}
#endif
- OriginTrialContext::AddTokensFromHeader(
- document, response_.HttpHeaderField(http_names::kOriginTrial));
-
OriginTrialContext::ActivateNavigationFeaturesFromInitiator(
document, &initiator_origin_trial_features_);
}
@@ -1618,10 +1655,7 @@ 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().
- WTF::StringBuilder feature_policy;
- feature_policy.Append(response_.HttpHeaderField(http_names::kFeaturePolicy));
- MergeFeaturesFromOriginPolicy(feature_policy, origin_policy_);
- document->ApplyFeaturePolicyFromHeader(feature_policy.ToString());
+ document->ApplyPendingFeaturePolicyHeaders();
WTF::String report_only_feature_policy(
response_.HttpHeaderField(http_names::kFeaturePolicyReportOnly));
@@ -1653,37 +1687,6 @@ const AtomicString& DocumentLoader::MimeType() const {
return response_.MimeType();
}
-// This is only called by
-// FrameLoader::ReplaceDocumentWhileExecutingJavaScriptURL()
-void DocumentLoader::ReplaceDocumentWhileExecutingJavaScriptURL(
- const KURL& url,
- Document* owner_document,
- const String& source) {
- // This is necessary because extensions look at DocumentLoader::url_ when
- // deciding whether to inject a content script. In the case where the content
- // script can be injected into blank frames, and an iframe is created with
- // a javascript url as its src attribute, url_ will be empty here as the
- // javascript url was run in the context of the initial empty document.
- // However, the document's url will be about:blank, and content scripts
- // should be allowed to inject into this document.
- if (url_.IsEmpty())
- url_ = BlankURL();
-
- InstallNewDocument(url, nullptr, owner_document, MimeType(),
- response_.TextEncodingName(),
- InstallNewDocumentReason::kJavascriptURL,
- kForceSynchronousParsing, NullURL());
-
- if (!source.IsNull()) {
- frame_->GetDocument()->SetCompatibilityMode(Document::kNoQuirksMode);
- parser_->Append(source);
- }
-
- // Append() might lead to a detach.
- if (parser_)
- parser_->Finish();
-}
-
void DocumentLoader::BlockParser() {
parser_blocked_count_++;
}
@@ -1798,7 +1801,6 @@ void DocumentLoader::ParseAndPersistClientHints(
void DocumentLoader::InitializePrefetchedSignedExchangeManager() {
if (params_->prefetched_signed_exchanges.empty())
return;
- DCHECK(RuntimeEnabledFeatures::SignedExchangeSubresourcePrefetchEnabled());
// |prefetched_signed_exchanges| is set only when the page is loaded from a
// signed exchange.
DCHECK(GetResponse().IsSignedExchangeInnerResponse());
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 e3758819af5..5d17b03dd2f 100644
--- a/chromium/third_party/blink/renderer/core/loader/document_loader.h
+++ b/chromium/third_party/blink/renderer/core/loader/document_loader.h
@@ -34,7 +34,7 @@
#include "base/memory/scoped_refptr.h"
#include "base/optional.h"
#include "base/unguessable_token.h"
-#include "third_party/blink/public/mojom/loader/mhtml_load_result.mojom-shared.h"
+#include "third_party/blink/public/mojom/loader/mhtml_load_result.mojom-blink.h"
#include "third_party/blink/public/platform/scheduler/web_scoped_virtual_time_pauser.h"
#include "third_party/blink/public/platform/web_loading_behavior_flag.h"
#include "third_party/blink/public/platform/web_navigation_body_loader.h"
@@ -42,12 +42,13 @@
#include "third_party/blink/public/web/web_frame_load_type.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/public/web/web_origin_policy.h"
#include "third_party/blink/renderer/bindings/core/v8/source_location.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/dom/weak_identifier_map.h"
#include "third_party/blink/renderer/core/frame/dactyloscoper.h"
#include "third_party/blink/renderer/core/frame/frame_types.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
+#include "third_party/blink/renderer/core/frame/use_counter_helper.h"
#include "third_party/blink/renderer/core/html/parser/parser_synchronization_policy.h"
#include "third_party/blink/renderer/core/loader/document_load_timing.h"
#include "third_party/blink/renderer/core/loader/frame_loader_types.h"
@@ -55,6 +56,7 @@
#include "third_party/blink/renderer/core/loader/preload_helper.h"
#include "third_party/blink/renderer/core/loader/previews_resource_loading_hints.h"
#include "third_party/blink/renderer/core/page/viewport_description.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/loader/fetch/client_hints_preferences.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_error.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_request.h"
@@ -121,10 +123,6 @@ class CORE_EXPORT DocumentLoader
uint64_t MainResourceIdentifier() const;
- void ReplaceDocumentWhileExecutingJavaScriptURL(const KURL&,
- Document* owner_document,
- const String& source);
-
const AtomicString& MimeType() const;
const KURL& OriginalUrl() const;
@@ -150,6 +148,7 @@ class CORE_EXPORT DocumentLoader
const Referrer& GetReferrer() const;
const KURL& UnreachableURL() const;
EncodedFormData* HttpBody() const;
+ const base::UnguessableToken& AppcacheHostId() const;
void DidChangePerformanceTiming();
void DidObserveLoadingBehavior(WebLoadingBehaviorFlag);
@@ -189,6 +188,9 @@ class CORE_EXPORT DocumentLoader
void StartLoading();
void StopLoading();
+ // Starts loading the response.
+ void StartLoadingResponse();
+
// Called when the browser process has asked this renderer process to commit a
// same document navigation in that frame. Returns false if the navigation
// cannot commit, true otherwise.
@@ -262,13 +264,6 @@ class CORE_EXPORT DocumentLoader
void BlockParser();
void ResumeParser();
- // Returns the currently stored content security policy, if this is called
- // after the document has been installed it will return nullptr as the
- // CSP belongs to the document at that point.
- const ContentSecurityPolicy* GetContentSecurityPolicy() const {
- return content_security_policy_.Get();
- }
-
bool IsListingFtpDirectory() const { return listing_ftp_directory_; }
UseCounterHelper& GetUseCounterHelper() { return use_counter_; }
@@ -284,10 +279,26 @@ class CORE_EXPORT DocumentLoader
// The caller owns the |clock| which must outlive the DocumentLoader.
void SetTickClockForTesting(const base::TickClock* clock) { clock_ = clock; }
+ void SetApplicationCacheHostForTesting(ApplicationCacheHost* host) {
+ application_cache_host_ = host;
+ }
- protected:
- bool had_transient_activation() const { return had_transient_activation_; }
+ void SetLoadingJavaScriptUrl() { loading_url_as_javascript_ = true; }
+ WebURLRequest::PreviewsState previews_state() const {
+ return previews_state_;
+ }
+
+ bool HadTransientActivation() const { return had_transient_activation_; }
+
+ bool IsBrowserInitiated() const { return is_browser_initiated_; }
+
+ // TODO(dcheng, japhet): Some day, Document::Url() will always match
+ // DocumentLoader::Url(), and one of them will be removed. Today is not that
+ // day though.
+ void UpdateUrlForDocumentOpen(const KURL& url) { url_ = url; }
+
+ protected:
Vector<KURL> redirect_chain_;
// Archive used to load document and/or subresources. If one of the ancestor
@@ -299,26 +310,25 @@ class CORE_EXPORT DocumentLoader
mojom::MHTMLLoadResult::kSuccess;
private:
- // installNewDocument() does the work of creating a Document and
+ // InstallNewDocument() does the work of creating a Document and
// DocumentParser, as well as creating a new LocalDOMWindow if needed. It also
// initalizes a bunch of state on the Document (e.g., the state based on
// response headers).
- enum class InstallNewDocumentReason { kNavigation, kJavascriptURL };
void InstallNewDocument(
const KURL&,
const scoped_refptr<const SecurityOrigin> initiator_origin,
Document* owner_document,
const AtomicString& mime_type,
const AtomicString& encoding,
- InstallNewDocumentReason,
ParserSynchronizationPolicy,
const KURL& overriding_url);
void DidInstallNewDocument(Document*);
void WillCommitNavigation();
void DidCommitNavigation(GlobalObjectReusePolicy);
- void CommitNavigation(const AtomicString& mime_type,
- const KURL& overriding_url = KURL());
+ void PrepareForNavigationCommit();
+ void FinishNavigationCommit(const AtomicString& mime_type,
+ const KURL& overriding_url = KURL());
void CommitSameDocumentNavigationInternal(
const KURL&,
@@ -336,10 +346,11 @@ class CORE_EXPORT DocumentLoader
void CommitData(const char* bytes, size_t length);
- ContentSecurityPolicy* CreateCSP(const ResourceResponse&,
- const String& origin_policy_string);
+ ContentSecurityPolicy* CreateCSP(
+ const ResourceResponse&,
+ const base::Optional<WebOriginPolicy>& origin_policy);
void StartLoadingInternal();
- void FinishedLoading(TimeTicks finish_time);
+ void FinishedLoading(base::TimeTicks finish_time);
void CancelLoadAfterCSPDenied(const ResourceResponse&);
enum class HistoryNavigationType {
@@ -351,11 +362,12 @@ class CORE_EXPORT DocumentLoader
WebFrameLoadType,
HistoryNavigationType);
+ void FinalizeMHTMLArchiveLoad();
void HandleRedirect(const KURL& current_request_url);
void HandleResponse();
void HandleData(const char* data, size_t length);
- void LoadEmpty();
+ void InitializeEmptyResponse();
bool ShouldReportTimingInfoToParent();
@@ -369,7 +381,7 @@ class CORE_EXPORT DocumentLoader
// WebNavigationBodyLoader::Client
void BodyCodeCacheReceived(base::span<const uint8_t>) override;
void BodyDataReceived(base::span<const char> data) override;
- void BodyLoadingFinished(TimeTicks completion_time,
+ void BodyLoadingFinished(base::TimeTicks completion_time,
int64_t total_encoded_data_length,
int64_t total_encoded_body_length,
int64_t total_decoded_body_length,
@@ -399,11 +411,12 @@ class CORE_EXPORT DocumentLoader
scoped_refptr<EncodedFormData> http_body_;
AtomicString http_content_type_;
WebURLRequest::PreviewsState previews_state_;
- String origin_policy_;
+ base::Optional<WebOriginPolicy> origin_policy_;
scoped_refptr<const SecurityOrigin> requestor_origin_;
KURL unreachable_url_;
int error_code_;
std::unique_ptr<WebNavigationBodyLoader> body_loader_;
+ base::UnguessableToken appcache_host_id_;
// Params are saved in constructor and are cleared after StartLoading().
// TODO(dgozman): remove once StartLoading is merged with constructor.
@@ -441,7 +454,7 @@ class CORE_EXPORT DocumentLoader
DocumentLoadTiming document_load_timing_;
- TimeTicks time_of_last_data_received_;
+ base::TimeTicks time_of_last_data_received_;
Member<ApplicationCacheHost> application_cache_host_;
@@ -474,6 +487,9 @@ class CORE_EXPORT DocumentLoader
// Whether this load request had a user activation when created.
bool had_transient_activation_ = false;
+ // Whether this load request was initiated by the browser.
+ bool is_browser_initiated_ = false;
+
// See WebNavigationParams for definition.
bool was_discarded_ = false;
@@ -481,6 +497,7 @@ class CORE_EXPORT DocumentLoader
bool loading_mhtml_archive_ = false;
bool loading_srcdoc_ = false;
bool loading_url_as_empty_document_ = false;
+ bool loading_url_as_javascript_ = false;
uint64_t main_resource_identifier_ = 0;
scoped_refptr<ResourceTimingInfo> navigation_timing_info_;
bool report_timing_info_to_parent_ = false;
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 86fa47f944f..a255c57cca9 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
@@ -4,8 +4,6 @@
#include "third_party/blink/renderer/core/loader/document_loader.h"
-#include <queue>
-#include <string>
#include <utility>
#include "base/auto_reset.h"
#include "testing/gtest/include/gtest/gtest.h"
@@ -17,9 +15,12 @@
#include "third_party/blink/renderer/core/frame/web_local_frame_impl.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/testing/scoped_fake_plugin_registry.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/static_data_navigation_body_loader.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/wtf/deque.h"
namespace blink {
@@ -102,9 +103,9 @@ TEST_F(DocumentLoaderTest, MultiChunkWithReentrancy) {
params->response.SetMimeType("application/pdf");
params->response.SetHttpStatusCode(200);
- std::string data("<html><body>foo</body></html>");
- for (size_t i = 0; i < data.size(); i++)
- data_.push(data[i]);
+ String data("<html><body>foo</body></html>");
+ for (wtf_size_t i = 0; i < data.length(); i++)
+ data_.push_back(data[i]);
auto body_loader = std::make_unique<StaticDataNavigationBodyLoader>();
body_loader_ = body_loader.get();
@@ -122,8 +123,8 @@ TEST_F(DocumentLoaderTest, MultiChunkWithReentrancy) {
}
// Serve the remaining bytes to complete the load.
- EXPECT_FALSE(data_.empty());
- while (!data_.empty())
+ EXPECT_FALSE(data_.IsEmpty());
+ while (!data_.IsEmpty())
DispatchOneByte();
body_loader_->Finish();
@@ -147,15 +148,14 @@ TEST_F(DocumentLoaderTest, MultiChunkWithReentrancy) {
}
void DispatchOneByte() {
- char c = data_.front();
- data_.pop();
+ char c = data_.TakeFirst();
body_loader_->Write(&c, 1);
}
bool ServedReentrantly() const { return served_reentrantly_; }
private:
- std::queue<char> data_;
+ Deque<char> data_;
bool dispatching_did_receive_data_ = false;
bool served_reentrantly_ = false;
StaticDataNavigationBodyLoader* body_loader_ = nullptr;
@@ -221,4 +221,35 @@ TEST_F(DocumentLoaderTest, MixedContentOptOutNotSetIfNoHeaderReceived) {
->GetMixedAutoUpgradeOptOut());
}
+class DocumentLoaderSimTest : public SimTest {};
+
+TEST_F(DocumentLoaderSimTest, DocumentOpenUpdatesUrl) {
+ SimRequest main_resource("https://example.com", "text/html");
+ LoadURL("https://example.com");
+ main_resource.Write("<iframe src='javascript:42;'></iframe>");
+
+ auto* child_frame = To<WebLocalFrameImpl>(MainFrame().FirstChild());
+ auto* child_document = child_frame->GetFrame()->GetDocument();
+ EXPECT_TRUE(child_document->HasPendingJavaScriptUrlsForTest());
+
+ main_resource.Write(
+ "<script>"
+ "window[0].document.open();"
+ "window[0].document.write('hello');"
+ "window[0].document.close();"
+ "</script>");
+
+ main_resource.Finish();
+
+ // document.open() should have cancelled the pending JavaScript URLs.
+ EXPECT_FALSE(child_document->HasPendingJavaScriptUrlsForTest());
+
+ // Per https://whatwg.org/C/dynamic-markup-insertion.html#document-open-steps,
+ // the URL associated with the Document should match the URL of the entry
+ // Document.
+ EXPECT_EQ(KURL("https://example.com"), child_document->Url());
+ // Similarly, the URL of the DocumentLoader should also match.
+ EXPECT_EQ(KURL("https://example.com"), child_document->Loader()->Url());
+}
+
} // 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 b7459052069..8fb81885635 100644
--- a/chromium/third_party/blink/renderer/core/loader/empty_clients.cc
+++ b/chromium/third_party/blink/renderer/core/loader/empty_clients.cc
@@ -33,7 +33,6 @@
#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_provider_client.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_media_player.h"
-#include "third_party/blink/public/web/web_application_cache_host.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"
@@ -156,8 +155,8 @@ LocalFrame* EmptyLocalFrameClient::CreateFrame(const AtomicString&,
std::pair<RemoteFrame*, base::UnguessableToken>
EmptyLocalFrameClient::CreatePortal(
HTMLPortalElement*,
- mojom::blink::PortalAssociatedRequest,
- mojom::blink::PortalClientAssociatedPtrInfo) {
+ mojo::PendingAssociatedReceiver<mojom::blink::Portal>,
+ mojo::PendingAssociatedRemote<mojom::blink::PortalClient>) {
return std::pair<RemoteFrame*, base::UnguessableToken>(
nullptr, base::UnguessableToken());
}
@@ -207,13 +206,6 @@ EmptyLocalFrameClient::CreateServiceWorkerProvider() {
return nullptr;
}
-std::unique_ptr<WebApplicationCacheHost>
-EmptyLocalFrameClient::CreateApplicationCacheHost(
- DocumentLoader*,
- WebApplicationCacheHostClient*) {
- return nullptr;
-}
-
EmptyRemoteFrameClient::EmptyRemoteFrameClient() = default;
} // namespace blink
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 57b35dd1a54..469d071483f 100644
--- a/chromium/third_party/blink/renderer/core/loader/empty_clients.h
+++ b/chromium/third_party/blink/renderer/core/loader/empty_clients.h
@@ -100,9 +100,11 @@ class CORE_EXPORT EmptyChromeClient : public ChromeClient {
void SetOverscrollBehavior(LocalFrame& frame,
const cc::OverscrollBehavior&) override {}
- void BeginLifecycleUpdates() override {}
- void StartDeferringCommits(base::TimeDelta timeout) override {}
- void StopDeferringCommits(cc::PaintHoldingCommitTrigger) override {}
+ void BeginLifecycleUpdates(LocalFrame& main_frame) override {}
+ void StartDeferringCommits(LocalFrame& main_frame,
+ base::TimeDelta timeout) override {}
+ void StopDeferringCommits(LocalFrame& main_frame,
+ cc::PaintHoldingCommitTrigger) override {}
bool HadFormInteraction() const override { return false; }
@@ -233,6 +235,8 @@ class CORE_EXPORT EmptyChromeClient : public ChromeClient {
void SetCursorForPlugin(const WebCursorInfo&, LocalFrame*) override {}
void InstallSupplements(LocalFrame&) override {}
+
+ void MainFrameScrollOffsetChanged(LocalFrame& main_frame) const override {}
};
class CORE_EXPORT EmptyLocalFrameClient : public LocalFrameClient {
@@ -336,8 +340,8 @@ class CORE_EXPORT EmptyLocalFrameClient : public LocalFrameClient {
LocalFrame* CreateFrame(const AtomicString&, HTMLFrameOwnerElement*) override;
std::pair<RemoteFrame*, base::UnguessableToken> CreatePortal(
HTMLPortalElement*,
- mojom::blink::PortalAssociatedRequest,
- mojom::blink::PortalClientAssociatedPtrInfo) override;
+ mojo::PendingAssociatedReceiver<mojom::blink::Portal>,
+ mojo::PendingAssociatedRemote<mojom::blink::PortalClient>) override;
RemoteFrame* AdoptPortal(HTMLPortalElement*) override;
WebPluginContainerImpl* CreatePlugin(HTMLPlugInElement&,
const KURL&,
@@ -367,8 +371,6 @@ class CORE_EXPORT EmptyLocalFrameClient : public LocalFrameClient {
void VisibilityChanged(blink::mojom::FrameVisibility) override {}
- WebCookieJar* CookieJar() const override { return nullptr; }
-
service_manager::InterfaceProvider* GetInterfaceProvider() override {
return &interface_provider_;
}
@@ -386,9 +388,6 @@ class CORE_EXPORT EmptyLocalFrameClient : public LocalFrameClient {
WebContentSettingsClient* GetContentSettingsClient() override {
return nullptr;
}
- std::unique_ptr<WebApplicationCacheHost> CreateApplicationCacheHost(
- DocumentLoader*,
- WebApplicationCacheHostClient*) override;
void SetTextCheckerClientForTesting(WebTextCheckClient*);
WebTextCheckClient* GetTextCheckerClient() const override;
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 e0015055bf4..e489d40af9b 100644
--- a/chromium/third_party/blink/renderer/core/loader/form_submission.cc
+++ b/chromium/third_party/blink/renderer/core/loader/form_submission.cc
@@ -34,7 +34,6 @@
#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/use_counter.h"
#include "third_party/blink/renderer/core/html/forms/form_data.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"
@@ -43,6 +42,7 @@
#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/platform/heap/handle.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/network/encoded_form_data.h"
#include "third_party/blink/renderer/platform/network/form_data_encoder.h"
#include "third_party/blink/renderer/platform/network/http_names.h"
@@ -58,7 +58,7 @@ static int64_t GenerateFormDataIdentifier() {
// Initialize to the current time to reduce the likelihood of generating
// identifiers that overlap with those from past/future browser sessions.
static int64_t next_identifier =
- static_cast<int64_t>(CurrentTime() * 1000000.0);
+ static_cast<int64_t>(base::Time::Now().ToDoubleT() * 1000000.0);
return ++next_identifier;
}
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 fa4405e8c53..519bdea77ec 100644
--- a/chromium/third_party/blink/renderer/core/loader/form_submission.h
+++ b/chromium/third_party/blink/renderer/core/loader/form_submission.h
@@ -38,7 +38,7 @@
#include "third_party/blink/renderer/platform/heap/handle.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/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 1a0bd0fd4bb..52d540c44f5 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
@@ -38,7 +38,7 @@
#include "build/build_config.h"
#include "third_party/blink/public/common/client_hints/client_hints.h"
#include "third_party/blink/public/common/device_memory/approximated_device_memory.h"
-#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-shared.h"
+#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h"
#include "third_party/blink/public/mojom/loader/request_context_frame_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/scheduler/web_scoped_virtual_time_pauser.h"
@@ -46,7 +46,6 @@
#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"
-#include "third_party/blink/public/web/web_application_cache_host.h"
#include "third_party/blink/public/web/web_frame.h"
#include "third_party/blink/public/web/web_local_frame.h"
#include "third_party/blink/public/web/web_local_frame_client.h"
@@ -64,7 +63,6 @@
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/frame/navigator.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"
@@ -89,12 +87,12 @@
#include "third_party/blink/renderer/core/timing/performance.h"
#include "third_party/blink/renderer/core/timing/window_performance.h"
#include "third_party/blink/renderer/platform/bindings/script_forbidden_scope.h"
-#include "third_party/blink/renderer/platform/bindings/v8_dom_activity_logger.h"
#include "third_party/blink/renderer/platform/exported/wrapped_resource_request.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/traced_value.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/loader/fetch/client_hints_preferences.h"
-#include "third_party/blink/renderer/platform/loader/fetch/fetch_initiator_type_names.h"
+#include "third_party/blink/renderer/platform/loader/fetch/detachable_use_counter.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_load_priority.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_loading_log.h"
@@ -240,9 +238,9 @@ ResourceFetcher* FrameFetchContext::CreateFetcherForCommittedDocument(
properties),
frame.GetTaskRunner(TaskType::kNetworking),
MakeGarbageCollected<LoaderFactoryForFrame>(frame_or_imported_document));
- auto* console_logger =
+ init.use_counter = MakeGarbageCollected<DetachableUseCounter>(&document);
+ init.console_logger =
MakeGarbageCollected<DetachableConsoleLogger>(&document);
- init.console_logger = console_logger;
// Frame loading should normally start with |kTight| throttling, as the
// frame will be in layout-blocking state until the <body> tag is inserted
init.initial_throttling_policy =
@@ -276,9 +274,8 @@ ResourceFetcher* FrameFetchContext::CreateFetcherForImportedDocument(
properties),
document->GetTaskRunner(blink::TaskType::kNetworking),
MakeGarbageCollected<LoaderFactoryForFrame>(frame_or_imported_document));
- auto* console_logger =
- MakeGarbageCollected<DetachableConsoleLogger>(document);
- init.console_logger = console_logger;
+ init.use_counter = MakeGarbageCollected<DetachableUseCounter>(document);
+ init.console_logger = MakeGarbageCollected<DetachableConsoleLogger>(document);
init.frame_scheduler = frame.GetFrameScheduler();
auto* fetcher = MakeGarbageCollected<ResourceFetcher>(init);
fetcher->SetResourceLoadObserver(
@@ -326,6 +323,10 @@ FrameFetchContext::GetPreviewsResourceLoadingHints() const {
return document_loader->GetPreviewsResourceLoadingHints();
}
+WebURLRequest::PreviewsState FrameFetchContext::previews_state() const {
+ return GetLocalFrameClient()->GetPreviewsStateForFrame();
+}
+
LocalFrame* FrameFetchContext::GetFrame() const {
return &frame_or_imported_document_->GetFrame();
}
@@ -348,30 +349,6 @@ void FrameFetchContext::AddAdditionalRequestHeaders(ResourceRequest& request) {
if (save_data_enabled_)
request.SetHttpHeaderField(http_names::kSaveData, "on");
-
- if (GetLocalFrameClient()->GetPreviewsStateForFrame() &
- WebURLRequest::kNoScriptOn) {
- request.AddHttpHeaderField(
- "Intervention",
- "<https://www.chromestatus.com/features/4775088607985664>; "
- "level=\"warning\"");
- }
-
- if (GetLocalFrameClient()->GetPreviewsStateForFrame() &
- WebURLRequest::kResourceLoadingHintsOn) {
- request.AddHttpHeaderField(
- "Intervention",
- "<https://www.chromestatus.com/features/4510564810227712>; "
- "level=\"warning\"");
- }
-
- if (GetLocalFrameClient()->GetPreviewsStateForFrame() &
- WebURLRequest::kClientLoFiOn) {
- request.AddHttpHeaderField(
- "Intervention",
- "<https://www.chromestatus.com/features/6072546726248448>; "
- "level=\"warning\"");
- }
}
// TODO(toyoshim, arthursonzogni): PlzNavigate doesn't use this function to set
@@ -466,29 +443,6 @@ void FrameFetchContext::PrepareRequest(
}
}
-void FrameFetchContext::RecordLoadingActivity(
- const ResourceRequest& request,
- ResourceType type,
- const AtomicString& fetch_initiator_name) {
- if (GetResourceFetcherProperties().IsDetached() || !GetDocumentLoader() ||
- GetDocumentLoader()->Archive() || !request.Url().IsValid())
- return;
- V8DOMActivityLogger* activity_logger = nullptr;
- if (fetch_initiator_name == fetch_initiator_type_names::kXmlhttprequest) {
- activity_logger = V8DOMActivityLogger::CurrentActivityLogger();
- } else {
- activity_logger =
- V8DOMActivityLogger::CurrentActivityLoggerIfIsolatedWorld();
- }
-
- if (activity_logger) {
- Vector<String> argv;
- argv.push_back(Resource::ResourceTypeToString(type, fetch_initiator_name));
- argv.push_back(request.Url());
- activity_logger->LogEvent("blinkRequestResource", argv.size(), argv.data());
- }
-}
-
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
@@ -570,8 +524,7 @@ void FrameFetchContext::AddClientHintsIfNecessary(
if (RuntimeEnabledFeatures::UserAgentClientHintEnabled()) {
StringBuilder result;
result.Append(ua.brand.data());
- const std::string& version =
- use_full_ua ? ua.full_version : ua.major_version;
+ const auto& version = use_full_ua ? ua.full_version : ua.major_version;
if (!version.empty()) {
result.Append(' ');
result.Append(version.data());
@@ -675,7 +628,7 @@ void FrameFetchContext::AddClientHintsIfNecessary(
mojom::FeaturePolicyFeature::kClientHintRTT, resource_origin))) &&
ShouldSendClientHint(mojom::WebClientHintsType::kRtt, hints_preferences,
enabled_hints)) {
- base::Optional<TimeDelta> http_rtt =
+ base::Optional<base::TimeDelta> http_rtt =
GetNetworkStateNotifier().GetWebHoldbackHttpRtt();
if (!http_rtt) {
http_rtt = GetNetworkStateNotifier().HttpRtt();
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 756bbef0e8f..245079bec77 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
@@ -33,6 +33,7 @@ n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
#include "base/optional.h"
#include "base/single_thread_task_runner.h"
+#include "third_party/blink/public/common/user_agent/user_agent_metadata.h"
#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"
@@ -87,10 +88,6 @@ class CORE_EXPORT FrameFetchContext final : public BaseFetchContext {
WebScopedVirtualTimePauser&,
ResourceType) override;
- void RecordLoadingActivity(const ResourceRequest&,
- ResourceType,
- const AtomicString& fetch_initiator_name) override;
-
void AddResourceTiming(const ResourceTimingInfo&) override;
bool AllowImage(bool images_enabled, const KURL&) const override;
@@ -133,6 +130,7 @@ class CORE_EXPORT FrameFetchContext final : public BaseFetchContext {
SubresourceFilter* GetSubresourceFilter() const override;
PreviewsResourceLoadingHints* GetPreviewsResourceLoadingHints()
const override;
+ WebURLRequest::PreviewsState previews_state() const override;
bool AllowScriptFromSource(const KURL&) const override;
bool ShouldBlockRequestByInspector(const KURL&) const override;
void DispatchDidBlockRequest(const ResourceRequest&,
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 a1fdbb90053..0dbbc5483d0 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
@@ -38,7 +38,7 @@
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/device_memory/approximated_device_memory.h"
#include "third_party/blink/public/common/features.h"
-#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-shared.h"
+#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h"
#include "third_party/blink/public/mojom/loader/request_context_frame_type.mojom-blink.h"
#include "third_party/blink/public/mojom/net/ip_address_space.mojom-blink.h"
#include "third_party/blink/public/platform/scheduler/web_scoped_virtual_time_pauser.h"
@@ -54,7 +54,6 @@
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/frame/navigator.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_iframe_element.h"
#include "third_party/blink/renderer/core/loader/document_loader.h"
#include "third_party/blink/renderer/core/loader/empty_clients.h"
@@ -63,8 +62,8 @@
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/testing/dummy_page_holder.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_initiator_info.h"
-#include "third_party/blink/renderer/platform/loader/fetch/fetch_initiator_type_names.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/loader/fetch/resource_request.h"
@@ -73,6 +72,7 @@
#include "third_party/blink/renderer/platform/loader/testing/mock_resource.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/unit_test_helpers.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/weborigin/security_violation_reporting_policy.h"
@@ -120,9 +120,23 @@ class FrameFetchContextTest : public testing::Test {
protected:
void SetUp() override { RecreateFetchContext(); }
- void RecreateFetchContext() {
+ void RecreateFetchContext(const KURL& url = KURL(),
+ const String& feature_policy_header = String()) {
dummy_page_holder = std::make_unique<DummyPageHolder>(IntSize(500, 500));
dummy_page_holder->GetPage().SetDeviceScaleFactorDeprecated(1.0);
+ if (url.IsValid()) {
+ auto params = WebNavigationParams::CreateWithHTMLBuffer(
+ SharedBuffer::Create(), url);
+ if (!feature_policy_header.IsEmpty()) {
+ params->response.SetHttpHeaderField(http_names::kFeaturePolicy,
+ feature_policy_header);
+ }
+ dummy_page_holder->GetFrame().Loader().CommitNavigation(
+ std::move(params), nullptr /* extra_data */);
+ blink::test::RunPendingTasks();
+ ASSERT_EQ(url.GetString(),
+ dummy_page_holder->GetDocument().Url().GetString());
+ }
document = &dummy_page_holder->GetDocument();
owner = MakeGarbageCollected<DummyFrameOwner>();
}
@@ -260,9 +274,7 @@ class FrameFetchContextMockedLocalFrameClientTest
class FrameFetchContextModifyRequestTest : public FrameFetchContextTest {
public:
FrameFetchContextModifyRequestTest()
- : example_origin(SecurityOrigin::Create(KURL("https://example.test/"))),
- secure_origin(SecurityOrigin::Create(
- KURL("https://secureorigin.test/image.png"))) {}
+ : example_origin(SecurityOrigin::Create(KURL("https://example.test/"))) {}
protected:
void ModifyRequestForCSP(ResourceRequest& resource_request,
@@ -325,13 +337,16 @@ class FrameFetchContextModifyRequestTest : public FrameFetchContextTest {
void ExpectIsAutomaticUpgradeSet(const char* input,
const char* main_frame,
+ WebInsecureRequestPolicy policy,
bool expected_value) {
const KURL input_url(input);
const KURL main_frame_url(main_frame);
ResourceRequest resource_request(input_url);
resource_request.SetRequestContext(mojom::RequestContextType::SCRIPT);
- document->SetSecurityOrigin(SecurityOrigin::Create(KURL(main_frame_url)));
+ RecreateFetchContext(main_frame_url);
+ document->SetInsecureRequestPolicy(policy);
+
ModifyRequestForCSP(resource_request,
network::mojom::RequestContextFrameType::kNone);
@@ -366,7 +381,6 @@ class FrameFetchContextModifyRequestTest : public FrameFetchContextTest {
}
scoped_refptr<const SecurityOrigin> example_origin;
- scoped_refptr<SecurityOrigin> secure_origin;
};
TEST_F(FrameFetchContextModifyRequestTest, UpgradeInsecureResourceRequests) {
@@ -439,7 +453,10 @@ TEST_F(FrameFetchContextModifyRequestTest, UpgradeInsecureResourceRequests) {
TEST_F(FrameFetchContextModifyRequestTest,
DoNotUpgradeInsecureResourceRequests) {
- document->SetSecurityOrigin(secure_origin);
+ base::test::ScopedFeatureList feature_list;
+ feature_list.InitAndDisableFeature(blink::features::kMixedContentAutoupgrade);
+
+ RecreateFetchContext(KURL("https://secureorigin.test/image.png"));
document->SetInsecureRequestPolicy(kLeaveInsecureRequestsAlone);
ExpectUpgrade("http://example.test/image.png",
@@ -466,26 +483,27 @@ TEST_F(FrameFetchContextModifyRequestTest,
TEST_F(FrameFetchContextModifyRequestTest, IsAutomaticUpgradeSet) {
base::test::ScopedFeatureList scoped_feature_list;
scoped_feature_list.InitAndEnableFeature(features::kMixedContentAutoupgrade);
- document->SetInsecureRequestPolicy(kLeaveInsecureRequestsAlone);
ExpectIsAutomaticUpgradeSet("http://example.test/image.png",
- "https://example.test", true);
+ "https://example.test",
+ kLeaveInsecureRequestsAlone, true);
}
TEST_F(FrameFetchContextModifyRequestTest, IsAutomaticUpgradeNotSet) {
base::test::ScopedFeatureList scoped_feature_list;
scoped_feature_list.InitAndEnableFeature(features::kMixedContentAutoupgrade);
- document->SetInsecureRequestPolicy(kLeaveInsecureRequestsAlone);
// Upgrade shouldn't happen if the resource is already https.
ExpectIsAutomaticUpgradeSet("https://example.test/image.png",
- "https://example.test", false);
+ "https://example.test",
+ kLeaveInsecureRequestsAlone, false);
// Upgrade shouldn't happen if the site is http.
ExpectIsAutomaticUpgradeSet("http://example.test/image.png",
- "http://example.test", false);
+ "http://example.test",
+ kLeaveInsecureRequestsAlone, false);
- document->SetInsecureRequestPolicy(kUpgradeInsecureRequests);
// Flag shouldn't be set if upgrade was due to upgrade-insecure-requests.
ExpectIsAutomaticUpgradeSet("http://example.test/image.png",
- "https://example.test", false);
+ "https://example.test", kUpgradeInsecureRequests,
+ false);
}
TEST_F(FrameFetchContextModifyRequestTest, SendUpgradeInsecureRequestHeader) {
@@ -574,12 +592,8 @@ class FrameFetchContextHintsTest : public FrameFetchContextTest {
FrameFetchContextHintsTest() = default;
void SetUp() override {
- FrameFetchContextTest::SetUp();
// Set the document URL to a secure document.
- document->SetURL(KURL("https://www.example.com/"));
- document->SetSecurityOrigin(
- SecurityOrigin::Create(KURL("https://www.example.com/")));
- document->InitializeFeaturePolicy({}, {}, nullptr, nullptr);
+ RecreateFetchContext(KURL("https://www.example.com/"));
Settings* settings = document->GetSettings();
settings->SetScriptEnabled(true);
}
@@ -658,10 +672,8 @@ TEST_F(FrameFetchContextHintsTest, MonitorDeviceMemoryHintsInsecureContext) {
// Verify that client hints are attched when the resources belong to a local
// context.
TEST_F(FrameFetchContextHintsTest, MonitorDeviceMemoryHintsLocalContext) {
- document->SetURL(KURL("http://localhost/"));
- document->SetSecurityOrigin(
- SecurityOrigin::Create(KURL("http://localhost/")));
- document->InitializeFeaturePolicy({}, {}, nullptr, nullptr);
+ RecreateFetchContext(KURL("http://localhost/"));
+ document->GetSettings()->SetScriptEnabled(true);
ExpectHeader("http://localhost/1.gif", "Device-Memory", false, "");
ClientHintsPreferences preferences;
preferences.SetShouldSendForTesting(mojom::WebClientHintsType::kDeviceMemory);
@@ -899,13 +911,12 @@ TEST_F(FrameFetchContextHintsTest, MonitorAllHints) {
// Verify that the client hints should be attached for third-party subresources
// fetched over secure transport, when specifically allowed by feature policy.
TEST_F(FrameFetchContextHintsTest, MonitorAllHintsFeaturePolicy) {
- ParsedFeaturePolicy policy = FeaturePolicyParser::ParseHeader(
+ RecreateFetchContext(
+ KURL("https://www.example.com/"),
"ch-dpr *; ch-device-memory *; ch-downlink *; ch-ect *; ch-lang *;"
"ch-rtt *; ch-ua *; ch-ua-arch *; ch-ua-platform *; ch-ua-model *;"
- "ch-viewport-width *; ch-width *",
- SecurityOrigin::CreateFromString("https://www.example.com/"), nullptr,
- document);
- document->InitializeFeaturePolicy(policy, {}, nullptr, nullptr);
+ "ch-viewport-width *; ch-width *");
+ document->GetSettings()->SetScriptEnabled(true);
ClientHintsPreferences preferences;
preferences.SetShouldSendForTesting(mojom::WebClientHintsType::kDeviceMemory);
preferences.SetShouldSendForTesting(mojom::WebClientHintsType::kDpr);
@@ -961,11 +972,9 @@ TEST_F(FrameFetchContextHintsTest, MonitorAllHintsFeaturePolicy) {
// Verify that only the specifically allowed client hints are attached for
// third-party subresources fetched over secure transport.
TEST_F(FrameFetchContextHintsTest, MonitorSomeHintsFeaturePolicy) {
- ParsedFeaturePolicy policy = FeaturePolicyParser::ParseHeader(
- "ch-device-memory 'self' https://www.example.net",
- SecurityOrigin::CreateFromString("https://www.example.com/"), nullptr,
- document);
- document->InitializeFeaturePolicy(policy, {}, nullptr, nullptr);
+ RecreateFetchContext(KURL("https://www.example.com/"),
+ "ch-device-memory 'self' https://www.example.net");
+ document->GetSettings()->SetScriptEnabled(true);
ClientHintsPreferences preferences;
preferences.SetShouldSendForTesting(mojom::WebClientHintsType::kDeviceMemory);
preferences.SetShouldSendForTesting(mojom::WebClientHintsType::kDpr);
@@ -996,11 +1005,8 @@ TEST_F(FrameFetchContextHintsTest, MonitorSomeHintsFeaturePolicy) {
// fetched over insecure transport, even when specifically allowed by feature
// policy.
TEST_F(FrameFetchContextHintsTest, MonitorHintsFeaturePolicyInsecureContext) {
- ParsedFeaturePolicy policy = FeaturePolicyParser::ParseHeader(
- "ch-device-memory *",
- SecurityOrigin::CreateFromString("https://www.example.com/"), nullptr,
- document);
- document->InitializeFeaturePolicy(policy, {}, nullptr, nullptr);
+ RecreateFetchContext(KURL("https://www.example.com/"), "ch-device-memory *");
+ document->GetSettings()->SetScriptEnabled(true);
ExpectHeader("https://www.example.com/1.gif", "Device-Memory", false, "");
ClientHintsPreferences preferences;
preferences.SetShouldSendForTesting(mojom::WebClientHintsType::kDeviceMemory);
@@ -1211,20 +1217,6 @@ TEST_F(FrameFetchContextMockedLocalFrameClientTest,
EXPECT_EQ("hi", request.HttpHeaderField(http_names::kUserAgent));
}
-TEST_F(FrameFetchContextTest, RecordLoadingActivityWhenDetached) {
- ResourceRequest request(KURL("https://www.example.com/"));
-
- dummy_page_holder = nullptr;
-
- GetFetchContext()->RecordLoadingActivity(
- request, ResourceType::kRaw, fetch_initiator_type_names::kXmlhttprequest);
- // Should not crash.
-
- GetFetchContext()->RecordLoadingActivity(
- request, ResourceType::kRaw, fetch_initiator_type_names::kDocument);
- // Should not crash.
-}
-
TEST_F(FrameFetchContextTest, AddResourceTimingWhenDetached) {
scoped_refptr<ResourceTimingInfo> info = ResourceTimingInfo::Create(
"type", base::TimeTicks() + base::TimeDelta::FromSecondsD(0.3));
@@ -1278,13 +1270,11 @@ TEST_F(FrameFetchContextTest, PopulateResourceRequestWhenDetached) {
}
TEST_F(FrameFetchContextTest, SetFirstPartyCookieWhenDetached) {
- const KURL url("https://www.example.com/hoge/fuga");
- ResourceRequest request(url);
const KURL document_url("https://www2.example.com/foo/bar");
- scoped_refptr<SecurityOrigin> origin = SecurityOrigin::Create(document_url);
+ RecreateFetchContext(document_url);
- document->SetSecurityOrigin(origin);
- document->SetURL(document_url);
+ const KURL url("https://www.example.com/hoge/fuga");
+ ResourceRequest request(url);
dummy_page_holder = nullptr;
@@ -1295,91 +1285,27 @@ TEST_F(FrameFetchContextTest, SetFirstPartyCookieWhenDetached) {
}
TEST_F(FrameFetchContextTest, TopFrameOrigin) {
- const KURL url("https://www.example.com/hoge/fuga");
- ResourceRequest request(url);
const KURL document_url("https://www2.example.com/foo/bar");
- scoped_refptr<SecurityOrigin> origin = SecurityOrigin::Create(document_url);
+ RecreateFetchContext(document_url);
+ const SecurityOrigin* origin = document->GetSecurityOrigin();
- document->SetSecurityOrigin(origin);
- document->SetURL(document_url);
+ const KURL url("https://www.example.com/hoge/fuga");
+ ResourceRequest request(url);
EXPECT_EQ(origin, GetTopFrameOrigin());
}
TEST_F(FrameFetchContextTest, TopFrameOriginDetached) {
- const KURL url("https://www.example.com/hoge/fuga");
- ResourceRequest request(url);
const KURL document_url("https://www2.example.com/foo/bar");
- scoped_refptr<SecurityOrigin> origin = SecurityOrigin::Create(document_url);
+ RecreateFetchContext(document_url);
+ const SecurityOrigin* origin = document->GetSecurityOrigin();
- document->SetSecurityOrigin(origin);
- document->SetURL(document_url);
+ const KURL url("https://www.example.com/hoge/fuga");
+ ResourceRequest request(url);
dummy_page_holder = nullptr;
EXPECT_EQ(origin, GetTopFrameOrigin());
}
-// Tests if "Intervention" header is added for frame with Client Lo-Fi enabled.
-TEST_F(FrameFetchContextMockedLocalFrameClientTest,
- ClientLoFiInterventionHeader) {
- // Verify header not added if Lo-Fi not active.
- EXPECT_CALL(*client, GetPreviewsStateForFrame())
- .WillRepeatedly(testing::Return(WebURLRequest::kPreviewsOff));
- ResourceRequest resource_request("http://www.example.com/style.css");
- GetFetchContext()->AddAdditionalRequestHeaders(resource_request);
- EXPECT_EQ(g_null_atom, resource_request.HttpHeaderField("Intervention"));
-
- // Verify header is added if Lo-Fi is active.
- EXPECT_CALL(*client, GetPreviewsStateForFrame())
- .WillRepeatedly(testing::Return(WebURLRequest::kClientLoFiOn));
- GetFetchContext()->AddAdditionalRequestHeaders(resource_request);
- EXPECT_EQ(
- "<https://www.chromestatus.com/features/6072546726248448>; "
- "level=\"warning\"",
- resource_request.HttpHeaderField("Intervention"));
-
- // Verify appended to an existing "Intervention" header value.
- ResourceRequest resource_request2("http://www.example.com/getad.js");
- resource_request2.SetHttpHeaderField("Intervention",
- "<https://otherintervention.org>");
- GetFetchContext()->AddAdditionalRequestHeaders(resource_request2);
- EXPECT_EQ(
- "<https://otherintervention.org>, "
- "<https://www.chromestatus.com/features/6072546726248448>; "
- "level=\"warning\"",
- resource_request2.HttpHeaderField("Intervention"));
-}
-
-// Tests if "Intervention" header is added for frame with NoScript enabled.
-TEST_F(FrameFetchContextMockedLocalFrameClientTest,
- NoScriptInterventionHeader) {
- // Verify header not added if NoScript not active.
- EXPECT_CALL(*client, GetPreviewsStateForFrame())
- .WillRepeatedly(testing::Return(WebURLRequest::kPreviewsOff));
- ResourceRequest resource_request("http://www.example.com/style.css");
- GetFetchContext()->AddAdditionalRequestHeaders(resource_request);
- EXPECT_EQ(g_null_atom, resource_request.HttpHeaderField("Intervention"));
-
- // Verify header is added if NoScript is active.
- EXPECT_CALL(*client, GetPreviewsStateForFrame())
- .WillRepeatedly(testing::Return(WebURLRequest::kNoScriptOn));
- GetFetchContext()->AddAdditionalRequestHeaders(resource_request);
- EXPECT_EQ(
- "<https://www.chromestatus.com/features/4775088607985664>; "
- "level=\"warning\"",
- resource_request.HttpHeaderField("Intervention"));
-
- // Verify appended to an existing "Intervention" header value.
- ResourceRequest resource_request2("http://www.example.com/getad.js");
- resource_request2.SetHttpHeaderField("Intervention",
- "<https://otherintervention.org>");
- GetFetchContext()->AddAdditionalRequestHeaders(resource_request2);
- EXPECT_EQ(
- "<https://otherintervention.org>, "
- "<https://www.chromestatus.com/features/4775088607985664>; "
- "level=\"warning\"",
- resource_request2.HttpHeaderField("Intervention"));
-}
-
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/loader/frame_load_request.cc b/chromium/third_party/blink/renderer/core/loader/frame_load_request.cc
index dd5fb5074c2..f04f0034b50 100644
--- a/chromium/third_party/blink/renderer/core/loader/frame_load_request.cc
+++ b/chromium/third_party/blink/renderer/core/loader/frame_load_request.cc
@@ -37,7 +37,8 @@ static void SetReferrerForRequest(Document* origin_document,
// 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);
+ request.SetHttpReferrer(
+ referrer, ResourceRequest::SetHttpReferrerLocation::kFrameLoadRequest);
request.SetHTTPOriginToMatchReferrerIfNeeded();
}
@@ -48,12 +49,10 @@ FrameLoadRequest::FrameLoadRequest(Document* origin_document,
resource_request_(resource_request),
should_send_referrer_(kMaybeSendReferrer) {
// These flags are passed to a service worker which controls the page.
- resource_request_.SetFetchRequestMode(
- network::mojom::FetchRequestMode::kNavigate);
- resource_request_.SetFetchCredentialsMode(
- network::mojom::FetchCredentialsMode::kInclude);
- resource_request_.SetFetchRedirectMode(
- network::mojom::FetchRedirectMode::kManual);
+ resource_request_.SetMode(network::mojom::RequestMode::kNavigate);
+ resource_request_.SetCredentialsMode(
+ network::mojom::CredentialsMode::kInclude);
+ resource_request_.SetRedirectMode(network::mojom::RedirectMode::kManual);
if (const WebInputEvent* input_event = CurrentInputEvent::Get())
SetInputStartTime(input_event->TimeStamp());
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 9d98e85ee2b..c56168f8bda 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
@@ -27,7 +27,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_FRAME_LOAD_REQUEST_H_
#include "third_party/blink/public/mojom/blob/blob_url_store.mojom-blink.h"
-#include "third_party/blink/public/mojom/loader/request_context_frame_type.mojom-shared.h"
+#include "third_party/blink/public/mojom/loader/request_context_frame_type.mojom-blink.h"
#include "third_party/blink/public/web/web_triggering_event_info.h"
#include "third_party/blink/public/web/web_window_features.h"
#include "third_party/blink/renderer/core/dom/document.h"
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 1c1bd65c5f7..32125adc8dc 100644
--- a/chromium/third_party/blink/renderer/core/loader/frame_loader.cc
+++ b/chromium/third_party/blink/renderer/core/loader/frame_loader.cc
@@ -42,7 +42,7 @@
#include "base/auto_reset.h"
#include "base/unguessable_token.h"
#include "third_party/blink/public/common/features.h"
-#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-shared.h"
+#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h"
#include "third_party/blink/public/mojom/frame/navigation_initiator.mojom-blink.h"
#include "third_party/blink/public/mojom/loader/request_context_frame_type.mojom-blink.h"
#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_network_provider.h"
@@ -97,7 +97,7 @@
#include "third_party/blink/renderer/platform/bindings/script_forbidden_scope.h"
#include "third_party/blink/renderer/platform/bindings/v8_dom_activity_logger.h"
#include "third_party/blink/renderer/platform/exported/wrapped_resource_request.h"
-#include "third_party/blink/renderer/platform/instance_counters.h"
+#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher_properties.h"
@@ -111,7 +111,7 @@
#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"
-#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
+#include "third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
@@ -156,9 +156,11 @@ ResourceRequest FrameLoader::ResourceRequestForReload(
// header and instead use a separate member. See https://crbug.com/850813.
if (client_redirect_policy == ClientRedirectPolicy::kClientRedirect) {
request.SetHttpReferrer(SecurityPolicy::GenerateReferrer(
- frame_->GetDocument()->GetReferrerPolicy(),
- frame_->GetDocument()->Url(),
- frame_->GetDocument()->OutgoingReferrer()));
+ frame_->GetDocument()->GetReferrerPolicy(),
+ frame_->GetDocument()->Url(),
+ frame_->GetDocument()->OutgoingReferrer()),
+ ResourceRequest::SetHttpReferrerLocation::
+ kFrameLoaderResourceRequestForReload);
}
request.SetSkipServiceWorker(frame_load_type ==
@@ -204,6 +206,14 @@ void FrameLoader::Init() {
frame_, kWebNavigationTypeOther, std::move(navigation_params),
nullptr /* extra_data */);
provisional_document_loader_->StartLoading();
+ WillCommitNavigation();
+ if (!DetachDocument())
+ return;
+
+ CommitDocumentLoader(provisional_document_loader_.Release());
+
+ // Load the document if needed.
+ document_loader_->StartLoadingResponse();
frame_->GetDocument()->CancelParsing();
@@ -299,21 +309,18 @@ void FrameLoader::DispatchUnloadEvent() {
provisional_document_loader_
? &provisional_document_loader_->GetTiming()
: nullptr);
- // Don't remove event listeners from a transitional empty document (see
- // https://bugs.webkit.org/show_bug.cgi?id=28716 for more information).
- bool keep_event_listeners =
- provisional_document_loader_ &&
- ShouldReuseDefaultView(
- SecurityOrigin::Create(provisional_document_loader_->Url()),
- provisional_document_loader_->GetContentSecurityPolicy());
- if (!keep_event_listeners)
+ // Remove event listeners if we're firing unload events for a reason other
+ // than committing a navigation. In the commit case, we'll determine whether
+ // event listeners should be retained when choosing whether to reuse the
+ // LocalDOMWindow.
+ if (!provisional_document_loader_)
document->RemoveAllEventListenersRecursively();
}
}
void FrameLoader::DidExplicitOpen() {
probe::LifecycleEvent(frame_, GetDocumentLoader(), "init",
- CurrentTimeTicksInSeconds());
+ base::TimeTicks::Now().since_origin().InSecondsF());
// Calling document.open counts as committing the first real document load.
if (!state_machine_.CommittedFirstRealDocumentLoad())
state_machine_.AdvanceTo(FrameLoaderStateMachine::kCommittedFirstRealLoad);
@@ -330,44 +337,6 @@ void FrameLoader::DidExplicitOpen() {
}
}
-// This is only called by ScriptController::executeScriptIfJavaScriptURL and
-// always contains the result of evaluating a javascript: url. This is the
-// <iframe src="javascript:'html'"> case.
-void FrameLoader::ReplaceDocumentWhileExecutingJavaScriptURL(
- const String& source,
- Document* owner_document) {
- Document* document = frame_->GetDocument();
- if (!document_loader_ ||
- document->PageDismissalEventBeingDispatched() != Document::kNoDismissal)
- return;
-
- UseCounter::Count(*document, WebFeature::kReplaceDocumentViaJavaScriptURL);
-
- const KURL& url = document->Url();
-
- document_loader_->StopLoading();
-
- // 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.
- SubframeLoadingDisabler disabler(document);
- // https://html.spec.whatwg.org/C/browsing-the-web.html#unload-a-document
- // The ignore-opens-during-unload counter of the parent Document must be
- // incremented when unloading its descendants.
- IgnoreOpensDuringUnloadCountIncrementer ignore_opens_during_unload(document);
- frame_->DetachChildren();
-
- // detachChildren() potentially detaches or navigates this frame. The load
- // cannot continue in those cases.
- if (!frame_->IsAttached() || document != frame_->GetDocument())
- return;
-
- frame_->GetDocument()->Shutdown();
- Client()->TransitionToCommittedForNewPage();
- document_loader_->ReplaceDocumentWhileExecutingJavaScriptURL(
- url, owner_document, source);
-}
-
void FrameLoader::FinishedParsing() {
if (state_machine_.CreatingInitialEmptyDocument())
return;
@@ -574,10 +543,6 @@ bool FrameLoader::AllowRequestForThisFrame(const FrameLoadRequest& request) {
((frame_->Owner()->GetFramePolicy().sandbox_flags &
WebSandboxFlags::kOrigin) != WebSandboxFlags::kNone))
return false;
-
- frame_->GetDocument()->ProcessJavaScriptUrl(
- url, request.ShouldCheckMainWorldContentSecurityPolicy());
- return false;
}
if (!request.OriginDocument()->GetSecurityOrigin()->CanDisplay(url)) {
@@ -760,6 +725,12 @@ void FrameLoader::StartNavigation(const FrameLoadRequest& passed_request,
return;
}
+ if (url.ProtocolIsJavaScript()) {
+ frame_->GetDocument()->ProcessJavaScriptUrl(
+ url, request.ShouldCheckMainWorldContentSecurityPolicy());
+ return;
+ }
+
bool has_transient_activation =
LocalFrame::HasTransientUserActivation(frame_);
// TODO(csharrison): In M71 when UserActivation v2 should ship, we can remove
@@ -815,27 +786,25 @@ static void FillStaticResponseIfNeeded(WebNavigationParams* params,
// - use it here instead of re-reading from the owner.
// This way we will get rid of extra dependency between starting and
// committing navigation.
- CString encoded_srcdoc;
+ String srcdoc;
HTMLFrameOwnerElement* owner_element = frame->DeprecatedLocalOwner();
if (!IsHTMLIFrameElement(owner_element) ||
!owner_element->FastHasAttribute(html_names::kSrcdocAttr)) {
// Cannot retrieve srcdoc content anymore (perhaps, the attribute was
// cleared) - load empty instead.
} else {
- String srcdoc = owner_element->FastGetAttribute(html_names::kSrcdocAttr);
+ srcdoc = owner_element->FastGetAttribute(html_names::kSrcdocAttr);
DCHECK(!srcdoc.IsNull());
- encoded_srcdoc = srcdoc.Utf8();
}
- WebNavigationParams::FillStaticResponse(
- params, "text/html", "UTF-8",
- base::make_span(encoded_srcdoc.data(), encoded_srcdoc.length()));
+ WebNavigationParams::FillStaticResponse(params, "text/html", "UTF-8",
+ StringUTF8Adaptor(srcdoc));
return;
}
MHTMLArchive* archive = nullptr;
if (auto* parent = DynamicTo<LocalFrame>(frame->Tree().Parent()))
archive = parent->Loader().GetDocumentLoader()->Archive();
- if (archive) {
+ if (archive && !url.ProtocolIsData()) {
// If we have an archive loaded in some ancestor frame, we should
// retrieve document content from that archive. This is different from
// loading an archive into this frame, which will be handled separately
@@ -882,7 +851,8 @@ static bool ShouldNavigate(WebNavigationParams* params, LocalFrame* frame) {
void FrameLoader::CommitNavigation(
std::unique_ptr<WebNavigationParams> navigation_params,
- std::unique_ptr<WebDocumentLoader::ExtraData> extra_data) {
+ std::unique_ptr<WebDocumentLoader::ExtraData> extra_data,
+ bool is_javascript_url) {
DCHECK(frame_->GetDocument());
DCHECK(Client()->HasWebView());
@@ -947,19 +917,36 @@ void FrameLoader::CommitNavigation(
DocumentLoader* provisional_document_loader = Client()->CreateDocumentLoader(
frame_, navigation_type, std::move(navigation_params),
std::move(extra_data));
- if (history_item)
- provisional_document_loader->SetItemForHistoryNavigation(history_item);
- progress_tracker_->ProgressStarted();
- provisional_document_loader_ = provisional_document_loader;
- frame_->GetFrameScheduler()->DidStartProvisionalLoad(frame_->IsMainFrame());
{
- FrameNavigationDisabler navigation_disabler(*frame_);
- Client()->DispatchDidStartProvisionalLoad(provisional_document_loader_);
+ base::AutoReset<bool> scoped_committing(&committing_navigation_, true);
+ if (history_item)
+ provisional_document_loader->SetItemForHistoryNavigation(history_item);
+ if (is_javascript_url)
+ provisional_document_loader->SetLoadingJavaScriptUrl();
+
+ progress_tracker_->ProgressStarted();
+ provisional_document_loader_ = provisional_document_loader;
+ frame_->GetFrameScheduler()->DidStartProvisionalLoad(frame_->IsMainFrame());
+ {
+ FrameNavigationDisabler navigation_disabler(*frame_);
+ Client()->DispatchDidStartProvisionalLoad(provisional_document_loader_);
+ }
+ probe::DidStartProvisionalLoad(frame_);
+ virtual_time_pauser_.PauseVirtualTime();
+
+ provisional_document_loader_->StartLoading();
+ WillCommitNavigation();
+
+ if (!DetachDocument())
+ return;
}
- probe::DidStartProvisionalLoad(frame_);
- virtual_time_pauser_.PauseVirtualTime();
- provisional_document_loader_->StartLoading();
+
+ CommitDocumentLoader(provisional_document_loader_.Release());
+
+ // Load the document if needed.
+ document_loader_->StartLoadingResponse();
+
TakeObjectSnapshot();
}
@@ -1018,7 +1005,7 @@ void FrameLoader::DidAccessInitialDocument() {
}
}
-bool FrameLoader::PrepareForCommit() {
+bool FrameLoader::DetachDocument() {
PluginScriptForbiddenScope forbid_plugin_destructor_scripting;
DocumentLoader* pdl = provisional_document_loader_;
@@ -1066,16 +1053,12 @@ bool FrameLoader::PrepareForCommit() {
// domWindow) since the doc is now detached?
if (frame_->GetDocument())
frame_->GetDocument()->Shutdown();
- document_loader_ = provisional_document_loader_.Release();
- if (document_loader_)
- document_loader_->MarkAsCommitted();
-
- TakeObjectSnapshot();
+ document_loader_ = nullptr;
return true;
}
-void FrameLoader::CommitProvisionalLoad() {
+void FrameLoader::WillCommitNavigation() {
DCHECK(Client()->HasWebView());
// Check if the destination page is allowed to access the previous page's
@@ -1088,9 +1071,14 @@ void FrameLoader::CommitProvisionalLoad() {
security_origin->CanRequest(frame_->GetDocument()->Url()));
}
virtual_time_pauser_.UnpauseVirtualTime();
+}
- if (!PrepareForCommit())
- return;
+void FrameLoader::CommitDocumentLoader(DocumentLoader* document_loader) {
+ document_loader_ = document_loader;
+ CHECK(document_loader_);
+ document_loader_->MarkAsCommitted();
+
+ TakeObjectSnapshot();
Client()->TransitionToCommittedForNewPage();
}
@@ -1225,6 +1213,7 @@ void FrameLoader::Detach() {
DetachDocumentLoader(provisional_document_loader_);
}
ClearClientNavigation();
+ committing_navigation_ = false;
DidFinishNavigation();
if (progress_tracker_) {
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 fc8cd3c855a..5c0c830fb1a 100644
--- a/chromium/third_party/blink/renderer/core/loader/frame_loader.h
+++ b/chromium/third_party/blink/renderer/core/loader/frame_loader.h
@@ -35,7 +35,7 @@
#include "base/macros.h"
#include "third_party/blink/public/common/user_agent/user_agent_metadata.h"
-#include "third_party/blink/public/mojom/loader/request_context_frame_type.mojom-shared.h"
+#include "third_party/blink/public/mojom/loader/request_context_frame_type.mojom-blink.h"
#include "third_party/blink/public/platform/scheduler/web_scoped_virtual_time_pauser.h"
#include "third_party/blink/public/web/web_document_loader.h"
#include "third_party/blink/public/web/web_frame_load_type.h"
@@ -100,7 +100,8 @@ class CORE_EXPORT FrameLoader final {
// See WebNavigationParams for details.
void CommitNavigation(
std::unique_ptr<WebNavigationParams> navigation_params,
- std::unique_ptr<WebDocumentLoader::ExtraData> extra_data);
+ std::unique_ptr<WebDocumentLoader::ExtraData> extra_data,
+ bool is_javascript_url = false);
// Called before the browser process is asked to navigate this frame, to mark
// the frame as loading and save some navigation information for later use.
@@ -118,9 +119,6 @@ class CORE_EXPORT FrameLoader final {
// existence of the frame after StopAllLoaders() returns.
void StopAllLoaders();
- void ReplaceDocumentWhileExecutingJavaScriptURL(const String& source,
- Document* owner_document);
-
// Notifies the client that the initial empty document has been accessed, and
// thus it is no longer safe to show a provisional URL above the document
// without risking a URL spoof. The client must not call back into JavaScript.
@@ -175,12 +173,10 @@ class CORE_EXPORT FrameLoader final {
WebFrameLoadType,
HistoryItem*);
- // This prepares the FrameLoader for the next commit. It will dispatch unload
- // events, abort XHR requests and detach the document. Returns true if the
- // frame is ready to receive the next commit, or false otherwise.
- bool PrepareForCommit();
-
- void CommitProvisionalLoad();
+ // This will attempt to detach the current document. It will dispatch unload
+ // events and abort XHR requests. Returns true if the frame is ready to
+ // receive the next document commit, or false otherwise.
+ bool DetachDocument();
FrameLoaderStateMachine* StateMachine() const { return &state_machine_; }
@@ -194,7 +190,7 @@ class CORE_EXPORT FrameLoader final {
void RestoreScrollPositionAndViewState();
bool HasProvisionalNavigation() const {
- return client_navigation_.get() || provisional_document_loader_.Get();
+ return committing_navigation_ || client_navigation_.get();
}
bool MaybeRenderFallbackContent();
@@ -248,6 +244,11 @@ class CORE_EXPORT FrameLoader final {
std::unique_ptr<TracedValue> ToTracedValue() const;
void TakeObjectSnapshot() const;
+ void WillCommitNavigation();
+
+ // Commits the given |document_loader|.
+ void CommitDocumentLoader(DocumentLoader* document_loader);
+
LocalFrameClient* Client() const;
Member<LocalFrame> frame_;
@@ -284,6 +285,7 @@ class CORE_EXPORT FrameLoader final {
bool dispatching_did_clear_window_object_in_main_world_;
bool detached_;
+ bool committing_navigation_ = false;
WebScopedVirtualTimePauser virtual_time_pauser_;
diff --git a/chromium/third_party/blink/renderer/core/loader/frame_loader_state_machine.h b/chromium/third_party/blink/renderer/core/loader/frame_loader_state_machine.h
index 30913b05573..4e73e2d832c 100644
--- a/chromium/third_party/blink/renderer/core/loader/frame_loader_state_machine.h
+++ b/chromium/third_party/blink/renderer/core/loader/frame_loader_state_machine.h
@@ -32,7 +32,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/loader/frame_resource_fetcher_properties.cc b/chromium/third_party/blink/renderer/core/loader/frame_resource_fetcher_properties.cc
index 0f2d78f5725..89c5589312b 100644
--- a/chromium/third_party/blink/renderer/core/loader/frame_resource_fetcher_properties.cc
+++ b/chromium/third_party/blink/renderer/core/loader/frame_resource_fetcher_properties.cc
@@ -43,7 +43,7 @@ FrameResourceFetcherProperties::GetControllerServiceWorkerMode() const {
.GetServiceWorkerNetworkProvider();
if (!service_worker_network_provider)
return blink::mojom::ControllerServiceWorkerMode::kNoController;
- return service_worker_network_provider->IsControlledByServiceWorker();
+ return service_worker_network_provider->GetControllerServiceWorkerMode();
}
int64_t FrameResourceFetcherProperties::ServiceWorkerId() const {
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 974a37c6093..b96d132faaa 100644
--- a/chromium/third_party/blink/renderer/core/loader/history_item.cc
+++ b/chromium/third_party/blink/renderer/core/loader/history_item.cc
@@ -34,7 +34,6 @@
#include "third_party/blink/renderer/platform/network/encoded_form_data.h"
#include "third_party/blink/renderer/platform/weborigin/security_policy.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
-#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
namespace blink {
@@ -42,7 +41,8 @@ namespace blink {
static int64_t GenerateSequenceNumber() {
// Initialize to the current time to reduce the likelihood of generating
// identifiers that overlap with those from past/future browser sessions.
- static int64_t next = static_cast<int64_t>(CurrentTime() * 1000000.0);
+ static int64_t next =
+ static_cast<int64_t>(base::Time::Now().ToDoubleT() * 1000000.0);
return ++next;
}
@@ -152,9 +152,12 @@ EncodedFormData* HistoryItem::FormData() {
ResourceRequest HistoryItem::GenerateResourceRequest(
mojom::FetchCacheMode cache_mode) {
ResourceRequest request(url_string_);
- // 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_);
+ request.SetReferrerString(
+ referrer_.referrer,
+ ResourceRequest::SetReferrerStringLocation::kHistoryItem);
+ request.SetReferrerPolicy(
+ referrer_.referrer_policy,
+ ResourceRequest::SetReferrerPolicyLocation::kHistoryItem);
request.SetCacheMode(cache_mode);
if (form_data_) {
request.SetHttpMethod(http_names::kPOST);
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 4a0a62fae0e..7e185ab7309 100644
--- a/chromium/third_party/blink/renderer/core/loader/http_equiv.cc
+++ b/chromium/third_party/blink/renderer/core/loader/http_equiv.cc
@@ -12,11 +12,11 @@
#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/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/private/frame_client_hints_preferences_context.h"
#include "third_party/blink/renderer/core/origin_trials/origin_trial_context.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/loader/fetch/client_hints_preferences.h"
#include "third_party/blink/renderer/platform/network/http_names.h"
#include "third_party/blink/renderer/platform/network/http_parsers.h"
@@ -57,7 +57,7 @@ bool AllowScriptFromSourceWithoutNotifying(
// Notifies content settings client of persistent client hint headers.
void NotifyPersistentClientHintsToContentSettingsClient(Document& document) {
- TimeDelta persist_duration =
+ base::TimeDelta persist_duration =
document.GetFrame()->GetClientHintsPreferences().GetPersistDuration();
if (persist_duration.InSeconds() <= 0)
return;
@@ -122,7 +122,7 @@ void HttpEquiv::Process(Document& document,
document.GetContentSecurityPolicy()->ReportMetaOutsideHead(content);
} else if (EqualIgnoringASCIICase(equiv, http_names::kOriginTrial)) {
if (in_document_head_element)
- OriginTrialContext::FromOrCreate(&document)->AddToken(content);
+ document.GetOriginTrialContext()->AddToken(content);
}
}
@@ -197,21 +197,11 @@ void HttpEquiv::ProcessHttpEquivRefresh(Document& document,
void HttpEquiv::ProcessHttpEquivSetCookie(Document& document,
const AtomicString& content,
Element* element) {
- Deprecation::CountDeprecation(document, WebFeature::kMetaSetCookie);
-
- if (!document.GetContentSecurityPolicy()->AllowInline(
- ContentSecurityPolicy::InlineType::kScript, element, "" /* content */,
- "" /* nonce */, NullURL(), OrdinalNumber(),
- SecurityViolationReportingPolicy::kSuppressReporting)) {
- UseCounter::Count(document,
- WebFeature::kMetaSetCookieWhenCSPBlocksInlineScript);
- }
-
document.AddConsoleMessage(ConsoleMessage::Create(
mojom::ConsoleMessageSource::kSecurity,
mojom::ConsoleMessageLevel::kError,
String::Format("Blocked setting the `%s` cookie from a `<meta>` tag.",
- content.Utf8().data())));
+ content.Utf8().c_str())));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/loader/http_equiv.h b/chromium/third_party/blink/renderer/core/loader/http_equiv.h
index f590063d690..5074adc1901 100644
--- a/chromium/third_party/blink/renderer/core/loader/http_equiv.h
+++ b/chromium/third_party/blink/renderer/core/loader/http_equiv.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_HTTP_EQUIV_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_HTTP_EQUIV_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/loader/http_refresh_scheduler.cc b/chromium/third_party/blink/renderer/core/loader/http_refresh_scheduler.cc
index 7e5279863db..d5ccaf2c9f5 100644
--- a/chromium/third_party/blink/renderer/core/loader/http_refresh_scheduler.cc
+++ b/chromium/third_party/blink/renderer/core/loader/http_refresh_scheduler.cc
@@ -124,7 +124,7 @@ void HttpRefreshScheduler::MaybeStartTimer() {
navigate_task_handle_ = PostDelayedCancellableTask(
*document_->GetTaskRunner(TaskType::kInternalLoading), FROM_HERE,
WTF::Bind(&HttpRefreshScheduler::NavigateTask, WrapWeakPersistent(this)),
- TimeDelta::FromSecondsD(refresh_->delay));
+ base::TimeDelta::FromSecondsD(refresh_->delay));
probe::FrameScheduledNavigation(document_->GetFrame(), refresh_->url,
refresh_->delay, refresh_->reason);
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 56c3d7ad15b..8b7c8557e5e 100644
--- a/chromium/third_party/blink/renderer/core/loader/idleness_detector.cc
+++ b/chromium/third_party/blink/renderer/core/loader/idleness_detector.cc
@@ -5,6 +5,7 @@
#include "third_party/blink/renderer/core/loader/idleness_detector.h"
#include "base/logging.h"
+#include "base/time/default_tick_clock.h"
#include "services/resource_coordinator/public/cpp/resource_coordinator_features.h"
#include "third_party/blink/public/platform/modules/service_worker/web_service_worker_network_provider.h"
#include "third_party/blink/public/platform/platform.h"
@@ -21,8 +22,8 @@
namespace blink {
-constexpr TimeDelta IdlenessDetector::kNetworkQuietWindow;
-constexpr TimeDelta IdlenessDetector::kNetworkQuietWatchdog;
+constexpr base::TimeDelta IdlenessDetector::kNetworkQuietWindow;
+constexpr base::TimeDelta IdlenessDetector::kNetworkQuietWatchdog;
void IdlenessDetector::Shutdown() {
Stop();
@@ -32,10 +33,10 @@ void IdlenessDetector::Shutdown() {
void IdlenessDetector::WillCommitLoad() {
in_network_2_quiet_period_ = false;
in_network_0_quiet_period_ = false;
- network_2_quiet_ = TimeTicks();
- network_0_quiet_ = TimeTicks();
- network_2_quiet_start_time_ = TimeTicks();
- network_0_quiet_start_time_ = TimeTicks();
+ network_2_quiet_ = base::TimeTicks();
+ network_0_quiet_ = base::TimeTicks();
+ network_2_quiet_start_time_ = base::TimeTicks();
+ network_0_quiet_start_time_ = base::TimeTicks();
}
void IdlenessDetector::DomContentLoadedEventFired() {
@@ -49,8 +50,8 @@ void IdlenessDetector::DomContentLoadedEventFired() {
in_network_2_quiet_period_ = true;
in_network_0_quiet_period_ = true;
- network_2_quiet_ = TimeTicks();
- network_0_quiet_ = TimeTicks();
+ network_2_quiet_ = base::TimeTicks();
+ network_0_quiet_ = base::TimeTicks();
OnDidLoadResource();
}
@@ -67,9 +68,9 @@ void IdlenessDetector::OnWillSendRequest(ResourceFetcher* fetcher) {
int request_count = fetcher->ActiveRequestCount() + 1;
// If we are above the allowed number of active requests, reset timers.
if (in_network_2_quiet_period_ && request_count > 2)
- network_2_quiet_ = TimeTicks();
+ network_2_quiet_ = base::TimeTicks();
if (in_network_0_quiet_period_ && request_count > 0)
- network_0_quiet_ = TimeTicks();
+ network_0_quiet_ = base::TimeTicks();
}
// This function is called when the number of active connections is decreased.
@@ -93,7 +94,7 @@ void IdlenessDetector::OnDidLoadResource() {
if (request_count > 2)
return;
- TimeTicks timestamp = CurrentTimeTicks();
+ base::TimeTicks timestamp = clock_->NowTicks();
// Arriving at =2 updates the quiet_2 base timestamp.
// Arriving at <2 sets the quiet_2 base timestamp only if
// it was not already set.
@@ -116,7 +117,7 @@ void IdlenessDetector::OnDidLoadResource() {
}
}
-TimeTicks IdlenessDetector::GetNetworkAlmostIdleTime() {
+base::TimeTicks IdlenessDetector::GetNetworkAlmostIdleTime() {
return network_2_quiet_start_time_;
}
@@ -127,13 +128,13 @@ bool IdlenessDetector::NetworkIsAlmostIdle() {
return false;
if (network_2_quiet_start_time_.is_null())
return false;
- TimeTicks current_time = TimeTicks::Now();
+ base::TimeTicks current_time = base::TimeTicks::Now();
if (current_time - network_2_quiet_start_time_ <= network_quiet_window_)
return false;
return true;
}
-TimeTicks IdlenessDetector::GetNetworkIdleTime() {
+base::TimeTicks IdlenessDetector::GetNetworkIdleTime() {
return network_0_quiet_start_time_;
}
@@ -151,7 +152,6 @@ void IdlenessDetector::WillProcessTask(base::TimeTicks start_time) {
local_frame_->GetDocument()->GetResourceCoordinator()) {
document_resource_coordinator->SetNetworkAlmostIdle();
}
- local_frame_->GetDocument()->Fetcher()->OnNetworkQuiet();
if (WebServiceWorkerNetworkProvider* service_worker_network_provider =
loader->GetServiceWorkerNetworkProvider()) {
service_worker_network_provider->DispatchNetworkQuiet();
@@ -165,7 +165,7 @@ void IdlenessDetector::WillProcessTask(base::TimeTicks start_time) {
}
}
in_network_2_quiet_period_ = false;
- network_2_quiet_ = TimeTicks();
+ network_2_quiet_ = base::TimeTicks();
}
if (in_network_0_quiet_period_ && !network_0_quiet_.is_null() &&
@@ -173,10 +173,8 @@ void IdlenessDetector::WillProcessTask(base::TimeTicks start_time) {
probe::LifecycleEvent(
local_frame_, loader, "networkIdle",
network_0_quiet_start_time_.since_origin().InSecondsF());
- FirstMeaningfulPaintDetector::From(*local_frame_->GetDocument())
- .OnNetwork0Quiet();
in_network_0_quiet_period_ = false;
- network_0_quiet_ = TimeTicks();
+ network_0_quiet_ = base::TimeTicks();
}
if (!in_network_0_quiet_period_ && !in_network_2_quiet_period_)
@@ -192,15 +190,17 @@ void IdlenessDetector::DidProcessTask(base::TimeTicks start_time,
network_0_quiet_ += end_time - start_time;
}
-IdlenessDetector::IdlenessDetector(LocalFrame* local_frame)
+IdlenessDetector::IdlenessDetector(LocalFrame* local_frame,
+ const base::TickClock* clock)
: local_frame_(local_frame),
task_observer_added_(false),
+ clock_(clock),
network_quiet_timer_(
local_frame->GetTaskRunner(TaskType::kInternalLoading),
this,
&IdlenessDetector::NetworkQuietTimerFired) {
if (local_frame->GetSettings()) {
- network_quiet_window_ = TimeDelta::FromSecondsD(
+ network_quiet_window_ = base::TimeDelta::FromSecondsD(
local_frame->GetSettings()->GetNetworkQuietTimeout());
}
}
diff --git a/chromium/third_party/blink/renderer/core/loader/idleness_detector.h b/chromium/third_party/blink/renderer/core/loader/idleness_detector.h
index 2997d44eca8..6ea918e0586 100644
--- a/chromium/third_party/blink/renderer/core/loader/idleness_detector.h
+++ b/chromium/third_party/blink/renderer/core/loader/idleness_detector.h
@@ -7,6 +7,7 @@
#include "base/macros.h"
#include "base/task/sequence_manager/task_time_observer.h"
+#include "base/time/default_tick_clock.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/timer.h"
@@ -25,7 +26,9 @@ class CORE_EXPORT IdlenessDetector
: public GarbageCollectedFinalized<IdlenessDetector>,
public base::sequence_manager::TaskTimeObserver {
public:
- explicit IdlenessDetector(LocalFrame*);
+ IdlenessDetector(
+ LocalFrame*,
+ const base::TickClock* = base::DefaultTickClock::GetInstance());
void Shutdown();
void WillCommitLoad();
@@ -35,8 +38,8 @@ class CORE_EXPORT IdlenessDetector
void OnWillSendRequest(ResourceFetcher*);
void OnDidLoadResource();
- TimeTicks GetNetworkAlmostIdleTime();
- TimeTicks GetNetworkIdleTime();
+ base::TimeTicks GetNetworkAlmostIdleTime();
+ base::TimeTicks GetNetworkIdleTime();
bool NetworkIsAlmostIdle();
void Trace(blink::Visitor*);
@@ -46,9 +49,10 @@ class CORE_EXPORT IdlenessDetector
// The page is quiet if there are no more than 2 active network requests for
// this duration of time.
- static constexpr TimeDelta kNetworkQuietWindow =
- TimeDelta::FromMilliseconds(500);
- static constexpr TimeDelta kNetworkQuietWatchdog = TimeDelta::FromSeconds(2);
+ static constexpr base::TimeDelta kNetworkQuietWindow =
+ base::TimeDelta::FromMilliseconds(500);
+ static constexpr base::TimeDelta kNetworkQuietWatchdog =
+ base::TimeDelta::FromSeconds(2);
static constexpr int kNetworkQuietMaximumConnections = 2;
// TaskTimeObserver implementation.
@@ -65,13 +69,15 @@ class CORE_EXPORT IdlenessDetector
bool in_network_0_quiet_period_ = true;
bool in_network_2_quiet_period_ = true;
- TimeDelta network_quiet_window_ = kNetworkQuietWindow;
+ const base::TickClock* clock_;
+
+ base::TimeDelta network_quiet_window_ = kNetworkQuietWindow;
// Store the accumulated time of network quiet.
- TimeTicks network_0_quiet_;
- TimeTicks network_2_quiet_;
+ base::TimeTicks network_0_quiet_;
+ base::TimeTicks network_2_quiet_;
// Record the actual start time of network quiet.
- TimeTicks network_0_quiet_start_time_;
- TimeTicks network_2_quiet_start_time_;
+ base::TimeTicks network_0_quiet_start_time_;
+ base::TimeTicks network_2_quiet_start_time_;
TaskRunnerTimer<IdlenessDetector> network_quiet_timer_;
DISALLOW_COPY_AND_ASSIGN(IdlenessDetector);
diff --git a/chromium/third_party/blink/renderer/core/loader/idleness_detector_test.cc b/chromium/third_party/blink/renderer/core/loader/idleness_detector_test.cc
index fa7542d5eb4..eeba80ebbea 100644
--- a/chromium/third_party/blink/renderer/core/loader/idleness_detector_test.cc
+++ b/chromium/third_party/blink/renderer/core/loader/idleness_detector_test.cc
@@ -6,14 +6,15 @@
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/core/testing/page_test_base.h"
-#include "third_party/blink/renderer/platform/testing/testing_platform_support_with_mock_scheduler.h"
namespace blink {
class IdlenessDetectorTest : public PageTestBase {
protected:
void SetUp() override {
- platform_time_ = CurrentTimeTicks();
+ EnablePlatform();
+ auto task_runner = platform()->test_task_runner();
+ platform_time_ = task_runner->NowTicks();
DCHECK(!platform_time_.is_null());
PageTestBase::SetUp();
}
@@ -31,14 +32,14 @@ class IdlenessDetectorTest : public PageTestBase {
void WillProcessTask(base::TimeTicks start_time) {
DCHECK(start_time >= platform_time_);
- platform_->AdvanceClock(start_time - platform_time_);
+ platform()->AdvanceClock(start_time - platform_time_);
platform_time_ = start_time;
Detector()->WillProcessTask(start_time);
}
void DidProcessTask(base::TimeTicks start_time, base::TimeTicks end_time) {
DCHECK(start_time < end_time);
- platform_->AdvanceClock(end_time - start_time);
+ platform()->AdvanceClock(end_time - start_time);
platform_time_ = end_time;
Detector()->DidProcessTask(start_time, end_time);
}
@@ -47,9 +48,6 @@ class IdlenessDetectorTest : public PageTestBase {
return base::TimeTicks() + base::TimeDelta::FromSecondsD(seconds);
}
- ScopedTestingPlatformSupport<TestingPlatformSupportWithMockScheduler>
- platform_;
-
private:
base::TimeTicks platform_time_;
};
@@ -86,7 +84,7 @@ TEST_F(IdlenessDetectorTest, NetworkQuietWatchdogTimerFired) {
WillProcessTask(SecondsToTimeTicks(1));
DidProcessTask(SecondsToTimeTicks(1), SecondsToTimeTicks(1.01));
- platform_->RunForPeriodSeconds(3);
+ platform()->RunForPeriodSeconds(3);
EXPECT_FALSE(IsNetworkQuietTimerActive());
EXPECT_TRUE(HadNetworkQuiet());
}
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 6701f3ff8ef..2f53751c117 100644
--- a/chromium/third_party/blink/renderer/core/loader/image_loader.cc
+++ b/chromium/third_party/blink/renderer/core/loader/image_loader.cc
@@ -25,7 +25,7 @@
#include <memory>
#include <utility>
-#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-shared.h"
+#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h"
#include "third_party/blink/public/platform/web_client_hints_type.h"
#include "third_party/blink/public/platform/web_url_request.h"
#include "third_party/blink/renderer/bindings/core/v8/script_controller.h"
@@ -42,7 +42,6 @@
#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/html/cross_origin_attribute.h"
#include "third_party/blink/renderer/core/html/html_image_element.h"
#include "third_party/blink/renderer/core/html/lazy_load_image_observer.h"
@@ -59,6 +58,7 @@
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/bindings/v8_per_isolate_data.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.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_fetcher.h"
@@ -88,6 +88,7 @@ LoadingAttrValue GetLoadingAttrValue(const HTMLImageElement& html_image) {
? LoadingAttrValue::kLazy
: LoadingAttrValue::kAuto;
}
+
LazyLoadImageEligibility DetermineLazyLoadImageEligibility(
const LocalFrame& frame,
const HTMLImageElement& html_image,
@@ -195,8 +196,7 @@ class ImageLoader::Task {
should_bypass_main_world_csp_(ShouldBypassMainWorldCSP(loader)),
update_behavior_(update_behavior),
referrer_policy_(referrer_policy),
- request_url_(request_url),
- weak_factory_(this) {
+ request_url_(request_url) {
ExecutionContext& context = loader_->GetElement()->GetDocument();
probe::AsyncTaskScheduled(&context, "Image", this);
v8::Isolate* isolate = V8PerIsolateData::MainThreadIsolate();
@@ -244,7 +244,7 @@ class ImageLoader::Task {
WeakPersistent<ScriptState> script_state_;
network::mojom::ReferrerPolicy referrer_policy_;
KURL request_url_;
- base::WeakPtrFactory<Task> weak_factory_;
+ base::WeakPtrFactory<Task> weak_factory_{this};
};
ImageLoader::ImageLoader(Element* element)
@@ -360,7 +360,8 @@ void ImageLoader::SetImageForTest(ImageResourceContent* new_image) {
}
bool ImageLoader::ShouldUpdateOnInsertedInto(
- ContainerNode& insertion_point) const {
+ ContainerNode& insertion_point,
+ network::mojom::ReferrerPolicy referrer_policy) const {
// If we're being inserted into a disconnected tree, we don't need to update.
if (!insertion_point.isConnected())
return false;
@@ -372,10 +373,41 @@ bool ImageLoader::ShouldUpdateOnInsertedInto(
if (element_->GetDocument().ValidBaseElementURL() != last_base_element_url_)
return true;
- // Finally, try to update if we're idle (that is, we have neither the image
- // contents nor any activity). This could be an indication that we skipped a
- // previous load when inserted into an inactive document.
- return !image_content_ && !HasPendingActivity();
+ // If we already have image content, then we don't need an update.
+ if (image_content_)
+ return false;
+
+ // Finally, try to update if we're idle. This could be an indication that we
+ // skipped a previous load when inserted into an inactive document. Note that
+ // if we're not idle, we should also update our referrer policy if it has
+ // changed.
+ return !HasPendingActivity() || referrer_policy != last_referrer_policy_;
+}
+
+bool ImageLoader::ImageIsPotentiallyAvailable() const {
+ bool image_has_loaded = image_content_ && !image_content_->IsLoading() &&
+ !image_content_->ErrorOccurred();
+ bool image_still_loading = !image_has_loaded && HasPendingActivity() &&
+ !HasPendingError() &&
+ !element_->ImageSourceURL().IsEmpty();
+ bool image_has_image = image_content_ && image_content_->HasImage();
+ bool image_is_document = loading_image_document_ && image_content_ &&
+ !image_content_->ErrorOccurred();
+
+ // Icky special case for deferred images:
+ // A deferred image is not loading, does have pending activity, does not
+ // have an error, but it does have an ImageResourceContent associated
+ // with it, so |image_has_loaded| will be true even though the image hasn't
+ // actually loaded. Fixing the definition of |image_has_loaded| isn't
+ // sufficient, because a deferred image does have pending activity, does not
+ // have a pending error, and does have a source URL, so if |image_has_loaded|
+ // was correct, |image_still_loading| would become wrong.
+ //
+ // Instead of dealing with that, there's a separate check that the
+ // ImageResourceContent has non-null image data associated with it, which
+ // isn't folded into |image_has_loaded| above.
+ return (image_has_loaded && image_has_image) || image_still_loading ||
+ image_is_document;
}
void ImageLoader::ClearImage() {
@@ -548,7 +580,9 @@ void ImageLoader::DoUpdateFromElement(
resource_request.SetPreviewsState(WebURLRequest::kPreviewsNoTransform);
}
- resource_request.SetReferrerPolicy(referrer_policy);
+ resource_request.SetReferrerPolicy(
+ referrer_policy,
+ ResourceRequest::SetReferrerPolicyLocation::kImageLoader);
// Correct the RequestContext if necessary.
if (IsHTMLPictureElement(GetElement()->parentNode()) ||
@@ -592,17 +626,16 @@ void ImageLoader::DoUpdateFromElement(
const LazyLoadImageEligibility lazy_load_image_eligibility =
DetermineLazyLoadImageEligibility(*frame, *html_image,
params.Url());
- const auto lazy_load_image_enabled_state =
- frame->GetLazyLoadImageEnabledState();
+ const auto lazy_load_image_setting = frame->GetLazyLoadImageSetting();
if ((lazy_load_image_eligibility ==
LazyLoadImageEligibility::kEnabledExplicit &&
- lazy_load_image_enabled_state !=
- LocalFrame::LazyLoadImageEnabledState::kDisabled) ||
+ lazy_load_image_setting !=
+ LocalFrame::LazyLoadImageSetting::kDisabled) ||
(lazy_load_image_eligibility ==
LazyLoadImageEligibility::kEnabledAutomatic &&
- lazy_load_image_enabled_state ==
- LocalFrame::LazyLoadImageEnabledState::kEnabledAutomatic)) {
+ lazy_load_image_setting ==
+ LocalFrame::LazyLoadImageSetting::kEnabledAutomatic)) {
if ((was_fully_deferred_ =
!RuntimeEnabledFeatures::
LazyImageLoadingMetadataFetchEnabled() ||
@@ -629,7 +662,7 @@ void ImageLoader::DoUpdateFromElement(
}
// If the image was previously set to full image and had no dimensions, it
- // // is a full load of a placeholder image.
+ // is a full load of a placeholder image.
if (!was_fully_deferred_ &&
lazy_image_load_state_ == LazyImageLoadState::kFullImage) {
params.SetLazyImageAutoReload();
@@ -660,6 +693,13 @@ void ImageLoader::DoUpdateFromElement(
new_image_content == old_image_content) {
ToLayoutImage(element_->GetLayoutObject())->IntrinsicSizeChanged();
} else {
+ // Loading didn't start (loading of images was disabled). We show fallback
+ // contents here, while we don't dispatch an 'error' event etc., because
+ // spec-wise the image remains in the "Unavailable" state.
+ if (new_image_content &&
+ new_image_content->GetContentStatus() == ResourceStatus::kNotStarted)
+ NoImageResourceToLoad();
+
if (pending_load_event_.IsActive())
pending_load_event_.Cancel();
@@ -697,6 +737,7 @@ void ImageLoader::UpdateFromElement(
suppress_error_events_ = (update_behavior == kUpdateSizeChanged);
last_base_element_url_ =
element_->GetDocument().ValidBaseElementURL().GetString();
+ last_referrer_policy_ = referrer_policy;
if (update_behavior == kUpdateIgnorePreviousError)
ClearFailedLoadURL();
@@ -722,8 +763,7 @@ void ImageLoader::UpdateFromElement(
// ImageResource to be populated later.
if (loading_image_document_) {
ResourceRequest request(url);
- request.SetFetchCredentialsMode(
- network::mojom::FetchCredentialsMode::kOmit);
+ request.SetCredentialsMode(network::mojom::CredentialsMode::kOmit);
ImageResource* image_resource = ImageResource::Create(request);
image_resource->NotifyStartLoad();
SetImageForImageDocument(image_resource);
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 5f462884311..ffea35f5fd3 100644
--- a/chromium/third_party/blink/renderer/core/loader/image_loader.h
+++ b/chromium/third_party/blink/renderer/core/loader/image_loader.h
@@ -90,7 +90,15 @@ class CORE_EXPORT ImageLoader : public GarbageCollectedFinalized<ImageLoader>,
// Returns true if this loader should be updated via UpdateFromElement() when
// being inserted into a new parent; returns false otherwise.
- bool ShouldUpdateOnInsertedInto(ContainerNode& insertion_point) const;
+ bool ShouldUpdateOnInsertedInto(
+ ContainerNode& insertion_point,
+ network::mojom::ReferrerPolicy referrer_policy =
+ network::mojom::ReferrerPolicy::kDefault) const;
+
+ // Returns true if a the owner of this loader should consider the image being
+ // loaded as "potentially available", i.e that it may eventually become
+ // available.
+ bool ImageIsPotentiallyAvailable() const;
// Cancels pending load events, and doesn't dispatch new ones.
// Note: ClearImage/SetImage.*() are not a simple setter.
@@ -110,7 +118,6 @@ class CORE_EXPORT ImageLoader : public GarbageCollectedFinalized<ImageLoader>,
// Otherwise:
// Normal loading via ResourceFetcher/ResourceLoader.
// |image_resource_for_image_document_| is null.
- bool IsLoadingImageDocument() { return loading_image_document_; }
void SetLoadingImageDocument() { loading_image_document_ = true; }
ImageResource* ImageResourceForImageDocument() const {
return image_resource_for_image_document_;
@@ -208,6 +215,8 @@ class CORE_EXPORT ImageLoader : public GarbageCollectedFinalized<ImageLoader>,
Member<ImageResource> image_resource_for_image_document_;
String last_base_element_url_;
+ network::mojom::ReferrerPolicy last_referrer_policy_ =
+ network::mojom::ReferrerPolicy::kDefault;
AtomicString failed_load_url_;
base::WeakPtr<Task> pending_task_; // owned by Microtask
std::unique_ptr<IncrementLoadEventDelayCount>
diff --git a/chromium/third_party/blink/renderer/core/loader/image_loader_test.cc b/chromium/third_party/blink/renderer/core/loader/image_loader_test.cc
new file mode 100644
index 00000000000..95d02c94f77
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/loader/image_loader_test.cc
@@ -0,0 +1,52 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/loader/image_loader.h"
+
+#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/renderer/core/html/html_image_loader.h"
+#include "third_party/blink/renderer/core/testing/core_unit_test_helper.h"
+
+namespace blink {
+
+class ImageLoaderTest : public RenderingTest {};
+
+TEST_F(ImageLoaderTest, ReferrerPolicyChangeCausesUpdateOnInsert) {
+ SetHtmlInnerHTML(R"HTML(
+ <img id="test" src="test.png">
+ )HTML");
+
+ auto* element = GetDocument().getElementById("test");
+ ASSERT_TRUE(element);
+
+ auto* loader = MakeGarbageCollected<HTMLImageLoader>(element);
+ ASSERT_TRUE(loader);
+
+ // We should already be collected, so UpdateFromElement() would cause some
+ // pending activity.
+ loader->UpdateFromElement();
+ ASSERT_TRUE(loader->HasPendingActivity());
+
+ // We don't need an update, since we're already loading an image.
+ EXPECT_FALSE(loader->ShouldUpdateOnInsertedInto(*element));
+
+ // However, if the referrer policy changes, then we should need an update.
+ EXPECT_TRUE(loader->ShouldUpdateOnInsertedInto(
+ *element, network::mojom::ReferrerPolicy::kNever));
+
+ // Changing referrer policy.
+ loader->UpdateFromElement(ImageLoader::kUpdateNormal,
+ network::mojom::ReferrerPolicy::kNever);
+
+ // Now, we don't need an update with the latest referrer policy.
+ EXPECT_FALSE(loader->ShouldUpdateOnInsertedInto(
+ *element, network::mojom::ReferrerPolicy::kNever));
+
+ // But we do want an update if the referrer policy changes back to what it was
+ // before.
+ EXPECT_TRUE(loader->ShouldUpdateOnInsertedInto(
+ *element, network::mojom::ReferrerPolicy::kDefault));
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/loader/importance_attribute.h b/chromium/third_party/blink/renderer/core/loader/importance_attribute.h
index 859102e4217..92f8aa29a60 100644
--- a/chromium/third_party/blink/renderer/core/loader/importance_attribute.h
+++ b/chromium/third_party/blink/renderer/core/loader/importance_attribute.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_IMPORTANCE_ATTRIBUTE_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_IMPORTANCE_ATTRIBUTE_H_
-#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-shared.h"
+#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
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 016389ea171..b63032a0557 100644
--- a/chromium/third_party/blink/renderer/core/loader/interactive_detector.cc
+++ b/chromium/third_party/blink/renderer/core/loader/interactive_detector.cc
@@ -9,7 +9,7 @@
#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/loader/document_loader.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
@@ -18,7 +18,7 @@ namespace blink {
// Required length of main thread and network quiet window for determining
// Time to Interactive.
-constexpr auto kTimeToInteractiveWindow = TimeDelta::FromSeconds(5);
+constexpr auto kTimeToInteractiveWindow = base::TimeDelta::FromSeconds(5);
// Network is considered "quiet" if there are no more than 2 active network
// requests for this duration of time.
constexpr int kNetworkQuietMaximumConnections = 2;
@@ -59,7 +59,7 @@ InteractiveDetector::InteractiveDetector(
initially_hidden_(document.hidden()) {}
void InteractiveDetector::SetNavigationStartTime(
- TimeTicks navigation_start_time) {
+ base::TimeTicks navigation_start_time) {
// Should not set nav start twice.
DCHECK(page_event_times_.nav_start.is_null());
@@ -70,7 +70,7 @@ void InteractiveDetector::SetNavigationStartTime(
LongTaskDetector::Instance().RegisterObserver(this);
page_event_times_.nav_start = navigation_start_time;
- TimeTicks initial_timer_fire_time =
+ base::TimeTicks initial_timer_fire_time =
navigation_start_time + kTimeToInteractiveWindow;
active_main_thread_quiet_window_start_ = navigation_start_time;
@@ -88,24 +88,25 @@ int InteractiveDetector::ActiveConnections() {
return network_activity_checker_->GetActiveConnections();
}
-void InteractiveDetector::StartOrPostponeCITimer(TimeTicks timer_fire_time) {
+void InteractiveDetector::StartOrPostponeCITimer(
+ base::TimeTicks timer_fire_time) {
// This function should never be called after Time To Interactive is
// reached.
DCHECK(interactive_time_.is_null());
// We give 1ms extra padding to the timer fire time to prevent floating point
// arithmetic pitfalls when comparing window sizes.
- timer_fire_time += TimeDelta::FromMilliseconds(1);
+ timer_fire_time += base::TimeDelta::FromMilliseconds(1);
// Return if there is an active timer scheduled to fire later than
// |timer_fire_time|.
if (timer_fire_time < time_to_interactive_timer_fire_time_)
return;
- TimeDelta delay = timer_fire_time - clock_->NowTicks();
+ base::TimeDelta delay = timer_fire_time - clock_->NowTicks();
time_to_interactive_timer_fire_time_ = timer_fire_time;
- if (delay <= TimeDelta()) {
+ if (delay <= base::TimeDelta()) {
// This argument of this function is never used and only there to fulfill
// the API contract. nullptr should work fine.
TimeToInteractiveTimerFired(nullptr);
@@ -114,50 +115,51 @@ void InteractiveDetector::StartOrPostponeCITimer(TimeTicks timer_fire_time) {
}
}
-TimeTicks InteractiveDetector::GetInteractiveTime() const {
+base::TimeTicks InteractiveDetector::GetInteractiveTime() const {
// TODO(crbug.com/808685) Simplify FMP and TTI input invalidation.
return page_event_times_.first_meaningful_paint_invalidated
- ? TimeTicks()
+ ? base::TimeTicks()
: interactive_time_;
}
-TimeTicks InteractiveDetector::GetInteractiveDetectionTime() const {
+base::TimeTicks InteractiveDetector::GetInteractiveDetectionTime() const {
// TODO(crbug.com/808685) Simplify FMP and TTI input invalidation.
return page_event_times_.first_meaningful_paint_invalidated
- ? TimeTicks()
+ ? base::TimeTicks()
: interactive_detection_time_;
}
-TimeTicks InteractiveDetector::GetFirstInvalidatingInputTime() const {
+base::TimeTicks InteractiveDetector::GetFirstInvalidatingInputTime() const {
return page_event_times_.first_invalidating_input;
}
-TimeDelta InteractiveDetector::GetFirstInputDelay() const {
+base::TimeDelta InteractiveDetector::GetFirstInputDelay() const {
return page_event_times_.first_input_delay;
}
-TimeTicks InteractiveDetector::GetFirstInputTimestamp() const {
+base::TimeTicks InteractiveDetector::GetFirstInputTimestamp() const {
return page_event_times_.first_input_timestamp;
}
-TimeDelta InteractiveDetector::GetLongestInputDelay() const {
+base::TimeDelta InteractiveDetector::GetLongestInputDelay() const {
return page_event_times_.longest_input_delay;
}
-TimeTicks InteractiveDetector::GetLongestInputTimestamp() const {
+base::TimeTicks InteractiveDetector::GetLongestInputTimestamp() const {
return page_event_times_.longest_input_timestamp;
}
-bool InteractiveDetector::PageWasBackgroundedSinceEvent(TimeTicks event_time) {
+bool InteractiveDetector::PageWasBackgroundedSinceEvent(
+ base::TimeTicks event_time) {
DCHECK(GetSupplementable());
if (GetSupplementable()->hidden()) {
return true;
}
bool curr_hidden = initially_hidden_;
- TimeTicks visibility_start = page_event_times_.nav_start;
+ base::TimeTicks visibility_start = page_event_times_.nav_start;
for (auto change_event : visibility_change_events_) {
- TimeTicks visibility_end = change_event.timestamp;
+ base::TimeTicks visibility_end = change_event.timestamp;
if (curr_hidden && event_time < visibility_end) {
// [event_time, now] intersects a backgrounded range.
return true;
@@ -171,8 +173,8 @@ bool InteractiveDetector::PageWasBackgroundedSinceEvent(TimeTicks event_time) {
void InteractiveDetector::HandleForInputDelay(
const Event& event,
- TimeTicks event_platform_timestamp,
- TimeTicks processing_start) {
+ base::TimeTicks event_platform_timestamp,
+ base::TimeTicks processing_start) {
DCHECK(event.isTrusted());
// This only happens sometimes on tests unrelated to InteractiveDetector. It
@@ -199,8 +201,8 @@ void InteractiveDetector::HandleForInputDelay(
return;
// These variables track the values which will be reported to histograms.
- TimeDelta delay;
- TimeTicks event_timestamp;
+ base::TimeDelta delay;
+ base::TimeTicks event_timestamp;
if (event.type() == event_type_names::kPointerup) {
// PointerUp by itself is not considered a significant input.
if (pending_pointerdown_timestamp_.is_null())
@@ -248,7 +250,8 @@ void InteractiveDetector::HandleForInputDelay(
GetSupplementable()->Loader()->DidChangePerformanceTiming();
}
-void InteractiveDetector::BeginNetworkQuietPeriod(TimeTicks current_time) {
+void InteractiveDetector::BeginNetworkQuietPeriod(
+ base::TimeTicks current_time) {
// Value of 0.0 indicates there is no currently actively network quiet window.
DCHECK(active_network_quiet_window_start_.is_null());
active_network_quiet_window_start_ = current_time;
@@ -256,7 +259,7 @@ void InteractiveDetector::BeginNetworkQuietPeriod(TimeTicks current_time) {
StartOrPostponeCITimer(current_time + kTimeToInteractiveWindow);
}
-void InteractiveDetector::EndNetworkQuietPeriod(TimeTicks current_time) {
+void InteractiveDetector::EndNetworkQuietPeriod(base::TimeTicks current_time) {
DCHECK(!active_network_quiet_window_start_.is_null());
if (current_time - active_network_quiet_window_start_ >=
@@ -264,31 +267,31 @@ void InteractiveDetector::EndNetworkQuietPeriod(TimeTicks current_time) {
network_quiet_windows_.emplace_back(active_network_quiet_window_start_,
current_time);
}
- active_network_quiet_window_start_ = TimeTicks();
+ active_network_quiet_window_start_ = base::TimeTicks();
}
// The optional opt_current_time, if provided, saves us a call to
// clock_->NowTicks().
void InteractiveDetector::UpdateNetworkQuietState(
double request_count,
- base::Optional<TimeTicks> opt_current_time) {
+ base::Optional<base::TimeTicks> opt_current_time) {
if (request_count <= kNetworkQuietMaximumConnections &&
active_network_quiet_window_start_.is_null()) {
// Not using `value_or(clock_->NowTicks())` here because arguments to
// functions are eagerly evaluated, which always call clock_->NowTicks.
- TimeTicks current_time =
+ base::TimeTicks current_time =
opt_current_time ? opt_current_time.value() : clock_->NowTicks();
BeginNetworkQuietPeriod(current_time);
} else if (request_count > kNetworkQuietMaximumConnections &&
!active_network_quiet_window_start_.is_null()) {
- TimeTicks current_time =
+ base::TimeTicks current_time =
opt_current_time ? opt_current_time.value() : clock_->NowTicks();
EndNetworkQuietPeriod(current_time);
}
}
void InteractiveDetector::OnResourceLoadBegin(
- base::Optional<TimeTicks> load_begin_time) {
+ base::Optional<base::TimeTicks> load_begin_time) {
if (!GetSupplementable())
return;
if (!interactive_time_.is_null())
@@ -301,7 +304,7 @@ void InteractiveDetector::OnResourceLoadBegin(
// The optional load_finish_time, if provided, saves us a call to
// clock_->NowTicks.
void InteractiveDetector::OnResourceLoadEnd(
- base::Optional<TimeTicks> load_finish_time) {
+ base::Optional<base::TimeTicks> load_finish_time) {
if (!GetSupplementable())
return;
if (!interactive_time_.is_null())
@@ -309,12 +312,12 @@ void InteractiveDetector::OnResourceLoadEnd(
UpdateNetworkQuietState(ActiveConnections(), load_finish_time);
}
-void InteractiveDetector::OnLongTaskDetected(TimeTicks start_time,
- TimeTicks end_time) {
+void InteractiveDetector::OnLongTaskDetected(base::TimeTicks start_time,
+ base::TimeTicks end_time) {
// We should not be receiving long task notifications after Time to
// Interactive has already been reached.
DCHECK(interactive_time_.is_null());
- TimeDelta quiet_window_length =
+ base::TimeDelta quiet_window_length =
start_time - active_main_thread_quiet_window_start_;
if (quiet_window_length >= kTimeToInteractiveWindow) {
main_thread_quiet_windows_.emplace_back(
@@ -325,7 +328,7 @@ void InteractiveDetector::OnLongTaskDetected(TimeTicks start_time,
}
void InteractiveDetector::OnFirstMeaningfulPaintDetected(
- TimeTicks fmp_time,
+ base::TimeTicks fmp_time,
FirstMeaningfulPaintDetector::HadUserInput user_input_before_fmp) {
DCHECK(page_event_times_.first_meaningful_paint
.is_null()); // Should not set FMP twice.
@@ -341,7 +344,7 @@ void InteractiveDetector::OnFirstMeaningfulPaintDetected(
}
}
-void InteractiveDetector::OnDomContentLoadedEnd(TimeTicks dcl_end_time) {
+void InteractiveDetector::OnDomContentLoadedEnd(base::TimeTicks dcl_end_time) {
// InteractiveDetector should only receive the first DCL event.
DCHECK(page_event_times_.dom_content_loaded_end.is_null());
page_event_times_.dom_content_loaded_end = dcl_end_time;
@@ -349,7 +352,7 @@ void InteractiveDetector::OnDomContentLoadedEnd(TimeTicks dcl_end_time) {
}
void InteractiveDetector::OnInvalidatingInputEvent(
- TimeTicks invalidation_time) {
+ base::TimeTicks invalidation_time) {
if (!page_event_times_.first_invalidating_input.is_null())
return;
@@ -365,7 +368,8 @@ void InteractiveDetector::OnInvalidatingInputEvent(
}
void InteractiveDetector::OnPageHiddenChanged(bool is_hidden) {
- visibility_change_events_.push_back({clock_->NowTicks(), is_hidden});
+ visibility_change_events_.push_back(
+ VisibilityChangeEvent{clock_->NowTicks(), is_hidden});
}
void InteractiveDetector::TimeToInteractiveTimerFired(TimerBase*) {
@@ -373,12 +377,12 @@ void InteractiveDetector::TimeToInteractiveTimerFired(TimerBase*) {
return;
// Value of 0.0 indicates there is currently no active timer.
- time_to_interactive_timer_fire_time_ = TimeTicks();
+ time_to_interactive_timer_fire_time_ = base::TimeTicks();
CheckTimeToInteractiveReached();
}
void InteractiveDetector::AddCurrentlyActiveQuietIntervals(
- TimeTicks current_time) {
+ base::TimeTicks current_time) {
// Network is currently quiet.
if (!active_network_quiet_window_start_.is_null()) {
if (current_time - active_network_quiet_window_start_ >=
@@ -399,24 +403,25 @@ void InteractiveDetector::AddCurrentlyActiveQuietIntervals(
}
void InteractiveDetector::RemoveCurrentlyActiveQuietIntervals() {
- if (!network_quiet_windows_.empty() &&
+ if (!network_quiet_windows_.IsEmpty() &&
network_quiet_windows_.back().Low() ==
active_network_quiet_window_start_) {
network_quiet_windows_.pop_back();
}
- if (!main_thread_quiet_windows_.empty() &&
+ if (!main_thread_quiet_windows_.IsEmpty() &&
main_thread_quiet_windows_.back().Low() ==
active_main_thread_quiet_window_start_) {
main_thread_quiet_windows_.pop_back();
}
}
-TimeTicks InteractiveDetector::FindInteractiveCandidate(TimeTicks lower_bound) {
+base::TimeTicks InteractiveDetector::FindInteractiveCandidate(
+ base::TimeTicks lower_bound) {
// Main thread iterator.
- auto it_mt = main_thread_quiet_windows_.begin();
+ auto* it_mt = main_thread_quiet_windows_.begin();
// Network iterator.
- auto it_net = network_quiet_windows_.begin();
+ auto* it_net = network_quiet_windows_.begin();
while (it_mt < main_thread_quiet_windows_.end() &&
it_net < network_quiet_windows_.end()) {
@@ -444,10 +449,10 @@ TimeTicks InteractiveDetector::FindInteractiveCandidate(TimeTicks lower_bound) {
}
// At this point we know we have a non-empty overlap after lower_bound.
- TimeTicks overlap_start =
+ base::TimeTicks overlap_start =
std::max({it_mt->Low(), it_net->Low(), lower_bound});
- TimeTicks overlap_end = std::min(it_mt->High(), it_net->High());
- TimeDelta overlap_duration = overlap_end - overlap_start;
+ base::TimeTicks overlap_end = std::min(it_mt->High(), it_net->High());
+ base::TimeDelta overlap_duration = overlap_end - overlap_start;
if (overlap_duration >= kTimeToInteractiveWindow) {
return std::max(lower_bound, it_mt->Low());
}
@@ -462,7 +467,7 @@ TimeTicks InteractiveDetector::FindInteractiveCandidate(TimeTicks lower_bound) {
}
// Time To Interactive candidate not found.
- return TimeTicks();
+ return base::TimeTicks();
}
void InteractiveDetector::CheckTimeToInteractiveReached() {
@@ -475,7 +480,7 @@ void InteractiveDetector::CheckTimeToInteractiveReached() {
page_event_times_.dom_content_loaded_end.is_null())
return;
- const TimeTicks current_time = clock_->NowTicks();
+ const base::TimeTicks current_time = clock_->NowTicks();
if (current_time - page_event_times_.first_meaningful_paint <
kTimeToInteractiveWindow) {
// Too close to FMP to determine Time to Interactive.
@@ -483,7 +488,7 @@ void InteractiveDetector::CheckTimeToInteractiveReached() {
}
AddCurrentlyActiveQuietIntervals(current_time);
- const TimeTicks interactive_candidate =
+ const base::TimeTicks interactive_candidate =
FindInteractiveCandidate(page_event_times_.first_meaningful_paint);
RemoveCurrentlyActiveQuietIntervals();
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 56f66a1855b..ffe5ca4a151 100644
--- a/chromium/third_party/blink/renderer/core/loader/interactive_detector.h
+++ b/chromium/third_party/blink/renderer/core/loader/interactive_detector.h
@@ -18,6 +18,7 @@
#include "third_party/blink/renderer/platform/supplementable.h"
#include "third_party/blink/renderer/platform/timer.h"
#include "third_party/blink/renderer/platform/wtf/pod_interval.h"
+#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace base {
class TickClock;
@@ -66,54 +67,54 @@ class CORE_EXPORT InteractiveDetector
explicit InteractiveDetector(Document&, NetworkActivityChecker*);
~InteractiveDetector() override = default;
- // Calls to CurrentTimeTicksInSeconds is expensive, so we try not to call it
- // unless we really have to. If we already have the event time available, we
- // pass it in as an argument.
- void OnResourceLoadBegin(base::Optional<TimeTicks> load_begin_time);
- void OnResourceLoadEnd(base::Optional<TimeTicks> load_finish_time);
+ // Calls to base::TimeTicks::Now().since_origin().InSecondsF() is expensive,
+ // so we try not to call it unless we really have to. If we already have the
+ // event time available, we pass it in as an argument.
+ void OnResourceLoadBegin(base::Optional<base::TimeTicks> load_begin_time);
+ void OnResourceLoadEnd(base::Optional<base::TimeTicks> load_finish_time);
- void SetNavigationStartTime(TimeTicks navigation_start_time);
+ void SetNavigationStartTime(base::TimeTicks navigation_start_time);
void OnFirstMeaningfulPaintDetected(
- TimeTicks fmp_time,
+ base::TimeTicks fmp_time,
FirstMeaningfulPaintDetector::HadUserInput user_input_before_fmp);
- void OnDomContentLoadedEnd(TimeTicks dcl_time);
- void OnInvalidatingInputEvent(TimeTicks invalidation_time);
+ void OnDomContentLoadedEnd(base::TimeTicks dcl_time);
+ void OnInvalidatingInputEvent(base::TimeTicks invalidation_time);
void OnPageHiddenChanged(bool is_hidden);
// Returns Interactive Time if already detected, or 0.0 otherwise.
- TimeTicks GetInteractiveTime() const;
+ base::TimeTicks GetInteractiveTime() const;
// Returns the time when page interactive was detected. The detection time can
// be useful to make decisions about metric invalidation in scenarios like tab
// backgrounding.
- TimeTicks GetInteractiveDetectionTime() const;
+ base::TimeTicks GetInteractiveDetectionTime() const;
// Returns the first time interactive detector received a significant input
// that may cause observers to discard the interactive time value.
- TimeTicks GetFirstInvalidatingInputTime() const;
+ base::TimeTicks GetFirstInvalidatingInputTime() const;
// The duration between the hardware timestamp and being queued on the main
// thread for the first click, tap, key press, cancelable touchstart, or
// pointer down followed by a pointer up.
- TimeDelta GetFirstInputDelay() const;
+ base::TimeDelta GetFirstInputDelay() const;
// The timestamp of the event whose delay is reported by GetFirstInputDelay().
- TimeTicks GetFirstInputTimestamp() const;
+ base::TimeTicks GetFirstInputTimestamp() const;
// Queueing Time of the meaningful input event with longest delay. Meaningful
// input events are click, tap, key press, cancellable touchstart, or pointer
// down followed by a pointer up.
- TimeDelta GetLongestInputDelay() const;
+ base::TimeDelta GetLongestInputDelay() const;
// The timestamp of the event whose delay is reported by
// GetLongestInputDelay().
- TimeTicks GetLongestInputTimestamp() const;
+ base::TimeTicks GetLongestInputTimestamp() const;
// Process an input event, updating first_input_delay and
// first_input_timestamp if needed.
void HandleForInputDelay(const Event&,
- TimeTicks event_platform_timestamp,
- TimeTicks processing_start);
+ base::TimeTicks event_platform_timestamp,
+ base::TimeTicks processing_start);
// ContextLifecycleObserver
void ContextDestroyed(ExecutionContext*) override;
@@ -130,76 +131,77 @@ class CORE_EXPORT InteractiveDetector
const base::TickClock* clock_;
- TimeTicks interactive_time_;
- TimeTicks interactive_detection_time_;
+ base::TimeTicks interactive_time_;
+ base::TimeTicks interactive_detection_time_;
// Page event times that Interactive Detector depends on.
- // Null TimeTicks values indicate the event has not been detected yet.
+ // Null base::TimeTicks values indicate the event has not been detected yet.
struct {
- TimeTicks first_meaningful_paint;
- TimeTicks dom_content_loaded_end;
- TimeTicks nav_start;
- TimeTicks first_invalidating_input;
- TimeDelta first_input_delay;
- TimeDelta longest_input_delay;
- TimeTicks first_input_timestamp;
- TimeTicks longest_input_timestamp;
+ base::TimeTicks first_meaningful_paint;
+ base::TimeTicks dom_content_loaded_end;
+ base::TimeTicks nav_start;
+ base::TimeTicks first_invalidating_input;
+ base::TimeDelta first_input_delay;
+ base::TimeDelta longest_input_delay;
+ base::TimeTicks first_input_timestamp;
+ base::TimeTicks longest_input_timestamp;
bool first_meaningful_paint_invalidated = false;
} page_event_times_;
struct VisibilityChangeEvent {
- TimeTicks timestamp;
+ base::TimeTicks timestamp;
bool was_hidden;
};
// Stores sufficiently long quiet windows on main thread and network.
- std::vector<WTF::PODInterval<TimeTicks>> main_thread_quiet_windows_;
- std::vector<WTF::PODInterval<TimeTicks>> network_quiet_windows_;
+ Vector<WTF::PODInterval<base::TimeTicks>> main_thread_quiet_windows_;
+ Vector<WTF::PODInterval<base::TimeTicks>> network_quiet_windows_;
// Start times of currently active main thread and network quiet windows.
- // Null TimeTicks values indicate main thread or network is not quiet at the
- // moment.
- TimeTicks active_main_thread_quiet_window_start_;
- TimeTicks active_network_quiet_window_start_;
+ // Null base::TimeTicks values indicate main thread or network is not quiet at
+ // the moment.
+ base::TimeTicks active_main_thread_quiet_window_start_;
+ base::TimeTicks active_network_quiet_window_start_;
// Adds currently active quiet main thread and network quiet windows to the
// vectors. Should be called before calling
// FindInteractiveCandidate.
- void AddCurrentlyActiveQuietIntervals(TimeTicks current_time);
+ void AddCurrentlyActiveQuietIntervals(base::TimeTicks current_time);
// Undoes AddCurrentlyActiveQuietIntervals.
void RemoveCurrentlyActiveQuietIntervals();
std::unique_ptr<NetworkActivityChecker> network_activity_checker_;
int ActiveConnections();
- void BeginNetworkQuietPeriod(TimeTicks current_time);
- void EndNetworkQuietPeriod(TimeTicks current_time);
+ void BeginNetworkQuietPeriod(base::TimeTicks current_time);
+ void EndNetworkQuietPeriod(base::TimeTicks current_time);
// Updates current network quietness tracking information. Opens and closes
// network quiet windows as necessary.
void UpdateNetworkQuietState(double request_count,
- base::Optional<TimeTicks> current_time);
+ base::Optional<base::TimeTicks> current_time);
TaskRunnerTimer<InteractiveDetector> time_to_interactive_timer_;
- TimeTicks time_to_interactive_timer_fire_time_;
- void StartOrPostponeCITimer(TimeTicks timer_fire_time);
+ base::TimeTicks time_to_interactive_timer_fire_time_;
+ void StartOrPostponeCITimer(base::TimeTicks timer_fire_time);
void TimeToInteractiveTimerFired(TimerBase*);
void CheckTimeToInteractiveReached();
void OnTimeToInteractiveDetected();
- std::vector<VisibilityChangeEvent> visibility_change_events_;
+ Vector<VisibilityChangeEvent> visibility_change_events_;
bool initially_hidden_;
// Returns true if page was ever backgrounded in the range
- // [event_time, CurrentTimeTicks()].
- bool PageWasBackgroundedSinceEvent(TimeTicks event_time);
+ // [event_time, base::TimeTicks::Now()].
+ bool PageWasBackgroundedSinceEvent(base::TimeTicks event_time);
// Finds a window of length kTimeToInteractiveWindowSeconds after lower_bound
// such that both main thread and network are quiet. Returns the end of last
// long task before that quiet window, or lower_bound, whichever is bigger -
// this is called the Interactive Candidate. Returns 0.0 if no such quiet
// window is found.
- TimeTicks FindInteractiveCandidate(TimeTicks lower_bound);
+ base::TimeTicks FindInteractiveCandidate(base::TimeTicks lower_bound);
// LongTaskObserver implementation
- void OnLongTaskDetected(TimeTicks start_time, TimeTicks end_time) override;
+ void OnLongTaskDetected(base::TimeTicks start_time,
+ base::TimeTicks end_time) override;
// The duration between the hardware timestamp and when we received the event
// for the previous pointer down. Only non-zero if we've received a pointer
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 b8c7417e25b..223efec74e6 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
@@ -9,10 +9,10 @@
#include "third_party/blink/renderer/core/paint/first_meaningful_paint_detector.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/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"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
namespace blink {
@@ -39,15 +39,18 @@ class InteractiveDetectorTest : public testing::Test {
public:
InteractiveDetectorTest() {
platform_->AdvanceClockSeconds(1);
- dummy_page_holder_ = std::make_unique<DummyPageHolder>();
+
+ auto test_task_runner = platform_->test_task_runner();
+ auto* tick_clock = test_task_runner->GetMockTickClock();
+ dummy_page_holder_ = std::make_unique<DummyPageHolder>(
+ IntSize(), nullptr, nullptr, base::NullCallback(), tick_clock);
Document* document = &dummy_page_holder_->GetDocument();
detector_ = MakeGarbageCollected<InteractiveDetector>(
*document, new NetworkActivityCheckerForTest(document));
- auto test_task_runner = platform_->test_task_runner();
detector_->SetTaskRunnerForTesting(test_task_runner);
- detector_->SetTickClockForTesting(test_task_runner->GetMockTickClock());
+ detector_->SetTickClockForTesting(tick_clock);
// By this time, the DummyPageHolder has created an InteractiveDetector, and
// sent DOMContentLoadedEnd. We overwrite it with our new
@@ -67,7 +70,7 @@ class InteractiveDetectorTest : public testing::Test {
protected:
InteractiveDetector* GetDetector() { return detector_; }
- TimeTicks GetDummyTaskEndTime() { return dummy_task_end_time_; }
+ base::TimeTicks GetDummyTaskEndTime() { return dummy_task_end_time_; }
NetworkActivityCheckerForTest* GetNetworkActivityChecker() {
// We know in this test context that network_activity_checker_ is an
@@ -76,36 +79,38 @@ class InteractiveDetectorTest : public testing::Test {
detector_->network_activity_checker_.get());
}
- void SimulateNavigationStart(TimeTicks nav_start_time) {
+ void SimulateNavigationStart(base::TimeTicks nav_start_time) {
RunTillTimestamp(nav_start_time);
detector_->SetNavigationStartTime(nav_start_time);
}
- void SimulateLongTask(TimeTicks start, TimeTicks end) {
- CHECK(end - start >= TimeDelta::FromSecondsD(0.05));
+ void SimulateLongTask(base::TimeTicks start, base::TimeTicks end) {
+ CHECK(end - start >= base::TimeDelta::FromSecondsD(0.05));
RunTillTimestamp(end);
detector_->OnLongTaskDetected(start, end);
}
- void SimulateDOMContentLoadedEnd(TimeTicks dcl_time) {
+ void SimulateDOMContentLoadedEnd(base::TimeTicks dcl_time) {
RunTillTimestamp(dcl_time);
detector_->OnDomContentLoadedEnd(dcl_time);
}
- void SimulateFMPDetected(TimeTicks fmp_time, TimeTicks detection_time) {
+ void SimulateFMPDetected(base::TimeTicks fmp_time,
+ base::TimeTicks detection_time) {
RunTillTimestamp(detection_time);
detector_->OnFirstMeaningfulPaintDetected(
fmp_time, FirstMeaningfulPaintDetector::kNoUserInput);
}
- void SimulateInteractiveInvalidatingInput(TimeTicks timestamp) {
+ void SimulateInteractiveInvalidatingInput(base::TimeTicks timestamp) {
RunTillTimestamp(timestamp);
detector_->OnInvalidatingInputEvent(timestamp);
}
- void RunTillTimestamp(TimeTicks target_time) {
- TimeTicks current_time = Now();
- platform_->RunForPeriod(std::max(TimeDelta(), target_time - current_time));
+ void RunTillTimestamp(base::TimeTicks target_time) {
+ base::TimeTicks current_time = Now();
+ platform_->RunForPeriod(
+ std::max(base::TimeDelta(), target_time - current_time));
}
int GetActiveConnections() {
@@ -116,14 +121,14 @@ class InteractiveDetectorTest : public testing::Test {
GetNetworkActivityChecker()->SetActiveConnections(active_connections);
}
- void SimulateResourceLoadBegin(TimeTicks load_begin_time) {
+ void SimulateResourceLoadBegin(base::TimeTicks load_begin_time) {
RunTillTimestamp(load_begin_time);
detector_->OnResourceLoadBegin(load_begin_time);
// ActiveConnections is incremented after detector runs OnResourceLoadBegin;
SetActiveConnections(GetActiveConnections() + 1);
}
- void SimulateResourceLoadEnd(TimeTicks load_finish_time) {
+ void SimulateResourceLoadEnd(base::TimeTicks load_finish_time) {
RunTillTimestamp(load_finish_time);
int active_connections = GetActiveConnections();
SetActiveConnections(active_connections - 1);
@@ -132,7 +137,9 @@ class InteractiveDetectorTest : public testing::Test {
base::TimeTicks Now() { return platform_->test_task_runner()->NowTicks(); }
- TimeTicks GetInteractiveTime() { return detector_->GetInteractiveTime(); }
+ base::TimeTicks GetInteractiveTime() {
+ return detector_->GetInteractiveTime();
+ }
ScopedTestingPlatformSupport<TestingPlatformSupportWithMockScheduler>
platform_;
@@ -140,7 +147,7 @@ class InteractiveDetectorTest : public testing::Test {
private:
Persistent<InteractiveDetector> detector_;
std::unique_ptr<DummyPageHolder> dummy_page_holder_;
- TimeTicks dummy_task_end_time_;
+ base::TimeTicks dummy_task_end_time_;
};
// Note: The tests currently assume kTimeToInteractiveWindowSeconds is 5
@@ -156,375 +163,396 @@ class InteractiveDetectorTest : public testing::Test {
// The name shows the ordering of these events in the test.
TEST_F(InteractiveDetectorTest, FMP_DCL_FmpDetect) {
- TimeTicks t0 = Now();
+ base::TimeTicks t0 = Now();
SimulateNavigationStart(t0);
// Network is forever quiet for this test.
SetActiveConnections(1);
- SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(3));
- SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(5),
- /* detection_time */ t0 + TimeDelta::FromSeconds(7));
+ SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(3));
+ SimulateFMPDetected(
+ /* fmp_time */ t0 + base::TimeDelta::FromSeconds(5),
+ /* detection_time */ t0 + base::TimeDelta::FromSeconds(7));
// Run until 5 seconds after FMP.
- RunTillTimestamp((t0 + TimeDelta::FromSeconds(5)) +
- TimeDelta::FromSecondsD(5.0 + 0.1));
+ RunTillTimestamp((t0 + base::TimeDelta::FromSeconds(5)) +
+ base::TimeDelta::FromSecondsD(5.0 + 0.1));
// Reached TTI at FMP.
- EXPECT_EQ(GetInteractiveTime(), t0 + TimeDelta::FromSeconds(5));
+ EXPECT_EQ(GetInteractiveTime(), t0 + base::TimeDelta::FromSeconds(5));
}
TEST_F(InteractiveDetectorTest, DCL_FMP_FmpDetect) {
- TimeTicks t0 = Now();
+ base::TimeTicks t0 = Now();
SimulateNavigationStart(t0);
// Network is forever quiet for this test.
SetActiveConnections(1);
- SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(5));
- SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(3),
- /* detection_time */ t0 + TimeDelta::FromSeconds(7));
+ SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(5));
+ SimulateFMPDetected(
+ /* fmp_time */ t0 + base::TimeDelta::FromSeconds(3),
+ /* detection_time */ t0 + base::TimeDelta::FromSeconds(7));
// Run until 5 seconds after FMP.
- RunTillTimestamp((t0 + TimeDelta::FromSeconds(3)) +
- TimeDelta::FromSecondsD(5.0 + 0.1));
+ RunTillTimestamp((t0 + base::TimeDelta::FromSeconds(3)) +
+ base::TimeDelta::FromSecondsD(5.0 + 0.1));
// Reached TTI at DCL.
- EXPECT_EQ(GetInteractiveTime(), t0 + TimeDelta::FromSeconds(5));
+ EXPECT_EQ(GetInteractiveTime(), t0 + base::TimeDelta::FromSeconds(5));
}
TEST_F(InteractiveDetectorTest, InstantDetectionAtFmpDetectIfPossible) {
- TimeTicks t0 = Now();
+ base::TimeTicks t0 = Now();
SimulateNavigationStart(t0);
// Network is forever quiet for this test.
SetActiveConnections(1);
- SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(5));
- SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(3),
- /* detection_time */ t0 + TimeDelta::FromSeconds(10));
+ SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(5));
+ SimulateFMPDetected(
+ /* fmp_time */ t0 + base::TimeDelta::FromSeconds(3),
+ /* detection_time */ t0 + base::TimeDelta::FromSeconds(10));
// Although we just detected FMP, the FMP timestamp is more than
// kTimeToInteractiveWindowSeconds earlier. We should instantaneously
// detect that we reached TTI at DCL.
- EXPECT_EQ(GetInteractiveTime(), t0 + TimeDelta::FromSeconds(5));
+ EXPECT_EQ(GetInteractiveTime(), t0 + base::TimeDelta::FromSeconds(5));
}
TEST_F(InteractiveDetectorTest, FmpDetectFiresAfterLateLongTask) {
- TimeTicks t0 = Now();
+ base::TimeTicks t0 = Now();
SimulateNavigationStart(t0);
// Network is forever quiet for this test.
SetActiveConnections(1);
- SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(3));
- SimulateLongTask(t0 + TimeDelta::FromSeconds(9),
- t0 + TimeDelta::FromSecondsD(9.1));
- SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(3),
- /* detection_time */ t0 + TimeDelta::FromSeconds(10));
+ SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(3));
+ SimulateLongTask(t0 + base::TimeDelta::FromSeconds(9),
+ t0 + base::TimeDelta::FromSecondsD(9.1));
+ SimulateFMPDetected(
+ /* fmp_time */ t0 + base::TimeDelta::FromSeconds(3),
+ /* detection_time */ t0 + base::TimeDelta::FromSeconds(10));
// There is a 5 second quiet window after fmp_time - the long task is 6s
// seconds after fmp_time. We should instantly detect we reached TTI at FMP.
- EXPECT_EQ(GetInteractiveTime(), t0 + TimeDelta::FromSeconds(3));
+ EXPECT_EQ(GetInteractiveTime(), t0 + base::TimeDelta::FromSeconds(3));
}
TEST_F(InteractiveDetectorTest, FMP_FmpDetect_DCL) {
- TimeTicks t0 = Now();
+ base::TimeTicks t0 = Now();
SimulateNavigationStart(t0);
// Network is forever quiet for this test.
SetActiveConnections(1);
- SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(3),
- /* detection_time */ t0 + TimeDelta::FromSeconds(5));
- SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(9));
+ SimulateFMPDetected(
+ /* fmp_time */ t0 + base::TimeDelta::FromSeconds(3),
+ /* detection_time */ t0 + base::TimeDelta::FromSeconds(5));
+ SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(9));
// TTI reached at DCL.
- EXPECT_EQ(GetInteractiveTime(), t0 + TimeDelta::FromSeconds(9));
+ EXPECT_EQ(GetInteractiveTime(), t0 + base::TimeDelta::FromSeconds(9));
}
TEST_F(InteractiveDetectorTest, LongTaskBeforeFMPDoesNotAffectTTI) {
- TimeTicks t0 = Now();
+ base::TimeTicks t0 = Now();
SimulateNavigationStart(t0);
// Network is forever quiet for this test.
SetActiveConnections(1);
- SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(3));
- SimulateLongTask(t0 + TimeDelta::FromSecondsD(5.1),
- t0 + TimeDelta::FromSecondsD(5.2));
- SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(8),
- /* detection_time */ t0 + TimeDelta::FromSeconds(9));
+ SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(3));
+ SimulateLongTask(t0 + base::TimeDelta::FromSecondsD(5.1),
+ t0 + base::TimeDelta::FromSecondsD(5.2));
+ SimulateFMPDetected(
+ /* fmp_time */ t0 + base::TimeDelta::FromSeconds(8),
+ /* detection_time */ t0 + base::TimeDelta::FromSeconds(9));
// Run till 5 seconds after FMP.
- RunTillTimestamp((t0 + TimeDelta::FromSeconds(8)) +
- TimeDelta::FromSecondsD(5.0 + 0.1));
+ RunTillTimestamp((t0 + base::TimeDelta::FromSeconds(8)) +
+ base::TimeDelta::FromSecondsD(5.0 + 0.1));
// TTI reached at FMP.
- EXPECT_EQ(GetInteractiveTime(), t0 + TimeDelta::FromSeconds(8));
+ EXPECT_EQ(GetInteractiveTime(), t0 + base::TimeDelta::FromSeconds(8));
}
TEST_F(InteractiveDetectorTest, DCLDoesNotResetTimer) {
- TimeTicks t0 = Now();
+ base::TimeTicks t0 = Now();
SimulateNavigationStart(t0);
// Network is forever quiet for this test.
SetActiveConnections(1);
- SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(3),
- /* detection_time */ t0 + TimeDelta::FromSeconds(4));
- SimulateLongTask(t0 + TimeDelta::FromSeconds(5),
- t0 + TimeDelta::FromSecondsD(5.1));
- SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(8));
+ SimulateFMPDetected(
+ /* fmp_time */ t0 + base::TimeDelta::FromSeconds(3),
+ /* detection_time */ t0 + base::TimeDelta::FromSeconds(4));
+ SimulateLongTask(t0 + base::TimeDelta::FromSeconds(5),
+ t0 + base::TimeDelta::FromSecondsD(5.1));
+ SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(8));
// Run till 5 seconds after long task end.
- RunTillTimestamp((t0 + TimeDelta::FromSecondsD(5.1)) +
- TimeDelta::FromSecondsD(5.0 + 0.1));
+ RunTillTimestamp((t0 + base::TimeDelta::FromSecondsD(5.1)) +
+ base::TimeDelta::FromSecondsD(5.0 + 0.1));
// TTI Reached at DCL.
- EXPECT_EQ(GetInteractiveTime(), t0 + TimeDelta::FromSeconds(8));
+ EXPECT_EQ(GetInteractiveTime(), t0 + base::TimeDelta::FromSeconds(8));
}
TEST_F(InteractiveDetectorTest, DCL_FMP_FmpDetect_LT) {
- TimeTicks t0 = Now();
+ base::TimeTicks t0 = Now();
SimulateNavigationStart(t0);
// Network is forever quiet for this test.
SetActiveConnections(1);
- SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(3));
- SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(4),
- /* detection_time */ t0 + TimeDelta::FromSeconds(5));
- SimulateLongTask(t0 + TimeDelta::FromSeconds(7),
- t0 + TimeDelta::FromSecondsD(7.1));
+ SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(3));
+ SimulateFMPDetected(
+ /* fmp_time */ t0 + base::TimeDelta::FromSeconds(4),
+ /* detection_time */ t0 + base::TimeDelta::FromSeconds(5));
+ SimulateLongTask(t0 + base::TimeDelta::FromSeconds(7),
+ t0 + base::TimeDelta::FromSecondsD(7.1));
// Run till 5 seconds after long task end.
- RunTillTimestamp((t0 + TimeDelta::FromSecondsD(7.1)) +
- TimeDelta::FromSecondsD(5.0 + 0.1));
+ RunTillTimestamp((t0 + base::TimeDelta::FromSecondsD(7.1)) +
+ base::TimeDelta::FromSecondsD(5.0 + 0.1));
// TTI reached at long task end.
- EXPECT_EQ(GetInteractiveTime(), t0 + TimeDelta::FromSecondsD(7.1));
+ EXPECT_EQ(GetInteractiveTime(), t0 + base::TimeDelta::FromSecondsD(7.1));
}
TEST_F(InteractiveDetectorTest, DCL_FMP_LT_FmpDetect) {
- TimeTicks t0 = Now();
+ base::TimeTicks t0 = Now();
SimulateNavigationStart(t0);
// Network is forever quiet for this test.
SetActiveConnections(1);
- SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(3));
- SimulateLongTask(t0 + TimeDelta::FromSeconds(7),
- t0 + TimeDelta::FromSecondsD(7.1));
- SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(3),
- /* detection_time */ t0 + TimeDelta::FromSeconds(5));
+ SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(3));
+ SimulateLongTask(t0 + base::TimeDelta::FromSeconds(7),
+ t0 + base::TimeDelta::FromSecondsD(7.1));
+ SimulateFMPDetected(
+ /* fmp_time */ t0 + base::TimeDelta::FromSeconds(3),
+ /* detection_time */ t0 + base::TimeDelta::FromSeconds(5));
// Run till 5 seconds after long task end.
- RunTillTimestamp((t0 + TimeDelta::FromSecondsD(7.1)) +
- TimeDelta::FromSecondsD(5.0 + 0.1));
+ RunTillTimestamp((t0 + base::TimeDelta::FromSecondsD(7.1)) +
+ base::TimeDelta::FromSecondsD(5.0 + 0.1));
// TTI reached at long task end.
- EXPECT_EQ(GetInteractiveTime(), t0 + TimeDelta::FromSecondsD(7.1));
+ EXPECT_EQ(GetInteractiveTime(), t0 + base::TimeDelta::FromSecondsD(7.1));
}
TEST_F(InteractiveDetectorTest, FMP_FmpDetect_LT_DCL) {
- TimeTicks t0 = Now();
+ base::TimeTicks t0 = Now();
SimulateNavigationStart(t0);
// Network is forever quiet for this test.
SetActiveConnections(1);
- SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(3),
- /* detection_time */ t0 + TimeDelta::FromSeconds(4));
- SimulateLongTask(t0 + TimeDelta::FromSeconds(7),
- t0 + TimeDelta::FromSecondsD(7.1));
- SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(8));
+ SimulateFMPDetected(
+ /* fmp_time */ t0 + base::TimeDelta::FromSeconds(3),
+ /* detection_time */ t0 + base::TimeDelta::FromSeconds(4));
+ SimulateLongTask(t0 + base::TimeDelta::FromSeconds(7),
+ t0 + base::TimeDelta::FromSecondsD(7.1));
+ SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(8));
// Run till 5 seconds after long task end.
- RunTillTimestamp((t0 + TimeDelta::FromSecondsD(7.1)) +
- TimeDelta::FromSecondsD(5.0 + 0.1));
+ RunTillTimestamp((t0 + base::TimeDelta::FromSecondsD(7.1)) +
+ base::TimeDelta::FromSecondsD(5.0 + 0.1));
// TTI reached at DCL. Note that we do not need to wait for DCL + 5 seconds.
- EXPECT_EQ(GetInteractiveTime(), t0 + TimeDelta::FromSeconds(8));
+ EXPECT_EQ(GetInteractiveTime(), t0 + base::TimeDelta::FromSeconds(8));
}
TEST_F(InteractiveDetectorTest, DclIsMoreThan5sAfterFMP) {
- TimeTicks t0 = Now();
+ base::TimeTicks t0 = Now();
SimulateNavigationStart(t0);
// Network is forever quiet for this test.
SetActiveConnections(1);
- SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(3),
- /* detection_time */ t0 + TimeDelta::FromSeconds(4));
- SimulateLongTask(t0 + TimeDelta::FromSeconds(7),
- t0 + TimeDelta::FromSecondsD(7.1)); // Long task 1.
- SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(10));
+ SimulateFMPDetected(
+ /* fmp_time */ t0 + base::TimeDelta::FromSeconds(3),
+ /* detection_time */ t0 + base::TimeDelta::FromSeconds(4));
+ SimulateLongTask(t0 + base::TimeDelta::FromSeconds(7),
+ t0 + base::TimeDelta::FromSecondsD(7.1)); // Long task 1.
+ SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(10));
// Have not reached TTI yet.
- EXPECT_EQ(GetInteractiveTime(), TimeTicks());
- SimulateLongTask(t0 + TimeDelta::FromSeconds(11),
- t0 + TimeDelta::FromSecondsD(11.1)); // Long task 2.
+ EXPECT_EQ(GetInteractiveTime(), base::TimeTicks());
+ SimulateLongTask(t0 + base::TimeDelta::FromSeconds(11),
+ t0 + base::TimeDelta::FromSecondsD(11.1)); // Long task 2.
// Run till long task 2 end + 5 seconds.
- RunTillTimestamp((t0 + TimeDelta::FromSecondsD(11.1)) +
- TimeDelta::FromSecondsD(5.0 + 0.1));
+ RunTillTimestamp((t0 + base::TimeDelta::FromSecondsD(11.1)) +
+ base::TimeDelta::FromSecondsD(5.0 + 0.1));
// TTI reached at long task 2 end.
- EXPECT_EQ(GetInteractiveTime(), (t0 + TimeDelta::FromSecondsD(11.1)));
+ EXPECT_EQ(GetInteractiveTime(), (t0 + base::TimeDelta::FromSecondsD(11.1)));
}
TEST_F(InteractiveDetectorTest, NetworkBusyBlocksTTIEvenWhenMainThreadQuiet) {
- TimeTicks t0 = Now();
+ base::TimeTicks t0 = Now();
SimulateNavigationStart(t0);
SetActiveConnections(1);
- SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(2));
- SimulateResourceLoadBegin(t0 +
- TimeDelta::FromSecondsD(3.4)); // Request 2 start.
+ SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(2));
SimulateResourceLoadBegin(
- t0 + TimeDelta::FromSecondsD(3.5)); // Request 3 start. Network busy.
- SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(3),
- /* detection_time */ t0 + TimeDelta::FromSeconds(4));
- SimulateLongTask(t0 + TimeDelta::FromSeconds(7),
- t0 + TimeDelta::FromSecondsD(7.1)); // Long task 1.
- SimulateResourceLoadEnd(t0 +
- TimeDelta::FromSecondsD(12.2)); // Network quiet.
+ t0 + base::TimeDelta::FromSecondsD(3.4)); // Request 2 start.
+ SimulateResourceLoadBegin(t0 + base::TimeDelta::FromSecondsD(
+ 3.5)); // Request 3 start. Network busy.
+ SimulateFMPDetected(
+ /* fmp_time */ t0 + base::TimeDelta::FromSeconds(3),
+ /* detection_time */ t0 + base::TimeDelta::FromSeconds(4));
+ SimulateLongTask(t0 + base::TimeDelta::FromSeconds(7),
+ t0 + base::TimeDelta::FromSecondsD(7.1)); // Long task 1.
+ SimulateResourceLoadEnd(
+ t0 + base::TimeDelta::FromSecondsD(12.2)); // Network quiet.
// Network busy kept page from reaching TTI..
- EXPECT_EQ(GetInteractiveTime(), TimeTicks());
- SimulateLongTask(t0 + TimeDelta::FromSeconds(13),
- t0 + TimeDelta::FromSecondsD(13.1)); // Long task 2.
+ EXPECT_EQ(GetInteractiveTime(), base::TimeTicks());
+ SimulateLongTask(t0 + base::TimeDelta::FromSeconds(13),
+ t0 + base::TimeDelta::FromSecondsD(13.1)); // Long task 2.
// Run till 5 seconds after long task 2 end.
- RunTillTimestamp((t0 + TimeDelta::FromSecondsD(13.1)) +
- TimeDelta::FromSecondsD(5.0 + 0.1));
- EXPECT_EQ(GetInteractiveTime(), (t0 + TimeDelta::FromSecondsD(13.1)));
+ RunTillTimestamp((t0 + base::TimeDelta::FromSecondsD(13.1)) +
+ base::TimeDelta::FromSecondsD(5.0 + 0.1));
+ EXPECT_EQ(GetInteractiveTime(), (t0 + base::TimeDelta::FromSecondsD(13.1)));
}
TEST_F(InteractiveDetectorTest, LongEnoughQuietWindowBetweenFMPAndFmpDetect) {
- TimeTicks t0 = Now();
+ base::TimeTicks t0 = Now();
SimulateNavigationStart(t0);
SetActiveConnections(1);
- SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(2));
- SimulateLongTask(t0 + TimeDelta::FromSecondsD(2.1),
- t0 + TimeDelta::FromSecondsD(2.2)); // Long task 1.
- SimulateLongTask(t0 + TimeDelta::FromSecondsD(8.2),
- t0 + TimeDelta::FromSecondsD(8.3)); // Long task 2.
- SimulateResourceLoadBegin(t0 +
- TimeDelta::FromSecondsD(8.4)); // Request 2 start.
+ SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(2));
+ SimulateLongTask(t0 + base::TimeDelta::FromSecondsD(2.1),
+ t0 + base::TimeDelta::FromSecondsD(2.2)); // Long task 1.
+ SimulateLongTask(t0 + base::TimeDelta::FromSecondsD(8.2),
+ t0 + base::TimeDelta::FromSecondsD(8.3)); // Long task 2.
SimulateResourceLoadBegin(
- t0 + TimeDelta::FromSecondsD(8.5)); // Request 3 start. Network busy.
- SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(3),
- /* detection_time */ t0 + TimeDelta::FromSeconds(10));
+ t0 + base::TimeDelta::FromSecondsD(8.4)); // Request 2 start.
+ SimulateResourceLoadBegin(t0 + base::TimeDelta::FromSecondsD(
+ 8.5)); // Request 3 start. Network busy.
+ SimulateFMPDetected(
+ /* fmp_time */ t0 + base::TimeDelta::FromSeconds(3),
+ /* detection_time */ t0 + base::TimeDelta::FromSeconds(10));
// Even though network is currently busy and we have long task finishing
// recently, we should be able to detect that the page already achieved TTI at
// FMP.
- EXPECT_EQ(GetInteractiveTime(), t0 + TimeDelta::FromSeconds(3));
+ EXPECT_EQ(GetInteractiveTime(), t0 + base::TimeDelta::FromSeconds(3));
}
TEST_F(InteractiveDetectorTest, NetworkBusyEndIsNotTTI) {
- TimeTicks t0 = Now();
+ base::TimeTicks t0 = Now();
SimulateNavigationStart(t0);
SetActiveConnections(1);
- SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(2));
- SimulateResourceLoadBegin(t0 +
- TimeDelta::FromSecondsD(3.4)); // Request 2 start.
+ SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(2));
SimulateResourceLoadBegin(
- t0 + TimeDelta::FromSecondsD(3.5)); // Request 3 start. Network busy.
- SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(3),
- /* detection_time */ t0 + TimeDelta::FromSeconds(4));
- SimulateLongTask(t0 + TimeDelta::FromSeconds(7),
- t0 + TimeDelta::FromSecondsD(7.1)); // Long task 1.
- SimulateLongTask(t0 + TimeDelta::FromSeconds(13),
- t0 + TimeDelta::FromSecondsD(13.1)); // Long task 2.
- SimulateResourceLoadEnd(t0 + TimeDelta::FromSeconds(14)); // Network quiet.
+ t0 + base::TimeDelta::FromSecondsD(3.4)); // Request 2 start.
+ SimulateResourceLoadBegin(t0 + base::TimeDelta::FromSecondsD(
+ 3.5)); // Request 3 start. Network busy.
+ SimulateFMPDetected(
+ /* fmp_time */ t0 + base::TimeDelta::FromSeconds(3),
+ /* detection_time */ t0 + base::TimeDelta::FromSeconds(4));
+ SimulateLongTask(t0 + base::TimeDelta::FromSeconds(7),
+ t0 + base::TimeDelta::FromSecondsD(7.1)); // Long task 1.
+ SimulateLongTask(t0 + base::TimeDelta::FromSeconds(13),
+ t0 + base::TimeDelta::FromSecondsD(13.1)); // Long task 2.
+ SimulateResourceLoadEnd(t0 +
+ base::TimeDelta::FromSeconds(14)); // Network quiet.
// Run till 5 seconds after network busy end.
- RunTillTimestamp((t0 + TimeDelta::FromSeconds(14)) +
- TimeDelta::FromSecondsD(5.0 + 0.1));
+ RunTillTimestamp((t0 + base::TimeDelta::FromSeconds(14)) +
+ base::TimeDelta::FromSecondsD(5.0 + 0.1));
// TTI reached at long task 2 end, NOT at network busy end.
- EXPECT_EQ(GetInteractiveTime(), t0 + TimeDelta::FromSecondsD(13.1));
+ EXPECT_EQ(GetInteractiveTime(), t0 + base::TimeDelta::FromSecondsD(13.1));
}
TEST_F(InteractiveDetectorTest, LateLongTaskWithLateFMPDetection) {
- TimeTicks t0 = Now();
+ base::TimeTicks t0 = Now();
SimulateNavigationStart(t0);
SetActiveConnections(1);
- SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(2));
- SimulateResourceLoadBegin(t0 +
- TimeDelta::FromSecondsD(3.4)); // Request 2 start.
+ SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(2));
SimulateResourceLoadBegin(
- t0 + TimeDelta::FromSecondsD(3.5)); // Request 3 start. Network busy.
- SimulateLongTask(t0 + TimeDelta::FromSeconds(7),
- t0 + TimeDelta::FromSecondsD(7.1)); // Long task 1.
- SimulateResourceLoadEnd(t0 + TimeDelta::FromSeconds(8)); // Network quiet.
- SimulateLongTask(t0 + TimeDelta::FromSeconds(14),
- t0 + TimeDelta::FromSecondsD(14.1)); // Long task 2.
- SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(3),
- /* detection_time */ t0 + TimeDelta::FromSeconds(20));
+ t0 + base::TimeDelta::FromSecondsD(3.4)); // Request 2 start.
+ SimulateResourceLoadBegin(t0 + base::TimeDelta::FromSecondsD(
+ 3.5)); // Request 3 start. Network busy.
+ SimulateLongTask(t0 + base::TimeDelta::FromSeconds(7),
+ t0 + base::TimeDelta::FromSecondsD(7.1)); // Long task 1.
+ SimulateResourceLoadEnd(t0 +
+ base::TimeDelta::FromSeconds(8)); // Network quiet.
+ SimulateLongTask(t0 + base::TimeDelta::FromSeconds(14),
+ t0 + base::TimeDelta::FromSecondsD(14.1)); // Long task 2.
+ SimulateFMPDetected(
+ /* fmp_time */ t0 + base::TimeDelta::FromSeconds(3),
+ /* detection_time */ t0 + base::TimeDelta::FromSeconds(20));
// TTI reached at long task 1 end, NOT at long task 2 end.
- EXPECT_EQ(GetInteractiveTime(), t0 + TimeDelta::FromSecondsD(7.1));
+ EXPECT_EQ(GetInteractiveTime(), t0 + base::TimeDelta::FromSecondsD(7.1));
}
TEST_F(InteractiveDetectorTest, IntermittentNetworkBusyBlocksTTI) {
- TimeTicks t0 = Now();
+ base::TimeTicks t0 = Now();
SimulateNavigationStart(t0);
SetActiveConnections(1);
- SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(2));
- SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(3),
- /* detection_time */ t0 + TimeDelta::FromSeconds(4));
- SimulateLongTask(t0 + TimeDelta::FromSeconds(7),
- t0 + TimeDelta::FromSecondsD(7.1)); // Long task 1.
+ SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(2));
+ SimulateFMPDetected(
+ /* fmp_time */ t0 + base::TimeDelta::FromSeconds(3),
+ /* detection_time */ t0 + base::TimeDelta::FromSeconds(4));
+ SimulateLongTask(t0 + base::TimeDelta::FromSeconds(7),
+ t0 + base::TimeDelta::FromSecondsD(7.1)); // Long task 1.
SimulateResourceLoadBegin(
- t0 + TimeDelta::FromSecondsD(7.9)); // Active connections: 2
+ t0 + base::TimeDelta::FromSecondsD(7.9)); // Active connections: 2
// Network busy start.
SimulateResourceLoadBegin(
- t0 + TimeDelta::FromSeconds(8)); // Active connections: 3.
+ t0 + base::TimeDelta::FromSeconds(8)); // Active connections: 3.
// Network busy end.
SimulateResourceLoadEnd(
- t0 + TimeDelta::FromSecondsD(8.5)); // Active connections: 2.
+ t0 + base::TimeDelta::FromSecondsD(8.5)); // Active connections: 2.
// Network busy start.
SimulateResourceLoadBegin(
- t0 + TimeDelta::FromSeconds(11)); // Active connections: 3.
+ t0 + base::TimeDelta::FromSeconds(11)); // Active connections: 3.
// Network busy end.
SimulateResourceLoadEnd(
- t0 + TimeDelta::FromSeconds(12)); // Active connections: 2.
- SimulateLongTask(t0 + TimeDelta::FromSeconds(14),
- t0 + TimeDelta::FromSecondsD(14.1)); // Long task 2.
+ t0 + base::TimeDelta::FromSeconds(12)); // Active connections: 2.
+ SimulateLongTask(t0 + base::TimeDelta::FromSeconds(14),
+ t0 + base::TimeDelta::FromSecondsD(14.1)); // Long task 2.
// Run till 5 seconds after long task 2 end.
- RunTillTimestamp((t0 + TimeDelta::FromSecondsD(14.1)) +
- TimeDelta::FromSecondsD(5.0 + 0.1));
+ RunTillTimestamp((t0 + base::TimeDelta::FromSecondsD(14.1)) +
+ base::TimeDelta::FromSecondsD(5.0 + 0.1));
// TTI reached at long task 2 end.
- EXPECT_EQ(GetInteractiveTime(), t0 + TimeDelta::FromSecondsD(14.1));
+ EXPECT_EQ(GetInteractiveTime(), t0 + base::TimeDelta::FromSecondsD(14.1));
}
TEST_F(InteractiveDetectorTest, InvalidatingUserInput) {
- TimeTicks t0 = Now();
+ base::TimeTicks t0 = Now();
SimulateNavigationStart(t0);
// Network is forever quiet for this test.
SetActiveConnections(1);
- SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(2));
- SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(3),
- /* detection_time */ t0 + TimeDelta::FromSeconds(4));
- SimulateInteractiveInvalidatingInput(t0 + TimeDelta::FromSeconds(5));
- SimulateLongTask(t0 + TimeDelta::FromSeconds(7),
- t0 + TimeDelta::FromSecondsD(7.1)); // Long task 1.
+ SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(2));
+ SimulateFMPDetected(
+ /* fmp_time */ t0 + base::TimeDelta::FromSeconds(3),
+ /* detection_time */ t0 + base::TimeDelta::FromSeconds(4));
+ SimulateInteractiveInvalidatingInput(t0 + base::TimeDelta::FromSeconds(5));
+ SimulateLongTask(t0 + base::TimeDelta::FromSeconds(7),
+ t0 + base::TimeDelta::FromSecondsD(7.1)); // Long task 1.
// Run till 5 seconds after long task 2 end.
- RunTillTimestamp((t0 + TimeDelta::FromSecondsD(7.1)) +
- TimeDelta::FromSecondsD(5.0 + 0.1));
+ RunTillTimestamp((t0 + base::TimeDelta::FromSecondsD(7.1)) +
+ base::TimeDelta::FromSecondsD(5.0 + 0.1));
// We still detect interactive time on the blink side even if there is an
// invalidating user input. Page Load Metrics filters out this value in the
// browser process for UMA reporting.
- EXPECT_EQ(GetInteractiveTime(), t0 + TimeDelta::FromSecondsD(7.1));
+ EXPECT_EQ(GetInteractiveTime(), t0 + base::TimeDelta::FromSecondsD(7.1));
EXPECT_EQ(GetDetector()->GetFirstInvalidatingInputTime(),
- t0 + TimeDelta::FromSeconds(5));
+ t0 + base::TimeDelta::FromSeconds(5));
}
TEST_F(InteractiveDetectorTest, InvalidatingUserInputClampedAtNavStart) {
- TimeTicks t0 = Now();
+ base::TimeTicks t0 = Now();
SimulateNavigationStart(t0);
// Network is forever quiet for this test.
SetActiveConnections(1);
- SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(2));
- SimulateFMPDetected(/* fmp_time */ t0 + TimeDelta::FromSeconds(3),
- /* detection_time */ t0 + TimeDelta::FromSeconds(4));
+ SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(2));
+ SimulateFMPDetected(
+ /* fmp_time */ t0 + base::TimeDelta::FromSeconds(3),
+ /* detection_time */ t0 + base::TimeDelta::FromSeconds(4));
// Invalidating input timestamp is earlier than navigation start.
- SimulateInteractiveInvalidatingInput(t0 - TimeDelta::FromSeconds(10));
+ SimulateInteractiveInvalidatingInput(t0 - base::TimeDelta::FromSeconds(10));
// Run till 5 seconds after FMP.
- RunTillTimestamp((t0 + TimeDelta::FromSecondsD(7.1)) +
- TimeDelta::FromSecondsD(5.0 + 0.1));
+ RunTillTimestamp((t0 + base::TimeDelta::FromSecondsD(7.1)) +
+ base::TimeDelta::FromSecondsD(5.0 + 0.1));
EXPECT_EQ(GetInteractiveTime(),
- t0 + TimeDelta::FromSeconds(3)); // TTI at FMP.
+ t0 + base::TimeDelta::FromSeconds(3)); // TTI at FMP.
// Invalidating input timestamp is clamped at navigation start.
EXPECT_EQ(GetDetector()->GetFirstInvalidatingInputTime(), t0);
}
TEST_F(InteractiveDetectorTest, InvalidatedFMP) {
- TimeTicks t0 = Now();
+ base::TimeTicks t0 = Now();
SimulateNavigationStart(t0);
// Network is forever quiet for this test.
SetActiveConnections(1);
- SimulateInteractiveInvalidatingInput(t0 + TimeDelta::FromSeconds(1));
- SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(2));
- RunTillTimestamp(t0 + TimeDelta::FromSeconds(4)); // FMP Detection time.
+ SimulateInteractiveInvalidatingInput(t0 + base::TimeDelta::FromSeconds(1));
+ SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(2));
+ RunTillTimestamp(t0 +
+ base::TimeDelta::FromSeconds(4)); // FMP Detection time.
GetDetector()->OnFirstMeaningfulPaintDetected(
- t0 + TimeDelta::FromSeconds(3),
+ t0 + base::TimeDelta::FromSeconds(3),
FirstMeaningfulPaintDetector::kHadUserInput);
// Run till 5 seconds after FMP.
- RunTillTimestamp((t0 + TimeDelta::FromSeconds(3)) +
- TimeDelta::FromSecondsD(5.0 + 0.1));
+ RunTillTimestamp((t0 + base::TimeDelta::FromSeconds(3)) +
+ base::TimeDelta::FromSecondsD(5.0 + 0.1));
// Since FMP was invalidated, we do not have TTI or TTI Detection Time.
- EXPECT_EQ(GetInteractiveTime(), TimeTicks());
+ EXPECT_EQ(GetInteractiveTime(), base::TimeTicks());
EXPECT_EQ(
GetDetector()->GetInteractiveDetectionTime().since_origin().InSecondsF(),
0.0);
// Invalidating input timestamp is available.
EXPECT_EQ(GetDetector()->GetFirstInvalidatingInputTime(),
- t0 + TimeDelta::FromSeconds(1));
+ t0 + base::TimeDelta::FromSeconds(1));
}
TEST_F(InteractiveDetectorTest, TaskLongerThan5sBlocksTTI) {
- TimeTicks t0 = Now();
+ base::TimeTicks t0 = Now();
GetDetector()->SetNavigationStartTime(t0);
- SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(2));
- SimulateFMPDetected(t0 + TimeDelta::FromSeconds(3),
- t0 + TimeDelta::FromSeconds(4));
+ SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(2));
+ SimulateFMPDetected(t0 + base::TimeDelta::FromSeconds(3),
+ t0 + base::TimeDelta::FromSeconds(4));
// Post a task with 6 seconds duration.
Thread::Current()->GetTaskRunner()->PostTask(
@@ -539,12 +567,12 @@ TEST_F(InteractiveDetectorTest, TaskLongerThan5sBlocksTTI) {
}
TEST_F(InteractiveDetectorTest, LongTaskAfterTTIDoesNothing) {
- TimeTicks t0 = Now();
+ base::TimeTicks t0 = Now();
GetDetector()->SetNavigationStartTime(t0);
- SimulateDOMContentLoadedEnd(t0 + TimeDelta::FromSeconds(2));
- SimulateFMPDetected(t0 + TimeDelta::FromSeconds(3),
- t0 + TimeDelta::FromSeconds(4));
+ SimulateDOMContentLoadedEnd(t0 + base::TimeDelta::FromSeconds(2));
+ SimulateFMPDetected(t0 + base::TimeDelta::FromSeconds(3),
+ t0 + base::TimeDelta::FromSeconds(4));
// Long task 1.
Thread::Current()->GetTaskRunner()->PostTask(
@@ -553,7 +581,7 @@ TEST_F(InteractiveDetectorTest, LongTaskAfterTTIDoesNothing) {
platform_->RunUntilIdle();
- TimeTicks long_task_1_end_time = GetDummyTaskEndTime();
+ base::TimeTicks long_task_1_end_time = GetDummyTaskEndTime();
// We should be able to detect TTI 5s after the end of long task.
platform_->RunForPeriodSeconds(5.1);
EXPECT_EQ(GetDetector()->GetInteractiveTime(), long_task_1_end_time);
diff --git a/chromium/third_party/blink/renderer/core/loader/link_load_parameters.h b/chromium/third_party/blink/renderer/core/loader/link_load_parameters.h
index d64c1252e68..ce2c3a00d7c 100644
--- a/chromium/third_party/blink/renderer/core/loader/link_load_parameters.h
+++ b/chromium/third_party/blink/renderer/core/loader/link_load_parameters.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_LINK_LOAD_PARAMETERS_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_LINK_LOAD_PARAMETERS_H_
-#include "services/network/public/mojom/referrer_policy.mojom-shared.h"
+#include "services/network/public/mojom/referrer_policy.mojom-blink.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/html/cross_origin_attribute.h"
#include "third_party/blink/renderer/core/html/link_rel_attribute.h"
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 7132c27f3c5..cdb64f18d24 100644
--- a/chromium/third_party/blink/renderer/core/loader/link_loader.cc
+++ b/chromium/third_party/blink/renderer/core/loader/link_loader.cc
@@ -34,7 +34,6 @@
#include "third_party/blink/public/common/prerender/prerender_rel_type.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/use_counter.h"
#include "third_party/blink/renderer/core/loader/importance_attribute.h"
#include "third_party/blink/renderer/core/loader/link_load_parameters.h"
#include "third_party/blink/renderer/core/loader/link_loader_client.h"
@@ -43,6 +42,7 @@
#include "third_party/blink/renderer/core/loader/resource/css_style_sheet_resource.h"
#include "third_party/blink/renderer/core/loader/subresource_integrity_helper.h"
#include "third_party/blink/renderer/core/page/viewport_description.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_client.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_finish_observer.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h"
@@ -133,10 +133,14 @@ LinkLoader::~LinkLoader() = default;
void LinkLoader::NotifyFinished() {
DCHECK(finish_observer_);
Resource* resource = finish_observer_->GetResource();
- if (resource->ErrorOccurred())
+ if (resource->ErrorOccurred() ||
+ (resource->IsLinkPreload() &&
+ resource->IntegrityDisposition() ==
+ ResourceIntegrityDisposition::kFailed)) {
client_->LinkLoadingErrored();
- else
+ } else {
client_->LinkLoaded();
+ }
}
// https://html.spec.whatwg.org/C/#link-type-modulepreload
@@ -222,7 +226,9 @@ void LinkLoader::LoadStylesheet(const LinkLoadParameters& params,
Document& document,
ResourceClient* link_client) {
ResourceRequest resource_request(document.CompleteURL(params.href));
- resource_request.SetReferrerPolicy(params.referrer_policy);
+ resource_request.SetReferrerPolicy(
+ params.referrer_policy,
+ ResourceRequest::SetReferrerPolicyLocation::kLoadStylesheet);
mojom::FetchImportanceMode importance_mode =
GetFetchImportanceAttributeValue(params.importance);
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 d71dee23182..e6cd611086a 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
@@ -468,25 +468,25 @@ struct ModulePreloadTestParams {
CrossOriginAttributeValue cross_origin;
network::mojom::ReferrerPolicy referrer_policy;
bool expecting_load;
- network::mojom::FetchCredentialsMode expected_credentials_mode;
+ network::mojom::CredentialsMode expected_credentials_mode;
};
constexpr ModulePreloadTestParams kModulePreloadTestParams[] = {
{"", nullptr, nullptr, kCrossOriginAttributeNotSet,
network::mojom::ReferrerPolicy::kDefault, false,
- network::mojom::FetchCredentialsMode::kSameOrigin},
+ network::mojom::CredentialsMode::kSameOrigin},
{"http://example.test/cat.js", nullptr, nullptr,
kCrossOriginAttributeNotSet, network::mojom::ReferrerPolicy::kDefault,
- true, network::mojom::FetchCredentialsMode::kSameOrigin},
+ true, network::mojom::CredentialsMode::kSameOrigin},
{"http://example.test/cat.js", nullptr, nullptr,
kCrossOriginAttributeAnonymous, network::mojom::ReferrerPolicy::kDefault,
- true, network::mojom::FetchCredentialsMode::kSameOrigin},
+ true, network::mojom::CredentialsMode::kSameOrigin},
{"http://example.test/cat.js", "nonce", nullptr,
kCrossOriginAttributeNotSet, network::mojom::ReferrerPolicy::kNever, true,
- network::mojom::FetchCredentialsMode::kSameOrigin},
+ network::mojom::CredentialsMode::kSameOrigin},
{"http://example.test/cat.js", nullptr, "sha384-abc",
kCrossOriginAttributeNotSet, network::mojom::ReferrerPolicy::kDefault,
- true, network::mojom::FetchCredentialsMode::kSameOrigin}};
+ true, network::mojom::CredentialsMode::kSameOrigin}};
class LinkLoaderModulePreloadTest
: public testing::TestWithParam<ModulePreloadTestParams> {};
diff --git a/chromium/third_party/blink/renderer/core/loader/loader_factory_for_frame.cc b/chromium/third_party/blink/renderer/core/loader/loader_factory_for_frame.cc
index bf7622600d4..14196adcf3b 100644
--- a/chromium/third_party/blink/renderer/core/loader/loader_factory_for_frame.cc
+++ b/chromium/third_party/blink/renderer/core/loader/loader_factory_for_frame.cc
@@ -95,7 +95,6 @@ std::unique_ptr<WebURLLoader> LoaderFactoryForFrame::CreateURLLoader(
}
if (prefetched_signed_exchange_manager_) {
- DCHECK(RuntimeEnabledFeatures::SignedExchangeSubresourcePrefetchEnabled());
auto loader =
prefetched_signed_exchange_manager_->MaybeCreateURLLoader(webreq);
if (loader)
diff --git a/chromium/third_party/blink/renderer/core/loader/long_task_detector.h b/chromium/third_party/blink/renderer/core/loader/long_task_detector.h
index f98bc1d430e..47c68ffcdcc 100644
--- a/chromium/third_party/blink/renderer/core/loader/long_task_detector.h
+++ b/chromium/third_party/blink/renderer/core/loader/long_task_detector.h
@@ -18,7 +18,8 @@ class CORE_EXPORT LongTaskObserver : public GarbageCollectedMixin {
public:
virtual ~LongTaskObserver() = default;
- virtual void OnLongTaskDetected(TimeTicks start_time, TimeTicks end_time) = 0;
+ virtual void OnLongTaskDetected(base::TimeTicks start_time,
+ base::TimeTicks end_time) = 0;
};
// LongTaskDetector detects tasks longer than kLongTaskThreshold and notifies
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 82fdf0d3f2a..da8092b21fc 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
@@ -5,9 +5,9 @@
#include "third_party/blink/renderer/core/loader/long_task_detector.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/testing/testing_platform_support_with_mock_scheduler.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
namespace blink {
@@ -21,11 +21,12 @@ class TestLongTaskObserver :
USING_GARBAGE_COLLECTED_MIXIN(TestLongTaskObserver);
public:
- TimeTicks last_long_task_start;
- TimeTicks last_long_task_end;
+ base::TimeTicks last_long_task_start;
+ base::TimeTicks last_long_task_end;
// LongTaskObserver implementation.
- void OnLongTaskDetected(TimeTicks start_time, TimeTicks end_time) override {
+ void OnLongTaskDetected(base::TimeTicks start_time,
+ base::TimeTicks end_time) override {
last_long_task_start = start_time;
last_long_task_end = end_time;
}
@@ -36,9 +37,9 @@ class LongTaskDetectorTest : public testing::Test {
public:
// Public because it's executed on a task queue.
void DummyTaskWithDuration(base::TimeDelta duration) {
- dummy_task_start_time_ = CurrentTimeTicks();
+ dummy_task_start_time_ = platform_->test_task_runner()->NowTicks();
platform_->AdvanceClock(duration);
- dummy_task_end_time_ = CurrentTimeTicks();
+ dummy_task_end_time_ = platform_->test_task_runner()->NowTicks();
}
protected:
@@ -48,9 +49,9 @@ class LongTaskDetectorTest : public testing::Test {
// of tasks.
platform_->RunForPeriodSeconds(1);
}
- TimeTicks DummyTaskStartTime() { return dummy_task_start_time_; }
+ base::TimeTicks DummyTaskStartTime() { return dummy_task_start_time_; }
- TimeTicks DummyTaskEndTime() { return dummy_task_end_time_; }
+ base::TimeTicks DummyTaskEndTime() { return dummy_task_end_time_; }
void SimulateTask(base::TimeDelta duration) {
Thread::Current()->GetTaskRunner()->PostTask(
@@ -63,8 +64,8 @@ class LongTaskDetectorTest : public testing::Test {
platform_;
private:
- TimeTicks dummy_task_start_time_;
- TimeTicks dummy_task_end_time_;
+ base::TimeTicks dummy_task_start_time_;
+ base::TimeTicks dummy_task_end_time_;
};
TEST_F(LongTaskDetectorTest, DeliversLongTaskNotificationOnlyWhenRegistered) {
@@ -72,12 +73,12 @@ TEST_F(LongTaskDetectorTest, DeliversLongTaskNotificationOnlyWhenRegistered) {
MakeGarbageCollected<TestLongTaskObserver>();
SimulateTask(LongTaskDetector::kLongTaskThreshold +
base::TimeDelta::FromMilliseconds(10));
- EXPECT_EQ(long_task_observer->last_long_task_end, TimeTicks());
+ EXPECT_EQ(long_task_observer->last_long_task_end, base::TimeTicks());
LongTaskDetector::Instance().RegisterObserver(long_task_observer);
SimulateTask(LongTaskDetector::kLongTaskThreshold +
base::TimeDelta::FromMilliseconds(10));
- TimeTicks long_task_end_when_registered = DummyTaskEndTime();
+ base::TimeTicks long_task_end_when_registered = DummyTaskEndTime();
EXPECT_EQ(long_task_observer->last_long_task_start, DummyTaskStartTime());
EXPECT_EQ(long_task_observer->last_long_task_end,
long_task_end_when_registered);
@@ -97,7 +98,7 @@ TEST_F(LongTaskDetectorTest, DoesNotGetNotifiedOfShortTasks) {
LongTaskDetector::Instance().RegisterObserver(long_task_observer);
SimulateTask(LongTaskDetector::kLongTaskThreshold -
base::TimeDelta::FromMilliseconds(10));
- EXPECT_EQ(long_task_observer->last_long_task_end, TimeTicks());
+ EXPECT_EQ(long_task_observer->last_long_task_end, base::TimeTicks());
SimulateTask(LongTaskDetector::kLongTaskThreshold +
base::TimeDelta::FromMilliseconds(10));
@@ -113,7 +114,7 @@ TEST_F(LongTaskDetectorTest, RegisterSameObserverTwice) {
SimulateTask(LongTaskDetector::kLongTaskThreshold +
base::TimeDelta::FromMilliseconds(10));
- TimeTicks long_task_end_when_registered = DummyTaskEndTime();
+ base::TimeTicks long_task_end_when_registered = DummyTaskEndTime();
EXPECT_EQ(long_task_observer->last_long_task_start, DummyTaskStartTime());
EXPECT_EQ(long_task_observer->last_long_task_end,
long_task_end_when_registered);
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 1c09ce24dc3..9d277ea4755 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
@@ -43,7 +43,6 @@
#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_fetch_context.h"
@@ -52,6 +51,7 @@
#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
#include "third_party/blink/renderer/core/workers/worker_or_worklet_global_scope.h"
#include "third_party/blink/renderer/core/workers/worker_settings.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher_properties.h"
#include "third_party/blink/renderer/platform/network/network_utils.h"
#include "third_party/blink/renderer/platform/weborigin/scheme_registry.h"
@@ -300,8 +300,8 @@ ConsoleMessage* MixedContentChecker::CreateConsoleMessageAboutFetch(
String message = String::Format(
"Mixed Content: The page at '%s' was loaded over HTTPS, but requested an "
"insecure %s '%s'. %s",
- main_resource_url.ElidedString().Utf8().data(),
- RequestContextName(request_context), url.ElidedString().Utf8().data(),
+ main_resource_url.ElidedString().Utf8().c_str(),
+ RequestContextName(request_context), url.ElidedString().Utf8().c_str(),
allowed ? "This content should also be served over HTTPS."
: "This request has been blocked; the content must be served "
"over HTTPS.");
@@ -549,8 +549,8 @@ ConsoleMessage* MixedContentChecker::CreateConsoleMessageAboutWebSocket(
String message = String::Format(
"Mixed Content: The page at '%s' was loaded over HTTPS, but attempted to "
"connect to the insecure WebSocket endpoint '%s'. %s",
- main_resource_url.ElidedString().Utf8().data(),
- url.ElidedString().Utf8().data(),
+ main_resource_url.ElidedString().Utf8().c_str(),
+ url.ElidedString().Utf8().c_str(),
allowed ? "This endpoint should be available via WSS. Insecure access is "
"deprecated."
: "This request has been blocked; this endpoint must be "
@@ -656,8 +656,8 @@ bool MixedContentChecker::IsMixedFormAction(
"Mixed Content: The page at '%s' was loaded over a secure connection, "
"but contains a form that targets an insecure endpoint '%s'. This "
"endpoint should be made available over a secure connection.",
- MainResourceUrlForFrame(mixed_frame).ElidedString().Utf8().data(),
- url.ElidedString().Utf8().data());
+ MainResourceUrlForFrame(mixed_frame).ElidedString().Utf8().c_str(),
+ url.ElidedString().Utf8().c_str());
frame->GetDocument()->AddConsoleMessage(
ConsoleMessage::Create(mojom::ConsoleMessageSource::kSecurity,
mojom::ConsoleMessageLevel::kWarning, message));
@@ -675,7 +675,7 @@ bool MixedContentChecker::ShouldAutoupgrade(HttpsState context_https_state,
return false;
}
- std::string autoupgrade_mode = base::GetFieldTrialParamValueByFeature(
+ auto autoupgrade_mode = base::GetFieldTrialParamValueByFeature(
blink::features::kMixedContentAutoupgrade,
blink::features::kMixedContentAutoupgradeModeParamName);
@@ -774,8 +774,8 @@ ConsoleMessage* MixedContentChecker::CreateConsoleMessageAboutFetchAutoupgrade(
"automatically upgraded to HTTPS, For more information see "
"https://chromium.googlesource.com/chromium/src/+/master/docs/security/"
"autoupgrade-mixed.md",
- main_resource_url.ElidedString().Utf8().data(),
- mixed_content_url.ElidedString().Utf8().data());
+ main_resource_url.ElidedString().Utf8().c_str(),
+ mixed_content_url.ElidedString().Utf8().c_str());
return ConsoleMessage::Create(mojom::ConsoleMessageSource::kSecurity,
mojom::ConsoleMessageLevel::kWarning, message);
}
@@ -792,8 +792,8 @@ MixedContentChecker::CreateConsoleMessageAboutWebSocketAutoupgrade(
"information see "
"https://chromium.googlesource.com/chromium/src/+/master/docs/security/"
"autoupgrade-mixed.md",
- main_resource_url.ElidedString().Utf8().data(),
- mixed_content_url.ElidedString().Utf8().data());
+ main_resource_url.ElidedString().Utf8().c_str(),
+ mixed_content_url.ElidedString().Utf8().c_str());
return ConsoleMessage::Create(mojom::ConsoleMessageSource::kSecurity,
mojom::ConsoleMessageLevel::kWarning, message);
}
diff --git a/chromium/third_party/blink/renderer/core/loader/mixed_content_checker_test.cc b/chromium/third_party/blink/renderer/core/loader/mixed_content_checker_test.cc
index 0760d121dda..ca4ec7f057d 100644
--- a/chromium/third_party/blink/renderer/core/loader/mixed_content_checker_test.cc
+++ b/chromium/third_party/blink/renderer/core/loader/mixed_content_checker_test.cc
@@ -16,6 +16,7 @@
#include "third_party/blink/renderer/core/loader/empty_clients.h"
#include "third_party/blink/renderer/core/testing/dummy_page_holder.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_response.h"
+#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
@@ -71,8 +72,11 @@ TEST(MixedContentCheckerTest, IsMixedContent) {
TEST(MixedContentCheckerTest, ContextTypeForInspector) {
auto dummy_page_holder = std::make_unique<DummyPageHolder>(IntSize(1, 1));
- dummy_page_holder->GetFrame().GetDocument()->SetSecurityOrigin(
- SecurityOrigin::CreateFromString("http://example.test"));
+ dummy_page_holder->GetFrame().Loader().CommitNavigation(
+ WebNavigationParams::CreateWithHTMLBuffer(SharedBuffer::Create(),
+ KURL("http://example.test")),
+ nullptr /* extra_data */);
+ blink::test::RunPendingTasks();
ResourceRequest not_mixed_content("https://example.test/foo.jpg");
not_mixed_content.SetRequestContext(mojom::RequestContextType::SCRIPT);
@@ -80,8 +84,12 @@ TEST(MixedContentCheckerTest, ContextTypeForInspector) {
MixedContentChecker::ContextTypeForInspector(
&dummy_page_holder->GetFrame(), not_mixed_content));
- dummy_page_holder->GetFrame().GetDocument()->SetSecurityOrigin(
- SecurityOrigin::CreateFromString("https://example.test"));
+ dummy_page_holder->GetFrame().Loader().CommitNavigation(
+ WebNavigationParams::CreateWithHTMLBuffer(SharedBuffer::Create(),
+ KURL("https://example.test")),
+ nullptr /* extra_data */);
+ blink::test::RunPendingTasks();
+
EXPECT_EQ(WebMixedContentContextType::kNotMixedContent,
MixedContentChecker::ContextTypeForInspector(
&dummy_page_holder->GetFrame(), not_mixed_content));
@@ -143,21 +151,22 @@ TEST(MixedContentCheckerTest, HandleCertificateError) {
}
TEST(MixedContentCheckerTest, DetectMixedForm) {
+ KURL main_resource_url(NullURL(), "https://example.test/");
MixedContentCheckerMockLocalFrameClient* client =
MakeGarbageCollected<MixedContentCheckerMockLocalFrameClient>();
auto dummy_page_holder =
std::make_unique<DummyPageHolder>(IntSize(1, 1), nullptr, client);
-
- KURL main_resource_url(NullURL(), "https://example.test/");
+ dummy_page_holder->GetFrame().Loader().CommitNavigation(
+ WebNavigationParams::CreateWithHTMLBuffer(SharedBuffer::Create(),
+ main_resource_url),
+ nullptr /* extra_data */);
+ blink::test::RunPendingTasks();
KURL http_form_action_url(NullURL(), "http://example-action.test/");
KURL https_form_action_url(NullURL(), "https://example-action.test/");
KURL javascript_form_action_url(NullURL(), "javascript:void(0);");
KURL mailto_form_action_url(NullURL(), "mailto:action@example-action.test");
- dummy_page_holder->GetFrame().GetDocument()->SetSecurityOrigin(
- SecurityOrigin::Create(main_resource_url));
-
// mailto and http are non-secure form targets.
EXPECT_CALL(*client, DidContainInsecureFormAction()).Times(2);
@@ -176,20 +185,22 @@ TEST(MixedContentCheckerTest, DetectMixedForm) {
}
TEST(MixedContentCheckerTest, DetectMixedFavicon) {
+ KURL main_resource_url("https://example.test/");
MixedContentCheckerMockLocalFrameClient* client =
MakeGarbageCollected<MixedContentCheckerMockLocalFrameClient>();
auto dummy_page_holder =
std::make_unique<DummyPageHolder>(IntSize(1, 1), nullptr, client);
+ dummy_page_holder->GetFrame().Loader().CommitNavigation(
+ WebNavigationParams::CreateWithHTMLBuffer(SharedBuffer::Create(),
+ main_resource_url),
+ nullptr /* extra_data */);
+ blink::test::RunPendingTasks();
dummy_page_holder->GetFrame().GetSettings()->SetAllowRunningOfInsecureContent(
false);
- KURL main_resource_url("https://example.test/");
KURL http_favicon_url("http://example.test/favicon.png");
KURL https_favicon_url("https://example.test/favicon.png");
- dummy_page_holder->GetFrame().GetDocument()->SetSecurityOrigin(
- SecurityOrigin::Create(main_resource_url));
-
// Test that a mixed content favicon is correctly blocked.
EXPECT_TRUE(MixedContentChecker::ShouldBlockFetch(
&dummy_page_holder->GetFrame(), mojom::RequestContextType::FAVICON,
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 708df929505..e55c7ac39e9 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
@@ -43,7 +43,7 @@ void DocumentModuleScriptFetcher::NotifyFinished(Resource* resource) {
ModuleScriptCreationParams params(
script_resource->GetResponse().CurrentRequestUrl(),
script_resource->SourceText(), script_resource->CacheHandler(),
- script_resource->GetResourceRequest().GetFetchCredentialsMode());
+ script_resource->GetResourceRequest().GetCredentialsMode());
client_->NotifyFetchFinished(params, error_messages);
}
@@ -80,7 +80,7 @@ bool DocumentModuleScriptFetcher::FetchIfLayeredAPI(
ModuleScriptCreationParams params(
layered_api_url, ParkableString(source_text.ReleaseImpl()),
nullptr /* cache_handler */,
- fetch_params.GetResourceRequest().GetFetchCredentialsMode());
+ fetch_params.GetResourceRequest().GetCredentialsMode());
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
index 2292755a193..33f366d3f24 100644
--- 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
@@ -72,7 +72,7 @@ void InstalledServiceWorkerModuleScriptFetcher::Fetch(
ModuleScriptCreationParams params(
fetch_params.Url(), ParkableString(script_data->TakeSourceText().Impl()),
nullptr /* cache_handler */,
- fetch_params.GetResourceRequest().GetFetchCredentialsMode());
+ fetch_params.GetResourceRequest().GetCredentialsMode());
client->NotifyFetchFinished(params, HeapVector<Member<ConsoleMessage>>());
}
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 2920c71e2b5..a2e943eb8d2 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
@@ -8,10 +8,10 @@
#include "base/optional.h"
#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/heap/persistent.h"
#include "third_party/blink/renderer/platform/loader/fetch/cached_metadata_handler.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_copier.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
@@ -21,17 +21,16 @@ class ModuleScriptCreationParams {
DISALLOW_NEW();
public:
- ModuleScriptCreationParams(
- const KURL& response_url,
- const ParkableString& source_text,
- SingleCachedMetadataHandler* cache_handler,
- network::mojom::FetchCredentialsMode fetch_credentials_mode)
+ ModuleScriptCreationParams(const KURL& response_url,
+ const ParkableString& source_text,
+ SingleCachedMetadataHandler* cache_handler,
+ network::mojom::CredentialsMode credentials_mode)
: response_url_(response_url),
is_isolated_(false),
source_text_(source_text),
isolated_source_text_(),
cache_handler_(cache_handler),
- fetch_credentials_mode_(fetch_credentials_mode) {}
+ credentials_mode_(credentials_mode) {}
~ModuleScriptCreationParams() = default;
@@ -54,8 +53,8 @@ class ModuleScriptCreationParams {
return source_text_;
}
SingleCachedMetadataHandler* CacheHandler() const { return cache_handler_; }
- network::mojom::FetchCredentialsMode GetFetchCredentialsMode() const {
- return fetch_credentials_mode_;
+ network::mojom::CredentialsMode GetFetchCredentialsMode() const {
+ return credentials_mode_;
}
bool IsSafeToSendToAnotherThread() const {
@@ -64,15 +63,14 @@ class ModuleScriptCreationParams {
private:
// Creates an isolated copy.
- ModuleScriptCreationParams(
- const KURL& response_url,
- const String& isolated_source_text,
- network::mojom::FetchCredentialsMode fetch_credentials_mode)
+ ModuleScriptCreationParams(const KURL& response_url,
+ const String& isolated_source_text,
+ network::mojom::CredentialsMode credentials_mode)
: response_url_(response_url),
is_isolated_(true),
source_text_(),
isolated_source_text_(isolated_source_text),
- fetch_credentials_mode_(fetch_credentials_mode) {}
+ credentials_mode_(credentials_mode) {}
const KURL response_url_;
@@ -85,19 +83,23 @@ class ModuleScriptCreationParams {
// |cache_handler_| is cleared when crossing thread boundaries.
Persistent<SingleCachedMetadataHandler> cache_handler_;
- const network::mojom::FetchCredentialsMode fetch_credentials_mode_;
+ const network::mojom::CredentialsMode credentials_mode_;
};
+} // namespace blink
+
+namespace WTF {
+
// Creates a deep copy because |response_url_| and |source_text_| are not
// cross-thread-transfer-safe.
template <>
-struct CrossThreadCopier<ModuleScriptCreationParams> {
- static ModuleScriptCreationParams Copy(
- const ModuleScriptCreationParams& params) {
+struct CrossThreadCopier<blink::ModuleScriptCreationParams> {
+ static blink::ModuleScriptCreationParams Copy(
+ const blink::ModuleScriptCreationParams& params) {
return params.IsolatedCopy();
}
};
-} // namespace blink
+} // namespace WTF
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_MODULESCRIPT_MODULE_SCRIPT_CREATION_PARAMS_H_
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 cd2690a0f45..b68a0557112 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
@@ -21,12 +21,10 @@ void ModuleScriptFetcher::Client::OnFailed() {
NotifyFetchFinished(base::nullopt, HeapVector<Member<ConsoleMessage>>());
}
+// <specdef href="https://html.spec.whatwg.org/C/#fetch-a-single-module-script">
bool ModuleScriptFetcher::WasModuleLoadSuccessful(
Resource* resource,
HeapVector<Member<ConsoleMessage>>* error_messages) {
- // Implements conditions in Step 7 of
- // https://html.spec.whatwg.org/C/#fetch-a-single-module-script
-
DCHECK(error_messages);
if (resource) {
@@ -34,7 +32,7 @@ bool ModuleScriptFetcher::WasModuleLoadSuccessful(
resource->IntegrityReportInfo(), error_messages);
}
- // - response's type is "error"
+ // <spec step="9">... response's type is "error" ...</spec>
if (!resource || resource->ErrorOccurred() ||
resource->IntegrityDisposition() !=
ResourceIntegrityDisposition::kPassed) {
@@ -42,18 +40,23 @@ bool ModuleScriptFetcher::WasModuleLoadSuccessful(
}
const auto& response = resource->GetResponse();
- // - response's status is not an ok status
+ // <spec step="9">... response's status is not an ok status</spec>
if (response.IsHTTP() && !cors::IsOkStatus(response.HttpStatusCode())) {
return false;
}
- // The result of extracting a MIME type from response's header list
- // (ignoring parameters) is not a JavaScript MIME type
+ // <spec step="10">Let type be the result of extracting a MIME type from
+ // response's header list.</spec>
+ //
+ // <spec step="12">If type is a JavaScript MIME type, then:</spec>
+ //
// Note: For historical reasons, fetching a classic script does not include
// MIME type checking. In contrast, module scripts will fail to load if they
// are not of a correct MIME type.
// We use ResourceResponse::HttpContentType() instead of MimeType(), as
// MimeType() may be rewritten by mime sniffer.
+ //
+ // Non-JavaScript module is not yet implemented.
if (!MIMETypeRegistry::IsSupportedJavaScriptMIMEType(
response.HttpContentType())) {
String message =
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 e79e35040ad..9e76c02ce4e 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
@@ -93,7 +93,7 @@ void ModuleScriptLoader::Fetch(
level, custom_fetch_type);
}
-// https://html.spec.whatwg.org/C/#fetch-a-single-module-script
+// <specdef href="https://html.spec.whatwg.org/C/#fetch-a-single-module-script">
void ModuleScriptLoader::FetchInternal(
const ModuleScriptFetchRequest& module_request,
ResourceFetcher* fetch_client_settings_object_fetcher,
@@ -103,16 +103,16 @@ void ModuleScriptLoader::FetchInternal(
fetch_client_settings_object_fetcher->GetProperties()
.GetFetchClientSettingsObject();
- // Step 4. "Set moduleMap[url] to "fetching"." [spec text]
+ // <spec step="4">Set moduleMap[url] to "fetching".</spec>
AdvanceState(State::kFetching);
- // Step 5. "Let request be a new request whose url is url, ..." [spec text]
+ // <spec step="5">Let request be a new request whose url is url, ...</spec>
ResourceRequest resource_request(module_request.Url());
#if DCHECK_IS_ON()
url_ = module_request.Url();
#endif
- // "destination is destination," [spec text]
+ // <spec step="5">... destination is destination, ...</spec>
resource_request.SetRequestContext(module_request.Destination());
ResourceLoaderOptions options;
@@ -125,13 +125,14 @@ void ModuleScriptLoader::FetchInternal(
// AbstractWorker::ResolveURL, but it might be good to try and follow the spec
// here, and let this resolve in a network error as Fetch dictates?
- // Step 6. "Set up the module script request given request and options."
- // [spec text]
- // [SMSR]
- // https://html.spec.whatwg.org/C/#set-up-the-module-script-request
+ // <spec step="7">Set up the module script request given request and
+ // options.</spec>
+ //
+ // <specdef label="SMSR"
+ // href="https://html.spec.whatwg.org/C/#set-up-the-module-script-request">
- // [SMSR] "... its parser metadata to options's parser metadata, ..."
- // [spec text]
+ // <spec label="SMSR">... its parser metadata to options's parser metadata,
+ // ...</spec>
options.parser_disposition = options_.ParserState();
// As initiator for module script fetch is not specified in HTML spec,
@@ -148,42 +149,34 @@ void ModuleScriptLoader::FetchInternal(
// Note: |options| should not be modified after here.
FetchParameters fetch_params(resource_request, options);
- // [SMSR] "... its integrity metadata to options's integrity metadata, ..."
- // [spec text]
+ // <spec label="SMSR">... its integrity metadata to options's integrity
+ // metadata, ...</spec>
fetch_params.SetIntegrityMetadata(options_.GetIntegrityMetadata());
fetch_params.MutableResourceRequest().SetFetchIntegrity(
options_.GetIntegrityAttributeValue());
- // [SMSR] "Set request's cryptographic nonce metadata to options's
- // cryptographic nonce, ..." [spec text]
+ // <spec label="SMSR">Set request's cryptographic nonce metadata to options's
+ // cryptographic nonce, ...</spec>
fetch_params.SetContentSecurityPolicyNonce(options_.Nonce());
- // [SMSR] "... its referrer policy to options's referrer policy." [spec text]
- // Note: For now this is done below with SetHttpReferrer()
- network::mojom::ReferrerPolicy referrer_policy =
- module_request.Options().GetReferrerPolicy();
- if (referrer_policy == network::mojom::ReferrerPolicy::kDefault)
- referrer_policy = fetch_client_settings_object.GetReferrerPolicy();
+ // <spec label="SMSR">... its referrer policy to options's referrer
+ // policy.</spec>
+ fetch_params.MutableResourceRequest().SetReferrerPolicy(
+ module_request.Options().GetReferrerPolicy(),
+ ResourceRequest::SetReferrerPolicyLocation::kModuleLoader);
- // Step 5. "... mode is "cors", ..."
- // [SMSR] "... and its credentials mode to options's credentials mode."
- // [spec text]
+ // <spec step="5">... mode is "cors", ...</spec>
+ //
+ // <spec label="SMSR">... its credentials mode to options's credentials mode,
+ // ...</spec>
fetch_params.SetCrossOriginAccessControl(
fetch_client_settings_object.GetSecurityOrigin(),
options_.CredentialsMode());
- // Step 5. "... referrer is referrer, ..." [spec text]
- // Note: For now this is done below with SetHttpReferrer()
- String referrer_string = module_request.ReferrerString();
- if (referrer_string == Referrer::ClientReferrerString())
- referrer_string = fetch_client_settings_object.GetOutgoingReferrer();
-
- // TODO(domfarolino): Stop storing ResourceRequest's referrer as a
- // blink::Referrer (https://crbug.com/850813).
- fetch_params.MutableResourceRequest().SetHttpReferrer(
- SecurityPolicy::GenerateReferrer(referrer_policy,
- fetch_params.GetResourceRequest().Url(),
- referrer_string));
+ // <spec step="5">... referrer is referrer, ...</spec>
+ fetch_params.MutableResourceRequest().SetReferrerString(
+ module_request.ReferrerString(),
+ ResourceRequest::SetReferrerStringLocation::kModuleScriptLoader);
// Priority Hints and a request's "importance" are currently non-standard, but
// we can assume the following (see https://crbug.com/821464):
@@ -191,7 +184,8 @@ void ModuleScriptLoader::FetchInternal(
fetch_params.MutableResourceRequest().SetFetchImportanceMode(
options_.Importance());
- // Step 5. "... and client is fetch client settings object." [spec text]
+ // <spec step="5">... and client is fetch client settings object.</spec>
+ //
// -> set by ResourceFetcher
// Note: The fetch request's "origin" isn't specified in
@@ -206,25 +200,24 @@ void ModuleScriptLoader::FetchInternal(
fetch_params.MutableResourceRequest().SetPriority(
ResourceLoadPriority::kHigh);
- // Use UTF-8, according to Step 9:
- // "Let source text be the result of UTF-8 decoding response's body."
- // [spec text]
+ // <spec step="12.1">Let source text be the result of UTF-8 decoding
+ // response's body.</spec>
fetch_params.SetDecoderOptions(
TextResourceDecoderOptions::CreateAlwaysUseUTF8ForText());
- // Step 7. "If the caller specified custom steps to perform the fetch,
+ // <spec step="8">If the caller specified custom steps to perform the fetch,
// perform them on request, setting the is top-level flag if the top-level
// module fetch flag is set. Return from this algorithm, and when the custom
// perform the fetch steps complete with response response, run the remaining
- // steps.
- // Otherwise, fetch request. Return from this algorithm, and run the remaining
- // steps as part of the fetch's process response for the response response."
- // [spec text]
+ // steps. Otherwise, fetch request. Return from this algorithm, and run the
+ // remaining steps as part of the fetch's process response for the response
+ // response.</spec>
module_fetcher_ = modulator_->CreateModuleScriptFetcher(custom_fetch_type);
module_fetcher_->Fetch(fetch_params, fetch_client_settings_object_fetcher,
modulator_, level, this);
}
+// <specdef href="https://html.spec.whatwg.org/C/#fetch-a-single-module-script">
void ModuleScriptLoader::NotifyFetchFinished(
const base::Optional<ModuleScriptCreationParams>& params,
const HeapVector<Member<ConsoleMessage>>& error_messages) {
@@ -234,11 +227,12 @@ void ModuleScriptLoader::NotifyFetchFinished(
return;
}
- // Note: "conditions" referred in Step 8 is implemented in
- // WasModuleLoadSuccessful() in module_script_fetcher.cc.
- // Step 8. "If any of the following conditions are met, set moduleMap[url] to
- // null, asynchronously complete this algorithm with null, and abort these
- // steps." [spec text]
+ // <spec step="9">If any of the following conditions are met, set
+ // moduleMap[url] to null, asynchronously complete this algorithm with null,
+ // and abort these steps: ...</spec>
+ //
+ // Note: the "conditions" are implemented in WasModuleLoadSuccessful() in
+ // module_script_fetcher.cc.
if (!params.has_value()) {
for (ConsoleMessage* error_message : error_messages) {
ExecutionContext::From(modulator_->GetScriptState())
@@ -248,11 +242,12 @@ void ModuleScriptLoader::NotifyFetchFinished(
return;
}
- // Step 9. "Let source text be the result of UTF-8 decoding response's body."
- // [spec text]
- // 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]
+ // <spec step="12.1">Let source text be the result of UTF-8 decoding
+ // response's body.</spec>
+ //
+ // <spec step="12.2">Set module script to the result of creating a JavaScript
+ // module script given source text, module map settings object, response's
+ // url, and options.</spec>
module_script_ = JSModuleScript::Create(
params->GetSourceText(), params->CacheHandler(),
ScriptSourceLocationType::kExternalFile, modulator_,
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 9e3ca31b821..2edffe4b29a 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
@@ -143,6 +143,11 @@ class ModuleScriptLoaderTest : public PageTestBase {
->RunUntilIdle();
}
+ private:
+ const base::TickClock* GetTickClock() override {
+ return platform_->test_task_runner()->GetMockTickClock();
+ }
+
protected:
const KURL url_;
const scoped_refptr<const SecurityOrigin> security_origin_;
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 6eda5c98b90..b2bc0222717 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
@@ -16,6 +16,19 @@
#include "third_party/blink/renderer/platform/wtf/vector.h"
#include "v8/include/v8.h"
+// <specdef label="IMSGF"
+// href="https://html.spec.whatwg.org/C/#internal-module-script-graph-fetching-procedure">
+
+// <specdef label="fetch-a-module-script-tree"
+// href="https://html.spec.whatwg.org/C/#fetch-a-module-script-tree">
+
+// <specdef
+// label="fetch-a-module-worker-script-tree"
+// href="https://html.spec.whatwg.org/C/#fetch-a-module-worker-script-tree">
+
+// <specdef label="fetch-an-import()-module-script-graph"
+// href="https://html.spec.whatwg.org/C/#fetch-an-import()-module-script-graph">
+
namespace blink {
void ModuleTreeLinker::Fetch(
@@ -142,14 +155,15 @@ void ModuleTreeLinker::AdvanceState(State new_state) {
registry_->ReleaseFinishedFetcher(this);
- // [IMSGF] Step 6. When the appropriate algorithm asynchronously completes
- // with final result, asynchronously complete this algorithm with final
- // result.
+ // <spec label="IMSGF" step="6">When the appropriate algorithm
+ // asynchronously completes with final result, asynchronously complete this
+ // algorithm with final result.</spec>
client_->NotifyModuleTreeLoadFinished(result_);
}
}
-// https://html.spec.whatwg.org/C/#fetch-a-module-script-tree
+// #fetch-a-module-script-tree, #fetch-an-import()-module-script-graph, and
+// #fetch-a-module-worker-script-tree.
void ModuleTreeLinker::FetchRoot(const KURL& original_url,
const ScriptFetchOptions& options) {
#if DCHECK_IS_ON()
@@ -157,9 +171,7 @@ void ModuleTreeLinker::FetchRoot(const KURL& original_url,
root_is_inline_ = false;
#endif
- // https://github.com/WICG/import-maps/blob/master/spec.md#when-import-maps-can-be-encountered
- // The internal module script graph fetching procedure flips the boolean to
- // false. [spec text]
+ // https://wicg.github.io/import-maps/#wait-for-import-maps
modulator_->ClearIsAcquiringImportMaps();
AdvanceState(State::kFetchingSelf);
@@ -176,10 +188,17 @@ void ModuleTreeLinker::FetchRoot(const KURL& original_url,
url_ = url;
#endif
- // <spec
- // href="https://github.com/drufball/layered-apis/blob/master/spec.md#fetch-a-module-script-graph"
- // step="2">If url is failure, asynchronously complete this algorithm with
- // null.</spec>
+ // <spec label="fetch-a-module-script-tree" step="2">If result is null,
+ // asynchronously complete this algorithm with null, and abort these
+ // steps.</spec>
+ //
+ // <spec label="fetch-an-import()-module-script-graph" step="4">If result is
+ // null, asynchronously complete this algorithm with null, and abort these
+ // steps.</spec>
+ //
+ // <spec label="fetch-a-module-worker-script-tree" step="3">If result is null,
+ // asynchronously complete this algorithm with null, and abort these
+ // steps.</spec>
if (!url.IsValid()) {
result_ = nullptr;
modulator_->TaskRunner()->PostTask(
@@ -188,22 +207,40 @@ void ModuleTreeLinker::FetchRoot(const KURL& original_url,
return;
}
- // Step 1. Let visited set be << url >>.
+ // <spec label="fetch-a-module-script-tree" step="3">Let visited set be « url
+ // ».</spec>
+ //
+ // <spec label="fetch-an-import()-module-script-graph" step="5">Let visited
+ // set be « url ».</spec>
+ //
+ // <spec label="fetch-a-module-worker-script-tree" step="4">Let visited set be
+ // « url ».</spec>
visited_set_.insert(url);
- // Step 2. Perform the internal module script graph fetching procedure given
- // url, settings object, destination, options, settings object, visited set,
- // "client", and with the top-level module fetch flag set.
+ // <spec label="fetch-a-module-script-tree" step="1">Fetch a single module
+ // script given url, settings object, "script", options, settings object,
+ // "client", and with the top-level module fetch flag set. ...</spec>
+ //
+ // <spec label="fetch-an-import()-module-script-graph" step="3">Fetch a single
+ // module script given url, settings object, "script", options, settings
+ // object, "client", and with the top-level module fetch flag set. ...</spec>
+ //
+ // <spec label="fetch-a-module-worker-script-tree" step="2">Fetch a single
+ // module script given url, fetch client settings object, destination,
+ // options, module map settings object, "client", and with the top-level
+ // module fetch flag set. ...</spec>
ModuleScriptFetchRequest request(url, destination_, options,
Referrer::ClientReferrerString(),
TextPosition::MinimumPosition());
-
- InitiateInternalModuleScriptGraphFetching(
- request, ModuleGraphLevel::kTopLevelModuleFetch);
+ ++num_incomplete_fetches_;
+ modulator_->FetchSingle(request, fetch_client_settings_object_fetcher_.Get(),
+ ModuleGraphLevel::kTopLevelModuleFetch,
+ custom_fetch_type_, this);
}
+// <specdef
+// href="https://html.spec.whatwg.org/C/#fetch-an-inline-module-script-graph">
void ModuleTreeLinker::FetchRootInline(ModuleScript* module_script) {
- // Top-level entry point for [FDaI] for an inline module script.
DCHECK(module_script);
#if DCHECK_IS_ON()
original_url_ = module_script->BaseURL();
@@ -211,9 +248,9 @@ void ModuleTreeLinker::FetchRootInline(ModuleScript* module_script) {
root_is_inline_ = true;
#endif
- // https://github.com/WICG/import-maps/blob/master/spec.md#when-import-maps-can-be-encountered
- // The internal module script graph fetching procedure flips the boolean to
- // false. [spec text]
+ // https://wicg.github.io/import-maps/#wait-for-import-maps
+ //
+ // TODO(hiroshige): This should be done before |module_script| is created.
modulator_->ClearIsAcquiringImportMaps();
AdvanceState(State::kFetchingSelf);
@@ -224,31 +261,21 @@ void ModuleTreeLinker::FetchRootInline(ModuleScript* module_script) {
result_ = module_script;
AdvanceState(State::kFetchingDependencies);
+ // <spec step="3">Let visited set be an empty set.</spec>
+ //
+ // |visited_set_| is initialized to an empty set in ctor.
+
+ // <spec step="4">Fetch the descendants of and instantiate script, ...</spec>
modulator_->TaskRunner()->PostTask(
FROM_HERE,
WTF::Bind(&ModuleTreeLinker::FetchDescendants, WrapPersistent(this),
WrapPersistent(module_script)));
}
-void ModuleTreeLinker::InitiateInternalModuleScriptGraphFetching(
- const ModuleScriptFetchRequest& request,
- ModuleGraphLevel level) {
- // [IMSGF] Step 1. Assert: visited set contains url.
- DCHECK(visited_set_.Contains(request.Url()));
-
- ++num_incomplete_fetches_;
-
- // [IMSGF] Step 2. Fetch a single module script given ...
- modulator_->FetchSingle(request, fetch_client_settings_object_fetcher_.Get(),
- level, custom_fetch_type_, this);
-
- // [IMSGF] Step 3-- are executed when NotifyModuleLoadFinished() is called.
-}
-
+// Returning from #fetch-a-single-module-script, calling from
+// #fetch-a-module-script-tree, #fetch-an-import()-module-script-graph, and
+// #fetch-a-module-worker-script-tree, and IMSGF.
void ModuleTreeLinker::NotifyModuleLoadFinished(ModuleScript* module_script) {
- // [IMSGF] Step 3. Return from this algorithm, and run the following steps
- // when fetching a single module script asynchronously completes with result:
-
CHECK_GT(num_incomplete_fetches_, 0u);
--num_incomplete_fetches_;
@@ -263,12 +290,8 @@ void ModuleTreeLinker::NotifyModuleLoadFinished(ModuleScript* module_script) {
#endif
if (state_ == State::kFetchingSelf) {
- // Corresponds to top-level calls to
- // https://html.spec.whatwg.org/C/#fetch-the-descendants-of-and-instantiate-a-module-script
- // i.e. [IMSGF] with the top-level module fetch flag set (external), or
- // Step 22 of "prepare a script" (inline).
- // |module_script| is the top-level module, and will be instantiated
- // and returned later.
+ // non-IMSGF cases: |module_script| is the top-level module, and will be
+ // instantiated and returned later.
result_ = module_script;
AdvanceState(State::kFetchingDependencies);
}
@@ -279,24 +302,43 @@ void ModuleTreeLinker::NotifyModuleLoadFinished(ModuleScript* module_script) {
return;
}
- // Note: top-level module fetch flag is implemented so that Instantiate()
- // is called once after all descendants are fetched, which corresponds to
- // the single invocation of "fetch the descendants of and instantiate".
-
- // [IMSGF] Step 4. If result is null, asynchronously complete this algorithm
- // with null, and abort these steps.
+ // <spec label="fetch-a-module-script-tree" step="2">If result is null,
+ // asynchronously complete this algorithm with null, and abort these
+ // steps.</spec>
+ //
+ // <spec label="fetch-an-import()-module-script-graph" step="4">If result is
+ // null, asynchronously complete this algorithm with null, and abort these
+ // steps.</spec>
+ //
+ // <spec label="fetch-a-module-worker-script-tree" step="3">If result is null,
+ // asynchronously complete this algorithm with null, and abort these
+ // steps.</spec>
+ //
+ // <spec label="IMSGF" step="4">If result is null, asynchronously complete
+ // this algorithm with null, and abort these steps.</spec>
if (!module_script) {
result_ = nullptr;
AdvanceState(State::kFinished);
return;
}
- // [IMSGF] Step 5. If the top-level module fetch flag is set, fetch the
- // descendants of and instantiate result given destination and visited set.
- // Otherwise, fetch the descendants of result given the same arguments.
+ // <spec label="fetch-a-module-script-tree" step="4">Fetch the descendants of
+ // and instantiate ...</spec>
+ //
+ // <spec label="fetch-an-import()-module-script-graph" step="6">Fetch the
+ // descendants of and instantiate result ...</spec>
+ //
+ // <spec label="fetch-a-module-worker-script-tree" step="5">Fetch the
+ // descendants of and instantiate result given fetch client settings object,
+ // ...</spec>
+ //
+ // <spec label="IMSGF" step="5">Fetch the descendants of result given fetch
+ // client settings object, destination, and visited set.</spec>
FetchDescendants(module_script);
}
+// <specdef
+// href="https://html.spec.whatwg.org/C/#fetch-the-descendants-of-a-module-script">
void ModuleTreeLinker::FetchDescendants(const ModuleScript* module_script) {
DCHECK(module_script);
@@ -307,11 +349,11 @@ void ModuleTreeLinker::FetchDescendants(const ModuleScript* module_script) {
return;
}
- // [FD] Step 2. Let record be module script's record.
+ // <spec step="2">Let record be module script's record.</spec>
ModuleRecord record = module_script->Record();
- // [FD] Step 1. If module script's record is null, then asynchronously
- // complete this algorithm with module script and abort these steps.
+ // <spec step="1">If module script's record is null, then asynchronously
+ // complete this algorithm with module script and abort these steps.</spec>
if (record.IsNull()) {
found_parse_error_ = true;
// We don't early-exit here and wait until all module scripts to be
@@ -326,36 +368,37 @@ void ModuleTreeLinker::FetchDescendants(const ModuleScript* module_script) {
return;
}
- // [FD] Step 3. If record.[[RequestedModules]] is empty, asynchronously
- // complete this algorithm with module script.
+ // <spec step="3">... if record.[[RequestedModules]] is empty, asynchronously
+ // complete this algorithm with module script.</spec>
//
// Note: We defer this bail-out until the end of the procedure. The rest of
// the procedure will be no-op anyway if record.[[RequestedModules]] is empty.
- // [FD] Step 4. Let urls be a new empty list.
+ // <spec step="4">Let urls be a new empty list.</spec>
Vector<KURL> urls;
Vector<TextPosition> positions;
- // [FD] Step 5. For each string requested of record.[[RequestedModules]],
+ // <spec step="5">For each string requested of
+ // record.[[RequestedModules]],</spec>
Vector<Modulator::ModuleRequest> module_requests =
modulator_->ModuleRequestsFromModuleRecord(record);
for (const auto& module_request : module_requests) {
- // [FD] Step 5.1. Let url be the result of resolving a module specifier
- // given module script and requested.
+ // <spec step="5.1">Let url be the result of resolving a module specifier
+ // given module script's base URL and requested.</spec>
KURL url = module_script->ResolveModuleSpecifier(module_request.specifier);
- // [FD] Step 5.2. Assert: url is never failure, because resolving a module
+ // <spec step="5.2">Assert: url is never failure, because resolving a module
// specifier must have been previously successful with these same two
- // arguments.
+ // arguments.</spec>
CHECK(url.IsValid()) << "ModuleScript::ResolveModuleSpecifier() impl must "
"return a valid url.";
- // [FD] Step 5.3. If visited set does not contain url, then:
+ // <spec step="5.3">If visited set does not contain url, then:</spec>
if (!visited_set_.Contains(url)) {
- // [FD] Step 5.3.1. Append url to urls.
+ // <spec step="5.3.1">Append url to urls.</spec>
urls.push_back(url);
- // [FD] Step 5.3.2. Append url to visited set.
+ // <spec step="5.3.2">Append url to visited set.</spec>
visited_set_.insert(url);
positions.push_back(module_request.position);
@@ -363,8 +406,8 @@ void ModuleTreeLinker::FetchDescendants(const ModuleScript* module_script) {
}
if (urls.IsEmpty()) {
- // [FD] Step 3. If record.[[RequestedModules]] is empty, asynchronously
- // complete this algorithm with module script.
+ // <spec step="3">... if record.[[RequestedModules]] is empty,
+ // asynchronously complete this algorithm with module script.</spec>
//
// Also, if record.[[RequestedModules]] is not empty but |urls| is
// empty here, we complete this algorithm.
@@ -372,12 +415,15 @@ void ModuleTreeLinker::FetchDescendants(const ModuleScript* module_script) {
return;
}
- // [FD] Step 6. Let options be the descendant script fetch options for module
- // script's fetch options.
- // https://html.spec.whatwg.org/C/#descendant-script-fetch-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 string.
+ // <spec step="6">Let options be the descendant script fetch options for
+ // module script's fetch options.</spec>
+ //
+ // <spec
+ // href="https://html.spec.whatwg.org/C/#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 string.</spec>
+ //
// TODO(domfarolino): It has not yet been decided how a root module script's
// "importance" mode should trickle down to imports. There is discussion of
// this at https://github.com/whatwg/html/issues/3670, but for now, descendant
@@ -389,20 +435,32 @@ void ModuleTreeLinker::FetchDescendants(const ModuleScript* module_script) {
module_script->FetchOptions().GetReferrerPolicy(),
mojom::FetchImportanceMode::kImportanceAuto);
- // [FD] Step 7. For each url in urls, ...
+ // <spec step="8">For each url in urls, ...</spec>
//
- // [FD] Step 7. These invocations of the internal module script graph fetching
- // procedure should be performed in parallel to each other.
+ // <spec step="8">... These invocations of the internal module script graph
+ // fetching procedure should be performed in parallel to each other.
+ // ...</spec>
for (wtf_size_t i = 0; i < urls.size(); ++i) {
- // [FD] Step 7. ... perform the internal module script graph fetching
+ // <spec step="8">... 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,
- // and with the top-level module fetch flag unset. ...
+ // module script's settings object, visited set, and module script's base
+ // URL. ...</spec>
ModuleScriptFetchRequest request(urls[i], destination_, options,
module_script->BaseURL().GetString(),
positions[i]);
- InitiateInternalModuleScriptGraphFetching(
- request, ModuleGraphLevel::kDependentModuleFetch);
+
+ // <spec label="IMSGF" step="1">Assert: visited set contains url.</spec>
+ DCHECK(visited_set_.Contains(request.Url()));
+
+ ++num_incomplete_fetches_;
+
+ // <spec label="IMSGF" step="2">Fetch a single module script given url,
+ // fetch client settings object, destination, options, module map settings
+ // object, referrer, and with the top-level module fetch flag unset.
+ // ...</spec>
+ modulator_->FetchSingle(
+ request, fetch_client_settings_object_fetcher_.Get(),
+ ModuleGraphLevel::kDependentModuleFetch, custom_fetch_type_, this);
}
// Asynchronously continue processing after NotifyModuleLoadFinished() is
@@ -413,16 +471,20 @@ void ModuleTreeLinker::FetchDescendants(const ModuleScript* module_script) {
void ModuleTreeLinker::FinalizeFetchDescendantsForOneModuleScript() {
// [FD] of a single module script is completed here:
//
- // [FD] Step 7. Otherwise, wait until all of the internal module script graph
- // fetching procedure invocations have asynchronously completed. ...
-
- // And, if |num_incomplete_fetches_| is 0, all the invocations of [FD]
- // (called from [FDaI] Step 2) of the root module script is completed here
- // and thus we proceed to [FDaI] Step 4 implemented by Instantiate().
+ // <spec step="8">... Otherwise, wait until all of the internal module script
+ // graph fetching procedure invocations have asynchronously completed.
+ // ...</spec>
+
+ // And, if |num_incomplete_fetches_| is 0, all the invocations of
+ // #fetch-the-descendants-of-a-module-script is completed here and we proceed
+ // to #fetch-the-descendants-of-and-instantiate-a-module-script Step 3
+ // implemented by Instantiate().
if (num_incomplete_fetches_ == 0)
Instantiate();
}
+// <specdef
+// href="https://html.spec.whatwg.org/C/#fetch-the-descendants-of-and-instantiate-a-module-script">
void ModuleTreeLinker::Instantiate() {
// [nospec] Abort the steps if the browsing context is discarded.
if (!modulator_->HasValidContext()) {
@@ -431,14 +493,14 @@ void ModuleTreeLinker::Instantiate() {
return;
}
- // [FDaI] Step 4. If result is null, then asynchronously complete this
- // algorithm with result.
+ // <spec step="3">If result is null, then asynchronously complete this
+ // algorithm with result.</spec>
if (!result_) {
AdvanceState(State::kFinished);
return;
}
- // [FDaI] Step 6. If parse error is null, then:
+ // <spec step="5">If parse error is null, then:</spec>
//
// [Optimization] If |found_parse_error_| is false (i.e. no parse errors
// were found during fetching), we are sure that |parse error| is null and
@@ -449,38 +511,40 @@ void ModuleTreeLinker::Instantiate() {
DCHECK(FindFirstParseError(result_, &discovered_set).IsEmpty());
#endif
- // [FDaI] Step 6.1. Let record be result's record.
+ // <spec step="5.1">Let record be result's record.</spec>
ModuleRecord record = result_->Record();
- // [FDaI] Step 6.2. Perform record.Instantiate().
+ // <spec step="5.2">Perform record.Instantiate(). ...</spec>
AdvanceState(State::kInstantiating);
ScriptValue instantiation_error = modulator_->InstantiateModule(record);
- // [FDaI] Step 6.2. If this throws an exception, set result's error to
- // rethrow to that exception.
+ // <spec step="5.2">... If this throws an exception, set result's error to
+ // rethrow to that exception.</spec>
if (!instantiation_error.IsEmpty())
result_->SetErrorToRethrow(instantiation_error);
} else {
- // [FDaI] Step 7. Otherwise ...
+ // <spec step="6">Otherwise, ...</spec>
- // [FFPE] Step 2. If discoveredSet was not given, let it be an empty set.
+ // <spec
+ // href="https://html.spec.whatwg.org/C/#finding-the-first-parse-error"
+ // step="2">If discoveredSet was not given, let it be an empty set.</spec>
HeapHashSet<Member<const ModuleScript>> discovered_set;
- // [FDaI] Step 5. Let parse error be the result of finding the first parse
- // error given result.
+ // <spec step="4">Let parse error be the result of finding the first parse
+ // error given result.</spec>
ScriptValue parse_error = FindFirstParseError(result_, &discovered_set);
DCHECK(!parse_error.IsEmpty());
- // [FDaI] Step 7. ... set result's error to rethrow to parse error.
+ // <spec step="6">... set result's error to rethrow to parse error.</spec>
result_->SetErrorToRethrow(parse_error);
}
- // [FDaI] Step 8. Asynchronously complete this algorithm with result.
+ // <spec step="7">Asynchronously complete this algorithm with result.</spec>
AdvanceState(State::kFinished);
}
-// [FFPE] https://html.spec.whatwg.org/C/#finding-the-first-parse-error
-//
+// <specdef
+// href="https://html.spec.whatwg.org/C/#finding-the-first-parse-error">
// This returns non-empty ScriptValue iff a parse error is found.
ScriptValue ModuleTreeLinker::FindFirstParseError(
const ModuleScript* module_script,
@@ -489,66 +553,69 @@ ScriptValue ModuleTreeLinker::FindFirstParseError(
// all module scripts in the graph are non-null.
DCHECK(module_script);
- // [FFPE] Step 1. Let moduleMap be moduleScript's settings object's module
- // map.
+ // <spec step="1">Let moduleMap be moduleScript's settings object's module
+ // map.</spec>
//
// This is accessed via |modulator_|.
// [FFPE] Step 2 is done before calling this in Instantiate().
- // [FFPE] Step 3. Append moduleScript to discoveredSet.
+ // <spec step="3">Append moduleScript to discoveredSet.</spec>
discovered_set->insert(module_script);
- // [FFPE] Step 4. If moduleScript's record is null, then return moduleScript's
- // parse error.
+ // <spec step="4">If moduleScript's record is null, then return moduleScript's
+ // parse error.</spec>
ModuleRecord record = module_script->Record();
if (record.IsNull())
return module_script->CreateParseError();
- // [FFPE] Step 5. Let childSpecifiers be the value of moduleScript's record's
- // [[RequestedModules]] internal slot.
+ // <spec step="5.1">Let childSpecifiers be the value of moduleScript's
+ // record's [[RequestedModules]] internal slot.</spec>
Vector<Modulator::ModuleRequest> child_specifiers =
modulator_->ModuleRequestsFromModuleRecord(record);
for (const auto& module_request : child_specifiers) {
- // [FFPE] Step 6. Let childURLs be the list obtained by calling resolve a
+ // <spec step="5.2">Let childURLs be the list obtained by calling resolve a
// module specifier once for each item of childSpecifiers, given
- // moduleScript and that item.
+ // moduleScript's base URL and that item. ...</spec>
KURL child_url =
module_script->ResolveModuleSpecifier(module_request.specifier);
- // [FFPE] Step 6. ... (None of these will ever fail, as otherwise
- // moduleScript would have been marked as itself having a parse error.)
+ // <spec step="5.2">... (None of these will ever fail, as otherwise
+ // moduleScript would have been marked as itself having a parse
+ // error.)</spec>
CHECK(child_url.IsValid())
<< "ModuleScript::ResolveModuleSpecifier() impl must "
"return a valid url.";
- // [FFPE] Step 7. Let childModules be the list obtained by getting each
- // value in moduleMap whose key is given by an item of childURLs.
+ // <spec step="5.3">Let childModules be the list obtained by getting each
+ // value in moduleMap whose key is given by an item of childURLs.</spec>
//
- // [FFPE] Step 8. For each childModule of childModules:
+ // <spec step="5.4">For each childModule of childModules:</spec>
const ModuleScript* child_module =
modulator_->GetFetchedModuleScript(child_url);
- // [FFPE] Step 8.1. Assert: childModule is a module script (i.e., it is not
- // "fetching" or null)
+ // <spec step="5.4.1">Assert: childModule is a module script (i.e., it is
+ // not "fetching" or null); ...</spec>
CHECK(child_module);
- // [FFPE] Step 8.2. If discoveredSet already contains childModule, continue.
+ // <spec step="5.4.2">If discoveredSet already contains childModule,
+ // continue.</spec>
if (discovered_set->Contains(child_module))
continue;
- // [FFPE] Step 8.3. Let childParseError be the result of finding the first
- // parse error given childModule and discoveredSet.
+ // <spec step="5.4.3">Let childParseError be the result of finding the first
+ // parse error given childModule and discoveredSet.</spec>
ScriptValue child_parse_error =
FindFirstParseError(child_module, discovered_set);
- // [FFPE] Step 8.4. If childParseError is not null, return childParseError.
+ // <spec step="5.4.4">If childParseError is not null, return
+ // childParseError.</spec>
if (!child_parse_error.IsEmpty())
return child_parse_error;
}
- // [FFPE] Step 9. Return null.
+ // <spec step="6">Return null.</spec>
return ScriptValue();
}
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 afe4b508599..aaa95665fa5 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
@@ -16,30 +16,21 @@
namespace blink {
-class ModuleScriptFetchRequest;
class ModuleTreeLinkerRegistry;
// A ModuleTreeLinker is responsible for running and keeping intermediate states
-// for a top-level [IMSGF] "internal module script graph fetching procedure" or
-// a top-level [FDaI] "fetch the descendants of and instantiate", and all the
-// invocations of [IMSGF] and [FD] "fetch the descendants" under that.
+// for top-level fetch * module script graph spec concepts and all the
+// invocations of #internal-module-script-graph-fetching-procedure and
+// #fetch-the-descendants-of-a-module-script.
//
// Modulator represents "a module map settings object" and
// ResourceFetcher represents "a fetch client settings object"
// by its |Context()->GetFetchClientSettingsObject()|.
-//
-// Spec links:
-// [IMSGF]
-// https://html.spec.whatwg.org/C/#internal-module-script-graph-fetching-procedure
-// [FD]
-// https://html.spec.whatwg.org/C/#fetch-the-descendants-of-a-module-script
-// [FDaI]
-// https://html.spec.whatwg.org/C/#fetch-the-descendants-of-and-instantiate-a-module-script
-// [FFPE]
-// https://html.spec.whatwg.org/C/#finding-the-first-parse-error
class CORE_EXPORT ModuleTreeLinker final : public SingleModuleClient {
public:
// https://html.spec.whatwg.org/C/#fetch-a-module-script-tree
+ // https://html.spec.whatwg.org/C/#fetch-a-module-worker-script-tree
+ // https://html.spec.whatwg.org/C/#fetch-an-import()-module-script-graph
static void Fetch(const KURL&,
ResourceFetcher* fetch_client_settings_object_fetcher,
mojom::RequestContextType destination,
@@ -49,7 +40,7 @@ class CORE_EXPORT ModuleTreeLinker final : public SingleModuleClient {
ModuleTreeLinkerRegistry*,
ModuleTreeClient*);
- // [FDaI] for an inline script.
+ // https://html.spec.whatwg.org/C/#fetch-an-inline-module-script-graph
static void FetchDescendantsForInlineScript(
ModuleScript*,
ResourceFetcher* fetch_client_settings_object_fetcher,
@@ -92,13 +83,6 @@ class CORE_EXPORT ModuleTreeLinker final : public SingleModuleClient {
void FetchRoot(const KURL&, const ScriptFetchOptions&);
void FetchRootInline(ModuleScript*);
- // Steps 1--2 of [IMSGF].
- void InitiateInternalModuleScriptGraphFetching(
- const ModuleScriptFetchRequest&,
- ModuleGraphLevel);
-
- // Steps 3--7 of [IMSGF], and [FD]/[FDaI] called from [IMSGF].
- // TODO(hiroshige): Currently
void NotifyModuleLoadFinished(ModuleScript*) override;
void FetchDescendants(const ModuleScript*);
@@ -123,8 +107,8 @@ class CORE_EXPORT ModuleTreeLinker final : public SingleModuleClient {
const Member<ModuleTreeClient> client_;
State state_ = State::kInitial;
- // Correspond to _result_ in
- // https://html.spec.whatwg.org/C/#internal-module-script-graph-fetching-procedure
+ // Correspond to _result_ in the top-level fetch * module script graph
+ // algorithms.
Member<ModuleScript> result_;
bool found_parse_error_ = false;
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 30399ede5af..730671ba679 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,7 +4,7 @@
#include "third_party/blink/renderer/core/loader/modulescript/worker_module_script_fetcher.h"
-#include "services/network/public/mojom/referrer_policy.mojom-shared.h"
+#include "services/network/public/mojom/referrer_policy.mojom-blink.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/core/origin_trials/origin_trial_context.h"
#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
@@ -20,7 +20,7 @@ WorkerModuleScriptFetcher::WorkerModuleScriptFetcher(
WorkerGlobalScope* global_scope)
: global_scope_(global_scope) {}
-// https://html.spec.whatwg.org/C/#worker-processing-model
+// <specdef href="https://html.spec.whatwg.org/C/#run-a-worker">
void WorkerModuleScriptFetcher::Fetch(
FetchParameters& fetch_params,
ResourceFetcher* fetch_client_settings_object_fetcher,
@@ -31,14 +31,16 @@ void WorkerModuleScriptFetcher::Fetch(
client_ = client;
level_ = level;
- // Step 12. "In both cases, to perform the fetch given request, perform the
- // following steps if the is top-level flag is set:" [spec text]
- // Step 12.1. "Set request's reserved client to inside settings." [spec text]
+ // <spec step="12">In both cases, to perform the fetch given request, perform
+ // the following steps if the is top-level flag is set:</spec>
+ //
+ // <spec step="12.1">Set request's reserved client to inside settings.</spec>
+ //
// This is implemented in the browser process.
- // Step 12.2. "Fetch request, and asynchronously wait to run the remaining
- // steps as part of fetch's process response for the response response." [spec
- // text]
+ // <spec step="12.2">Fetch request, and asynchronously wait to run the
+ // remaining steps as part of fetch's process response for the response
+ // response.</spec>
ScriptResource::Fetch(fetch_params, fetch_client_settings_object_fetcher,
this, ScriptResource::kNoStreaming);
}
@@ -128,10 +130,10 @@ void WorkerModuleScriptFetcher::NotifyFinished(Resource* resource) {
ModuleScriptCreationParams params(
script_resource->GetResponse().CurrentRequestUrl(),
script_resource->SourceText(), script_resource->CacheHandler(),
- script_resource->GetResourceRequest().GetFetchCredentialsMode());
+ script_resource->GetResourceRequest().GetCredentialsMode());
- // Step 12.7. "Asynchronously complete the perform the fetch steps with
- // response." [spec text]
+ // <spec step="12.7">Asynchronously complete the perform the fetch steps with
+ // response.</spec>
client_->NotifyFetchFinished(params, error_messages);
}
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 514deddb9aa..425b99a81c6 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
@@ -46,10 +46,10 @@ void WorkletModuleScriptFetcher::NotifyFinished(Resource* resource) {
ScriptResource* script_resource = ToScriptResource(resource);
HeapVector<Member<ConsoleMessage>> error_messages;
if (WasModuleLoadSuccessful(script_resource, &error_messages)) {
- params.emplace(
- script_resource->GetResponse().CurrentRequestUrl(),
- script_resource->SourceText(), script_resource->CacheHandler(),
- script_resource->GetResourceRequest().GetFetchCredentialsMode());
+ params.emplace(script_resource->GetResponse().CurrentRequestUrl(),
+ script_resource->SourceText(),
+ script_resource->CacheHandler(),
+ script_resource->GetResourceRequest().GetCredentialsMode());
}
// This will eventually notify |client| passed to
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 3ca8a1c8c02..2451d28ee42 100644
--- a/chromium/third_party/blink/renderer/core/loader/ping_loader.cc
+++ b/chromium/third_party/blink/renderer/core/loader/ping_loader.cc
@@ -228,8 +228,12 @@ void PingLoader::SendLinkAuditPing(LocalFrame* frame,
request.SetKeepalive(true);
// TODO(domfarolino): Add WPTs ensuring that pings do not have a referrer
// header.
- request.SetReferrerString(Referrer::NoReferrer());
- request.SetReferrerPolicy(network::mojom::ReferrerPolicy::kNever);
+ request.SetReferrerString(
+ Referrer::NoReferrer(),
+ ResourceRequest::SetReferrerStringLocation::kPingLoader);
+ request.SetReferrerPolicy(
+ network::mojom::ReferrerPolicy::kNever,
+ ResourceRequest::SetReferrerPolicyLocation::kPingLoader);
request.SetRequestContext(mojom::RequestContextType::PING);
FetchParameters params(request);
params.MutableOptions().initiator_info.name =
@@ -255,11 +259,10 @@ void PingLoader::SendViolationReport(LocalFrame* frame,
}
request.SetKeepalive(true);
request.SetHttpBody(std::move(report));
- request.SetFetchCredentialsMode(
- network::mojom::FetchCredentialsMode::kSameOrigin);
+ request.SetCredentialsMode(network::mojom::CredentialsMode::kSameOrigin);
request.SetRequestContext(mojom::RequestContextType::CSP_REPORT);
request.SetRequestorOrigin(frame->GetDocument()->GetSecurityOrigin());
- request.SetFetchRedirectMode(network::mojom::FetchRedirectMode::kError);
+ request.SetRedirectMode(network::mojom::RedirectMode::kError);
FetchParameters params(request);
params.MutableOptions().initiator_info.name =
fetch_initiator_type_names::kViolationreport;
diff --git a/chromium/third_party/blink/renderer/core/loader/prefetched_signed_exchange_manager.cc b/chromium/third_party/blink/renderer/core/loader/prefetched_signed_exchange_manager.cc
index 2e5bb1fae88..d65e7050798 100644
--- a/chromium/third_party/blink/renderer/core/loader/prefetched_signed_exchange_manager.cc
+++ b/chromium/third_party/blink/renderer/core/loader/prefetched_signed_exchange_manager.cc
@@ -7,7 +7,7 @@
#include "base/callback.h"
#include "base/memory/weak_ptr.h"
#include "base/optional.h"
-#include "third_party/blink/public/mojom/devtools/console_message.mojom-shared.h"
+#include "third_party/blink/public/mojom/devtools/console_message.mojom-blink.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_url_load_timing.h"
@@ -16,7 +16,9 @@
#include "third_party/blink/public/platform/web_url_loader_factory.h"
#include "third_party/blink/public/platform/web_url_response.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/frame/navigator.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/core/loader/alternate_signed_exchange_resource_info.h"
#include "third_party/blink/renderer/platform/loader/link_header.h"
@@ -39,9 +41,7 @@ class PrefetchedSignedExchangeManager::PrefetchedSignedExchangeLoader
PrefetchedSignedExchangeLoader(
const WebURLRequest& request,
scoped_refptr<base::SingleThreadTaskRunner> task_runner)
- : request_(request),
- task_runner_(std::move(task_runner)),
- weak_ptr_factory_(this) {}
+ : request_(request), task_runner_(std::move(task_runner)) {}
~PrefetchedSignedExchangeLoader() override {}
@@ -119,7 +119,7 @@ class PrefetchedSignedExchangeManager::PrefetchedSignedExchangeLoader
std::unique_ptr<WebURLLoader> url_loader_;
std::queue<base::OnceClosure> pending_method_calls_;
- base::WeakPtrFactory<PrefetchedSignedExchangeLoader> weak_ptr_factory_;
+ base::WeakPtrFactory<PrefetchedSignedExchangeLoader> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(PrefetchedSignedExchangeLoader);
};
@@ -131,7 +131,6 @@ PrefetchedSignedExchangeManager* PrefetchedSignedExchangeManager::MaybeCreate(
const String& inner_link_header,
WebVector<std::unique_ptr<WebNavigationParams::PrefetchedSignedExchange>>
prefetched_signed_exchanges) {
- DCHECK(RuntimeEnabledFeatures::SignedExchangeSubresourcePrefetchEnabled());
if (prefetched_signed_exchanges.empty())
return nullptr;
std::unique_ptr<AlternateSignedExchangeResourceInfo> alternative_resources =
@@ -163,7 +162,6 @@ PrefetchedSignedExchangeManager::PrefetchedSignedExchangeManager(
: frame_(frame),
alternative_resources_(std::move(alternative_resources)),
prefetched_exchanges_map_(std::move(prefetched_exchanges_map)) {
- DCHECK(RuntimeEnabledFeatures::SignedExchangeSubresourcePrefetchEnabled());
}
PrefetchedSignedExchangeManager::~PrefetchedSignedExchangeManager() {}
@@ -188,8 +186,9 @@ PrefetchedSignedExchangeManager::MaybeCreateURLLoader(
const WebURLRequest& request) {
if (started_)
return nullptr;
- const auto* matching_resource =
- alternative_resources_->FindMatchingEntry(request.Url());
+ const auto* matching_resource = alternative_resources_->FindMatchingEntry(
+ request.Url(), request.GetRequestContext(),
+ frame_->DomWindow()->navigator()->languages());
if (!matching_resource)
return nullptr;
@@ -221,7 +220,7 @@ PrefetchedSignedExchangeManager::CreatePrefetchedSignedExchangeURLLoader(
}
void PrefetchedSignedExchangeManager::TriggerLoad() {
- std::vector<WebNavigationParams::PrefetchedSignedExchange*>
+ Vector<WebNavigationParams::PrefetchedSignedExchange*>
maching_prefetched_exchanges;
for (auto loader : loaders_) {
if (!loader) {
@@ -231,8 +230,9 @@ void PrefetchedSignedExchangeManager::TriggerLoad() {
// arbitrary information to the publisher using this resource.
continue;
}
- const auto* matching_resource =
- alternative_resources_->FindMatchingEntry(loader->request().Url());
+ const auto* matching_resource = alternative_resources_->FindMatchingEntry(
+ loader->request().Url(), loader->request().GetRequestContext(),
+ frame_->DomWindow()->navigator()->languages());
const auto alternative_url = matching_resource->alternative_url();
if (!alternative_url.IsValid()) {
// There is no matching "alternate" link header in outer response header.
diff --git a/chromium/third_party/blink/renderer/core/loader/prefetched_signed_exchange_manager.h b/chromium/third_party/blink/renderer/core/loader/prefetched_signed_exchange_manager.h
index 834a9064005..9cad373739d 100644
--- a/chromium/third_party/blink/renderer/core/loader/prefetched_signed_exchange_manager.h
+++ b/chromium/third_party/blink/renderer/core/loader/prefetched_signed_exchange_manager.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_PREFETCHED_SIGNED_EXCHANGE_MANAGER_H_
#include "base/macros.h"
-#include "services/network/public/mojom/url_loader_factory.mojom-shared.h"
+#include "services/network/public/mojom/url_loader_factory.mojom-blink.h"
#include "third_party/blink/public/web/web_navigation_params.h"
#include "third_party/blink/renderer/core/loader/preload_helper.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
diff --git a/chromium/third_party/blink/renderer/core/loader/preload_helper.cc b/chromium/third_party/blink/renderer/core/loader/preload_helper.cc
index ac460df1e03..4a39b9e1e2c 100644
--- a/chromium/third_party/blink/renderer/core/loader/preload_helper.cc
+++ b/chromium/third_party/blink/renderer/core/loader/preload_helper.cc
@@ -12,9 +12,10 @@
#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/frame_console.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/navigator.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/frame/viewport_data.h"
#include "third_party/blink/renderer/core/html/parser/html_preload_scanner.h"
#include "third_party/blink/renderer/core/html/parser/html_srcset_parser.h"
@@ -31,6 +32,7 @@
#include "third_party/blink/renderer/core/loader/subresource_integrity_helper.h"
#include "third_party/blink/renderer/core/script/modulator.h"
#include "third_party/blink/renderer/core/script/script_loader.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_initiator_type_names.h"
#include "third_party/blink/renderer/platform/loader/fetch/raw_resource.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
@@ -280,7 +282,9 @@ Resource* PreloadHelper::PreloadIfNeeded(
resource_request.SetRequestContext(ResourceFetcher::DetermineRequestContext(
resource_type.value(), ResourceFetcher::kImageNotImageSet));
- resource_request.SetReferrerPolicy(params.referrer_policy);
+ resource_request.SetReferrerPolicy(
+ params.referrer_policy,
+ ResourceRequest::SetReferrerPolicyLocation::kPreloadIfNeeded);
resource_request.SetFetchImportanceMode(
GetFetchImportanceAttributeValue(params.importance));
@@ -295,6 +299,33 @@ Resource* PreloadHelper::PreloadIfNeeded(
link_fetch_params.SetCrossOriginAccessControl(document.GetSecurityOrigin(),
params.cross_origin);
}
+
+ const String& integrity_attr = params.integrity;
+ // TODO(crbug.com/981419): Honor the integrity attribute value for all
+ // supported preload destinations, not just the destinations that support SRI
+ // in the first place.
+ if (resource_type == ResourceType::kScript ||
+ resource_type == ResourceType::kCSSStyleSheet) {
+ if (!integrity_attr.IsEmpty()) {
+ IntegrityMetadataSet metadata_set;
+ SubresourceIntegrity::ParseIntegrityAttribute(
+ integrity_attr, SubresourceIntegrityHelper::GetFeatures(&document),
+ metadata_set);
+ link_fetch_params.SetIntegrityMetadata(metadata_set);
+ link_fetch_params.MutableResourceRequest().SetFetchIntegrity(
+ integrity_attr);
+ }
+ } else {
+ if (!integrity_attr.IsEmpty()) {
+ document.AddConsoleMessage(ConsoleMessage::Create(
+ mojom::ConsoleMessageSource::kOther,
+ mojom::ConsoleMessageLevel::kWarning,
+ String("The `integrity` attribute is currently ignored for preload "
+ "destinations that do not support subresource integrity. See "
+ "https://crbug.com/981419 for more information")));
+ }
+ }
+
link_fetch_params.SetContentSecurityPolicyNonce(params.nonce);
Settings* settings = document.GetSettings();
if (settings && settings->GetLogPreload()) {
@@ -387,7 +418,7 @@ void PreloadHelper::ModulePreloadIfNeeded(
// Step 6. "Let credentials mode be the module script credentials mode for the
// crossorigin attribute." [spec text]
- network::mojom::FetchCredentialsMode credentials_mode =
+ network::mojom::CredentialsMode credentials_mode =
ScriptLoader::ModuleScriptCredentialsMode(params.cross_origin);
// Step 7. "Let cryptographic nonce be the value of the nonce attribute, if it
@@ -450,7 +481,9 @@ Resource* PreloadHelper::PrefetchIfNeeded(const LinkLoadParameters& params,
UseCounter::Count(document, WebFeature::kLinkRelPrefetch);
ResourceRequest resource_request(params.href);
- resource_request.SetReferrerPolicy(params.referrer_policy);
+ resource_request.SetReferrerPolicy(
+ params.referrer_policy,
+ ResourceRequest::SetReferrerPolicyLocation::kPrefetchIfNeeded);
resource_request.SetFetchImportanceMode(
GetFetchImportanceAttributeValue(params.importance));
@@ -462,6 +495,11 @@ Resource* PreloadHelper::PrefetchIfNeeded(const LinkLoadParameters& params,
link_fetch_params.SetCrossOriginAccessControl(
document.GetSecurityOrigin(), params.cross_origin);
}
+ link_fetch_params.SetSignedExchangePrefetchCacheEnabled(
+ RuntimeEnabledFeatures::
+ SignedExchangePrefetchCacheForNavigationsEnabled() ||
+ RuntimeEnabledFeatures::SignedExchangeSubresourcePrefetchEnabled(
+ &document));
return LinkFetchResource::Fetch(ResourceType::kLinkPrefetch,
link_fetch_params, document.Fetcher());
}
@@ -490,14 +528,22 @@ void PreloadHelper::LoadLinksFromHeader(
if (media_policy == kOnlyLoadNonMedia && header.IsViewportDependent())
continue;
+ // TODO(domfarolino): Remove the following UseCounter-related lines when
+ // data on link stylesheet headers has been collected. See
+ // https://crbug.com/19237.
+ DCHECK_EQ(header.Rel(), header.Rel().DeprecatedLower());
+ if (header.Rel() == "stylesheet")
+ UseCounter::Count(document, WebFeature::kLinkHeaderStylesheet);
+
LinkLoadParameters params(header, base_url);
if (alternate_resource_info && params.rel.IsLinkPreload()) {
- DCHECK(
- RuntimeEnabledFeatures::SignedExchangeSubresourcePrefetchEnabled());
+ DCHECK(document);
+ DCHECK(RuntimeEnabledFeatures::SignedExchangeSubresourcePrefetchEnabled(
+ document));
KURL url = params.href;
base::Optional<ResourceType> resource_type =
PreloadHelper::GetResourceTypeFromAsAttribute(params.as);
- if (document && resource_type == ResourceType::kImage &&
+ if (resource_type == ResourceType::kImage &&
!params.image_srcset.IsEmpty()) {
// |media_values| is created based on the viewport dimensions of the
// current page that prefetched SXGs, not on the viewport of the SXG
@@ -510,9 +556,12 @@ void PreloadHelper::LoadLinksFromHeader(
params.image_srcset, params.image_sizes);
}
const auto* alternative_resource =
- alternate_resource_info->FindMatchingEntry(url);
+ alternate_resource_info->FindMatchingEntry(
+ url, resource_type, frame.DomWindow()->navigator()->languages());
if (alternative_resource &&
alternative_resource->alternative_url().IsValid()) {
+ UseCounter::Count(document,
+ WebFeature::kSignedExchangeSubresourcePrefetch);
params.href = alternative_resource->alternative_url();
// Change the rel to "prefetch" to trigger the prefetch logic. This
// request will be handled by a PrefetchURLLoader in the browser
@@ -526,8 +575,7 @@ void PreloadHelper::LoadLinksFromHeader(
// undesirable alternative resource association that affects the next
// navigation, but can only populate things in the cache that can be
// used by the next navigation only when they requested the same URL
- // with the same association mapping. TODO(crbug.com/935267): Implement
- // this logic.
+ // with the same association mapping.
params.rel = LinkRelAttribute("prefetch");
}
}
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 41718e7a9f1..620197da5e3 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
@@ -9,7 +9,7 @@
#include "services/metrics/public/cpp/ukm_builders.h"
#include "services/metrics/public/cpp/ukm_recorder.h"
#include "third_party/blink/public/common/features.h"
-#include "third_party/blink/public/mojom/devtools/console_message.mojom-shared.h"
+#include "third_party/blink/public/mojom/devtools/console_message.mojom-blink.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"
@@ -17,6 +17,7 @@
#include "third_party/blink/renderer/platform/weborigin/kurl.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 {
@@ -34,23 +35,42 @@ String GetConsoleLogStringForBlockedLoad(const KURL& url) {
PreviewsResourceLoadingHints* PreviewsResourceLoadingHints::Create(
ExecutionContext& execution_context,
int64_t ukm_source_id,
- const std::vector<WTF::String>& subresource_patterns_to_block) {
+ const WebVector<WebString>& subresource_patterns_to_block) {
return MakeGarbageCollected<PreviewsResourceLoadingHints>(
&execution_context, ukm_source_id, subresource_patterns_to_block);
}
+// static
+PreviewsResourceLoadingHints*
+PreviewsResourceLoadingHints::CreateFromLoadingHintsProvider(
+ ExecutionContext& execution_context,
+ std::unique_ptr<WebLoadingHintsProvider> loading_hints_provider) {
+ WebVector<WebString> subresource_patterns_to_block;
+ for (const auto& pattern :
+ loading_hints_provider->subresource_patterns_to_block) {
+ // |pattern| is guaranteed to be ascii.
+ subresource_patterns_to_block.emplace_back(pattern);
+ }
+
+ return MakeGarbageCollected<PreviewsResourceLoadingHints>(
+ &execution_context, loading_hints_provider->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)
+ const WebVector<WebString>& subresource_patterns_to_block)
: execution_context_(execution_context),
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);
+ subresource_patterns_to_block_usage_.Fill(
+ false,
+ static_cast<WTF::wtf_size_t>(subresource_patterns_to_block.size()));
+ blocked_resource_load_priority_counts_.Fill(
+ 0, static_cast<int>(ResourceLoadPriority::kHighest) + 1);
// Populate which specific resource types are eligible for blocking.
// Certain resource types are blocked by default since their blocking
@@ -64,7 +84,7 @@ PreviewsResourceLoadingHints::PreviewsResourceLoadingHints(
// should be either "true" or "false".
block_resource_type_[i] = base::GetFieldTrialParamByFeatureAsBool(
features::kPreviewsResourceLoadingHintsSpecificResourceTypes,
- String::Format("block_resource_type_%d", i).Ascii().data(),
+ String::Format("block_resource_type_%d", i).Ascii(),
block_resource_type_[i]);
}
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 0065639aa40..8eed4903953 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
@@ -5,15 +5,15 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_PREVIEWS_RESOURCE_LOADING_HINTS_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_PREVIEWS_RESOURCE_LOADING_HINTS_H_
-#include <vector>
-
#include "base/feature_list.h"
+#include "third_party/blink/public/platform/web_loading_hints_provider.h"
#include "third_party/blink/renderer/core/core_export.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/loader/fetch/resource.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_load_priority.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
+#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace ukm {
class UkmRecorder;
@@ -32,12 +32,16 @@ class CORE_EXPORT PreviewsResourceLoadingHints final
static PreviewsResourceLoadingHints* Create(
ExecutionContext& execution_context,
int64_t ukm_source_id,
- const std::vector<WTF::String>& subresource_patterns_to_block);
+ const WebVector<WebString>& subresource_patterns_to_block);
+
+ static PreviewsResourceLoadingHints* CreateFromLoadingHintsProvider(
+ ExecutionContext& execution_context,
+ std::unique_ptr<WebLoadingHintsProvider> loading_hints_provider);
PreviewsResourceLoadingHints(
ExecutionContext* execution_context,
int64_t ukm_source_id,
- const std::vector<WTF::String>& subresource_patterns_to_block);
+ const WebVector<WebString>& subresource_patterns_to_block);
~PreviewsResourceLoadingHints();
// Returns true if load of resource with type |type|, URL |resource_url|
@@ -63,10 +67,10 @@ class CORE_EXPORT PreviewsResourceLoadingHints final
// |subresource_patterns_to_block_| is a collection of subresource patterns
// for resources whose loading should be blocked. Each pattern is a
- // WTF::String. If a subresource URL contains any of the strings specified in
+ // WebString. If a subresource URL contains any of the strings specified in
// |subresource_patterns_to_block_|, then that subresource's loading could
// be blocked.
- const std::vector<WTF::String> subresource_patterns_to_block_;
+ const WebVector<WebString> subresource_patterns_to_block_;
// True if resource blocking hints should apply to resource of a given type.
bool block_resource_type_[static_cast<int>(ResourceType::kMaxValue) + 1] = {
@@ -74,12 +78,11 @@ class CORE_EXPORT PreviewsResourceLoadingHints final
// |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_;
+ mutable 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_;
+ mutable Vector<int> 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 656866d0c57..0e4c1d03f1e 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
@@ -4,9 +4,8 @@
#include "third_party/blink/renderer/core/loader/previews_resource_loading_hints_receiver_impl.h"
-#include <vector>
-
#include "base/metrics/histogram_macros.h"
+#include "third_party/blink/public/common/features.h"
#include "third_party/blink/renderer/core/loader/document_loader.h"
#include "third_party/blink/renderer/core/loader/previews_resource_loading_hints.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
@@ -17,7 +16,10 @@ PreviewsResourceLoadingHintsReceiverImpl::
PreviewsResourceLoadingHintsReceiverImpl(
mojom::blink::PreviewsResourceLoadingHintsReceiverRequest request,
Document* document)
- : binding_(this, std::move(request)), document_(document) {}
+ : binding_(this, std::move(request)), document_(document) {
+ DCHECK(!base::FeatureList::IsEnabled(
+ blink::features::kSendPreviewsLoadingHintsBeforeCommit));
+}
PreviewsResourceLoadingHintsReceiverImpl::
~PreviewsResourceLoadingHintsReceiverImpl() {}
@@ -30,7 +32,7 @@ void PreviewsResourceLoadingHintsReceiverImpl::SetResourceLoadingHints(
"ResourceLoadingHints.CountBlockedSubresourcePatterns",
resource_loading_hints->subresources_to_block.size());
- std::vector<WTF::String> subresource_patterns_to_block;
+ Vector<WTF::String> subresource_patterns_to_block;
for (const auto& subresource :
resource_loading_hints->subresources_to_block) {
subresource_patterns_to_block.push_back(subresource);
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 d2380c72713..17784531c31 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
@@ -5,7 +5,6 @@
#include "third_party/blink/renderer/core/loader/previews_resource_loading_hints.h"
#include <memory>
-#include <vector>
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
@@ -40,7 +39,7 @@ class PreviewsResourceLoadingHintsTest : public PageTestBase {
};
TEST_F(PreviewsResourceLoadingHintsTest, NoPatterns) {
- std::vector<WTF::String> subresources_to_block;
+ Vector<WTF::String> subresources_to_block;
PreviewsResourceLoadingHints* hints = PreviewsResourceLoadingHints::Create(
dummy_page_holder_->GetDocument(), ukm::UkmRecorder::GetNewSourceID(),
@@ -51,7 +50,7 @@ TEST_F(PreviewsResourceLoadingHintsTest, NoPatterns) {
}
TEST_F(PreviewsResourceLoadingHintsTest, OnePattern) {
- std::vector<WTF::String> subresources_to_block;
+ Vector<WTF::String> subresources_to_block;
subresources_to_block.push_back("foo.jpg");
PreviewsResourceLoadingHints* hints = PreviewsResourceLoadingHints::Create(
@@ -112,7 +111,7 @@ TEST_F(PreviewsResourceLoadingHintsTest, OnePattern) {
}
TEST_F(PreviewsResourceLoadingHintsTest, MultiplePatterns) {
- std::vector<WTF::String> subresources_to_block;
+ Vector<WTF::String> subresources_to_block;
subresources_to_block.push_back(".example1.com/foo.jpg");
subresources_to_block.push_back(".example1.com/bar.jpg");
subresources_to_block.push_back(".example2.com/baz.jpg");
@@ -146,7 +145,7 @@ TEST_F(PreviewsResourceLoadingHintsTest, MultiplePatterns) {
}
TEST_F(PreviewsResourceLoadingHintsTest, OnePatternHistogramChecker) {
- std::vector<WTF::String> subresources_to_block;
+ Vector<WTF::String> subresources_to_block;
subresources_to_block.push_back("foo.jpg");
PreviewsResourceLoadingHints* hints = PreviewsResourceLoadingHints::Create(
@@ -199,7 +198,7 @@ TEST_F(PreviewsResourceLoadingHintsTest, OnePatternHistogramChecker) {
}
TEST_F(PreviewsResourceLoadingHintsTest, MultiplePatternUKMChecker) {
- std::vector<WTF::String> subresources_to_block;
+ 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");
@@ -298,7 +297,7 @@ class PreviewsResourceLoadingHintsTestBlockImages
TEST_F(PreviewsResourceLoadingHintsTestBlockImages,
OnePatternWithResourceSubtype) {
- std::vector<WTF::String> subresources_to_block;
+ Vector<WTF::String> subresources_to_block;
subresources_to_block.push_back("foo.jpg");
PreviewsResourceLoadingHints* hints = PreviewsResourceLoadingHints::Create(
@@ -354,7 +353,7 @@ class PreviewsResourceLoadingHintsTestAllowCSS
TEST_F(PreviewsResourceLoadingHintsTestAllowCSS,
OnePatternWithResourceSubtype) {
- std::vector<WTF::String> subresources_to_block;
+ Vector<WTF::String> subresources_to_block;
subresources_to_block.push_back("foo.jpg");
PreviewsResourceLoadingHints* hints = PreviewsResourceLoadingHints::Create(
diff --git a/chromium/third_party/blink/renderer/core/loader/private/frame_client_hints_preferences_context.cc b/chromium/third_party/blink/renderer/core/loader/private/frame_client_hints_preferences_context.cc
index 908dca814dd..2d73edca099 100644
--- a/chromium/third_party/blink/renderer/core/loader/private/frame_client_hints_preferences_context.cc
+++ b/chromium/third_party/blink/renderer/core/loader/private/frame_client_hints_preferences_context.cc
@@ -6,7 +6,7 @@
#include "base/stl_util.h"
#include "third_party/blink/renderer/core/dom/document.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/loader/private/frame_client_hints_preferences_context.h b/chromium/third_party/blink/renderer/core/loader/private/frame_client_hints_preferences_context.h
index cb24274256f..ebbebd507bb 100644
--- a/chromium/third_party/blink/renderer/core/loader/private/frame_client_hints_preferences_context.h
+++ b/chromium/third_party/blink/renderer/core/loader/private/frame_client_hints_preferences_context.h
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/platform/heap/persistent.h"
#include "third_party/blink/renderer/platform/loader/fetch/client_hints_preferences.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
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 bc1ccb73de4..01aaa2809ba 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,7 +30,7 @@
#include "third_party/blink/renderer/core/loader/private/prerender_handle.h"
-#include "services/network/public/mojom/referrer_policy.mojom-shared.h"
+#include "services/network/public/mojom/referrer_policy.mojom-blink.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"
@@ -54,7 +54,8 @@ PrerenderHandle* PrerenderHandle::Create(Document& document,
auto* prerender = MakeGarbageCollected<Prerender>(
client, url, prerender_rel_types,
SecurityPolicy::GenerateReferrer(document.GetReferrerPolicy(), url,
- document.OutgoingReferrer()));
+ document.OutgoingReferrer()),
+ document.GetSecurityOrigin());
PrerendererClient* prerenderer_client =
PrerendererClient::From(document.GetPage());
@@ -68,7 +69,9 @@ PrerenderHandle* PrerenderHandle::Create(Document& document,
PrerenderHandle::PrerenderHandle(Document& document, Prerender* prerender)
: ContextLifecycleObserver(&document), prerender_(prerender) {}
-PrerenderHandle::~PrerenderHandle() {
+PrerenderHandle::~PrerenderHandle() = default;
+
+void PrerenderHandle::Dispose() {
if (prerender_) {
prerender_->Abandon();
Detach();
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 f380c8333c8..14ad87f0870 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
@@ -46,6 +46,7 @@ class PrerenderClient;
class PrerenderHandle final : public GarbageCollectedFinalized<PrerenderHandle>,
public ContextLifecycleObserver {
USING_GARBAGE_COLLECTED_MIXIN(PrerenderHandle);
+ USING_PRE_FINALIZER(PrerenderHandle, Dispose);
public:
static PrerenderHandle* Create(Document&,
@@ -55,6 +56,7 @@ class PrerenderHandle final : public GarbageCollectedFinalized<PrerenderHandle>,
PrerenderHandle(Document&, Prerender*);
virtual ~PrerenderHandle();
+ void Dispose();
void Cancel();
const KURL& Url() const;
@@ -63,7 +65,6 @@ class PrerenderHandle final : public GarbageCollectedFinalized<PrerenderHandle>,
void ContextDestroyed(ExecutionContext*) override;
void Trace(blink::Visitor*) override;
- EAGERLY_FINALIZE();
private:
void Detach();
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 9ec575f0e16..bdff8d67f63 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
@@ -37,13 +37,12 @@ class ProgrammaticScrollTest : public testing::Test {
}
protected:
- void RegisterMockedHttpURLLoad(const std::string& file_name) {
+ void RegisterMockedHttpURLLoad(const String& file_name) {
url_test_helpers::RegisterMockedURLLoadFromBase(
- WebString::FromUTF8(base_url_), test::CoreTestDataPath(),
- WebString::FromUTF8(file_name));
+ WebString(base_url_), test::CoreTestDataPath(), WebString(file_name));
}
- std::string base_url_;
+ String base_url_;
};
TEST_F(ProgrammaticScrollTest, RestoreScrollPositionAndViewStateWithScale) {
@@ -51,7 +50,7 @@ TEST_F(ProgrammaticScrollTest, RestoreScrollPositionAndViewStateWithScale) {
frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view =
- web_view_helper.InitializeAndLoad(base_url_ + "long_scroll.html");
+ web_view_helper.InitializeAndLoad(base_url_.Utf8() + "long_scroll.html");
web_view->MainFrameWidget()->Resize(WebSize(1000, 1000));
web_view->MainFrameWidget()->UpdateAllLifecyclePhases(
WebWidget::LifecycleUpdateReason::kTest);
@@ -84,7 +83,7 @@ TEST_F(ProgrammaticScrollTest, RestoreScrollPositionAndViewStateWithoutScale) {
frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view =
- web_view_helper.InitializeAndLoad(base_url_ + "long_scroll.html");
+ web_view_helper.InitializeAndLoad(base_url_.Utf8() + "long_scroll.html");
web_view->MainFrameWidget()->Resize(WebSize(1000, 1000));
web_view->MainFrameWidget()->UpdateAllLifecyclePhases(
WebWidget::LifecycleUpdateReason::kTest);
@@ -114,7 +113,7 @@ TEST_F(ProgrammaticScrollTest, SaveScrollStateClearsAnchor) {
frame_test_helpers::WebViewHelper web_view_helper;
WebViewImpl* web_view =
- web_view_helper.InitializeAndLoad(base_url_ + "long_scroll.html");
+ web_view_helper.InitializeAndLoad(base_url_.Utf8() + "long_scroll.html");
web_view->MainFrameWidget()->Resize(WebSize(1000, 1000));
web_view->MainFrameWidget()->UpdateAllLifecyclePhases(
WebWidget::LifecycleUpdateReason::kTest);
@@ -159,12 +158,12 @@ TEST_F(ProgrammaticScrollSimTest, NavigateToHash) {
body {
height: 4000px;
}
- h2 {
+ div {
position: absolute;
top: 3000px;
}
</style>
- <h2 id="target">Target</h2>
+ <div id="target">Target</h2>
)HTML");
main_resource.Finish();
css_resource.Complete();
@@ -175,7 +174,7 @@ TEST_F(ProgrammaticScrollSimTest, NavigateToHash) {
test::RunPendingTasks();
ScrollableArea* layout_viewport = GetDocument().View()->LayoutViewport();
- EXPECT_EQ(3001, layout_viewport->GetScrollOffset().Height());
+ EXPECT_EQ(3000, layout_viewport->GetScrollOffset().Height());
}
} // namespace blink
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 23998dbf4c3..8b458a21027 100644
--- a/chromium/third_party/blink/renderer/core/loader/progress_tracker.cc
+++ b/chromium/third_party/blink/renderer/core/loader/progress_tracker.cc
@@ -38,7 +38,6 @@
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
#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/text/cstring.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
namespace blink {
@@ -218,7 +217,7 @@ void ProgressTracker::MaybeSendProgress() {
if (progress_value_ < last_notified_progress_value_)
return;
- double now = CurrentTime();
+ double now = base::Time::Now().ToDoubleT();
double notified_progress_time_delta = now - last_notified_progress_time_;
double notification_progress_delta =
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 0e4ba58f0b6..94be6b94041 100644
--- a/chromium/third_party/blink/renderer/core/loader/progress_tracker.h
+++ b/chromium/third_party/blink/renderer/core/loader/progress_tracker.h
@@ -33,7 +33,7 @@
#include "third_party/blink/renderer/core/loader/frame_loader_types.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_load_priority.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
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 0e884737d1f..070f330bbac 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
@@ -55,7 +55,7 @@ CSSStyleSheetResource* CSSStyleSheetResource::CreateForTest(
const KURL& url,
const WTF::TextEncoding& encoding) {
ResourceRequest request(url);
- request.SetFetchCredentialsMode(network::mojom::FetchCredentialsMode::kOmit);
+ request.SetCredentialsMode(network::mojom::CredentialsMode::kOmit);
ResourceLoaderOptions options;
TextResourceDecoderOptions decoder_options(
TextResourceDecoderOptions::kCSSContent, encoding);
diff --git a/chromium/third_party/blink/renderer/core/loader/resource/document_resource.cc b/chromium/third_party/blink/renderer/core/loader/resource/document_resource.cc
index 018321d90b5..1ad946d56b1 100644
--- a/chromium/third_party/blink/renderer/core/loader/resource/document_resource.cc
+++ b/chromium/third_party/blink/renderer/core/loader/resource/document_resource.cc
@@ -36,8 +36,8 @@ namespace blink {
DocumentResource* DocumentResource::FetchSVGDocument(FetchParameters& params,
ResourceFetcher* fetcher,
ResourceClient* client) {
- DCHECK_EQ(params.GetResourceRequest().GetFetchRequestMode(),
- network::mojom::FetchRequestMode::kSameOrigin);
+ DCHECK_EQ(params.GetResourceRequest().GetMode(),
+ network::mojom::RequestMode::kSameOrigin);
params.SetRequestContext(mojom::RequestContextType::IMAGE);
return ToDocumentResource(
fetcher->RequestResource(params, SVGDocumentResourceFactory(), client));
diff --git a/chromium/third_party/blink/renderer/core/loader/resource/font_resource.cc b/chromium/third_party/blink/renderer/core/loader/resource/font_resource.cc
index 2ef8f169978..4d8f1a9eac2 100644
--- a/chromium/third_party/blink/renderer/core/loader/resource/font_resource.cc
+++ b/chromium/third_party/blink/renderer/core/loader/resource/font_resource.cc
@@ -29,7 +29,7 @@
#include "third_party/blink/public/mojom/loader/request_context_frame_type.mojom-blink.h"
#include "third_party/blink/renderer/platform/fonts/font_custom_platform_data.h"
#include "third_party/blink/renderer/platform/fonts/font_platform_data.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_client_walker.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
@@ -44,8 +44,10 @@ namespace blink {
// https://tabatkins.github.io/specs/css-font-display/#font-display-desc
// TODO(toyoshim): Revisit short limit value once cache-aware font display is
// launched. crbug.com/570205
-constexpr TimeDelta kFontLoadWaitShort = TimeDelta::FromMilliseconds(100);
-constexpr TimeDelta kFontLoadWaitLong = TimeDelta::FromMilliseconds(3000);
+constexpr base::TimeDelta kFontLoadWaitShort =
+ base::TimeDelta::FromMilliseconds(100);
+constexpr base::TimeDelta kFontLoadWaitLong =
+ base::TimeDelta::FromMilliseconds(3000);
enum FontPackageFormat {
kPackageFormatUnknown,
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 85b72c95a1c..887b06698c0 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
@@ -7,7 +7,7 @@
#include "base/test/scoped_feature_list.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/features.h"
-#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-shared.h"
+#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.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/renderer/core/css/css_font_face_src_value.h"
@@ -128,7 +128,7 @@ TEST_F(CacheAwareFontResourceTest, CacheAwareFontLoading) {
CSSFontFaceSrcValue* src_value = CSSFontFaceSrcValue::Create(
url.GetString(), url.GetString(),
Referrer(document.Url(), document.GetReferrerPolicy()),
- kDoNotCheckContentSecurityPolicy);
+ kDoNotCheckContentSecurityPolicy, OriginClean::kTrue);
// Route font requests in this test through CSSFontFaceSrcValue::Fetch
// instead of calling FontResource::Fetch directly. CSSFontFaceSrcValue
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 85dd5d56c49..ba87072e739 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
@@ -32,8 +32,8 @@
#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"
-#include "third_party/blink/renderer/platform/histogram.h"
-#include "third_party/blink/renderer/platform/instance_counters.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_initiator_type_names.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h"
@@ -62,15 +62,7 @@ namespace {
// The amount of time to wait before informing the clients that the image has
// been updated (in seconds). This effectively throttles invalidations that
// result from new data arriving for this image.
-constexpr auto kFlushDelay = TimeDelta::FromSeconds(1);
-
-bool HasServerLoFiResponseHeaders(const ResourceResponse& response) {
- return response.HttpHeaderField("chrome-proxy-content-transform")
- .Contains("empty-image") ||
- // Check for the legacy Server Lo-Fi response headers, since it's
- // possible that an old Lo-Fi image could be served from the cache.
- response.HttpHeaderField("chrome-proxy").Contains("q=low");
-}
+constexpr auto kFlushDelay = base::TimeDelta::FromSeconds(1);
} // namespace
@@ -91,7 +83,7 @@ class ImageResource::ImageResourceInfoImpl final
private:
const KURL& Url() const override { return resource_->Url(); }
- TimeTicks LoadResponseEnd() const override {
+ base::TimeTicks LoadResponseEnd() const override {
return resource_->LoadResponseEnd();
}
bool IsSchedulingReload() const override {
@@ -359,13 +351,13 @@ void ImageResource::AppendData(const char* data, size_t length) {
if (!is_pending_flushing_) {
scoped_refptr<base::SingleThreadTaskRunner> task_runner =
Loader()->GetLoadingTaskRunner();
- TimeTicks now = CurrentTimeTicks();
+ base::TimeTicks now = base::TimeTicks::Now();
if (last_flush_time_.is_null())
last_flush_time_ = now;
DCHECK_LE(last_flush_time_, now);
- TimeDelta flush_delay =
- std::max(TimeDelta(), last_flush_time_ - now + kFlushDelay);
+ base::TimeDelta flush_delay =
+ std::max(base::TimeDelta(), last_flush_time_ - now + kFlushDelay);
task_runner->PostDelayedTask(FROM_HERE,
WTF::Bind(&ImageResource::FlushImageIfNeeded,
WrapWeakPersistent(this)),
@@ -379,7 +371,7 @@ void ImageResource::FlushImageIfNeeded() {
// We might have already loaded the image fully, in which case we don't need
// to call |updateImage()|.
if (IsLoading()) {
- last_flush_time_ = CurrentTimeTicks();
+ last_flush_time_ = base::TimeTicks::Now();
UpdateImage(Data(), ImageResourceContent::kUpdateImage, false);
}
is_pending_flushing_ = false;
@@ -402,9 +394,8 @@ void ImageResource::DecodeError(bool all_data_received) {
// Observers are notified via ImageResource::finish().
// TODO(hiroshige): Do not call didFinishLoading() directly.
Loader()->AbortResponseBodyLoading();
- Loader()->DidFinishLoading(
- CurrentTimeTicks(), size, size, size, false,
- std::vector<network::cors::PreflightTimingInfo>());
+ Loader()->DidFinishLoading(base::TimeTicks::Now(), size, size, size, false,
+ {});
} else {
auto result = GetContent()->UpdateImage(
nullptr, GetStatus(),
@@ -427,7 +418,7 @@ void ImageResource::NotifyStartLoad() {
GetContent()->NotifyStartLoad();
}
-void ImageResource::Finish(TimeTicks load_finish_time,
+void ImageResource::Finish(base::TimeTicks load_finish_time,
base::SingleThreadTaskRunner* task_runner) {
if (multipart_parser_) {
if (!ErrorOccurred())
@@ -510,44 +501,9 @@ void ImageResource::ResponseReceived(const ResourceResponse& response) {
placeholder_option_ = PlaceholderOption::kReloadPlaceholderOnDecodeError;
}
}
-
- if (HasServerLoFiResponseHeaders(GetResponse())) {
- // Ensure that the PreviewsState bit for Server Lo-Fi is set iff Chrome
- // received the appropriate Server Lo-Fi response headers for this image.
- //
- // Normally, the |kServerLoFiOn| bit should already be set if Server Lo-Fi
- // response headers are coming back, but it's possible for legacy Lo-Fi
- // images to be served from the cache even if Chrome isn't in Lo-Fi mode.
- // This also serves as a nice last line of defence to ensure that Server
- // Lo-Fi images can be reloaded to show the original even if e.g. a server
- // bug causes Lo-Fi images to be sent when they aren't expected.
- SetPreviewsState(GetResourceRequest().GetPreviewsState() |
- WebURLRequest::kServerLoFiOn);
- } else if (GetResourceRequest().GetPreviewsState() &
- WebURLRequest::kServerLoFiOn) {
- // If Chrome expects a Lo-Fi response, but the server decided to send the
- // full image, then clear the Server Lo-Fi Previews state bit.
- WebURLRequest::PreviewsState new_previews_state =
- GetResourceRequest().GetPreviewsState();
-
- new_previews_state &= ~WebURLRequest::kServerLoFiOn;
- if (new_previews_state == WebURLRequest::kPreviewsUnspecified)
- new_previews_state = WebURLRequest::kPreviewsOff;
-
- SetPreviewsState(new_previews_state);
- }
}
bool ImageResource::ShouldShowPlaceholder() const {
- if (RuntimeEnabledFeatures::ClientPlaceholdersForServerLoFiEnabled() &&
- (GetResourceRequest().GetPreviewsState() &
- WebURLRequest::kServerLoFiOn)) {
- // If the runtime feature is enabled, show Client Lo-Fi placeholder images
- // in place of Server Lo-Fi responses. This is done so that all Lo-Fi images
- // have a consistent appearance.
- return true;
- }
-
switch (placeholder_option_) {
case PlaceholderOption::kShowAndReloadPlaceholderAlways:
case PlaceholderOption::kShowAndDoNotReloadPlaceholder:
@@ -595,17 +551,6 @@ void ImageResource::ReloadIfLoFiOrPlaceholderImage(
if (policy == kReloadIfNeeded && !ShouldReloadBrokenPlaceholder())
return;
- // If the image is loaded, then the |PreviewsState::kServerLoFiOn| bit should
- // be set iff the image has Server Lo-Fi response headers.
- DCHECK(!IsLoaded() ||
- HasServerLoFiResponseHeaders(GetResponse()) ==
- static_cast<bool>(GetResourceRequest().GetPreviewsState() &
- WebURLRequest::kServerLoFiOn));
-
- if (placeholder_option_ == PlaceholderOption::kDoNotReloadPlaceholder &&
- !(GetResourceRequest().GetPreviewsState() & WebURLRequest::kServerLoFiOn))
- return;
-
// Prevent clients and observers from being notified of completion while the
// reload is being scheduled, so that e.g. canceling an existing load in
// progress doesn't cause clients and observers to be notified of completion
@@ -613,8 +558,7 @@ void ImageResource::ReloadIfLoFiOrPlaceholderImage(
DCHECK(!is_scheduling_reload_);
is_scheduling_reload_ = true;
- if (GetResourceRequest().GetPreviewsState() &
- (WebURLRequest::kClientLoFiOn | WebURLRequest::kServerLoFiOn)) {
+ if (GetResourceRequest().GetPreviewsState() & WebURLRequest::kClientLoFiOn) {
SetCachePolicyBypassingCache();
}
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 7533e6b96b0..ff6d0fb1358 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
@@ -89,7 +89,8 @@ class CORE_EXPORT ImageResource final
void NotifyStartLoad() override;
void ResponseReceived(const ResourceResponse&) override;
void AppendData(const char*, size_t) override;
- void Finish(TimeTicks finish_time, base::SingleThreadTaskRunner*) override;
+ void Finish(base::TimeTicks finish_time,
+ base::SingleThreadTaskRunner*) override;
void FinishAsError(const ResourceError&,
base::SingleThreadTaskRunner*) override;
@@ -172,7 +173,7 @@ class CORE_EXPORT ImageResource final
};
PlaceholderOption placeholder_option_;
- TimeTicks last_flush_time_;
+ base::TimeTicks last_flush_time_;
bool is_during_finish_as_error_ = false;
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 1a9981b13d6..04b8d7dfc2f 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
@@ -14,7 +14,7 @@
#include "third_party/blink/renderer/platform/geometry/int_size.h"
#include "third_party/blink/renderer/platform/graphics/bitmap_image.h"
#include "third_party/blink/renderer/platform/graphics/placeholder_image.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/network/http_parsers.h"
#include "third_party/blink/renderer/platform/network/mime/mime_type_registry.h"
@@ -41,7 +41,7 @@ class NullImageResourceInfo final
private:
const KURL& Url() const override { return url_; }
- TimeTicks LoadResponseEnd() const override { return TimeTicks(); }
+ base::TimeTicks LoadResponseEnd() const override { return base::TimeTicks(); }
bool IsSchedulingReload() const override { return false; }
const ResourceResponse& GetResponse() const override { return response_; }
bool ShouldShowPlaceholder() const override { return false; }
@@ -655,7 +655,7 @@ const KURL& ImageResourceContent::Url() const {
return info_->Url();
}
-TimeTicks ImageResourceContent::LoadResponseEnd() const {
+base::TimeTicks ImageResourceContent::LoadResponseEnd() const {
return info_->LoadResponseEnd();
}
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 bc2551c8049..7c91be4f723 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
@@ -109,7 +109,7 @@ class CORE_EXPORT ImageResourceContent final
// Redirecting methods to Resource.
const KURL& Url() const;
- TimeTicks LoadResponseEnd() const;
+ base::TimeTicks LoadResponseEnd() const;
bool IsAccessAllowed();
const ResourceResponse& GetResponse() const;
base::Optional<ResourceError> GetResourceError() const;
diff --git a/chromium/third_party/blink/renderer/core/loader/resource/image_resource_info.h b/chromium/third_party/blink/renderer/core/loader/resource/image_resource_info.h
index f08d66a8944..1a8a9ec6c3c 100644
--- a/chromium/third_party/blink/renderer/core/loader/resource/image_resource_info.h
+++ b/chromium/third_party/blink/renderer/core/loader/resource/image_resource_info.h
@@ -29,7 +29,7 @@ class CORE_EXPORT ImageResourceInfo : public GarbageCollectedMixin {
public:
~ImageResourceInfo() = default;
virtual const KURL& Url() const = 0;
- virtual TimeTicks LoadResponseEnd() const = 0;
+ virtual base::TimeTicks LoadResponseEnd() const = 0;
virtual bool IsSchedulingReload() const = 0;
virtual const ResourceResponse& GetResponse() const = 0;
virtual bool ShouldShowPlaceholder() const = 0;
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 decab279a75..f3de598cd57 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
@@ -33,7 +33,7 @@
#include <memory>
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
-#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-shared.h"
+#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_url.h"
#include "third_party/blink/public/platform/web_url_loader_mock_factory.h"
@@ -45,7 +45,7 @@
#include "third_party/blink/renderer/platform/graphics/bitmap_image.h"
#include "third_party/blink/renderer/platform/graphics/image.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
-#include "third_party/blink/renderer/platform/instance_counters.h"
+#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h"
#include "third_party/blink/renderer/platform/loader/fetch/console_logger.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_initiator_info.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_initiator_type_names.h"
@@ -232,8 +232,7 @@ void TestThatReloadIsStartedThenServeReload(
WrappedResourceResponse(resource_response));
image_resource->Loader()->DidReceiveData(data, kDataLength);
image_resource->Loader()->DidFinishLoading(
- TimeTicks(), kDataLength, kDataLength, kDataLength, false,
- std::vector<network::cors::PreflightTimingInfo>());
+ base::TimeTicks(), kDataLength, kDataLength, kDataLength, false, {});
// Checks |imageResource|'s status after reloading.
EXPECT_EQ(ResourceStatus::kCached, image_resource->GetStatus());
@@ -289,10 +288,9 @@ void TestThatIsPlaceholderRequestAndServeResponse(
reinterpret_cast<const char*>(kJpegImage),
kJpegImageSubrangeWithDimensionsLength);
image_resource->Loader()->DidFinishLoading(
- TimeTicks(), kJpegImageSubrangeWithDimensionsLength,
+ base::TimeTicks(), kJpegImageSubrangeWithDimensionsLength,
kJpegImageSubrangeWithDimensionsLength,
- kJpegImageSubrangeWithDimensionsLength, false,
- std::vector<network::cors::PreflightTimingInfo>());
+ kJpegImageSubrangeWithDimensionsLength, false, {});
// Checks that |imageResource| is successfully loaded, showing a placeholder.
EXPECT_EQ(ResourceStatus::kCached, image_resource->GetStatus());
@@ -333,8 +331,8 @@ void TestThatIsNotPlaceholderRequestAndServeResponse(
image_resource->Loader()->DidReceiveData(
reinterpret_cast<const char*>(kJpegImage), sizeof(kJpegImage));
image_resource->Loader()->DidFinishLoading(
- TimeTicks(), sizeof(kJpegImage), sizeof(kJpegImage), sizeof(kJpegImage),
- false, std::vector<network::cors::PreflightTimingInfo>());
+ base::TimeTicks(), sizeof(kJpegImage), sizeof(kJpegImage),
+ sizeof(kJpegImage), false, {});
// Checks that |imageResource| is successfully loaded,
// showing a non-placeholder image.
@@ -431,9 +429,8 @@ TEST(ImageResourceTest, MultipartImage) {
// This part finishes. The image is created, callbacks are sent, and the data
// buffer is cleared.
- image_resource->Loader()->DidFinishLoading(
- TimeTicks(), 0, 0, 0, false,
- std::vector<network::cors::PreflightTimingInfo>());
+ image_resource->Loader()->DidFinishLoading(base::TimeTicks(), 0, 0, 0, false,
+ {});
EXPECT_TRUE(image_resource->ResourceBuffer());
EXPECT_FALSE(image_resource->ErrorOccurred());
ASSERT_TRUE(image_resource->GetContent()->HasImage());
@@ -477,9 +474,8 @@ TEST(ImageResourceTest, BitmapMultipartImage) {
image_resource->AppendData(reinterpret_cast<const char*>(kJpegImage),
sizeof(kJpegImage));
image_resource->AppendData(kBoundary, strlen(kBoundary));
- image_resource->Loader()->DidFinishLoading(
- TimeTicks(), 0, 0, 0, false,
- std::vector<network::cors::PreflightTimingInfo>());
+ image_resource->Loader()->DidFinishLoading(base::TimeTicks(), 0, 0, 0, false,
+ {});
EXPECT_TRUE(image_resource->GetContent()->HasImage());
EXPECT_TRUE(image_resource->GetContent()->GetImage()->IsBitmapImage());
EXPECT_TRUE(image_resource->GetContent()
@@ -644,285 +640,7 @@ TEST(ImageResourceTest, UpdateBitmapImages) {
EXPECT_TRUE(image_resource->GetContent()->GetImage()->IsBitmapImage());
}
-class ImageResourceReloadTest
- : public testing::TestWithParam<bool>,
- private ScopedClientPlaceholdersForServerLoFiForTest {
- public:
- ImageResourceReloadTest()
- : ScopedClientPlaceholdersForServerLoFiForTest(GetParam()) {}
- ~ImageResourceReloadTest() override = default;
-
- bool IsClientPlaceholderForServerLoFiEnabled() const { return GetParam(); }
-
- void SetUp() override {
- }
-};
-
-TEST_P(ImageResourceReloadTest, ReloadIfLoFiOrPlaceholderAfterFinished) {
- KURL test_url(kTestURL);
- ScopedMockedURLLoad scoped_mocked_url_load(test_url, GetTestFilePath());
- ImageResource* image_resource = ImageResource::CreateForTest(test_url);
- image_resource->NotifyStartLoad();
-
- auto observer =
- std::make_unique<MockImageResourceObserver>(image_resource->GetContent());
- ResourceFetcher* fetcher = CreateFetcher();
-
- // Send the image response.
- ResourceResponse resource_response(NullURL());
- resource_response.SetMimeType("image/jpeg");
- resource_response.SetExpectedContentLength(sizeof(kJpegImage));
- resource_response.AddHttpHeaderField("chrome-proxy-content-transform",
- "empty-image");
-
- image_resource->ResponseReceived(resource_response);
- image_resource->AppendData(reinterpret_cast<const char*>(kJpegImage),
- sizeof(kJpegImage));
- image_resource->FinishForTest();
- EXPECT_FALSE(image_resource->ErrorOccurred());
- ASSERT_TRUE(image_resource->GetContent()->HasImage());
- EXPECT_FALSE(image_resource->GetContent()->GetImage()->IsNull());
- EXPECT_EQ(2, observer->ImageChangedCount());
- EXPECT_EQ(kJpegImageWidth, observer->ImageWidthOnLastImageChanged());
- // The observer should have been notified that the image load completed.
- EXPECT_TRUE(observer->ImageNotifyFinishedCalled());
- EXPECT_EQ(kJpegImageWidth, observer->ImageWidthOnImageNotifyFinished());
- EXPECT_NE(IsClientPlaceholderForServerLoFiEnabled(),
- image_resource->GetContent()->GetImage()->IsBitmapImage());
- EXPECT_EQ(IsClientPlaceholderForServerLoFiEnabled(),
- image_resource->ShouldShowPlaceholder());
- EXPECT_EQ(kJpegImageWidth, image_resource->GetContent()->GetImage()->width());
- EXPECT_EQ(kJpegImageHeight,
- image_resource->GetContent()->GetImage()->height());
-
- // Call reloadIfLoFiOrPlaceholderImage() after the image has finished loading.
- image_resource->ReloadIfLoFiOrPlaceholderImage(fetcher,
- Resource::kReloadAlways);
-
- EXPECT_EQ(3, observer->ImageChangedCount());
- TestThatReloadIsStartedThenServeReload(test_url, image_resource,
- image_resource->GetContent(),
- observer.get(), false);
-}
-
-TEST_P(ImageResourceReloadTest,
- ReloadIfLoFiOrPlaceholderAfterFinishedWithOldHeaders) {
- KURL test_url(kTestURL);
- ScopedMockedURLLoad scoped_mocked_url_load(test_url, GetTestFilePath());
- ImageResource* image_resource = ImageResource::CreateForTest(test_url);
- image_resource->NotifyStartLoad();
-
- auto observer =
- std::make_unique<MockImageResourceObserver>(image_resource->GetContent());
- ResourceFetcher* fetcher = CreateFetcher();
-
- // Send the image response.
- ResourceResponse resource_response(NullURL());
- resource_response.SetMimeType("image/jpeg");
- resource_response.SetExpectedContentLength(sizeof(kJpegImage));
- resource_response.AddHttpHeaderField("chrome-proxy", "q=low");
-
- image_resource->ResponseReceived(resource_response);
- image_resource->AppendData(reinterpret_cast<const char*>(kJpegImage),
- sizeof(kJpegImage));
- image_resource->FinishForTest();
- EXPECT_FALSE(image_resource->ErrorOccurred());
- ASSERT_TRUE(image_resource->GetContent()->HasImage());
- EXPECT_FALSE(image_resource->GetContent()->GetImage()->IsNull());
- EXPECT_EQ(2, observer->ImageChangedCount());
- EXPECT_EQ(kJpegImageWidth, observer->ImageWidthOnLastImageChanged());
- // The observer should have been notified that the image load completed.
- EXPECT_TRUE(observer->ImageNotifyFinishedCalled());
- EXPECT_EQ(kJpegImageWidth, observer->ImageWidthOnImageNotifyFinished());
- EXPECT_NE(IsClientPlaceholderForServerLoFiEnabled(),
- image_resource->GetContent()->GetImage()->IsBitmapImage());
- EXPECT_EQ(IsClientPlaceholderForServerLoFiEnabled(),
- image_resource->ShouldShowPlaceholder());
- EXPECT_EQ(kJpegImageWidth, image_resource->GetContent()->GetImage()->width());
- EXPECT_EQ(kJpegImageHeight,
- image_resource->GetContent()->GetImage()->height());
-
- // Call reloadIfLoFiOrPlaceholderImage() after the image has finished loading.
- image_resource->ReloadIfLoFiOrPlaceholderImage(fetcher,
- Resource::kReloadAlways);
-
- EXPECT_EQ(3, observer->ImageChangedCount());
- TestThatReloadIsStartedThenServeReload(test_url, image_resource,
- image_resource->GetContent(),
- observer.get(), false);
-}
-
-TEST_P(ImageResourceReloadTest,
- ReloadIfLoFiOrPlaceholderAfterFinishedWithoutLoFiHeaders) {
- KURL test_url(kTestURL);
- ScopedMockedURLLoad scoped_mocked_url_load(test_url, GetTestFilePath());
- ResourceRequest request(test_url);
- request.SetPreviewsState(WebURLRequest::kServerLoFiOn);
- ImageResource* image_resource = ImageResource::Create(request);
- image_resource->NotifyStartLoad();
-
- auto observer =
- std::make_unique<MockImageResourceObserver>(image_resource->GetContent());
- ResourceFetcher* fetcher = CreateFetcher();
-
- // Send the image response, without any LoFi image response headers.
- ResourceResponse resource_response(NullURL());
- resource_response.SetMimeType("image/jpeg");
- resource_response.SetExpectedContentLength(sizeof(kJpegImage));
- image_resource->ResponseReceived(resource_response);
- image_resource->AppendData(reinterpret_cast<const char*>(kJpegImage),
- sizeof(kJpegImage));
- image_resource->FinishForTest();
- EXPECT_FALSE(image_resource->ErrorOccurred());
- ASSERT_TRUE(image_resource->GetContent()->HasImage());
- EXPECT_FALSE(image_resource->GetContent()->GetImage()->IsNull());
- EXPECT_EQ(2, observer->ImageChangedCount());
- EXPECT_EQ(kJpegImageWidth, observer->ImageWidthOnLastImageChanged());
- // The observer should have been notified that the image load completed.
- EXPECT_TRUE(observer->ImageNotifyFinishedCalled());
- EXPECT_EQ(kJpegImageWidth, observer->ImageWidthOnImageNotifyFinished());
- EXPECT_TRUE(image_resource->GetContent()->GetImage()->IsBitmapImage());
- EXPECT_EQ(kJpegImageWidth, image_resource->GetContent()->GetImage()->width());
- EXPECT_EQ(kJpegImageHeight,
- image_resource->GetContent()->GetImage()->height());
-
- // Call reloadIfLoFiOrPlaceholderImage() after the image has finished loading.
- image_resource->ReloadIfLoFiOrPlaceholderImage(fetcher,
- Resource::kReloadAlways);
-
- // The image should not have been reloaded, since it didn't have the LoFi
- // image response headers.
- EXPECT_EQ(2, observer->ImageChangedCount());
- EXPECT_TRUE(image_resource->IsLoaded());
-}
-
-TEST_P(ImageResourceReloadTest, ReloadIfLoFiOrPlaceholderViaResourceFetcher) {
- ResourceFetcher* fetcher = CreateFetcher();
-
- KURL test_url(kTestURL);
- ScopedMockedURLLoad scoped_mocked_url_load(test_url, GetTestFilePath());
-
- ResourceRequest request = ResourceRequest(test_url);
- request.SetPreviewsState(WebURLRequest::kServerLoFiOn);
- FetchParameters fetch_params(request);
- ImageResource* image_resource = ImageResource::Fetch(fetch_params, fetcher);
- ImageResourceContent* content = image_resource->GetContent();
-
- auto observer = std::make_unique<MockImageResourceObserver>(content);
-
- // Send the image response.
- ResourceResponse resource_response(NullURL());
- resource_response.SetMimeType("image/jpeg");
- resource_response.SetExpectedContentLength(sizeof(kJpegImage));
- resource_response.AddHttpHeaderField("chrome-proxy-content-transform",
- "empty-image");
-
- image_resource->Loader()->DidReceiveResponse(
- WrappedResourceResponse(resource_response));
- image_resource->Loader()->DidReceiveData(
- reinterpret_cast<const char*>(kJpegImage), sizeof(kJpegImage));
- image_resource->Loader()->DidFinishLoading(
- TimeTicks(), sizeof(kJpegImage), sizeof(kJpegImage), sizeof(kJpegImage),
- false, std::vector<network::cors::PreflightTimingInfo>());
-
- EXPECT_TRUE(observer->ImageNotifyFinishedCalled());
- EXPECT_EQ(image_resource, fetcher->CachedResource(test_url));
-
- fetcher->ReloadLoFiImages();
-
- EXPECT_EQ(3, observer->ImageChangedCount());
-
- TestThatReloadIsStartedThenServeReload(test_url, image_resource, content,
- observer.get(), false);
-
- GetMemoryCache()->Remove(image_resource);
-}
-
-TEST_P(ImageResourceReloadTest, ReloadIfLoFiOrPlaceholderBeforeResponse) {
- KURL test_url(kTestURL);
- ScopedMockedURLLoad scoped_mocked_url_load(test_url, GetTestFilePath());
-
- ResourceRequest request(test_url);
- request.SetPreviewsState(WebURLRequest::kServerLoFiOn);
- FetchParameters fetch_params(request);
- ResourceFetcher* fetcher = CreateFetcher();
-
- ImageResource* image_resource = ImageResource::Fetch(fetch_params, fetcher);
- auto observer =
- std::make_unique<MockImageResourceObserver>(image_resource->GetContent());
-
- EXPECT_FALSE(image_resource->ErrorOccurred());
- EXPECT_EQ(IsClientPlaceholderForServerLoFiEnabled(),
- image_resource->ShouldShowPlaceholder());
-
- // Call reloadIfLoFiOrPlaceholderImage() while the image is still loading.
- image_resource->ReloadIfLoFiOrPlaceholderImage(fetcher,
- Resource::kReloadAlways);
-
- EXPECT_EQ(1, observer->ImageChangedCount());
- EXPECT_EQ(0, observer->ImageWidthOnLastImageChanged());
- // The observer should not have been notified of completion yet, since the
- // image is still loading.
- EXPECT_FALSE(observer->ImageNotifyFinishedCalled());
-
- TestThatReloadIsStartedThenServeReload(test_url, image_resource,
- image_resource->GetContent(),
- observer.get(), false);
-}
-
-TEST_P(ImageResourceReloadTest, ReloadIfLoFiOrPlaceholderDuringResponse) {
- KURL test_url(kTestURL);
- ScopedMockedURLLoad scoped_mocked_url_load(test_url, GetTestFilePath());
-
- ResourceRequest request(test_url);
- request.SetPreviewsState(WebURLRequest::kServerLoFiOn);
- FetchParameters fetch_params(request);
- ResourceFetcher* fetcher = CreateFetcher();
-
- ImageResource* image_resource = ImageResource::Fetch(fetch_params, fetcher);
- auto observer =
- std::make_unique<MockImageResourceObserver>(image_resource->GetContent());
-
- // Send the image response.
- ResourceResponse resource_response(test_url);
- resource_response.SetMimeType("image/jpeg");
- resource_response.SetExpectedContentLength(sizeof(kJpegImage));
- resource_response.AddHttpHeaderField("chrome-proxy-content-transform",
- "empty-image");
-
- image_resource->Loader()->DidReceiveResponse(
- WrappedResourceResponse(resource_response));
- image_resource->Loader()->DidReceiveData(
- reinterpret_cast<const char*>(kJpegImage), sizeof(kJpegImage));
-
- EXPECT_FALSE(image_resource->ErrorOccurred());
- ASSERT_TRUE(image_resource->GetContent()->HasImage());
- EXPECT_FALSE(image_resource->GetContent()->GetImage()->IsNull());
- EXPECT_EQ(1, observer->ImageChangedCount());
- EXPECT_EQ(kJpegImageWidth, observer->ImageWidthOnLastImageChanged());
- EXPECT_FALSE(observer->ImageNotifyFinishedCalled());
- EXPECT_EQ(IsClientPlaceholderForServerLoFiEnabled(),
- image_resource->ShouldShowPlaceholder());
- EXPECT_EQ(kJpegImageWidth, image_resource->GetContent()->GetImage()->width());
- EXPECT_EQ(kJpegImageHeight,
- image_resource->GetContent()->GetImage()->height());
-
- // Call reloadIfLoFiOrPlaceholderImage() while the image is still loading.
- image_resource->ReloadIfLoFiOrPlaceholderImage(fetcher,
- Resource::kReloadAlways);
-
- EXPECT_EQ(2, observer->ImageChangedCount());
- EXPECT_EQ(0, observer->ImageWidthOnLastImageChanged());
- // The observer should not have been notified of completion yet, since the
- // image is still loading.
- EXPECT_FALSE(observer->ImageNotifyFinishedCalled());
-
- TestThatReloadIsStartedThenServeReload(test_url, image_resource,
- image_resource->GetContent(),
- observer.get(), false);
-}
-
-TEST_P(ImageResourceReloadTest, ReloadIfLoFiOrPlaceholderForPlaceholder) {
+TEST(ImageResourceReloadTest, ReloadIfLoFiOrPlaceholderForPlaceholder) {
KURL test_url(kTestURL);
ScopedMockedURLLoad scoped_mocked_url_load(test_url, GetTestFilePath());
@@ -946,7 +664,7 @@ TEST_P(ImageResourceReloadTest, ReloadIfLoFiOrPlaceholderForPlaceholder) {
observer.get(), false);
}
-TEST_P(ImageResourceReloadTest, ReloadLoFiImagesWithDuplicateURLs) {
+TEST(ImageResourceReloadTest, ReloadLoFiImagesWithDuplicateURLs) {
KURL test_url(kTestURL);
ScopedMockedURLLoad scoped_mocked_url_load(test_url, GetTestFilePath());
ResourceFetcher* fetcher = CreateFetcher();
@@ -976,10 +694,6 @@ TEST_P(ImageResourceReloadTest, ReloadLoFiImagesWithDuplicateURLs) {
EXPECT_FALSE(full_image_resource->ShouldShowPlaceholder());
}
-INSTANTIATE_TEST_SUITE_P(/* no prefix */,
- ImageResourceReloadTest,
- testing::Bool());
-
TEST(ImageResourceTest, SVGImage) {
KURL url("http://127.0.0.1:8000/foo");
ImageResource* image_resource = ImageResource::CreateForTest(url);
@@ -1325,9 +1039,8 @@ TEST(ImageResourceTest, DecodeErrorWithEmptyBody) {
EXPECT_FALSE(observer->ImageNotifyFinishedCalled());
EXPECT_EQ(0, observer->ImageChangedCount());
- image_resource->Loader()->DidFinishLoading(
- TimeTicks(), 0, 0, 0, false,
- std::vector<network::cors::PreflightTimingInfo>());
+ image_resource->Loader()->DidFinishLoading(base::TimeTicks(), 0, 0, 0, false,
+ {});
EXPECT_EQ(ResourceStatus::kDecodeError, image_resource->GetStatus());
EXPECT_TRUE(observer->ImageNotifyFinishedCalled());
@@ -1372,10 +1085,9 @@ TEST(ImageResourceTest, PartialContentWithoutDimensions) {
EXPECT_EQ(0, observer->ImageChangedCount());
image_resource->Loader()->DidFinishLoading(
- TimeTicks(), kJpegImageSubrangeWithoutDimensionsLength,
+ base::TimeTicks(), kJpegImageSubrangeWithoutDimensionsLength,
kJpegImageSubrangeWithoutDimensionsLength,
- kJpegImageSubrangeWithoutDimensionsLength, false,
- std::vector<network::cors::PreflightTimingInfo>());
+ kJpegImageSubrangeWithoutDimensionsLength, false, {});
EXPECT_EQ(ResourceStatus::kDecodeError, image_resource->GetStatus());
EXPECT_TRUE(observer->ImageNotifyFinishedCalled());
@@ -1400,9 +1112,7 @@ TEST(ImageResourceTest, FetchDisallowPlaceholder) {
}
TEST(ImageResourceTest, FetchAllowPlaceholderDataURL) {
- KURL test_url("data:image/jpeg;base64," +
- Base64Encode(reinterpret_cast<const char*>(kJpegImage),
- sizeof(kJpegImage)));
+ KURL test_url("data:image/jpeg;base64," + Base64Encode(kJpegImage));
FetchParameters params{ResourceRequest(test_url)};
params.SetAllowImagePlaceholder();
ImageResource* image_resource = ImageResource::Fetch(params, CreateFetcher());
@@ -1603,10 +1313,9 @@ TEST(ImageResourceTest, FetchAllowPlaceholderPartialContentWithoutDimensions) {
EXPECT_EQ(0, observer->ImageChangedCount());
image_resource->Loader()->DidFinishLoading(
- TimeTicks(), kJpegImageSubrangeWithoutDimensionsLength,
+ base::TimeTicks(), kJpegImageSubrangeWithoutDimensionsLength,
kJpegImageSubrangeWithoutDimensionsLength,
- kJpegImageSubrangeWithoutDimensionsLength, false,
- std::vector<network::cors::PreflightTimingInfo>());
+ kJpegImageSubrangeWithoutDimensionsLength, false, {});
EXPECT_FALSE(observer->ImageNotifyFinishedCalled());
EXPECT_EQ(2, observer->ImageChangedCount());
@@ -1746,8 +1455,8 @@ TEST(ImageResourceTest, FetchAllowPlaceholderFullResponseDecodeSuccess) {
image_resource->Loader()->DidReceiveData(
reinterpret_cast<const char*>(kJpegImage), sizeof(kJpegImage));
image_resource->Loader()->DidFinishLoading(
- TimeTicks(), sizeof(kJpegImage), sizeof(kJpegImage), sizeof(kJpegImage),
- false, std::vector<network::cors::PreflightTimingInfo>());
+ base::TimeTicks(), sizeof(kJpegImage), sizeof(kJpegImage),
+ sizeof(kJpegImage), false, {});
EXPECT_EQ(ResourceStatus::kCached, image_resource->GetStatus());
EXPECT_EQ(sizeof(kJpegImage), image_resource->EncodedSize());
@@ -1862,7 +1571,7 @@ TEST(ImageResourceTest, PeriodicFlushTest) {
std::unique_ptr<DummyPageHolder> page_holder =
std::make_unique<DummyPageHolder>(
IntSize(800, 600), &clients,
- MakeGarbageCollected<EmptyLocalFrameClient>(), nullptr);
+ MakeGarbageCollected<EmptyLocalFrameClient>());
KURL test_url(kTestURL);
ScopedMockedURLLoad scoped_mocked_url_load(test_url, GetTestFilePath());
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 71c17ddb839..dec020fe0b8 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
@@ -267,7 +267,15 @@ void ScriptResource::ResponseBodyReceived(
WTF::BindRepeating(&ScriptResource::OnDataPipeReadable,
WrapWeakPersistent(this)));
CHECK(data_pipe_);
- watcher_->ArmOrNotify();
+
+ MojoResult ready_result;
+ mojo::HandleSignalsState ready_state;
+ MojoResult rv = watcher_->Arm(&ready_result, &ready_state);
+ if (rv == MOJO_RESULT_OK)
+ return;
+
+ DCHECK_EQ(MOJO_RESULT_FAILED_PRECONDITION, rv);
+ OnDataPipeReadable(ready_result, ready_state);
}
void ScriptResource::OnDataPipeReadable(MojoResult result,
@@ -407,7 +415,7 @@ void ScriptResource::StartStreaming(
return;
}
- static bool script_streaming_enabled =
+ static const bool script_streaming_enabled =
base::FeatureList::IsEnabled(features::kScriptStreaming);
if (!script_streaming_enabled) {
return;
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 1aa8e72667d..ba2a14fee01 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
@@ -79,8 +79,7 @@ class CORE_EXPORT ScriptResource final : public TextResource {
static ScriptResource* CreateForTest(const KURL& url,
const WTF::TextEncoding& encoding) {
ResourceRequest request(url);
- request.SetFetchCredentialsMode(
- network::mojom::FetchCredentialsMode::kOmit);
+ request.SetCredentialsMode(network::mojom::CredentialsMode::kOmit);
ResourceLoaderOptions options;
TextResourceDecoderOptions decoder_options(
TextResourceDecoderOptions::kPlainTextContent, encoding);
diff --git a/chromium/third_party/blink/renderer/core/loader/resource_load_observer_for_frame.cc b/chromium/third_party/blink/renderer/core/loader/resource_load_observer_for_frame.cc
index 97373c4e7ec..697502d51ed 100644
--- a/chromium/third_party/blink/renderer/core/loader/resource_load_observer_for_frame.cc
+++ b/chromium/third_party/blink/renderer/core/loader/resource_load_observer_for_frame.cc
@@ -4,11 +4,12 @@
#include "third_party/blink/renderer/core/loader/resource_load_observer_for_frame.h"
+#include "services/metrics/public/cpp/ukm_builders.h"
+#include "services/metrics/public/cpp/ukm_recorder.h"
#include "third_party/blink/renderer/core/core_probes_inl.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/local_frame_client.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/frame/web_feature.h"
#include "third_party/blink/renderer/core/inspector/inspector_trace_events.h"
#include "third_party/blink/renderer/core/loader/alternate_signed_exchange_resource_info.h"
@@ -21,8 +22,14 @@
#include "third_party/blink/renderer/core/loader/preload_helper.h"
#include "third_party/blink/renderer/core/loader/progress_tracker.h"
#include "third_party/blink/renderer/core/loader/subresource_filter.h"
+#include "third_party/blink/renderer/platform/bindings/v8_dom_activity_logger.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object.h"
+#include "third_party/blink/renderer/platform/loader/fetch/fetch_initiator_info.h"
+#include "third_party/blink/renderer/platform/loader/fetch/fetch_initiator_type_names.h"
+#include "third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher_properties.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"
@@ -35,6 +42,33 @@ ResourceLoadObserverForFrame::ResourceLoadObserverForFrame(
fetcher_properties_(fetcher_properties) {}
ResourceLoadObserverForFrame::~ResourceLoadObserverForFrame() = default;
+void ResourceLoadObserverForFrame::DidStartRequest(
+ const FetchParameters& params,
+ ResourceType resource_type) {
+ // TODO(yhirano): Consider removing ResourceLoadObserver::DidStartRequest
+ // completely when we remove V8DOMActivityLogger.
+ DocumentLoader* document_loader =
+ frame_or_imported_document_->GetDocumentLoader();
+ if (document_loader && !document_loader->Archive() &&
+ params.Url().IsValid() && !params.IsSpeculativePreload()) {
+ V8DOMActivityLogger* activity_logger = nullptr;
+ const AtomicString& initiator_name = params.Options().initiator_info.name;
+ if (initiator_name == fetch_initiator_type_names::kXmlhttprequest) {
+ activity_logger = V8DOMActivityLogger::CurrentActivityLogger();
+ } else {
+ activity_logger =
+ V8DOMActivityLogger::CurrentActivityLoggerIfIsolatedWorld();
+ }
+ if (activity_logger) {
+ Vector<String> argv = {
+ Resource::ResourceTypeToString(resource_type, initiator_name),
+ params.Url()};
+ activity_logger->LogEvent("blinkRequestResource", argv.size(),
+ argv.data());
+ }
+ }
+}
+
void ResourceLoadObserverForFrame::WillSendRequest(
uint64_t identifier,
const ResourceRequest& request,
@@ -113,7 +147,8 @@ void ResourceLoadObserverForFrame::DidReceiveResponse(
response.RemoteIPAddress());
std::unique_ptr<AlternateSignedExchangeResourceInfo> alternate_resource_info;
- if (RuntimeEnabledFeatures::SignedExchangeSubresourcePrefetchEnabled() &&
+ if (RuntimeEnabledFeatures::SignedExchangeSubresourcePrefetchEnabled(
+ &frame_or_imported_document_->GetDocument()) &&
response.IsSignedExchangeInnerResponse() &&
resource->GetType() == ResourceType::kLinkPrefetch &&
resource->LastResourceResponse()) {
@@ -146,6 +181,14 @@ void ResourceLoadObserverForFrame::DidReceiveResponse(
if (response.IsLegacyTLSVersion()) {
CountUsage(WebFeature::kLegacyTLSVersionInSubresource);
frame_client->ReportLegacyTLSVersion(response.CurrentRequestUrl());
+ // For non-main-frame loads, we have to use the main frame's document for
+ // the UKM recorder and source ID.
+ auto& root = frame.LocalFrameRoot();
+ ukm::builders::Net_LegacyTLSVersion(root.GetDocument()->UkmSourceID())
+ .SetIsMainFrame(frame.IsMainFrame())
+ .SetIsSubresource(true)
+ .SetIsAdResource(resource->GetResourceRequest().IsAdResource())
+ .Record(root.GetDocument()->UkmRecorder());
}
frame.Loader().Progress().IncrementProgress(identifier, response);
@@ -188,11 +231,10 @@ void ResourceLoadObserverForFrame::DidDownloadToBlob(uint64_t identifier,
void ResourceLoadObserverForFrame::DidFinishLoading(
uint64_t identifier,
- TimeTicks finish_time,
+ base::TimeTicks finish_time,
int64_t encoded_data_length,
int64_t decoded_body_length,
- bool should_report_corb_blocking,
- ResponseSource response_source) {
+ bool should_report_corb_blocking) {
LocalFrame& frame = frame_or_imported_document_->GetFrame();
DocumentLoader& document_loader =
frame_or_imported_document_->GetMasterDocumentLoader();
@@ -210,9 +252,7 @@ void ResourceLoadObserverForFrame::DidFinishLoading(
idleness_detector->OnDidLoadResource();
}
}
- if (response_source == ResponseSource::kNotFromMemoryCache) {
- document.CheckCompleted();
- }
+ document.CheckCompleted();
}
void ResourceLoadObserverForFrame::DidFailLoading(const KURL&,
@@ -234,7 +274,7 @@ void ResourceLoadObserverForFrame::DidFailLoading(const KURL&,
Document& document = frame_or_imported_document_->GetDocument();
if (auto* interactive_detector = InteractiveDetector::From(document)) {
// We have not yet recorded load_finish_time. Pass nullopt here; we will
- // call CurrentTimeTicksInSeconds lazily when we need it.
+ // call base::TimeTicks::Now() lazily when we need it.
interactive_detector->OnResourceLoadEnd(base::nullopt);
}
if (LocalFrame* frame = document.GetFrame()) {
diff --git a/chromium/third_party/blink/renderer/core/loader/resource_load_observer_for_frame.h b/chromium/third_party/blink/renderer/core/loader/resource_load_observer_for_frame.h
index 909a1ae9b08..f496d3f62c1 100644
--- a/chromium/third_party/blink/renderer/core/loader/resource_load_observer_for_frame.h
+++ b/chromium/third_party/blink/renderer/core/loader/resource_load_observer_for_frame.h
@@ -28,6 +28,7 @@ class CORE_EXPORT ResourceLoadObserverForFrame final
~ResourceLoadObserverForFrame() override;
// ResourceLoadObserver implementation.
+ void DidStartRequest(const FetchParameters&, ResourceType) override;
void WillSendRequest(uint64_t identifier,
const ResourceRequest&,
const ResourceResponse& redirect_response,
@@ -47,11 +48,10 @@ class CORE_EXPORT ResourceLoadObserverForFrame final
int transfer_size_diff) override;
void DidDownloadToBlob(uint64_t identifier, BlobDataHandle*) override;
void DidFinishLoading(uint64_t identifier,
- TimeTicks finish_time,
+ base::TimeTicks finish_time,
int64_t encoded_data_length,
int64_t decoded_body_length,
- bool should_report_corb_blocking,
- ResponseSource) override;
+ bool should_report_corb_blocking) override;
void DidFailLoading(const KURL&,
uint64_t identifier,
const ResourceError&,
diff --git a/chromium/third_party/blink/renderer/core/loader/resource_load_observer_for_worker.cc b/chromium/third_party/blink/renderer/core/loader/resource_load_observer_for_worker.cc
index 879a8463af6..75c6bfec9e0 100644
--- a/chromium/third_party/blink/renderer/core/loader/resource_load_observer_for_worker.cc
+++ b/chromium/third_party/blink/renderer/core/loader/resource_load_observer_for_worker.cc
@@ -24,6 +24,9 @@ ResourceLoadObserverForWorker::ResourceLoadObserverForWorker(
ResourceLoadObserverForWorker::~ResourceLoadObserverForWorker() = default;
+void ResourceLoadObserverForWorker::DidStartRequest(const FetchParameters&,
+ ResourceType) {}
+
void ResourceLoadObserverForWorker::WillSendRequest(
uint64_t identifier,
const ResourceRequest& request,
@@ -82,11 +85,10 @@ void ResourceLoadObserverForWorker::DidDownloadToBlob(uint64_t identifier,
void ResourceLoadObserverForWorker::DidFinishLoading(
uint64_t identifier,
- TimeTicks finish_time,
+ base::TimeTicks finish_time,
int64_t encoded_data_length,
int64_t decoded_body_length,
- bool should_report_corb_blocking,
- ResponseSource) {
+ bool should_report_corb_blocking) {
probe::DidFinishLoading(probe_, identifier, nullptr, finish_time,
encoded_data_length, decoded_body_length,
should_report_corb_blocking);
diff --git a/chromium/third_party/blink/renderer/core/loader/resource_load_observer_for_worker.h b/chromium/third_party/blink/renderer/core/loader/resource_load_observer_for_worker.h
index 3e606658370..534488fe2ce 100644
--- a/chromium/third_party/blink/renderer/core/loader/resource_load_observer_for_worker.h
+++ b/chromium/third_party/blink/renderer/core/loader/resource_load_observer_for_worker.h
@@ -25,6 +25,7 @@ class ResourceLoadObserverForWorker final : public ResourceLoadObserver {
~ResourceLoadObserverForWorker() override;
// ResourceLoadObserver implementation.
+ void DidStartRequest(const FetchParameters&, ResourceType) override;
void WillSendRequest(uint64_t identifier,
const ResourceRequest&,
const ResourceResponse& redirect_response,
@@ -44,11 +45,10 @@ class ResourceLoadObserverForWorker final : public ResourceLoadObserver {
int transfer_size_diff) override;
void DidDownloadToBlob(uint64_t identifier, BlobDataHandle*) override;
void DidFinishLoading(uint64_t identifier,
- TimeTicks finish_time,
+ base::TimeTicks finish_time,
int64_t encoded_data_length,
int64_t decoded_body_length,
- bool should_report_corb_blocking,
- ResponseSource) override;
+ bool should_report_corb_blocking) override;
void DidFailLoading(const KURL&,
uint64_t identifier,
const ResourceError&,
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 51333fa3ac4..ccb865d14e1 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
@@ -4,9 +4,9 @@
#include "third_party/blink/renderer/core/loader/subresource_integrity_helper.h"
-#include "third_party/blink/public/mojom/devtools/console_message.mojom-shared.h"
+#include "third_party/blink/public/mojom/devtools/console_message.mojom-blink.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/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/loader/subresource_integrity_helper.h b/chromium/third_party/blink/renderer/core/loader/subresource_integrity_helper.h
index ee19a328887..f4290693407 100644
--- a/chromium/third_party/blink/renderer/core/loader/subresource_integrity_helper.h
+++ b/chromium/third_party/blink/renderer/core/loader/subresource_integrity_helper.h
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/platform/loader/subresource_integrity.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 fc613bd1f87..0c16de8a988 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
@@ -25,7 +25,7 @@
#include "third_party/blink/renderer/core/loader/text_track_loader.h"
-#include "services/network/public/mojom/fetch_api.mojom-shared.h"
+#include "services/network/public/mojom/fetch_api.mojom-blink.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
@@ -97,7 +97,7 @@ void TextTrackLoader::NotifyFinished(Resource* resource) {
}
if (!cue_load_timer_.IsActive())
- cue_load_timer_.StartOneShot(TimeDelta(), FROM_HERE);
+ cue_load_timer_.StartOneShot(base::TimeDelta(), FROM_HERE);
CancelLoad();
}
@@ -115,8 +115,8 @@ bool TextTrackLoader::Load(const KURL& url,
FetchParameters cue_fetch_params(ResourceRequest(url), options);
if (cross_origin == kCrossOriginAttributeNotSet) {
- cue_fetch_params.MutableResourceRequest().SetFetchRequestMode(
- network::mojom::FetchRequestMode::kSameOrigin);
+ cue_fetch_params.MutableResourceRequest().SetMode(
+ network::mojom::RequestMode::kSameOrigin);
} else {
cue_fetch_params.SetCrossOriginAccessControl(
GetDocument().GetSecurityOrigin(), cross_origin);
@@ -131,14 +131,14 @@ void TextTrackLoader::NewCuesParsed() {
return;
new_cues_available_ = true;
- cue_load_timer_.StartOneShot(TimeDelta(), FROM_HERE);
+ cue_load_timer_.StartOneShot(base::TimeDelta(), FROM_HERE);
}
void TextTrackLoader::FileFailedToParse() {
state_ = kFailed;
if (!cue_load_timer_.IsActive())
- cue_load_timer_.StartOneShot(TimeDelta(), FROM_HERE);
+ cue_load_timer_.StartOneShot(base::TimeDelta(), FROM_HERE);
CancelLoad();
}
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 24596cc7756..34c1d2f6dcf 100644
--- a/chromium/third_party/blink/renderer/core/loader/threadable_loader.cc
+++ b/chromium/third_party/blink/renderer/core/loader/threadable_loader.cc
@@ -87,7 +87,7 @@ AtomicString CreateAccessControlRequestHeadersHeader(
// Sort header names lexicographically.
std::sort(filtered_headers.begin(), filtered_headers.end(),
- WTF::CodePointCompareLessThan);
+ WTF::CodeUnitCompareLessThan);
StringBuilder header_buffer;
for (const String& header : filtered_headers) {
if (!header_buffer.IsEmpty())
@@ -110,7 +110,7 @@ class ThreadableLoader::DetachedClient final
public:
explicit DetachedClient(ThreadableLoader* loader)
- : self_keep_alive_(this), loader_(loader) {}
+ : self_keep_alive_(PERSISTENT_FROM_HERE, this), loader_(loader) {}
~DetachedClient() override {}
void DidFinishLoading(uint64_t identifier) override {
@@ -165,13 +165,19 @@ ThreadableLoader::CreateAccessControlPreflightRequest(
preflight_request->SetHttpMethod(http_names::kOPTIONS);
preflight_request->SetHttpHeaderField(http_names::kAccessControlRequestMethod,
request.HttpMethod());
+ preflight_request->SetMode(network::mojom::RequestMode::kCors);
preflight_request->SetPriority(request.Priority());
preflight_request->SetRequestContext(request.GetRequestContext());
- preflight_request->SetFetchCredentialsMode(
- network::mojom::FetchCredentialsMode::kOmit);
+ preflight_request->SetCredentialsMode(network::mojom::CredentialsMode::kOmit);
preflight_request->SetSkipServiceWorker(true);
- preflight_request->SetReferrerString(request.ReferrerString());
- preflight_request->SetReferrerPolicy(request.GetReferrerPolicy());
+ preflight_request->SetReferrerString(
+ request.ReferrerString(),
+ ResourceRequest::SetReferrerStringLocation::
+ kThreadableLoaderCreateAccessControlPreflightRequest);
+ preflight_request->SetReferrerPolicy(
+ request.GetReferrerPolicy(),
+ ResourceRequest::SetReferrerPolicyLocation::
+ kThreadableLoaderCreateAccessControlPreflightRequest);
if (request.IsExternalRequest()) {
preflight_request->SetHttpHeaderField(
@@ -211,13 +217,13 @@ ThreadableLoader::ThreadableLoader(
async_(resource_loader_options.synchronous_policy ==
kRequestAsynchronously),
request_context_(mojom::RequestContextType::UNSPECIFIED),
- fetch_request_mode_(network::mojom::FetchRequestMode::kSameOrigin),
- fetch_credentials_mode_(network::mojom::FetchCredentialsMode::kOmit),
+ request_mode_(network::mojom::RequestMode::kSameOrigin),
+ credentials_mode_(network::mojom::CredentialsMode::kOmit),
timeout_timer_(execution_context_->GetTaskRunner(TaskType::kNetworking),
this,
&ThreadableLoader::DidTimeout),
redirect_limit_(kMaxRedirects),
- redirect_mode_(network::mojom::FetchRedirectMode::kFollow),
+ redirect_mode_(network::mojom::RedirectMode::kFollow),
override_referrer_(false) {
DCHECK(client);
if (!resource_fetcher_) {
@@ -232,8 +238,7 @@ void ThreadableLoader::Start(const ResourceRequest& request) {
// Setting an outgoing referer is only supported in the async code path.
DCHECK(async_ || request.HttpReferrer().IsEmpty());
- bool cors_enabled =
- cors::IsCorsEnabledRequestMode(request.GetFetchRequestMode());
+ bool cors_enabled = cors::IsCorsEnabledRequestMode(request.GetMode());
// kPreventPreflight can be used only when the CORS is enabled.
DCHECK(request.CorsPreflightPolicy() ==
@@ -243,21 +248,20 @@ void ThreadableLoader::Start(const ResourceRequest& request) {
initial_request_url_ = request.Url();
last_request_url_ = initial_request_url_;
request_context_ = request.GetRequestContext();
- fetch_request_mode_ = request.GetFetchRequestMode();
- fetch_credentials_mode_ = request.GetFetchCredentialsMode();
- redirect_mode_ = request.GetFetchRedirectMode();
+ request_mode_ = request.GetMode();
+ credentials_mode_ = request.GetCredentialsMode();
+ redirect_mode_ = request.GetRedirectMode();
- if (request.GetFetchRequestMode() ==
- network::mojom::FetchRequestMode::kNoCors) {
+ if (request.GetMode() == network::mojom::RequestMode::kNoCors) {
SECURITY_CHECK(cors::IsNoCorsAllowedContext(request_context_));
}
cors_flag_ = cors::CalculateCorsFlag(request.Url(), GetSecurityOrigin(),
- request.GetFetchRequestMode());
+ request.GetMode());
// The CORS flag variable is not yet used at the step in the spec that
// corresponds to this line, but divert |cors_flag_| here for convenience.
- if (cors_flag_ && request.GetFetchRequestMode() ==
- network::mojom::FetchRequestMode::kSameOrigin) {
+ if (cors_flag_ &&
+ request.GetMode() == network::mojom::RequestMode::kSameOrigin) {
ThreadableLoaderClient* client = client_;
Clear();
client->DidFail(ResourceError(
@@ -266,7 +270,7 @@ void ThreadableLoader::Start(const ResourceRequest& request) {
return;
}
- request_started_ = CurrentTimeTicks();
+ request_started_ = base::TimeTicks::Now();
// Save any headers on the request here. If this request redirects
// cross-origin, we cancel the old request create a new one, and copy these
@@ -315,7 +319,7 @@ void ThreadableLoader::Start(const ResourceRequest& request) {
return;
}
- if (cors::IsCorsEnabledRequestMode(request.GetFetchRequestMode())) {
+ if (cors::IsCorsEnabledRequestMode(request.GetMode())) {
// Save the request to fallback_request_for_service_worker to use when the
// service worker doesn't handle (call respondWith()) a CORS enabled
// request.
@@ -333,7 +337,7 @@ void ThreadableLoader::DispatchInitialRequest(ResourceRequest& request) {
return;
}
- DCHECK(cors::IsCorsEnabledRequestMode(request.GetFetchRequestMode()) ||
+ DCHECK(cors::IsCorsEnabledRequestMode(request.GetMode()) ||
request.IsExternalRequest());
MakeCrossOriginAccessRequest(request);
@@ -344,10 +348,14 @@ void ThreadableLoader::PrepareCrossOriginRequest(
if (GetSecurityOrigin())
request.SetHTTPOrigin(GetSecurityOrigin());
- // TODO(domfarolino): Stop setting the HTTPReferrer header, and instead use
- // ResourceRequest::referrer_. See https://crbug.com/850813.
- if (override_referrer_)
- request.SetHttpReferrer(referrer_after_redirect_);
+ if (override_referrer_) {
+ request.SetReferrerString(referrer_after_redirect_.referrer,
+ ResourceRequest::SetReferrerStringLocation::
+ kThreadableLoaderPrepareCrossOriginRequest);
+ request.SetReferrerPolicy(referrer_after_redirect_.referrer_policy,
+ ResourceRequest::SetReferrerPolicyLocation::
+ kThreadableLoaderPrepareCrossOriginRequest);
+ }
}
void ThreadableLoader::LoadPreflightRequest(
@@ -373,7 +381,7 @@ void ThreadableLoader::LoadPreflightRequest(
void ThreadableLoader::MakeCrossOriginAccessRequest(
const ResourceRequest& request) {
- DCHECK(cors::IsCorsEnabledRequestMode(request.GetFetchRequestMode()) ||
+ DCHECK(cors::IsCorsEnabledRequestMode(request.GetMode()) ||
request.IsExternalRequest());
DCHECK(client_);
DCHECK(!GetResource());
@@ -417,8 +425,8 @@ void ThreadableLoader::MakeCrossOriginAccessRequest(
return;
}
- if (request.GetFetchRequestMode() !=
- network::mojom::FetchRequestMode::kCorsWithForcedPreflight) {
+ if (request.GetMode() !=
+ network::mojom::RequestMode::kCorsWithForcedPreflight) {
if (request.CorsPreflightPolicy() ==
network::mojom::CorsPreflightPolicy::kPreventPreflight) {
PrepareCrossOriginRequest(cross_origin_request);
@@ -454,7 +462,7 @@ void ThreadableLoader::MakeCrossOriginAccessRequest(
if (should_ignore_preflight_cache ||
!cors::CheckIfRequestCanSkipPreflight(
GetSecurityOrigin()->ToString(), cross_origin_request.Url(),
- cross_origin_request.GetFetchCredentialsMode(),
+ cross_origin_request.GetCredentialsMode(),
cross_origin_request.HttpMethod(),
cross_origin_request.HttpHeaderFields())) {
LoadPreflightRequest(cross_origin_request, cross_origin_options);
@@ -472,13 +480,13 @@ void ThreadableLoader::MakeCrossOriginAccessRequest(
ThreadableLoader::~ThreadableLoader() {}
-void ThreadableLoader::SetTimeout(const TimeDelta& timeout) {
+void ThreadableLoader::SetTimeout(const base::TimeDelta& timeout) {
timeout_ = timeout;
- // |request_started_| <= TimeTicks() indicates loading is either not yet
+ // |request_started_| <= base::TimeTicks() indicates loading is either not yet
// started or is already finished, and thus we don't need to do anything with
// timeout_timer_.
- if (request_started_ <= TimeTicks()) {
+ if (request_started_ <= base::TimeTicks()) {
DCHECK(!timeout_timer_.IsActive());
return;
}
@@ -493,8 +501,9 @@ void ThreadableLoader::SetTimeout(const TimeDelta& timeout) {
// was initially sent, however other uses of this method may need to
// behave differently, in which case this should be re-arranged somehow.
if (!timeout_.is_zero()) {
- TimeDelta elapsed_time = CurrentTimeTicks() - request_started_;
- TimeDelta resolved_time = std::max(timeout_ - elapsed_time, TimeDelta());
+ base::TimeDelta elapsed_time = base::TimeTicks::Now() - request_started_;
+ base::TimeDelta resolved_time =
+ std::max(timeout_ - elapsed_time, base::TimeDelta());
timeout_timer_.StartOneShot(resolved_time, FROM_HERE);
}
}
@@ -526,7 +535,7 @@ void ThreadableLoader::SetDefersLoading(bool value) {
void ThreadableLoader::Clear() {
client_ = nullptr;
timeout_timer_.Stop();
- request_started_ = TimeTicks();
+ request_started_ = base::TimeTicks();
if (GetResource())
checker_.WillRemoveClient();
ClearResource();
@@ -571,19 +580,19 @@ bool ThreadableLoader::RedirectReceived(
if (const auto error_status = cors::CheckAccess(
original_url, redirect_response.HttpStatusCode(),
redirect_response.HttpHeaderFields(),
- new_request.GetFetchCredentialsMode(), *GetSecurityOrigin())) {
+ new_request.GetCredentialsMode(), *GetSecurityOrigin())) {
DispatchDidFail(ResourceError(original_url, *error_status));
return false;
}
}
- if (redirect_mode_ == network::mojom::FetchRedirectMode::kError) {
+ if (redirect_mode_ == network::mojom::RedirectMode::kError) {
bool follow = client_->WillFollowRedirect(new_url, redirect_response);
DCHECK(!follow);
return false;
}
- if (redirect_mode_ == network::mojom::FetchRedirectMode::kManual) {
+ if (redirect_mode_ == network::mojom::RedirectMode::kManual) {
auto redirect_response_to_pass = redirect_response;
redirect_response_to_pass.SetType(
network::mojom::FetchResponseType::kOpaqueRedirect);
@@ -593,7 +602,7 @@ bool ThreadableLoader::RedirectReceived(
return false;
}
- DCHECK_EQ(redirect_mode_, network::mojom::FetchRedirectMode::kFollow);
+ DCHECK_EQ(redirect_mode_, network::mojom::RedirectMode::kFollow);
if (redirect_limit_ <= 0) {
ThreadableLoaderClient* client = client_;
@@ -614,14 +623,12 @@ bool ThreadableLoader::RedirectReceived(
// Allow same origin requests to continue after allowing clients to audit
// the redirect.
- if (!(cors_flag_ ||
- cors::CalculateCorsFlag(new_url, GetSecurityOrigin(),
- new_request.GetFetchRequestMode()))) {
+ if (!(cors_flag_ || cors::CalculateCorsFlag(new_url, GetSecurityOrigin(),
+ new_request.GetMode()))) {
bool follow =
client_->WillFollowRedirect(new_url, redirect_response_to_pass);
response_tainting_ = cors::CalculateResponseTainting(
- new_url, new_request.GetFetchRequestMode(), GetSecurityOrigin(),
- CorsFlag::Unset);
+ new_url, new_request.GetMode(), GetSecurityOrigin(), CorsFlag::Unset);
return follow;
}
@@ -633,7 +640,7 @@ bool ThreadableLoader::RedirectReceived(
redirect_response_to_pass, resource);
if (auto error_status = cors::CheckRedirectLocation(
- new_url, fetch_request_mode_, GetSecurityOrigin(),
+ new_url, request_mode_, GetSecurityOrigin(),
cors_flag_ ? CorsFlag::Set : CorsFlag::Unset)) {
DispatchDidFail(ResourceError(original_url, *error_status));
return false;
@@ -751,8 +758,8 @@ void ThreadableLoader::HandlePreflightResponse(
base::Optional<network::CorsErrorStatus> cors_error_status =
cors::CheckPreflightAccess(
response.CurrentRequestUrl(), response.HttpStatusCode(),
- response.HttpHeaderFields(),
- actual_request_.GetFetchCredentialsMode(), *GetSecurityOrigin());
+ response.HttpHeaderFields(), actual_request_.GetCredentialsMode(),
+ *GetSecurityOrigin());
if (cors_error_status) {
HandlePreflightFailure(response.CurrentRequestUrl(), *cors_error_status);
return;
@@ -779,8 +786,7 @@ void ThreadableLoader::HandlePreflightResponse(
error_status = cors::EnsurePreflightResultAndCacheOnSuccess(
response.HttpHeaderFields(), GetSecurityOrigin()->ToString(),
actual_request_.Url(), actual_request_.HttpMethod(),
- actual_request_.HttpHeaderFields(),
- actual_request_.GetFetchCredentialsMode());
+ actual_request_.HttpHeaderFields(), actual_request_.GetCredentialsMode());
if (error_status)
HandlePreflightFailure(response.CurrentRequestUrl(), *error_status);
}
@@ -840,7 +846,7 @@ void ThreadableLoader::ResponseReceived(Resource* resource,
// 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 (request_mode_ != network::mojom::RequestMode::kNoCors &&
response.GetType() == network::mojom::FetchResponseType::kOpaque) {
DispatchDidFail(
ResourceError(response.CurrentRequestUrl(),
@@ -869,8 +875,7 @@ void ThreadableLoader::ResponseReceived(Resource* resource,
if (cors_flag_) {
base::Optional<network::CorsErrorStatus> access_error = cors::CheckAccess(
response.CurrentRequestUrl(), response.HttpStatusCode(),
- response.HttpHeaderFields(), fetch_credentials_mode_,
- *GetSecurityOrigin());
+ response.HttpHeaderFields(), credentials_mode_, *GetSecurityOrigin());
if (access_error) {
ReportResponseReceived(resource->InspectorId(), response);
DispatchDidFail(
@@ -1020,18 +1025,18 @@ void ThreadableLoader::LoadRequest(
kDisableCorsHandlingByResourceFetcher;
if (out_of_blink_cors_) {
- if (request.GetFetchCredentialsMode() ==
- network::mojom::FetchCredentialsMode::kOmit) {
- // See comments at network::ResourceRequest::fetch_credentials_mode.
+ if (request.GetCredentialsMode() ==
+ network::mojom::CredentialsMode::kOmit) {
+ // See comments at network::ResourceRequest::credentials_mode.
request.SetAllowStoredCredentials(false);
}
} else {
if (actual_request_.IsNull()) {
response_tainting_ = cors::CalculateResponseTainting(
- request.Url(), request.GetFetchRequestMode(), GetSecurityOrigin(),
+ request.Url(), request.GetMode(), GetSecurityOrigin(),
cors_flag_ ? CorsFlag::Set : CorsFlag::Unset);
request.SetAllowStoredCredentials(cors::CalculateCredentialsFlag(
- request.GetFetchCredentialsMode(), response_tainting_));
+ request.GetCredentialsMode(), response_tainting_));
} else {
request.SetAllowStoredCredentials(false);
}
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 64154b40978..a682fdad527 100644
--- a/chromium/third_party/blink/renderer/core/loader/threadable_loader.h
+++ b/chromium/third_party/blink/renderer/core/loader/threadable_loader.h
@@ -37,7 +37,6 @@
#include "base/macros.h"
#include "services/network/public/mojom/fetch_api.mojom-blink.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/handle.h"
#include "third_party/blink/renderer/platform/loader/fetch/raw_resource.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_error.h"
@@ -45,7 +44,8 @@
#include "third_party/blink/renderer/platform/network/http_header_map.h"
#include "third_party/blink/renderer/platform/timer.h"
#include "third_party/blink/renderer/platform/weborigin/referrer.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_copier.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
@@ -121,7 +121,7 @@ class CORE_EXPORT ThreadableLoader final
// time the request started.
//
// Passing a timeout of zero means there should be no timeout.
- void SetTimeout(const TimeDelta& timeout);
+ void SetTimeout(const base::TimeDelta& timeout);
void Cancel();
@@ -213,7 +213,7 @@ class CORE_EXPORT ThreadableLoader final
Member<ExecutionContext> execution_context_;
Member<ResourceFetcher> resource_fetcher_;
- TimeDelta timeout_;
+ base::TimeDelta timeout_;
// Some items may be overridden by m_forceDoNotAllowStoredCredentials and
// m_securityOrigin. In such a case, build a ResourceLoaderOptions with
// up-to-date values from them and this variable, and use it.
@@ -235,8 +235,8 @@ class CORE_EXPORT ThreadableLoader final
// Saved so that we can use the original value for the modes in
// ResponseReceived() where |resource| might be a reused one (e.g. preloaded
// resource) which can have different modes.
- network::mojom::FetchRequestMode fetch_request_mode_;
- network::mojom::FetchCredentialsMode fetch_credentials_mode_;
+ network::mojom::RequestMode request_mode_;
+ network::mojom::CredentialsMode credentials_mode_;
// Holds the original request for fallback in case the Service Worker
// does not respond.
@@ -256,12 +256,13 @@ class CORE_EXPORT ThreadableLoader final
HTTPHeaderMap request_headers_;
TaskRunnerTimer<ThreadableLoader> timeout_timer_;
- TimeTicks request_started_; // Time an asynchronous fetch request is started
+ base::TimeTicks
+ request_started_; // Time an asynchronous fetch request is started
// Max number of times that this ThreadableLoader can follow.
int redirect_limit_;
- network::mojom::FetchRedirectMode redirect_mode_;
+ network::mojom::RedirectMode redirect_mode_;
// Holds the referrer after a redirect response was received. This referrer is
// used to populate the HTTP Referer header when following the redirect.
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 7f1a0107dd1..5d8fe7e1539 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
@@ -160,9 +160,11 @@ class ThreadableLoaderTestHelper final {
public:
ThreadableLoaderTestHelper()
: dummy_page_holder_(std::make_unique<DummyPageHolder>(IntSize(1, 1))) {
- GetDocument().SetURL(KURL("http://fake.url/"));
- GetDocument().SetSecurityOrigin(
- SecurityOrigin::Create(KURL("http://fake.url/")));
+ KURL url("http://fake.url/");
+ dummy_page_holder_->GetFrame().Loader().CommitNavigation(
+ WebNavigationParams::CreateWithHTMLBuffer(SharedBuffer::Create(), url),
+ nullptr /* extra_data */);
+ blink::test::RunPendingTasks();
}
void CreateLoader(ThreadableLoaderClient* client) {
@@ -208,13 +210,12 @@ class ThreadableLoaderTest : public testing::Test {
: helper_(std::make_unique<ThreadableLoaderTestHelper>()) {}
void StartLoader(const KURL& url,
- network::mojom::FetchRequestMode fetch_request_mode =
- network::mojom::FetchRequestMode::kNoCors) {
+ network::mojom::RequestMode request_mode =
+ network::mojom::RequestMode::kNoCors) {
ResourceRequest request(url);
request.SetRequestContext(mojom::RequestContextType::OBJECT);
- request.SetFetchRequestMode(fetch_request_mode);
- request.SetFetchCredentialsMode(
- network::mojom::FetchCredentialsMode::kOmit);
+ request.SetMode(request_mode);
+ request.SetCredentialsMode(network::mojom::CredentialsMode::kOmit);
helper_->StartLoader(request);
}
@@ -464,7 +465,7 @@ TEST_F(ThreadableLoaderTest, DidFailInStart) {
network::mojom::CorsError::kDisallowedByMode))));
EXPECT_CALL(GetCheckpoint(), Call(2));
- StartLoader(ErrorURL(), network::mojom::FetchRequestMode::kSameOrigin);
+ StartLoader(ErrorURL(), network::mojom::RequestMode::kSameOrigin);
CallCheckpoint(2);
ServeRequests();
}
@@ -479,7 +480,7 @@ TEST_F(ThreadableLoaderTest, CancelInDidFailInStart) {
.WillOnce(InvokeWithoutArgs(this, &ThreadableLoaderTest::CancelLoader));
EXPECT_CALL(GetCheckpoint(), Call(2));
- StartLoader(ErrorURL(), network::mojom::FetchRequestMode::kSameOrigin);
+ StartLoader(ErrorURL(), network::mojom::RequestMode::kSameOrigin);
CallCheckpoint(2);
ServeRequests();
}
@@ -494,7 +495,7 @@ TEST_F(ThreadableLoaderTest, ClearInDidFailInStart) {
.WillOnce(InvokeWithoutArgs(this, &ThreadableLoaderTest::ClearLoader));
EXPECT_CALL(GetCheckpoint(), Call(2));
- StartLoader(ErrorURL(), network::mojom::FetchRequestMode::kSameOrigin);
+ StartLoader(ErrorURL(), network::mojom::RequestMode::kSameOrigin);
CallCheckpoint(2);
ServeRequests();
}
@@ -512,7 +513,7 @@ TEST_F(ThreadableLoaderTest, DidFailAccessControlCheck) {
network::CorsErrorStatus(
network::mojom::CorsError::kMissingAllowOriginHeader))));
- StartLoader(SuccessURL(), network::mojom::FetchRequestMode::kCors);
+ StartLoader(SuccessURL(), network::mojom::RequestMode::kCors);
CallCheckpoint(2);
ServeRequests();
}
@@ -579,7 +580,7 @@ TEST_F(ThreadableLoaderTest, DidFailRedirectCheck) {
EXPECT_CALL(GetCheckpoint(), Call(2));
EXPECT_CALL(*Client(), DidFailRedirectCheck());
- StartLoader(RedirectLoopURL(), network::mojom::FetchRequestMode::kCors);
+ StartLoader(RedirectLoopURL(), network::mojom::RequestMode::kCors);
CallCheckpoint(2);
ServeRequests();
}
@@ -594,7 +595,7 @@ TEST_F(ThreadableLoaderTest, CancelInDidFailRedirectCheck) {
EXPECT_CALL(*Client(), DidFailRedirectCheck())
.WillOnce(InvokeWithoutArgs(this, &ThreadableLoaderTest::CancelLoader));
- StartLoader(RedirectLoopURL(), network::mojom::FetchRequestMode::kCors);
+ StartLoader(RedirectLoopURL(), network::mojom::RequestMode::kCors);
CallCheckpoint(2);
ServeRequests();
}
@@ -609,7 +610,7 @@ TEST_F(ThreadableLoaderTest, ClearInDidFailRedirectCheck) {
EXPECT_CALL(*Client(), DidFailRedirectCheck())
.WillOnce(InvokeWithoutArgs(this, &ThreadableLoaderTest::ClearLoader));
- StartLoader(RedirectLoopURL(), network::mojom::FetchRequestMode::kCors);
+ StartLoader(RedirectLoopURL(), network::mojom::RequestMode::kCors);
CallCheckpoint(2);
ServeRequests();
}
@@ -629,7 +630,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::RequestMode::kCors);
CallCheckpoint(2);
}
diff --git a/chromium/third_party/blink/renderer/core/loader/threaded_icon_loader.cc b/chromium/third_party/blink/renderer/core/loader/threaded_icon_loader.cc
new file mode 100644
index 00000000000..668d44a1613
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/loader/threaded_icon_loader.cc
@@ -0,0 +1,183 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/loader/threaded_icon_loader.h"
+
+#include <algorithm>
+
+#include "base/metrics/histogram_macros.h"
+#include "skia/ext/image_operations.h"
+#include "third_party/blink/renderer/core/execution_context/execution_context.h"
+#include "third_party/blink/renderer/platform/image-decoders/image_decoder.h"
+#include "third_party/blink/renderer/platform/image-decoders/image_frame.h"
+#include "third_party/blink/renderer/platform/image-decoders/segment_reader.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/scheduler/public/post_cross_thread_task.h"
+#include "third_party/blink/renderer/platform/scheduler/public/worker_pool.h"
+#include "third_party/blink/renderer/platform/weborigin/kurl.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
+
+namespace blink {
+
+namespace {
+
+// Because including base::ClampToRange would be a dependency violation.
+int ClampToRange(const int value, const int min, const int max) {
+ return std::min(std::max(value, min), max);
+}
+
+} // namespace
+
+void ThreadedIconLoader::Start(ExecutionContext* execution_context,
+ const ResourceRequest& resource_request,
+ const base::Optional<WebSize>& resize_dimensions,
+ IconCallback callback) {
+ DCHECK(!stopped_);
+ DCHECK(resource_request.Url().IsValid());
+ DCHECK_EQ(resource_request.GetRequestContext(),
+ mojom::RequestContextType::IMAGE);
+ DCHECK(!icon_callback_);
+
+ icon_callback_ = std::move(callback);
+ resize_dimensions_ = resize_dimensions;
+
+ ResourceLoaderOptions resource_loader_options;
+ if (execution_context->IsWorkerGlobalScope())
+ resource_loader_options.request_initiator_context = kWorkerContext;
+
+ threadable_loader_ = MakeGarbageCollected<ThreadableLoader>(
+ *execution_context, this, resource_loader_options);
+ threadable_loader_->SetTimeout(resource_request.TimeoutInterval());
+ threadable_loader_->Start(resource_request);
+
+ start_time_ = base::TimeTicks::Now();
+}
+
+void ThreadedIconLoader::Stop() {
+ stopped_ = true;
+ if (threadable_loader_) {
+ threadable_loader_->Cancel();
+ threadable_loader_ = nullptr;
+ }
+}
+
+void ThreadedIconLoader::DidReceiveData(const char* data, unsigned length) {
+ if (!data_)
+ data_ = SharedBuffer::Create();
+ data_->Append(data, length);
+}
+
+void ThreadedIconLoader::DidFinishLoading(uint64_t resource_identifier) {
+ if (stopped_)
+ return;
+
+ if (!data_) {
+ std::move(icon_callback_).Run(SkBitmap(), -1);
+ return;
+ }
+
+ UMA_HISTOGRAM_MEDIUM_TIMES("Blink.ThreadedIconLoader.LoadTime",
+ base::TimeTicks::Now() - start_time_);
+
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner =
+ Thread::Current()->GetTaskRunner();
+
+ worker_pool::PostTask(
+ FROM_HERE,
+ CrossThreadBindOnce(
+ &ThreadedIconLoader::DecodeAndResizeImageOnBackgroundThread,
+ WrapCrossThreadPersistent(this), std::move(task_runner),
+ SegmentReader::CreateFromSharedBuffer(std::move(data_))));
+}
+
+void ThreadedIconLoader::DecodeAndResizeImageOnBackgroundThread(
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner,
+ scoped_refptr<SegmentReader> data) {
+ DCHECK(task_runner);
+ DCHECK(data);
+
+ auto notify_complete = [&](double refactor_scale) {
+ PostCrossThreadTask(
+ *task_runner, FROM_HERE,
+ CrossThreadBindOnce(&ThreadedIconLoader::OnBackgroundTaskComplete,
+ WrapCrossThreadPersistent(this), refactor_scale));
+ };
+
+ std::unique_ptr<ImageDecoder> decoder = ImageDecoder::Create(
+ std::move(data), /* data_complete= */ true,
+ ImageDecoder::kAlphaPremultiplied, ImageDecoder::kDefaultBitDepth,
+ ColorBehavior::TransformToSRGB());
+
+ if (!decoder) {
+ notify_complete(-1.0);
+ return;
+ }
+
+ ImageFrame* image_frame = decoder->DecodeFrameBufferAtIndex(0);
+
+ if (!image_frame) {
+ notify_complete(-1.0);
+ return;
+ }
+
+ decoded_icon_ = image_frame->Bitmap();
+ if (!resize_dimensions_) {
+ notify_complete(1.0);
+ return;
+ }
+
+ // If the icon is larger than |resize_dimensions_| permits, we need to resize
+ // it as well. This can be done synchronously given that we're on a
+ // background thread already.
+ double scale = std::min(
+ static_cast<double>(resize_dimensions_->width) / decoded_icon_.width(),
+ static_cast<double>(resize_dimensions_->height) / decoded_icon_.height());
+
+ if (scale >= 1.0) {
+ notify_complete(1.0);
+ return;
+ }
+
+ int resized_width =
+ ClampToRange(static_cast<int>(scale * decoded_icon_.width()), 1,
+ resize_dimensions_->width);
+ int resized_height =
+ ClampToRange(static_cast<int>(scale * decoded_icon_.height()), 1,
+ resize_dimensions_->height);
+
+ // Use the RESIZE_GOOD quality allowing the implementation to pick an
+ // appropriate method for the resize. Can be increased to RESIZE_BETTER
+ // or RESIZE_BEST if the quality looks poor.
+ decoded_icon_ = skia::ImageOperations::Resize(
+ decoded_icon_, skia::ImageOperations::RESIZE_GOOD, resized_width,
+ resized_height);
+
+ notify_complete(scale);
+}
+
+void ThreadedIconLoader::OnBackgroundTaskComplete(double resize_scale) {
+ if (stopped_)
+ return;
+ std::move(icon_callback_).Run(std::move(decoded_icon_), resize_scale);
+}
+
+void ThreadedIconLoader::DidFail(const ResourceError& error) {
+ if (stopped_)
+ return;
+ std::move(icon_callback_).Run(SkBitmap(), -1);
+}
+
+void ThreadedIconLoader::DidFailRedirectCheck() {
+ if (stopped_)
+ return;
+ std::move(icon_callback_).Run(SkBitmap(), -1);
+}
+
+void ThreadedIconLoader::Trace(blink::Visitor* visitor) {
+ visitor->Trace(threadable_loader_);
+ ThreadableLoaderClient::Trace(visitor);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/loader/threaded_icon_loader.h b/chromium/third_party/blink/renderer/core/loader/threaded_icon_loader.h
new file mode 100644
index 00000000000..2b8b9fdd224
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/loader/threaded_icon_loader.h
@@ -0,0 +1,82 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_THREADED_ICON_LOADER_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_THREADED_ICON_LOADER_H_
+
+#include "base/memory/scoped_refptr.h"
+#include "base/optional.h"
+#include "base/time/time.h"
+#include "third_party/blink/public/platform/web_size.h"
+#include "third_party/blink/renderer/core/core_export.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/heap/garbage_collected.h"
+#include "third_party/skia/include/core/SkBitmap.h"
+
+namespace blink {
+
+class ResourceRequest;
+class SegmentReader;
+
+// Utility class for loading, decoding, and potentially rescaling an icon on a
+// background thread. Note that icons are only downscaled and never upscaled.
+class CORE_EXPORT ThreadedIconLoader final
+ : public GarbageCollectedFinalized<ThreadedIconLoader>,
+ public ThreadableLoaderClient {
+ USING_GARBAGE_COLLECTED_MIXIN(ThreadedIconLoader);
+
+ public:
+ // On failure, |callback| is called with a null SkBitmap and |resize_scale|
+ // set to -1. On success, the icon is provided with a |resize_scale| <= 1.
+ using IconCallback =
+ base::OnceCallback<void(SkBitmap icon, double resize_scale)>;
+
+ // Starts a background task to download and decode the icon.
+ // If |resize_dimensions| is provided, the icon will will be downscaled to
+ // those dimensions.
+ void Start(ExecutionContext* execution_context,
+ const ResourceRequest& resource_request,
+ const base::Optional<WebSize>& resize_dimensions,
+ IconCallback callback);
+
+ // Stops the background task. The provided callback will not be run if
+ // `Stop` is called.
+ void Stop();
+
+ // ThreadableLoaderClient interface.
+ void DidReceiveData(const char* data, unsigned length) override;
+ void DidFinishLoading(uint64_t resource_identifier) override;
+ void DidFail(const ResourceError& error) override;
+ void DidFailRedirectCheck() override;
+
+ void Trace(blink::Visitor* visitor) override;
+
+ private:
+ void DecodeAndResizeImageOnBackgroundThread(
+ scoped_refptr<base::SingleThreadTaskRunner> task_runner,
+ scoped_refptr<SegmentReader> data);
+
+ void OnBackgroundTaskComplete(double resize_scale);
+
+ Member<ThreadableLoader> threadable_loader_;
+
+ // Data received from |threadable_loader_|. Will be invalidated when decoding
+ // of the image data starts.
+ scoped_refptr<SharedBuffer> data_;
+
+ // Accessed from main thread and background thread.
+ base::Optional<WebSize> resize_dimensions_;
+ SkBitmap decoded_icon_;
+
+ IconCallback icon_callback_;
+
+ base::TimeTicks start_time_;
+
+ bool stopped_ = false;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_THREADED_ICON_LOADER_H_
diff --git a/chromium/third_party/blink/renderer/core/loader/threaded_icon_loader_test.cc b/chromium/third_party/blink/renderer/core/loader/threaded_icon_loader_test.cc
new file mode 100644
index 00000000000..18f20c13005
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/loader/threaded_icon_loader_test.cc
@@ -0,0 +1,141 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/loader/threaded_icon_loader.h"
+
+#include "base/optional.h"
+#include "testing/gtest/include/gtest/gtest.h"
+#include "third_party/blink/public/platform/web_size.h"
+#include "third_party/blink/public/platform/web_url.h"
+#include "third_party/blink/public/platform/web_url_loader_mock_factory.h"
+#include "third_party/blink/renderer/core/execution_context/execution_context.h"
+#include "third_party/blink/renderer/core/testing/page_test_base.h"
+#include "third_party/blink/renderer/platform/testing/histogram_tester.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"
+#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/wtf_string.h"
+
+namespace blink {
+namespace {
+
+constexpr char kIconLoaderBaseUrl[] = "http://test.com/";
+constexpr char kIconLoaderBaseDir[] = "notifications/";
+constexpr char kIconLoaderIcon100x100[] = "100x100.png";
+constexpr char kIconLoaderInvalidIcon[] = "file.txt";
+
+class ThreadedIconLoaderTest : public PageTestBase {
+ public:
+ void SetUp() override {
+ PageTestBase::SetUp(IntSize());
+ GetDocument().SetBaseURLOverride(KURL(kIconLoaderBaseUrl));
+ }
+
+ void TearDown() override {
+ platform_->GetURLLoaderMockFactory()
+ ->UnregisterAllURLsAndClearMemoryCache();
+ }
+
+ // Registers a mocked url. When fetched, |fileName| will be loaded from the
+ // test data directory.
+ KURL RegisterMockedURL(const String& file_name) {
+ return url_test_helpers::RegisterMockedURLLoadFromBase(
+ kIconLoaderBaseUrl, test::CoreTestDataPath(kIconLoaderBaseDir),
+ file_name, "image/png");
+ }
+
+ std::pair<SkBitmap, double> LoadIcon(
+ const KURL& url,
+ base::Optional<WebSize> resize_dimensions = base::nullopt) {
+ auto* icon_loader = MakeGarbageCollected<ThreadedIconLoader>();
+
+ ResourceRequest resource_request(url);
+ resource_request.SetRequestContext(mojom::RequestContextType::IMAGE);
+ resource_request.SetPriority(ResourceLoadPriority::kMedium);
+
+ SkBitmap icon;
+ double resize_scale;
+ base::RunLoop run_loop;
+ icon_loader->Start(
+ &GetDocument(), resource_request, resize_dimensions,
+ WTF::Bind(&ThreadedIconLoaderTest::DidGetIcon, WTF::Unretained(this),
+ run_loop.QuitClosure(), WTF::Unretained(&icon),
+ WTF::Unretained(&resize_scale)));
+ platform_->GetURLLoaderMockFactory()->ServeAsynchronousRequests();
+ run_loop.Run();
+
+ return {icon, resize_scale};
+ }
+
+ private:
+ void DidGetIcon(base::OnceClosure quit_closure,
+ SkBitmap* out_icon,
+ double* out_resize_scale,
+ SkBitmap icon,
+ double resize_scale) {
+ *out_icon = std::move(icon);
+ *out_resize_scale = resize_scale;
+ std::move(quit_closure).Run();
+ }
+
+ ScopedTestingPlatformSupport<TestingPlatformSupport> platform_;
+};
+
+TEST_F(ThreadedIconLoaderTest, LoadIcon) {
+ auto result = LoadIcon(RegisterMockedURL(kIconLoaderIcon100x100));
+ const SkBitmap& icon = result.first;
+ double resize_scale = result.second;
+
+ ASSERT_FALSE(icon.isNull());
+ EXPECT_FALSE(icon.drawsNothing());
+ EXPECT_EQ(icon.width(), 100);
+ EXPECT_EQ(icon.height(), 100);
+ EXPECT_EQ(resize_scale, 1.0);
+}
+
+TEST_F(ThreadedIconLoaderTest, LoadAndDownscaleIcon) {
+ WebSize dimensions = {50, 50};
+ auto result = LoadIcon(RegisterMockedURL(kIconLoaderIcon100x100), dimensions);
+ const SkBitmap& icon = result.first;
+ double resize_scale = result.second;
+
+ ASSERT_FALSE(icon.isNull());
+ EXPECT_FALSE(icon.drawsNothing());
+ EXPECT_EQ(icon.width(), 50);
+ EXPECT_EQ(icon.height(), 50);
+ EXPECT_EQ(resize_scale, 0.5);
+}
+
+TEST_F(ThreadedIconLoaderTest, LoadIconAndUpscaleIgnored) {
+ WebSize dimensions = {500, 500};
+ auto result = LoadIcon(RegisterMockedURL(kIconLoaderIcon100x100), dimensions);
+ const SkBitmap& icon = result.first;
+ double resize_scale = result.second;
+
+ ASSERT_FALSE(icon.isNull());
+ EXPECT_FALSE(icon.drawsNothing());
+ EXPECT_EQ(icon.width(), 100);
+ EXPECT_EQ(icon.height(), 100);
+ EXPECT_EQ(resize_scale, 1.0);
+}
+
+TEST_F(ThreadedIconLoaderTest, InvalidResourceReturnsNullIcon) {
+ auto result = LoadIcon(RegisterMockedURL(kIconLoaderInvalidIcon));
+ const SkBitmap& icon = result.first;
+ double resize_scale = result.second;
+
+ ASSERT_TRUE(icon.isNull());
+ EXPECT_EQ(resize_scale, -1.0);
+}
+
+TEST_F(ThreadedIconLoaderTest, LoadTimeRecordedByUMA) {
+ HistogramTester histogram_tester;
+ LoadIcon(RegisterMockedURL(kIconLoaderIcon100x100));
+ histogram_tester.ExpectTotalCount("Blink.ThreadedIconLoader.LoadTime", 1);
+}
+
+} // namespace
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/exported/web_associated_url_loader_impl.cc b/chromium/third_party/blink/renderer/core/loader/web_associated_url_loader_impl.cc
index 67b24bcee32..b8019469ab7 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_associated_url_loader_impl.cc
+++ b/chromium/third_party/blink/renderer/core/loader/web_associated_url_loader_impl.cc
@@ -28,7 +28,7 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "third_party/blink/renderer/core/exported/web_associated_url_loader_impl.h"
+#include "third_party/blink/renderer/core/loader/web_associated_url_loader_impl.h"
#include <limits>
#include <memory>
@@ -102,8 +102,8 @@ class WebAssociatedURLLoaderImpl::ClientAdapter final
ClientAdapter(WebAssociatedURLLoaderImpl*,
WebAssociatedURLLoaderClient*,
const WebAssociatedURLLoaderOptions&,
- network::mojom::FetchRequestMode,
- network::mojom::FetchCredentialsMode,
+ network::mojom::RequestMode,
+ network::mojom::CredentialsMode,
scoped_refptr<base::SingleThreadTaskRunner>);
// ThreadableLoaderClient
@@ -122,7 +122,7 @@ class WebAssociatedURLLoaderImpl::ClientAdapter final
const KURL& /*new_url*/,
const ResourceResponse& /*redirect_response*/) override;
- // Sets an error to be reported back to the client, asychronously.
+ // Sets an error to be reported back to the client, asynchronously.
void SetDelayedError(const ResourceError&);
// Enables forwarding of error notifications to the
@@ -145,8 +145,8 @@ class WebAssociatedURLLoaderImpl::ClientAdapter final
WebAssociatedURLLoaderImpl* loader_;
WebAssociatedURLLoaderClient* client_;
WebAssociatedURLLoaderOptions options_;
- network::mojom::FetchRequestMode fetch_request_mode_;
- network::mojom::FetchCredentialsMode credentials_mode_;
+ network::mojom::RequestMode request_mode_;
+ network::mojom::CredentialsMode credentials_mode_;
base::Optional<WebURLError> error_;
TaskRunnerTimer<ClientAdapter> error_timer_;
@@ -160,13 +160,13 @@ WebAssociatedURLLoaderImpl::ClientAdapter::ClientAdapter(
WebAssociatedURLLoaderImpl* loader,
WebAssociatedURLLoaderClient* client,
const WebAssociatedURLLoaderOptions& options,
- network::mojom::FetchRequestMode fetch_request_mode,
- network::mojom::FetchCredentialsMode credentials_mode,
+ network::mojom::RequestMode request_mode,
+ network::mojom::CredentialsMode credentials_mode,
scoped_refptr<base::SingleThreadTaskRunner> task_runner)
: loader_(loader),
client_(client),
options_(options),
- fetch_request_mode_(fetch_request_mode),
+ request_mode_(request_mode),
credentials_mode_(credentials_mode),
error_timer_(std::move(task_runner), this, &ClientAdapter::NotifyError),
enable_error_notifications_(false),
@@ -203,9 +203,9 @@ void WebAssociatedURLLoaderImpl::ClientAdapter::DidReceiveResponse(
return;
if (options_.expose_all_response_headers ||
- (fetch_request_mode_ != network::mojom::FetchRequestMode::kCors &&
- fetch_request_mode_ !=
- network::mojom::FetchRequestMode::kCorsWithForcedPreflight)) {
+ (request_mode_ != network::mojom::RequestMode::kCors &&
+ request_mode_ !=
+ network::mojom::RequestMode::kCorsWithForcedPreflight)) {
// Use the original ResourceResponse.
client_->DidReceiveResponse(WrappedResourceResponse(response));
return;
@@ -217,9 +217,8 @@ void WebAssociatedURLLoaderImpl::ClientAdapter::DidReceiveResponse(
for (const auto& header : response.HttpHeaderFields()) {
if (FetchUtils::IsForbiddenResponseHeaderName(header.key) ||
(!cors::IsCorsSafelistedResponseHeader(header.key) &&
- exposed_headers.find(header.key.Ascii().data()) ==
- exposed_headers.end()))
- blocked_headers.insert(header.key.Ascii().data());
+ exposed_headers.find(header.key.Ascii()) == exposed_headers.end()))
+ blocked_headers.insert(header.key.Ascii());
}
if (blocked_headers.empty()) {
@@ -297,7 +296,7 @@ void WebAssociatedURLLoaderImpl::ClientAdapter::EnableErrorNotifications() {
// client after WebAssociatedURLLoader::loadAsynchronously has returned to the
// caller.
if (did_fail_)
- error_timer_.StartOneShot(TimeDelta(), FROM_HERE);
+ error_timer_.StartOneShot(base::TimeDelta(), FROM_HERE);
}
void WebAssociatedURLLoaderImpl::ClientAdapter::NotifyError(TimerBase* timer) {
@@ -384,20 +383,20 @@ void WebAssociatedURLLoaderImpl::LoadAsynchronously(
}
client_ = client;
client_adapter_ = MakeGarbageCollected<ClientAdapter>(
- this, client, options_, request.GetFetchRequestMode(),
- request.GetFetchCredentialsMode(), std::move(task_runner));
+ this, client, options_, request.GetMode(), request.GetCredentialsMode(),
+ std::move(task_runner));
if (allow_load) {
ResourceLoaderOptions resource_loader_options;
resource_loader_options.data_buffering_policy = kDoNotBufferData;
if (options_.grant_universal_access) {
- const auto mode = new_request.GetFetchRequestMode();
- DCHECK(mode == network::mojom::FetchRequestMode::kNoCors ||
- mode == network::mojom::FetchRequestMode::kNavigate);
+ const auto request_mode = new_request.GetMode();
+ DCHECK(request_mode == network::mojom::RequestMode::kNoCors ||
+ request_mode == network::mojom::RequestMode::kNavigate);
// Some callers, notablly flash, with |grant_universal_access| want to
// have an origin matching with referrer.
- KURL referrer(request.HttpHeaderField(http_names::kReferer));
+ KURL referrer(request.ToResourceRequest().ReferrerString());
scoped_refptr<SecurityOrigin> origin = SecurityOrigin::Create(referrer);
origin->GrantUniversalAccess();
new_request.ToMutableResourceRequest().SetRequestorOrigin(origin);
diff --git a/chromium/third_party/blink/renderer/core/exported/web_associated_url_loader_impl.h b/chromium/third_party/blink/renderer/core/loader/web_associated_url_loader_impl.h
index 70b69ee9679..2c8ccfc2669 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_associated_url_loader_impl.h
+++ b/chromium/third_party/blink/renderer/core/loader/web_associated_url_loader_impl.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_EXPORTED_WEB_ASSOCIATED_URL_LOADER_IMPL_H_
-#define THIRD_PARTY_BLINK_RENDERER_CORE_EXPORTED_WEB_ASSOCIATED_URL_LOADER_IMPL_H_
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_WEB_ASSOCIATED_URL_LOADER_IMPL_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_WEB_ASSOCIATED_URL_LOADER_IMPL_H_
#include <memory>
@@ -24,6 +24,8 @@ class Document;
// This class is used to implement WebFrame::createAssociatedURLLoader.
class CORE_EXPORT WebAssociatedURLLoaderImpl final
: public WebAssociatedURLLoader {
+ USING_FAST_MALLOC(WebAssociatedURLLoaderImpl);
+
public:
WebAssociatedURLLoaderImpl(Document*, const WebAssociatedURLLoaderOptions&);
~WebAssociatedURLLoaderImpl() override;
diff --git a/chromium/third_party/blink/renderer/core/exported/web_associated_url_loader_impl_test.cc b/chromium/third_party/blink/renderer/core/loader/web_associated_url_loader_impl_test.cc
index 25c68a09045..f9855015fff 100644
--- a/chromium/third_party/blink/renderer/core/exported/web_associated_url_loader_impl_test.cc
+++ b/chromium/third_party/blink/renderer/core/loader/web_associated_url_loader_impl_test.cc
@@ -51,11 +51,10 @@
#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/testing/url_test_helpers.h"
-#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
-using blink::url_test_helpers::ToKURL;
using blink::test::RunPendingTasks;
+using blink::url_test_helpers::ToKURL;
namespace blink {
@@ -78,9 +77,9 @@ class WebAssociatedURLLoaderTest : public testing::Test,
const WTF::String& filename) {
WebURLResponse response;
response.SetMimeType("text/html");
- KURL url = ToKURL(url_root + filename.Utf8().data());
+ KURL url = ToKURL(url_root + filename.Utf8());
Platform::Current()->GetURLLoaderMockFactory()->RegisterURL(
- url, response, test::CoreTestDataPath(filename.Utf8().data()));
+ url, response, test::CoreTestDataPath(filename.Utf8().c_str()));
return url;
}
@@ -90,14 +89,15 @@ class WebAssociatedURLLoaderTest : public testing::Test,
std::string url_root = "http://www.test.com/";
KURL url = RegisterMockedUrl(url_root, "iframes_test.html");
const char* iframe_support_files[] = {
- "invisible_iframe.html", "visible_iframe.html",
+ "invisible_iframe.html",
+ "visible_iframe.html",
"zero_sized_iframe.html",
};
for (size_t i = 0; i < base::size(iframe_support_files); ++i) {
RegisterMockedUrl(url_root, iframe_support_files[i]);
}
- frame_test_helpers::LoadFrame(MainFrame(), url.GetString().Utf8().data());
+ frame_test_helpers::LoadFrame(MainFrame(), url.GetString().Utf8().c_str());
Platform::Current()->GetURLLoaderMockFactory()->UnregisterURL(url);
}
@@ -165,9 +165,8 @@ class WebAssociatedURLLoaderTest : public testing::Test,
void CheckMethodFails(const char* unsafe_method) {
WebURLRequest request(ToKURL("http://www.test.com/success.html"));
- request.SetFetchRequestMode(network::mojom::FetchRequestMode::kSameOrigin);
- request.SetFetchCredentialsMode(
- network::mojom::FetchCredentialsMode::kOmit);
+ request.SetMode(network::mojom::RequestMode::kSameOrigin);
+ request.SetCredentialsMode(network::mojom::CredentialsMode::kOmit);
request.SetHttpMethod(WebString::FromUTF8(unsafe_method));
WebAssociatedURLLoaderOptions options;
options.untrusted_http = true;
@@ -180,9 +179,8 @@ class WebAssociatedURLLoaderTest : public testing::Test,
void CheckHeaderFails(const char* header_field, const char* header_value) {
WebURLRequest request(ToKURL("http://www.test.com/success.html"));
- request.SetFetchRequestMode(network::mojom::FetchRequestMode::kSameOrigin);
- request.SetFetchCredentialsMode(
- network::mojom::FetchCredentialsMode::kOmit);
+ request.SetMode(network::mojom::RequestMode::kSameOrigin);
+ request.SetCredentialsMode(network::mojom::CredentialsMode::kOmit);
if (EqualIgnoringASCIICase(WebString::FromUTF8(header_field), "referer")) {
request.SetHttpReferrer(WebString::FromUTF8(header_value),
network::mojom::ReferrerPolicy::kDefault);
@@ -220,9 +218,8 @@ class WebAssociatedURLLoaderTest : public testing::Test,
KURL url = ToKURL(id);
WebURLRequest request(url);
- request.SetFetchRequestMode(network::mojom::FetchRequestMode::kCors);
- request.SetFetchCredentialsMode(
- network::mojom::FetchCredentialsMode::kOmit);
+ request.SetMode(network::mojom::RequestMode::kCors);
+ request.SetCredentialsMode(network::mojom::CredentialsMode::kOmit);
WebString header_name_string(WebString::FromUTF8(header_name));
expected_response_ = WebURLResponse();
@@ -276,8 +273,8 @@ class WebAssociatedURLLoaderTest : public testing::Test,
TEST_F(WebAssociatedURLLoaderTest, SameOriginSuccess) {
KURL url = ToKURL("http://www.test.com/SameOriginSuccess.html");
WebURLRequest request(url);
- request.SetFetchRequestMode(network::mojom::FetchRequestMode::kSameOrigin);
- request.SetFetchCredentialsMode(network::mojom::FetchCredentialsMode::kOmit);
+ request.SetMode(network::mojom::RequestMode::kSameOrigin);
+ request.SetCredentialsMode(network::mojom::CredentialsMode::kOmit);
expected_response_ = WebURLResponse();
expected_response_.SetMimeType("text/html");
@@ -299,8 +296,8 @@ TEST_F(WebAssociatedURLLoaderTest, SameOriginRestriction) {
// This is cross-origin since the frame was loaded from www.test.com.
KURL url = ToKURL("http://www.other.com/SameOriginRestriction.html");
WebURLRequest request(url);
- request.SetFetchRequestMode(network::mojom::FetchRequestMode::kSameOrigin);
- request.SetFetchCredentialsMode(network::mojom::FetchCredentialsMode::kOmit);
+ request.SetMode(network::mojom::RequestMode::kSameOrigin);
+ request.SetCredentialsMode(network::mojom::CredentialsMode::kOmit);
CheckFails(request);
}
@@ -312,7 +309,7 @@ TEST_F(WebAssociatedURLLoaderTest, CrossOriginSuccess) {
// No-CORS requests (CrossOriginRequestPolicyAllow) aren't allowed for the
// default context. So we set the context as Script here.
request.SetRequestContext(mojom::RequestContextType::SCRIPT);
- request.SetFetchCredentialsMode(network::mojom::FetchCredentialsMode::kOmit);
+ request.SetCredentialsMode(network::mojom::CredentialsMode::kOmit);
expected_response_ = WebURLResponse();
expected_response_.SetMimeType("text/html");
@@ -336,8 +333,8 @@ TEST_F(WebAssociatedURLLoaderTest, CrossOriginWithAccessControlSuccess) {
KURL url =
ToKURL("http://www.other.com/CrossOriginWithAccessControlSuccess.html");
WebURLRequest request(url);
- request.SetFetchRequestMode(network::mojom::FetchRequestMode::kCors);
- request.SetFetchCredentialsMode(network::mojom::FetchCredentialsMode::kOmit);
+ request.SetMode(network::mojom::RequestMode::kCors);
+ request.SetCredentialsMode(network::mojom::CredentialsMode::kOmit);
expected_response_ = WebURLResponse();
expected_response_.SetMimeType("text/html");
@@ -365,7 +362,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.SetMode(network::mojom::RequestMode::kCors);
expected_response_ = WebURLResponse();
expected_response_.SetMimeType("text/html");
@@ -394,8 +391,8 @@ TEST_F(WebAssociatedURLLoaderTest,
KURL url =
ToKURL("http://www.other.com/CrossOriginWithAccessControlFailure.html");
WebURLRequest request(url);
- request.SetFetchRequestMode(network::mojom::FetchRequestMode::kCors);
- request.SetFetchCredentialsMode(network::mojom::FetchCredentialsMode::kOmit);
+ request.SetMode(network::mojom::RequestMode::kCors);
+ request.SetCredentialsMode(network::mojom::CredentialsMode::kOmit);
expected_response_ = WebURLResponse();
expected_response_.SetMimeType("text/html");
@@ -424,8 +421,8 @@ TEST_F(WebAssociatedURLLoaderTest, RedirectSuccess) {
KURL redirect_url = ToKURL(redirect);
WebURLRequest request(url);
- request.SetFetchRequestMode(network::mojom::FetchRequestMode::kSameOrigin);
- request.SetFetchCredentialsMode(network::mojom::FetchCredentialsMode::kOmit);
+ request.SetMode(network::mojom::RequestMode::kSameOrigin);
+ request.SetCredentialsMode(network::mojom::CredentialsMode::kOmit);
expected_redirect_response_ = WebURLResponse();
expected_redirect_response_.SetMimeType("text/html");
@@ -460,8 +457,8 @@ TEST_F(WebAssociatedURLLoaderTest, RedirectCrossOriginFailure) {
KURL redirect_url = ToKURL(redirect);
WebURLRequest request(url);
- request.SetFetchRequestMode(network::mojom::FetchRequestMode::kSameOrigin);
- request.SetFetchCredentialsMode(network::mojom::FetchCredentialsMode::kOmit);
+ request.SetMode(network::mojom::RequestMode::kSameOrigin);
+ request.SetCredentialsMode(network::mojom::CredentialsMode::kOmit);
expected_redirect_response_ = WebURLResponse();
expected_redirect_response_.SetMimeType("text/html");
@@ -500,8 +497,8 @@ TEST_F(WebAssociatedURLLoaderTest,
KURL redirect_url = ToKURL(redirect);
WebURLRequest request(url);
- request.SetFetchRequestMode(network::mojom::FetchRequestMode::kCors);
- request.SetFetchCredentialsMode(network::mojom::FetchCredentialsMode::kOmit);
+ request.SetMode(network::mojom::RequestMode::kCors);
+ request.SetCredentialsMode(network::mojom::CredentialsMode::kOmit);
expected_redirect_response_ = WebURLResponse();
expected_redirect_response_.SetMimeType("text/html");
@@ -543,8 +540,8 @@ TEST_F(WebAssociatedURLLoaderTest,
KURL redirect_url = ToKURL(redirect);
WebURLRequest request(url);
- request.SetFetchRequestMode(network::mojom::FetchRequestMode::kCors);
- request.SetFetchCredentialsMode(network::mojom::FetchCredentialsMode::kOmit);
+ request.SetMode(network::mojom::RequestMode::kCors);
+ request.SetCredentialsMode(network::mojom::CredentialsMode::kOmit);
// Add a CORS simple header.
request.SetHttpHeaderField("accept", "application/json");
@@ -664,8 +661,8 @@ TEST_F(WebAssociatedURLLoaderTest, CrossOriginHeaderAllowResponseHeaders) {
KURL url =
ToKURL("http://www.other.com/CrossOriginHeaderAllowResponseHeaders.html");
WebURLRequest request(url);
- request.SetFetchRequestMode(network::mojom::FetchRequestMode::kCors);
- request.SetFetchCredentialsMode(network::mojom::FetchCredentialsMode::kOmit);
+ request.SetMode(network::mojom::RequestMode::kCors);
+ request.SetCredentialsMode(network::mojom::CredentialsMode::kOmit);
WebString header_name_string(WebString::FromUTF8("non-safelisted"));
expected_response_ = WebURLResponse();
@@ -695,8 +692,8 @@ TEST_F(WebAssociatedURLLoaderTest, AccessCheckForLocalURL) {
WebURLRequest request(url);
request.SetRequestContext(mojom::RequestContextType::PLUGIN);
- request.SetFetchRequestMode(network::mojom::FetchRequestMode::kNoCors);
- request.SetFetchCredentialsMode(network::mojom::FetchCredentialsMode::kOmit);
+ request.SetMode(network::mojom::RequestMode::kNoCors);
+ request.SetCredentialsMode(network::mojom::CredentialsMode::kOmit);
expected_response_ = WebURLResponse();
expected_response_.SetMimeType("text/plain");
@@ -722,8 +719,8 @@ TEST_F(WebAssociatedURLLoaderTest, BypassAccessCheckForLocalURL) {
WebURLRequest request(url);
request.SetRequestContext(mojom::RequestContextType::PLUGIN);
- request.SetFetchRequestMode(network::mojom::FetchRequestMode::kNoCors);
- request.SetFetchCredentialsMode(network::mojom::FetchCredentialsMode::kOmit);
+ request.SetMode(network::mojom::RequestMode::kNoCors);
+ request.SetCredentialsMode(network::mojom::CredentialsMode::kOmit);
expected_response_ = WebURLResponse();
expected_response_.SetMimeType("text/plain");
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 1ad94733442..7f2f15bdfee 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
@@ -11,7 +11,6 @@
#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/renderer/core/frame/deprecation.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#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"
@@ -20,6 +19,7 @@
#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/platform/exported/wrapped_resource_request.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher_properties.h"
@@ -222,8 +222,6 @@ void WorkerFetchContext::AddResourceTiming(const ResourceTimingInfo& info) {
// worklets.
if (global_scope_->IsWorkletGlobalScope())
return;
- if (!resource_timing_notifier_)
- return;
const SecurityOrigin* security_origin = GetResourceFetcherProperties()
.GetFetchClientSettingsObject()
.GetSecurityOrigin();
@@ -246,11 +244,6 @@ void WorkerFetchContext::PopulateResourceRequest(
out_request.SetTopFrameOrigin(GetTopFrameOrigin());
}
-FetchContext* WorkerFetchContext::Detach() {
- resource_timing_notifier_.Clear();
- return BaseFetchContext::Detach();
-}
-
void WorkerFetchContext::SetFirstPartyCookie(ResourceRequest& out_request) {
if (out_request.SiteForCookies().IsNull())
out_request.SetSiteForCookies(GetSiteForCookies());
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 f725745b073..4cd0d96507d 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
@@ -83,7 +83,6 @@ class WorkerFetchContext final : public BaseFetchContext {
const ClientHintsPreferences&,
const FetchParameters::ResourceWidth&,
ResourceRequest&) override;
- FetchContext* Detach() override;
WorkerSettings* GetWorkerSettings() const;
WorkerContentSettingsClient* GetWorkerContentSettingsClient() const;
@@ -111,7 +110,8 @@ class WorkerFetchContext final : public BaseFetchContext {
// WorkerGlobalScope and owned by this WorkerFetchContext.
const Member<ContentSecurityPolicy> content_security_policy_;
- CrossThreadPersistent<WorkerResourceTimingNotifier> resource_timing_notifier_;
+ const CrossThreadPersistent<WorkerResourceTimingNotifier>
+ resource_timing_notifier_;
// 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/loader/worker_resource_fetcher_properties.cc b/chromium/third_party/blink/renderer/core/loader/worker_resource_fetcher_properties.cc
index f413fcbdf33..ebdcbdf84f4 100644
--- a/chromium/third_party/blink/renderer/core/loader/worker_resource_fetcher_properties.cc
+++ b/chromium/third_party/blink/renderer/core/loader/worker_resource_fetcher_properties.cc
@@ -28,7 +28,7 @@ void WorkerResourceFetcherProperties::Trace(Visitor* visitor) {
mojom::ControllerServiceWorkerMode
WorkerResourceFetcherProperties::GetControllerServiceWorkerMode() const {
- return web_context_->IsControlledByServiceWorker();
+ return web_context_->GetControllerServiceWorkerMode();
}
bool WorkerResourceFetcherProperties::IsPaused() const {
diff --git a/chromium/third_party/blink/renderer/core/loader/worker_resource_timing_notifier_impl.cc b/chromium/third_party/blink/renderer/core/loader/worker_resource_timing_notifier_impl.cc
index aaa662c6199..af0ea8b8499 100644
--- a/chromium/third_party/blink/renderer/core/loader/worker_resource_timing_notifier_impl.cc
+++ b/chromium/third_party/blink/renderer/core/loader/worker_resource_timing_notifier_impl.cc
@@ -9,10 +9,10 @@
#include "third_party/blink/renderer/core/timing/dom_window_performance.h"
#include "third_party/blink/renderer/core/timing/performance.h"
#include "third_party/blink/renderer/core/timing/worker_global_scope_performance.h"
-#include "third_party/blink/renderer/platform/cross_thread_copier.h"
-#include "third_party/blink/renderer/platform/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_timing_info.h"
#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_copier.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
namespace blink {
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 f2ad6c0566a..4d0e8b74753 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
@@ -7,7 +7,6 @@
#include <utility>
#include "mojo/public/cpp/base/big_buffer.h"
#include "third_party/blink/public/mojom/blob/blob.mojom-blink.h"
-#include "third_party/blink/public/platform/web_string.h"
#include "third_party/blink/renderer/core/imagebitmap/image_bitmap.h"
#include "third_party/blink/renderer/platform/blob/blob_data.h"
@@ -61,10 +60,10 @@ BlinkTransferableMessage ToBlinkTransferableMessage(
message.encoded_message.size());
for (auto& blob : message.blobs) {
result.message->BlobDataHandles().Set(
- WebString::FromUTF8(blob->uuid),
+ String::FromUTF8(blob->uuid),
BlobDataHandle::Create(
- WebString::FromUTF8(blob->uuid),
- WebString::FromUTF8(blob->content_type), blob->size,
+ String::FromUTF8(blob->uuid), String::FromUTF8(blob->content_type),
+ blob->size,
mojom::blink::BlobPtrInfo(blob->blob.PassHandle(),
mojom::Blob::Version_)));
}
@@ -83,6 +82,7 @@ BlinkTransferableMessage ToBlinkTransferableMessage(
message.user_activation->was_active);
}
result.transfer_user_activation = message.transfer_user_activation;
+ result.allow_autoplay = message.allow_autoplay;
if (!message.array_buffer_contents_array.empty()) {
SerializedScriptValue::ArrayBufferContentsArray array_buffer_contents_array;
@@ -129,8 +129,8 @@ TransferableMessage ToTransferableMessage(BlinkTransferableMessage message) {
result.blobs.reserve(message.message->BlobDataHandles().size());
for (const auto& blob : message.message->BlobDataHandles()) {
result.blobs.push_back(mojom::SerializedBlob::New(
- WebString(blob.value->Uuid()).Utf8(),
- WebString(blob.value->GetType()).Utf8(), blob.value->size(),
+ blob.value->Uuid().Utf8(), blob.value->GetType().Utf8(),
+ blob.value->size(),
mojom::BlobPtrInfo(
blob.value->CloneBlobPtr().PassInterface().PassHandle(),
mojom::Blob::Version_)));
@@ -151,6 +151,7 @@ TransferableMessage ToTransferableMessage(BlinkTransferableMessage message) {
message.user_activation->was_active);
}
result.transfer_user_activation = message.transfer_user_activation;
+ result.allow_autoplay = message.allow_autoplay;
auto& array_buffer_contents_array =
message.message->GetArrayBufferContentsArray();
diff --git a/chromium/third_party/blink/renderer/core/messaging/blink_transferable_message.h b/chromium/third_party/blink/renderer/core/messaging/blink_transferable_message.h
index b1ca9705d90..ccf6185c3af 100644
--- a/chromium/third_party/blink/renderer/core/messaging/blink_transferable_message.h
+++ b/chromium/third_party/blink/renderer/core/messaging/blink_transferable_message.h
@@ -12,7 +12,7 @@
#include "third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/messaging/blink_cloneable_message.h"
-#include "third_party/blink/renderer/platform/cross_thread_copier.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_copier.h"
namespace blink {
@@ -34,6 +34,7 @@ struct CORE_EXPORT BlinkTransferableMessage : BlinkCloneableMessage {
mojom::blink::UserActivationSnapshotPtr user_activation;
bool transfer_user_activation = false;
+ bool allow_autoplay = false;
private:
DISALLOW_COPY_AND_ASSIGN(BlinkTransferableMessage);
@@ -53,15 +54,19 @@ CORE_EXPORT BlinkTransferableMessage
// longer.
CORE_EXPORT TransferableMessage ToTransferableMessage(BlinkTransferableMessage);
+} // namespace blink
+
+namespace WTF {
+
template <>
-struct CrossThreadCopier<BlinkTransferableMessage> {
+struct CrossThreadCopier<blink::BlinkTransferableMessage> {
STATIC_ONLY(CrossThreadCopier);
- using Type = BlinkTransferableMessage;
+ using Type = blink::BlinkTransferableMessage;
static Type Copy(Type pointer) {
return pointer; // This is in fact a move.
}
};
-} // namespace blink
+} // namespace WTF
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_MESSAGING_BLINK_TRANSFERABLE_MESSAGE_H_
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 180fe597084..343c797da23 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
@@ -52,6 +52,7 @@ bool StructTraits<blink::mojom::blink::TransferableMessage::DataView,
std::make_move_iterator(stream_channels.end()));
out->has_user_gesture = data.has_user_gesture();
out->transfer_user_activation = data.transfer_user_activation();
+ out->allow_autoplay = data.allow_autoplay();
out->message->SetArrayBufferContentsArray(
std::move(array_buffer_contents_array));
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 53ee100b685..9dcf78fa6fa 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
@@ -66,6 +66,10 @@ struct CORE_EXPORT
return input.transfer_user_activation;
}
+ static bool allow_autoplay(const blink::BlinkTransferableMessage& input) {
+ return input.allow_autoplay;
+ }
+
static bool Read(blink::mojom::blink::TransferableMessage::DataView,
blink::BlinkTransferableMessage* out);
};
diff --git a/chromium/third_party/blink/renderer/core/messaging/blink_transferable_message_struct_traits_test.cc b/chromium/third_party/blink/renderer/core/messaging/blink_transferable_message_struct_traits_test.cc
index 5864542788b..db72b27483e 100644
--- a/chromium/third_party/blink/renderer/core/messaging/blink_transferable_message_struct_traits_test.cc
+++ b/chromium/third_party/blink/renderer/core/messaging/blink_transferable_message_struct_traits_test.cc
@@ -68,11 +68,11 @@ TEST(BlinkTransferableMessageStructTraitsTest,
ASSERT_EQ(out.message->GetArrayBufferContentsArray().size(), 1U);
WTF::ArrayBufferContents& deserialized_contents =
out.message->GetArrayBufferContentsArray()[0];
- std::vector<uint8_t> deserialized_data(
- static_cast<uint8_t*>(deserialized_contents.Data()),
- static_cast<uint8_t*>(deserialized_contents.Data()) + 8);
+ Vector<uint8_t> deserialized_data;
+ deserialized_data.Append(static_cast<uint8_t*>(deserialized_contents.Data()),
+ 8);
ASSERT_EQ(deserialized_data.size(), 8U);
- for (uint8_t i = 0; i < deserialized_data.size(); i++) {
+ for (wtf_size_t i = 0; i < deserialized_data.size(); i++) {
ASSERT_TRUE(deserialized_data[i] == i);
}
}
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 20dbefdb983..fd635f6dd71 100644
--- a/chromium/third_party/blink/renderer/core/messaging/message_port.cc
+++ b/chromium/third_party/blink/renderer/core/messaging/message_port.cc
@@ -35,7 +35,6 @@
#include "third_party/blink/renderer/core/events/message_event.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/frame/user_activation.h"
#include "third_party/blink/renderer/core/inspector/thread_debugger.h"
#include "third_party/blink/renderer/core/messaging/blink_transferable_message_struct_traits.h"
@@ -43,7 +42,8 @@
#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/bindings/script_state.h"
-#include "third_party/blink/renderer/platform/cross_thread_functional.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/mojo/DEPS b/chromium/third_party/blink/renderer/core/mojo/DEPS
index a3ad46964e4..a3bebdc81a8 100644
--- a/chromium/third_party/blink/renderer/core/mojo/DEPS
+++ b/chromium/third_party/blink/renderer/core/mojo/DEPS
@@ -1,3 +1,5 @@
include_rules = [
- "+mojo/public/cpp/system",
+ "+base/numerics/safe_math.h",
+
+ "+mojo/public",
]
diff --git a/chromium/third_party/blink/renderer/core/mojo/mojo.cc b/chromium/third_party/blink/renderer/core/mojo/mojo.cc
index 4f0e56320fd..ecb71fb76ce 100644
--- a/chromium/third_party/blink/renderer/core/mojo/mojo.cc
+++ b/chromium/third_party/blink/renderer/core/mojo/mojo.cc
@@ -100,8 +100,7 @@ void Mojo::bindInterface(ScriptState* script_state,
const String& interface_name,
MojoHandle* request_handle,
const String& scope) {
- std::string name =
- StringUTF8Adaptor(interface_name).AsStringPiece().as_string();
+ std::string name = interface_name.Utf8();
auto handle =
mojo::ScopedMessagePipeHandle::From(request_handle->TakeHandle());
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 b74bf25779e..a2491fcdd63 100644
--- a/chromium/third_party/blink/renderer/core/mojo/mojo_handle.cc
+++ b/chromium/third_party/blink/renderer/core/mojo/mojo_handle.cc
@@ -4,6 +4,9 @@
#include "third_party/blink/renderer/core/mojo/mojo_handle.h"
+#include "base/numerics/safe_math.h"
+#include "mojo/public/c/system/message_pipe.h"
+#include "mojo/public/cpp/bindings/message.h"
#include "mojo/public/cpp/system/message_pipe.h"
#include "third_party/blink/renderer/bindings/core/v8/array_buffer_or_array_buffer_view.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
@@ -50,11 +53,17 @@ MojoWatcher* MojoHandle::watch(ScriptState* script_state,
MojoResult MojoHandle::writeMessage(
ArrayBufferOrArrayBufferView& buffer,
const HeapVector<Member<MojoHandle>>& handles) {
- // mojo::WriteMessageRaw takes ownership of the handles, so release them here.
- Vector<::MojoHandle, kHandleVectorInlineCapacity> raw_handles(handles.size());
- std::transform(
- handles.begin(), handles.end(), raw_handles.begin(),
- [](MojoHandle* handle) { return handle->handle_.release().value(); });
+ Vector<mojo::ScopedHandle, kHandleVectorInlineCapacity> scoped_handles;
+ scoped_handles.ReserveCapacity(handles.size());
+ bool has_invalid_handles = false;
+ for (auto& handle : handles) {
+ if (!handle->handle_.is_valid())
+ has_invalid_handles = true;
+ else
+ scoped_handles.emplace_back(std::move(handle->handle_));
+ }
+ if (has_invalid_handles)
+ return MOJO_RESULT_INVALID_ARGUMENT;
const void* bytes = nullptr;
size_t num_bytes = 0;
@@ -68,9 +77,13 @@ MojoResult MojoHandle::writeMessage(
num_bytes = view->byteLength();
}
- return mojo::WriteMessageRaw(
- mojo::MessagePipeHandle(handle_.get().value()), bytes, num_bytes,
- raw_handles.data(), raw_handles.size(), MOJO_WRITE_MESSAGE_FLAG_NONE);
+ auto message = mojo::Message(
+ base::make_span(static_cast<const uint8_t*>(bytes), num_bytes),
+ base::make_span(scoped_handles));
+ DCHECK(!message.IsNull());
+ return mojo::WriteMessageNew(mojo::MessagePipeHandle(handle_.get().value()),
+ message.TakeMojoMessage(),
+ MOJO_WRITE_MESSAGE_FLAG_NONE);
}
MojoReadMessageResult* MojoHandle::readMessage(
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 a5ab3f8660a..d4e0652b39d 100644
--- a/chromium/third_party/blink/renderer/core/mojo/mojo_watcher.cc
+++ b/chromium/third_party/blink/renderer/core/mojo/mojo_watcher.cc
@@ -9,8 +9,8 @@
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#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/scheduler/public/post_cross_thread_task.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
namespace blink {
@@ -25,17 +25,15 @@ MojoWatcher* MojoWatcher::Create(mojo::Handle handle,
// Current clients expect to recieve the initial error returned by MojoWatch
// via watch callback.
//
- // Note that the usage of wrapPersistent is intentional so that the intial
+ // Note that the usage of WrapPersistent is intentional so that the initial
// error is guaranteed to be reported to the client in case where the given
// handle is invalid and garbage collection happens before the callback
// is scheduled.
if (result != MOJO_RESULT_OK) {
watcher->task_runner_->PostTask(
FROM_HERE,
- WTF::Bind(&V8PersistentCallbackFunction<
- V8MojoWatchCallback>::InvokeAndReportException,
- WrapPersistent(ToV8PersistentCallbackFunction(callback)),
- WrapPersistent(watcher), result));
+ WTF::Bind(&V8MojoWatchCallback::InvokeAndReportException,
+ WrapPersistent(callback), WrapPersistent(watcher), result));
}
return watcher;
}
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 05ed60bccad..d3868722230 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
@@ -55,8 +55,7 @@ void MojoInterfaceInterceptor::start(ExceptionState& exception_state) {
return;
}
- std::string interface_name =
- StringUTF8Adaptor(interface_name_).AsStringPiece().as_string();
+ std::string interface_name = interface_name_.Utf8();
if (process_scope_) {
service_manager::Connector* connector = Platform::Current()->GetConnector();
@@ -100,8 +99,7 @@ void MojoInterfaceInterceptor::stop() {
return;
started_ = false;
- std::string interface_name =
- StringUTF8Adaptor(interface_name_).AsStringPiece().as_string();
+ std::string interface_name = interface_name_.Utf8();
if (process_scope_) {
auto filter = service_manager::ServiceFilter::ByName(
diff --git a/chromium/third_party/blink/renderer/core/offscreencanvas/OWNERS b/chromium/third_party/blink/renderer/core/offscreencanvas/OWNERS
index ffa62011cfd..5ef87b1aa3f 100644
--- a/chromium/third_party/blink/renderer/core/offscreencanvas/OWNERS
+++ b/chromium/third_party/blink/renderer/core/offscreencanvas/OWNERS
@@ -1,5 +1,4 @@
fserb@chromium.org
-xidachen@chromium.org
# TEAM: paint-dev@chromium.org
# COMPONENT: Blink>Canvas
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 eda7b801dfe..29f889eb76a 100644
--- a/chromium/third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.cc
+++ b/chromium/third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.cc
@@ -26,15 +26,18 @@
#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/histogram.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
#include "third_party/skia/include/core/SkSurface.h"
namespace blink {
-OffscreenCanvas::OffscreenCanvas(const IntSize& size) : size_(size) {
+OffscreenCanvas::OffscreenCanvas(const IntSize& size)
+ : CanvasRenderingContextHost(
+ CanvasRenderingContextHost::HostType::kOffscreenCanvasHost),
+ size_(size) {
UpdateMemoryUsage();
}
@@ -53,10 +56,9 @@ void OffscreenCanvas::Commit(scoped_refptr<CanvasResource> canvas_resource,
const SkIRect& damage_rect) {
if (!HasPlaceholderCanvas() || !canvas_resource)
return;
- RecordCanvasSizeToUMA(
- Size(), CanvasRenderingContextHost::HostType::kOffscreenCanvasHost);
+ RecordCanvasSizeToUMA(Size());
- base::TimeTicks commit_start_time = WTF::CurrentTimeTicks();
+ base::TimeTicks commit_start_time = base::TimeTicks::Now();
current_frame_damage_rect_.join(damage_rect);
GetOrCreateResourceDispatcher()->DispatchFrameSync(
std::move(canvas_resource), commit_start_time, current_frame_damage_rect_,
@@ -325,22 +327,27 @@ CanvasResourceProvider* OffscreenCanvas::GetOrCreateResourceProvider() {
IntSize surface_size(width(), height());
CanvasResourceProvider::ResourceUsage usage;
if (can_use_gpu) {
- if (HasPlaceholderCanvas())
- usage = CanvasResourceProvider::kAcceleratedCompositedResourceUsage;
- else
- usage = CanvasResourceProvider::kAcceleratedResourceUsage;
+ if (HasPlaceholderCanvas()) {
+ usage = CanvasResourceProvider::ResourceUsage::
+ kAcceleratedCompositedResourceUsage;
+ } else {
+ usage =
+ CanvasResourceProvider::ResourceUsage::kAcceleratedResourceUsage;
+ }
} else {
- if (HasPlaceholderCanvas())
- usage = CanvasResourceProvider::kSoftwareCompositedResourceUsage;
- else
- usage = CanvasResourceProvider::kSoftwareResourceUsage;
+ if (HasPlaceholderCanvas()) {
+ usage = CanvasResourceProvider::ResourceUsage::
+ kSoftwareCompositedResourceUsage;
+ } else {
+ usage = CanvasResourceProvider::ResourceUsage::kSoftwareResourceUsage;
+ }
}
base::WeakPtr<CanvasResourceDispatcher> dispatcher_weakptr =
HasPlaceholderCanvas() ? GetOrCreateResourceDispatcher()->GetWeakPtr()
: nullptr;
- ReplaceResourceProvider(CanvasResourceProvider::Create(
+ ReplaceResourceProvider(CanvasResourceProvider::CreateForCanvas(
surface_size, usage, SharedGpuContext::ContextProviderWrapper(), 0,
context_->ColorParams(), presentation_mode,
std::move(dispatcher_weakptr), false /* is_origin_top_left */));
@@ -411,7 +418,7 @@ void OffscreenCanvas::PushFrame(scoped_refptr<CanvasResource> canvas_resource,
current_frame_damage_rect_.join(damage_rect);
if (current_frame_damage_rect_.isEmpty() || !canvas_resource)
return;
- const base::TimeTicks commit_start_time = WTF::CurrentTimeTicks();
+ const base::TimeTicks commit_start_time = base::TimeTicks::Now();
GetOrCreateResourceDispatcher()->DispatchFrame(
std::move(canvas_resource), commit_start_time, current_frame_damage_rect_,
!RenderingContext()->IsOriginTopLeft() /* needs_vertical_flip */,
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 f1165def76e..6811af6b449 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
@@ -19,7 +19,7 @@
#include "third_party/blink/renderer/core/origin_trials/origin_trials.h"
#include "third_party/blink/renderer/core/workers/worklet_global_scope.h"
#include "third_party/blink/renderer/platform/bindings/origin_trial_features.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.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/text/string_builder.h"
@@ -94,34 +94,17 @@ bool IsCrossNavigationFeature(OriginTrialFeature feature) {
} // namespace
+OriginTrialContext::OriginTrialContext()
+ : OriginTrialContext(TrialTokenValidator::Policy()
+ ? std::make_unique<TrialTokenValidator>()
+ : nullptr) {}
+
OriginTrialContext::OriginTrialContext(
- ExecutionContext& context,
std::unique_ptr<TrialTokenValidator> validator)
- : Supplement<ExecutionContext>(context),
- trial_token_validator_(std::move(validator)) {}
-
-// static
-const char OriginTrialContext::kSupplementName[] = "OriginTrialContext";
-
-// static
-const OriginTrialContext* OriginTrialContext::From(
- const ExecutionContext* context) {
- return Supplement<ExecutionContext>::From<OriginTrialContext>(context);
-}
+ : trial_token_validator_(std::move(validator)) {}
-// static
-OriginTrialContext* OriginTrialContext::FromOrCreate(
- ExecutionContext* context) {
- OriginTrialContext* origin_trials =
- Supplement<ExecutionContext>::From<OriginTrialContext>(context);
- if (!origin_trials) {
- origin_trials = MakeGarbageCollected<OriginTrialContext>(
- *context, TrialTokenValidator::Policy()
- ? std::make_unique<TrialTokenValidator>()
- : nullptr);
- Supplement<ExecutionContext>::ProvideTo(*context, origin_trials);
- }
- return origin_trials;
+void OriginTrialContext::BindExecutionContext(ExecutionContext* context) {
+ context_ = context;
}
// static
@@ -157,7 +140,8 @@ void OriginTrialContext::AddTokens(ExecutionContext* context,
const Vector<String>* tokens) {
if (!tokens || tokens->IsEmpty())
return;
- FromOrCreate(context)->AddTokens(*tokens);
+ DCHECK(context && context->GetOriginTrialContext());
+ context->GetOriginTrialContext()->AddTokens(*tokens);
}
// static
@@ -166,13 +150,17 @@ void OriginTrialContext::ActivateNavigationFeaturesFromInitiator(
const Vector<OriginTrialFeature>* features) {
if (!features || features->IsEmpty())
return;
- FromOrCreate(context)->ActivateNavigationFeaturesFromInitiator(*features);
+ DCHECK(context && context->GetOriginTrialContext());
+ context->GetOriginTrialContext()->ActivateNavigationFeaturesFromInitiator(
+ *features);
}
// static
std::unique_ptr<Vector<String>> OriginTrialContext::GetTokens(
ExecutionContext* execution_context) {
- const OriginTrialContext* context = From(execution_context);
+ DCHECK(execution_context);
+ const OriginTrialContext* context =
+ execution_context->GetOriginTrialContext();
if (!context || context->tokens_.IsEmpty())
return nullptr;
return std::make_unique<Vector<String>>(context->tokens_);
@@ -182,7 +170,9 @@ std::unique_ptr<Vector<String>> OriginTrialContext::GetTokens(
std::unique_ptr<Vector<OriginTrialFeature>>
OriginTrialContext::GetEnabledNavigationFeatures(
ExecutionContext* execution_context) {
- const OriginTrialContext* context = From(execution_context);
+ DCHECK(execution_context);
+ const OriginTrialContext* context =
+ execution_context->GetOriginTrialContext();
return context ? context->GetEnabledNavigationFeatures() : nullptr;
}
@@ -204,7 +194,7 @@ void OriginTrialContext::AddToken(const String& token) {
if (token.IsEmpty())
return;
tokens_.push_back(token);
- if (EnableTrialFromToken(token)) {
+ if (EnableTrialFromToken(GetSecurityOrigin(), IsSecureContext(), token)) {
// Only install pending features if the provided token is valid. Otherwise,
// there was no change to the list of enabled features.
InitializePendingFeatures();
@@ -212,13 +202,19 @@ void OriginTrialContext::AddToken(const String& token) {
}
void OriginTrialContext::AddTokens(const Vector<String>& tokens) {
+ AddTokens(GetSecurityOrigin(), IsSecureContext(), tokens);
+}
+
+void OriginTrialContext::AddTokens(const SecurityOrigin* origin,
+ bool is_secure,
+ const Vector<String>& tokens) {
if (tokens.IsEmpty())
return;
bool found_valid = false;
for (const String& token : tokens) {
if (!token.IsEmpty()) {
tokens_.push_back(token);
- if (EnableTrialFromToken(token))
+ if (EnableTrialFromToken(origin, is_secure, token))
found_valid = true;
}
}
@@ -242,7 +238,7 @@ void OriginTrialContext::ActivateNavigationFeaturesFromInitiator(
void OriginTrialContext::InitializePendingFeatures() {
if (!enabled_features_.size() && !navigation_activated_features_.size())
return;
- auto* document = DynamicTo<Document>(GetSupplementable());
+ auto* document = DynamicTo<Document>(context_.Get());
if (!document)
return;
LocalFrame* frame = document->GetFrame();
@@ -290,12 +286,12 @@ bool OriginTrialContext::IsFeatureEnabled(OriginTrialFeature feature) const {
// For the purposes of origin trials, we consider imported documents to be
// part of the master document. Thus, check if the trial is enabled in the
// master document and use that result.
- auto* document = DynamicTo<Document>(GetSupplementable());
+ auto* document = DynamicTo<Document>(context_.Get());
if (!document || !document->IsHTMLImport())
return false;
const OriginTrialContext* context =
- OriginTrialContext::From(&document->MasterDocument());
+ document->MasterDocument().GetOriginTrialContext();
if (!context)
return false;
return context->IsFeatureEnabled(feature);
@@ -309,7 +305,9 @@ bool OriginTrialContext::IsNavigationFeatureActivated(
return navigation_activated_features_.Contains(feature);
}
-bool OriginTrialContext::EnableTrialFromToken(const String& token) {
+bool OriginTrialContext::EnableTrialFromToken(const SecurityOrigin* origin,
+ bool is_secure,
+ const String& token) {
DCHECK(!token.IsEmpty());
// Origin trials are only enabled for secure origins
@@ -319,13 +317,6 @@ bool OriginTrialContext::EnableTrialFromToken(const String& token) {
// - For the purpose of origin trials, we consider worklets as running in the
// same context as the originating document. Thus, the special logic here
// to validate the token against the document context.
- bool is_secure = false;
- ExecutionContext* context = GetSupplementable();
- if (auto* scope = DynamicTo<WorkletGlobalScope>(context)) {
- is_secure = scope->DocumentSecureContext();
- } else {
- is_secure = context->IsSecureContext();
- }
if (!is_secure) {
TokenValidationResultHistogram().Count(
static_cast<int>(OriginTrialTokenStatus::kInsecure));
@@ -338,12 +329,6 @@ bool OriginTrialContext::EnableTrialFromToken(const String& token) {
return false;
}
- const SecurityOrigin* origin;
- if (auto* scope = DynamicTo<WorkletGlobalScope>(context))
- origin = scope->DocumentSecurityOrigin();
- else
- origin = context->GetSecurityOrigin();
-
bool valid = false;
StringUTF8Adaptor token_string(token);
std::string trial_name_str;
@@ -374,7 +359,28 @@ bool OriginTrialContext::EnableTrialFromToken(const String& token) {
}
void OriginTrialContext::Trace(blink::Visitor* visitor) {
- Supplement<ExecutionContext>::Trace(visitor);
+ visitor->Trace(context_);
+}
+
+const SecurityOrigin* OriginTrialContext::GetSecurityOrigin() {
+ const SecurityOrigin* origin;
+ CHECK(context_);
+ if (auto* scope = DynamicTo<WorkletGlobalScope>(context_.Get()))
+ origin = scope->DocumentSecurityOrigin();
+ else
+ origin = context_->GetSecurityOrigin();
+ return origin;
+}
+
+bool OriginTrialContext::IsSecureContext() {
+ bool is_secure = false;
+ CHECK(context_);
+ if (auto* scope = DynamicTo<WorkletGlobalScope>(context_.Get())) {
+ is_secure = scope->DocumentSecureContext();
+ } else {
+ is_secure = context_->IsSecureContext();
+ }
+ return is_secure;
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/origin_trials/origin_trial_context.h b/chromium/third_party/blink/renderer/core/origin_trials/origin_trial_context.h
index 9a6b2b39f09..acf07bca187 100644
--- a/chromium/third_party/blink/renderer/core/origin_trials/origin_trial_context.h
+++ b/chromium/third_party/blink/renderer/core/origin_trials/origin_trial_context.h
@@ -9,7 +9,6 @@
#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/core/origin_trials/origin_trials.h"
-#include "third_party/blink/renderer/platform/supplementable.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/blink/renderer/platform/wtf/text/wtf_string.h"
@@ -34,22 +33,12 @@ class ExecutionContext;
//
// For more information, see https://github.com/jpchase/OriginTrials.
class CORE_EXPORT OriginTrialContext final
- : public GarbageCollectedFinalized<OriginTrialContext>,
- public Supplement<ExecutionContext> {
- USING_GARBAGE_COLLECTED_MIXIN(OriginTrialContext);
-
+ : public GarbageCollectedFinalized<OriginTrialContext> {
public:
- static const char kSupplementName[];
-
- OriginTrialContext(ExecutionContext&, std::unique_ptr<TrialTokenValidator>);
+ OriginTrialContext();
+ explicit OriginTrialContext(std::unique_ptr<TrialTokenValidator> validator);
- // Returns the OriginTrialContext for a specific ExecutionContext, if one
- // exists.
- static const OriginTrialContext* From(const ExecutionContext*);
-
- // Returns the OriginTrialContext for a specific ExecutionContext, creating
- // one if one does not already exist.
- static OriginTrialContext* FromOrCreate(ExecutionContext*);
+ void BindExecutionContext(ExecutionContext*);
// Parses an Origin-Trial header as specified in
// https://jpchase.github.io/OriginTrials/#header into individual tokens.
@@ -84,6 +73,9 @@ class CORE_EXPORT OriginTrialContext final
void AddToken(const String& token);
void AddTokens(const Vector<String>& tokens);
+ void AddTokens(const SecurityOrigin* origin,
+ bool is_secure,
+ const Vector<String>& tokens);
void ActivateNavigationFeaturesFromInitiator(
const Vector<OriginTrialFeature>& features);
@@ -117,23 +109,29 @@ class CORE_EXPORT OriginTrialContext final
// enabled.
void InitializePendingFeatures();
- void Trace(blink::Visitor*) override;
+ void Trace(blink::Visitor*);
private:
// Validate the trial token. If valid, the trial named in the token is
// added to the list of enabled trials. Returns true or false to indicate if
// the token is valid.
- bool EnableTrialFromToken(const String& token);
+ bool EnableTrialFromToken(const SecurityOrigin* origin,
+ bool is_secure,
+ const String& token);
// Installs JavaScript bindings on the relevant objects for the specified
// OriginTrialFeature.
void InstallFeature(OriginTrialFeature, ScriptState*);
+ const SecurityOrigin* GetSecurityOrigin();
+ bool IsSecureContext();
+
Vector<String> tokens_;
HashSet<OriginTrialFeature> enabled_features_;
HashSet<OriginTrialFeature> installed_features_;
HashSet<OriginTrialFeature> navigation_activated_features_;
std::unique_ptr<TrialTokenValidator> trial_token_validator_;
+ Member<ExecutionContext> context_;
};
} // namespace blink
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 28cee35ebb6..d7583262635 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
@@ -76,11 +76,10 @@ class OriginTrialContextTest : public testing::Test,
protected:
OriginTrialContextTest()
: ScopedOriginTrialsForTest(true),
- execution_context_(MakeGarbageCollected<NullExecutionContext>()),
token_validator_(new MockTokenValidator),
- origin_trial_context_(MakeGarbageCollected<OriginTrialContext>(
- *execution_context_,
- std::unique_ptr<MockTokenValidator>(token_validator_))),
+ execution_context_(MakeGarbageCollected<NullExecutionContext>(
+ MakeGarbageCollected<OriginTrialContext>(
+ std::unique_ptr<MockTokenValidator>(token_validator_)))),
histogram_tester_(new HistogramTester()) {}
MockTokenValidator* TokenValidator() { return token_validator_; }
@@ -96,17 +95,21 @@ class OriginTrialContextTest : public testing::Test,
bool IsFeatureEnabled(const String& origin, OriginTrialFeature feature) {
UpdateSecurityOrigin(origin);
// Need at least one token to ensure the token validator is called.
- origin_trial_context_->AddToken(kTokenPlaceholder);
- return origin_trial_context_->IsFeatureEnabled(feature);
+ execution_context_->GetOriginTrialContext()->AddToken(kTokenPlaceholder);
+ return execution_context_->GetOriginTrialContext()->IsFeatureEnabled(
+ feature);
}
std::unique_ptr<Vector<OriginTrialFeature>> GetEnabledNavigationFeatures() {
- return origin_trial_context_->GetEnabledNavigationFeatures();
+ return execution_context_->GetOriginTrialContext()
+ ->GetEnabledNavigationFeatures();
}
bool ActivateNavigationFeature(OriginTrialFeature feature) {
- origin_trial_context_->ActivateNavigationFeaturesFromInitiator({feature});
- return origin_trial_context_->IsNavigationFeatureActivated(feature);
+ execution_context_->GetOriginTrialContext()
+ ->ActivateNavigationFeaturesFromInitiator({feature});
+ return execution_context_->GetOriginTrialContext()
+ ->IsNavigationFeatureActivated(feature);
}
void ExpectStatusUniqueMetric(OriginTrialTokenStatus status, int count) {
@@ -119,9 +122,8 @@ class OriginTrialContextTest : public testing::Test,
}
private:
- Persistent<NullExecutionContext> execution_context_;
MockTokenValidator* token_validator_;
- Persistent<OriginTrialContext> origin_trial_context_;
+ Persistent<NullExecutionContext> execution_context_;
std::unique_ptr<HistogramTester> histogram_tester_;
};
@@ -242,7 +244,7 @@ TEST_F(OriginTrialContextTest, FeaturePolicy) {
// Create a dummy document with an OriginTrialContext.
auto dummy = std::make_unique<DummyPageHolder>();
Document* document = &dummy->GetDocument();
- OriginTrialContext* context = OriginTrialContext::FromOrCreate(document);
+ OriginTrialContext* context = document->GetOriginTrialContext();
// Enable the sample origin trial API ("Frobulate").
context->AddFeature(OriginTrialFeature::kOriginTrialsSampleAPI);
diff --git a/chromium/third_party/blink/renderer/core/page/autoscroll_controller.cc b/chromium/third_party/blink/renderer/core/page/autoscroll_controller.cc
index 9e59ff8029a..efb54520168 100644
--- a/chromium/third_party/blink/renderer/core/page/autoscroll_controller.cc
+++ b/chromium/third_party/blink/renderer/core/page/autoscroll_controller.cc
@@ -44,11 +44,13 @@ namespace blink {
// Delay time in second for start autoscroll if pointer is in border edge of
// scrollable element.
-constexpr TimeDelta kAutoscrollDelay = TimeDelta::FromSecondsD(0.2);
+constexpr base::TimeDelta kAutoscrollDelay = base::TimeDelta::FromSecondsD(0.2);
static const int kNoMiddleClickAutoscrollRadius = 15;
-static const Cursor& MiddleClickAutoscrollCursor(const FloatSize& velocity) {
+static const Cursor& MiddleClickAutoscrollCursor(const FloatSize& velocity,
+ bool scroll_vert,
+ bool scroll_horiz) {
// At the original click location we draw a 4 arrowed icon. Over this icon
// there won't be any scroll, So don't change the cursor over this area.
bool east = velocity.Width() < 0;
@@ -56,24 +58,32 @@ static const Cursor& MiddleClickAutoscrollCursor(const FloatSize& velocity) {
bool north = velocity.Height() > 0;
bool south = velocity.Height() < 0;
- if (north) {
- if (east)
- return NorthEastPanningCursor();
- if (west)
- return NorthWestPanningCursor();
+ if (north && scroll_vert) {
+ if (scroll_horiz) {
+ if (east)
+ return NorthEastPanningCursor();
+ if (west)
+ return NorthWestPanningCursor();
+ }
return NorthPanningCursor();
}
- if (south) {
- if (east)
- return SouthEastPanningCursor();
- if (west)
- return SouthWestPanningCursor();
+ if (south && scroll_vert) {
+ if (scroll_horiz) {
+ if (east)
+ return SouthEastPanningCursor();
+ if (west)
+ return SouthWestPanningCursor();
+ }
return SouthPanningCursor();
}
- if (east)
+ if (east && scroll_horiz)
return EastPanningCursor();
- if (west)
+ if (west && scroll_horiz)
return WestPanningCursor();
+ if (scroll_vert && !scroll_horiz)
+ return MiddlePanningVerticalCursor();
+ if (scroll_horiz && !scroll_vert)
+ return MiddlePanningHorizontalCursor();
return MiddlePanningCursor();
}
@@ -156,7 +166,7 @@ void AutoscrollController::UpdateAutoscrollLayoutObject() {
void AutoscrollController::UpdateDragAndDrop(Node* drop_target_node,
const FloatPoint& event_position,
- TimeTicks event_time) {
+ base::TimeTicks event_time) {
if (!drop_target_node || !drop_target_node->GetLayoutObject()) {
StopAutoscroll();
return;
@@ -185,15 +195,15 @@ void AutoscrollController::UpdateDragAndDrop(Node* drop_target_node,
return;
}
- LayoutSize offset =
- scrollable->CalculateAutoscrollDirection(event_position).ToLayoutSize();
+ PhysicalOffset offset =
+ scrollable->CalculateAutoscrollDirection(event_position);
if (offset.IsZero()) {
StopAutoscroll();
return;
}
drag_and_drop_autoscroll_reference_position_ =
- LayoutPoint(event_position) + offset;
+ PhysicalOffset::FromFloatPointRound(event_position) + offset;
if (autoscroll_type_ == kNoAutoscroll) {
autoscroll_type_ = kAutoscrollForDragAndDrop;
@@ -241,7 +251,8 @@ void AutoscrollController::HandleMouseMoveForMiddleClickAutoscroll(
if (middle_click_mode_ == kMiddleClickInitial)
middle_click_mode_ = kMiddleClickHolding;
page_->GetChromeClient().SetCursorOverridden(false);
- view->SetCursor(MiddleClickAutoscrollCursor(velocity));
+ view->SetCursor(MiddleClickAutoscrollCursor(
+ velocity, can_scroll_vertically_, can_scroll_horizontally_));
page_->GetChromeClient().SetCursorOverridden(true);
page_->GetChromeClient().AutoscrollFling(velocity, frame);
}
@@ -280,7 +291,9 @@ bool AutoscrollController::MiddleClickAutoscrollInProgress() const {
void AutoscrollController::StartMiddleClickAutoscroll(
LocalFrame* frame,
const FloatPoint& position,
- const FloatPoint& position_global) {
+ const FloatPoint& position_global,
+ bool scroll_vert,
+ bool scroll_horiz) {
DCHECK(RuntimeEnabledFeatures::MiddleClickAutoscrollEnabled());
// We don't want to trigger the autoscroll or the middleClickAutoscroll if
// it's already active.
@@ -290,14 +303,18 @@ void AutoscrollController::StartMiddleClickAutoscroll(
autoscroll_type_ = kAutoscrollForMiddleClick;
middle_click_mode_ = kMiddleClickInitial;
middle_click_autoscroll_start_pos_global_ = position_global;
+ can_scroll_vertically_ = scroll_vert;
+ can_scroll_horizontally_ = scroll_horiz;
UseCounter::Count(frame->GetDocument(),
WebFeature::kMiddleClickAutoscrollStart);
last_velocity_ = FloatSize();
- if (LocalFrameView* view = frame->View())
- view->SetCursor(MiddleClickAutoscrollCursor(last_velocity_));
+ if (LocalFrameView* view = frame->View()) {
+ view->SetCursor(MiddleClickAutoscrollCursor(
+ last_velocity_, can_scroll_vertically_, can_scroll_horizontally_));
+ }
page_->GetChromeClient().SetCursorOverridden(true);
page_->GetChromeClient().AutoscrollStart(
position.ScaledBy(1 / frame->DevicePixelRatio()), frame);
@@ -315,16 +332,17 @@ void AutoscrollController::Animate() {
EventHandler& event_handler =
autoscroll_layout_object_->GetFrame()->GetEventHandler();
- LayoutSize offset = autoscroll_layout_object_
- ->CalculateAutoscrollDirection(
- event_handler.LastKnownMousePositionInRootFrame())
- .ToLayoutSize();
- LayoutPoint selection_point =
- LayoutPoint(event_handler.LastKnownMousePositionInRootFrame()) + offset;
+ PhysicalOffset offset =
+ autoscroll_layout_object_->CalculateAutoscrollDirection(
+ event_handler.LastKnownMousePositionInRootFrame());
+ PhysicalOffset selection_point =
+ PhysicalOffset::FromFloatPointRound(
+ event_handler.LastKnownMousePositionInRootFrame()) +
+ offset;
switch (autoscroll_type_) {
case kAutoscrollForDragAndDrop:
ScheduleMainThreadAnimation();
- if ((CurrentTimeTicks() - drag_and_drop_autoscroll_start_time_) >
+ if ((base::TimeTicks::Now() - drag_and_drop_autoscroll_start_time_) >
kAutoscrollDelay)
autoscroll_layout_object_->Autoscroll(
drag_and_drop_autoscroll_reference_position_);
diff --git a/chromium/third_party/blink/renderer/core/page/autoscroll_controller.h b/chromium/third_party/blink/renderer/core/page/autoscroll_controller.h
index 3cf3249af6f..9264fd195f6 100644
--- a/chromium/third_party/blink/renderer/core/page/autoscroll_controller.h
+++ b/chromium/third_party/blink/renderer/core/page/autoscroll_controller.h
@@ -28,9 +28,9 @@
#include "base/gtest_prod_util.h"
#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/layout/geometry/physical_offset.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/geometry/layout_point.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
@@ -81,12 +81,14 @@ class CORE_EXPORT AutoscrollController final
void UpdateAutoscrollLayoutObject();
void UpdateDragAndDrop(Node* target_node,
const FloatPoint& event_position,
- TimeTicks event_time);
+ base::TimeTicks event_time);
// Middle-click autoscroll.
void StartMiddleClickAutoscroll(LocalFrame*,
const FloatPoint& position,
- const FloatPoint& position_global);
+ const FloatPoint& position_global,
+ bool scroll_vert,
+ bool scroll_horiz);
void HandleMouseMoveForMiddleClickAutoscroll(
LocalFrame*,
const FloatPoint& position_global,
@@ -107,13 +109,15 @@ class CORE_EXPORT AutoscrollController final
void ScheduleMainThreadAnimation();
LayoutBox* autoscroll_layout_object_ = nullptr;
LayoutBox* pressed_layout_object_ = nullptr;
- LayoutPoint drag_and_drop_autoscroll_reference_position_;
- TimeTicks drag_and_drop_autoscroll_start_time_;
+ PhysicalOffset drag_and_drop_autoscroll_reference_position_;
+ base::TimeTicks drag_and_drop_autoscroll_start_time_;
// Middle-click autoscroll.
FloatPoint middle_click_autoscroll_start_pos_global_;
FloatSize last_velocity_;
MiddleClickMode middle_click_mode_ = kMiddleClickInitial;
+ bool can_scroll_vertically_ = false;
+ bool can_scroll_horizontally_ = false;
FRIEND_TEST_ALL_PREFIXES(AutoscrollControllerTest,
CrashWhenLayoutStopAnimationBeforeScheduleAnimation);
diff --git a/chromium/third_party/blink/renderer/core/page/autoscroll_controller_test.cc b/chromium/third_party/blink/renderer/core/page/autoscroll_controller_test.cc
index a55cd6ae324..bf08c825f41 100644
--- a/chromium/third_party/blink/renderer/core/page/autoscroll_controller_test.cc
+++ b/chromium/third_party/blink/renderer/core/page/autoscroll_controller_test.cc
@@ -59,7 +59,7 @@ TEST_F(AutoscrollControllerTest,
WebMouseEvent event(WebInputEvent::kMouseDown, WebFloatPoint(5, 5),
WebFloatPoint(5, 5), WebPointerProperties::Button::kLeft,
0, WebInputEvent::Modifiers::kLeftButtonDown,
- CurrentTimeTicks());
+ base::TimeTicks::Now());
event.SetFrameScale(1);
GetDocument().GetFrame()->GetEventHandler().HandleMousePressEvent(event);
@@ -85,13 +85,14 @@ TEST_F(AutoscrollControllerTest, ContinueAutoscrollAfterMouseLeaveEvent) {
EXPECT_FALSE(controller.IsAutoscrolling());
- controller.StartMiddleClickAutoscroll(frame, FloatPoint(), FloatPoint());
+ controller.StartMiddleClickAutoscroll(frame, FloatPoint(), FloatPoint(),
+ false, false);
EXPECT_TRUE(controller.IsAutoscrolling());
WebMouseEvent mouse_leave_event(WebInputEvent::kMouseLeave,
WebInputEvent::kNoModifiers,
- CurrentTimeTicks());
+ base::TimeTicks::Now());
mouse_leave_event.SetFrameScale(1);
frame->GetEventHandler().HandleMouseLeaveEvent(mouse_leave_event);
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 54f2a8f45ae..9e63a309a4b 100644
--- a/chromium/third_party/blink/renderer/core/page/chrome_client.cc
+++ b/chromium/third_party/blink/renderer/core/page/chrome_client.cc
@@ -214,17 +214,15 @@ void ChromeClient::SetToolTip(LocalFrame& frame,
// Lastly, some elements provide default tooltip strings. e.g. <input
// type="file" multiple> shows a tooltip for the selected filenames.
if (tool_tip.IsNull()) {
- if (Node* node = result.InnerNode()) {
- if (node->IsElementNode()) {
- tool_tip = ToElement(node)->DefaultToolTip();
+ if (auto* element = DynamicTo<Element>(result.InnerNode())) {
+ tool_tip = element->DefaultToolTip();
- // FIXME: We should obtain text direction of tooltip from
- // ChromeClient or platform. As of October 2011, all client
- // implementations don't use text direction information for
- // ChromeClient::setToolTip. We'll work on tooltip text
- // direction during bidi cleanup in form inputs.
- tool_tip_direction = TextDirection::kLtr;
- }
+ // FIXME: We should obtain text direction of tooltip from
+ // ChromeClient or platform. As of October 2011, all client
+ // implementations don't use text direction information for
+ // ChromeClient::setToolTip. We'll work on tooltip text
+ // direction during bidi cleanup in form inputs.
+ tool_tip_direction = TextDirection::kLtr;
}
}
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 8fee97444f0..f1a2e57b137 100644
--- a/chromium/third_party/blink/renderer/core/page/chrome_client.h
+++ b/chromium/third_party/blink/renderer/core/page/chrome_client.h
@@ -32,7 +32,7 @@
#include "cc/trees/paint_holding_commit_trigger.h"
#include "third_party/blink/public/common/dom_storage/session_storage_namespace_id.h"
#include "third_party/blink/public/common/feature_policy/feature_policy.h"
-#include "third_party/blink/public/mojom/devtools/console_message.mojom-shared.h"
+#include "third_party/blink/public/mojom/devtools/console_message.mojom-blink.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"
@@ -42,6 +42,7 @@
#include "third_party/blink/renderer/core/frame/sandbox_flags.h"
#include "third_party/blink/renderer/core/html/forms/external_date_time_chooser.h"
#include "third_party/blink/renderer/core/html/forms/popup_menu.h"
+#include "third_party/blink/renderer/core/layout/geometry/physical_offset.h"
#include "third_party/blink/renderer/core/loader/frame_loader.h"
#include "third_party/blink/renderer/core/loader/navigation_policy.h"
#include "third_party/blink/renderer/core/scroll/scroll_types.h"
@@ -96,6 +97,7 @@ class WebViewImpl;
struct DateTimeChooserParameters;
struct FrameLoadRequest;
+struct WebTextAutosizerPageInfo;
struct ViewportDescription;
struct WebCursorInfo;
struct WebScreenInfo;
@@ -145,9 +147,32 @@ class CORE_EXPORT ChromeClient
virtual bool HadFormInteraction() const = 0;
- virtual void BeginLifecycleUpdates() = 0;
- virtual void StartDeferringCommits(base::TimeDelta timeout) = 0;
- virtual void StopDeferringCommits(cc::PaintHoldingCommitTrigger) = 0;
+ // Allow document lifecycle updates to be run in order to produce composited
+ // outputs. Updates are blocked from occurring during loading navigation in
+ // order to prevent contention and allow Blink to proceed more quickly. This
+ // signals that enough progress has been made and document lifecycle updates
+ // are desirable. This will allow visual updates to occur unless the caller
+ // also uses StartDeferringCommits().
+ //
+ // This may only be called for the main frame, and takes it as
+ // reference to make it clear that callers may only call this while a local
+ // main frame is present and the values does not persist between instances of
+ // local main frames.
+ virtual void BeginLifecycleUpdates(LocalFrame& main_frame) = 0;
+
+ // Start or stop compositor commits from occurring, with a timeout before they
+ // are allowed again. Document lifecycle updates are still allowed during this
+ // time, which will update compositor state, but this prevents the state from
+ // being committed to the compositor thread and generating visual updates.
+ //
+ // These may only be called for the main frame, and takes it as
+ // reference to make it clear that callers may only call this while a local
+ // main frame is present and the state does not persist between instances of
+ // local main frames.
+ virtual void StartDeferringCommits(LocalFrame& main_frame,
+ base::TimeDelta timeout) = 0;
+ virtual void StopDeferringCommits(LocalFrame& main_frame,
+ cc::PaintHoldingCommitTrigger) = 0;
// Start a system drag and drop operation.
virtual void StartDragging(LocalFrame*,
@@ -269,7 +294,7 @@ class CORE_EXPORT ChromeClient
virtual float ClampPageScaleFactorToLimits(float scale) const {
return scale;
}
- virtual void MainFrameScrollOffsetChanged() const {}
+ virtual void MainFrameScrollOffsetChanged(LocalFrame& main_frame) const = 0;
virtual void ResizeAfterLayout() const {}
virtual void MainFrameLayoutUpdated() const {}
@@ -317,8 +342,13 @@ class CORE_EXPORT ChromeClient
virtual void AttachRootLayer(scoped_refptr<cc::Layer>,
LocalFrame* local_root) = 0;
+ // Set the CompositorAnimationTimeline for a local root. Should later be unset
+ // by a call to DetachCompositorAnimationTimeline().
virtual void AttachCompositorAnimationTimeline(CompositorAnimationTimeline*,
LocalFrame* local_root) {}
+ // Removes the CompositorAnimationTimeline for a local root. The timeline
+ // would have previously been given to AttachCompositorAnimationTimeline() but
+ // it's valid to call this even if the timeline was never attached.
virtual void DetachCompositorAnimationTimeline(CompositorAnimationTimeline*,
LocalFrame* local_root) {}
@@ -330,12 +360,17 @@ class CORE_EXPORT ChromeClient
virtual void ClearLayerSelection(LocalFrame*) {}
virtual void UpdateLayerSelection(LocalFrame*, const cc::LayerSelection&) {}
+ // The client keeps track of which touch/mousewheel event types have handlers,
+ // and if they do, whether the handlers are passive and/or blocking. This
+ // allows the client to know which optimizations can be used for the
+ // associated event classes.
virtual void SetEventListenerProperties(LocalFrame*,
cc::EventListenerClass,
cc::EventListenerProperties) = 0;
virtual cc::EventListenerProperties EventListenerProperties(
LocalFrame*,
cc::EventListenerClass) const = 0;
+
virtual void SetHasScrollEventHandlers(LocalFrame*, bool) = 0;
virtual void SetNeedsLowLatencyInput(LocalFrame*, bool) = 0;
virtual void SetNeedsUnbufferedInputForDebugger(LocalFrame*, bool) = 0;
@@ -438,6 +473,9 @@ class CORE_EXPORT ChromeClient
virtual void Trace(blink::Visitor*);
+ virtual void DidUpdateTextAutosizerPageInfo(const WebTextAutosizerPageInfo&) {
+ }
+
protected:
ChromeClient() = default;
@@ -467,7 +505,7 @@ class CORE_EXPORT ChromeClient
void SetToolTip(LocalFrame&, const HitTestLocation&, const HitTestResult&);
WeakMember<Node> last_mouse_over_node_;
- LayoutPoint last_tool_tip_point_;
+ PhysicalOffset last_tool_tip_point_;
String last_tool_tip_text_;
FRIEND_TEST_ALL_PREFIXES(ChromeClientTest, SetToolTipFlood);
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 b71a9ad5dba..97c37b0ae3a 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
@@ -30,7 +30,6 @@
*/
#include "third_party/blink/renderer/core/page/chrome_client_impl.h"
-#include "third_party/blink/renderer/platform/heap/heap.h"
#include <memory>
#include <utility>
@@ -43,6 +42,7 @@
#include "third_party/blink/public/platform/web_cursor_info.h"
#include "third_party/blink/public/platform/web_float_rect.h"
#include "third_party/blink/public/platform/web_rect.h"
+#include "third_party/blink/public/platform/web_text_autosizer_page_info.h"
#include "third_party/blink/public/platform/web_url_request.h"
#include "third_party/blink/public/web/blink.h"
#include "third_party/blink/public/web/web_autofill_client.h"
@@ -68,7 +68,6 @@
#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/frame/settings.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/frame/visual_viewport.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"
@@ -101,12 +100,13 @@
#include "third_party/blink/renderer/platform/graphics/compositor_element_id.h"
#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/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.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"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#include "third_party/blink/renderer/platform/wtf/text/string_concatenate.h"
@@ -508,7 +508,9 @@ void ChromeClientImpl::PageScaleFactorChanged() const {
web_view_->PageScaleFactorChanged();
}
-void ChromeClientImpl::MainFrameScrollOffsetChanged() const {
+void ChromeClientImpl::MainFrameScrollOffsetChanged(
+ LocalFrame& main_frame) const {
+ DCHECK(main_frame.IsMainFrame());
web_view_->MainFrameScrollOffsetChanged();
}
@@ -782,28 +784,27 @@ void ChromeClientImpl::AttachRootLayer(scoped_refptr<cc::Layer> root_layer,
void ChromeClientImpl::AttachCompositorAnimationTimeline(
CompositorAnimationTimeline* compositor_timeline,
LocalFrame* local_frame) {
- if (!Platform::Current()->IsThreadedAnimationEnabled())
- return;
+ DCHECK(Platform::Current()->IsThreadedAnimationEnabled());
WebLocalFrameImpl* web_frame = WebLocalFrameImpl::FromFrame(local_frame);
- if (WebFrameWidgetBase* widget = web_frame->LocalRootFrameWidget()) {
- widget->AnimationHost()->AddAnimationTimeline(
- compositor_timeline->GetAnimationTimeline());
- }
+ WebFrameWidgetBase* widget = web_frame->LocalRootFrameWidget();
+ // TODO(crbug.com/912193): This is called while a frame is attached so widget
+ // is never null, right?
+ CHECK(widget);
+ widget->AnimationHost()->AddAnimationTimeline(
+ compositor_timeline->GetAnimationTimeline());
}
void ChromeClientImpl::DetachCompositorAnimationTimeline(
CompositorAnimationTimeline* compositor_timeline,
LocalFrame* local_frame) {
- if (!Platform::Current()->IsThreadedAnimationEnabled())
- return;
+ DCHECK(Platform::Current()->IsThreadedAnimationEnabled());
WebLocalFrameImpl* web_frame = WebLocalFrameImpl::FromFrame(local_frame);
- // This method can be called when the frame is being detached, after the
- // widget is destroyed.
- // TODO(dcheng): This should be called before the widget is gone...
- if (WebFrameWidgetBase* widget = web_frame->LocalRootFrameWidget()) {
- widget->AnimationHost()->RemoveAnimationTimeline(
- compositor_timeline->GetAnimationTimeline());
- }
+ WebFrameWidgetBase* widget = web_frame->LocalRootFrameWidget();
+ // TODO(crbug.com/912193): This should not be called after Document::Shutdown,
+ // so widget is never null, right?
+ CHECK(widget);
+ widget->AnimationHost()->RemoveAnimationTimeline(
+ compositor_timeline->GetAnimationTimeline());
}
void ChromeClientImpl::EnterFullscreen(LocalFrame& frame,
@@ -976,65 +977,36 @@ void ChromeClientImpl::SetEventListenerProperties(
return;
WebLocalFrameImpl* web_frame = WebLocalFrameImpl::FromFrame(frame);
- // The widget may be nullptr if the frame is provisional.
- // TODO(dcheng): This needs to be cleaned up at some point.
- // https://crbug.com/578349
- if (web_frame->IsProvisional()) {
- // If we hit a provisional frame, we expect it to be during initialization
- // in which case the |properties| should be 'nothing'.
- DCHECK(properties == cc::EventListenerProperties::kNone);
- return;
- }
WebFrameWidgetBase* widget = web_frame->LocalRootFrameWidget();
// TODO(https://crbug.com/820787): When creating a local root, the widget
// won't be set yet. While notifications in this case are technically
// redundant, it adds an awkward special case.
if (!widget) {
+ if (web_frame->IsProvisional()) {
+ // If we hit a provisional frame, we expect it to be during initialization
+ // in which case the |properties| should be 'nothing'.
+ DCHECK(properties == cc::EventListenerProperties::kNone);
+ }
return;
}
- // This relies on widget always pointing to a WebFrameWidgetBase when
- // |frame| points to an OOPIF frame, i.e. |frame|'s mainFrame() is
- // remote.
WebWidgetClient* client = widget->Client();
- if (WebLayerTreeView* tree_view = widget->GetLayerTreeView()) {
- tree_view->SetEventListenerProperties(event_class, properties);
- if (event_class == cc::EventListenerClass::kTouchStartOrMove) {
- client->HasTouchEventHandlers(
- properties != cc::EventListenerProperties::kNone ||
- tree_view->EventListenerProperties(
- cc::EventListenerClass::kTouchEndOrCancel) !=
- cc::EventListenerProperties::kNone);
- } else if (event_class == cc::EventListenerClass::kTouchEndOrCancel) {
- client->HasTouchEventHandlers(
- properties != cc::EventListenerProperties::kNone ||
- tree_view->EventListenerProperties(
- cc::EventListenerClass::kTouchStartOrMove) !=
- cc::EventListenerProperties::kNone);
- } else if (event_class == cc::EventListenerClass::kPointerRawUpdate) {
- client->HasPointerRawUpdateEventHandlers(
- properties != cc::EventListenerProperties::kNone);
- }
- } else {
- client->HasTouchEventHandlers(true);
- }
-}
-
-void ChromeClientImpl::BeginLifecycleUpdates() {
- web_view_->StopDeferringMainFrameUpdate();
- // The WidgetClient is null for some WebViews, in which case they can not
- // composite.
- if (web_view_->WidgetClient())
- web_view_->WidgetClient()->ScheduleAnimation();
-}
-
-void ChromeClientImpl::StartDeferringCommits(base::TimeDelta timeout) {
- web_view_->StartDeferringCommits(timeout);
-}
-void ChromeClientImpl::StopDeferringCommits(
- cc::PaintHoldingCommitTrigger trigger) {
- web_view_->StopDeferringCommits(trigger);
+ client->SetEventListenerProperties(event_class, properties);
+
+ if (event_class == cc::EventListenerClass::kTouchStartOrMove ||
+ event_class == cc::EventListenerClass::kTouchEndOrCancel) {
+ client->SetHasTouchEventHandlers(
+ client->EventListenerProperties(
+ cc::EventListenerClass::kTouchStartOrMove) !=
+ cc::EventListenerProperties::kNone ||
+ client->EventListenerProperties(
+ cc::EventListenerClass::kTouchEndOrCancel) !=
+ cc::EventListenerProperties::kNone);
+ } else if (event_class == cc::EventListenerClass::kPointerRawUpdate) {
+ client->SetHasPointerRawUpdateEventHandlers(
+ properties != cc::EventListenerProperties::kNone);
+ }
}
cc::EventListenerProperties ChromeClientImpl::EventListenerProperties(
@@ -1045,25 +1017,54 @@ cc::EventListenerProperties ChromeClientImpl::EventListenerProperties(
WebFrameWidgetBase* widget =
WebLocalFrameImpl::FromFrame(frame)->LocalRootFrameWidget();
-
- if (!widget || !widget->GetLayerTreeView())
+ if (!widget)
return cc::EventListenerProperties::kNone;
- return widget->GetLayerTreeView()->EventListenerProperties(event_class);
+ WebWidgetClient* client = widget->Client();
+ return client->EventListenerProperties(event_class);
+}
+
+void ChromeClientImpl::BeginLifecycleUpdates(LocalFrame& main_frame) {
+ DCHECK(main_frame.IsMainFrame());
+ web_view_->StopDeferringMainFrameUpdate();
+}
+
+void ChromeClientImpl::StartDeferringCommits(LocalFrame& main_frame,
+ base::TimeDelta timeout) {
+ DCHECK(main_frame.IsMainFrame());
+ // WebWidgetClient can be null when not compositing, and deferring commits
+ // only applies with a compositor.
+ if (!web_view_->does_composite())
+ return;
+ WebWidgetClient* client =
+ WebLocalFrameImpl::FromFrame(main_frame)->FrameWidgetImpl()->Client();
+ client->StartDeferringCommits(timeout);
+}
+
+void ChromeClientImpl::StopDeferringCommits(
+ LocalFrame& main_frame,
+ cc::PaintHoldingCommitTrigger trigger) {
+ DCHECK(main_frame.IsMainFrame());
+ // WebWidgetClient can be null when not compositing, and deferring commits
+ // only applies with a compositor.
+ if (!web_view_->does_composite())
+ return;
+ WebWidgetClient* client =
+ WebLocalFrameImpl::FromFrame(main_frame)->FrameWidgetImpl()->Client();
+ client->StopDeferringCommits(trigger);
}
void ChromeClientImpl::SetHasScrollEventHandlers(LocalFrame* frame,
bool has_event_handlers) {
- // |frame| might be null if called via TreeScopeAdopter::
- // moveNodeToNewDocument() and the new document has no frame attached.
- // Since a document without a frame cannot attach one later, it is safe to
- // exit early.
+ // |frame| might be null if called via
+ // TreeScopeAdopter::MoveNodeToNewDocument() and the new document has no frame
+ // attached. Since a document without a frame cannot attach one later, it is
+ // safe to exit early.
if (!frame)
return;
- WebFrameWidgetBase* widget =
- WebLocalFrameImpl::FromFrame(frame)->LocalRootFrameWidget();
- if (widget && widget->GetLayerTreeView())
- widget->GetLayerTreeView()->SetHaveScrollEventHandlers(has_event_handlers);
+ WebWidgetClient* client =
+ WebLocalFrameImpl::FromFrame(frame)->LocalRootFrameWidget()->Client();
+ client->SetHaveScrollEventHandlers(has_event_handlers);
}
void ChromeClientImpl::SetNeedsLowLatencyInput(LocalFrame* frame,
@@ -1117,7 +1118,7 @@ bool ChromeClientImpl::RequestPointerLock(LocalFrame* frame) {
return WebLocalFrameImpl::FromFrame(frame)
->LocalRootFrameWidget()
->Client()
- ->RequestPointerLock();
+ ->RequestPointerLock(WebLocalFrameImpl::FromFrame(frame));
}
void ChromeClientImpl::RequestPointerUnlock(LocalFrame* frame) {
@@ -1263,4 +1264,9 @@ WebAutofillClient* ChromeClientImpl::AutofillClientFromFrame(
return WebLocalFrameImpl::FromFrame(frame)->AutofillClient();
}
+void ChromeClientImpl::DidUpdateTextAutosizerPageInfo(
+ const WebTextAutosizerPageInfo& page_info) {
+ web_view_->Client()->DidUpdateTextAutosizerPageInfo(page_info);
+}
+
} // namespace blink
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 0a9e173aa95..b90ab2010ce 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
@@ -67,9 +67,11 @@ class CORE_EXPORT ChromeClientImpl final : public ChromeClient {
bool CanTakeFocus(WebFocusType) override;
void TakeFocus(WebFocusType) override;
void FocusedElementChanged(Element* from_node, Element* to_node) override;
- void BeginLifecycleUpdates() override;
- void StartDeferringCommits(base::TimeDelta timeout) override;
- void StopDeferringCommits(cc::PaintHoldingCommitTrigger) override;
+ void BeginLifecycleUpdates(LocalFrame& main_frame) override;
+ void StartDeferringCommits(LocalFrame& main_frame,
+ base::TimeDelta timeout) override;
+ void StopDeferringCommits(LocalFrame& main_frame,
+ cc::PaintHoldingCommitTrigger) override;
bool HadFormInteraction() const override;
void StartDragging(LocalFrame*,
const WebDragData&,
@@ -130,7 +132,7 @@ class CORE_EXPORT ChromeClientImpl final : public ChromeClient {
bool DoubleTapToZoomEnabled() const override;
void PageScaleFactorChanged() const override;
float ClampPageScaleFactorToLimits(float scale) const override;
- void MainFrameScrollOffsetChanged() const override;
+ void MainFrameScrollOffsetChanged(LocalFrame& main_frame) const override;
void ResizeAfterLayout() const override;
void MainFrameLayoutUpdated() const override;
void ShowMouseOverURL(const HitTestResult&) override;
@@ -150,10 +152,6 @@ class CORE_EXPORT ChromeClientImpl final : public ChromeClient {
void SetCursor(const Cursor&, LocalFrame*) override;
void SetCursorOverridden(bool) override;
Cursor LastSetCursorForTesting() const override;
- // The client keeps track of which touch/mousewheel event types have handlers,
- // and if they do, whether the handlers are passive and/or blocking. This
- // allows the client to know which optimizations can be used for the
- // associated event classes.
void SetEventListenerProperties(LocalFrame*,
cc::EventListenerClass,
cc::EventListenerProperties) override;
@@ -265,6 +263,8 @@ class CORE_EXPORT ChromeClientImpl final : public ChromeClient {
void FallbackCursorModeSetCursorVisibility(LocalFrame* frame,
bool visible) override;
+ void DidUpdateTextAutosizerPageInfo(const WebTextAutosizerPageInfo&) override;
+
private:
bool IsChromeClientImpl() const override { return true; }
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 250db636294..360f45f00c2 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
@@ -11,6 +11,7 @@
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/layout/hit_test_result.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/platform/heap/heap.h"
namespace blink {
@@ -40,7 +41,7 @@ class ChromeClientTest : public testing::Test {};
TEST_F(ChromeClientTest, SetToolTipFlood) {
ChromeClientToolTipLogger logger;
ChromeClient* client = &logger;
- HitTestLocation location(LayoutPoint(10, 20));
+ HitTestLocation location(PhysicalOffset(10, 20));
HitTestResult result(HitTestRequest(HitTestRequest::kMove), location);
auto* doc = MakeGarbageCollected<Document>();
auto* element = MakeGarbageCollected<HTMLElement>(html_names::kDivTag, *doc);
@@ -73,7 +74,7 @@ TEST_F(ChromeClientTest, SetToolTipFlood) {
TEST_F(ChromeClientTest, SetToolTipEmptyString) {
ChromeClient* client = MakeGarbageCollected<EmptyChromeClient>();
- HitTestLocation location(LayoutPoint(10, 20));
+ HitTestLocation location(PhysicalOffset(10, 20));
HitTestResult result(HitTestRequest(HitTestRequest::kMove), location);
auto& doc = *MakeGarbageCollected<Document>();
auto& input_element =
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 0d69fdd64d3..e7527b8cbe3 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
@@ -96,7 +96,8 @@ void ContextMenuController::DocumentDetached(Document* document) {
void ContextMenuController::HandleContextMenuEvent(MouseEvent* mouse_event) {
DCHECK(mouse_event->type() == event_type_names::kContextmenu);
LocalFrame* frame = mouse_event->target()->ToNode()->GetDocument().GetFrame();
- LayoutPoint location(mouse_event->AbsoluteLocation());
+ PhysicalOffset location = PhysicalOffset::FromFloatPointRound(
+ FloatPoint(mouse_event->AbsoluteLocation()));
if (ShowContextMenu(frame, location, mouse_event->GetMenuSourceType()))
mouse_event->SetDefaultHandled();
}
@@ -107,7 +108,8 @@ void ContextMenuController::ShowContextMenuAtPoint(
float y,
ContextMenuProvider* menu_provider) {
menu_provider_ = menu_provider;
- if (!ShowContextMenu(frame, LayoutPoint(x, y), kMenuSourceNone))
+ if (!ShowContextMenu(frame, PhysicalOffset(LayoutUnit(x), LayoutUnit(y)),
+ kMenuSourceNone))
ClearContextMenu();
}
@@ -136,11 +138,6 @@ static KURL UrlFromFrame(LocalFrame* frame) {
static int ComputeEditFlags(Document& selected_document, Editor& editor) {
int edit_flags = WebContextMenuData::kCanDoNone;
- if (!selected_document.IsHTMLDocument() &&
- !selected_document.IsXHTMLDocument())
- return edit_flags;
-
- edit_flags |= WebContextMenuData::kCanTranslate;
if (editor.CanUndo())
edit_flags |= WebContextMenuData::kCanUndo;
if (editor.CanRedo())
@@ -155,8 +152,12 @@ static int ComputeEditFlags(Document& selected_document, Editor& editor) {
edit_flags |= WebContextMenuData::kCanDelete;
if (editor.CanEditRichly())
edit_flags |= WebContextMenuData::kCanEditRichly;
- if (selected_document.queryCommandEnabled("selectAll", ASSERT_NO_EXCEPTION))
- edit_flags |= WebContextMenuData::kCanSelectAll;
+ if (selected_document.IsHTMLDocument() ||
+ selected_document.IsXHTMLDocument()) {
+ edit_flags |= WebContextMenuData::kCanTranslate;
+ if (selected_document.queryCommandEnabled("selectAll", ASSERT_NO_EXCEPTION))
+ edit_flags |= WebContextMenuData::kCanSelectAll;
+ }
return edit_flags;
}
@@ -200,7 +201,7 @@ bool ContextMenuController::ShouldShowContextMenuFromTouch(
}
bool ContextMenuController::ShowContextMenu(LocalFrame* frame,
- const LayoutPoint& point,
+ const PhysicalOffset& point,
WebMenuSourceType source_type) {
// Displaying the context menu in this function is a big hack as we don't
// have context, i.e. whether this is being invoked via a script or in
@@ -210,8 +211,9 @@ bool ContextMenuController::ShowContextMenu(LocalFrame* frame,
if (!ContextMenuAllowedScope::IsContextMenuAllowed())
return false;
- HitTestRequest::HitTestRequestType type =
- HitTestRequest::kReadOnly | HitTestRequest::kActive;
+ HitTestRequest::HitTestRequestType type = HitTestRequest::kReadOnly |
+ HitTestRequest::kActive |
+ HitTestRequest::kRetargetForInert;
HitTestLocation location(point);
HitTestResult result(type, location);
if (frame)
@@ -239,11 +241,8 @@ bool ContextMenuController::ShowContextMenu(LocalFrame* frame,
auto* html_element = DynamicTo<HTMLElement>(result.InnerNode());
if (html_element) {
- if (!html_element->title().IsEmpty()) {
- data.title_text = html_element->title();
- } else {
- data.title_text = html_element->AltText();
- }
+ data.title_text = html_element->title();
+ data.alt_text = html_element->AltText();
}
if (IsHTMLCanvasElement(result.InnerNode())) {
@@ -257,17 +256,6 @@ bool ContextMenuController::ShowContextMenu(LocalFrame* frame,
// An image can be null for many reasons, like being blocked, no image
// data received from server yet.
data.has_image_contents = result.GetImage() && !result.GetImage()->IsNull();
- data.is_placeholder_image =
- result.GetImage() && result.GetImage()->IsPlaceholderImage();
- if (data.has_image_contents &&
- IsHTMLImageElement(result.InnerNodeOrImageMapImage())) {
- HTMLImageElement* image_element =
- ToHTMLImageElement(result.InnerNodeOrImageMapImage());
- if (image_element && image_element->CachedImage()) {
- data.image_response = WrappedResourceResponse(
- image_element->CachedImage()->GetResponse());
- }
- }
} else if (!result.AbsoluteMediaURL().IsEmpty() ||
result.GetMediaStreamDescriptor()) {
if (!result.AbsoluteMediaURL().IsEmpty())
diff --git a/chromium/third_party/blink/renderer/core/page/context_menu_controller.h b/chromium/third_party/blink/renderer/core/page/context_menu_controller.h
index 93f48a42bb1..df28bc8a3b7 100644
--- a/chromium/third_party/blink/renderer/core/page/context_menu_controller.h
+++ b/chromium/third_party/blink/renderer/core/page/context_menu_controller.h
@@ -68,7 +68,7 @@ class CORE_EXPORT ContextMenuController final
friend class ContextMenuControllerTest;
// Returns whether a Context Menu was actually shown.
- bool ShowContextMenu(LocalFrame*, const LayoutPoint&, WebMenuSourceType);
+ bool ShowContextMenu(LocalFrame*, const PhysicalOffset&, WebMenuSourceType);
bool ShouldShowContextMenuFromTouch(const WebContextMenuData&);
Member<Page> page_;
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 49a2c8db059..1c840bb35b3 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
@@ -9,6 +9,7 @@
#include "third_party/blink/public/platform/web_media_stream_track.h"
#include "third_party/blink/public/platform/web_menu_source_type.h"
#include "third_party/blink/public/web/web_context_menu_data.h"
+#include "third_party/blink/renderer/core/editing/frame_selection.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/core/geometry/dom_rect.h"
@@ -72,19 +73,32 @@ class ContextMenuControllerTest : public testing::Test {
WebWidget::LifecycleUpdateReason::kTest);
}
- bool ShowContextMenu(const LayoutPoint& location, WebMenuSourceType source) {
+ bool ShowContextMenu(const PhysicalOffset& location,
+ WebMenuSourceType source) {
return web_view_helper_.GetWebView()
->GetPage()
->GetContextMenuController()
.ShowContextMenu(GetDocument()->GetFrame(), location, source);
}
+ bool ShowContextMenuForElement(Element* element, WebMenuSourceType source) {
+ const DOMRect* rect = element->getBoundingClientRect();
+ PhysicalOffset location(LayoutUnit((rect->left() + rect->right()) / 2),
+ LayoutUnit((rect->top() + rect->bottom()) / 2));
+ ContextMenuAllowedScope context_menu_allowed_scope;
+ return ShowContextMenu(location, source);
+ }
+
Document* GetDocument() {
return static_cast<Document*>(
web_view_helper_.LocalMainFrame()->GetDocument());
}
Page* GetPage() { return web_view_helper_.GetWebView()->GetPage(); }
+ WebLocalFrameImpl* LocalMainFrame() {
+ return web_view_helper_.LocalMainFrame();
+ }
+ void LoadAhem() { web_view_helper_.LoadAhem(); }
const TestWebFrameClientImpl& GetWebFrameClient() const {
return web_frame_client_;
@@ -125,8 +139,8 @@ TEST_F(ContextMenuControllerTest, VideoNotLoaded) {
.WillRepeatedly(Return(false));
DOMRect* rect = video->getBoundingClientRect();
- LayoutPoint location((rect->left() + rect->right()) / 2,
- (rect->top() + rect->bottom()) / 2);
+ PhysicalOffset location(LayoutUnit((rect->left() + rect->right()) / 2),
+ LayoutUnit((rect->top() + rect->bottom()) / 2));
EXPECT_TRUE(ShowContextMenu(location, kMenuSourceMouse));
// Context menu info are sent to the WebLocalFrameClient.
@@ -135,7 +149,7 @@ TEST_F(ContextMenuControllerTest, VideoNotLoaded) {
EXPECT_EQ(WebContextMenuData::kMediaTypeVideo, context_menu_data.media_type);
EXPECT_EQ(video_url, context_menu_data.src_url.GetString());
- const std::vector<std::pair<WebContextMenuData::MediaFlags, bool>>
+ const Vector<std::pair<WebContextMenuData::MediaFlags, bool>>
expected_media_flags = {
{WebContextMenuData::kMediaInError, false},
{WebContextMenuData::kMediaPaused, true},
@@ -186,8 +200,8 @@ TEST_F(ContextMenuControllerTest, VideoWithAudioOnly) {
.WillRepeatedly(Return(true));
DOMRect* rect = video->getBoundingClientRect();
- LayoutPoint location((rect->left() + rect->right()) / 2,
- (rect->top() + rect->bottom()) / 2);
+ PhysicalOffset location(LayoutUnit((rect->left() + rect->right()) / 2),
+ LayoutUnit((rect->top() + rect->bottom()) / 2));
EXPECT_TRUE(ShowContextMenu(location, kMenuSourceMouse));
// Context menu info are sent to the WebLocalFrameClient.
@@ -196,7 +210,7 @@ TEST_F(ContextMenuControllerTest, VideoWithAudioOnly) {
EXPECT_EQ(WebContextMenuData::kMediaTypeAudio, context_menu_data.media_type);
EXPECT_EQ(video_url, context_menu_data.src_url.GetString());
- const std::vector<std::pair<WebContextMenuData::MediaFlags, bool>>
+ const Vector<std::pair<WebContextMenuData::MediaFlags, bool>>
expected_media_flags = {
{WebContextMenuData::kMediaInError, false},
{WebContextMenuData::kMediaPaused, true},
@@ -243,8 +257,8 @@ TEST_F(ContextMenuControllerTest, PictureInPictureEnabledVideoLoaded) {
.WillRepeatedly(Return(true));
DOMRect* rect = video->getBoundingClientRect();
- LayoutPoint location((rect->left() + rect->right()) / 2,
- (rect->top() + rect->bottom()) / 2);
+ PhysicalOffset location(LayoutUnit((rect->left() + rect->right()) / 2),
+ LayoutUnit((rect->top() + rect->bottom()) / 2));
EXPECT_TRUE(ShowContextMenu(location, kMenuSourceMouse));
// Context menu info are sent to the WebLocalFrameClient.
@@ -253,7 +267,7 @@ TEST_F(ContextMenuControllerTest, PictureInPictureEnabledVideoLoaded) {
EXPECT_EQ(WebContextMenuData::kMediaTypeVideo, context_menu_data.media_type);
EXPECT_EQ(video_url, context_menu_data.src_url.GetString());
- const std::vector<std::pair<WebContextMenuData::MediaFlags, bool>>
+ const Vector<std::pair<WebContextMenuData::MediaFlags, bool>>
expected_media_flags = {
{WebContextMenuData::kMediaInError, false},
{WebContextMenuData::kMediaPaused, true},
@@ -300,8 +314,8 @@ TEST_F(ContextMenuControllerTest, PictureInPictureDisabledVideoLoaded) {
.WillRepeatedly(Return(true));
DOMRect* rect = video->getBoundingClientRect();
- LayoutPoint location((rect->left() + rect->right()) / 2,
- (rect->top() + rect->bottom()) / 2);
+ PhysicalOffset location(LayoutUnit((rect->left() + rect->right()) / 2),
+ LayoutUnit((rect->top() + rect->bottom()) / 2));
EXPECT_TRUE(ShowContextMenu(location, kMenuSourceMouse));
// Context menu info are sent to the WebLocalFrameClient.
@@ -310,7 +324,7 @@ TEST_F(ContextMenuControllerTest, PictureInPictureDisabledVideoLoaded) {
EXPECT_EQ(WebContextMenuData::kMediaTypeVideo, context_menu_data.media_type);
EXPECT_EQ(video_url, context_menu_data.src_url.GetString());
- const std::vector<std::pair<WebContextMenuData::MediaFlags, bool>>
+ const Vector<std::pair<WebContextMenuData::MediaFlags, bool>>
expected_media_flags = {
{WebContextMenuData::kMediaInError, false},
{WebContextMenuData::kMediaPaused, true},
@@ -359,8 +373,8 @@ TEST_F(ContextMenuControllerTest, MediaStreamVideoLoaded) {
.WillRepeatedly(Return(true));
DOMRect* rect = video->getBoundingClientRect();
- LayoutPoint location((rect->left() + rect->right()) / 2,
- (rect->top() + rect->bottom()) / 2);
+ PhysicalOffset location(LayoutUnit((rect->left() + rect->right()) / 2),
+ LayoutUnit((rect->top() + rect->bottom()) / 2));
EXPECT_TRUE(ShowContextMenu(location, kMenuSourceMouse));
// Context menu info are sent to the WebLocalFrameClient.
@@ -368,7 +382,7 @@ TEST_F(ContextMenuControllerTest, MediaStreamVideoLoaded) {
GetWebFrameClient().GetContextMenuData();
EXPECT_EQ(WebContextMenuData::kMediaTypeVideo, context_menu_data.media_type);
- const std::vector<std::pair<WebContextMenuData::MediaFlags, bool>>
+ const Vector<std::pair<WebContextMenuData::MediaFlags, bool>>
expected_media_flags = {
{WebContextMenuData::kMediaInError, false},
{WebContextMenuData::kMediaPaused, true},
@@ -421,8 +435,8 @@ TEST_F(ContextMenuControllerTest, InfiniteDurationVideoLoaded) {
DurationChanged(video.Get());
DOMRect* rect = video->getBoundingClientRect();
- LayoutPoint location((rect->left() + rect->right()) / 2,
- (rect->top() + rect->bottom()) / 2);
+ PhysicalOffset location(LayoutUnit((rect->left() + rect->right()) / 2),
+ LayoutUnit((rect->top() + rect->bottom()) / 2));
EXPECT_TRUE(ShowContextMenu(location, kMenuSourceMouse));
// Context menu info are sent to the WebLocalFrameClient.
@@ -431,7 +445,7 @@ TEST_F(ContextMenuControllerTest, InfiniteDurationVideoLoaded) {
EXPECT_EQ(WebContextMenuData::kMediaTypeVideo, context_menu_data.media_type);
EXPECT_EQ(video_url, context_menu_data.src_url.GetString());
- const std::vector<std::pair<WebContextMenuData::MediaFlags, bool>>
+ const Vector<std::pair<WebContextMenuData::MediaFlags, bool>>
expected_media_flags = {
{WebContextMenuData::kMediaInError, false},
{WebContextMenuData::kMediaPaused, true},
@@ -455,4 +469,78 @@ TEST_F(ContextMenuControllerTest, InfiniteDurationVideoLoaded) {
}
}
+TEST_F(ContextMenuControllerTest, EditingActionsEnabledInSVGDocument) {
+ frame_test_helpers::LoadFrame(LocalMainFrame(), R"SVG(data:image/svg+xml,
+ <svg xmlns='http://www.w3.org/2000/svg'
+ xmlns:h='http://www.w3.org/1999/xhtml'
+ font-family='Ahem'>
+ <text y='20' id='t'>Copyable text</text>
+ <foreignObject y='30' width='100' height='200'>
+ <h:div id='e' style='width: 100px; height: 50px'
+ contenteditable='true'>
+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
+ </h:div>
+ </foreignObject>
+ </svg>
+ )SVG");
+ LoadAhem();
+
+ Document* document = GetDocument();
+ ASSERT_TRUE(document->IsSVGDocument());
+
+ Element* text_element = document->getElementById("t");
+ document->UpdateStyleAndLayout();
+ FrameSelection& selection = document->GetFrame()->Selection();
+
+ // <text> element
+ selection.SelectSubString(*text_element, 4, 8);
+ EXPECT_TRUE(ShowContextMenuForElement(text_element, kMenuSourceMouse));
+
+ WebContextMenuData context_menu_data =
+ GetWebFrameClient().GetContextMenuData();
+ EXPECT_EQ(context_menu_data.media_type, WebContextMenuData::kMediaTypeNone);
+ EXPECT_EQ(context_menu_data.edit_flags, WebContextMenuData::kCanCopy);
+ EXPECT_EQ(context_menu_data.selected_text, "able tex");
+
+ // <div contenteditable=true>
+ Element* editable_element = document->getElementById("e");
+ selection.SelectSubString(*editable_element, 0, 42);
+ EXPECT_TRUE(ShowContextMenuForElement(editable_element, kMenuSourceMouse));
+
+ context_menu_data = GetWebFrameClient().GetContextMenuData();
+ EXPECT_EQ(context_menu_data.media_type, WebContextMenuData::kMediaTypeNone);
+ EXPECT_EQ(context_menu_data.edit_flags,
+ WebContextMenuData::kCanCut | WebContextMenuData::kCanCopy |
+ WebContextMenuData::kCanPaste | WebContextMenuData::kCanDelete |
+ WebContextMenuData::kCanEditRichly);
+}
+
+TEST_F(ContextMenuControllerTest, EditingActionsEnabledInXMLDocument) {
+ frame_test_helpers::LoadFrame(LocalMainFrame(), R"XML(data:text/xml,
+ <root>
+ <style xmlns="http://www.w3.org/1999/xhtml">
+ root { color: blue; }
+ </style>
+ <text id="t">Blue text</text>
+ </root>
+ )XML");
+
+ Document* document = GetDocument();
+ ASSERT_TRUE(document->IsXMLDocument());
+ ASSERT_FALSE(document->IsHTMLDocument());
+
+ Element* text_element = document->getElementById("t");
+ document->UpdateStyleAndLayout();
+ FrameSelection& selection = document->GetFrame()->Selection();
+
+ selection.SelectAll();
+ EXPECT_TRUE(ShowContextMenuForElement(text_element, kMenuSourceMouse));
+
+ WebContextMenuData context_menu_data =
+ GetWebFrameClient().GetContextMenuData();
+ EXPECT_EQ(context_menu_data.media_type, WebContextMenuData::kMediaTypeNone);
+ EXPECT_EQ(context_menu_data.edit_flags, WebContextMenuData::kCanCopy);
+ EXPECT_EQ(context_menu_data.selected_text, "Blue text");
+}
+
} // namespace blink
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 d4e5edc3ca1..8b97b286e05 100644
--- a/chromium/third_party/blink/renderer/core/page/create_window.cc
+++ b/chromium/third_party/blink/renderer/core/page/create_window.cc
@@ -288,13 +288,11 @@ Frame* CreateNewWindow(LocalFrame& opener_frame,
AllocateSessionStorageNamespaceId();
Page* old_page = opener_frame.GetPage();
- if (base::FeatureList::IsEnabled(features::kOnionSoupDOMStorage)) {
- // TODO(dmurph): Don't copy session storage when features.noopener is true:
- // https://html.spec.whatwg.org/C/#copy-session-storage
- // https://crbug.com/771959
- CoreInitializer::GetInstance().CloneSessionStorage(old_page,
- new_namespace_id);
- }
+ // TODO(dmurph): Don't copy session storage when features.noopener is true:
+ // https://html.spec.whatwg.org/C/#copy-session-storage
+ // https://crbug.com/771959
+ CoreInitializer::GetInstance().CloneSessionStorage(old_page,
+ new_namespace_id);
Page* page = old_page->GetChromeClient().CreateWindow(
&opener_frame, request, frame_name, features, sandbox_flags,
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 c3ffeee94a5..df4db495601 100644
--- a/chromium/third_party/blink/renderer/core/page/drag_controller.cc
+++ b/chromium/third_party/blink/renderer/core/page/drag_controller.cc
@@ -128,7 +128,7 @@ static WebMouseEvent CreateMouseEvent(DragData* drag_data) {
WebInputEvent::kMouseMove, drag_data->ClientPosition(),
drag_data->GlobalPosition(), WebPointerProperties::Button::kLeft, 0,
static_cast<WebInputEvent::Modifiers>(drag_data->GetModifiers()),
- CurrentTimeTicks());
+ base::TimeTicks::Now());
// TODO(dtapuska): Really we should chnage DragData to store the viewport
// coordinates and scale.
result.SetFrameScale(1);
@@ -238,8 +238,8 @@ void DragController::DragExited(DragData* drag_data, LocalFrame& local_root) {
void DragController::PerformDrag(DragData* drag_data, LocalFrame& local_root) {
DCHECK(drag_data);
- document_under_mouse_ =
- local_root.DocumentAtPoint(LayoutPoint(drag_data->ClientPosition()));
+ document_under_mouse_ = local_root.DocumentAtPoint(
+ PhysicalOffset::FromFloatPointRound(drag_data->ClientPosition()));
std::unique_ptr<UserGestureIndicator> gesture =
LocalFrame::NotifyUserActivation(
document_under_mouse_ ? document_under_mouse_->GetFrame() : nullptr,
@@ -261,7 +261,7 @@ void DragController::PerformDrag(DragData* drag_data, LocalFrame& local_root) {
// When drop target is plugin element and it can process drag, we
// should prevent default behavior.
const HitTestLocation location(local_root.View()->ConvertFromRootFrame(
- LayoutPoint(drag_data->ClientPosition())));
+ PhysicalOffset::FromFloatPointRound(drag_data->ClientPosition())));
const HitTestResult result =
event_handler.HitTestResultAtLocation(location);
prevented_default |=
@@ -332,8 +332,8 @@ DragOperation DragController::DragEnteredOrUpdated(DragData* drag_data,
LocalFrame& local_root) {
DCHECK(drag_data);
- MouseMovedIntoDocument(
- local_root.DocumentAtPoint(LayoutPoint(drag_data->ClientPosition())));
+ MouseMovedIntoDocument(local_root.DocumentAtPoint(
+ PhysicalOffset::FromFloatPointRound(drag_data->ClientPosition())));
// TODO(esprehn): Replace acceptsLoadDrops with a Setting used in core.
drag_destination_action_ =
@@ -363,8 +363,9 @@ static HTMLInputElement* AsFileInput(Node* node) {
// This can return null if an empty document is loaded.
static Element* ElementUnderMouse(Document* document_under_mouse,
- const LayoutPoint& point) {
- HitTestRequest request(HitTestRequest::kReadOnly | HitTestRequest::kActive);
+ const PhysicalOffset& point) {
+ HitTestRequest request(HitTestRequest::kReadOnly | HitTestRequest::kActive |
+ HitTestRequest::kRetargetForInert);
HitTestLocation location(point);
HitTestResult result(request, location);
document_under_mouse->GetLayoutView()->HitTest(location, result);
@@ -375,7 +376,7 @@ static Element* ElementUnderMouse(Document* document_under_mouse,
if (n && n->IsInShadowTree())
n = n->OwnerShadowHost();
- return ToElement(n);
+ return To<Element>(n);
}
bool DragController::TryDocumentDrag(DragData* drag_data,
@@ -416,8 +417,8 @@ bool DragController::TryDocumentDrag(DragData* drag_data,
if ((action_mask & kDragDestinationActionEdit) &&
CanProcessDrag(drag_data, local_root)) {
- LayoutPoint point = frame_view->ConvertFromRootFrame(
- LayoutPoint(drag_data->ClientPosition()));
+ PhysicalOffset point = frame_view->ConvertFromRootFrame(
+ PhysicalOffset::FromFloatPointRound(drag_data->ClientPosition()));
Element* element = ElementUnderMouse(document_under_mouse_.Get(), point);
if (!element)
return false;
@@ -466,8 +467,8 @@ bool DragController::TryDocumentDrag(DragData* drag_data,
DragOperation DragController::OperationForLoad(DragData* drag_data,
LocalFrame& local_root) {
DCHECK(drag_data);
- Document* doc =
- local_root.DocumentAtPoint(LayoutPoint(drag_data->ClientPosition()));
+ Document* doc = local_root.DocumentAtPoint(
+ PhysicalOffset::FromFloatPointRound(drag_data->ClientPosition()));
if (doc &&
(did_initiate_drag_ || doc->IsPluginDocument() || HasEditableStyle(*doc)))
@@ -481,7 +482,7 @@ DragOperation DragController::OperationForLoad(DragData* drag_data,
static bool SetSelectionToDragCaret(LocalFrame* frame,
const SelectionInDOMTree& drag_caret,
Range*& range,
- const LayoutPoint& point) {
+ const PhysicalOffset& point) {
frame->Selection().SetSelectionAndEndTyping(drag_caret);
// TODO(editing-dev): The use of
// UpdateStyleAndLayout
@@ -541,8 +542,8 @@ bool DragController::ConcludeEditDrag(DragData* drag_data) {
if (!document_under_mouse_)
return false;
- LayoutPoint point = document_under_mouse_->View()->ConvertFromRootFrame(
- LayoutPoint(drag_data->ClientPosition()));
+ PhysicalOffset point = document_under_mouse_->View()->ConvertFromRootFrame(
+ PhysicalOffset::FromFloatPointRound(drag_data->ClientPosition()));
Element* element = ElementUnderMouse(document_under_mouse_.Get(), point);
if (!element)
return false;
@@ -708,8 +709,8 @@ bool DragController::CanProcessDrag(DragData* drag_data,
if (!local_root.ContentLayoutObject())
return false;
- LayoutPoint point = local_root.View()->ConvertFromRootFrame(
- LayoutPoint(drag_data->ClientPosition()));
+ PhysicalOffset point = local_root.View()->ConvertFromRootFrame(
+ PhysicalOffset::FromFloatPointRound(drag_data->ClientPosition()));
HitTestLocation location(point);
HitTestResult result =
@@ -814,7 +815,7 @@ Node* DragController::DraggableNode(const LocalFrame* src,
const IntPoint& drag_origin,
SelectionDragPolicy selection_drag_policy,
DragSourceAction& drag_type) const {
- if (src->Selection().Contains(drag_origin)) {
+ if (src->Selection().Contains(PhysicalOffset(drag_origin))) {
drag_type = kDragSourceActionSelection;
if (selection_drag_policy == kImmediateSelectionDragResolution)
return start_node;
@@ -968,9 +969,9 @@ bool DragController::PopulateDragDataTransfer(LocalFrame* src,
if (state.drag_type_ == kDragSourceActionSelection) {
data_transfer->WriteSelection(src->Selection());
} else if (state.drag_type_ == kDragSourceActionImage) {
- if (image_url.IsEmpty() || !node || !node->IsElementNode())
+ auto* element = DynamicTo<Element>(node);
+ if (image_url.IsEmpty() || !element)
return false;
- Element* element = ToElement(node);
PrepareDataTransferForImageDrag(src, data_transfer, element, link_url,
image_url,
hit_test_result.AltDisplayString());
@@ -1224,9 +1225,9 @@ bool DragController::StartDrag(LocalFrame* src,
DoSystemDrag(drag_image.get(), drag_location, drag_origin, data_transfer,
src, false);
} else if (state.drag_type_ == kDragSourceActionImage) {
- if (image_url.IsEmpty() || !node || !node->IsElementNode())
+ auto* element = DynamicTo<Element>(node);
+ if (image_url.IsEmpty() || !element)
return false;
- Element* element = ToElement(node);
Image* image = GetImage(element);
if (!image || image->IsNull() || !image->Data() || !image->Data()->size())
return false;
diff --git a/chromium/third_party/blink/renderer/core/page/drag_image.cc b/chromium/third_party/blink/renderer/core/page/drag_image.cc
index 2e1fedb2873..aa12bdadc87 100644
--- a/chromium/third_party/blink/renderer/core/page/drag_image.cc
+++ b/chromium/third_party/blink/renderer/core/page/drag_image.cc
@@ -201,9 +201,11 @@ std::unique_ptr<DragImage> DragImage::Create(const KURL& url,
// fill the background
IntSize scaled_image_size = image_size;
scaled_image_size.Scale(device_scale_factor);
+ // TODO(fserb): are we sure this should be software?
std::unique_ptr<CanvasResourceProvider> resource_provider(
CanvasResourceProvider::Create(
- scaled_image_size, CanvasResourceProvider::kSoftwareResourceUsage,
+ scaled_image_size,
+ CanvasResourceProvider::ResourceUsage::kSoftwareResourceUsage,
nullptr, // context_provider_wrapper
0, // msaa_sample_count
CanvasColorParams(), CanvasResourceProvider::kDefaultPresentationMode,
diff --git a/chromium/third_party/blink/renderer/core/page/drag_image.h b/chromium/third_party/blink/renderer/core/page/drag_image.h
index b2fbcd0406b..5a8fd1bd4c3 100644
--- a/chromium/third_party/blink/renderer/core/page/drag_image.h
+++ b/chromium/third_party/blink/renderer/core/page/drag_image.h
@@ -36,7 +36,7 @@
#include "third_party/blink/renderer/platform/graphics/image_orientation.h"
#include "third_party/blink/renderer/platform/graphics/paint/display_item_client.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_image.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "third_party/skia/include/core/SkBitmap.h"
diff --git a/chromium/third_party/blink/renderer/core/page/event_with_hit_test_results.h b/chromium/third_party/blink/renderer/core/page/event_with_hit_test_results.h
index e31396af8eb..839dbd901d8 100644
--- a/chromium/third_party/blink/renderer/core/page/event_with_hit_test_results.h
+++ b/chromium/third_party/blink/renderer/core/page/event_with_hit_test_results.h
@@ -43,7 +43,7 @@ class EventWithHitTestResults {
const EventType& Event() const { return event_; }
const HitTestResult& GetHitTestResult() const { return hit_test_result_; }
- LayoutPoint LocalPoint() const { return hit_test_result_.LocalPoint(); }
+ PhysicalOffset LocalPoint() const { return hit_test_result_.LocalPoint(); }
Scrollbar* GetScrollbar() const { return hit_test_result_.GetScrollbar(); }
bool IsOverLink() const { return hit_test_result_.IsOverLink(); }
bool IsOverEmbeddedContentView() const {
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 4a0e1016160..aa350fb7a01 100644
--- a/chromium/third_party/blink/renderer/core/page/focus_controller.cc
+++ b/chromium/third_party/blink/renderer/core/page/focus_controller.cc
@@ -1134,15 +1134,15 @@ Element* FocusController::NextFocusableElementInForm(Element* element,
if (!html_element)
return nullptr;
- if (!element->IsFormControlElement() &&
- !html_element->isContentEditableForBinding())
+ auto* form_control_element = DynamicTo<HTMLFormControlElement>(element);
+ if (!form_control_element && !html_element->isContentEditableForBinding())
return nullptr;
HTMLFormElement* form_owner = nullptr;
if (html_element->isContentEditableForBinding())
form_owner = Traversal<HTMLFormElement>::FirstAncestor(*element);
else
- form_owner = ToHTMLFormControlElement(element)->formOwner();
+ form_owner = form_control_element->formOwner();
if (!form_owner)
return nullptr;
@@ -1160,10 +1160,9 @@ Element* FocusController::NextFocusableElementInForm(Element* element,
if (next_html_element->isContentEditableForBinding() &&
next_element->IsDescendantOf(form_owner))
return next_element;
- if (!next_element->IsFormControlElement())
+ auto* form_element = DynamicTo<HTMLFormControlElement>(next_element);
+ if (!form_element)
continue;
- HTMLFormControlElement* form_element =
- ToHTMLFormControlElement(next_element);
if (form_element->formOwner() != form_owner ||
form_element->IsDisabledOrReadOnly())
continue;
diff --git a/chromium/third_party/blink/renderer/core/page/focus_controller_test.cc b/chromium/third_party/blink/renderer/core/page/focus_controller_test.cc
index df0c2943175..b597c0466a6 100644
--- a/chromium/third_party/blink/renderer/core/page/focus_controller_test.cc
+++ b/chromium/third_party/blink/renderer/core/page/focus_controller_test.cc
@@ -20,7 +20,7 @@ class FocusControllerTest : public PageTestBase {
TEST_F(FocusControllerTest, SetInitialFocus) {
GetDocument().body()->SetInnerHTMLFromString("<input><textarea>");
- Element* input = ToElement(GetDocument().body()->firstChild());
+ auto* input = To<Element>(GetDocument().body()->firstChild());
// Set sequential focus navigation point before the initial focus.
input->focus();
input->blur();
@@ -35,12 +35,12 @@ TEST_F(FocusControllerTest, DoNotCrash1) {
"<div id='host'></div>This test is for crbug.com/609012<p id='target' "
"tabindex='0'></p>");
// <div> with shadow root
- Element* host = ToElement(GetDocument().body()->firstChild());
+ auto* host = To<Element>(GetDocument().body()->firstChild());
host->AttachShadowRootInternal(ShadowRootType::kOpen);
// "This test is for crbug.com/609012"
Node* text = host->nextSibling();
// <p>
- Element* target = ToElement(text->nextSibling());
+ auto* target = To<Element>(text->nextSibling());
// Set sequential focus navigation point at text node.
GetDocument().SetSequentialFocusNavigationStartingPoint(text);
@@ -55,11 +55,11 @@ TEST_F(FocusControllerTest, DoNotCrash2) {
"<p id='target' tabindex='0'></p>This test is for crbug.com/609012<div "
"id='host'></div>");
// <p>
- Element* target = ToElement(GetDocument().body()->firstChild());
+ auto* target = To<Element>(GetDocument().body()->firstChild());
// "This test is for crbug.com/609012"
Node* text = target->nextSibling();
// <div> with shadow root
- Element* host = ToElement(text->nextSibling());
+ auto* host = To<Element>(text->nextSibling());
host->AttachShadowRootInternal(ShadowRootType::kOpen);
// Set sequential focus navigation point at text node.
@@ -90,9 +90,9 @@ TEST_F(FocusControllerTest, SVGFocusableElementInForm) {
"<input id='last'>"
"</form>");
- Element* form = ToElement(GetDocument().body()->firstChild());
- Element* first = ToElement(form->firstChild());
- Element* last = ToElement(form->lastChild());
+ auto* form = To<Element>(GetDocument().body()->firstChild());
+ auto* first = To<Element>(form->firstChild());
+ auto* last = To<Element>(form->lastChild());
Element* next = GetFocusController().NextFocusableElementInForm(
first, kWebFocusTypeForward);
diff --git a/chromium/third_party/blink/renderer/core/page/frame_tree.cc b/chromium/third_party/blink/renderer/core/page/frame_tree.cc
index c944b99eeb7..b35e797ece4 100644
--- a/chromium/third_party/blink/renderer/core/page/frame_tree.cc
+++ b/chromium/third_party/blink/renderer/core/page/frame_tree.cc
@@ -27,12 +27,11 @@
#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/use_counter.h"
#include "third_party/blink/renderer/core/page/chrome_client.h"
#include "third_party/blink/renderer/core/page/create_window.h"
#include "third_party/blink/renderer/core/page/page.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
-#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
using std::swap;
@@ -377,7 +376,7 @@ static void printFrames(const blink::Frame* frame,
printIndent(indent);
printf(" uri=%s\n\n",
local_frame
- ? local_frame->GetDocument()->Url().GetString().Utf8().data()
+ ? local_frame->GetDocument()->Url().GetString().Utf8().c_str()
: nullptr);
for (blink::Frame* child = frame->Tree().FirstChild(); child;
diff --git a/chromium/third_party/blink/renderer/core/page/page.cc b/chromium/third_party/blink/renderer/core/page/page.cc
index 0f8ae2090eb..d3f15ac9569 100644
--- a/chromium/third_party/blink/renderer/core/page/page.cc
+++ b/chromium/third_party/blink/renderer/core/page/page.cc
@@ -200,7 +200,8 @@ Page::Page(PageClients& page_clients)
subframe_count_(0),
next_related_page_(this),
prev_related_page_(this),
- autoplay_flags_(0) {
+ autoplay_flags_(0),
+ web_text_autosizer_page_info_({0, 0, 1.f}) {
DCHECK(!AllPages().Contains(this));
AllPages().insert(this);
}
@@ -589,10 +590,11 @@ void Page::SettingsChanged(SettingsDelegate::ChangeType change_type) {
->GetDocument()
->GetViewportData()
.UpdateViewportDescription();
- // The text autosizer has dependencies on the viewport.
- if (TextAutosizer* text_autosizer =
- DeprecatedLocalMainFrame()->GetDocument()->GetTextAutosizer())
- text_autosizer->UpdatePageInfoInAllFrames();
+ // The text autosizer has dependencies on the viewport. Viewport
+ // description only applies to the main frame. On a viewport description
+ // change; any changes will be calculated starting from the local main
+ // frame renderer and propagated to the OOPIF renderers.
+ TextAutosizer::UpdatePageInfoInAllFrames(MainFrame());
}
break;
case SettingsDelegate::kViewportScrollbarChange:
@@ -617,11 +619,11 @@ void Page::SettingsChanged(SettingsDelegate::ChangeType change_type) {
}
break;
case SettingsDelegate::kTextAutosizingChange:
- if (!MainFrame() || !MainFrame()->IsLocalFrame())
+ if (!MainFrame())
break;
- if (TextAutosizer* text_autosizer =
- DeprecatedLocalMainFrame()->GetDocument()->GetTextAutosizer())
- text_autosizer->UpdatePageInfoInAllFrames();
+ // We need to update even for remote main frames since this setting
+ // could be changed via InternalSettings.
+ TextAutosizer::UpdatePageInfoInAllFrames(MainFrame());
break;
case SettingsDelegate::kFontFamilyChange:
for (Frame* frame = MainFrame(); frame;
diff --git a/chromium/third_party/blink/renderer/core/page/page.h b/chromium/third_party/blink/renderer/core/page/page.h
index eb5e930c465..cc3fa3e02fa 100644
--- a/chromium/third_party/blink/renderer/core/page/page.h
+++ b/chromium/third_party/blink/renderer/core/page/page.h
@@ -26,6 +26,7 @@
#include <memory>
#include "base/macros.h"
+#include "third_party/blink/public/platform/web_text_autosizer_page_info.h"
#include "third_party/blink/public/web/web_window_features.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/frame/deprecation.h"
@@ -318,6 +319,13 @@ class CORE_EXPORT Page final : public GarbageCollectedFinalized<Page>,
void SetInsidePortal(bool inside_portal);
bool InsidePortal() const;
+ void SetTextAutosizePageInfo(const WebTextAutosizerPageInfo& page_info) {
+ web_text_autosizer_page_info_ = page_info;
+ }
+ const WebTextAutosizerPageInfo& TextAutosizerPageInfo() const {
+ return web_text_autosizer_page_info_;
+ }
+
private:
friend class ScopedPagePauser;
@@ -419,6 +427,8 @@ class CORE_EXPORT Page final : public GarbageCollectedFinalized<Page>,
// Accessed by frames to determine whether to expose the PortalHost object.
bool inside_portal_ = false;
+ WebTextAutosizerPageInfo web_text_autosizer_page_info_;
+
DISALLOW_COPY_AND_ASSIGN(Page);
};
diff --git a/chromium/third_party/blink/renderer/core/page/page_popup_client.h b/chromium/third_party/blink/renderer/core/page/page_popup_client.h
index 0d46cf36bfa..98ee6143335 100644
--- a/chromium/third_party/blink/renderer/core/page/page_popup_client.h
+++ b/chromium/third_party/blink/renderer/core/page/page_popup_client.h
@@ -34,7 +34,7 @@
#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/shared_buffer.h"
-#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
+#include "third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
@@ -94,8 +94,8 @@ class CORE_EXPORT PagePopupClient {
};
inline void PagePopupClient::AddString(const String& str, SharedBuffer* data) {
- CString str8 = str.Utf8();
- data->Append(str8.data(), str8.length());
+ StringUTF8Adaptor utf8(str);
+ data->Append(utf8.data(), utf8.size());
}
} // namespace blink
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 8006218d46a..d0777576a07 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
@@ -36,7 +36,7 @@
#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/input/event_handler.h"
-#include "third_party/blink/renderer/core/layout/jank_tracker.h"
+#include "third_party/blink/renderer/core/layout/layout_shift_tracker.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/page/autoscroll_controller.h"
#include "third_party/blink/renderer/core/page/page.h"
@@ -86,7 +86,7 @@ WebInputEventResult PageWidgetDelegate::HandleInputEvent(
Document* document = root->GetDocument();
DCHECK(document);
if (LocalFrameView* view = document->View())
- view->GetJankTracker().NotifyInput(event);
+ view->GetLayoutShiftTracker().NotifyInput(event);
}
if (event.GetModifiers() & WebInputEvent::kIsTouchAccessibility &&
@@ -210,8 +210,8 @@ WebInputEventResult PageWidgetDelegate::HandleInputEvent(
void PageWidgetEventHandler::HandleMouseMove(
LocalFrame& main_frame,
const WebMouseEvent& event,
- const std::vector<const WebInputEvent*>& coalesced_events,
- const std::vector<const WebInputEvent*>& predicted_events) {
+ const WebVector<const WebInputEvent*>& coalesced_events,
+ const WebVector<const WebInputEvent*>& predicted_events) {
WebMouseEvent transformed_event =
TransformWebMouseEvent(main_frame.View(), event);
main_frame.GetEventHandler().HandleMouseMoveEvent(
@@ -252,8 +252,8 @@ WebInputEventResult PageWidgetEventHandler::HandleMouseWheel(
WebInputEventResult PageWidgetEventHandler::HandlePointerEvent(
LocalFrame& main_frame,
const WebPointerEvent& event,
- const std::vector<const WebInputEvent*>& coalesced_events,
- const std::vector<const WebInputEvent*>& predicted_events) {
+ const WebVector<const WebInputEvent*>& coalesced_events,
+ const WebVector<const WebInputEvent*>& predicted_events) {
WebPointerEvent transformed_event =
TransformWebPointerEvent(main_frame.View(), event);
return main_frame.GetEventHandler().HandlePointerEvent(
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 d5effcc5725..645d4acb280 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
@@ -34,7 +34,7 @@
#include "third_party/blink/public/platform/web_coalesced_input_event.h"
#include "third_party/blink/public/web/web_widget.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
class LocalFrame;
@@ -50,8 +50,8 @@ class CORE_EXPORT PageWidgetEventHandler {
public:
virtual void HandleMouseMove(LocalFrame& main_frame,
const WebMouseEvent&,
- const std::vector<const WebInputEvent*>&,
- const std::vector<const WebInputEvent*>&);
+ const WebVector<const WebInputEvent*>&,
+ const WebVector<const WebInputEvent*>&);
virtual void HandleMouseLeave(LocalFrame& main_frame, const WebMouseEvent&);
virtual void HandleMouseDown(LocalFrame& main_frame, const WebMouseEvent&);
virtual void HandleMouseUp(LocalFrame& main_frame, const WebMouseEvent&);
@@ -63,8 +63,8 @@ class CORE_EXPORT PageWidgetEventHandler {
virtual WebInputEventResult HandlePointerEvent(
LocalFrame& main_frame,
const WebPointerEvent&,
- const std::vector<const WebInputEvent*>&,
- const std::vector<const WebInputEvent*>&);
+ const WebVector<const WebInputEvent*>&,
+ const WebVector<const WebInputEvent*>&);
virtual ~PageWidgetEventHandler() {}
};
diff --git a/chromium/third_party/blink/renderer/core/page/plugin_data.cc b/chromium/third_party/blink/renderer/core/page/plugin_data.cc
index 89a12219de6..53a38094530 100644
--- a/chromium/third_party/blink/renderer/core/page/plugin_data.cc
+++ b/chromium/third_party/blink/renderer/core/page/plugin_data.cc
@@ -120,12 +120,12 @@ void PluginData::UpdatePluginList(const SecurityOrigin* main_frame_origin) {
std::sort(
plugins_.begin(), plugins_.end(),
[](const Member<PluginInfo>& lhs, const Member<PluginInfo>& rhs) -> bool {
- return WTF::CodePointCompareLessThan(lhs->Name(), rhs->Name());
+ return WTF::CodeUnitCompareLessThan(lhs->Name(), rhs->Name());
});
std::sort(mimes_.begin(), mimes_.end(),
[](const Member<MimeClassInfo>& lhs,
const Member<MimeClassInfo>& rhs) -> bool {
- return WTF::CodePointCompareLessThan(lhs->Type(), rhs->Type());
+ return WTF::CodeUnitCompareLessThan(lhs->Type(), rhs->Type());
});
}
diff --git a/chromium/third_party/blink/renderer/core/page/plugin_script_forbidden_scope.h b/chromium/third_party/blink/renderer/core/page/plugin_script_forbidden_scope.h
index b7491a265f7..8ee2203cb13 100644
--- a/chromium/third_party/blink/renderer/core/page/plugin_script_forbidden_scope.h
+++ b/chromium/third_party/blink/renderer/core/page/plugin_script_forbidden_scope.h
@@ -7,7 +7,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 869c3485f46..5b281c7ed7a 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
@@ -132,10 +132,18 @@ void PointerLockController::DidNotAcquirePointerLock() {
}
void PointerLockController::DidLosePointerLock() {
- EnqueueEvent(
- event_type_names::kPointerlockchange,
+ Document* pointer_lock_document =
element_ ? &element_->GetDocument()
- : document_of_removed_element_while_waiting_for_unlock_.Get());
+ : document_of_removed_element_while_waiting_for_unlock_.Get();
+ EnqueueEvent(event_type_names::kPointerlockchange, pointer_lock_document);
+
+ // Set the last mouse position back the locked position.
+ if (pointer_lock_document && pointer_lock_document->GetFrame()) {
+ pointer_lock_document->GetFrame()
+ ->GetEventHandler()
+ .ResetMousePositionForPointerUnlock();
+ }
+
ClearElement();
document_of_removed_element_while_waiting_for_unlock_ = nullptr;
}
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 358bebb64f8..2c91f87a726 100644
--- a/chromium/third_party/blink/renderer/core/page/print_context.cc
+++ b/chromium/third_party/blink/renderer/core/page/print_context.cc
@@ -204,10 +204,10 @@ void PrintContext::CollectLinkedDestinations(Node* node) {
for (Node* i = node->firstChild(); i; i = i->nextSibling())
CollectLinkedDestinations(i);
- if (!node->IsLink() || !node->IsElementNode())
+ auto* element = DynamicTo<Element>(node);
+ if (!node->IsLink() || !element)
return;
- const AtomicString& href =
- ToElement(node)->getAttribute(html_names::kHrefAttr);
+ const AtomicString& href = element->getAttribute(html_names::kHrefAttr);
if (href.IsNull())
return;
KURL url = node->GetDocument().CompleteURL(href);
@@ -251,7 +251,8 @@ String PrintContext::PageProperty(LocalFrame* frame,
// want to collect @page rules and figure out what declarations apply on a
// given page (that may or may not exist).
print_context->BeginPrintMode(800, 1000);
- scoped_refptr<ComputedStyle> style = document->StyleForPage(page_number);
+ scoped_refptr<const ComputedStyle> style =
+ document->StyleForPage(page_number);
// Implement formatters for properties we care about.
if (!strcmp(property_name, "margin-left")) {
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 6487b77f59b..b14acfddfeb 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
@@ -6,8 +6,10 @@
#include <memory>
+#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/core/dom/document.h"
+#include "third_party/blink/renderer/core/events/before_print_event.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/html/html_element.h"
@@ -24,6 +26,8 @@
#include "third_party/blink/renderer/platform/wtf/text/text_stream.h"
#include "third_party/skia/include/core/SkCanvas.h"
+using testing::_;
+
namespace blink {
const int kPageWidth = 800;
@@ -60,6 +64,22 @@ class MockPageContextCanvas : public SkCanvas {
return recorded_operations_;
}
+ MOCK_METHOD2(onDrawRect, void(const SkRect&, const SkPaint&));
+ MOCK_METHOD1(DrawPicture, void(const SkPicture*));
+ MOCK_METHOD1(OnDrawPicture, void(const SkPicture*));
+ MOCK_METHOD3(OnDrawPicture,
+ void(const SkPicture*, const SkMatrix*, const SkPaint*));
+ MOCK_METHOD3(DrawPicture,
+ void(const SkPicture*, const SkMatrix*, const SkPaint*));
+ MOCK_METHOD4(onDrawImage,
+ void(const SkImage*, SkScalar, SkScalar, const SkPaint*));
+ MOCK_METHOD5(onDrawImageRect,
+ void(const SkImage*,
+ const SkRect*,
+ const SkRect&,
+ const SkPaint*,
+ SrcRectConstraint));
+
private:
Vector<Operation> recorded_operations_;
};
@@ -84,8 +104,11 @@ class PrintContextTest : public PaintTestConfigurations, public RenderingTest {
GetDocument().body()->SetInnerHTMLFromString(body_content);
}
- void PrintSinglePage(MockPageContextCanvas& canvas) {
+ void PrintSinglePage(SkCanvas& canvas) {
IntRect page_rect(0, 0, kPageWidth, kPageHeight);
+ GetDocument().SetPrinting(Document::kBeforePrinting);
+ Event* event = MakeGarbageCollected<BeforePrintEvent>();
+ GetPrintContext().GetFrame()->DomWindow()->DispatchEvent(*event);
GetPrintContext().BeginPrintMode(page_rect.Width(), page_rect.Height());
UpdateAllLifecyclePhasesForTest();
PaintRecordBuilder builder;
@@ -396,6 +419,46 @@ TEST_P(PrintContextFrameTest, BasicPrintPageLayout) {
EXPECT_EQ(node->OffsetWidth(), 800);
}
+TEST_P(PrintContextTest, Canvas2DBeforePrint) {
+ MockPageContextCanvas canvas;
+ SetBodyInnerHTML("<canvas id='c' width=100 height=100></canvas>");
+ GetDocument().GetSettings()->SetScriptEnabled(true);
+ Element* const script_element =
+ GetDocument().CreateRawElement(html_names::kScriptTag);
+ script_element->setTextContent(
+ "window.addEventListener('beforeprint', (ev) => {"
+ "const ctx = document.getElementById('c').getContext('2d');"
+ "ctx.fillRect(0, 0, 10, 10);"
+ "ctx.fillRect(50, 50, 10, 10);"
+ "});");
+ GetDocument().body()->AppendChild(script_element);
+
+ EXPECT_CALL(canvas, onDrawRect(_, _)).Times(testing::AtLeast(2));
+
+ PrintSinglePage(canvas);
+}
+
+TEST_P(PrintContextTest, Canvas2DPixelated) {
+ MockPageContextCanvas canvas;
+ SetBodyInnerHTML(
+ "<canvas id='c' style='image-rendering: pixelated' "
+ "width=100 height=100></canvas>");
+ GetDocument().GetSettings()->SetScriptEnabled(true);
+ Element* const script_element =
+ GetDocument().CreateRawElement(html_names::kScriptTag);
+ script_element->setTextContent(
+ "window.addEventListener('beforeprint', (ev) => {"
+ "const ctx = document.getElementById('c').getContext('2d');"
+ "ctx.fillRect(0, 0, 10, 10);"
+ "ctx.fillRect(50, 50, 10, 10);"
+ "});");
+ GetDocument().body()->AppendChild(script_element);
+
+ EXPECT_CALL(canvas, onDrawImageRect(_, _, _, _, _));
+
+ PrintSinglePage(canvas);
+}
+
// This tests that we don't resize or re-layout subframes in printed content.
// TODO(weili): This test fails when the iframe isn't the root scroller - e.g.
// Adding ScopedImplicitRootScrollerForTest disabler(false);
diff --git a/chromium/third_party/blink/renderer/core/page/scoped_page_pauser.h b/chromium/third_party/blink/renderer/core/page/scoped_page_pauser.h
index 21e6ada2208..5e34428fc00 100644
--- a/chromium/third_party/blink/renderer/core/page/scoped_page_pauser.h
+++ b/chromium/third_party/blink/renderer/core/page/scoped_page_pauser.h
@@ -23,7 +23,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/element_fragment_anchor.cc b/chromium/third_party/blink/renderer/core/page/scrolling/element_fragment_anchor.cc
index a2d7b1d89e4..085d5aa2741 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/element_fragment_anchor.cc
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/element_fragment_anchor.cc
@@ -62,9 +62,7 @@ ElementFragmentAnchor* ElementFragmentAnchor::TryCreate(const KURL& url,
}
// Setting to null will clear the current target.
- Element* target = anchor_node && anchor_node->IsElementNode()
- ? ToElement(anchor_node)
- : nullptr;
+ auto* target = DynamicTo<Element>(anchor_node);
doc.SetCSSTarget(target);
if (doc.IsSVGDocument()) {
@@ -115,9 +113,10 @@ bool ElementFragmentAnchor::Invoke() {
boundary_local_frame->View()->SetSafeToPropagateScrollToParent(false);
}
- Element* element_to_scroll = anchor_node_->IsElementNode()
- ? ToElement(anchor_node_)
- : doc.documentElement();
+ auto* element_to_scroll = DynamicTo<Element>(anchor_node_.Get());
+ if (!element_to_scroll)
+ element_to_scroll = doc.documentElement();
+
if (element_to_scroll) {
ScrollIntoViewOptions* options = ScrollIntoViewOptions::Create();
options->setBlock("start");
@@ -202,8 +201,9 @@ void ElementFragmentAnchor::ApplyFocusIfNeeded() {
// If anchorNode is not focusable or fragment scrolling is not allowed,
// clear focus, which matches the behavior of other browsers.
frame_->GetDocument()->UpdateStyleAndLayoutTree();
- if (anchor_node_->IsElementNode() && ToElement(anchor_node_)->IsFocusable()) {
- ToElement(anchor_node_)->focus();
+ auto* element = DynamicTo<Element>(anchor_node_.Get());
+ if (element && element->IsFocusable()) {
+ element->focus();
} else {
frame_->GetDocument()->SetSequentialFocusNavigationStartingPoint(
anchor_node_);
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/fragment_anchor.cc b/chromium/third_party/blink/renderer/core/page/scrolling/fragment_anchor.cc
index 2c238008962..caf3e53f6a5 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/fragment_anchor.cc
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/fragment_anchor.cc
@@ -4,6 +4,7 @@
#include "third_party/blink/renderer/core/page/scrolling/fragment_anchor.h"
+#include "base/metrics/histogram_macros.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/page/scrolling/element_fragment_anchor.h"
#include "third_party/blink/renderer/core/page/scrolling/text_fragment_anchor.h"
@@ -14,15 +15,57 @@ namespace blink {
FragmentAnchor* FragmentAnchor::TryCreate(const KURL& url,
LocalFrame& frame,
bool same_document_navigation) {
+ DCHECK(frame.GetDocument());
+
FragmentAnchor* anchor = nullptr;
+ const bool text_fragment_identifiers_enabled =
+ RuntimeEnabledFeatures::TextFragmentIdentifiersEnabled(
+ frame.GetDocument());
+
+ // The text fragment anchor will be created if we successfully parsed the
+ // targetText but we only do the text matching later on.
+ bool text_fragment_anchor_created = false;
+ if (text_fragment_identifiers_enabled) {
+ anchor = TextFragmentAnchor::TryCreateFragmentDirective(
+ url, frame, same_document_navigation);
+ text_fragment_anchor_created = anchor;
+ }
+
+ // Count how often we see a # in the fragment (i.e. after the # delimiting
+ // the hash). We do this after trying to find a ##targetText so that we don't
+ // pollute this metric with our own feature since we're trying to determine
+ // how prevalent ## is. If a ##targetText is found, it'll strip off the ##
+ // and any text following it.
+ if (url.HasFragmentIdentifier()) {
+ size_t hash_pos = url.FragmentIdentifier().Find("#");
+ if (hash_pos != kNotFound)
+ UseCounter::Count(frame.GetDocument(), WebFeature::kFragmentDoubleHash);
+ }
- anchor = ElementFragmentAnchor::TryCreate(url, frame);
+ bool element_id_anchor_found = false;
if (!anchor) {
- if (RuntimeEnabledFeatures::TextFragmentIdentifiersEnabled(
- frame.GetDocument())) {
- anchor =
- TextFragmentAnchor::TryCreate(url, frame, same_document_navigation);
- }
+ anchor = ElementFragmentAnchor::TryCreate(url, frame);
+ element_id_anchor_found = anchor;
+ }
+
+ if (text_fragment_identifiers_enabled) {
+ FragmentAnchor* text_anchor =
+ TextFragmentAnchor::TryCreate(url, frame, same_document_navigation);
+ text_fragment_anchor_created |= static_cast<bool>(text_anchor);
+ // We parse the anchor to determine if we should report the UMA metric
+ // below but we should only use it if we didn't find an element-id based
+ // fragment.
+ if (!anchor)
+ anchor = text_anchor;
+ }
+
+ // Track how often we have a element fragment that we can't find. Only track
+ // if we didn't match a text fragment since we expect those would inflate the
+ // "failed" case.
+ if (frame.GetDocument()->IsHTMLDocument() && url.HasFragmentIdentifier() &&
+ !text_fragment_anchor_created) {
+ UMA_HISTOGRAM_BOOLEAN("TextFragmentAnchor.ElementIdFragmentFound",
+ element_id_anchor_found);
}
return anchor;
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/main_thread_scrolling_reasons_test.cc b/chromium/third_party/blink/renderer/core/page/scrolling/main_thread_scrolling_reasons_test.cc
index 2b62015ddf7..d78c20cf502 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/main_thread_scrolling_reasons_test.cc
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/main_thread_scrolling_reasons_test.cc
@@ -56,12 +56,13 @@ class MainThreadScrollingReasonsTest
->UnregisterAllURLsAndClearMemoryCache();
}
- void NavigateTo(const std::string& url) {
- frame_test_helpers::LoadFrame(GetWebView()->MainFrameImpl(), url);
+ void NavigateTo(const String& url) {
+ frame_test_helpers::LoadFrame(GetWebView()->MainFrameImpl(), url.Utf8());
}
- void LoadHTML(const std::string& html) {
- frame_test_helpers::LoadHTMLString(GetWebView()->MainFrameImpl(), html,
+ void LoadHTML(const String& html) {
+ frame_test_helpers::LoadHTMLString(GetWebView()->MainFrameImpl(),
+ html.Utf8(),
url_test_helpers::ToKURL("about:blank"));
}
@@ -70,10 +71,9 @@ class MainThreadScrollingReasonsTest
WebWidget::LifecycleUpdateReason::kTest);
}
- void RegisterMockedHttpURLLoad(const std::string& file_name) {
+ void RegisterMockedHttpURLLoad(const String& file_name) {
url_test_helpers::RegisterMockedURLLoadFromBase(
- WebString::FromUTF8(base_url_), test::CoreTestDataPath(),
- WebString::FromUTF8(file_name));
+ WebString(base_url_), test::CoreTestDataPath(), WebString(file_name));
}
uint32_t GetViewMainThreadScrollingReasons() const {
@@ -98,7 +98,7 @@ class MainThreadScrollingReasonsTest
LocalFrame* GetFrame() const { return helper_.LocalMainFrame()->GetFrame(); }
protected:
- std::string base_url_;
+ String base_url_;
private:
static void ConfigureSettings(WebSettings* settings) {
@@ -324,12 +324,12 @@ class NonCompositedMainThreadScrollingReasonsTest
RegisterMockedHttpURLLoad("two_scrollable_area.html");
NavigateTo(base_url_ + "two_scrollable_area.html");
}
- void TestNonCompositedReasons(const std::string& target,
- const uint32_t reason) {
+ void TestNonCompositedReasons(const String& target, const uint32_t reason) {
GetWebView()->GetSettings()->SetPreferCompositingToLCDTextEnabled(false);
Document* document = GetFrame()->GetDocument();
Element* container = document->getElementById("scroller1");
- container->setAttribute("class", target.c_str(), ASSERT_NO_EXCEPTION);
+ container->setAttribute("class", target.Utf8().c_str(),
+ ASSERT_NO_EXCEPTION);
ForceFullCompositingUpdate();
PaintLayerScrollableArea* scrollable_area =
@@ -362,7 +362,8 @@ class NonCompositedMainThreadScrollingReasonsTest
EXPECT_FALSE(frame_view->GetMainThreadScrollingReasons() & reason);
// Add target attribute would again lead to scroll on main thread
- container->setAttribute("class", target.c_str(), ASSERT_NO_EXCEPTION);
+ container->setAttribute("class", target.Utf8().c_str(),
+ ASSERT_NO_EXCEPTION);
ForceFullCompositingUpdate();
EXPECT_TRUE(scrollable_area->GetNonCompositedMainThreadScrollingReasons() &
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 66a66f41e05..2d30e629e41 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,7 +9,6 @@
#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"
@@ -25,6 +24,7 @@
#include "third_party/blink/renderer/core/scroll/scrollable_area.h"
#include "third_party/blink/renderer/platform/graphics/graphics_layer.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
@@ -426,13 +426,14 @@ void RootScrollerController::ConsiderForImplicit(Node& node) {
if (document_->GetPage()->GetChromeClient().IsPopup())
return;
- if (!node.IsElementNode())
+ auto* element = DynamicTo<Element>(node);
+ if (!element)
return;
- if (!IsValidImplicitCandidate(ToElement(node)))
+ if (!IsValidImplicitCandidate(*element))
return;
- implicit_candidates_.insert(&ToElement(node));
+ implicit_candidates_.insert(element);
}
template <typename Function>
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 edda6359525..3995159daff 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
@@ -11,7 +11,7 @@
#include "third_party/blink/public/web/web_remote_frame.h"
#include "third_party/blink/public/web/web_script_source.h"
#include "third_party/blink/public/web/web_settings.h"
-#include "third_party/blink/renderer/bindings/core/v8/node_or_string.h"
+#include "third_party/blink/renderer/bindings/core/v8/node_or_string_or_trusted_script.h"
#include "third_party/blink/renderer/core/exported/web_remote_frame_impl.h"
#include "third_party/blink/renderer/core/frame/browser_controls.h"
#include "third_party/blink/renderer/core/frame/dom_visual_viewport.h"
@@ -78,12 +78,12 @@ class RootScrollerTest : public testing::Test,
}
}
- WebViewImpl* Initialize(const std::string& page_name,
+ WebViewImpl* Initialize(const String& page_name,
frame_test_helpers::TestWebWidgetClient* client) {
return InitializeInternal(base_url_ + page_name, client);
}
- WebViewImpl* Initialize(const std::string& page_name) {
+ WebViewImpl* Initialize(const String& page_name) {
return InitializeInternal(base_url_ + page_name, nullptr);
}
@@ -101,10 +101,9 @@ class RootScrollerTest : public testing::Test,
settings->SetMainFrameResizesAreOrientationChanges(true);
}
- void RegisterMockedHttpURLLoad(const std::string& file_name) {
+ void RegisterMockedHttpURLLoad(const String& file_name) {
url_test_helpers::RegisterMockedURLLoadFromBase(
- WebString::FromUTF8(base_url_), test::CoreTestDataPath(),
- WebString::FromUTF8(file_name));
+ WebString(base_url_), test::CoreTestDataPath(), WebString(file_name));
}
void ExecuteScript(const WebString& code) {
@@ -177,9 +176,9 @@ class RootScrollerTest : public testing::Test,
}
WebViewImpl* InitializeInternal(
- const std::string& url,
+ const String& url,
frame_test_helpers::TestWebWidgetClient* client) {
- helper_.InitializeAndLoad(url, nullptr, nullptr, client,
+ helper_.InitializeAndLoad(url.Utf8(), nullptr, nullptr, client,
&ConfigureSettings);
// Initialize browser controls to be shown.
@@ -196,7 +195,7 @@ class RootScrollerTest : public testing::Test,
DocumentLifecycle::LifecycleUpdateReason::kTest);
}
- std::string base_url_;
+ String base_url_;
std::unique_ptr<frame_test_helpers::TestWebViewClient> view_client_;
frame_test_helpers::WebViewHelper helper_;
RuntimeEnabledFeatures::Backup features_backup_;
@@ -226,8 +225,8 @@ TEST_F(RootScrollerTest, defaultEffectiveRootScrollerIsDocumentNode) {
// Replace the documentElement with the iframe. The effectiveRootScroller
// should remain the same.
- HeapVector<NodeOrString> nodes;
- nodes.push_back(NodeOrString::FromNode(iframe));
+ HeapVector<NodeOrStringOrTrustedScript> nodes;
+ nodes.push_back(NodeOrStringOrTrustedScript::FromNode(iframe));
document->documentElement()->ReplaceWith(nodes, ASSERT_NO_EXCEPTION);
UpdateAllLifecyclePhases(MainFrameView());
@@ -800,8 +799,8 @@ TEST_F(RootScrollerTest, RemoteMainFrame) {
WebSecurityOrigin(SecurityOrigin::CreateUniqueOpaque()), false);
local_frame = frame_test_helpers::CreateLocalChild(*remote_main_frame);
- frame_test_helpers::LoadFrame(local_frame,
- base_url_ + "root-scroller-child.html");
+ frame_test_helpers::LoadFrame(
+ local_frame, base_url_.Utf8() + "root-scroller-child.html");
widget = local_frame->FrameWidget();
widget->Resize(WebSize(400, 400));
}
@@ -1614,7 +1613,7 @@ TEST_F(ImplicitRootScrollerSimTest, ImplicitRootScroller) {
// overflow: auto and overflow: scroll should cause a valid element to be
// promoted to root scroller. Otherwise, they shouldn't, even if they're
// otherwise a valid root scroller element.
- std::vector<std::tuple<String, String, Node*>> test_cases = {
+ Vector<std::tuple<String, String, Node*>> test_cases = {
{"overflow", "hidden", &GetDocument()},
{"overflow", "auto", container},
{"overflow", "scroll", container},
@@ -2551,6 +2550,121 @@ TEST_F(ImplicitRootScrollerSimTest, PromotionChangesLayoutSize) {
<< "Once loaded, the iframe should be promoted.";
}
+// Tests that bottom-fixed objects inside of an iframe root scroller and frame
+// are marked as being affected by top controls movement. Those inside a
+// non-rootScroller iframe should not be marked as such.
+TEST_F(ImplicitRootScrollerSimTest, BottomFixedAffectedByTopControls) {
+ WebView().ResizeWithBrowserControls(IntSize(800, 650), 50, 0, false);
+ SimRequest main_request("https://example.com/test.html", "text/html");
+ SimRequest child_request1("https://example.com/child1.html", "text/html");
+ SimRequest child_request2("https://example.com/child2.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;
+ }
+ #container1 {
+ width: 100%;
+ height: 100%;
+ border: 0;
+ }
+ #container2 {
+ position: absolute;
+ width: 10px;
+ height: 10px;
+ left: 100px;
+ top: 100px;
+ border: 0;
+ }
+ #fixed {
+ position: fixed;
+ bottom: 10px;
+ left: 10px;
+ width: 10px;
+ height: 10px;
+ background-color: red;
+ }
+ </style>
+ <iframe id="container1" src="child1.html">
+ </iframe>
+ <iframe id="container2" src="child2.html">
+ </iframe>
+ <div id="fixed"></div>
+ )HTML");
+ child_request1.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ body {
+ height: 1000px;
+ }
+ #fixed {
+ width: 50px;
+ height: 50px;
+ position: fixed;
+ bottom: 0px;
+ left: 0px;
+ }
+ </style>
+ <div id="fixed"></div>
+ )HTML");
+ child_request2.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ body {
+ height: 1000px;
+ }
+ #fixed {
+ width: 50px;
+ height: 50px;
+ position: fixed;
+ bottom: 0px;
+ left: 0px;
+ }
+ </style>
+ <div id="fixed"></div>
+ )HTML");
+
+ Compositor().BeginFrame();
+
+ Element* container1 = GetDocument().getElementById("container1");
+ Element* container2 = GetDocument().getElementById("container2");
+ ASSERT_EQ(container1,
+ GetDocument().GetRootScrollerController().EffectiveRootScroller())
+ << "The #container1 iframe must be promoted.";
+
+ Document* child1_document =
+ To<HTMLFrameOwnerElement>(container1)->contentDocument();
+ Document* child2_document =
+ To<HTMLFrameOwnerElement>(container2)->contentDocument();
+ LayoutObject* fixed =
+ GetDocument().getElementById("fixed")->GetLayoutObject();
+ LayoutObject* fixed1 =
+ child1_document->getElementById("fixed")->GetLayoutObject();
+ LayoutObject* fixed2 =
+ child2_document->getElementById("fixed")->GetLayoutObject();
+
+ EXPECT_TRUE(fixed->FirstFragment()
+ .ContentsProperties()
+ .Transform()
+ .IsAffectedByOuterViewportBoundsDelta());
+ EXPECT_TRUE(fixed1->FirstFragment()
+ .ContentsProperties()
+ .Transform()
+ .IsAffectedByOuterViewportBoundsDelta());
+ EXPECT_FALSE(fixed2->FirstFragment()
+ .ContentsProperties()
+ .Transform()
+ .IsAffectedByOuterViewportBoundsDelta());
+}
+
// Ensure that we're using the content box for an iframe. Promotion will cause
// the content to use the layout size of the parent frame so having padding or
// a border would cause us to relayout.
@@ -2824,7 +2938,7 @@ TEST_F(ImplicitRootScrollerSimTest, ClippingAncestorPreventsPromotion) {
Compositor().BeginFrame();
// Each of these style-value pairs should prevent promotion of the iframe.
- std::vector<std::tuple<String, String>> test_cases = {
+ Vector<std::tuple<String, String>> test_cases = {
{"overflow", "scroll"},
{"overflow", "hidden"},
{"overflow", "auto"},
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 3ae7c5000aa..02c528dafb7 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
@@ -171,7 +171,7 @@ TEST_F(ScrollIntoViewTest, SmoothScroll) {
Compositor().BeginFrame(); // update run_state_.
Compositor().BeginFrame(); // Set start_time = now.
Compositor().BeginFrame(0.2);
- ASSERT_EQ(Window().scrollY(), 299);
+ ASSERT_NEAR(Window().scrollY(), 299, 1);
// Finish scrolling the container
Compositor().BeginFrame(1);
@@ -207,7 +207,7 @@ TEST_F(ScrollIntoViewTest, NestedContainer) {
Compositor().BeginFrame(); // update run_state_.
Compositor().BeginFrame(); // Set start_time = now.
Compositor().BeginFrame(0.2);
- ASSERT_EQ(Window().scrollY(), 299);
+ ASSERT_NEAR(Window().scrollY(), 299, 1);
ASSERT_EQ(container->scrollTop(), 0);
// Finish scrolling the outer container
@@ -218,7 +218,7 @@ TEST_F(ScrollIntoViewTest, NestedContainer) {
// Scrolling the inner container
Compositor().BeginFrame(); // Set start_time = now.
Compositor().BeginFrame(0.2);
- ASSERT_EQ(container->scrollTop(), 299);
+ ASSERT_NEAR(container->scrollTop(), 299, 1);
// Finish scrolling the inner container
Compositor().BeginFrame(1);
@@ -261,14 +261,14 @@ TEST_F(ScrollIntoViewTest, NewScrollIntoViewAbortsCurrentAnimation) {
Compositor().BeginFrame(); // update run_state_.
Compositor().BeginFrame(); // Set start_time = now.
Compositor().BeginFrame(0.2);
- ASSERT_EQ(Window().scrollY(), 299);
+ ASSERT_NEAR(Window().scrollY(), 299, 1);
ASSERT_EQ(container1->scrollTop(), 0);
content2->scrollIntoView(arg);
Compositor().BeginFrame(); // update run_state_.
Compositor().BeginFrame(); // Set start_time = now.
Compositor().BeginFrame(0.2);
- ASSERT_EQ(Window().scrollY(), 61);
+ ASSERT_NEAR(Window().scrollY(), 61, 1);
ASSERT_EQ(container1->scrollTop(), 0); // container1 should not scroll.
Compositor().BeginFrame(1);
@@ -278,7 +278,7 @@ TEST_F(ScrollIntoViewTest, NewScrollIntoViewAbortsCurrentAnimation) {
// Scrolling content2 in container2
Compositor().BeginFrame(); // Set start_time = now.
Compositor().BeginFrame(0.2);
- ASSERT_EQ(container2->scrollTop(), 300);
+ ASSERT_NEAR(container2->scrollTop(), 300, 1);
// Finish all the animation to make sure there is no another animation queued
// on container1.
@@ -320,7 +320,7 @@ TEST_F(ScrollIntoViewTest, ScrollWindowAbortsCurrentAnimation) {
Compositor().BeginFrame(); // update run_state_.
Compositor().BeginFrame(); // Set start_time = now.
Compositor().BeginFrame(0.2);
- ASSERT_EQ(Window().scrollY(), 299);
+ ASSERT_NEAR(Window().scrollY(), 299, 1);
ASSERT_EQ(container->scrollTop(), 0);
ScrollToOptions* window_option = ScrollToOptions::Create();
@@ -331,7 +331,7 @@ TEST_F(ScrollIntoViewTest, ScrollWindowAbortsCurrentAnimation) {
Compositor().BeginFrame(); // update run_state_.
Compositor().BeginFrame(); // Set start_time = now.
Compositor().BeginFrame(0.2);
- ASSERT_EQ(Window().scrollY(), 58);
+ ASSERT_NEAR(Window().scrollY(), 58, 1);
Compositor().BeginFrame(1);
ASSERT_EQ(Window().scrollY(), 0);
@@ -435,7 +435,7 @@ TEST_F(ScrollIntoViewTest, SmoothAndInstantInChain) {
Compositor().BeginFrame(); // update run_state_.
Compositor().BeginFrame(); // Set start_time = now.
Compositor().BeginFrame(0.2);
- ASSERT_EQ(container->scrollTop(), 299);
+ ASSERT_NEAR(container->scrollTop(), 299, 1);
// Finish scrolling the container
Compositor().BeginFrame(1);
@@ -468,7 +468,7 @@ TEST_F(ScrollIntoViewTest, SmoothScrollAnchor) {
Compositor().BeginFrame(); // update run_state_.
Compositor().BeginFrame(); // Set start_time = now.
Compositor().BeginFrame(0.2);
- ASSERT_EQ(container->scrollTop(), 299);
+ ASSERT_NEAR(container->scrollTop(), 299, 1);
// Finish scrolling the container
Compositor().BeginFrame(1);
@@ -521,7 +521,7 @@ TEST_F(ScrollIntoViewTest, ApplyRootElementScrollBehaviorToViewport) {
Compositor().BeginFrame(); // update run_state_.
Compositor().BeginFrame(); // Set start_time = now.
Compositor().BeginFrame(0.2);
- ASSERT_EQ(Window().scrollY(), 299);
+ ASSERT_NEAR(Window().scrollY(), 299, 1);
// Finish scrolling the container
Compositor().BeginFrame(1);
@@ -589,7 +589,7 @@ TEST_F(ScrollIntoViewTest, StopAtLayoutViewportOption) {
ScrollAlignment::kAlignLeftAlways, ScrollAlignment::kAlignTopAlways,
kProgrammaticScroll, false, kScrollBehaviorInstant);
params.stop_at_main_frame_layout_viewport = true;
- target->ScrollRectToVisible(LayoutRect(target->AbsoluteBoundingBoxRect()),
+ target->ScrollRectToVisible(PhysicalRect(target->AbsoluteBoundingBoxRect()),
params);
ScrollableArea* root_scroller =
@@ -687,7 +687,7 @@ TEST_F(ScrollIntoViewTest, SmoothUserScrollNotAbortedByProgrammaticScrolls) {
Compositor().BeginFrame(); // update run_state_.
Compositor().BeginFrame(); // Set start_time = now.
Compositor().BeginFrame(0.2);
- ASSERT_EQ(Window().scrollY(), 299);
+ ASSERT_NEAR(Window().scrollY(), 299, 1);
// ProgrammaticScroll that could interrupt the current smooth scroll.
Window().scrollTo(0, 0);
@@ -722,7 +722,7 @@ TEST_F(ScrollIntoViewTest, LongDistanceSmoothScrollFinishedInThreeSeconds) {
Compositor().BeginFrame(); // update run_state_.
Compositor().BeginFrame(); // Set start_time = now.
Compositor().BeginFrame(0.2);
- ASSERT_EQ(Window().scrollY(), 864);
+ ASSERT_NEAR(Window().scrollY(), 864, 1);
// Finish scrolling the container
Compositor().BeginFrame(2.8);
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 8d49e807edf..8cd487ec503 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
@@ -60,7 +60,7 @@ class ScrollBeginEventBuilder : public WebGestureEvent {
WebGestureDevice device)
: WebGestureEvent(WebInputEvent::kGestureScrollBegin,
WebInputEvent::kNoModifiers,
- CurrentTimeTicks(),
+ base::TimeTicks::Now(),
device) {
SetPositionInWidget(position);
SetPositionInScreen(position);
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 24c03a97ca7..862cb34656f 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
@@ -71,9 +71,8 @@ void ScrollState::consumeDelta(double x,
}
void ScrollState::distributeToScrollChainDescendant() {
- if (!scroll_chain_.empty()) {
- DOMNodeId descendant_id = scroll_chain_.front();
- scroll_chain_.pop_front();
+ if (!scroll_chain_.IsEmpty()) {
+ DOMNodeId descendant_id = scroll_chain_.TakeFirst();
NodeForId(descendant_id)->CallDistributeScroll(*this);
}
}
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 517dac96530..ce38f0e33a3 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
@@ -5,7 +5,6 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAGE_SCROLLING_SCROLL_STATE_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAGE_SCROLLING_SCROLL_STATE_H_
-#include <deque>
#include <memory>
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/dom/dom_node_ids.h"
@@ -14,6 +13,7 @@
#include "third_party/blink/renderer/core/scroll/scroll_state_data.h"
#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/wtf/deque.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
namespace blink {
@@ -68,7 +68,7 @@ class CORE_EXPORT ScrollState final : public ScriptWrappable {
void ConsumeDeltaNative(double x, double y);
// TODO(tdresser): this needs to be web exposed. See crbug.com/483091.
- void SetScrollChain(std::deque<DOMNodeId> scroll_chain) {
+ void SetScrollChain(Deque<DOMNodeId> scroll_chain) {
scroll_chain_ = scroll_chain;
}
@@ -97,7 +97,7 @@ class CORE_EXPORT ScrollState final : public ScriptWrappable {
ScrollState() = delete;
std::unique_ptr<ScrollStateData> data_;
- std::deque<DOMNodeId> scroll_chain_;
+ Deque<DOMNodeId> scroll_chain_;
Member<Node> node_;
};
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 daca9a264e5..840f045958b 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
@@ -49,8 +49,7 @@ class ScrollStateCallbackV8Impl : public ScrollStateCallback {
explicit ScrollStateCallbackV8Impl(
V8ScrollStateCallback* callback,
WebNativeScrollBehavior native_scroll_behavior)
- : ScrollStateCallback(native_scroll_behavior),
- callback_(ToV8PersistentCallbackFunction(callback)) {}
+ : ScrollStateCallback(native_scroll_behavior), callback_(callback) {}
~ScrollStateCallbackV8Impl() override = default;
void Trace(blink::Visitor*) override;
@@ -61,7 +60,7 @@ class ScrollStateCallbackV8Impl : public ScrollStateCallback {
static WebNativeScrollBehavior ParseNativeScrollBehavior(
const String& native_scroll_behavior);
- Member<V8PersistentCallbackFunction<V8ScrollStateCallback>> callback_;
+ Member<V8ScrollStateCallback> callback_;
};
} // namespace blink
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 54767cfda05..69a5e32063f 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
@@ -65,7 +65,7 @@
#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/histogram.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
@@ -240,11 +240,14 @@ template <typename Function>
static void ForAllPaintingGraphicsLayers(GraphicsLayer& layer,
const Function& function) {
// Don't recurse into display-locked elements.
- if (layer.Client().PaintBlockedByDisplayLock())
+ if (layer.Client().PaintBlockedByDisplayLockIncludingAncestors(
+ DisplayLockContextLifecycleTarget::kSelf)) {
return;
+ }
if (layer.PaintsContentOrHitTest())
function(layer);
+
for (auto* child : layer.Children())
ForAllPaintingGraphicsLayers(*child, function);
}
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator_context.h b/chromium/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator_context.h
index 36c5074e477..df16b878e95 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator_context.h
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator_context.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/animation/compositor_animation_timeline.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace cc {
class AnimationHost;
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 d9da75deab8..26038093279 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
@@ -127,9 +127,8 @@ class ScrollingCoordinatorTest : public testing::Test,
WebViewImpl* GetWebView() const { return helper_.GetWebView(); }
LocalFrame* GetFrame() const { return helper_.LocalMainFrame()->GetFrame(); }
-
- WebLayerTreeView* GetWebLayerTreeView() const {
- return GetWebView()->LayerTreeView();
+ frame_test_helpers::TestWebWidgetClient* GetWidgetClient() const {
+ return helper_.GetWebWidgetClient();
}
void LoadAhem() { helper_.LoadAhem(); }
@@ -165,10 +164,10 @@ TEST_P(ScrollingCoordinatorTest, fastScrollingByDefault) {
ASSERT_TRUE(root_scroll_layer->scrollable());
ASSERT_FALSE(root_scroll_layer->GetMainThreadScrollingReasons());
ASSERT_EQ(cc::EventListenerProperties::kNone,
- GetWebLayerTreeView()->EventListenerProperties(
+ GetWidgetClient()->EventListenerProperties(
cc::EventListenerClass::kTouchStartOrMove));
ASSERT_EQ(cc::EventListenerProperties::kNone,
- GetWebLayerTreeView()->EventListenerProperties(
+ GetWidgetClient()->EventListenerProperties(
cc::EventListenerClass::kMouseWheel));
cc::Layer* inner_viewport_scroll_layer =
@@ -456,7 +455,7 @@ TEST_P(ScrollingCoordinatorTest, touchEventHandler) {
ForceFullCompositingUpdate();
ASSERT_EQ(cc::EventListenerProperties::kBlocking,
- GetWebLayerTreeView()->EventListenerProperties(
+ GetWidgetClient()->EventListenerProperties(
cc::EventListenerClass::kTouchStartOrMove));
}
@@ -484,7 +483,7 @@ TEST_P(ScrollingCoordinatorTest, touchEventHandlerPassive) {
ForceFullCompositingUpdate();
ASSERT_EQ(cc::EventListenerProperties::kPassive,
- GetWebLayerTreeView()->EventListenerProperties(
+ GetWidgetClient()->EventListenerProperties(
cc::EventListenerClass::kTouchStartOrMove));
}
@@ -529,7 +528,7 @@ TEST_P(ScrollingCoordinatorTest, touchEventHandlerBoth) {
ForceFullCompositingUpdate();
ASSERT_EQ(cc::EventListenerProperties::kBlockingAndPassive,
- GetWebLayerTreeView()->EventListenerProperties(
+ GetWidgetClient()->EventListenerProperties(
cc::EventListenerClass::kTouchStartOrMove));
}
@@ -539,7 +538,7 @@ TEST_P(ScrollingCoordinatorTest, wheelEventHandler) {
ForceFullCompositingUpdate();
ASSERT_EQ(cc::EventListenerProperties::kBlocking,
- GetWebLayerTreeView()->EventListenerProperties(
+ GetWidgetClient()->EventListenerProperties(
cc::EventListenerClass::kMouseWheel));
}
@@ -549,7 +548,7 @@ TEST_P(ScrollingCoordinatorTest, wheelEventHandlerPassive) {
ForceFullCompositingUpdate();
ASSERT_EQ(cc::EventListenerProperties::kPassive,
- GetWebLayerTreeView()->EventListenerProperties(
+ GetWidgetClient()->EventListenerProperties(
cc::EventListenerClass::kMouseWheel));
}
@@ -559,7 +558,7 @@ TEST_P(ScrollingCoordinatorTest, wheelEventHandlerBoth) {
ForceFullCompositingUpdate();
ASSERT_EQ(cc::EventListenerProperties::kBlockingAndPassive,
- GetWebLayerTreeView()->EventListenerProperties(
+ GetWidgetClient()->EventListenerProperties(
cc::EventListenerClass::kMouseWheel));
}
@@ -568,7 +567,7 @@ TEST_P(ScrollingCoordinatorTest, scrollEventHandler) {
NavigateTo(base_url_ + "scroll-event-handler.html");
ForceFullCompositingUpdate();
- ASSERT_TRUE(GetWebLayerTreeView()->HaveScrollEventHandlers());
+ ASSERT_TRUE(GetWidgetClient()->HaveScrollEventHandlers());
}
TEST_P(ScrollingCoordinatorTest, updateEventHandlersDuringTeardown) {
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 984bd8077da..0ee31ee4ca4 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
@@ -368,8 +368,9 @@ bool SnapCoordinator::PerformSnapping(
scrollable_area->SetScrollOffset(
scrollable_area->ScrollPositionToOffset(snap_point.value()),
kProgrammaticScroll, kScrollBehaviorSmooth);
+ return true;
}
- return true;
+ return false;
}
base::Optional<cc::SnapContainerData> SnapCoordinator::GetSnapContainerData(
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 f7f30997330..538f45ebfb8 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
@@ -30,10 +30,11 @@ class SnapCoordinatorTest : public testing::Test,
protected:
SnapCoordinatorTest() : UseMockScrollbarSettings() {}
void SetUp() override {
- page_holder_ = std::make_unique<DummyPageHolder>();
+ page_holder_ = std::make_unique<DummyPageHolder>(
+ IntSize(), nullptr, nullptr, base::BindOnce([](Settings& settings) {
+ settings.SetAcceleratedCompositingEnabled(true);
+ }));
- page_holder_->GetPage().GetSettings().SetAcceleratedCompositingEnabled(
- true);
GetDocument().View()->SetParentVisible(true);
GetDocument().View()->SetSelfVisible(true);
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor.cc b/chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor.cc
index 3bb0a9ae55d..671cc77bd4e 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor.cc
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor.cc
@@ -14,6 +14,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/layout/layout_object.h"
+#include "third_party/blink/renderer/core/loader/document_loader.h"
#include "third_party/blink/renderer/core/page/scrolling/text_fragment_selector.h"
#include "third_party/blink/renderer/core/scroll/scroll_alignment.h"
#include "third_party/blink/renderer/core/scroll/scrollable_area.h"
@@ -22,13 +23,17 @@ namespace blink {
namespace {
+constexpr char kFragmentDirectivePrefix[] = "##";
constexpr char kTextFragmentIdentifierPrefix[] = "targetText=";
-constexpr size_t kTextFragmentIdentifierPrefixArrayLength =
- base::size(kTextFragmentIdentifierPrefix);
-bool ParseTargetTextIdentifier(
- const String& fragment,
- std::vector<TextFragmentSelector>* out_selectors) {
+// Subtract 1 because base::size includes the \0 string terminator.
+constexpr size_t kFragmentDirectivePrefixStringLength =
+ base::size(kFragmentDirectivePrefix) - 1;
+constexpr size_t kTextFragmentIdentifierPrefixStringLength =
+ base::size(kTextFragmentIdentifierPrefix) - 1;
+
+bool ParseTargetTextIdentifier(const String& fragment,
+ Vector<TextFragmentSelector>* out_selectors) {
DCHECK(out_selectors);
size_t start_pos = 0;
@@ -37,8 +42,7 @@ bool ParseTargetTextIdentifier(
if (fragment.Find(kTextFragmentIdentifierPrefix, start_pos) != start_pos)
return false;
- // The prefix array length includes the \0 string terminator.
- start_pos += kTextFragmentIdentifierPrefixArrayLength - 1;
+ start_pos += kTextFragmentIdentifierPrefixStringLength;
end_pos = fragment.find('&', start_pos);
String target_text;
@@ -54,20 +58,47 @@ bool ParseTargetTextIdentifier(
return true;
}
+// For fragment directive style text fragment anchors, we strip the directive
+// from the fragment string to avoid breaking pages that rely on the fragment.
+// E.g. "#id##targetText=a" --> "#id"
+String StripFragmentDirective(const String& fragment) {
+ size_t start_pos = fragment.Find(kFragmentDirectivePrefix);
+ if (start_pos == kNotFound)
+ return fragment;
+
+ return fragment.Substring(0, start_pos);
+}
+
+bool CheckSecurityRestrictions(LocalFrame& frame,
+ bool same_document_navigation) {
+ // For security reasons, we only allow text fragments on the main frame of a
+ // main window. So no iframes, no window.open. Also only on a full
+ // navigation.
+ if (frame.Tree().Parent() || frame.DomWindow()->opener() ||
+ same_document_navigation) {
+ return false;
+ }
+
+ // For security reasons, we only allow text fragment anchors for user or
+ // browser initiated navigations, i.e. no script navigations.
+ if (!(frame.Loader().GetDocumentLoader()->HadTransientActivation() ||
+ frame.Loader().GetDocumentLoader()->IsBrowserInitiated())) {
+ return false;
+ }
+
+ return true;
+}
+
} // namespace
TextFragmentAnchor* TextFragmentAnchor::TryCreate(
const KURL& url,
LocalFrame& frame,
bool same_document_navigation) {
- // For security reasons, we only allow text fragments on the main frame of a
- // main window. So no iframes, no window.open. Also only on a full
- // navigation.
- if (frame.Tree().Parent() || frame.DomWindow()->opener() ||
- same_document_navigation)
+ if (!CheckSecurityRestrictions(frame, same_document_navigation))
return nullptr;
- std::vector<TextFragmentSelector> selectors;
+ Vector<TextFragmentSelector> selectors;
if (!ParseTargetTextIdentifier(url.FragmentIdentifier(), &selectors))
return nullptr;
@@ -75,18 +106,52 @@ TextFragmentAnchor* TextFragmentAnchor::TryCreate(
return MakeGarbageCollected<TextFragmentAnchor>(selectors, frame);
}
+TextFragmentAnchor* TextFragmentAnchor::TryCreateFragmentDirective(
+ const KURL& url,
+ LocalFrame& frame,
+ bool same_document_navigation) {
+ DCHECK(RuntimeEnabledFeatures::TextFragmentIdentifiersEnabled(
+ frame.GetDocument()));
+
+ if (!CheckSecurityRestrictions(frame, same_document_navigation))
+ return nullptr;
+
+ Vector<TextFragmentSelector> selectors;
+
+ // Add the hash to the beginning of the fragment identifier as it is
+ // part of parsing the ##targetText= prefix but is not included by
+ // KURL::FragmentIdentifier().
+ String fragment = "#" + url.FragmentIdentifier();
+ size_t directive_pos = fragment.Find(kFragmentDirectivePrefix);
+ if (directive_pos == kNotFound)
+ return nullptr;
+
+ size_t start_pos = directive_pos + kFragmentDirectivePrefixStringLength;
+ if (!ParseTargetTextIdentifier(fragment.Substring(start_pos), &selectors))
+ return nullptr;
+
+ // Strip the fragment directive from the document URL so that the page cannot
+ // see the directive, to avoid breaking pages that rely on the fragment.
+ String stripped_fragment = StripFragmentDirective(fragment).Substring(1);
+ KURL stripped_url(url);
+ stripped_url.SetFragmentIdentifier(stripped_fragment);
+ frame.GetDocument()->SetURL(std::move(stripped_url));
+
+ return MakeGarbageCollected<TextFragmentAnchor>(selectors, frame);
+}
+
TextFragmentAnchor::TextFragmentAnchor(
- const std::vector<TextFragmentSelector>& text_fragment_selectors,
+ const Vector<TextFragmentSelector>& text_fragment_selectors,
LocalFrame& frame)
: frame_(&frame),
metrics_(MakeGarbageCollected<TextFragmentAnchorMetrics>(
frame_->GetDocument())) {
- DCHECK(!text_fragment_selectors.empty());
+ DCHECK(!text_fragment_selectors.IsEmpty());
DCHECK(frame_->View());
metrics_->DidCreateAnchor(text_fragment_selectors.size());
- text_fragment_finders_.reserve(text_fragment_selectors.size());
+ text_fragment_finders_.ReserveCapacity(text_fragment_selectors.size());
for (TextFragmentSelector selector : text_fragment_selectors)
text_fragment_finders_.emplace_back(*this, selector);
}
@@ -98,7 +163,7 @@ bool TextFragmentAnchor::Invoke() {
frame_->GetDocument()->Markers().RemoveMarkersOfTypes(
DocumentMarker::MarkerTypes::TextMatch());
- if (user_scrolled_)
+ if (user_scrolled_ && !did_scroll_into_view_)
metrics_->ScrollCancelled();
first_match_needs_scroll_ = !user_scrolled_;
@@ -106,7 +171,7 @@ bool TextFragmentAnchor::Invoke() {
{
// FindMatch might cause scrolling and set user_scrolled_ so reset it when
// it's done.
- base::AutoReset<bool>(&user_scrolled_, user_scrolled_);
+ base::AutoReset<bool> reset_user_scrolled(&user_scrolled_, user_scrolled_);
metrics_->ResetMatchCount();
for (auto& finder : text_fragment_finders_)
@@ -133,6 +198,9 @@ void TextFragmentAnchor::DidScroll(ScrollType type) {
void TextFragmentAnchor::PerformPreRafActions() {}
void TextFragmentAnchor::DidCompleteLoad() {
+ if (search_finished_)
+ return;
+
// If there is a pending layout we'll finish the search from Invoke.
if (!frame_->View()->NeedsLayout()) {
metrics_->ReportMetrics();
@@ -150,12 +218,24 @@ void TextFragmentAnchor::DidFindMatch(const EphemeralRangeInFlatTree& range) {
if (search_finished_)
return;
+ // TODO(nburris): Determine what we should do with overlapping text matches.
+ // This implementation drops a match if it overlaps a previous match, since
+ // overlapping ranges are likely unintentional by the URL creator and could
+ // therefore indicate that the page text has changed.
+ if (!frame_->GetDocument()
+ ->Markers()
+ .MarkersIntersectingRange(range,
+ DocumentMarker::MarkerTypes::TextMatch())
+ .IsEmpty()) {
+ return;
+ }
+
metrics_->DidFindMatch();
if (first_match_needs_scroll_) {
first_match_needs_scroll_ = false;
- LayoutRect bounding_box = LayoutRect(ComputeTextRect(range));
+ PhysicalRect bounding_box(ComputeTextRect(range));
// Set the bounding box height to zero because we want to center the top of
// the text range.
@@ -167,12 +247,13 @@ void TextFragmentAnchor::DidFindMatch(const EphemeralRangeInFlatTree& range) {
DCHECK(node.GetLayoutObject());
- LayoutRect scrolled_bounding_box =
+ PhysicalRect scrolled_bounding_box =
node.GetLayoutObject()->ScrollRectToVisible(
bounding_box,
- WebScrollIntoViewParams(ScrollAlignment::kAlignCenterIfNeeded,
- ScrollAlignment::kAlignCenterIfNeeded,
+ WebScrollIntoViewParams(ScrollAlignment::kAlignCenterAlways,
+ ScrollAlignment::kAlignCenterAlways,
kProgrammaticScroll));
+ did_scroll_into_view_ = true;
metrics_->DidScroll();
// We scrolled the text into view if the main document scrolled or the text
@@ -183,15 +264,13 @@ void TextFragmentAnchor::DidFindMatch(const EphemeralRangeInFlatTree& range) {
// actually in document coordinates and therefore does not change with a
// main document scroll.
if (!frame_->View()->GetScrollableArea()->GetScrollOffset().IsZero() ||
- scrolled_bounding_box.Location() != bounding_box.Location()) {
+ scrolled_bounding_box.offset != bounding_box.offset) {
metrics_->DidNonZeroScroll();
}
}
EphemeralRange dom_range =
EphemeralRange(ToPositionInDOMTree(range.StartPosition()),
ToPositionInDOMTree(range.EndPosition()));
- // TODO(nburris): Determine what we should do with overlapping text matches.
- // Currently, AddTextMatchMarker will crash when adding an overlapping marker.
frame_->GetDocument()->Markers().AddTextMatchMarker(
dom_range, TextMatchMarker::MatchStatus::kInactive);
frame_->GetEditor().SetMarkedTextMatchesAreHighlighted(true);
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor.h b/chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor.h
index c140a991d67..fa27ab012e5 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor.h
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor.h
@@ -26,8 +26,13 @@ class CORE_EXPORT TextFragmentAnchor final : public FragmentAnchor,
LocalFrame& frame,
bool same_document_navigation);
+ static TextFragmentAnchor* TryCreateFragmentDirective(
+ const KURL& url,
+ LocalFrame& frame,
+ bool same_document_navigation);
+
TextFragmentAnchor(
- const std::vector<TextFragmentSelector>& text_fragment_selectors,
+ const Vector<TextFragmentSelector>& text_fragment_selectors,
LocalFrame& frame);
~TextFragmentAnchor() override = default;
@@ -48,13 +53,19 @@ class CORE_EXPORT TextFragmentAnchor final : public FragmentAnchor,
void DidFindAmbiguousMatch() override;
private:
- std::vector<TextFragmentFinder> text_fragment_finders_;
+ Vector<TextFragmentFinder> text_fragment_finders_;
Member<LocalFrame> frame_;
bool search_finished_ = false;
+ // Whether the user has scrolled the page.
bool user_scrolled_ = false;
+ // Indicates that we should scroll into view the first match that we find, set
+ // to true each time the anchor is invoked if the user hasn't scrolled.
bool first_match_needs_scroll_ = false;
+ // Whether we successfully scrolled into view a match at least once, used for
+ // metrics reporting.
+ bool did_scroll_into_view_ = false;
Member<TextFragmentAnchorMetrics> metrics_;
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor_metrics.cc b/chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor_metrics.cc
index ac843d4b1ba..a9f439bdcc1 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor_metrics.cc
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor_metrics.cc
@@ -6,22 +6,16 @@
#include "base/logging.h"
#include "base/metrics/histogram_macros.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
TextFragmentAnchorMetrics::TextFragmentAnchorMetrics(Document* document)
: document_(document) {}
-TextFragmentAnchorMetrics::~TextFragmentAnchorMetrics() {
-#ifndef NDEBUG
- DCHECK(metrics_reported_);
-#endif
-}
-
void TextFragmentAnchorMetrics::DidCreateAnchor(int selector_count) {
UseCounter::Count(document_, WebFeature::kTextFragmentAnchor);
- create_time_ = WTF::CurrentTimeTicks();
+ create_time_ = base::TimeTicks::Now();
selector_count_ = selector_count;
}
@@ -43,7 +37,7 @@ void TextFragmentAnchorMetrics::ScrollCancelled() {
void TextFragmentAnchorMetrics::DidScroll() {
if (first_scroll_into_view_time_.is_null())
- first_scroll_into_view_time_ = WTF::CurrentTimeTicks();
+ first_scroll_into_view_time_ = base::TimeTicks::Now();
}
void TextFragmentAnchorMetrics::DidNonZeroScroll() {
@@ -62,22 +56,42 @@ void TextFragmentAnchorMetrics::ReportMetrics() {
}
UMA_HISTOGRAM_COUNTS_100("TextFragmentAnchor.SelectorCount", selector_count_);
+ TRACE_EVENT_INSTANT1("blink", "TextFragmentAnchorMetrics::ReportMetrics",
+ TRACE_EVENT_SCOPE_THREAD, "selector_count",
+ selector_count_);
const int match_rate_percent =
static_cast<int>(100 * ((match_count_ + 0.0) / selector_count_));
UMA_HISTOGRAM_PERCENTAGE("TextFragmentAnchor.MatchRate", match_rate_percent);
+ TRACE_EVENT_INSTANT1("blink", "TextFragmentAnchorMetrics::ReportMetrics",
+ TRACE_EVENT_SCOPE_THREAD, "match_rate",
+ match_rate_percent);
UMA_HISTOGRAM_BOOLEAN("TextFragmentAnchor.AmbiguousMatch", ambiguous_match_);
+ TRACE_EVENT_INSTANT1("blink", "TextFragmentAnchorMetrics::ReportMetrics",
+ TRACE_EVENT_SCOPE_THREAD, "ambiguous_match",
+ ambiguous_match_);
UMA_HISTOGRAM_BOOLEAN("TextFragmentAnchor.ScrollCancelled",
scroll_cancelled_);
+ TRACE_EVENT_INSTANT1("blink", "TextFragmentAnchorMetrics::ReportMetrics",
+ TRACE_EVENT_SCOPE_THREAD, "scroll_cancelled",
+ scroll_cancelled_);
if (first_scroll_into_view_time_ > create_time_) {
UMA_HISTOGRAM_BOOLEAN("TextFragmentAnchor.DidScrollIntoView",
did_non_zero_scroll_);
+ TRACE_EVENT_INSTANT1("blink", "TextFragmentAnchorMetrics::ReportMetrics",
+ TRACE_EVENT_SCOPE_THREAD, "did_scroll_into_view",
+ did_non_zero_scroll_);
+ base::TimeDelta time_to_scroll_into_view(first_scroll_into_view_time_ -
+ create_time_);
UMA_HISTOGRAM_TIMES("TextFragmentAnchor.TimeToScrollIntoView",
- first_scroll_into_view_time_ - create_time_);
+ time_to_scroll_into_view);
+ TRACE_EVENT_INSTANT1("blink", "TextFragmentAnchorMetrics::ReportMetrics",
+ TRACE_EVENT_SCOPE_THREAD, "time_to_scroll_into_view",
+ time_to_scroll_into_view.InMilliseconds());
}
#ifndef NDEBUG
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor_metrics.h b/chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor_metrics.h
index 5f9c049c381..6ca8ff6ac0f 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor_metrics.h
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor_metrics.h
@@ -17,7 +17,6 @@ class CORE_EXPORT TextFragmentAnchorMetrics final
: public GarbageCollectedFinalized<TextFragmentAnchorMetrics> {
public:
TextFragmentAnchorMetrics(Document* document);
- ~TextFragmentAnchorMetrics();
void DidCreateAnchor(int selector_count);
@@ -47,8 +46,8 @@ class CORE_EXPORT TextFragmentAnchorMetrics final
int match_count_ = 0;
bool ambiguous_match_ = false;
bool scroll_cancelled_ = false;
- WTF::TimeTicks create_time_;
- WTF::TimeTicks first_scroll_into_view_time_;
+ base::TimeTicks create_time_;
+ base::TimeTicks first_scroll_into_view_time_;
bool did_non_zero_scroll_ = false;
};
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor_metrics_test.cc b/chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor_metrics_test.cc
index 9c812ca0bb0..03cfaf8333a 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor_metrics_test.cc
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor_metrics_test.cc
@@ -243,6 +243,167 @@ TEST_F(TextFragmentAnchorMetricsTest, ScrollCancelled) {
0);
}
+class TextFragmentRelatedMetricTest : public TextFragmentAnchorMetricsTest,
+ public testing::WithParamInterface<bool> {
+ public:
+ TextFragmentRelatedMetricTest() : text_fragment_anchors_state_(GetParam()) {}
+
+ private:
+ ScopedTextFragmentIdentifiersForTest text_fragment_anchors_state_;
+};
+
+// These tests will run with and without the TextFragmentIdentifiers feature
+// enabled to ensure we collect metrics correctly under both situations.
+INSTANTIATE_TEST_SUITE_P(,
+ TextFragmentRelatedMetricTest,
+ testing::Values(false, true));
+
+// Test that we correctly track failed vs. successful element-id lookups. We
+// only count these in cases where we don't have a targetText, when the REF is
+// enabled.
+TEST_P(TextFragmentRelatedMetricTest, ElementIdSuccessFailureCounts) {
+ const int kUncounted = 0;
+ const int kFound = 1;
+ const int kNotFound = 2;
+
+ // When the TextFragmentAnchors feature is on, we should avoid counting the
+ // result of the element-id fragment if a targetText is successfully parsed.
+ // If the feature is off we treat the targetText as an element-id and should
+ // count the result.
+ const int kUncountedOrNotFound = GetParam() ? kUncounted : kNotFound;
+ const int kUncountedOrFound = GetParam() ? kUncounted : kFound;
+
+ Vector<std::pair<String, int>> test_cases = {
+ {"", kUncounted},
+ {"#element", kFound},
+ {"#doesntExist", kNotFound},
+ {"#element##foo", kNotFound},
+ {"#doesntexist##foo", kNotFound},
+ {"##element", kNotFound},
+ {"#element##targetText=doesntexist", kUncountedOrNotFound},
+ {"#element##targetText=page", kUncountedOrNotFound},
+ {"#targetText=doesntexist", kUncountedOrNotFound},
+ {"#targetText=page", kUncountedOrNotFound},
+ {"#targetText=name", kUncountedOrFound},
+ {"#element##targetText=name", kUncountedOrFound}};
+
+ const int kNotFoundSample = 0;
+ const int kFoundSample = 1;
+ const std::string histogram = "TextFragmentAnchor.ElementIdFragmentFound";
+
+ // Add counts to each histogram so that calls to GetBucketCount won't fail
+ // due to not finding the histogram.
+ UMA_HISTOGRAM_BOOLEAN(histogram, true);
+ UMA_HISTOGRAM_BOOLEAN(histogram, false);
+ int expected_found_count = 1;
+ int expected_not_found_count = 1;
+
+ for (auto test_case : test_cases) {
+ String url = "https://example.com/test.html" + test_case.first;
+ SimRequest request(url, "text/html");
+ LoadURL(url);
+ request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <p id="element">This is a test page</p>
+ <p id="targetText=name">This is a test page</p>
+ <p id="element##targetText=name">This is a test page</p>
+ )HTML");
+ Compositor().BeginFrame();
+
+ RunAsyncMatchingTasks();
+
+ auto not_found_count =
+ histogram_tester_.GetBucketCount(histogram, kNotFoundSample);
+ auto found_count =
+ histogram_tester_.GetBucketCount(histogram, kFoundSample);
+ int result = test_case.second;
+ if (result == kFound) {
+ ++expected_found_count;
+ ASSERT_EQ(expected_found_count, found_count)
+ << "ElementId should have been |Found| but did not UseCount on case: "
+ << test_case.first;
+ ASSERT_EQ(expected_not_found_count, not_found_count)
+ << "ElementId should have been |Found| but reported |NotFound| on "
+ "case: "
+ << test_case.first;
+ } else if (result == kNotFound) {
+ ++expected_not_found_count;
+ ASSERT_EQ(expected_not_found_count, not_found_count)
+ << "ElementId should have been |NotFound| but did not UseCount on "
+ "case: "
+ << test_case.first;
+ ASSERT_EQ(expected_found_count, found_count)
+ << "ElementId should have been |NotFound| but reported |Found| on "
+ "case: "
+ << test_case.first;
+ } else {
+ DCHECK_EQ(result, kUncounted);
+ ASSERT_EQ(expected_found_count, found_count)
+ << "Case should not have been counted but reported |Found| on case: "
+ << test_case.first;
+ ASSERT_EQ(expected_not_found_count, not_found_count)
+ << "Case should not have been counted but reported |NotFound| on "
+ "case: "
+ << test_case.first;
+ }
+ }
+}
+
+// Test that we correctly UseCount when we see a pound character '#' in the
+// fragment. We exclude the case where we see a ##targetText format
+// TextFragment so that we don't count it in uses of our own feature.
+TEST_P(TextFragmentRelatedMetricTest, DoubleHashUseCounter) {
+ const int kUncounted = 0;
+ const int kCounted = 1;
+
+ // When the TextFragmentAnchors feature is on, we should avoid counting a
+ // ##targetText directive as a use of double-hash in this case. When it's
+ // off, we expect to count it.
+ const int kCountedOnlyIfDisabled = !GetParam() ? kCounted : kUncounted;
+
+ Vector<std::pair<String, int>> test_cases = {
+ {"", kUncounted},
+ {"#element", kUncounted},
+ {"#doesntExist", kUncounted},
+ {"#element##foo", kCounted},
+ {"#doesntexist##foo", kCounted},
+ {"##element", kCounted},
+ {"#element#", kCounted},
+ {"#foo#bar#", kCounted},
+ {"#foo%23", kUncounted},
+ {"#element##targetText=doesntexist", kCountedOnlyIfDisabled},
+ {"#element##targetText=doesntexist#", kCountedOnlyIfDisabled},
+ {"#element##targetText=page", kCountedOnlyIfDisabled},
+ {"#element##targetText=page#", kCountedOnlyIfDisabled},
+ {"#targetText=doesntexist", kUncounted},
+ {"#targetText=page", kUncounted}};
+
+ for (auto test_case : test_cases) {
+ String url = "https://example.com/test.html" + test_case.first;
+ SimRequest request(url, "text/html");
+ LoadURL(url);
+ request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <p id="element">This is a test page</p>
+ )HTML");
+ Compositor().BeginFrame();
+
+ RunAsyncMatchingTasks();
+
+ bool is_use_counted =
+ GetDocument().IsUseCounted(WebFeature::kFragmentDoubleHash);
+ if (test_case.second == kCounted) {
+ EXPECT_TRUE(is_use_counted)
+ << "Expected to count double-hash but didn't in case: "
+ << test_case.first;
+ } else {
+ EXPECT_FALSE(is_use_counted)
+ << "Expected not to count double-hash but did in case: "
+ << test_case.first;
+ }
+ }
+}
+
} // namespace
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor_test.cc b/chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor_test.cc
index ad10da3ef33..ccdfdede8e7 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor_test.cc
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_anchor_test.cc
@@ -397,9 +397,9 @@ TEST_F(TextFragmentAnchorTest, MultipleNonMatchingStrings) {
// Test matching a text range within the same element
TEST_F(TextFragmentAnchorTest, SameElementTextRange) {
- SimRequest request("https://example.com/test.html#targetText=this,page",
+ SimRequest request("https://example.com/test.html#targetText=This,page",
"text/html");
- LoadURL("https://example.com/test.html#targetText=this,page");
+ LoadURL("https://example.com/test.html#targetText=This,page");
request.Complete(R"HTML(
<!DOCTYPE html>
<style>
@@ -619,9 +619,9 @@ TEST_F(TextFragmentAnchorTest, DistantElementTextRange) {
// Test a text range with both context terms in the same element.
TEST_F(TextFragmentAnchorTest, TextRangeWithContext) {
SimRequest request(
- "https://example.com/test.html#targetText=this-,is,test,-page",
+ "https://example.com/test.html#targetText=This-,is,test,-page",
"text/html");
- LoadURL("https://example.com/test.html#targetText=this-,is,test,-page");
+ LoadURL("https://example.com/test.html#targetText=This-,is,test,-page");
request.Complete(R"HTML(
<!DOCTYPE html>
<p id="text">This is a test page</p>
@@ -661,9 +661,9 @@ TEST_F(TextFragmentAnchorTest, PrefixNotFound) {
// Ensure that we do not match a text range if the suffix is not found.
TEST_F(TextFragmentAnchorTest, SuffixNotFound) {
SimRequest request(
- "https://example.com/test.html#targetText=this-,is,test,-suffix",
+ "https://example.com/test.html#targetText=This-,is,test,-suffix",
"text/html");
- LoadURL("https://example.com/test.html#targetText=this-,is,test,-suffix");
+ LoadURL("https://example.com/test.html#targetText=This-,is,test,-suffix");
request.Complete(R"HTML(
<!DOCTYPE html>
<p id="text">This is a test page</p>
@@ -678,11 +678,11 @@ TEST_F(TextFragmentAnchorTest, SuffixNotFound) {
// Test a text range with context terms in different elements
TEST_F(TextFragmentAnchorTest, TextRangeWithCrossElementContext) {
SimRequest request(
- "https://example.com/test.html#targetText=header%202-,a,text,-footer%201",
+ "https://example.com/test.html#targetText=Header%202-,A,text,-Footer%201",
"text/html");
LoadURL(
"https://example.com/"
- "test.html#targetText=header%202-,a,text,-footer%201");
+ "test.html#targetText=Header%202-,A,text,-Footer%201");
request.Complete(R"HTML(
<!DOCTYPE html>
<h1>Header 1</h1>
@@ -714,11 +714,11 @@ TEST_F(TextFragmentAnchorTest, TextRangeWithCrossElementContext) {
TEST_F(TextFragmentAnchorTest, CrossElementAndWhitespaceContext) {
SimRequest request(
"https://example.com/"
- "test.html#targetText=list%202-,cat,-good%20cat",
+ "test.html#targetText=List%202-,Cat,-Good%20cat",
"text/html");
LoadURL(
"https://example.com/"
- "test.html#targetText=list%202-,cat,-good%20cat");
+ "test.html#targetText=List%202-,Cat,-Good%20cat");
request.Complete(R"HTML(
<!DOCTYPE html>
<h1> List 1 </h1>
@@ -791,9 +791,9 @@ TEST_F(TextFragmentAnchorTest, CrossEmptySiblingAndParentElementContext) {
// Ensure we scroll to text when its prefix and suffix are out of view.
TEST_F(TextFragmentAnchorTest, DistantElementContext) {
SimRequest request(
- "https://example.com/test.html#targetText=prefix-,cats,-suffix",
+ "https://example.com/test.html#targetText=Prefix-,Cats,-Suffix",
"text/html");
- LoadURL("https://example.com/test.html#targetText=prefix-,cats,-suffix");
+ LoadURL("https://example.com/test.html#targetText=Prefix-,Cats,-Suffix");
request.Complete(R"HTML(
<!DOCTYPE html>
<style>
@@ -1010,6 +1010,276 @@ TEST_F(TextFragmentAnchorTest, DisabledInSamePageNavigation) {
EXPECT_EQ(ScrollOffset(), LayoutViewport()->GetScrollOffset());
}
+// Ensure matching is case insensitive.
+TEST_F(TextFragmentAnchorTest, CaseInsensitive) {
+ SimRequest request("https://example.com/test.html#targetText=Test",
+ "text/html");
+ LoadURL("https://example.com/test.html#targetText=Test");
+ request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ body {
+ height: 1200px;
+ }
+ p {
+ position: absolute;
+ top: 1000px;
+ }
+ </style>
+ <p id="text">test</p>
+ )HTML");
+ Compositor().BeginFrame();
+ RunAsyncMatchingTasks();
+
+ Element& p = *GetDocument().getElementById("text");
+
+ EXPECT_TRUE(ViewportRect().Contains(BoundingRectInFrame(p)))
+ << "<p> Element wasn't scrolled into view, viewport's scroll offset: "
+ << LayoutViewport()->GetScrollOffset().ToString();
+
+ EXPECT_EQ(1u, GetDocument().Markers().Markers().size());
+}
+
+// Test that the fragment anchor stays centered in view throughout loading.
+TEST_F(TextFragmentAnchorTest, TargetStaysInView) {
+ SimRequest main_request("https://example.com/test.html#targetText=test",
+ "text/html");
+ SimRequest image_request("https://example.com/image.svg", "image/svg+xml");
+ LoadURL("https://example.com/test.html#targetText=test");
+ main_request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ p {
+ margin-top: 1000px;
+ }
+ </style>
+ <img src="image.svg">
+ <p id="text">test</p>
+ )HTML");
+ Compositor().PaintFrame();
+ RunAsyncMatchingTasks();
+
+ ScrollOffset first_scroll_offset = LayoutViewport()->GetScrollOffset();
+ ASSERT_NE(ScrollOffset(), first_scroll_offset);
+
+ Element& p = *GetDocument().getElementById("text");
+ IntRect first_bounding_rect = BoundingRectInFrame(p);
+ EXPECT_TRUE(ViewportRect().Contains(first_bounding_rect));
+
+ // Load an image that pushes the target text out of view
+ image_request.Complete(R"SVG(
+ <svg xmlns="http://www.w3.org/2000/svg" width="200" height="2000">
+ <rect fill="green" width="200" height="2000"/>
+ </svg>
+ )SVG");
+ Compositor().BeginFrame();
+ RunAsyncMatchingTasks();
+
+ // Ensure the target text is still in view and stayed centered
+ ASSERT_NE(first_scroll_offset, LayoutViewport()->GetScrollOffset());
+ EXPECT_TRUE(ViewportRect().Contains(BoundingRectInFrame(p)));
+ EXPECT_EQ(first_bounding_rect, BoundingRectInFrame(p));
+
+ EXPECT_EQ(1u, GetDocument().Markers().Markers().size());
+}
+
+// Test that overlapping text ranges results in only the first one highlighted
+TEST_F(TextFragmentAnchorTest, OverlappingTextRanges) {
+ SimRequest request(
+ "https://example.com/test.html#targetText=This,test&targetText=is,page",
+ "text/html");
+ LoadURL(
+ "https://example.com/test.html#targetText=This,test&targetText=is,page");
+ request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ body {
+ height: 1200px;
+ }
+ p {
+ position: absolute;
+ top: 1000px;
+ }
+ </style>
+ <p id="text">This is a test page</p>
+ )HTML");
+ Compositor().BeginFrame();
+
+ RunAsyncMatchingTasks();
+
+ EXPECT_EQ(1u, GetDocument().Markers().Markers().size());
+
+ // Expect marker on "This is a test".
+ auto* text = To<Text>(GetDocument().getElementById("text")->firstChild());
+ DocumentMarkerVector markers = GetDocument().Markers().MarkersFor(
+ *text, DocumentMarker::MarkerTypes::TextMatch());
+ ASSERT_EQ(1u, markers.size());
+ EXPECT_EQ(0u, markers.at(0)->StartOffset());
+ EXPECT_EQ(14u, markers.at(0)->EndOffset());
+}
+
+// Test that the ##targetText fragment syntax works properly and is stripped
+// from the URL.
+TEST_F(TextFragmentAnchorTest, DoubleHashSyntax) {
+ SimRequest request("https://example.com/test.html##targetText=test",
+ "text/html");
+ LoadURL("https://example.com/test.html##targetText=test");
+ request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ body {
+ height: 1200px;
+ }
+ p {
+ position: absolute;
+ top: 1000px;
+ }
+ </style>
+ <p id="text">This is a test page</p>
+ )HTML");
+ Compositor().BeginFrame();
+
+ RunAsyncMatchingTasks();
+
+ EXPECT_EQ(1u, GetDocument().Markers().Markers().size());
+
+ EXPECT_EQ(GetDocument().Url(), "https://example.com/test.html#");
+}
+
+// Test that the ##targetText fragment directive is stripped from the URL when
+// there's also non-directive fragment contents.
+TEST_F(TextFragmentAnchorTest, DoubleHashStrippedWithRemainingFragment) {
+ SimRequest request("https://example.com/test.html#element##targetText=test",
+ "text/html");
+ LoadURL("https://example.com/test.html#element##targetText=test");
+ request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ body {
+ height: 1200px;
+ }
+ #text {
+ position: absolute;
+ top: 1000px;
+ }
+ #element {
+ position: absolute;
+ top: 2000px;
+ }
+ </style>
+ <p id="text">This is a test page</p>
+ <div id="element"></div>
+ )HTML");
+ Compositor().BeginFrame();
+
+ RunAsyncMatchingTasks();
+
+ EXPECT_EQ(GetDocument().Url(), "https://example.com/test.html#element");
+
+ Element& p = *GetDocument().getElementById("text");
+
+ EXPECT_TRUE(ViewportRect().Contains(BoundingRectInFrame(p)))
+ << "<p> Element wasn't scrolled into view, viewport's scroll offset: "
+ << LayoutViewport()->GetScrollOffset().ToString();
+}
+
+// If the fragment has a double hash, but the double hash isn't followed by a
+// valid targetText syntax, it should be interpreted as an element ID.
+TEST_F(TextFragmentAnchorTest, IdFragmentWithDoubleHash) {
+ SimRequest request("https://example.com/test.html#element##id", "text/html");
+ LoadURL("https://example.com/test.html#element##id");
+ request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ body {
+ height: 2200px;
+ }
+ p {
+ position: absolute;
+ top: 1000px;
+ }
+ div {
+ position: absolute;
+ top: 2000px;
+ }
+ </style>
+ <p id="element">This is a test page</p>
+ <div id="element##id"></div>
+ )HTML");
+ Compositor().BeginFrame();
+
+ RunAsyncMatchingTasks();
+
+ Element& div = *GetDocument().getElementById("element##id");
+
+ EXPECT_TRUE(ViewportRect().Contains(BoundingRectInFrame(div)))
+ << "Should have scrolled <div> into view but didn't, scroll offset: "
+ << LayoutViewport()->GetScrollOffset().ToString();
+}
+
+// Test matching a space to &nbsp character.
+TEST_F(TextFragmentAnchorTest, SpaceMatchesNbsp) {
+ SimRequest request("https://example.com/test.html#targetText=test%20page",
+ "text/html");
+ LoadURL("https://example.com/test.html#targetText=test%20page");
+ request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ body {
+ height: 1200px;
+ }
+ p {
+ position: absolute;
+ top: 1000px;
+ }
+ </style>
+ <p id="text">This is a test&nbsp;page</p>
+ )HTML");
+ Compositor().BeginFrame();
+
+ RunAsyncMatchingTasks();
+
+ Element& p = *GetDocument().getElementById("text");
+
+ EXPECT_TRUE(ViewportRect().Contains(BoundingRectInFrame(p)))
+ << "<p> Element wasn't scrolled into view, viewport's scroll offset: "
+ << LayoutViewport()->GetScrollOffset().ToString();
+
+ EXPECT_EQ(1u, GetDocument().Markers().Markers().size());
+}
+
+// Test matching text with a CSS text transform.
+TEST_F(TextFragmentAnchorTest, CSSTextTransform) {
+ SimRequest request("https://example.com/test.html#targetText=test%20page",
+ "text/html");
+ LoadURL("https://example.com/test.html#targetText=test%20page");
+ request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ body {
+ height: 1200px;
+ }
+ p {
+ position: absolute;
+ top: 1000px;
+ text-transform: uppercase;
+ }
+ </style>
+ <p id="text">This is a test page</p>
+ )HTML");
+ Compositor().BeginFrame();
+
+ RunAsyncMatchingTasks();
+
+ Element& p = *GetDocument().getElementById("text");
+
+ EXPECT_TRUE(ViewportRect().Contains(BoundingRectInFrame(p)))
+ << "<p> Element wasn't scrolled into view, viewport's scroll offset: "
+ << LayoutViewport()->GetScrollOffset().ToString();
+
+ EXPECT_EQ(1u, GetDocument().Markers().Markers().size());
+}
+
} // namespace
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_finder.cc b/chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_finder.cc
index 864c63fcffc..edca62e1bc1 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_finder.cc
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/text_fragment_finder.cc
@@ -11,6 +11,7 @@
#include "third_party/blink/renderer/core/dom/range.h"
#include "third_party/blink/renderer/core/editing/ephemeral_range.h"
#include "third_party/blink/renderer/core/editing/finder/find_buffer.h"
+#include "third_party/blink/renderer/core/editing/finder/find_options.h"
#include "third_party/blink/renderer/core/editing/iterators/character_iterator.h"
#include "third_party/blink/renderer/core/editing/position.h"
#include "third_party/blink/renderer/core/page/scrolling/text_fragment_selector.h"
@@ -24,9 +25,9 @@ const char kNoContext[] = "";
EphemeralRangeInFlatTree FindMatchInRange(String search_text,
PositionInFlatTree search_start,
PositionInFlatTree search_end) {
- const FindOptions find_options = kCaseInsensitive;
const EphemeralRangeInFlatTree search_range(search_start, search_end);
- return FindBuffer::FindMatchInRange(search_range, search_text, find_options);
+ return FindBuffer::FindMatchInRange(search_range, search_text,
+ kCaseInsensitive);
}
PositionInFlatTree NextTextPosition(PositionInFlatTree position,
@@ -56,10 +57,9 @@ EphemeralRangeInFlatTree FindImmediateMatch(String search_text,
return EphemeralRangeInFlatTree();
FindBuffer buffer(EphemeralRangeInFlatTree(search_start, search_end));
- const FindOptions find_options = kCaseInsensitive;
std::unique_ptr<FindBuffer::Results> match_results =
- buffer.FindMatches(search_text, find_options);
+ buffer.FindMatches(search_text, kCaseInsensitive);
if (!match_results->IsEmpty() && match_results->front().start == 0u) {
FindBuffer::BufferMatchResult match = match_results->front();
diff --git a/chromium/third_party/blink/renderer/core/page/scrolling/viewport_scroll_callback.cc b/chromium/third_party/blink/renderer/core/page/scrolling/viewport_scroll_callback.cc
index 6d6309abe60..ecbb10eb338 100644
--- a/chromium/third_party/blink/renderer/core/page/scrolling/viewport_scroll_callback.cc
+++ b/chromium/third_party/blink/renderer/core/page/scrolling/viewport_scroll_callback.cc
@@ -104,7 +104,8 @@ ScrollResult ViewportScrollCallback::PerformNativeScroll(ScrollState& state) {
ScrollGranularity granularity =
ScrollGranularity(static_cast<int>(state.deltaGranularity()));
- ScrollResult result = root_frame_viewport_->UserScroll(granularity, delta);
+ ScrollResult result = root_frame_viewport_->UserScroll(
+ granularity, delta, ScrollableArea::ScrollCallback());
// The viewport consumes everything.
// TODO(bokan): This isn't actually consuming everything but doing so breaks
diff --git a/chromium/third_party/blink/renderer/core/page/slot_scoped_traversal.cc b/chromium/third_party/blink/renderer/core/page/slot_scoped_traversal.cc
index 97e43e6a68a..df2d380074b 100644
--- a/chromium/third_party/blink/renderer/core/page/slot_scoped_traversal.cc
+++ b/chromium/third_party/blink/renderer/core/page/slot_scoped_traversal.cc
@@ -85,8 +85,8 @@ Element* SlotScopedTraversal::Next(const Element& current) {
DCHECK_NE(current_index, kNotFound);
for (++current_index; current_index < assigned_nodes.size();
++current_index) {
- if (assigned_nodes[current_index]->IsElementNode())
- return ToElement(assigned_nodes[current_index]);
+ if (auto* element = DynamicTo<Element>(assigned_nodes[current_index].Get()))
+ return element;
}
return nullptr;
}
@@ -113,10 +113,10 @@ Element* SlotScopedTraversal::Previous(const Element& current) {
DCHECK_NE(current_index, kNotFound);
for (; current_index > 0; --current_index) {
const Member<Node> assigned_node = assigned_nodes[current_index - 1];
- if (!assigned_node->IsElementNode())
+ auto* element = DynamicTo<Element>(assigned_node.Get());
+ if (!element)
continue;
- return LastWithinOrSelfSkippingChildrenOfShadowHost(
- *ToElement(assigned_node));
+ return LastWithinOrSelfSkippingChildrenOfShadowHost(*element);
}
return nullptr;
}
@@ -124,8 +124,8 @@ Element* SlotScopedTraversal::Previous(const Element& current) {
Element* SlotScopedTraversal::FirstAssignedToSlot(HTMLSlotElement& slot) {
const HeapVector<Member<Node>>& assigned_nodes = slot.AssignedNodes();
for (auto assigned_node : assigned_nodes) {
- if (assigned_node->IsElementNode())
- return ToElement(assigned_node);
+ if (auto* element = DynamicTo<Element>(assigned_node.Get()))
+ return element;
}
return nullptr;
}
@@ -134,10 +134,10 @@ Element* SlotScopedTraversal::LastAssignedToSlot(HTMLSlotElement& slot) {
const HeapVector<Member<Node>>& assigned_nodes = slot.AssignedNodes();
for (auto assigned_node = assigned_nodes.rbegin();
assigned_node != assigned_nodes.rend(); ++assigned_node) {
- if (!(*assigned_node)->IsElementNode())
+ auto* element = DynamicTo<Element>(assigned_node->Get());
+ if (!element)
continue;
- return LastWithinOrSelfSkippingChildrenOfShadowHost(
- *ToElement(*assigned_node));
+ return LastWithinOrSelfSkippingChildrenOfShadowHost(*element);
}
return nullptr;
}
diff --git a/chromium/third_party/blink/renderer/core/page/slot_scoped_traversal.h b/chromium/third_party/blink/renderer/core/page/slot_scoped_traversal.h
index 9b8728b0aad..d9cc4d4c0ac 100644
--- a/chromium/third_party/blink/renderer/core/page/slot_scoped_traversal.h
+++ b/chromium/third_party/blink/renderer/core/page/slot_scoped_traversal.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAGE_SLOT_SCOPED_TRAVERSAL_H_
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/page/slot_scoped_traversal_test.cc b/chromium/third_party/blink/renderer/core/page/slot_scoped_traversal_test.cc
index 0a945e40198..629825c5500 100644
--- a/chromium/third_party/blink/renderer/core/page/slot_scoped_traversal_test.cc
+++ b/chromium/third_party/blink/renderer/core/page/slot_scoped_traversal_test.cc
@@ -54,7 +54,7 @@ void SlotScopedTraversalTest::SetupSampleHTML(const char* main_html,
Element* body = GetDocument().body();
body->SetInnerHTMLFromString(String::FromUTF8(main_html));
if (shadow_html) {
- Element* shadow_host = ToElement(NodeTraversal::ChildAt(*body, index));
+ auto* shadow_host = To<Element>(NodeTraversal::ChildAt(*body, index));
AttachOpenShadowRoot(*shadow_host, shadow_html);
}
}
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 08bde9ae003..75878ac795a 100644
--- a/chromium/third_party/blink/renderer/core/page/spatial_navigation.cc
+++ b/chromium/third_party/blink/renderer/core/page/spatial_navigation.cc
@@ -56,7 +56,7 @@ constexpr double kMinDistance = std::numeric_limits<int>::lowest();
constexpr int kFudgeFactor = 2;
-static void DeflateIfOverlapped(LayoutRect&, LayoutRect&);
+static void DeflateIfOverlapped(PhysicalRect&, PhysicalRect&);
FocusCandidate::FocusCandidate(Node* node, SpatialNavigationDirection direction)
: visible_node(nullptr), focusable_node(nullptr), is_offscreen(true) {
@@ -88,15 +88,15 @@ bool IsSpatialNavigationEnabled(const LocalFrame* frame) {
}
static bool RectsIntersectOnOrthogonalAxis(SpatialNavigationDirection direction,
- const LayoutRect& a,
- const LayoutRect& b) {
+ const PhysicalRect& a,
+ const PhysicalRect& b) {
switch (direction) {
case SpatialNavigationDirection::kLeft:
case SpatialNavigationDirection::kRight:
- return a.MaxY() > b.Y() && a.Y() < b.MaxY();
+ return a.Bottom() > b.Y() && a.Y() < b.Bottom();
case SpatialNavigationDirection::kUp:
case SpatialNavigationDirection::kDown:
- return a.MaxX() > b.X() && a.X() < b.MaxX();
+ return a.Right() > b.X() && a.X() < b.Right();
default:
NOTREACHED();
return false;
@@ -106,22 +106,22 @@ static bool RectsIntersectOnOrthogonalAxis(SpatialNavigationDirection direction,
// Return true if rect |a| is below |b|. False otherwise.
// For overlapping rects, |a| is considered to be below |b|
// if both edges of |a| are below the respective ones of |b|.
-static inline bool Below(const LayoutRect& a, const LayoutRect& b) {
- return a.Y() >= b.MaxY() || (a.Y() >= b.Y() && a.MaxY() > b.MaxY() &&
- a.X() < b.MaxX() && a.MaxX() > b.X());
+static inline bool Below(const PhysicalRect& a, const PhysicalRect& b) {
+ return a.Y() >= b.Bottom() || (a.Y() >= b.Y() && a.Bottom() > b.Bottom() &&
+ a.X() < b.Right() && a.Right() > b.X());
}
// Return true if rect |a| is on the right of |b|. False otherwise.
// For overlapping rects, |a| is considered to be on the right of |b|
// if both edges of |a| are on the right of the respective ones of |b|.
-static inline bool RightOf(const LayoutRect& a, const LayoutRect& b) {
- return a.X() >= b.MaxX() || (a.X() >= b.X() && a.MaxX() > b.MaxX() &&
- a.Y() < b.MaxY() && a.MaxY() > b.Y());
+static inline bool RightOf(const PhysicalRect& a, const PhysicalRect& b) {
+ return a.X() >= b.Right() || (a.X() >= b.X() && a.Right() > b.Right() &&
+ a.Y() < b.Bottom() && a.Bottom() > b.Y());
}
static bool IsRectInDirection(SpatialNavigationDirection direction,
- const LayoutRect& cur_rect,
- const LayoutRect& target_rect) {
+ const PhysicalRect& cur_rect,
+ const PhysicalRect& target_rect) {
switch (direction) {
case SpatialNavigationDirection::kLeft:
return RightOf(cur_rect, target_rect);
@@ -148,7 +148,7 @@ FloatRect RectInViewport(const Node& node) {
if (!object)
return FloatRect();
- LayoutRect rect_in_root_frame = NodeRectInRootFrame(&node);
+ PhysicalRect rect_in_root_frame = NodeRectInRootFrame(&node);
// Convert to the visual viewport which will account for pinch zoom.
VisualViewport& visual_viewport =
@@ -207,9 +207,9 @@ bool IsUnobscured(const FocusCandidate& candidate) {
if (candidate.visible_node->IsMediaElement())
return true;
- LayoutRect viewport_rect = LayoutRect(
+ PhysicalRect viewport_rect(
local_main_frame->GetPage()->GetVisualViewport().VisibleContentRect());
- LayoutRect interesting_rect =
+ PhysicalRect interesting_rect =
Intersection(candidate.rect_in_root_frame, viewport_rect);
if (interesting_rect.IsEmpty())
@@ -296,7 +296,7 @@ bool ScrollInDirection(Node* container, SpatialNavigationDirection direction) {
return true;
}
-static void DeflateIfOverlapped(LayoutRect& a, LayoutRect& b) {
+static void DeflateIfOverlapped(PhysicalRect& a, PhysicalRect& b) {
if (!a.Intersects(b) || a.Contains(b) || b.Contains(a))
return;
@@ -407,7 +407,7 @@ bool CanScrollInDirection(const LocalFrame* frame,
ScrollableArea* scrollable_area = frame->View()->GetScrollableArea();
LayoutSize size(scrollable_area->ContentsSize());
LayoutSize offset(scrollable_area->ScrollOffsetInt());
- LayoutRect rect(scrollable_area->VisibleContentRect(kIncludeScrollbars));
+ PhysicalRect rect(scrollable_area->VisibleContentRect(kIncludeScrollbars));
switch (direction) {
case SpatialNavigationDirection::kLeft:
@@ -424,7 +424,7 @@ bool CanScrollInDirection(const LocalFrame* frame,
}
}
-LayoutRect NodeRectInRootFrame(const Node* node) {
+PhysicalRect NodeRectInRootFrame(const Node* node) {
DCHECK(node);
DCHECK(node->GetLayoutObject());
DCHECK(!node->GetDocument().View()->NeedsLayout());
@@ -443,7 +443,7 @@ LayoutRect NodeRectInRootFrame(const Node* node) {
LayoutUnit(object->StyleRef().BorderLeftWidth()));
object->MapToVisualRectInAncestorSpace(/*ancestor=*/nullptr, rect);
- return rect.ToLayoutRect();
+ return rect;
}
// This method calculates the exitPoint from the startingRect and the entryPoint
@@ -451,38 +451,38 @@ LayoutRect NodeRectInRootFrame(const Node* node) {
// distance between the 2 rects. Takes care of overlapping rects, defining
// points so that the distance between them is zero where necessary.
void EntryAndExitPointsForDirection(SpatialNavigationDirection direction,
- const LayoutRect& starting_rect,
- const LayoutRect& potential_rect,
+ const PhysicalRect& starting_rect,
+ const PhysicalRect& potential_rect,
LayoutPoint& exit_point,
LayoutPoint& entry_point) {
switch (direction) {
case SpatialNavigationDirection::kLeft:
exit_point.SetX(starting_rect.X());
- if (potential_rect.MaxX() < starting_rect.X())
- entry_point.SetX(potential_rect.MaxX());
+ if (potential_rect.Right() < starting_rect.X())
+ entry_point.SetX(potential_rect.Right());
else
entry_point.SetX(starting_rect.X());
break;
case SpatialNavigationDirection::kUp:
exit_point.SetY(starting_rect.Y());
- if (potential_rect.MaxY() < starting_rect.Y())
- entry_point.SetY(potential_rect.MaxY());
+ if (potential_rect.Bottom() < starting_rect.Y())
+ entry_point.SetY(potential_rect.Bottom());
else
entry_point.SetY(starting_rect.Y());
break;
case SpatialNavigationDirection::kRight:
- exit_point.SetX(starting_rect.MaxX());
- if (potential_rect.X() > starting_rect.MaxX())
+ exit_point.SetX(starting_rect.Right());
+ if (potential_rect.X() > starting_rect.Right())
entry_point.SetX(potential_rect.X());
else
- entry_point.SetX(starting_rect.MaxX());
+ entry_point.SetX(starting_rect.Right());
break;
case SpatialNavigationDirection::kDown:
- exit_point.SetY(starting_rect.MaxY());
- if (potential_rect.Y() > starting_rect.MaxY())
+ exit_point.SetY(starting_rect.Bottom());
+ if (potential_rect.Y() > starting_rect.Bottom())
entry_point.SetY(potential_rect.Y());
else
- entry_point.SetY(starting_rect.MaxY());
+ entry_point.SetY(starting_rect.Bottom());
break;
default:
NOTREACHED();
@@ -493,16 +493,16 @@ void EntryAndExitPointsForDirection(SpatialNavigationDirection direction,
case SpatialNavigationDirection::kRight:
if (Below(starting_rect, potential_rect)) {
exit_point.SetY(starting_rect.Y());
- if (potential_rect.MaxY() < starting_rect.Y())
- entry_point.SetY(potential_rect.MaxY());
+ if (potential_rect.Bottom() < starting_rect.Y())
+ entry_point.SetY(potential_rect.Bottom());
else
entry_point.SetY(starting_rect.Y());
} else if (Below(potential_rect, starting_rect)) {
- exit_point.SetY(starting_rect.MaxY());
- if (potential_rect.Y() > starting_rect.MaxY())
+ exit_point.SetY(starting_rect.Bottom());
+ if (potential_rect.Y() > starting_rect.Bottom())
entry_point.SetY(potential_rect.Y());
else
- entry_point.SetY(starting_rect.MaxY());
+ entry_point.SetY(starting_rect.Bottom());
} else {
exit_point.SetY(max(starting_rect.Y(), potential_rect.Y()));
entry_point.SetY(exit_point.Y());
@@ -512,16 +512,16 @@ void EntryAndExitPointsForDirection(SpatialNavigationDirection direction,
case SpatialNavigationDirection::kDown:
if (RightOf(starting_rect, potential_rect)) {
exit_point.SetX(starting_rect.X());
- if (potential_rect.MaxX() < starting_rect.X())
- entry_point.SetX(potential_rect.MaxX());
+ if (potential_rect.Right() < starting_rect.X())
+ entry_point.SetX(potential_rect.Right());
else
entry_point.SetX(starting_rect.X());
} else if (RightOf(potential_rect, starting_rect)) {
- exit_point.SetX(starting_rect.MaxX());
- if (potential_rect.X() > starting_rect.MaxX())
+ exit_point.SetX(starting_rect.Right());
+ if (potential_rect.X() > starting_rect.Right())
entry_point.SetX(potential_rect.X());
else
- entry_point.SetX(starting_rect.MaxX());
+ entry_point.SetX(starting_rect.Right());
} else {
exit_point.SetX(max(starting_rect.X(), potential_rect.X()));
entry_point.SetX(exit_point.X());
@@ -532,13 +532,56 @@ void EntryAndExitPointsForDirection(SpatialNavigationDirection direction,
}
}
+double ProjectedOverlap(SpatialNavigationDirection direction,
+ PhysicalRect current,
+ PhysicalRect candidate) {
+ switch (direction) {
+ case SpatialNavigationDirection::kLeft:
+ case SpatialNavigationDirection::kRight:
+ current.SetWidth(LayoutUnit(1));
+ candidate.SetX(current.X());
+ current.Intersect(candidate);
+ return current.Height();
+ case SpatialNavigationDirection::kUp:
+ case SpatialNavigationDirection::kDown:
+ current.SetHeight(LayoutUnit(1));
+ candidate.SetY(current.Y());
+ current.Intersect(candidate);
+ return current.Width();
+ default:
+ NOTREACHED();
+ return kMaxDistance;
+ }
+}
+
+double Alignment(SpatialNavigationDirection direction,
+ PhysicalRect current,
+ PhysicalRect candidate) {
+ // The formula and constants for "alignment" are experimental and
+ // come from https://drafts.csswg.org/css-nav-1/#heuristics.
+ const int kAlignWeight = 5;
+
+ double projected_overlap = ProjectedOverlap(direction, current, candidate);
+ switch (direction) {
+ case SpatialNavigationDirection::kLeft:
+ case SpatialNavigationDirection::kRight:
+ return (kAlignWeight * projected_overlap) / current.Height();
+ case SpatialNavigationDirection::kUp:
+ case SpatialNavigationDirection::kDown:
+ return (kAlignWeight * projected_overlap) / current.Width();
+ default:
+ NOTREACHED();
+ return kMaxDistance;
+ }
+}
+
double ComputeDistanceDataForNode(SpatialNavigationDirection direction,
const FocusCandidate& current_interest,
const FocusCandidate& candidate) {
double distance = 0.0;
double overlap = 0.0;
- LayoutRect node_rect = candidate.rect_in_root_frame;
- LayoutRect current_rect = current_interest.rect_in_root_frame;
+ PhysicalRect node_rect = candidate.rect_in_root_frame;
+ PhysicalRect current_rect = current_interest.rect_in_root_frame;
if (node_rect.Contains(current_rect)) {
// When leaving an "insider", don't focus its underlaying container box.
// Go directly to the outside world. This avoids focus from being trapped
@@ -564,7 +607,7 @@ double ComputeDistanceDataForNode(SpatialNavigationDirection direction,
return kMaxDistance;
} else {
DeflateIfOverlapped(current_rect, node_rect);
- LayoutRect intersection_rect = Intersection(current_rect, node_rect);
+ PhysicalRect intersection_rect = Intersection(current_rect, node_rect);
overlap =
(intersection_rect.Width() * intersection_rect.Height()).ToDouble();
}
@@ -616,36 +659,37 @@ double ComputeDistanceDataForNode(SpatialNavigationDirection direction,
return kMaxDistance;
}
- // Distance calculation is based on http://www.w3.org/TR/WICD/#focus-handling
- return distance + navigation_axis_distance +
+ // Distance calculation is based on https://drafts.csswg.org/css-nav-1/.
+ return distance + navigation_axis_distance -
+ Alignment(direction, current_rect, node_rect) +
weighted_orthogonal_axis_distance - sqrt(overlap);
}
// Returns a thin rectangle that represents one of |box|'s edges.
// To not intersect elements that are positioned inside |box|, we add one
// LayoutUnit of margin that puts the returned slice "just outside" |box|.
-LayoutRect OppositeEdge(SpatialNavigationDirection side,
- const LayoutRect& box,
- LayoutUnit thickness) {
- LayoutRect thin_rect = box;
+PhysicalRect OppositeEdge(SpatialNavigationDirection side,
+ const PhysicalRect& box,
+ LayoutUnit thickness) {
+ PhysicalRect thin_rect = box;
switch (side) {
case SpatialNavigationDirection::kLeft:
- thin_rect.SetX(thin_rect.MaxX() - thickness);
+ thin_rect.SetX(thin_rect.Right() - thickness);
thin_rect.SetWidth(thickness);
- thin_rect.Move(1, 0);
+ thin_rect.offset.left += 1;
break;
case SpatialNavigationDirection::kRight:
thin_rect.SetWidth(thickness);
- thin_rect.Move(-1, 0);
+ thin_rect.offset.left -= 1;
break;
case SpatialNavigationDirection::kDown:
thin_rect.SetHeight(thickness);
- thin_rect.Move(0, -1);
+ thin_rect.offset.top -= 1;
break;
case SpatialNavigationDirection::kUp:
- thin_rect.SetY(thin_rect.MaxY() - thickness);
+ thin_rect.SetY(thin_rect.Bottom() - thickness);
thin_rect.SetHeight(thickness);
- thin_rect.Move(0, 1);
+ thin_rect.offset.top += 1;
break;
default:
NOTREACHED();
@@ -654,13 +698,13 @@ LayoutRect OppositeEdge(SpatialNavigationDirection side,
return thin_rect;
}
-LayoutRect StartEdgeForAreaElement(const HTMLAreaElement& area,
- SpatialNavigationDirection direction) {
+PhysicalRect StartEdgeForAreaElement(const HTMLAreaElement& area,
+ SpatialNavigationDirection direction) {
DCHECK(area.ImageElement());
// Area elements tend to overlap more than other focusable elements. We
// flatten the rect of the area elements to minimize the effect of overlapping
// areas.
- LayoutRect rect = OppositeEdge(
+ PhysicalRect rect = OppositeEdge(
direction,
area.GetDocument().GetFrame()->View()->ConvertToRootFrame(
area.ComputeAbsoluteRect(area.ImageElement()->GetLayoutObject())),
@@ -673,8 +717,8 @@ HTMLFrameOwnerElement* FrameOwnerElement(const FocusCandidate& candidate) {
}
// The visual viewport's rect (given in the root frame's coordinate space).
-LayoutRect RootViewport(const LocalFrame* current_frame) {
- return LayoutRect(
+PhysicalRect RootViewport(const LocalFrame* current_frame) {
+ return PhysicalRect::EnclosingRect(
current_frame->GetPage()->GetVisualViewport().VisibleRect());
}
@@ -685,9 +729,9 @@ LayoutRect RootViewport(const LocalFrame* current_frame) {
// scroller’s scroller ... all the way up until the root frame's document.
// The root frame's document is a good base case because it's, per definition,
// a visible scrollable area.
-LayoutRect SearchOrigin(const LayoutRect viewport_rect_of_root_frame,
- Node* focus_node,
- const SpatialNavigationDirection direction) {
+PhysicalRect SearchOrigin(const PhysicalRect& viewport_rect_of_root_frame,
+ Node* focus_node,
+ const SpatialNavigationDirection direction) {
if (!focus_node) {
// Search from one of the visual viewport's edges towards the navigated
// direction. For example, UP makes spatnav search upwards, starting at the
@@ -703,7 +747,7 @@ LayoutRect SearchOrigin(const LayoutRect viewport_rect_of_root_frame,
if (area_element)
return StartEdgeForAreaElement(*area_element, direction);
- LayoutRect box_in_root_frame = NodeRectInRootFrame(focus_node);
+ PhysicalRect box_in_root_frame = NodeRectInRootFrame(focus_node);
return Intersection(box_in_root_frame, viewport_rect_of_root_frame);
}
@@ -711,7 +755,7 @@ LayoutRect SearchOrigin(const LayoutRect viewport_rect_of_root_frame,
while (container) {
if (!IsOffscreen(container)) {
// The first scroller that encloses focus and is [partially] visible.
- LayoutRect box_in_root_frame = NodeRectInRootFrame(container);
+ PhysicalRect box_in_root_frame = NodeRectInRootFrame(container);
return OppositeEdge(direction, Intersection(box_in_root_frame,
viewport_rect_of_root_frame));
}
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 7112a4d3bed..75bba97ac5a 100644
--- a/chromium/third_party/blink/renderer/core/page/spatial_navigation.h
+++ b/chromium/third_party/blink/renderer/core/page/spatial_navigation.h
@@ -24,7 +24,7 @@
#include "third_party/blink/public/platform/web_focus_type.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/dom/node.h"
-#include "third_party/blink/renderer/platform/geometry/layout_rect.h"
+#include "third_party/blink/renderer/core/layout/geometry/physical_rect.h"
#include <limits>
@@ -60,7 +60,7 @@ struct FocusCandidate {
// visibleNode and focusableNode are one and the same.
Member<Node> visible_node;
Member<Node> focusable_node;
- LayoutRect rect_in_root_frame;
+ PhysicalRect rect_in_root_frame;
bool is_offscreen;
};
@@ -78,17 +78,17 @@ bool CanScrollInDirection(const LocalFrame*, SpatialNavigationDirection);
double ComputeDistanceDataForNode(SpatialNavigationDirection,
const FocusCandidate& current_interest,
const FocusCandidate& candidate);
-CORE_EXPORT LayoutRect NodeRectInRootFrame(const Node*);
-CORE_EXPORT LayoutRect OppositeEdge(SpatialNavigationDirection side,
- const LayoutRect& box,
- LayoutUnit thickness = LayoutUnit());
-CORE_EXPORT LayoutRect RootViewport(const LocalFrame*);
-LayoutRect StartEdgeForAreaElement(const HTMLAreaElement&,
- SpatialNavigationDirection);
+CORE_EXPORT PhysicalRect NodeRectInRootFrame(const Node*);
+CORE_EXPORT PhysicalRect OppositeEdge(SpatialNavigationDirection side,
+ const PhysicalRect& box,
+ LayoutUnit thickness = LayoutUnit());
+CORE_EXPORT PhysicalRect RootViewport(const LocalFrame*);
+PhysicalRect StartEdgeForAreaElement(const HTMLAreaElement&,
+ SpatialNavigationDirection);
HTMLFrameOwnerElement* FrameOwnerElement(const FocusCandidate&);
-CORE_EXPORT LayoutRect SearchOrigin(const LayoutRect,
- Node*,
- const SpatialNavigationDirection);
+CORE_EXPORT PhysicalRect SearchOrigin(const PhysicalRect&,
+ Node*,
+ const SpatialNavigationDirection);
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/page/spatial_navigation_controller.cc b/chromium/third_party/blink/renderer/core/page/spatial_navigation_controller.cc
index 6c451e3d71d..0a9cc07c3b0 100644
--- a/chromium/third_party/blink/renderer/core/page/spatial_navigation_controller.cc
+++ b/chromium/third_party/blink/renderer/core/page/spatial_navigation_controller.cc
@@ -29,7 +29,7 @@
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/page/spatial_navigation.h"
#include "third_party/blink/renderer/platform/geometry/layout_rect.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/core/css/style_change_reason.h"
@@ -180,7 +180,7 @@ bool SpatialNavigationController::HandleEnterKeyboardEvent(
nullptr));
// We need enter to activate links, etc. The click should be after the
// focus in case the site transfers focus upon clicking.
- interest_element->DispatchSimulatedClick(event);
+ interest_element->DispatchSimulatedClick(event, kSendMouseUpDownEvents);
}
}
@@ -196,12 +196,10 @@ bool SpatialNavigationController::HandleImeSubmitKeyboardEvent(
KeyboardEvent* event) {
DCHECK(page_->GetSettings().GetSpatialNavigationEnabled());
- if (!IsHTMLFormControlElement(GetFocusedElement()))
+ auto* element = DynamicTo<HTMLFormControlElement>(GetFocusedElement());
+ if (!element)
return false;
- HTMLFormControlElement* element =
- ToHTMLFormControlElement(GetFocusedElement());
-
if (!element->formOwner())
return false;
@@ -271,15 +269,16 @@ bool SpatialNavigationController::Advance(
Node* container = ScrollableAreaOrDocumentOf(interest_node);
- const LayoutRect visible_rect(page_->GetVisualViewport().VisibleRect());
- const LayoutRect start_box =
+ const PhysicalRect visible_rect =
+ PhysicalRect::EnclosingRect(page_->GetVisualViewport().VisibleRect());
+ const PhysicalRect start_box =
SearchOrigin(visible_rect, interest_node, direction);
if (IsScrollableAreaOrDocument(interest_node) &&
!IsOffscreen(interest_node)) {
// A visible scroller has interest. Search inside of it from one of its
// edges.
- LayoutRect edge = OppositeEdge(direction, start_box);
+ PhysicalRect edge = OppositeEdge(direction, start_box);
if (AdvanceWithinContainer(*interest_node, edge, direction, nullptr))
return true;
}
@@ -312,7 +311,7 @@ bool SpatialNavigationController::Advance(
FocusCandidate SpatialNavigationController::FindNextCandidateInContainer(
Node& container,
- const LayoutRect& starting_rect_in_root_frame,
+ const PhysicalRect& starting_rect_in_root_frame,
SpatialNavigationDirection direction,
Node* interest_child_in_container) {
Element* element = ElementTraversal::FirstWithin(container);
@@ -351,7 +350,7 @@ FocusCandidate SpatialNavigationController::FindNextCandidateInContainer(
bool SpatialNavigationController::AdvanceWithinContainer(
Node& container,
- const LayoutRect& starting_rect_in_root_frame,
+ const PhysicalRect& starting_rect_in_root_frame,
SpatialNavigationDirection direction,
Node* interest_child_in_container) {
DCHECK(IsScrollableAreaOrDocument(&container));
@@ -367,7 +366,7 @@ bool SpatialNavigationController::AdvanceWithinContainer(
return ScrollInDirection(&container, direction);
}
- Element* element = ToElement(candidate.focusable_node);
+ auto* element = To<Element>(candidate.focusable_node.Get());
DCHECK(element);
MoveInterestTo(element);
return true;
@@ -412,7 +411,7 @@ Node* SpatialNavigationController::StartingNode() {
void SpatialNavigationController::MoveInterestTo(Node* next_node) {
DCHECK(!next_node || next_node->IsElementNode());
- Element* element = ToElement(next_node);
+ auto* element = To<Element>(next_node);
if (RuntimeEnabledFeatures::FocuslessSpatialNavigationEnabled()) {
if (interest_element_) {
@@ -476,7 +475,7 @@ void SpatialNavigationController::DispatchMouseMoveAt(Element* element) {
WebMouseEvent fake_mouse_move_event(
WebInputEvent::kMouseMove, event_position, event_position_screen,
WebPointerProperties::Button::kNoButton, click_count,
- WebInputEvent::kRelativeMotionEvent, CurrentTimeTicks());
+ WebInputEvent::kRelativeMotionEvent, base::TimeTicks::Now());
Vector<WebMouseEvent> coalesced_events, predicted_events;
DCHECK(IsA<LocalFrame>(page_->MainFrame()));
diff --git a/chromium/third_party/blink/renderer/core/page/spatial_navigation_controller.h b/chromium/third_party/blink/renderer/core/page/spatial_navigation_controller.h
index 3c87e446778..63380b0f538 100644
--- a/chromium/third_party/blink/renderer/core/page/spatial_navigation_controller.h
+++ b/chromium/third_party/blink/renderer/core/page/spatial_navigation_controller.h
@@ -14,10 +14,10 @@ namespace blink {
struct FocusCandidate;
class KeyboardEvent;
-class LayoutRect;
class LocalFrameView;
class Node;
class Page;
+struct PhysicalRect;
// Encapsulates logic and state related to "spatial navigation". Spatial
// Navigation is used to move and interact with a page in a purely directional
@@ -70,14 +70,14 @@ class CORE_EXPORT SpatialNavigationController
* may be in a nested container.
*/
bool AdvanceWithinContainer(Node& container,
- const LayoutRect& starting_rect_in_root_frame,
+ const PhysicalRect& starting_rect_in_root_frame,
SpatialNavigationDirection direction,
Node* interest_child_in_container);
// Parameters have same meanings as method above.
FocusCandidate FindNextCandidateInContainer(
Node& container,
- const LayoutRect& starting_rect_in_root_frame,
+ const PhysicalRect& starting_rect_in_root_frame,
SpatialNavigationDirection direction,
Node* interest_child_in_container);
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 a7416224660..88ac29f3a2b 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
@@ -11,8 +11,12 @@
#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/frame/web_local_frame_impl.h"
+#include "third_party/blink/renderer/core/html/forms/html_select_element.h"
#include "third_party/blink/renderer/core/input/event_handler.h"
+#include "third_party/blink/renderer/core/page/spatial_navigation_controller.h"
#include "third_party/blink/renderer/core/testing/core_unit_test_helper.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/runtime_enabled_features_test_helpers.h"
#include "third_party/blink/renderer/platform/testing/url_test_helpers.h"
#include "ui/events/keycodes/dom/dom_key.h"
@@ -24,30 +28,30 @@ class SpatialNavigationTest : public RenderingTest {
SpatialNavigationTest()
: RenderingTest(MakeGarbageCollected<SingleChildLocalFrameClient>()) {}
- LayoutRect TopOfVisualViewport() {
- LayoutRect visual_viewport = RootViewport(&GetFrame());
+ PhysicalRect TopOfVisualViewport() {
+ PhysicalRect visual_viewport = RootViewport(&GetFrame());
visual_viewport.SetY(visual_viewport.Y() - 1);
visual_viewport.SetHeight(LayoutUnit(0));
return visual_viewport;
}
- LayoutRect BottomOfVisualViewport() {
- LayoutRect visual_viewport = RootViewport(&GetFrame());
- visual_viewport.SetY(visual_viewport.MaxY() + 1);
+ PhysicalRect BottomOfVisualViewport() {
+ PhysicalRect visual_viewport = RootViewport(&GetFrame());
+ visual_viewport.SetY(visual_viewport.Bottom() + 1);
visual_viewport.SetHeight(LayoutUnit(0));
return visual_viewport;
}
- LayoutRect LeftSideOfVisualViewport() {
- LayoutRect visual_viewport = RootViewport(&GetFrame());
+ PhysicalRect LeftSideOfVisualViewport() {
+ PhysicalRect visual_viewport = RootViewport(&GetFrame());
visual_viewport.SetX(visual_viewport.X() - 1);
visual_viewport.SetWidth(LayoutUnit(0));
return visual_viewport;
}
- LayoutRect RightSideOfVisualViewport() {
- LayoutRect visual_viewport = RootViewport(&GetFrame());
- visual_viewport.SetX(visual_viewport.MaxX() + 1);
+ PhysicalRect RightSideOfVisualViewport() {
+ PhysicalRect visual_viewport = RootViewport(&GetFrame());
+ visual_viewport.SetX(visual_viewport.Right() + 1);
visual_viewport.SetWidth(LayoutUnit(0));
return visual_viewport;
}
@@ -80,11 +84,11 @@ TEST_F(SpatialNavigationTest, RootFramesVisualViewport) {
visual_viewport.SetLocation(FloatPoint(200, 200));
LocalFrameView* root_frame_view = GetFrame().LocalFrameRoot().View();
- const LayoutRect roots_visible_doc_rect(
+ const PhysicalRect roots_visible_doc_rect(
root_frame_view->GetScrollableArea()->VisibleContentRect());
// Convert the root frame's visible rect from document space -> frame space.
// For the root frame, frame space == root frame space, obviously.
- LayoutRect viewport_rect_of_root_frame =
+ PhysicalRect viewport_rect_of_root_frame =
root_frame_view->DocumentToFrame(roots_visible_doc_rect);
EXPECT_EQ(viewport_rect_of_root_frame, RootViewport(&GetFrame()));
@@ -187,11 +191,11 @@ TEST_F(SpatialNavigationTest, ZooomPutsElementOffScreen) {
}
TEST_F(SpatialNavigationTest, RootViewportRespectsVisibleSize) {
- EXPECT_EQ(RootViewport(&GetFrame()), LayoutRect(0, 0, 800, 600));
+ EXPECT_EQ(RootViewport(&GetFrame()), PhysicalRect(0, 0, 800, 600));
VisualViewport& visual_viewport = GetFrame().GetPage()->GetVisualViewport();
visual_viewport.SetSize({123, 123});
- EXPECT_EQ(RootViewport(&GetFrame()), LayoutRect(0, 0, 123, 123));
+ EXPECT_EQ(RootViewport(&GetFrame()), PhysicalRect(0, 0, 123, 123));
}
TEST_F(SpatialNavigationTest, StartAtVisibleFocusedElement) {
@@ -247,7 +251,7 @@ TEST_F(SpatialNavigationTest, StartAtVisibleFocusedIframe) {
}
TEST_F(SpatialNavigationTest, StartAtTopWhenGoingDownwardsWithoutFocus) {
- EXPECT_EQ(LayoutRect(0, -1, 111, 0),
+ EXPECT_EQ(PhysicalRect(0, -1, 111, 0),
SearchOrigin({0, 0, 111, 222}, nullptr,
SpatialNavigationDirection::kDown));
@@ -258,7 +262,7 @@ TEST_F(SpatialNavigationTest, StartAtTopWhenGoingDownwardsWithoutFocus) {
TEST_F(SpatialNavigationTest, StartAtBottomWhenGoingUpwardsWithoutFocus) {
EXPECT_EQ(
- LayoutRect(0, 222 + 1, 111, 0),
+ PhysicalRect(0, 222 + 1, 111, 0),
SearchOrigin({0, 0, 111, 222}, nullptr, SpatialNavigationDirection::kUp));
EXPECT_EQ(SearchOrigin(RootViewport(&GetFrame()), nullptr,
@@ -267,7 +271,7 @@ TEST_F(SpatialNavigationTest, StartAtBottomWhenGoingUpwardsWithoutFocus) {
}
TEST_F(SpatialNavigationTest, StartAtLeftSideWhenGoingEastWithoutFocus) {
- EXPECT_EQ(LayoutRect(-1, 0, 0, 222),
+ EXPECT_EQ(PhysicalRect(-1, 0, 0, 222),
SearchOrigin({0, 0, 111, 222}, nullptr,
SpatialNavigationDirection::kRight));
@@ -277,7 +281,7 @@ TEST_F(SpatialNavigationTest, StartAtLeftSideWhenGoingEastWithoutFocus) {
}
TEST_F(SpatialNavigationTest, StartAtRightSideWhenGoingWestWithoutFocus) {
- EXPECT_EQ(LayoutRect(111 + 1, 0, 0, 222),
+ EXPECT_EQ(PhysicalRect(111 + 1, 0, 0, 222),
SearchOrigin({0, 0, 111, 222}, nullptr,
SpatialNavigationDirection::kLeft));
@@ -319,7 +323,7 @@ TEST_F(SpatialNavigationTest, StartAtContainersEdge) {
Element* b = GetDocument().getElementById("b");
const Element* container = GetDocument().getElementById("container");
- const LayoutRect container_box = NodeRectInRootFrame(container);
+ const PhysicalRect container_box = NodeRectInRootFrame(container);
// TODO(crbug.com/889840):
// VisibleBoundsInVisualViewport does not (yet) take div-clipping into
@@ -330,7 +334,7 @@ TEST_F(SpatialNavigationTest, StartAtContainersEdge) {
EXPECT_TRUE(IsOffscreen(b));
// Go down.
- LayoutRect container_top_edge = container_box;
+ PhysicalRect container_top_edge = container_box;
container_top_edge.SetHeight(LayoutUnit(0));
container_top_edge.SetY(container_top_edge.Y() - 1);
EXPECT_EQ(SearchOrigin(RootViewport(&GetFrame()), b,
@@ -338,15 +342,15 @@ TEST_F(SpatialNavigationTest, StartAtContainersEdge) {
container_top_edge);
// Go up.
- LayoutRect container_bottom_edge = container_box;
+ PhysicalRect container_bottom_edge = container_box;
container_bottom_edge.SetHeight(LayoutUnit(0));
- container_bottom_edge.SetY(container_bottom_edge.MaxX() + 1);
+ container_bottom_edge.SetY(container_bottom_edge.Right() + 1);
EXPECT_EQ(SearchOrigin(RootViewport(&GetFrame()), b,
SpatialNavigationDirection::kUp),
container_bottom_edge);
// Go right.
- LayoutRect container_leftmost_edge = container_box;
+ PhysicalRect container_leftmost_edge = container_box;
container_leftmost_edge.SetWidth(LayoutUnit(0));
container_leftmost_edge.SetX(container_leftmost_edge.X() - 1);
EXPECT_EQ(SearchOrigin(RootViewport(&GetFrame()), b,
@@ -354,8 +358,8 @@ TEST_F(SpatialNavigationTest, StartAtContainersEdge) {
container_leftmost_edge);
// Go left.
- LayoutRect container_rightmost_edge = container_box;
- container_rightmost_edge.SetX(container_bottom_edge.MaxX() + 1);
+ PhysicalRect container_rightmost_edge = container_box;
+ container_rightmost_edge.SetX(container_bottom_edge.Right() + 1);
container_rightmost_edge.SetWidth(LayoutUnit(0));
EXPECT_EQ(SearchOrigin(RootViewport(&GetFrame()), b,
SpatialNavigationDirection::kLeft),
@@ -437,7 +441,7 @@ TEST_F(SpatialNavigationTest, PartiallyVisible) {
EXPECT_FALSE(IsOffscreen(b)); // <button> is not completely offscreen.
- LayoutRect button_in_root_frame = NodeRectInRootFrame(b);
+ PhysicalRect button_in_root_frame = NodeRectInRootFrame(b);
EXPECT_EQ(SearchOrigin(RootViewport(&GetFrame()), b,
SpatialNavigationDirection::kUp),
@@ -446,7 +450,7 @@ TEST_F(SpatialNavigationTest, PartiallyVisible) {
// Do some scrolling.
ScrollableArea* root_scroller = GetDocument().View()->GetScrollableArea();
root_scroller->SetScrollOffset(ScrollOffset(0, 600), kProgrammaticScroll);
- LayoutRect button_after_scroll = NodeRectInRootFrame(b);
+ PhysicalRect button_after_scroll = NodeRectInRootFrame(b);
ASSERT_NE(button_in_root_frame,
button_after_scroll); // As we scrolled, the
// <button>'s position in
@@ -563,7 +567,7 @@ TEST_F(SpatialNavigationTest, PartiallyVisibleIFrame) {
EXPECT_TRUE(IsOffscreen(child_element)); // Completely offscreen.
EXPECT_FALSE(IsOffscreen(enclosing_container)); // Partially visible.
- LayoutRect iframe = NodeRectInRootFrame(enclosing_container);
+ PhysicalRect iframe = NodeRectInRootFrame(enclosing_container);
// When searching downwards we start at activeElement's
// container's (here: the iframe's) topmost visible edge.
@@ -595,8 +599,8 @@ TEST_F(SpatialNavigationTest, PartiallyVisibleIFrame) {
}
TEST_F(SpatialNavigationTest, BottomOfPinchedViewport) {
- LayoutRect origin = SearchOrigin(RootViewport(&GetFrame()), nullptr,
- SpatialNavigationDirection::kUp);
+ PhysicalRect origin = SearchOrigin(RootViewport(&GetFrame()), nullptr,
+ SpatialNavigationDirection::kUp);
EXPECT_EQ(origin.Height(), 0);
EXPECT_EQ(origin.Width(), GetFrame().View()->Width());
EXPECT_EQ(origin.X(), 0);
@@ -617,8 +621,8 @@ TEST_F(SpatialNavigationTest, BottomOfPinchedViewport) {
}
TEST_F(SpatialNavigationTest, TopOfPinchedViewport) {
- LayoutRect origin = SearchOrigin(RootViewport(&GetFrame()), nullptr,
- SpatialNavigationDirection::kDown);
+ PhysicalRect origin = SearchOrigin(RootViewport(&GetFrame()), nullptr,
+ SpatialNavigationDirection::kDown);
EXPECT_EQ(origin.Height(), 0);
EXPECT_EQ(origin.Width(), GetFrame().View()->Width());
EXPECT_EQ(origin.X(), 0);
@@ -712,4 +716,75 @@ TEST_P(SpatialNavigationWithFocuslessModeTest, PressEnterKeyActiveElement) {
EXPECT_FALSE(b->IsActive());
}
+class FocuslessSpatialNavigationSimTest : public SimTest {
+ public:
+ FocuslessSpatialNavigationSimTest() : use_focusless_mode_(true) {}
+
+ void SetUp() override {
+ SimTest::SetUp();
+ WebView().GetPage()->GetSettings().SetSpatialNavigationEnabled(true);
+ }
+
+ void SimulateKeyPress(int dom_key) {
+ WebKeyboardEvent event{WebInputEvent::kRawKeyDown,
+ WebInputEvent::kNoModifiers,
+ WebInputEvent::GetStaticTimeStampForTests()};
+ event.dom_key = dom_key;
+ WebView().MainFrameWidget()->HandleInputEvent(
+ WebCoalescedInputEvent(event));
+
+ if (dom_key == ui::DomKey::ENTER) {
+ event.SetType(WebInputEvent::kChar);
+ WebView().MainFrameWidget()->HandleInputEvent(
+ WebCoalescedInputEvent(event));
+ }
+
+ event.SetType(WebInputEvent::kKeyUp);
+ WebView().MainFrameWidget()->HandleInputEvent(
+ WebCoalescedInputEvent(event));
+ }
+
+ ScopedFocuslessSpatialNavigationForTest use_focusless_mode_;
+};
+
+// Tests that opening a <select> popup works by pressing enter from
+// "interested" mode, without being focused.
+TEST_F(FocuslessSpatialNavigationSimTest, OpenSelectPopup) {
+ // This test requires PagePopup since we're testing opening the <select> drop
+ // down so skip this test on platforms (i.e. Android) that don't use this.
+ if (!RuntimeEnabledFeatures::PagePopupEnabled())
+ return;
+
+ WebView().MainFrameWidget()->Resize(WebSize(800, 600));
+ WebView().MainFrameWidget()->SetFocus(true);
+ WebView().SetIsActive(true);
+
+ SimRequest request("https://example.com/test.html", "text/html");
+ LoadURL("https://example.com/test.html");
+ request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <select id="target">
+ <option>A</option>
+ <option>B</option>
+ <option>C</option>
+ </select>
+ )HTML");
+ Compositor().BeginFrame();
+
+ HTMLSelectElement* select =
+ ToHTMLSelectElement(GetDocument().getElementById("target"));
+ SimulateKeyPress(ui::DomKey::ARROW_DOWN);
+
+ SpatialNavigationController& spat_nav_controller =
+ GetDocument().GetPage()->GetSpatialNavigationController();
+
+ ASSERT_EQ(select, spat_nav_controller.GetInterestedElement());
+ ASSERT_NE(select, GetDocument().ActiveElement());
+ ASSERT_FALSE(select->PopupIsVisible());
+
+ // The enter key should cause the popup to open.
+ SimulateKeyPress(ui::DomKey::ENTER);
+ EXPECT_TRUE(select->PopupIsVisible());
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/page/touch_adjustment.cc b/chromium/third_party/blink/renderer/core/page/touch_adjustment.cc
index 546ec0066dd..cdd08e7da09 100644
--- a/chromium/third_party/blink/renderer/core/page/touch_adjustment.cc
+++ b/chromium/third_party/blink/renderer/core/page/touch_adjustment.cc
@@ -94,8 +94,7 @@ bool NodeRespondsToTapGesture(Node* node) {
if (node->WillRespondToMouseClickEvents() ||
node->WillRespondToMouseMoveEvents())
return true;
- if (node->IsElementNode()) {
- Element* element = ToElement(node);
+ if (auto* element = DynamicTo<Element>(node)) {
// Tapping on a text field or other focusable item should trigger
// adjustment, except that iframe elements are hard-coded to support focus
// but the effect is often invisible so they should be excluded.
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 1566385ead9..7ab6b3b84f1 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
@@ -69,10 +69,10 @@ void ValidationMessageClientImpl::ShowValidationMessage(
message_ = message;
page_->GetChromeClient().RegisterPopupOpeningObserver(this);
constexpr auto kMinimumTimeToShowValidationMessage =
- TimeDelta::FromSeconds(5);
- constexpr auto kTimePerCharacter = TimeDelta::FromMilliseconds(50);
+ base::TimeDelta::FromSeconds(5);
+ constexpr auto kTimePerCharacter = base::TimeDelta::FromMilliseconds(50);
finish_time_ =
- CurrentTimeTicks() +
+ base::TimeTicks::Now() +
std::max(kMinimumTimeToShowValidationMessage,
(message.length() + sub_message.length()) * kTimePerCharacter);
@@ -114,7 +114,8 @@ void ValidationMessageClientImpl::HideValidationMessage(const Element& anchor) {
&ValidationMessageClientImpl::Reset);
// This should be equal to or larger than transition duration of
// #container.hiding in validation_bubble.css.
- const TimeDelta kHidingAnimationDuration = TimeDelta::FromSecondsD(0.13333);
+ const base::TimeDelta kHidingAnimationDuration =
+ base::TimeDelta::FromSecondsD(0.13333);
timer_->StartOneShot(kHidingAnimationDuration, FROM_HERE);
}
@@ -131,7 +132,7 @@ void ValidationMessageClientImpl::Reset(TimerBase*) {
timer_ = nullptr;
current_anchor_ = nullptr;
message_ = String();
- finish_time_ = TimeTicks();
+ finish_time_ = base::TimeTicks();
overlay_ = nullptr;
overlay_delegate_ = nullptr;
page_->GetChromeClient().UnregisterPopupOpeningObserver(this);
@@ -163,7 +164,7 @@ void ValidationMessageClientImpl::DidChangeFocusTo(const Element* new_element) {
void ValidationMessageClientImpl::CheckAnchorStatus(TimerBase*) {
DCHECK(current_anchor_);
if ((!WebTestSupport::IsRunningWebTest() &&
- CurrentTimeTicks() >= finish_time_) ||
+ base::TimeTicks::Now() >= finish_time_) ||
!CurrentView()) {
HideValidationMessage(*current_anchor_);
return;
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 5ca11d34aed..ead9a0db738 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
@@ -79,7 +79,7 @@ class ValidationMessageClientImpl final
Member<Page> page_;
Member<const Element> current_anchor_;
String message_;
- TimeTicks finish_time_;
+ base::TimeTicks finish_time_;
std::unique_ptr<TimerBase> timer_;
std::unique_ptr<FrameOverlay> overlay_;
// Raw pointer. This pointer is valid unless overlay_ is nullptr.
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 a3696f216fa..8f738806995 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
@@ -149,7 +149,8 @@ void ValidationMessageOverlayDelegate::CreatePage(const FrameOverlay& overlay) {
main_settings.GetMinimumLogicalFontSize());
auto* frame = MakeGarbageCollected<LocalFrame>(
- MakeGarbageCollected<EmptyLocalFrameClient>(), *page_, nullptr);
+ MakeGarbageCollected<EmptyLocalFrameClient>(), *page_, nullptr, nullptr,
+ nullptr);
frame->SetView(MakeGarbageCollected<LocalFrameView>(*frame, view_size));
frame->Init();
frame->View()->SetCanHaveScrollbars(false);
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 d591eed71c2..3b4ca939c59 100644
--- a/chromium/third_party/blink/renderer/core/page/viewport_description.cc
+++ b/chromium/third_party/blink/renderer/core/page/viewport_description.cc
@@ -36,7 +36,7 @@
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/frame/visual_viewport.h"
#include "third_party/blink/renderer/core/page/page.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
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 b646fc165d9..6c5af02972b 100644
--- a/chromium/third_party/blink/renderer/core/page/viewport_description.h
+++ b/chromium/third_party/blink/renderer/core/page/viewport_description.h
@@ -35,7 +35,7 @@
#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/geometry/length.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/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 a0e3149fdc4..9d49455e941 100644
--- a/chromium/third_party/blink/renderer/core/page/viewport_test.cc
+++ b/chromium/third_party/blink/renderer/core/page/viewport_test.cc
@@ -2947,86 +2947,6 @@ TEST_F(ViewportTest, viewportLimitsAdjustedForUserScale) {
EXPECT_NEAR(1.0f, constraints.minimum_scale, 0.01f);
}
-TEST_F(ViewportTest, ViewportTriggersGpuRasterization) {
- frame_test_helpers::WebViewHelper web_view_helper;
-
- RegisterMockedHttpURLLoad(
- "viewport/viewport-gpu-rasterization-disabled-without-viewport.html");
- web_view_helper.InitializeAndLoad(
- base_url_ +
- "viewport/viewport-gpu-rasterization-disabled-without-viewport.html",
- nullptr, nullptr, nullptr, SetViewportSettings);
- web_view_helper.GetWebView()->MainFrameWidget()->Resize(WebSize(640, 480));
- content::LayerTreeView* compositor = web_view_helper.GetLayerTreeView();
- EXPECT_FALSE(compositor->layer_tree_host()->has_gpu_rasterization_trigger());
- // Also test that setting enableViewport to false (as on desktop Chrome)
- // supports GPU raster unconditionally.
- web_view_helper.InitializeAndLoad(
- base_url_ +
- "viewport/viewport-gpu-rasterization-disabled-without-viewport.html");
- web_view_helper.GetWebView()->MainFrameWidget()->Resize(WebSize(640, 480));
- compositor = web_view_helper.GetLayerTreeView();
- EXPECT_TRUE(compositor->layer_tree_host()->has_gpu_rasterization_trigger());
-
- RegisterMockedHttpURLLoad("viewport/viewport-gpu-rasterization.html");
- web_view_helper.InitializeAndLoad(
- base_url_ + "viewport/viewport-gpu-rasterization.html", nullptr, nullptr,
- nullptr, SetViewportSettings);
- web_view_helper.GetWebView()->MainFrameWidget()->Resize(WebSize(640, 480));
- compositor = web_view_helper.GetLayerTreeView();
- EXPECT_TRUE(compositor->layer_tree_host()->has_gpu_rasterization_trigger());
-
- RegisterMockedHttpURLLoad(
- "viewport/viewport-gpu-rasterization-expanded-heuristics.html");
- web_view_helper.InitializeAndLoad(
- base_url_ +
- "viewport/viewport-gpu-rasterization-expanded-heuristics.html",
- nullptr, nullptr, nullptr, SetViewportSettings);
- web_view_helper.GetWebView()->MainFrameWidget()->Resize(WebSize(640, 480));
- compositor = web_view_helper.GetLayerTreeView();
- EXPECT_TRUE(compositor->layer_tree_host()->has_gpu_rasterization_trigger());
-
- RegisterMockedHttpURLLoad("viewport/viewport-1.html");
- web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-1.html",
- nullptr, nullptr, nullptr,
- SetViewportSettings);
- web_view_helper.GetWebView()->MainFrameWidget()->Resize(WebSize(640, 480));
- compositor = web_view_helper.GetLayerTreeView();
- EXPECT_TRUE(compositor->layer_tree_host()->has_gpu_rasterization_trigger());
-
- RegisterMockedHttpURLLoad("viewport/viewport-15.html");
- web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-15.html",
- nullptr, nullptr, nullptr,
- SetViewportSettings);
- web_view_helper.GetWebView()->MainFrameWidget()->Resize(WebSize(640, 480));
- compositor = web_view_helper.GetLayerTreeView();
- EXPECT_TRUE(compositor->layer_tree_host()->has_gpu_rasterization_trigger());
-
- RegisterMockedHttpURLLoad("viewport/viewport-130.html");
- web_view_helper.InitializeAndLoad(base_url_ + "viewport/viewport-130.html",
- nullptr, nullptr, nullptr,
- SetViewportSettings);
- web_view_helper.GetWebView()->MainFrameWidget()->Resize(WebSize(640, 480));
- compositor = web_view_helper.GetLayerTreeView();
- EXPECT_TRUE(compositor->layer_tree_host()->has_gpu_rasterization_trigger());
-
- RegisterMockedHttpURLLoad("viewport/viewport-legacy-handheldfriendly.html");
- web_view_helper.InitializeAndLoad(
- base_url_ + "viewport/viewport-legacy-handheldfriendly.html", nullptr,
- nullptr, nullptr, SetViewportSettings);
- web_view_helper.GetWebView()->MainFrameWidget()->Resize(WebSize(640, 480));
- compositor = web_view_helper.GetLayerTreeView();
- EXPECT_TRUE(compositor->layer_tree_host()->has_gpu_rasterization_trigger());
-
- RegisterMockedHttpURLLoad("viewport/viewport-legacy-mobileoptimized.html");
- web_view_helper.InitializeAndLoad(
- base_url_ + "viewport/viewport-legacy-handheldfriendly.html", nullptr,
- nullptr, nullptr, SetViewportSettings);
- web_view_helper.GetWebView()->MainFrameWidget()->Resize(WebSize(640, 480));
- compositor = web_view_helper.GetLayerTreeView();
- EXPECT_TRUE(compositor->layer_tree_host()->has_gpu_rasterization_trigger());
-}
-
class ConsoleMessageWebFrameClient
: public frame_test_helpers::TestWebFrameClient {
public:
diff --git a/chromium/third_party/blink/renderer/core/page/zoom_test.cc b/chromium/third_party/blink/renderer/core/page/zoom_test.cc
new file mode 100644
index 00000000000..487d958607d
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/page/zoom_test.cc
@@ -0,0 +1,30 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "testing/gtest/include/gtest/gtest.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/frame/local_frame_view.h"
+#include "third_party/blink/renderer/core/testing/sim/sim_test.h"
+
+namespace blink {
+
+class FractionalZoomSimTest : public SimTest {};
+
+TEST_F(FractionalZoomSimTest, CheckCSSMediaQueryWidthEqualsWindowInnerWidth) {
+ WebView().MainFrameWidget()->Resize(WebSize(1081, 1921));
+
+ // 1081/2.75 = 393.091
+ // 1081/2.00 = 540.500
+ // 1081/1.50 = 720.667
+ std::vector<float> factors = {2.75f, 2.00f, 1.50f};
+ for (auto factor : factors) {
+ WebView().SetZoomFactorForDeviceScaleFactor(factor);
+ EXPECT_EQ(GetDocument().View()->ViewportSizeForMediaQueries().Width(),
+ GetDocument().GetFrame()->DomWindow()->innerWidth());
+ }
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/paint/BUILD.gn b/chromium/third_party/blink/renderer/core/paint/BUILD.gn
index ae24cb60180..1ca6694862b 100644
--- a/chromium/third_party/blink/renderer/core/paint/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/paint/BUILD.gn
@@ -69,6 +69,8 @@ blink_core_sources("paint") {
"details_marker_painter.h",
"document_marker_painter.cc",
"document_marker_painter.h",
+ "element_timing_utils.cc",
+ "element_timing_utils.h",
"ellipsis_box_painter.cc",
"ellipsis_box_painter.h",
"embedded_content_painter.cc",
@@ -111,6 +113,8 @@ blink_core_sources("paint") {
"inline_painter.h",
"inline_text_box_painter.cc",
"inline_text_box_painter.h",
+ "largest_contentful_paint_calculator.cc",
+ "largest_contentful_paint_calculator.h",
"line_box_list_painter.cc",
"line_box_list_painter.h",
"link_highlight_impl.cc",
@@ -157,6 +161,8 @@ blink_core_sources("paint") {
"paint_layer_clipper.cc",
"paint_layer_clipper.h",
"paint_layer_fragment.h",
+ "paint_layer_paint_order_iterator.cc",
+ "paint_layer_paint_order_iterator.h",
"paint_layer_painter.cc",
"paint_layer_painter.h",
"paint_layer_painting_info.h",
@@ -166,8 +172,6 @@ blink_core_sources("paint") {
"paint_layer_scrollable_area.h",
"paint_layer_stacking_node.cc",
"paint_layer_stacking_node.h",
- "paint_layer_stacking_node_iterator.cc",
- "paint_layer_stacking_node_iterator.h",
"paint_phase.cc",
"paint_phase.h",
"paint_property_tree_builder.cc",
@@ -179,6 +183,8 @@ blink_core_sources("paint") {
"paint_timing.h",
"paint_timing_detector.cc",
"paint_timing_detector.h",
+ "paint_timing_visualizer.cc",
+ "paint_timing_visualizer.h",
"pre_paint_tree_walk.cc",
"pre_paint_tree_walk.h",
"replaced_painter.cc",
diff --git a/chromium/third_party/blink/renderer/core/paint/DEPS b/chromium/third_party/blink/renderer/core/paint/DEPS
index 2e6dc92680e..25664f0f1f8 100644
--- a/chromium/third_party/blink/renderer/core/paint/DEPS
+++ b/chromium/third_party/blink/renderer/core/paint/DEPS
@@ -10,5 +10,8 @@ specific_include_rules = {
"(theme_painter|fallback_theme)\.cc": [
"+ui/native_theme/native_theme.h",
"+ui/native_theme/native_theme_base.h",
+ ],
+ ".*test\.cc": [
+ "+base/test/trace_event_analyzer.h",
]
}
diff --git a/chromium/third_party/blink/renderer/core/paint/applied_decoration_painter.h b/chromium/third_party/blink/renderer/core/paint/applied_decoration_painter.h
index 9f4ad517388..f7d49cea0c9 100644
--- a/chromium/third_party/blink/renderer/core/paint/applied_decoration_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/applied_decoration_painter.h
@@ -12,7 +12,7 @@
#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/path.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 a2d5a2db059..b940fb6c8bc 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
@@ -62,10 +62,10 @@ bool FixedBackgroundPaintsInLocalCoordinates(
return !mapping->BackgroundPaintsOntoScrollingContentsLayer();
}
-IntPoint AccumulatedScrollOffsetForFixedBackground(
+LayoutPoint AccumulatedScrollOffsetForFixedBackground(
const LayoutBoxModelObject& object,
const LayoutBoxModelObject* container) {
- IntPoint result;
+ LayoutPoint result;
if (&object == container)
return result;
@@ -410,10 +410,12 @@ LayoutRect FixedAttachmentPositioningArea(const LayoutBoxModelObject& obj,
if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) {
DCHECK_EQ(obj.GetBackgroundPaintLocation(),
kBackgroundPaintInScrollingContents);
- rect.SetLocation(IntPoint(ToLayoutView(obj).ScrolledContentOffset()));
+ rect.SetLocation(LayoutPoint(ToLayoutView(obj).ScrolledContentOffset()));
} else if (auto* mapping = obj.Layer()->GetCompositedLayerMapping()) {
- if (mapping->BackgroundPaintsOntoScrollingContentsLayer())
- rect.SetLocation(IntPoint(ToLayoutView(obj).ScrolledContentOffset()));
+ if (mapping->BackgroundPaintsOntoScrollingContentsLayer()) {
+ rect.SetLocation(
+ LayoutPoint(ToLayoutView(obj).ScrolledContentOffset()));
+ }
}
}
diff --git a/chromium/third_party/blink/renderer/core/paint/background_image_geometry.h b/chromium/third_party/blink/renderer/core/paint/background_image_geometry.h
index e4e7678b989..a5bc12b175f 100644
--- a/chromium/third_party/blink/renderer/core/paint/background_image_geometry.h
+++ b/chromium/third_party/blink/renderer/core/paint/background_image_geometry.h
@@ -11,7 +11,7 @@
#include "third_party/blink/renderer/platform/geometry/layout_rect.h"
#include "third_party/blink/renderer/platform/geometry/layout_size.h"
#include "third_party/blink/renderer/platform/graphics/graphics_types.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/block_flow_paint_invalidator.h b/chromium/third_party/blink/renderer/core/paint/block_flow_paint_invalidator.h
index 86f7581d79b..777c22faf11 100644
--- a/chromium/third_party/blink/renderer/core/paint/block_flow_paint_invalidator.h
+++ b/chromium/third_party/blink/renderer/core/paint/block_flow_paint_invalidator.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_BLOCK_FLOW_PAINT_INVALIDATOR_H_
#include "third_party/blink/renderer/platform/graphics/paint_invalidation_reason.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/block_paint_invalidator.h b/chromium/third_party/blink/renderer/core/paint/block_paint_invalidator.h
index 7101dbdc7ea..3cb6bae198d 100644
--- a/chromium/third_party/blink/renderer/core/paint/block_paint_invalidator.h
+++ b/chromium/third_party/blink/renderer/core/paint/block_paint_invalidator.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_BLOCK_PAINT_INVALIDATOR_H_
#include "third_party/blink/renderer/platform/graphics/paint_invalidation_reason.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 f0ecc527988..ba067627fdf 100644
--- a/chromium/third_party/blink/renderer/core/paint/block_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/block_painter.cc
@@ -5,6 +5,7 @@
#include "third_party/blink/renderer/core/paint/block_painter.h"
#include "base/optional.h"
+#include "third_party/blink/renderer/core/display_lock/display_lock_context.h"
#include "third_party/blink/renderer/core/editing/drag_caret.h"
#include "third_party/blink/renderer/core/editing/frame_selection.h"
#include "third_party/blink/renderer/core/layout/api/line_layout_api_shim.h"
@@ -12,16 +13,12 @@
#include "third_party/blink/renderer/core/layout/layout_inline.h"
#include "third_party/blink/renderer/core/layout/ng/layout_ng_block_flow.h"
#include "third_party/blink/renderer/core/page/page.h"
-#include "third_party/blink/renderer/core/paint/box_painter.h"
#include "third_party/blink/renderer/core/paint/line_box_list_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.h"
+#include "third_party/blink/renderer/core/paint/paint_timing_detector.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/platform/graphics/graphics_layer.h"
-#include "third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h"
-#include "third_party/blink/renderer/platform/graphics/paint/scroll_hit_test_display_item.h"
namespace blink {
@@ -52,11 +49,6 @@ void BlockPainter::Paint(const PaintInfo& paint_info) {
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);
@@ -72,7 +64,10 @@ void BlockPainter::Paint(const PaintInfo& paint_info) {
if (original_phase == PaintPhase::kMask) {
layout_block_.PaintObject(local_paint_info, paint_offset);
} else if (original_phase != PaintPhase::kSelfBlockBackgroundOnly &&
- original_phase != PaintPhase::kSelfOutlineOnly) {
+ original_phase != PaintPhase::kSelfOutlineOnly &&
+ // For now all scrollers with overlay scrollbars are self-painting
+ // layers, so we don't need to traverse descendants here.
+ original_phase != PaintPhase::kOverlayScrollbars) {
ScopedBoxContentsPaintState contents_paint_state(paint_state,
layout_block_);
layout_block_.PaintObject(contents_paint_state.GetPaintInfo(),
@@ -106,26 +101,19 @@ void BlockPainter::Paint(const PaintInfo& paint_info) {
layout_block_.PaintObject(local_paint_info, paint_offset);
}
- // Our scrollbar widgets paint exactly when we tell them to, so that they work
- // properly with z-index. We paint after we painted the background/border, so
- // that the scrollbars will sit above the background/border.
+ // We paint scrollbars after we painted the other things, so that the
+ // scrollbars will sit above them.
local_paint_info.phase = original_phase;
- PaintOverflowControlsIfNeeded(local_paint_info, paint_offset);
-}
-
-void BlockPainter::PaintOverflowControlsIfNeeded(
- const PaintInfo& paint_info,
- const PhysicalOffset& paint_offset) {
- if (layout_block_.HasOverflowClip() &&
- layout_block_.StyleRef().Visibility() == EVisibility::kVisible &&
- ShouldPaintSelfBlockBackground(paint_info.phase)) {
- ScrollableAreaPainter(*layout_block_.Layer()->GetScrollableArea())
- .PaintOverflowControls(paint_info, RoundedIntPoint(paint_offset),
- false /* painting_overlay_controls */);
+ if (auto* scrollable_area = layout_block_.GetScrollableArea()) {
+ ScrollableAreaPainter(*scrollable_area)
+ .PaintOverflowControls(local_paint_info, RoundedIntPoint(paint_offset));
}
}
void BlockPainter::PaintChildren(const PaintInfo& paint_info) {
+ if (layout_block_.PaintBlockedByDisplayLock(DisplayLockContext::kChildren))
+ return;
+
// We may use legacy paint to paint the anonymous fieldset child. The layout
// object for the rendered legend will be a child of that one, and has to be
// skipped here, since it's handled by a special NG fieldset painter.
@@ -169,6 +157,8 @@ void BlockPainter::PaintChild(const LayoutBox& child,
void BlockPainter::PaintChildrenAtomically(const OrderIterator& order_iterator,
const PaintInfo& paint_info) {
+ if (layout_block_.PaintBlockedByDisplayLock(DisplayLockContext::kChildren))
+ return;
for (const LayoutBox* child = order_iterator.First(); child;
child = order_iterator.Next()) {
PaintAllChildPhasesAtomically(*child, paint_info);
@@ -177,6 +167,8 @@ void BlockPainter::PaintChildrenAtomically(const OrderIterator& order_iterator,
void BlockPainter::PaintAllChildPhasesAtomically(const LayoutBox& child,
const PaintInfo& paint_info) {
+ if (layout_block_.PaintBlockedByDisplayLock(DisplayLockContext::kChildren))
+ return;
if (!child.HasSelfPaintingLayer() && !child.IsFloating())
ObjectPainter(child).PaintAllPhasesAtomically(paint_info);
}
@@ -196,36 +188,6 @@ void BlockPainter::PaintInlineBox(const InlineBox& inline_box,
.PaintAllPhasesAtomically(paint_info);
}
-void BlockPainter::PaintScrollHitTestDisplayItem(const PaintInfo& paint_info) {
- DCHECK(RuntimeEnabledFeatures::CompositeAfterPaintEnabled());
-
- // Scroll 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;
-
- // The scroll hit test layer is in the unscrolled and unclipped space so the
- // scroll hit test layer can be enlarged beyond the clip. This will let us fix
- // crbug.com/753124 in the future where the scrolling element's border is hit
- // test differently if composited.
-
- const auto* fragment = paint_info.FragmentToPaint(layout_block_);
- const auto* properties = fragment ? fragment->PaintProperties() : nullptr;
-
- // If there is an associated scroll node, emit a scroll hit test display item.
- if (properties && properties->Scroll()) {
- DCHECK(properties->ScrollTranslation());
- // The local border box properties are used instead of the contents
- // properties so that the scroll hit test is not clipped or scrolled.
- ScopedPaintChunkProperties scroll_hit_test_properties(
- paint_info.context.GetPaintController(),
- fragment->LocalBorderBoxProperties(), layout_block_,
- DisplayItem::kScrollHitTest);
- ScrollHitTestDisplayItem::Record(paint_info.context, layout_block_,
- *properties->ScrollTranslation());
- }
-}
-
DISABLE_CFI_PERF
void BlockPainter::PaintObject(const PaintInfo& paint_info,
const PhysicalOffset& paint_offset) {
@@ -242,6 +204,17 @@ void BlockPainter::PaintObject(const PaintInfo& paint_info,
if (layout_block_.IsTruncated())
return;
+ ScopedPaintTimingDetectorBlockPaintHook
+ scoped_paint_timing_detector_block_paint_hook;
+ if (RuntimeEnabledFeatures::FirstContentfulPaintPlusPlusEnabled() ||
+ RuntimeEnabledFeatures::ElementTimingEnabled(
+ &layout_block_.GetDocument())) {
+ if (paint_info.phase == PaintPhase::kForeground) {
+ scoped_paint_timing_detector_block_paint_hook.EmplaceIfNeeded(
+ layout_block_, paint_info.context.GetPaintController()
+ .CurrentPaintChunkProperties());
+ }
+ }
// If we're *printing* the foreground, paint the URL.
if (paint_phase == PaintPhase::kForeground && paint_info.IsPrinting()) {
ObjectPainter(layout_block_)
@@ -293,7 +266,7 @@ void BlockPainter::PaintBlockFlowContents(const PaintInfo& paint_info,
ObjectPainter(layout_block_).PaintInlineChildrenOutlines(paint_info);
} else {
LineBoxListPainter(To<LayoutBlockFlow>(layout_block_).LineBoxes())
- .Paint(layout_block_, paint_info, paint_offset.ToLayoutPoint());
+ .Paint(layout_block_, paint_info, paint_offset);
}
// If we don't have any floats to paint, or we're in the wrong paint phase,
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 a4a0776c641..40d7dac7750 100644
--- a/chromium/third_party/blink/renderer/core/paint/block_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/block_painter.h
@@ -9,7 +9,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/layout/order_iterator.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/allocator/allocator.h"
namespace blink {
@@ -32,8 +32,6 @@ class BlockPainter {
void PaintContents(const PaintInfo&, const PhysicalOffset& paint_offset);
void PaintChildren(const PaintInfo&);
void PaintChild(const LayoutBox&, const PaintInfo&);
- void PaintOverflowControlsIfNeeded(const PaintInfo&,
- const PhysicalOffset& paint_offset);
// See ObjectPainter::PaintAllPhasesAtomically().
void PaintAllChildPhasesAtomically(const LayoutBox&, const PaintInfo&);
@@ -41,9 +39,6 @@ class BlockPainter {
static void PaintInlineBox(const InlineBox&, const PaintInfo&);
private:
- // Paint scroll hit test placeholders in the correct paint order (see:
- // ScrollHitTestDisplayItem.h).
- void PaintScrollHitTestDisplayItem(const PaintInfo&);
void PaintBlockFlowContents(const PaintInfo&, const PhysicalOffset&);
void PaintCarets(const PaintInfo&, const PhysicalOffset& 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 3736f579f79..3977e7b94de 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
@@ -22,170 +22,6 @@ using BlockPainterTest = PaintControllerPaintTest;
INSTANTIATE_PAINT_TEST_SUITE_P(BlockPainterTest);
-TEST_P(BlockPainterTest, ScrollHitTestProperties) {
- if (!RuntimeEnabledFeatures::CompositeAfterPaintEnabled())
- return;
- SetBodyInnerHTML(R"HTML(
- <style>
- ::-webkit-scrollbar { display: none; }
- body { margin: 0 }
- #container { width: 200px; height: 200px;
- overflow: scroll; background: blue; }
- #child { width: 100px; height: 300px; background: green; }
- </style>
- <div id='container'>
- <div id='child'></div>
- </div>
- )HTML");
-
- auto& container = To<LayoutBlock>(*GetLayoutObjectByElementId("container"));
- auto& child = *GetLayoutObjectByElementId("child");
-
- // The scroll hit test should be after the container background but before the
- // scrolled contents.
- 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.
- 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.
- 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.
- 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.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.
- 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());
- 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
- // translation node and the contents should be scrolled by this node.
- const auto& scroll_hit_test_display_item =
- static_cast<const ScrollHitTestDisplayItem&>(
- RootPaintController()
- .GetDisplayItemList()[scroll_hit_test_chunk.begin_index]);
- EXPECT_EQ(&contents_transform,
- &scroll_hit_test_display_item.scroll_offset_node());
-}
-
-TEST_P(BlockPainterTest, FrameScrollHitTestProperties) {
- if (!RuntimeEnabledFeatures::CompositeAfterPaintEnabled())
- return;
- SetBodyInnerHTML(R"HTML(
- <style>
- ::-webkit-scrollbar { display: none; }
- body { margin: 0; }
- #child { width: 100px; height: 2000px; background: green; }
- </style>
- <div id='child'></div>
- )HTML");
-
- auto& html =
- To<LayoutBlock>(*GetDocument().documentElement()->GetLayoutObject());
- auto& child = *GetLayoutObjectByElementId("child");
-
- // The scroll hit test should be after the document background but before the
- // scrolled contents.
- 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.
- 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());
- 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.
- 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());
- 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
- // translation node and the contents should be scrolled by this node.
- const auto& scroll_hit_test_display_item =
- static_cast<const ScrollHitTestDisplayItem&>(
- RootPaintController()
- .GetDisplayItemList()[scroll_hit_test_chunk.begin_index]);
- EXPECT_EQ(&contents_transform,
- &scroll_hit_test_display_item.scroll_offset_node());
-}
-
TEST_P(BlockPainterTest, OverflowRectForCullRectTesting) {
SetBodyInnerHTML(R"HTML(
<div id='scroller' style='width: 50px; height: 50px; overflow: scroll'>
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 682ce2ee3a9..eed39f2c998 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
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/layout/background_bleed_avoidance.h"
#include "third_party/blink/renderer/core/paint/box_painter_base.h"
#include "third_party/blink/renderer/platform/geometry/layout_size.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 2954491fce5..f1db8274944 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
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/graphics/paint_invalidation_reason.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 634d771acd8..22b78a04089 100644
--- a/chromium/third_party/blink/renderer/core/paint/box_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/box_painter.cc
@@ -5,6 +5,7 @@
#include "third_party/blink/renderer/core/paint/box_painter.h"
#include "base/optional.h"
+#include "third_party/blink/renderer/core/display_lock/display_lock_context.h"
#include "third_party/blink/renderer/core/layout/background_bleed_avoidance.h"
#include "third_party/blink/renderer/core/layout/layout_box.h"
#include "third_party/blink/renderer/core/layout/layout_object.h"
@@ -29,6 +30,7 @@
#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/graphics/paint/scroll_hit_test_display_item.h"
namespace blink {
@@ -39,6 +41,9 @@ void BoxPainter::Paint(const PaintInfo& paint_info) {
}
void BoxPainter::PaintChildren(const PaintInfo& paint_info) {
+ if (layout_box_.PaintBlockedByDisplayLock(DisplayLockContext::kChildren))
+ return;
+
PaintInfo child_info(paint_info);
for (LayoutObject* child = layout_box_.SlowFirstChild(); child;
child = child->NextSibling()) {
@@ -57,8 +62,9 @@ void BoxPainter::PaintBoxDecorationBackground(
PhysicalRect paint_rect;
const DisplayItemClient* background_client = nullptr;
base::Optional<ScopedBoxContentsPaintState> contents_paint_state;
- if (BoxDecorationData::IsPaintingScrollingBackground(paint_info,
- layout_box_)) {
+ bool painting_scrolling_background =
+ BoxDecorationData::IsPaintingScrollingBackground(paint_info, layout_box_);
+ if (painting_scrolling_background) {
// 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.
@@ -91,6 +97,14 @@ void BoxPainter::PaintBoxDecorationBackground(
}
RecordHitTestData(paint_info, paint_rect, *background_client);
+
+ if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) {
+ // 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 non-scrolling background.
+ if (!painting_scrolling_background)
+ RecordScrollHitTestData(paint_info, *background_client);
+ }
}
bool BoxPainter::BackgroundIsKnownToBeOpaque(const PaintInfo& paint_info) {
@@ -283,4 +297,41 @@ void BoxPainter::RecordHitTestData(const PaintInfo& paint_info,
HitTestRect(paint_rect.ToLayoutRect(), touch_action));
}
+void BoxPainter::RecordScrollHitTestData(
+ const PaintInfo& paint_info,
+ const DisplayItemClient& background_client) {
+ DCHECK(RuntimeEnabledFeatures::CompositeAfterPaintEnabled());
+
+ // 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 scroll.
+ if (layout_box_.StyleRef().Visibility() != EVisibility::kVisible)
+ return;
+
+ // Only create scroll hit test data for objects that scroll.
+ if (!layout_box_.GetScrollableArea() ||
+ !layout_box_.GetScrollableArea()->ScrollsOverflow()) {
+ return;
+ }
+
+ const auto* fragment = paint_info.FragmentToPaint(layout_box_);
+ const auto* properties = fragment ? fragment->PaintProperties() : nullptr;
+
+ // If there is an associated scroll node, emit a scroll hit test display item.
+ if (properties && properties->Scroll()) {
+ DCHECK(properties->ScrollTranslation());
+ // The local border box properties are used instead of the contents
+ // properties so that the scroll hit test is not clipped or scrolled.
+ ScopedPaintChunkProperties scroll_hit_test_properties(
+ paint_info.context.GetPaintController(),
+ fragment->LocalBorderBoxProperties(), background_client,
+ DisplayItem::kScrollHitTest);
+ ScrollHitTestDisplayItem::Record(paint_info.context, background_client,
+ *properties->ScrollTranslation());
+ }
+}
+
} // 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 ccabfa34768..0b79434cf20 100644
--- a/chromium/third_party/blink/renderer/core/paint/box_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/box_painter.h
@@ -9,7 +9,7 @@
#include "third_party/blink/renderer/core/paint/rounded_inner_rect_clipper.h"
#include "third_party/blink/renderer/platform/geometry/layout_size.h"
#include "third_party/blink/renderer/platform/graphics/graphics_types.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -45,6 +45,12 @@ class BoxPainter {
const PhysicalRect& paint_rect,
const DisplayItemClient& background_client);
+ // Paint a scroll hit test display item and record scroll hit test data. This
+ // should be called in the background paint phase even if there is no other
+ // painted content.
+ void RecordScrollHitTestData(const PaintInfo&,
+ 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 ef09329a8b4..b174873bd30 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
@@ -19,6 +19,7 @@
#include "third_party/blink/renderer/core/style/border_edge.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/core/style/shadow_list.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/graphics_context_state_saver.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_controller.h"
@@ -552,7 +553,7 @@ inline bool PaintFastBottomLayer(Node* node,
if (RuntimeEnabledFeatures::FirstContentfulPaintPlusPlusEnabled()) {
if (info.image && info.image->IsImageResource()) {
PaintTimingDetector::NotifyBackgroundImagePaint(
- node, image, info.image->CachedImage(),
+ node, image, To<StyleFetchedImage>(info.image.Get()),
paint_info.context.GetPaintController()
.CurrentPaintChunkProperties());
}
@@ -563,7 +564,7 @@ inline bool PaintFastBottomLayer(Node* node,
LocalDOMWindow* window = node->GetDocument().domWindow();
DCHECK(window);
ImageElementTiming::From(*window).NotifyBackgroundImagePainted(
- node, info.image,
+ node, To<StyleFetchedImage>(info.image.Get()),
context.GetPaintController().CurrentPaintChunkProperties());
}
return true;
@@ -685,7 +686,7 @@ void PaintFillLayerBackground(GraphicsContext& context,
if (RuntimeEnabledFeatures::FirstContentfulPaintPlusPlusEnabled()) {
if (info.image && info.image->IsImageResource()) {
PaintTimingDetector::NotifyBackgroundImagePaint(
- node, image, info.image->CachedImage(),
+ node, image, To<StyleFetchedImage>(info.image.Get()),
context.GetPaintController().CurrentPaintChunkProperties());
}
}
@@ -695,7 +696,7 @@ void PaintFillLayerBackground(GraphicsContext& context,
LocalDOMWindow* window = node->GetDocument().domWindow();
DCHECK(window);
ImageElementTiming::From(*window).NotifyBackgroundImagePainted(
- node, info.image,
+ node, To<StyleFetchedImage>(info.image.Get()),
context.GetPaintController().CurrentPaintChunkProperties());
}
}
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 ec244ade950..b56d40b52a1 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
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/style/style_image.h"
#include "third_party/blink/renderer/platform/geometry/layout_rect_outsets.h"
#include "third_party/blink/renderer/platform/graphics/color.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/skia/include/core/SkBlendMode.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/box_painter_test.cc b/chromium/third_party/blink/renderer/core/paint/box_painter_test.cc
index 6d0e9a8700f..f384f5a7d18 100644
--- a/chromium/third_party/blink/renderer/core/paint/box_painter_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/box_painter_test.cc
@@ -6,6 +6,7 @@
#include "testing/gmock/include/gmock/gmock.h"
#include "third_party/blink/renderer/core/paint/paint_controller_paint_test.h"
+#include "third_party/blink/renderer/platform/graphics/paint/scroll_hit_test_display_item.h"
using testing::ElementsAre;
@@ -33,4 +34,189 @@ TEST_P(BoxPainterTest, DontPaintEmptyDecorationBackground) {
PaintPhase::kSelfOutlineOnly))));
}
+TEST_P(BoxPainterTest, ScrollHitTestOrderWithScrollBackgroundAttachment) {
+ // Only CompositeAfterPaint supports scroll hit test display items.
+ if (!RuntimeEnabledFeatures::CompositeAfterPaintEnabled())
+ return;
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ ::-webkit-scrollbar { display: none; }
+ body { margin: 0; }
+ #container {
+ width: 200px;
+ height: 200px;
+ overflow-y: scroll;
+ background: linear-gradient(yellow, blue);
+ background-attachment: scroll;
+ will-change: transform;
+ }
+ #child { height: 300px; width: 10px; background: blue; }
+ </style>
+ <div id='container'>
+ <div id='child'></div>
+ </div>
+ )HTML");
+
+ auto& container = *GetLayoutObjectByElementId("container");
+ auto& child = *GetLayoutObjectByElementId("child");
+
+ // As a reminder, "background-attachment: scroll" does not move when the
+ // container's scroll offset changes.
+
+ // The scroll hit test should be after the non-scrolling (attachment:
+ // scroll) container background so that it does not prevent squashing the
+ // non-scrolling container background into the root layer.
+ EXPECT_THAT(RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&ViewScrollingBackgroundClient(),
+ kDocumentBackgroundType),
+ IsSameId(&container, kBackgroundType),
+ IsSameId(&container, kScrollHitTestType),
+ IsSameId(&child, kBackgroundType)));
+}
+
+TEST_P(BoxPainterTest, ScrollHitTestOrderWithLocalBackgroundAttachment) {
+ // Only CompositeAfterPaint supports scroll hit test display items.
+ if (!RuntimeEnabledFeatures::CompositeAfterPaintEnabled())
+ return;
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ ::-webkit-scrollbar { display: none; }
+ body { margin: 0; }
+ #container {
+ width: 200px;
+ height: 200px;
+ overflow-y: scroll;
+ background: linear-gradient(yellow, blue);
+ background-attachment: local;
+ will-change: transform;
+ }
+ #child { height: 300px; width: 10px; background: blue; }
+ </style>
+ <div id='container'>
+ <div id='child'></div>
+ </div>
+ )HTML");
+
+ auto& container = ToLayoutBox(*GetLayoutObjectByElementId("container"));
+ auto& child = *GetLayoutObjectByElementId("child");
+ auto* container_scrolling_client =
+ &container.GetScrollableArea()->GetScrollingBackgroundDisplayItemClient();
+
+ // As a reminder, "background-attachment: local" moves when the container's
+ // scroll offset changes.
+
+ // The scroll hit test should be before the scrolling (attachment: local)
+ // container background so that it does not prevent squashing the scrolling
+ // background into the scrolling contents.
+ EXPECT_THAT(RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&ViewScrollingBackgroundClient(),
+ kDocumentBackgroundType),
+ IsSameId(&container, kScrollHitTestType),
+ IsSameId(container_scrolling_client, kBackgroundType),
+ IsSameId(&child, kBackgroundType)));
+}
+
+TEST_P(BoxPainterTest, ScrollHitTestProperties) {
+ // This test depends on the CompositeAfterPaint behavior of painting solid
+ // color backgrounds into both the non-scrolled and scrolled spaces.
+ if (!RuntimeEnabledFeatures::CompositeAfterPaintEnabled())
+ return;
+
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ ::-webkit-scrollbar { display: none; }
+ body { margin: 0; }
+ #container {
+ width: 200px;
+ height: 200px;
+ overflow-y: scroll;
+ background: green;
+ }
+ #child { width: 100px; height: 300px; background: green; }
+ </style>
+ <div id='container'>
+ <div id='child'></div>
+ </div>
+ )HTML");
+
+ auto& container = To<LayoutBlock>(*GetLayoutObjectByElementId("container"));
+ const auto& paint_chunks = RootPaintController().PaintChunks();
+ auto& child = *GetLayoutObjectByElementId("child");
+
+ // The scroll hit test should be after the container background but before the
+ // scrolled contents.
+ 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& scrolling_contents_properties =
+ container.FirstFragment().ContentsProperties();
+ 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),
+ scrolling_contents_properties)));
+
+ // The document should not scroll so there should be no scroll offset
+ // 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.
+ 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.
+ 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.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.
+ 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());
+ 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
+ // translation node and the contents should be scrolled by this node.
+ const auto& scroll_hit_test_display_item =
+ static_cast<const ScrollHitTestDisplayItem&>(
+ RootPaintController()
+ .GetDisplayItemList()[scroll_hit_test_chunk.begin_index]);
+ EXPECT_EQ(&contents_transform,
+ &scroll_hit_test_display_item.scroll_offset_node());
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/paint/clip_rect.cc b/chromium/third_party/blink/renderer/core/paint/clip_rect.cc
index b72162bab0f..bfb3c2ef085 100644
--- a/chromium/third_party/blink/renderer/core/paint/clip_rect.cc
+++ b/chromium/third_party/blink/renderer/core/paint/clip_rect.cc
@@ -34,21 +34,24 @@
namespace blink {
ClipRect::ClipRect()
- : rect_(LayoutRect::InfiniteIntRect()),
+ : rect_(PhysicalRect::InfiniteIntRect()),
has_radius_(false),
is_infinite_(true) {}
-ClipRect::ClipRect(const FloatClipRect& rect)
- : rect_(PhysicalRect::EnclosingRect(rect.Rect())),
- has_radius_(rect.HasRadius()),
- is_infinite_(rect.IsInfinite()) {}
+ClipRect::ClipRect(const FloatClipRect& rect) {
+ SetRectInternal(rect);
+}
void ClipRect::SetRect(const FloatClipRect& rect) {
if (rect.IsInfinite() && IsInfinite())
return;
- rect_ = PhysicalRect::EnclosingRect(rect.Rect());
+ SetRectInternal(rect);
+}
+
+void ClipRect::SetRectInternal(const FloatClipRect& rect) {
has_radius_ = rect.HasRadius();
is_infinite_ = rect.IsInfinite();
+ rect_ = PhysicalRect::FastAndLossyFromFloatRect(rect.Rect());
}
void ClipRect::SetRect(const PhysicalRect& rect) {
@@ -77,7 +80,7 @@ void ClipRect::Intersect(const ClipRect& other) {
bool ClipRect::Intersects(const HitTestLocation& hit_test_location) const {
if (is_infinite_)
return true;
- return hit_test_location.Intersects(rect_.ToLayoutRect());
+ return hit_test_location.Intersects(rect_);
}
void ClipRect::Reset() {
diff --git a/chromium/third_party/blink/renderer/core/paint/clip_rect.h b/chromium/third_party/blink/renderer/core/paint/clip_rect.h
index 8813c67c69e..67ab7283135 100644
--- a/chromium/third_party/blink/renderer/core/paint/clip_rect.h
+++ b/chromium/third_party/blink/renderer/core/paint/clip_rect.h
@@ -28,7 +28,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/layout/geometry/physical_rect.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -84,6 +84,8 @@ class CORE_EXPORT ClipRect {
String ToString() const;
private:
+ void SetRectInternal(const FloatClipRect&);
+
PhysicalRect rect_;
bool has_radius_ : 1;
bool is_infinite_ : 1;
diff --git a/chromium/third_party/blink/renderer/core/paint/collapsed_border_painter.h b/chromium/third_party/blink/renderer/core/paint/collapsed_border_painter.h
index 3fccd0cfc3c..2b117e207ab 100644
--- a/chromium/third_party/blink/renderer/core/paint/collapsed_border_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/collapsed_border_painter.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/layout/layout_table.h"
#include "third_party/blink/renderer/core/layout/layout_table_cell.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.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 667ca7afa0b..e953626e45f 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
@@ -30,6 +30,7 @@
#include "cc/input/overscroll_behavior.h"
#include "cc/layers/picture_layer.h"
#include "third_party/blink/renderer/core/accessibility/apply_dark_mode.h"
+#include "third_party/blink/renderer/core/display_lock/display_lock_utilities.h"
#include "third_party/blink/renderer/core/dom/dom_node_ids.h"
#include "third_party/blink/renderer/core/exported/web_plugin_container_impl.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
@@ -44,12 +45,12 @@
#include "third_party/blink/renderer/core/html/media/html_video_element.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/layout/geometry/transform_state.h"
-#include "third_party/blink/renderer/core/layout/jank_tracker.h"
#include "third_party/blink/renderer/core/layout/layout_embedded_content.h"
#include "third_party/blink/renderer/core/layout/layout_embedded_object.h"
#include "third_party/blink/renderer/core/layout/layout_html_canvas.h"
#include "third_party/blink/renderer/core/layout/layout_image.h"
#include "third_party/blink/renderer/core/layout/layout_inline.h"
+#include "third_party/blink/renderer/core/layout/layout_shift_tracker.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/loader/resource/image_resource_content.h"
@@ -64,9 +65,9 @@
#include "third_party/blink/renderer/core/paint/frame_paint_timing.h"
#include "third_party/blink/renderer/core/paint/object_paint_invalidator.h"
#include "third_party/blink/renderer/core/paint/paint_info.h"
+#include "third_party/blink/renderer/core/paint/paint_layer_paint_order_iterator.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/paint/paint_layer_stacking_node_iterator.h"
#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"
@@ -366,7 +367,7 @@ void CompositedLayerMapping::UpdateStickyConstraints(
constraint.top_offset = constraints.top_offset;
constraint.bottom_offset = constraints.bottom_offset;
constraint.constraint_box_rect =
- GetLayoutObject().ComputeStickyConstrainingRect();
+ RoundedIntRect(GetLayoutObject().ComputeStickyConstrainingRect());
constraint.scroll_container_relative_sticky_box_rect =
RoundedIntRect(constraints.scroll_container_relative_sticky_box_rect);
constraint.scroll_container_relative_containing_block_rect = RoundedIntRect(
@@ -401,8 +402,7 @@ void CompositedLayerMapping::UpdateIsRootForIsolatedGroup() {
bool isolate = owning_layer_.ShouldIsolateCompositedDescendants();
// non stacking context layers should never isolate
- DCHECK((owning_layer_.StackingNode() &&
- owning_layer_.GetLayoutObject().StyleRef().IsStackingContext()) ||
+ DCHECK(owning_layer_.GetLayoutObject().StyleRef().IsStackingContext() ||
!isolate);
graphics_layer_->SetIsRootForIsolatedGroup(isolate);
@@ -1117,10 +1117,6 @@ void CompositedLayerMapping::UpdateSquashingLayerGeometry(
layers[i].offset_from_layout_object != new_offset_from_layout_object) {
ObjectPaintInvalidator(layers[i].paint_layer->GetLayoutObject())
.InvalidatePaintIncludingNonCompositingDescendants();
-
- TRACE_LAYER_INVALIDATION(layers[i].paint_layer,
- inspector_layer_invalidation_tracking_event::
- kSquashingLayerGeometryWasUpdated);
layers_needing_paint_invalidation.push_back(layers[i].paint_layer);
}
layers[i].offset_from_layout_object = new_offset_from_layout_object;
@@ -1329,7 +1325,7 @@ void CompositedLayerMapping::UpdateMainGraphicsLayerGeometry(
update_context.parent_object_offset_delta;
if (!layout_object_delta.IsZero()) {
LocalFrameView* frame_view = layout_object.View()->GetFrameView();
- frame_view->GetJankTracker().NotifyCompositedLayerMoved(
+ frame_view->GetLayoutShiftTracker().NotifyCompositedLayerMoved(
layout_object,
FloatRect(FloatPoint(), FloatSize(old_size - old_object_offset)),
FloatRect(FloatPoint(layout_object_delta),
@@ -1380,7 +1376,7 @@ void CompositedLayerMapping::ComputeGraphicsLayerParentLocation(
compositing_container->NeedsCompositedScrolling()) {
LayoutBox& layout_box =
ToLayoutBox(compositing_container->GetLayoutObject());
- IntSize scroll_offset = layout_box.ScrolledContentOffset();
+ IntSize scroll_offset = FlooredIntSize(layout_box.ScrolledContentOffset());
IntPoint scroll_origin =
compositing_container->GetScrollableArea()->ScrollOrigin();
scroll_origin.Move(-layout_box.OriginAdjustmentForScrollbars());
@@ -2439,6 +2435,12 @@ bool CompositedLayerMapping::UpdateMaskLayer(bool needs_mask_layer) {
if (!mask_layer_) {
mask_layer_ = CreateGraphicsLayer(CompositingReason::kLayerForMask);
mask_layer_->SetPaintingPhase(kGraphicsLayerPaintMask);
+ CompositorElementId element_id = CompositorElementIdFromUniqueObjectId(
+ owning_layer_.GetLayoutObject().UniqueId(),
+ CompositorElementIdNamespace::kEffectMask);
+ mask_layer_->SetElementId(element_id);
+ mask_layer_->CcLayer()->SetLayerMaskType(
+ cc::Layer::LayerMaskType::SINGLE_TEXTURE_MASK);
layer_changed = true;
}
} else if (mask_layer_) {
@@ -2777,16 +2779,8 @@ bool CompositedLayerMapping::HasVisibleNonCompositingDescendant(
if (!parent->HasVisibleDescendant())
return false;
- if (!parent->StackingNode())
- return false;
-
-#if DCHECK_IS_ON()
- LayerListMutationDetector mutation_checker(parent->StackingNode());
-#endif
-
- PaintLayerStackingNodeIterator normal_flow_iterator(*parent->StackingNode(),
- kAllChildren);
- while (PaintLayer* child_layer = normal_flow_iterator.Next()) {
+ PaintLayerPaintOrderIterator iterator(*parent, kAllChildren);
+ while (PaintLayer* child_layer = iterator.Next()) {
if (child_layer->HasCompositedLayerMapping())
continue;
if (child_layer->HasVisibleContent() ||
@@ -2883,7 +2877,9 @@ bool CompositedLayerMapping::IsDirectlyCompositedImage() const {
void CompositedLayerMapping::ContentChanged(ContentChangeType change_type) {
if ((change_type == kImageChanged) && GetLayoutObject().IsImage() &&
IsDirectlyCompositedImage()) {
- UpdateImageContents();
+ SetNeedsGraphicsLayerUpdate(kGraphicsLayerUpdateLocal);
+ Compositor()->SetNeedsCompositingUpdate(
+ kCompositingUpdateAfterGeometryChange);
return;
}
@@ -2895,6 +2891,9 @@ void CompositedLayerMapping::ContentChanged(ContentChangeType change_type) {
}
void CompositedLayerMapping::UpdateImageContents() {
+ DCHECK_EQ(owning_layer_.Compositor()->Lifecycle().GetState(),
+ DocumentLifecycle::kInCompositingUpdate);
+
DCHECK(GetLayoutObject().IsImage());
LayoutImage& image_layout_object = ToLayoutImage(GetLayoutObject());
@@ -2962,12 +2961,7 @@ PhysicalRect CompositedLayerMapping::ContentsBox() const {
}
bool CompositedLayerMapping::NeedsToReparentOverflowControls() const {
- const ComputedStyle& style = owning_layer_.GetLayoutObject().StyleRef();
- return owning_layer_.GetScrollableArea() &&
- owning_layer_.GetScrollableArea()->HasOverlayScrollbars() &&
- !style.IsStackingContext() &&
- (style.IsStacked() ||
- owning_layer_.IsNonStackedWithInFlowStackedDescendant());
+ return owning_layer_.NeedsReorderOverlayScrollbars();
}
GraphicsLayer* CompositedLayerMapping::DetachLayerForOverflowControls() {
@@ -3185,13 +3179,6 @@ void CompositedLayerMapping::DoPaintTask(
paint_info.paint_layer->SubpixelAccumulation());
PaintLayerPainter(*paint_info.paint_layer)
.PaintLayerContents(context, painting_info, paint_layer_flags);
-
- if (paint_info.paint_layer->ContainsDirtyOverlayScrollbars()) {
- PaintLayerPainter(*paint_info.paint_layer)
- .PaintLayerContents(
- context, painting_info,
- paint_layer_flags | kPaintLayerPaintingOverlayScrollbars);
- }
} else {
PaintLayerPaintingInfo painting_info(
paint_info.paint_layer, CullRect(dirty_rect), kGlobalPaintNormalPhase,
@@ -3265,6 +3252,37 @@ IntRect CompositedLayerMapping::RecomputeInterestRect(
// cases, fall back to painting the first kPixelDistanceToRecord pixels in
// each direction.
+ // Note that since the interest rect mapping above can produce extremely
+ // large numbers in cases of perspective, try our best to "normalize" the
+ // result by ensuring that none of the rect dimensions exceed some large,
+ // but reasonable, limit.
+ const float reasonable_pixel_limit = std::numeric_limits<int>::max() / 2.f;
+ auto unpadded_intersection = local_interest_rect;
+
+ // Note that by clamping X and Y, we are effectively moving the rect right /
+ // down. However, this will at most make us paint more content, which is
+ // better than erroneously deciding that the rect produced here is far
+ // offscreen.
+ if (unpadded_intersection.X() < -reasonable_pixel_limit)
+ unpadded_intersection.SetX(-reasonable_pixel_limit);
+ if (unpadded_intersection.Y() < -reasonable_pixel_limit)
+ unpadded_intersection.SetY(-reasonable_pixel_limit);
+ if (unpadded_intersection.MaxX() > reasonable_pixel_limit) {
+ unpadded_intersection.SetWidth(reasonable_pixel_limit -
+ unpadded_intersection.X());
+ }
+ if (unpadded_intersection.MaxY() > reasonable_pixel_limit) {
+ unpadded_intersection.SetHeight(reasonable_pixel_limit -
+ unpadded_intersection.Y());
+ }
+
+ unpadded_intersection.Intersect(FloatRect(graphics_layer_bounds));
+ // If our unpadded intersection is not empty, then use that before padding,
+ // since it can produce more stable results, and it would not produce any
+ // smaller area than if we used the original local interest rect.
+ if (!unpadded_intersection.IsEmpty())
+ local_interest_rect = unpadded_intersection;
+
// Expand by interest rect padding amount, scaled by the approximate scale
// of the GraphicsLayer relative to screen pixels. If width or height
// are zero or nearly zero, fall back to kPixelDistanceToRecord.
@@ -3277,8 +3295,13 @@ IntRect CompositedLayerMapping::RecomputeInterestRect(
visible_content_rect.Height() > std::numeric_limits<float>::epsilon()
? local_interest_rect.Height() / visible_content_rect.Height()
: 1.0f;
- local_interest_rect.InflateX(kPixelDistanceToRecord * x_scale);
- local_interest_rect.InflateY(kPixelDistanceToRecord * y_scale);
+ // Take the max, to account for situations like rotation transforms, which
+ // swap x and y.
+ // Since at this point we can also have an extremely large scale due to
+ // perspective (see the comments above), cap it to something reasonable.
+ float scale = std::min(std::max(x_scale, y_scale),
+ reasonable_pixel_limit / kPixelDistanceToRecord);
+ local_interest_rect.Inflate(kPixelDistanceToRecord * scale);
} else {
// Expand by interest rect padding amount.
local_interest_rect.Inflate(kPixelDistanceToRecord);
@@ -3506,6 +3529,10 @@ bool CompositedLayerMapping::ShouldThrottleRendering() const {
return GetLayoutObject().GetFrame()->ShouldThrottleRendering();
}
+bool CompositedLayerMapping::IsUnderSVGHiddenContainer() const {
+ return owning_layer_.IsUnderSVGHiddenContainer();
+}
+
bool CompositedLayerMapping::IsTrackingRasterInvalidations() const {
return GetLayoutObject().GetFrameView()->IsTrackingPaintInvalidations();
}
@@ -3521,8 +3548,29 @@ void CompositedLayerMapping::GraphicsLayersDidChange() {
frame_view->GraphicsLayersDidChange();
}
-bool CompositedLayerMapping::PaintBlockedByDisplayLock() const {
- return GetLayoutObject().PaintBlockedByDisplayLock();
+bool CompositedLayerMapping::PaintBlockedByDisplayLockIncludingAncestors(
+ DisplayLockContextLifecycleTarget target) const {
+ auto* node = GetLayoutObject().GetNode();
+ if (!node)
+ return false;
+ auto* element = DynamicTo<Element>(node);
+ if (target == DisplayLockContextLifecycleTarget::kSelf && element) {
+ if (auto* context = element->GetDisplayLockContext()) {
+ if (!context->ShouldPaint(DisplayLockContext::kSelf))
+ return true;
+ }
+ }
+ return DisplayLockUtilities::NearestLockedExclusiveAncestor(*node);
+}
+
+void CompositedLayerMapping::NotifyDisplayLockNeedsGraphicsLayerCollection() {
+ if (auto* node = GetLayoutObject().GetNode()) {
+ if (auto* locked_element =
+ DisplayLockUtilities::NearestLockedInclusiveAncestor(*node)) {
+ locked_element->GetDisplayLockContext()
+ ->NotifyNeedsGraphicsLayerCollection();
+ }
+ }
}
#if DCHECK_IS_ON()
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 10812e5997e..ca632833f00 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
@@ -36,7 +36,7 @@
#include "third_party/blink/renderer/platform/graphics/graphics_layer.h"
#include "third_party/blink/renderer/platform/graphics/graphics_layer_client.h"
#include "third_party/blink/renderer/platform/graphics/graphics_types.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -214,10 +214,13 @@ class CORE_EXPORT CompositedLayerMapping final : public GraphicsLayerClient {
GraphicsLayerPaintingPhase,
const IntRect& interest_rect) const override;
bool ShouldThrottleRendering() const override;
+ bool IsUnderSVGHiddenContainer() const override;
bool IsTrackingRasterInvalidations() const override;
void SetOverlayScrollbarsHidden(bool) override;
void GraphicsLayersDidChange() override;
- bool PaintBlockedByDisplayLock() const override;
+ bool PaintBlockedByDisplayLockIncludingAncestors(
+ DisplayLockContextLifecycleTarget) const override;
+ void NotifyDisplayLockNeedsGraphicsLayerCollection() override;
#if DCHECK_IS_ON()
void VerifyNotPainting() override;
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 543c8f983ff..5a791c2e9bf 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
@@ -51,8 +51,8 @@ class CompositedLayerMappingTest : public RenderingTest {
private:
void SetUp() override {
- RenderingTest::SetUp();
EnableCompositing();
+ RenderingTest::SetUp();
}
};
@@ -338,6 +338,42 @@ TEST_F(CompositedLayerMappingTest, PerspectiveInterestRect) {
RecomputeInterestRect(paint_layer->GraphicsLayerBacking()));
}
+TEST_F(CompositedLayerMappingTest, RotationInterestRect) {
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ .red_box {
+ position: fixed;
+ height: 100px;
+ width: 100vh; /* height of view, after -90 rot */
+ right: calc(16px - 50vh); /* 16 pixels above top of view, after -90 */
+ top: calc(50vh - 16px); /* 16 pixels in from right side, after -90 rot */
+ transform-origin: top;
+ transform: rotate(-90deg);
+ background-color: red;
+ will-change: transform;
+ }
+ .blue_box {
+ height: 30px;
+ width: 600px;
+ background: blue;
+ }
+</style>
+<div class="red_box" id=target>
+ <div class="blue_box"></div>
+</div>
+
+ )HTML");
+ GetFrame().View()->Resize(2000, 3000);
+
+ UpdateAllLifecyclePhasesForTest();
+ Element* element = GetDocument().getElementById("target");
+ PaintLayer* paint_layer =
+ ToLayoutBoxModelObject(element->GetLayoutObject())->Layer();
+ ASSERT_TRUE(!!paint_layer->GraphicsLayerBacking());
+ EXPECT_EQ(IntRect(0, 0, 3000, 100),
+ RecomputeInterestRect(paint_layer->GraphicsLayerBacking()));
+}
+
TEST_F(CompositedLayerMappingTest, 3D90DegRotatedTallInterestRect) {
// It's rotated 90 degrees about the X axis, which means its visual content
// rect is empty, and so the interest rect is the default (0, 0, 4000, 4000)
@@ -365,7 +401,7 @@ TEST_F(CompositedLayerMappingTest, 3D45DegRotatedTallInterestRect) {
PaintLayer* paint_layer =
ToLayoutBoxModelObject(element->GetLayoutObject())->Layer();
ASSERT_TRUE(!!paint_layer->GraphicsLayerBacking());
- EXPECT_EQ(IntRect(0, 0, 200, 4592),
+ EXPECT_EQ(IntRect(0, 0, 200, 6249),
RecomputeInterestRect(paint_layer->GraphicsLayerBacking()));
}
@@ -2752,7 +2788,7 @@ TEST_F(CompositedLayerMappingTest, TouchActionRectsWithoutContent) {
const auto* layer = mapping->MainGraphicsLayer()->CcLayer();
auto expected = gfx::Rect(0, 0, 100, 100);
- EXPECT_EQ(layer->touch_action_region().region().bounds(), expected);
+ EXPECT_EQ(layer->touch_action_region().GetAllRegions().bounds(), expected);
EXPECT_TRUE(mapping->MainGraphicsLayer()->PaintsHitTest());
diff --git a/chromium/third_party/blink/renderer/core/paint/compositing/compositing_inputs_root.h b/chromium/third_party/blink/renderer/core/paint/compositing/compositing_inputs_root.h
index 76c9d6458f4..fe5b27d41b3 100644
--- a/chromium/third_party/blink/renderer/core/paint/compositing/compositing_inputs_root.h
+++ b/chromium/third_party/blink/renderer/core/paint/compositing/compositing_inputs_root.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_COMPOSITING_COMPOSITING_INPUTS_ROOT_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_COMPOSITING_COMPOSITING_INPUTS_ROOT_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
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 d1704004ddf..498f24608af 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
@@ -6,7 +6,6 @@
#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/use_counter.h"
#include "third_party/blink/renderer/core/layout/layout_block.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.h"
@@ -14,6 +13,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/platform/instrumentation/tracing/trace_event.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
@@ -32,18 +32,38 @@ CompositingInputsUpdater::CompositingInputsUpdater(
CompositingInputsUpdater::~CompositingInputsUpdater() = default;
+bool CompositingInputsUpdater::LayerOrDescendantShouldBeComposited(
+ PaintLayer* layer) {
+ PaintLayerCompositor* compositor =
+ layer->GetLayoutObject().View()->Compositor();
+ return layer->DescendantHasDirectOrScrollingCompositingReason() ||
+ layer->NeedsCompositedScrolling() ||
+ (compositor->CanBeComposited(layer) &&
+ layer->DirectCompositingReasons());
+}
+
void CompositingInputsUpdater::Update() {
TRACE_EVENT0("blink", "CompositingInputsUpdater::update");
AncestorInfo info;
UpdateType update_type = kDoNotForceUpdate;
- ApplyAncestorInfoToSelfAndAncestorsRecursively(
- compositing_inputs_root_ ? compositing_inputs_root_ : root_layer_,
- update_type, info);
-
- UpdateSelfAndDescendantsRecursively(
- compositing_inputs_root_ ? compositing_inputs_root_ : root_layer_,
- update_type, info);
+ PaintLayer* layer =
+ compositing_inputs_root_ ? compositing_inputs_root_ : root_layer_;
+ CompositingReasons initial_compositing_reasons =
+ layer->DirectCompositingReasons();
+ ApplyAncestorInfoToSelfAndAncestorsRecursively(layer, update_type, info);
+ UpdateSelfAndDescendantsRecursively(layer, update_type, info);
+
+ // The layer has changed from non-compositing to compositing
+ if (initial_compositing_reasons == CompositingReason::kNone &&
+ LayerOrDescendantShouldBeComposited(layer)) {
+ // Update all parent layers
+ PaintLayer* parent_layer = layer->Parent();
+ while (parent_layer) {
+ parent_layer->SetDescendantHasDirectOrScrollingCompositingReason(true);
+ parent_layer = parent_layer->Parent();
+ }
+ }
}
void CompositingInputsUpdater::ApplyAncestorInfoToSelfAndAncestorsRecursively(
@@ -146,10 +166,7 @@ void CompositingInputsUpdater::UpdateSelfAndDescendantsRecursively(
if (should_recurse)
UpdateSelfAndDescendantsRecursively(child, update_type, info);
descendant_has_direct_compositing_reason |=
- child->DescendantHasDirectOrScrollingCompositingReason() ||
- child->NeedsCompositedScrolling() ||
- (compositor->CanBeComposited(child) &&
- child->DirectCompositingReasons());
+ LayerOrDescendantShouldBeComposited(child);
}
layer->SetDescendantHasDirectOrScrollingCompositingReason(
descendant_has_direct_compositing_reason);
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 3393699ea71..fd6cd01b05d 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
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_COMPOSITING_COMPOSITING_INPUTS_UPDATER_H_
#include "third_party/blink/renderer/core/layout/layout_geometry_map.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -79,6 +79,9 @@ class CompositingInputsUpdater {
// current value of AncestorInfo.
void UpdateAncestorInfo(PaintLayer*, UpdateType&, AncestorInfo&);
+ // Combine all reasons for compositing a layer into a single boolean value
+ bool LayerOrDescendantShouldBeComposited(PaintLayer*);
+
LayoutGeometryMap geometry_map_;
PaintLayer* root_layer_;
PaintLayer* compositing_inputs_root_;
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 a7f801e26f5..9e8aa067363 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
@@ -62,9 +62,9 @@ TEST_F(CompositingInputsUpdaterTest,
// Now make the outer scroller non-scrollable (i.e. overflow: visible), and
// the inner scroller into an actual scroller.
- ToElement(outer_scroller->GetNode())
+ To<Element>(outer_scroller->GetNode())
->SetInlineStyleProperty(CSSPropertyID::kOverflow, "visible");
- ToElement(inner_scroller->GetNode())
+ To<Element>(inner_scroller->GetNode())
->SetInlineStyleProperty(CSSPropertyID::kOverflow, "scroll");
// Before we update compositing inputs, validate that the current ancestor
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 a4e6f781c8d..f5379aaa38f 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
@@ -28,18 +28,18 @@
#include "third_party/blink/renderer/core/animation/scroll_timeline.h"
#include "third_party/blink/renderer/core/animation/worklet_animation_controller.h"
-#include "third_party/blink/renderer/core/inspector/inspector_trace_events.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/page/scrolling/scrolling_coordinator.h"
#include "third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.h"
+#include "third_party/blink/renderer/core/paint/paint_layer_paint_order_iterator.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
namespace blink {
// We will only allow squashing if the bbox-area:squashed-area doesn't exceed
-// the ratio |gSquashingSparsityTolerance|:1.
-static uint64_t g_squashing_sparsity_tolerance = 6;
+// the ratio |kSquashingSparsityTolerance|:1.
+constexpr uint64_t kSquashingSparsityTolerance = 6;
CompositingLayerAssigner::CompositingLayerAssigner(
PaintLayerCompositor* compositor)
@@ -90,7 +90,7 @@ bool CompositingLayerAssigner::SquashingWouldExceedSparsityTolerance(
const uint64_t new_squashed_area =
squashing_state.total_area_of_squashed_rects + bounds.Size().Area();
return new_bounding_rect_area >
- g_squashing_sparsity_tolerance * new_squashed_area;
+ kSquashingSparsityTolerance * new_squashed_area;
}
bool CompositingLayerAssigner::NeedsOwnBacking(const PaintLayer* layer) const {
@@ -252,9 +252,6 @@ void CompositingLayerAssigner::UpdateSquashingAssignment(
// Issue a paint invalidation, since |layer| may have been added to an
// already-existing squashing layer.
- TRACE_LAYER_INVALIDATION(
- layer,
- inspector_layer_invalidation_tracking_event::kAddedToSquashingLayer);
layers_needing_paint_invalidation.push_back(layer);
layers_changed_ = true;
} else if (composited_layer_update == kRemoveFromSquashingLayer) {
@@ -270,9 +267,6 @@ 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,
- inspector_layer_invalidation_tracking_event::
- kRemovedFromSquashingLayer);
layers_needing_paint_invalidation.push_back(layer);
layers_changed_ = true;
@@ -303,9 +297,6 @@ void CompositingLayerAssigner::AssignLayersToBackingsInternal(
if (compositor_->AllocateOrClearCompositedLayerMapping(
layer, composited_layer_update)) {
- TRACE_LAYER_INVALIDATION(
- layer,
- inspector_layer_invalidation_tracking_event::kNewCompositedLayer);
layers_needing_paint_invalidation.push_back(layer);
layers_changed_ = true;
if (ScrollingCoordinator* scrolling_coordinator =
@@ -349,10 +340,8 @@ void CompositingLayerAssigner::AssignLayersToBackingsInternal(
}
}
- if (layer->StackingDescendantNeedsCompositingLayerAssignment() &&
- layer->GetLayoutObject().StyleRef().IsStackingContext()) {
- PaintLayerStackingNodeIterator iterator(*layer->StackingNode(),
- kNegativeZOrderChildren);
+ if (layer->StackingDescendantNeedsCompositingLayerAssignment()) {
+ PaintLayerPaintOrderIterator iterator(*layer, kNegativeZOrderChildren);
while (PaintLayer* child_node = iterator.Next()) {
AssignLayersToBackingsInternal(child_node, squashing_state,
layers_needing_paint_invalidation);
@@ -369,10 +358,9 @@ void CompositingLayerAssigner::AssignLayersToBackingsInternal(
layers_needing_paint_invalidation);
}
- if (layer->StackingNode() &&
- layer->StackingDescendantNeedsCompositingLayerAssignment()) {
- PaintLayerStackingNodeIterator iterator(
- *layer->StackingNode(), kNormalFlowChildren | kPositiveZOrderChildren);
+ if (layer->StackingDescendantNeedsCompositingLayerAssignment()) {
+ PaintLayerPaintOrderIterator iterator(*layer,
+ kNormalFlowAndPositiveZOrderChildren);
while (PaintLayer* curr_layer = iterator.Next()) {
AssignLayersToBackingsInternal(curr_layer, squashing_state,
layers_needing_paint_invalidation);
diff --git a/chromium/third_party/blink/renderer/core/paint/compositing/compositing_layer_assigner.h b/chromium/third_party/blink/renderer/core/paint/compositing/compositing_layer_assigner.h
index 3f68d8c6cc7..e4e34b370fd 100644
--- a/chromium/third_party/blink/renderer/core/paint/compositing/compositing_layer_assigner.h
+++ b/chromium/third_party/blink/renderer/core/paint/compositing/compositing_layer_assigner.h
@@ -31,7 +31,7 @@
#include "third_party/blink/renderer/platform/geometry/int_rect.h"
#include "third_party/blink/renderer/platform/geometry/layout_point.h"
#include "third_party/blink/renderer/platform/graphics/squashing_disallowed_reasons.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/compositing/compositing_layer_assigner_test.cc b/chromium/third_party/blink/renderer/core/paint/compositing/compositing_layer_assigner_test.cc
index 0e36b33d49c..f191ecd0ba2 100644
--- a/chromium/third_party/blink/renderer/core/paint/compositing/compositing_layer_assigner_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/compositing/compositing_layer_assigner_test.cc
@@ -13,8 +13,8 @@ namespace blink {
class CompositedLayerAssignerTest : public RenderingTest {
private:
void SetUp() override {
- RenderingTest::SetUp();
EnableCompositing();
+ RenderingTest::SetUp();
}
};
diff --git a/chromium/third_party/blink/renderer/core/paint/compositing/compositing_layer_property_updater.h b/chromium/third_party/blink/renderer/core/paint/compositing/compositing_layer_property_updater.h
index f3e8d0d3534..710db4122c8 100644
--- a/chromium/third_party/blink/renderer/core/paint/compositing/compositing_layer_property_updater.h
+++ b/chromium/third_party/blink/renderer/core/paint/compositing/compositing_layer_property_updater.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_COMPOSITING_COMPOSITING_LAYER_PROPERTY_UPDATER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_COMPOSITING_COMPOSITING_LAYER_PROPERTY_UPDATER_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/compositing/compositing_layer_property_updater_test.cc b/chromium/third_party/blink/renderer/core/paint/compositing/compositing_layer_property_updater_test.cc
index 7bbd6f06919..077f6398a2c 100644
--- a/chromium/third_party/blink/renderer/core/paint/compositing/compositing_layer_property_updater_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/compositing/compositing_layer_property_updater_test.cc
@@ -19,8 +19,8 @@ namespace blink {
class CompositingLayerPropertyUpdaterTest : public RenderingTest {
private:
void SetUp() override {
- RenderingTest::SetUp();
EnableCompositing();
+ RenderingTest::SetUp();
}
};
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 3058d24f11c..edff13eb5eb 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
@@ -139,6 +139,9 @@ CompositingReasons CompositingReasonFinder::DirectReasonsForPaintProperties(
if (RequiresCompositingForScrollTimeline(*layer))
reasons |= CompositingReason::kScrollTimelineTarget;
+ if (RequiresCompositingForScrollDependentPosition(*layer))
+ reasons |= CompositingReason::kScrollDependentPosition;
+
return reasons;
}
diff --git a/chromium/third_party/blink/renderer/core/paint/compositing/compositing_reason_finder.h b/chromium/third_party/blink/renderer/core/paint/compositing/compositing_reason_finder.h
index 397600f7912..998c1495795 100644
--- a/chromium/third_party/blink/renderer/core/paint/compositing/compositing_reason_finder.h
+++ b/chromium/third_party/blink/renderer/core/paint/compositing/compositing_reason_finder.h
@@ -8,7 +8,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/graphics/compositing_reasons.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 039fbb03d05..40102a18d1a 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
@@ -22,8 +22,8 @@ class CompositingReasonFinderTest : public RenderingTest {
private:
void SetUp() override {
- RenderingTest::SetUp();
EnableCompositing();
+ RenderingTest::SetUp();
}
};
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 aa4e40db234..b3ae10816e9 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
@@ -31,9 +31,8 @@
#include "third_party/blink/renderer/core/layout/layout_view.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_paint_order_iterator.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
-#include "third_party/blink/renderer/core/paint/paint_layer_stacking_node.h"
-#include "third_party/blink/renderer/core/paint/paint_layer_stacking_node_iterator.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
namespace blink {
@@ -232,11 +231,7 @@ void CompositingRequirementsUpdater::Update(
#if DCHECK_IS_ON()
static void CheckSubtreeHasNoCompositing(PaintLayer* layer) {
- if (!layer->StackingNode())
- return;
- PaintLayerStackingNodeIterator iterator(
- *layer->StackingNode(),
- kNegativeZOrderChildren | kNormalFlowChildren | kPositiveZOrderChildren);
+ PaintLayerPaintOrderIterator iterator(*layer, kAllChildren);
while (PaintLayer* cur_layer = iterator.Next()) {
DCHECK(cur_layer->GetCompositingState() == kNotComposited);
DCHECK(!cur_layer->DirectCompositingReasons() ||
@@ -394,9 +389,7 @@ void CompositingRequirementsUpdater::UpdateRecursive(
}
#if DCHECK_IS_ON()
- base::Optional<LayerListMutationDetector> mutation_checker;
- if (layer->StackingNode())
- mutation_checker.emplace(layer->StackingNode());
+ PaintLayerListMutationDetector mutation_checker(*layer);
#endif
bool any_descendant_has3d_transform = false;
@@ -426,10 +419,8 @@ void CompositingRequirementsUpdater::UpdateRecursive(
!layer->HasCompositingDescendant() &&
!layer->DescendantMayNeedCompositingRequirementsUpdate();
- if (!skip_children &&
- layer->GetLayoutObject().StyleRef().IsStackingContext()) {
- PaintLayerStackingNodeIterator iterator(*layer->StackingNode(),
- kNegativeZOrderChildren);
+ if (!skip_children) {
+ PaintLayerPaintOrderIterator iterator(*layer, kNegativeZOrderChildren);
while (PaintLayer* child_layer = iterator.Next()) {
IntRect absolute_child_descendant_bounding_box;
UpdateRecursive(layer, child_layer, overlap_map, child_recursion_data,
@@ -478,9 +469,9 @@ void CompositingRequirementsUpdater::UpdateRecursive(
child_recursion_data.testing_overlap_ = true;
}
- if (!skip_children && layer->StackingNode()) {
- PaintLayerStackingNodeIterator iterator(
- *layer->StackingNode(), kNormalFlowChildren | kPositiveZOrderChildren);
+ if (!skip_children) {
+ PaintLayerPaintOrderIterator iterator(*layer,
+ kNormalFlowAndPositiveZOrderChildren);
while (PaintLayer* child_layer = iterator.Next()) {
IntRect absolute_child_descendant_bounding_box;
UpdateRecursive(layer, child_layer, overlap_map, child_recursion_data,
diff --git a/chromium/third_party/blink/renderer/core/paint/compositing/compositing_requirements_updater.h b/chromium/third_party/blink/renderer/core/paint/compositing/compositing_requirements_updater.h
index 81b6e8580a8..dcb9464a6d9 100644
--- a/chromium/third_party/blink/renderer/core/paint/compositing/compositing_requirements_updater.h
+++ b/chromium/third_party/blink/renderer/core/paint/compositing/compositing_requirements_updater.h
@@ -29,7 +29,7 @@
#include "third_party/blink/renderer/platform/geometry/int_rect.h"
#include "third_party/blink/renderer/platform/graphics/compositing_reasons.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
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 ff2fd07a10b..3bca46be1f7 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
@@ -20,8 +20,8 @@ class CompositingRequirementsUpdaterTest : public RenderingTest {
};
void CompositingRequirementsUpdaterTest::SetUp() {
- RenderingTest::SetUp();
EnableCompositing();
+ RenderingTest::SetUp();
}
TEST_F(CompositingRequirementsUpdaterTest,
diff --git a/chromium/third_party/blink/renderer/core/paint/compositing/graphics_layer_tree_as_text.cc b/chromium/third_party/blink/renderer/core/paint/compositing/graphics_layer_tree_as_text.cc
index ae4a4309d38..4de65500574 100644
--- a/chromium/third_party/blink/renderer/core/paint/compositing/graphics_layer_tree_as_text.cc
+++ b/chromium/third_party/blink/renderer/core/paint/compositing/graphics_layer_tree_as_text.cc
@@ -222,7 +222,8 @@ std::unique_ptr<JSONObject> GraphicsLayerAsJSON(
}
#if DCHECK_IS_ON()
- if (layer->DrawsContent() && (flags & kLayerTreeIncludesPaintRecords))
+ if (layer->HasLayerState() && layer->DrawsContent() &&
+ (flags & kLayerTreeIncludesPaintRecords))
json->SetValue("paintRecord", RecordAsJSON(*layer->CapturePaintRecord()));
#endif
@@ -369,7 +370,7 @@ void VerboseLogGraphicsLayerTree(const GraphicsLayer* root) {
String new_tree = GraphicsLayerTreeAsTextForTesting(root, flags);
auto it = s_previous_trees.find(root);
if (it == s_previous_trees.end() || it->value != new_tree) {
- VLOG(2) << "GraphicsLayer tree:\n" << new_tree.Utf8().data();
+ VLOG(2) << "GraphicsLayer tree:\n" << new_tree.Utf8();
s_previous_trees.Set(root, new_tree);
// For simplification, we don't remove deleted GraphicsLayers from the map.
}
@@ -386,7 +387,7 @@ void showGraphicsLayerTree(const blink::GraphicsLayer* layer) {
}
String output = blink::GraphicsLayerTreeAsTextForTesting(layer, 0xffffffff);
- LOG(ERROR) << output.Utf8().data();
+ LOG(ERROR) << output.Utf8();
}
void showGraphicsLayers(const blink::GraphicsLayer* layer) {
@@ -397,6 +398,6 @@ void showGraphicsLayers(const blink::GraphicsLayer* layer) {
String output = blink::GraphicsLayerTreeAsTextForTesting(
layer, 0xffffffff & ~blink::kOutputAsLayerTree);
- LOG(ERROR) << output.Utf8().data();
+ LOG(ERROR) << output.Utf8();
}
#endif
diff --git a/chromium/third_party/blink/renderer/core/paint/compositing/graphics_layer_tree_builder.cc b/chromium/third_party/blink/renderer/core/paint/compositing/graphics_layer_tree_builder.cc
index 2c797e04fa3..084bd945cc8 100644
--- a/chromium/third_party/blink/renderer/core/paint/compositing/graphics_layer_tree_builder.cc
+++ b/chromium/third_party/blink/renderer/core/paint/compositing/graphics_layer_tree_builder.cc
@@ -32,6 +32,7 @@
#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_paint_order_iterator.h"
namespace blink {
@@ -85,14 +86,11 @@ void GraphicsLayerTreeBuilder::RebuildRecursive(
: &pending_reparents;
#if DCHECK_IS_ON()
- base::Optional<LayerListMutationDetector> mutation_checker;
- if (layer.StackingNode())
- mutation_checker.emplace(layer.StackingNode());
+ PaintLayerListMutationDetector mutation_checker(layer);
#endif
- if (style.IsStackingContext()) {
- PaintLayerStackingNodeIterator iterator(*layer.StackingNode(),
- kNegativeZOrderChildren);
+ if (layer.IsStackingContextWithNegativeZOrderChildren()) {
+ PaintLayerPaintOrderIterator iterator(layer, kNegativeZOrderChildren);
while (PaintLayer* child_layer = iterator.Next()) {
RebuildRecursive(*child_layer, *layer_vector_for_children,
*pending_reparents_for_children);
@@ -107,9 +105,9 @@ void GraphicsLayerTreeBuilder::RebuildRecursive(
}
}
- if (layer.StackingNode()) {
- PaintLayerStackingNodeIterator iterator(
- *layer.StackingNode(), kNormalFlowChildren | kPositiveZOrderChildren);
+ {
+ PaintLayerPaintOrderIterator iterator(layer,
+ kNormalFlowAndPositiveZOrderChildren);
while (PaintLayer* child_layer = iterator.Next()) {
RebuildRecursive(*child_layer, *layer_vector_for_children,
*pending_reparents_for_children);
@@ -168,9 +166,8 @@ void GraphicsLayerTreeBuilder::RebuildRecursive(
pending_reparents.Set(&layer, child_layers.size());
// Set or overwrite the entry in |pending_reparents| for this scroller.
- // Overlay controls need to paint on top of all content under the
- // scroller, so keep overwriting if we find a PaintLayer that is
- // later in paint order.
+ // Overlay scrollbars need to paint on top of all content under the scroller,
+ // so keep overwriting if we find a PaintLayer that is later in paint order.
const PaintLayer* scroll_parent = layer.ScrollParent();
if (style.IsStacked() && scroll_parent &&
scroll_parent->HasCompositedLayerMapping() &&
diff --git a/chromium/third_party/blink/renderer/core/paint/compositing/graphics_layer_tree_builder.h b/chromium/third_party/blink/renderer/core/paint/compositing/graphics_layer_tree_builder.h
index 944933c0a1e..88e607b9442 100644
--- a/chromium/third_party/blink/renderer/core/paint/compositing/graphics_layer_tree_builder.h
+++ b/chromium/third_party/blink/renderer/core/paint/compositing/graphics_layer_tree_builder.h
@@ -28,7 +28,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_COMPOSITING_GRAPHICS_LAYER_TREE_BUILDER_H_
#include "third_party/blink/renderer/platform/graphics/graphics_layer.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/compositing/graphics_layer_updater.cc b/chromium/third_party/blink/renderer/core/paint/compositing/graphics_layer_updater.cc
index 99424fe8390..330c0c97874 100644
--- a/chromium/third_party/blink/renderer/core/paint/compositing/graphics_layer_updater.cc
+++ b/chromium/third_party/blink/renderer/core/paint/compositing/graphics_layer_updater.cc
@@ -27,7 +27,6 @@
#include "third_party/blink/renderer/core/paint/compositing/graphics_layer_updater.h"
#include "third_party/blink/renderer/core/html/media/html_media_element.h"
-#include "third_party/blink/renderer/core/inspector/inspector_trace_events.h"
#include "third_party/blink/renderer/core/layout/layout_block.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"
@@ -38,28 +37,32 @@
namespace blink {
GraphicsLayerUpdater::UpdateContext::UpdateContext()
- : compositing_stacking_context_(nullptr), compositing_ancestor_(nullptr) {}
+ : compositing_stacking_context_(nullptr),
+ compositing_ancestor_(nullptr),
+ use_slow_path_(false) {}
GraphicsLayerUpdater::UpdateContext::UpdateContext(const UpdateContext& other,
const PaintLayer& layer)
: compositing_stacking_context_(other.compositing_stacking_context_),
- compositing_ancestor_(other.CompositingContainer(layer)) {
+ compositing_ancestor_(other.CompositingContainer(layer)),
+ use_slow_path_(other.use_slow_path_) {
CompositingState compositing_state = layer.GetCompositingState();
if (compositing_state != kNotComposited &&
compositing_state != kPaintsIntoGroupedBacking) {
compositing_ancestor_ = &layer;
if (layer.GetLayoutObject().StyleRef().IsStackingContext())
compositing_stacking_context_ = &layer;
-
- // Any composited content under SVG must be a descendant of (but not
- // equal to, see PaintLayerCompositor::CanBeComposited)
- // a <foreignObject> element. The SVG root element amounts to a
- // compositing stacking ancestor to such an element, if the SVG
- // root is composited, because <foreignObject> is a replaced normal-flow
- // stacking element (see PaintLayer::IsReplacedNormalFlowStacking).
- if (layer.GetLayoutObject().IsSVGRoot())
- compositing_stacking_context_ = &layer;
}
+ // Any composited content under SVG must be a descendant of (but not
+ // equal to, see PaintLayerCompositor::CanBeComposited)
+ // a <foreignObject> element. The rules for compositing ancestors are
+ // complicated for this situation, due to <foreignObject> being a replaced
+ // nornmal-flow stacking element
+ // (see PaintLayer::IsReplacedNormalFlowStacking). Use a slow path
+ // for these situations, to simplify the logic.
+ if (layer.GetLayoutObject().IsSVGRoot() ||
+ layer.IsReplacedNormalFlowStacking())
+ use_slow_path_ = true;
parent_object_offset_delta =
compositing_ancestor_ == other.compositing_ancestor_
@@ -69,6 +72,9 @@ GraphicsLayerUpdater::UpdateContext::UpdateContext(const UpdateContext& other,
const PaintLayer* GraphicsLayerUpdater::UpdateContext::CompositingContainer(
const PaintLayer& layer) const {
+ if (use_slow_path_)
+ return layer.EnclosingLayerWithCompositedLayerMapping(kExcludeSelf);
+
const PaintLayer* compositing_container;
if (layer.GetLayoutObject().StyleRef().IsStacked() &&
!layer.IsReplacedNormalFlowStacking()) {
diff --git a/chromium/third_party/blink/renderer/core/paint/compositing/graphics_layer_updater.h b/chromium/third_party/blink/renderer/core/paint/compositing/graphics_layer_updater.h
index fc665cadfa2..9a98a937df3 100644
--- a/chromium/third_party/blink/renderer/core/paint/compositing/graphics_layer_updater.h
+++ b/chromium/third_party/blink/renderer/core/paint/compositing/graphics_layer_updater.h
@@ -28,7 +28,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_COMPOSITING_GRAPHICS_LAYER_UPDATER_H_
#include "third_party/blink/renderer/platform/graphics/graphics_layer.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -72,6 +72,7 @@ class GraphicsLayerUpdater {
private:
const PaintLayer* compositing_stacking_context_;
const PaintLayer* compositing_ancestor_;
+ bool use_slow_path_;
};
private:
diff --git a/chromium/third_party/blink/renderer/core/paint/compositing/paint_layer_compositor.cc b/chromium/third_party/blink/renderer/core/paint/compositing/paint_layer_compositor.cc
index 4f41faca55c..838e1ea5a41 100644
--- a/chromium/third_party/blink/renderer/core/paint/compositing/paint_layer_compositor.cc
+++ b/chromium/third_party/blink/renderer/core/paint/compositing/paint_layer_compositor.cc
@@ -26,6 +26,7 @@
#include "third_party/blink/renderer/core/paint/compositing/paint_layer_compositor.h"
#include "base/optional.h"
+#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/core/animation/document_animations.h"
#include "third_party/blink/renderer/core/animation/document_timeline.h"
#include "third_party/blink/renderer/core/animation/element_animations.h"
@@ -60,7 +61,7 @@
#include "third_party/blink/renderer/platform/graphics/graphics_layer.h"
#include "third_party/blink/renderer/platform/graphics/paint/cull_rect.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_controller.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
@@ -68,18 +69,26 @@ namespace blink {
PaintLayerCompositor::PaintLayerCompositor(LayoutView& layout_view)
: layout_view_(layout_view),
- pending_update_type_(kCompositingUpdateNone),
- has_accelerated_compositing_(true),
- compositing_(false),
- root_should_always_composite_dirty_(true),
- root_layer_attachment_(kRootLayerUnattached) {
- UpdateAcceleratedCompositingSettings();
-}
+ has_accelerated_compositing_(layout_view.GetDocument()
+ .GetSettings()
+ ->GetAcceleratedCompositingEnabled()) {}
PaintLayerCompositor::~PaintLayerCompositor() {
DCHECK_EQ(root_layer_attachment_, kRootLayerUnattached);
}
+void PaintLayerCompositor::CleanUp() {
+ if (InCompositingMode())
+ DetachRootLayer();
+}
+
+void PaintLayerCompositor::DidLayout() {
+ // FIXME: Technically we only need to do this when the LocalFrameView's
+ // isScrollable method would return a different value.
+ root_should_always_composite_dirty_ = true;
+ EnableCompositingModeIfNeeded();
+}
+
bool PaintLayerCompositor::InCompositingMode() const {
// FIXME: This should assert that lifecycle is >= CompositingClean since
// the last step of updateIfNeeded can set this bit to false.
@@ -98,9 +107,9 @@ void PaintLayerCompositor::SetCompositingModeEnabled(bool enable) {
compositing_ = enable;
if (compositing_)
- EnsureRootLayer();
+ AttachRootLayer();
else
- DestroyRootLayer();
+ DetachRootLayer();
// Schedule an update in the parent frame so the <iframe>'s layer in the owner
// document matches the compositing state here.
@@ -127,17 +136,28 @@ void PaintLayerCompositor::EnableCompositingModeIfNeeded() {
}
bool PaintLayerCompositor::RootShouldAlwaysComposite() const {
+ // If compositing is disabled for the WebView, then nothing composites.
if (!has_accelerated_compositing_)
return false;
- return layout_view_.GetFrame()->IsLocalRoot() ||
- CompositingReasonFinder::RequiresCompositingForScrollableFrame(
- layout_view_);
+ // Local roots composite always, when compositing is enabled globally.
+ if (layout_view_.GetFrame()->IsLocalRoot())
+ return true;
+ // Some non-local roots of embedded content do not have a LocalFrameView
+ // so they are not visible and should not get compositor layers.
+ if (!layout_view_.GetFrameView())
+ return false;
+ // Non-local root frames will composite only if needed for scrolling.
+ return CompositingReasonFinder::RequiresCompositingForScrollableFrame(
+ layout_view_);
}
void PaintLayerCompositor::UpdateAcceleratedCompositingSettings() {
- has_accelerated_compositing_ = layout_view_.GetDocument()
- .GetSettings()
- ->GetAcceleratedCompositingEnabled();
+ // AcceleratedCompositing setting does not change after initialization.
+ DCHECK_EQ(has_accelerated_compositing_,
+ layout_view_.GetDocument()
+ .GetSettings()
+ ->GetAcceleratedCompositingEnabled());
+
root_should_always_composite_dirty_ = true;
if (root_layer_attachment_ != kRootLayerUnattached)
RootLayer()->SetNeedsCompositingInputsUpdate();
@@ -226,15 +246,18 @@ void PaintLayerCompositor::UpdateIfNeededRecursiveInternal(
ScriptForbiddenScope forbid_script;
- // FIXME: enableCompositingModeIfNeeded can trigger a
+ // FIXME: EnableCompositingModeIfNeeded() can trigger a
// CompositingUpdateRebuildTree, which asserts that it's not
- // InCompositingUpdate.
+ // InCompositingUpdate().
EnableCompositingModeIfNeeded();
#if DCHECK_IS_ON()
view->SetIsUpdatingDescendantDependentFlags(true);
#endif
- RootLayer()->UpdateDescendantDependentFlags();
+ {
+ TRACE_EVENT0("blink", "PaintLayer::UpdateDescendantDependentFlags");
+ RootLayer()->UpdateDescendantDependentFlags();
+ }
#if DCHECK_IS_ON()
view->SetIsUpdatingDescendantDependentFlags(false);
#endif
@@ -298,6 +321,13 @@ void PaintLayerCompositor::UpdateIfNeededRecursiveInternal(
#endif
}
+#if DCHECK_IS_ON()
+void PaintLayerCompositor::AssertNoUnresolvedDirtyBits() {
+ DCHECK_EQ(pending_update_type_, kCompositingUpdateNone);
+ DCHECK(!root_should_always_composite_dirty_);
+}
+#endif
+
void PaintLayerCompositor::SetNeedsCompositingUpdate(
CompositingUpdateType update_type) {
DCHECK_NE(update_type, kCompositingUpdateNone);
@@ -311,22 +341,6 @@ void PaintLayerCompositor::SetNeedsCompositingUpdate(
Lifecycle().EnsureStateAtMost(DocumentLifecycle::kLayoutClean);
}
-void PaintLayerCompositor::DidLayout() {
- // FIXME: Technically we only need to do this when the LocalFrameView's
- // isScrollable method would return a different value.
- root_should_always_composite_dirty_ = true;
- EnableCompositingModeIfNeeded();
-}
-
-#if DCHECK_IS_ON()
-
-void PaintLayerCompositor::AssertNoUnresolvedDirtyBits() {
- DCHECK_EQ(pending_update_type_, kCompositingUpdateNone);
- DCHECK(!root_should_always_composite_dirty_);
-}
-
-#endif
-
GraphicsLayer* PaintLayerCompositor::OverlayFullscreenVideoGraphicsLayer() {
LayoutVideo* video =
FindFullscreenVideoLayoutObject(layout_view_.GetDocument());
@@ -455,6 +469,9 @@ void PaintLayerCompositor::UpdateIfNeeded(
return;
}
+ if (IsMainFrame())
+ GetPage()->GetVisualViewport().CreateLayerTree();
+
PaintLayer* update_root = RootLayer();
Vector<PaintLayer*> layers_needing_paint_invalidation;
@@ -575,10 +592,9 @@ void PaintLayerCompositor::AttachRootLayerViaChromeClient() {
}
static void RestartAnimationOnCompositor(const LayoutObject& layout_object) {
- Node* node = layout_object.GetNode();
- ElementAnimations* element_animations =
- (node && node->IsElementNode()) ? ToElement(node)->GetElementAnimations()
- : nullptr;
+ ElementAnimations* element_animations = nullptr;
+ if (auto* element = DynamicTo<Element>(layout_object.GetNode()))
+ element_animations = element->GetElementAnimations();
if (element_animations)
element_animations->RestartAnimationOnCompositor();
}
@@ -649,7 +665,7 @@ bool PaintLayerCompositor::AllocateOrClearCompositedLayerMapping(
PaintLayerCompositor* inner_compositor = FrameContentsCompositor(
ToLayoutEmbeddedContent(layer->GetLayoutObject()));
if (inner_compositor && inner_compositor->StaleInCompositingMode())
- inner_compositor->EnsureRootLayer();
+ inner_compositor->AttachRootLayer();
}
layer->ClearClipRects(kPaintingClipRects);
@@ -766,25 +782,6 @@ GraphicsLayer* PaintLayerCompositor::ScrollLayer() const {
return nullptr;
}
-void PaintLayerCompositor::SetIsInWindow(bool is_in_window) {
- if (!StaleInCompositingMode())
- return;
-
- if (is_in_window) {
- if (root_layer_attachment_ != kRootLayerUnattached)
- return;
-
- AttachCompositorTimeline();
- AttachRootLayer();
- } else {
- if (root_layer_attachment_ == kRootLayerUnattached)
- return;
-
- DetachRootLayer();
- DetachCompositorTimeline();
- }
-}
-
void PaintLayerCompositor::UpdatePotentialCompositingReasonsFromStyle(
PaintLayer& layer) {
auto reasons = CompositingReasonFinder::PotentialCompositingReasonsFromStyle(
@@ -833,8 +830,7 @@ bool PaintLayerCompositor::NeedsContentsCompositingLayer(
const PaintLayer* layer) const {
if (!layer->HasCompositingDescendant())
return false;
- return layer->StackingNode() &&
- layer->StackingNode()->HasNegativeZOrderList();
+ return layer->IsStackingContextWithNegativeZOrderChildren();
}
static void UpdateTrackingRasterInvalidationsRecursive(
@@ -865,44 +861,35 @@ void PaintLayerCompositor::UpdateTrackingRasterInvalidations() {
UpdateTrackingRasterInvalidationsRecursive(root_layer);
}
-void PaintLayerCompositor::EnsureRootLayer() {
+void PaintLayerCompositor::AttachRootLayer() {
if (root_layer_attachment_ != kRootLayerUnattached)
return;
- if (IsMainFrame())
- GetVisualViewport().CreateLayerTree();
-
- AttachCompositorTimeline();
- AttachRootLayer();
-}
-
-void PaintLayerCompositor::DestroyRootLayer() {
- DetachRootLayer();
-}
-
-void PaintLayerCompositor::AttachRootLayer() {
// With CompositeAfterPaint, PaintArtifactCompositor is responsible for the
// root layer.
if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled())
return;
+ // Local roots are attached to the ChromeClient later. Otherwise, we can
+ // attach the layer into the existing compositor layer tree.
if (layout_view_.GetFrame()->IsLocalRoot()) {
root_layer_attachment_ = kRootLayerPendingAttachViaChromeClient;
- } else {
- HTMLFrameOwnerElement* owner_element =
- layout_view_.GetDocument().LocalOwner();
- DCHECK(owner_element);
- // The layer will get hooked up via
- // CompositedLayerMapping::updateGraphicsLayerConfiguration() for the
- // frame's layoutObject in the parent document.
- owner_element->SetNeedsCompositingUpdate();
- if (owner_element->GetLayoutObject()) {
- ToLayoutBoxModelObject(owner_element->GetLayoutObject())
- ->Layer()
- ->SetNeedsCompositingInputsUpdate();
- }
- root_layer_attachment_ = kRootLayerAttachedViaEnclosingFrame;
+ return;
}
+
+ HTMLFrameOwnerElement* owner_element =
+ layout_view_.GetDocument().LocalOwner();
+ DCHECK(owner_element);
+ // The layer will get hooked up via
+ // CompositedLayerMapping::updateGraphicsLayerConfiguration() for the
+ // frame's layoutObject in the parent document.
+ owner_element->SetNeedsCompositingUpdate();
+ if (owner_element->GetLayoutObject()) {
+ ToLayoutBoxModelObject(owner_element->GetLayoutObject())
+ ->Layer()
+ ->SetNeedsCompositingInputsUpdate();
+ }
+ root_layer_attachment_ = kRootLayerAttachedViaEnclosingFrame;
}
void PaintLayerCompositor::DetachRootLayer() {
@@ -921,10 +908,8 @@ void PaintLayerCompositor::DetachRootLayer() {
}
case kRootLayerAttachedViaChromeClient: {
LocalFrame& frame = layout_view_.GetFrameView()->GetFrame();
- Page* page = frame.GetPage();
- if (!page)
- return;
- page->GetChromeClient().AttachRootGraphicsLayer(nullptr, &frame);
+ ChromeClient& chrome_client = frame.GetPage()->GetChromeClient();
+ chrome_client.AttachRootGraphicsLayer(nullptr, &frame);
break;
}
case kRootLayerPendingAttachViaChromeClient:
@@ -935,34 +920,6 @@ void PaintLayerCompositor::DetachRootLayer() {
root_layer_attachment_ = kRootLayerUnattached;
}
-void PaintLayerCompositor::AttachCompositorTimeline() {
- LocalFrame& frame = layout_view_.GetFrameView()->GetFrame();
- Page* page = frame.GetPage();
- if (!page || !frame.GetDocument())
- return;
-
- CompositorAnimationTimeline* compositor_timeline =
- frame.GetDocument()->Timeline().CompositorTimeline();
- if (compositor_timeline) {
- page->GetChromeClient().AttachCompositorAnimationTimeline(
- compositor_timeline, &frame);
- }
-}
-
-void PaintLayerCompositor::DetachCompositorTimeline() {
- LocalFrame& frame = layout_view_.GetFrameView()->GetFrame();
- Page* page = frame.GetPage();
- if (!page || !frame.GetDocument())
- return;
-
- CompositorAnimationTimeline* compositor_timeline =
- frame.GetDocument()->Timeline().CompositorTimeline();
- if (compositor_timeline) {
- page->GetChromeClient().DetachCompositorAnimationTimeline(
- compositor_timeline, &frame);
- }
-}
-
ScrollingCoordinator* PaintLayerCompositor::GetScrollingCoordinator() const {
if (Page* page = GetPage())
return page->GetScrollingCoordinator();
diff --git a/chromium/third_party/blink/renderer/core/paint/compositing/paint_layer_compositor.h b/chromium/third_party/blink/renderer/core/paint/compositing/paint_layer_compositor.h
index bbb7d4296a1..9c5608ec466 100644
--- a/chromium/third_party/blink/renderer/core/paint/compositing/paint_layer_compositor.h
+++ b/chromium/third_party/blink/renderer/core/paint/compositing/paint_layer_compositor.h
@@ -76,6 +76,15 @@ class CORE_EXPORT PaintLayerCompositor {
explicit PaintLayerCompositor(LayoutView&);
~PaintLayerCompositor();
+ // Called while the LocalFrame behind the LayoutView is being detached.
+ // Pointers in other objects should be cleaned up at this point, before
+ // pointers out of this object become invalid.
+ void CleanUp();
+
+ // Called after layout is performed on the LocalFrame holding the LayoutView,
+ // during the document lifecycle update.
+ void DidLayout();
+
void UpdateIfNeededRecursive(DocumentLifecycle::LifecycleState target_state);
// Return true if this LayoutView is in "compositing mode" (i.e. has one or
@@ -96,15 +105,14 @@ class CORE_EXPORT PaintLayerCompositor {
bool RootShouldAlwaysComposite() const;
- // Copy the accelerated compositing related flags from Settings
+ // Notifies about changes to PreferCompositingToLCDText or
+ // AcceleratedCompositing.
void UpdateAcceleratedCompositingSettings();
// Used to indicate that a compositing update will be needed for the next
// frame that gets drawn.
void SetNeedsCompositingUpdate(CompositingUpdateType);
- void DidLayout();
-
// Whether layer's compositedLayerMapping needs a GraphicsLayer to clip
// z-order children of the given Layer.
bool ClipsCompositingDescendants(const PaintLayer*) const;
@@ -131,8 +139,6 @@ class CORE_EXPORT PaintLayerCompositor {
// The LayoutView's scroll layer.
GraphicsLayer* ScrollLayer() const;
- void SetIsInWindow(bool);
-
static PaintLayerCompositor* FrameContentsCompositor(LayoutEmbeddedContent&);
// Return true if the layers changed.
static bool AttachFrameContentLayersToIframeLayer(LayoutEmbeddedContent&);
@@ -183,15 +189,9 @@ class CORE_EXPORT PaintLayerCompositor {
void UpdateIfNeeded(DocumentLifecycle::LifecycleState target_state,
CompositingReasonsStats&);
- void EnsureRootLayer();
- void DestroyRootLayer();
-
void AttachRootLayer();
void DetachRootLayer();
- void AttachCompositorTimeline();
- void DetachCompositorTimeline();
-
Page* GetPage() const;
ScrollingCoordinator* GetScrollingCoordinator() const;
@@ -213,20 +213,22 @@ class CORE_EXPORT PaintLayerCompositor {
GraphicsLayer* child_frame_parent_candidate = nullptr) const;
LayoutView& layout_view_;
+ const bool has_accelerated_compositing_ = true;
- CompositingUpdateType pending_update_type_;
-
- bool has_accelerated_compositing_;
- bool compositing_;
+ bool compositing_ = false;
// The root layer doesn't composite if it's a non-scrollable frame.
// So, after a layout we set this dirty bit to know that we need
// to recompute whether the root layer should composite even if
// none of its descendants composite.
- // FIXME: Get rid of all the callers of setCompositingModeEnabled
- // except the one in updateIfNeeded, then rename this to
- // m_compositingDirty.
- bool root_should_always_composite_dirty_;
+ // FIXME: Get rid of all the callers of SetCompositingModeEnabled()
+ // except the one in UpdateIfNeeded(), then rename this to
+ // compositing_dirty_.
+ bool root_should_always_composite_dirty_ = true;
+
+ // After initialization, compositing updates must be done, so start dirty.
+ CompositingUpdateType pending_update_type_ =
+ kCompositingUpdateAfterCompositingInputChange;
enum RootLayerAttachment {
kRootLayerUnattached,
@@ -234,7 +236,7 @@ class CORE_EXPORT PaintLayerCompositor {
kRootLayerAttachedViaChromeClient,
kRootLayerAttachedViaEnclosingFrame
};
- RootLayerAttachment root_layer_attachment_;
+ RootLayerAttachment root_layer_attachment_ = kRootLayerUnattached;
CompositingInputsRoot compositing_inputs_root_;
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 dc2990c2178..d760638e040 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
@@ -4,8 +4,8 @@
#include "third_party/blink/renderer/core/paint/compositing/paint_layer_compositor.h"
+#include "third_party/blink/renderer/core/animation/animatable.h"
#include "third_party/blink/renderer/core/animation/animation.h"
-#include "third_party/blink/renderer/core/animation/element_animation.h"
#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/testing/core_unit_test_helper.h"
@@ -20,8 +20,8 @@ class PaintLayerCompositorTest : public RenderingTest {
private:
void SetUp() override {
- RenderingTest::SetUp();
EnableCompositing();
+ RenderingTest::SetUp();
}
};
} // namespace
@@ -77,10 +77,8 @@ TEST_F(PaintLayerCompositorTest,
EXPECT_EQ(DocumentLifecycle::kPaintClean,
GetDocument().Lifecycle().GetState());
- HeapVector<Member<Animation>> boxAnimations =
- ElementAnimation::getAnimations(*box);
- HeapVector<Member<Animation>> otherBoxAnimations =
- ElementAnimation::getAnimations(*box);
+ HeapVector<Member<Animation>> boxAnimations = box->getAnimations();
+ HeapVector<Member<Animation>> otherBoxAnimations = otherBox->getAnimations();
EXPECT_EQ(1ul, boxAnimations.size());
EXPECT_EQ(1ul, otherBoxAnimations.size());
diff --git a/chromium/third_party/blink/renderer/core/paint/css_mask_painter.h b/chromium/third_party/blink/renderer/core/paint/css_mask_painter.h
index 469bc4dc6bd..cb2e0e82f31 100644
--- a/chromium/third_party/blink/renderer/core/paint/css_mask_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/css_mask_painter.h
@@ -9,7 +9,7 @@
#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/graphics/graphics_types.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 6871a017ea9..52d71f9f15d 100644
--- a/chromium/third_party/blink/renderer/core/paint/decoration_info.h
+++ b/chromium/third_party/blink/renderer/core/paint/decoration_info.h
@@ -8,7 +8,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/geometry/layout_unit.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/details_marker_painter.h b/chromium/third_party/blink/renderer/core/paint/details_marker_painter.h
index c60447ce53b..e5b1064519f 100644
--- a/chromium/third_party/blink/renderer/core/paint/details_marker_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/details_marker_painter.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_DETAILS_MARKER_PAINTER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_DETAILS_MARKER_PAINTER_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/document_marker_painter.h b/chromium/third_party/blink/renderer/core/paint/document_marker_painter.h
index 4880a1044c9..069343d2eed 100644
--- a/chromium/third_party/blink/renderer/core/paint/document_marker_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/document_marker_painter.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_DOCUMENT_MARKER_PAINTER_H_
#include "third_party/blink/renderer/core/editing/markers/document_marker.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/element_timing_utils.cc b/chromium/third_party/blink/renderer/core/paint/element_timing_utils.cc
new file mode 100644
index 00000000000..71d29db2cc3
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/paint/element_timing_utils.cc
@@ -0,0 +1,39 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/paint/element_timing_utils.h"
+
+#include "third_party/blink/public/platform/web_float_rect.h"
+#include "third_party/blink/public/web/web_widget_client.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/layout/layout_object.h"
+#include "third_party/blink/renderer/core/layout/layout_view.h"
+#include "third_party/blink/renderer/platform/graphics/paint/geometry_mapper.h"
+#include "third_party/blink/renderer/platform/graphics/paint/property_tree_state.h"
+
+namespace blink {
+
+// static
+FloatRect ElementTimingUtils::ComputeIntersectionRect(
+ LocalFrame* frame,
+ const IntRect& int_visual_rect,
+ const PropertyTreeState& current_paint_chunk_properties) {
+ // Compute the visible part of the image rect.
+ FloatClipRect visual_rect = FloatClipRect(FloatRect(int_visual_rect));
+ GeometryMapper::LocalToAncestorVisualRect(current_paint_chunk_properties,
+ frame->View()
+ ->GetLayoutView()
+ ->FirstFragment()
+ .LocalBorderBoxProperties(),
+ visual_rect);
+ WebFloatRect intersection_rect = visual_rect.Rect();
+ WebFrameWidgetBase* widget =
+ WebLocalFrameImpl::FromFrame(frame)->LocalRootFrameWidget();
+ DCHECK(widget);
+ widget->Client()->ConvertViewportToWindow(&intersection_rect);
+ return intersection_rect;
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/paint/element_timing_utils.h b/chromium/third_party/blink/renderer/core/paint/element_timing_utils.h
new file mode 100644
index 00000000000..c959eae1748
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/paint/element_timing_utils.h
@@ -0,0 +1,29 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_ELEMENT_TIMING_UTILS_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_ELEMENT_TIMING_UTILS_H_
+
+#include "third_party/blink/renderer/platform/geometry/float_rect.h"
+
+namespace blink {
+
+class IntRect;
+class LocalFrame;
+class PropertyTreeState;
+
+// Class containing methods shared between ImageElementTiming and
+// TextElementTiming.
+class ElementTimingUtils {
+ public:
+ // Computes the part a rect in a local transform space that is visible in the
+ // specified frame, and returns a result in DIPs.
+ static FloatRect ComputeIntersectionRect(LocalFrame*,
+ const IntRect&,
+ const PropertyTreeState&);
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_ELEMENT_TIMING_UTILS_H_
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 1278e8fdc72..df0263b1c2c 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
@@ -4,7 +4,6 @@
#include "third_party/blink/renderer/core/paint/ellipsis_box_painter.h"
-#include "third_party/blink/renderer/core/content_capture/content_holder.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"
#include "third_party/blink/renderer/core/layout/line/ellipsis_box.h"
@@ -13,6 +12,7 @@
#include "third_party/blink/renderer/core/paint/paint_info.h"
#include "third_party/blink/renderer/core/paint/paint_timing_detector.h"
#include "third_party/blink/renderer/core/paint/text_painter.h"
+#include "third_party/blink/renderer/platform/graphics/dom_node_id.h"
#include "third_party/blink/renderer/platform/graphics/graphics_context_state_saver.h"
#include "third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h"
@@ -35,7 +35,7 @@ void EllipsisBoxPainter::PaintEllipsis(const PaintInfo& paint_info,
LayoutUnit line_top,
LayoutUnit line_bottom,
const ComputedStyle& style) {
- LayoutPoint box_origin = ellipsis_box_.PhysicalLocation();
+ LayoutPoint box_origin = ellipsis_box_.PhysicalLocation().ToLayoutPoint();
box_origin.MoveBy(paint_offset);
GraphicsContext& context = paint_info.context;
@@ -71,7 +71,7 @@ void EllipsisBoxPainter::PaintEllipsis(const PaintInfo& paint_info,
ellipsis_box_.IsHorizontal());
text_painter.Paint(0, ellipsis_box_.EllipsisStr().length(),
ellipsis_box_.EllipsisStr().length(), text_style,
- NodeHolder::EmptyNodeHolder());
+ kInvalidDOMNodeId);
// TODO(npm): Check that there are non-whitespace characters. See
// crbug.com/788444.
context.GetPaintController().SetTextPainted();
diff --git a/chromium/third_party/blink/renderer/core/paint/ellipsis_box_painter.h b/chromium/third_party/blink/renderer/core/paint/ellipsis_box_painter.h
index 9b23826fc1f..e64293fc2a9 100644
--- a/chromium/third_party/blink/renderer/core/paint/ellipsis_box_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/ellipsis_box_painter.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_ELLIPSIS_BOX_PAINTER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_ELLIPSIS_BOX_PAINTER_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/embedded_content_painter.h b/chromium/third_party/blink/renderer/core/paint/embedded_content_painter.h
index 643802e2f5d..9442e0981e6 100644
--- a/chromium/third_party/blink/renderer/core/paint/embedded_content_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/embedded_content_painter.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_EMBEDDED_CONTENT_PAINTER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_EMBEDDED_CONTENT_PAINTER_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/embedded_object_painter.h b/chromium/third_party/blink/renderer/core/paint/embedded_object_painter.h
index 3a782450fa5..0857bf66011 100644
--- a/chromium/third_party/blink/renderer/core/paint/embedded_object_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/embedded_object_painter.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_EMBEDDED_OBJECT_PAINTER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_EMBEDDED_OBJECT_PAINTER_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/fieldset_painter.h b/chromium/third_party/blink/renderer/core/paint/fieldset_painter.h
index 7a810a13720..7ea6c6616c8 100644
--- a/chromium/third_party/blink/renderer/core/paint/fieldset_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/fieldset_painter.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_FIELDSET_PAINTER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_FIELDSET_PAINTER_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/file_upload_control_painter.h b/chromium/third_party/blink/renderer/core/paint/file_upload_control_painter.h
index 90378eba897..2647b5e57ed 100644
--- a/chromium/third_party/blink/renderer/core/paint/file_upload_control_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/file_upload_control_painter.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_FILE_UPLOAD_CONTROL_PAINTER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_FILE_UPLOAD_CONTROL_PAINTER_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/filter_effect_builder.h b/chromium/third_party/blink/renderer/core/paint/filter_effect_builder.h
index b23df97de26..32497c0c144 100644
--- a/chromium/third_party/blink/renderer/core/paint/filter_effect_builder.h
+++ b/chromium/third_party/blink/renderer/core/paint/filter_effect_builder.h
@@ -30,7 +30,7 @@
#include "third_party/blink/renderer/platform/geometry/float_rect.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_flags.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/skia/include/effects/SkBlurImageFilter.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/find_paint_offset_and_visual_rect_needing_update.h b/chromium/third_party/blink/renderer/core/paint/find_paint_offset_and_visual_rect_needing_update.h
index 7e73af9fcdc..853f329cc71 100644
--- a/chromium/third_party/blink/renderer/core/paint/find_paint_offset_and_visual_rect_needing_update.h
+++ b/chromium/third_party/blink/renderer/core/paint/find_paint_offset_and_visual_rect_needing_update.h
@@ -12,7 +12,7 @@
#include "third_party/blink/renderer/core/paint/paint_invalidator.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/paint_property_tree_builder.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/find_properties_needing_update.h b/chromium/third_party/blink/renderer/core/paint/find_properties_needing_update.h
index f6cd907b1db..c61a4cb05e9 100644
--- a/chromium/third_party/blink/renderer/core/paint/find_properties_needing_update.h
+++ b/chromium/third_party/blink/renderer/core/paint/find_properties_needing_update.h
@@ -12,7 +12,7 @@
#include "third_party/blink/renderer/core/layout/layout_object.h"
#include "third_party/blink/renderer/core/paint/object_paint_properties.h"
#include "third_party/blink/renderer/core/paint/paint_property_tree_builder.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/first_meaningful_paint_detector.cc b/chromium/third_party/blink/renderer/core/paint/first_meaningful_paint_detector.cc
index ba42f4d7c15..4c557678272 100644
--- a/chromium/third_party/blink/renderer/core/paint/first_meaningful_paint_detector.cc
+++ b/chromium/third_party/blink/renderer/core/paint/first_meaningful_paint_detector.cc
@@ -4,14 +4,15 @@
#include "third_party/blink/renderer/core/paint/first_meaningful_paint_detector.h"
+#include "base/time/default_tick_clock.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/renderer/core/css/font_face_set_document.h"
#include "third_party/blink/renderer/core/paint/paint_timing.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/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
namespace blink {
@@ -21,6 +22,7 @@ namespace {
// Meaningful Paint.
const int kBlankCharactersThreshold = 200;
+const base::TickClock* g_clock = nullptr;
} // namespace
FirstMeaningfulPaintDetector& FirstMeaningfulPaintDetector::From(
@@ -30,7 +32,10 @@ FirstMeaningfulPaintDetector& FirstMeaningfulPaintDetector::From(
FirstMeaningfulPaintDetector::FirstMeaningfulPaintDetector(
PaintTiming* paint_timing)
- : paint_timing_(paint_timing) {}
+ : paint_timing_(paint_timing) {
+ if (!g_clock)
+ g_clock = base::DefaultTickClock::GetInstance();
+}
Document* FirstMeaningfulPaintDetector::GetDocument() {
return paint_timing_->GetSupplementable();
@@ -46,7 +51,7 @@ void FirstMeaningfulPaintDetector::MarkNextPaintAsMeaningfulIfNeeded(
int contents_height_before_layout,
int contents_height_after_layout,
int visible_height) {
- if (network0_quiet_reached_ && network2_quiet_reached_)
+ if (network_quiet_reached_)
return;
unsigned delta = counter.Count() - prev_layout_object_count_;
@@ -84,14 +89,14 @@ void FirstMeaningfulPaintDetector::NotifyPaint() {
// Skip document background-only paints.
if (paint_timing_->FirstPaintRendered().is_null())
return;
- provisional_first_meaningful_paint_ = CurrentTimeTicks();
+ provisional_first_meaningful_paint_ = g_clock->NowTicks();
next_paint_is_meaningful_ = false;
- if (network2_quiet_reached_)
+ if (network_quiet_reached_)
return;
had_user_input_before_provisional_first_meaningful_paint_ = had_user_input_;
- provisional_first_meaningful_paint_swap_ = TimeTicks();
+ provisional_first_meaningful_paint_swap_ = base::TimeTicks();
RegisterNotifySwapTime(PaintEvent::kProvisionalFirstMeaningfulPaint);
}
@@ -103,44 +108,27 @@ void FirstMeaningfulPaintDetector::NotifyInputEvent() {
had_user_input_ = kHadUserInput;
}
-void FirstMeaningfulPaintDetector::OnNetwork0Quiet() {
- network0_quiet_reached_ = true;
- if (!GetDocument() || paint_timing_->FirstContentfulPaintRendered().is_null())
- return;
-
- if (!provisional_first_meaningful_paint_.is_null()) {
- // Enforce FirstContentfulPaint <= FirstMeaningfulPaint.
- first_meaningful_paint0_quiet_ =
- std::max(provisional_first_meaningful_paint_,
- paint_timing_->FirstContentfulPaintRendered());
- }
- ReportHistograms();
-}
-
void FirstMeaningfulPaintDetector::OnNetwork2Quiet() {
- if (!GetDocument() || network2_quiet_reached_ ||
+ if (!GetDocument() || network_quiet_reached_ ||
paint_timing_->FirstContentfulPaintRendered().is_null())
return;
- network2_quiet_reached_ = true;
+ network_quiet_reached_ = true;
if (!provisional_first_meaningful_paint_.is_null()) {
- TimeTicks first_meaningful_paint2_quiet_swap;
+ base::TimeTicks first_meaningful_paint_swap;
// Enforce FirstContentfulPaint <= FirstMeaningfulPaint.
if (provisional_first_meaningful_paint_ <
paint_timing_->FirstContentfulPaintRendered()) {
- first_meaningful_paint2_quiet_ =
- paint_timing_->FirstContentfulPaintRendered();
- first_meaningful_paint2_quiet_swap =
- paint_timing_->FirstContentfulPaint();
+ first_meaningful_paint_ = paint_timing_->FirstContentfulPaintRendered();
+ first_meaningful_paint_swap = paint_timing_->FirstContentfulPaint();
// It's possible that this timer fires between when the first contentful
// paint is set and its SwapPromise is fulfilled. If this happens, defer
// until NotifyFirstContentfulPaint() is called.
- if (first_meaningful_paint2_quiet_swap.is_null())
+ if (first_meaningful_paint_swap.is_null())
defer_first_meaningful_paint_ = kDeferFirstContentfulPaintNotSet;
} else {
- first_meaningful_paint2_quiet_ = provisional_first_meaningful_paint_;
- first_meaningful_paint2_quiet_swap =
- provisional_first_meaningful_paint_swap_;
+ first_meaningful_paint_ = provisional_first_meaningful_paint_;
+ first_meaningful_paint_swap = provisional_first_meaningful_paint_swap_;
// We might still be waiting for one or more swap promises, in which case
// we want to defer reporting first meaningful paint until they complete.
// Otherwise, we would either report the wrong swap timestamp or none at
@@ -151,54 +139,9 @@ void FirstMeaningfulPaintDetector::OnNetwork2Quiet() {
if (defer_first_meaningful_paint_ == kDoNotDefer) {
// Report FirstMeaningfulPaint when the page reached network 2-quiet if
// we aren't waiting for a swap timestamp.
- SetFirstMeaningfulPaint(first_meaningful_paint2_quiet_swap);
+ SetFirstMeaningfulPaint(first_meaningful_paint_swap);
}
}
- ReportHistograms();
-}
-
-void FirstMeaningfulPaintDetector::ReportHistograms() {
- // This enum backs an UMA histogram, and should be treated as append-only.
- enum HadNetworkQuiet {
- kHadNetwork0Quiet,
- kHadNetwork2Quiet,
- kHadNetworkQuietEnumMax
- };
- DEFINE_STATIC_LOCAL(EnumerationHistogram, had_network_quiet_histogram,
- ("PageLoad.Internal.Renderer."
- "FirstMeaningfulPaintDetector.HadNetworkQuiet",
- kHadNetworkQuietEnumMax));
-
- // This enum backs an UMA histogram, and should be treated as append-only.
- enum FMPOrderingEnum {
- kFMP0QuietFirst,
- kFMP2QuietFirst,
- kFMP0QuietEqualFMP2Quiet,
- kFMPOrderingEnumMax
- };
- DEFINE_STATIC_LOCAL(
- EnumerationHistogram, first_meaningful_paint_ordering_histogram,
- ("PageLoad.Internal.Renderer.FirstMeaningfulPaintDetector."
- "FirstMeaningfulPaintOrdering",
- kFMPOrderingEnumMax));
-
- if (!first_meaningful_paint0_quiet_.is_null() &&
- !first_meaningful_paint2_quiet_.is_null()) {
- int sample;
- if (first_meaningful_paint2_quiet_ < first_meaningful_paint0_quiet_) {
- sample = kFMP0QuietFirst;
- } else if (first_meaningful_paint2_quiet_ >
- first_meaningful_paint0_quiet_) {
- sample = kFMP2QuietFirst;
- } else {
- sample = kFMP0QuietEqualFMP2Quiet;
- }
- first_meaningful_paint_ordering_histogram.Count(sample);
- } else if (!first_meaningful_paint0_quiet_.is_null()) {
- had_network_quiet_histogram.Count(kHadNetwork0Quiet);
- } else if (!first_meaningful_paint2_quiet_.is_null()) {
- had_network_quiet_histogram.Count(kHadNetwork2Quiet);
- }
}
void FirstMeaningfulPaintDetector::RegisterNotifySwapTime(PaintEvent event) {
@@ -245,23 +188,23 @@ void FirstMeaningfulPaintDetector::ReportSwapTime(
if (defer_first_meaningful_paint_ == kDeferOutstandingSwapPromises &&
outstanding_swap_promise_count_ == 0) {
- DCHECK(!first_meaningful_paint2_quiet_.is_null());
+ DCHECK(!first_meaningful_paint_.is_null());
SetFirstMeaningfulPaint(provisional_first_meaningful_paint_swap_);
}
}
void FirstMeaningfulPaintDetector::NotifyFirstContentfulPaint(
- TimeTicks swap_stamp) {
+ base::TimeTicks swap_stamp) {
if (defer_first_meaningful_paint_ != kDeferFirstContentfulPaintNotSet)
return;
SetFirstMeaningfulPaint(swap_stamp);
}
void FirstMeaningfulPaintDetector::SetFirstMeaningfulPaint(
- TimeTicks swap_stamp) {
+ base::TimeTicks swap_stamp) {
DCHECK(paint_timing_->FirstMeaningfulPaint().is_null());
DCHECK(!swap_stamp.is_null());
- DCHECK(network2_quiet_reached_);
+ DCHECK(network_quiet_reached_);
double swap_time_seconds = swap_stamp.since_origin().InSecondsF();
probe::PaintTiming(GetDocument(), "firstMeaningfulPaint", swap_time_seconds);
@@ -275,6 +218,12 @@ void FirstMeaningfulPaintDetector::SetFirstMeaningfulPaint(
swap_stamp, had_user_input_before_provisional_first_meaningful_paint_);
}
+// static
+void FirstMeaningfulPaintDetector::SetTickClockForTesting(
+ const base::TickClock* clock) {
+ g_clock = clock;
+}
+
void FirstMeaningfulPaintDetector::Trace(blink::Visitor* visitor) {
visitor->Trace(paint_timing_);
}
diff --git a/chromium/third_party/blink/renderer/core/paint/first_meaningful_paint_detector.h b/chromium/third_party/blink/renderer/core/paint/first_meaningful_paint_detector.h
index ca390f18254..94ee49875fd 100644
--- a/chromium/third_party/blink/renderer/core/paint/first_meaningful_paint_detector.h
+++ b/chromium/third_party/blink/renderer/core/paint/first_meaningful_paint_detector.h
@@ -12,6 +12,10 @@
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
+namespace base {
+class TickClock;
+}
+
namespace blink {
class Document;
@@ -19,8 +23,8 @@ class LayoutObjectCounter;
class PaintTiming;
// FirstMeaningfulPaintDetector observes layout operations during page load
-// until network stable (0.5 seconds of no network activity), and computes the
-// layout-based First Meaningful Paint.
+// until network stable (no more than 2 network connections active in 0.5
+// seconds), and computes the layout-based First Meaningful Paint.
// See https://goo.gl/vpaxv6 and http://goo.gl/TEiMi4 for more details.
class CORE_EXPORT FirstMeaningfulPaintDetector
: public GarbageCollectedFinalized<FirstMeaningfulPaintDetector> {
@@ -37,10 +41,12 @@ class CORE_EXPORT FirstMeaningfulPaintDetector
void NotifyInputEvent();
void NotifyPaint();
void ReportSwapTime(PaintEvent, WebWidgetClient::SwapResult, base::TimeTicks);
- void NotifyFirstContentfulPaint(TimeTicks swap_stamp);
- void OnNetwork0Quiet();
+ void NotifyFirstContentfulPaint(base::TimeTicks swap_stamp);
void OnNetwork2Quiet();
+ // The caller owns the |clock| which must outlive the paint detector.
+ static void SetTickClockForTesting(const base::TickClock* clock);
+
void Trace(blink::Visitor*);
enum HadUserInput { kNoUserInput, kHadUserInput, kHadUserInputEnumMax };
@@ -56,9 +62,8 @@ class CORE_EXPORT FirstMeaningfulPaintDetector
Document* GetDocument();
int ActiveConnections();
- void ReportHistograms();
void RegisterNotifySwapTime(PaintEvent);
- void SetFirstMeaningfulPaint(TimeTicks swap_stamp);
+ void SetFirstMeaningfulPaint(base::TimeTicks swap_stamp);
bool next_paint_is_meaningful_ = false;
HadUserInput had_user_input_ = kNoUserInput;
@@ -66,16 +71,14 @@ class CORE_EXPORT FirstMeaningfulPaintDetector
kNoUserInput;
Member<PaintTiming> paint_timing_;
- TimeTicks provisional_first_meaningful_paint_;
- TimeTicks provisional_first_meaningful_paint_swap_;
+ base::TimeTicks provisional_first_meaningful_paint_;
+ base::TimeTicks provisional_first_meaningful_paint_swap_;
double max_significance_so_far_ = 0.0;
double accumulated_significance_while_having_blank_text_ = 0.0;
unsigned prev_layout_object_count_ = 0;
bool seen_first_meaningful_paint_candidate_ = false;
- bool network0_quiet_reached_ = false;
- bool network2_quiet_reached_ = false;
- TimeTicks first_meaningful_paint0_quiet_;
- TimeTicks first_meaningful_paint2_quiet_;
+ bool network_quiet_reached_ = false;
+ base::TimeTicks first_meaningful_paint_;
unsigned outstanding_swap_promise_count_ = 0;
DeferFirstMeaningfulPaint defer_first_meaningful_paint_ = kDoNotDefer;
DISALLOW_COPY_AND_ASSIGN(FirstMeaningfulPaintDetector);
diff --git a/chromium/third_party/blink/renderer/core/paint/first_meaningful_paint_detector_test.cc b/chromium/third_party/blink/renderer/core/paint/first_meaningful_paint_detector_test.cc
index aa4923c6a28..19483295968 100644
--- a/chromium/third_party/blink/renderer/core/paint/first_meaningful_paint_detector_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/first_meaningful_paint_detector_test.cc
@@ -9,7 +9,6 @@
#include "third_party/blink/renderer/core/paint/paint_event.h"
#include "third_party/blink/renderer/core/paint/paint_timing.h"
#include "third_party/blink/renderer/core/testing/page_test_base.h"
-#include "third_party/blink/renderer/platform/testing/testing_platform_support_with_mock_scheduler.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
@@ -18,13 +17,27 @@ namespace blink {
class FirstMeaningfulPaintDetectorTest : public PageTestBase {
protected:
void SetUp() override {
- platform_->AdvanceClock(TimeDelta::FromSeconds(1));
+ EnablePlatform();
+ platform()->AdvanceClock(base::TimeDelta::FromSeconds(1));
+ const base::TickClock* test_clock =
+ platform()->test_task_runner()->GetMockTickClock();
+ FirstMeaningfulPaintDetector::SetTickClockForTesting(test_clock);
PageTestBase::SetUp();
+ GetPaintTiming().SetTickClockForTesting(test_clock);
}
- TimeTicks AdvanceClockAndGetTime() {
- platform_->AdvanceClock(TimeDelta::FromSeconds(1));
- return CurrentTimeTicks();
+ void TearDown() override {
+ const base::TickClock* clock = base::DefaultTickClock::GetInstance();
+ GetPaintTiming().SetTickClockForTesting(clock);
+ PageTestBase::TearDown();
+ FirstMeaningfulPaintDetector::SetTickClockForTesting(clock);
+ }
+
+ base::TimeTicks Now() { return platform()->test_task_runner()->NowTicks(); }
+
+ base::TimeTicks AdvanceClockAndGetTime() {
+ platform()->AdvanceClock(base::TimeDelta::FromSeconds(1));
+ return Now();
}
PaintTiming& GetPaintTiming() { return PaintTiming::From(GetDocument()); }
@@ -33,7 +46,7 @@ class FirstMeaningfulPaintDetectorTest : public PageTestBase {
}
void SimulateLayoutAndPaint(int new_elements) {
- platform_->AdvanceClock(TimeDelta::FromMilliseconds(1));
+ platform()->AdvanceClock(base::TimeDelta::FromMilliseconds(1));
StringBuilder builder;
for (int i = 0; i < new_elements; i++)
builder.Append("<span>a</span>");
@@ -44,39 +57,27 @@ class FirstMeaningfulPaintDetectorTest : public PageTestBase {
void SimulateNetworkStable() {
GetDocument().SetParsingState(Document::kFinishedParsing);
- Detector().OnNetwork0Quiet();
- Detector().OnNetwork2Quiet();
- }
-
- void SimulateNetwork0Quiet() {
- GetDocument().SetParsingState(Document::kFinishedParsing);
- Detector().OnNetwork0Quiet();
- }
-
- void SimulateNetwork2Quiet() {
- GetDocument().SetParsingState(Document::kFinishedParsing);
Detector().OnNetwork2Quiet();
}
void SimulateUserInput() { Detector().NotifyInputEvent(); }
void ClearFirstPaintSwapPromise() {
- platform_->AdvanceClock(TimeDelta::FromMilliseconds(1));
- GetPaintTiming().ReportSwapTime(PaintEvent::kFirstPaint,
- WebWidgetClient::SwapResult::kDidSwap,
- CurrentTimeTicks());
+ platform()->AdvanceClock(base::TimeDelta::FromMilliseconds(1));
+ GetPaintTiming().ReportSwapTime(
+ PaintEvent::kFirstPaint, WebWidgetClient::SwapResult::kDidSwap, Now());
}
void ClearFirstContentfulPaintSwapPromise() {
- platform_->AdvanceClock(TimeDelta::FromMilliseconds(1));
+ platform()->AdvanceClock(base::TimeDelta::FromMilliseconds(1));
GetPaintTiming().ReportSwapTime(PaintEvent::kFirstContentfulPaint,
WebWidgetClient::SwapResult::kDidSwap,
- CurrentTimeTicks());
+ Now());
}
void ClearProvisionalFirstMeaningfulPaintSwapPromise() {
- platform_->AdvanceClock(TimeDelta::FromMilliseconds(1));
- ClearProvisionalFirstMeaningfulPaintSwapPromise(CurrentTimeTicks());
+ platform()->AdvanceClock(base::TimeDelta::FromMilliseconds(1));
+ ClearProvisionalFirstMeaningfulPaintSwapPromise(Now());
}
void ClearProvisionalFirstMeaningfulPaintSwapPromise(
@@ -98,17 +99,13 @@ class FirstMeaningfulPaintDetectorTest : public PageTestBase {
GetPaintTiming().MarkFirstPaint();
ClearFirstPaintSwapPromise();
}
-
- protected:
- ScopedTestingPlatformSupport<TestingPlatformSupportWithMockScheduler>
- platform_;
};
TEST_F(FirstMeaningfulPaintDetectorTest, NoFirstPaint) {
SimulateLayoutAndPaint(1);
EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 0U);
SimulateNetworkStable();
- EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), TimeTicks());
+ EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), base::TimeTicks());
}
TEST_F(FirstMeaningfulPaintDetectorTest, OneLayout) {
@@ -116,8 +113,8 @@ TEST_F(FirstMeaningfulPaintDetectorTest, OneLayout) {
SimulateLayoutAndPaint(1);
EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U);
ClearProvisionalFirstMeaningfulPaintSwapPromise();
- TimeTicks after_paint = AdvanceClockAndGetTime();
- EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), TimeTicks());
+ base::TimeTicks after_paint = AdvanceClockAndGetTime();
+ EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), base::TimeTicks());
SimulateNetworkStable();
EXPECT_LT(GetPaintTiming().FirstMeaningfulPaint(), after_paint);
}
@@ -127,11 +124,11 @@ TEST_F(FirstMeaningfulPaintDetectorTest, TwoLayoutsSignificantSecond) {
SimulateLayoutAndPaint(1);
EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U);
ClearProvisionalFirstMeaningfulPaintSwapPromise();
- TimeTicks after_layout1 = AdvanceClockAndGetTime();
+ base::TimeTicks after_layout1 = AdvanceClockAndGetTime();
SimulateLayoutAndPaint(10);
EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U);
ClearProvisionalFirstMeaningfulPaintSwapPromise();
- TimeTicks after_layout2 = AdvanceClockAndGetTime();
+ base::TimeTicks after_layout2 = AdvanceClockAndGetTime();
SimulateNetworkStable();
EXPECT_GT(GetPaintTiming().FirstMeaningfulPaint(), after_layout1);
EXPECT_LT(GetPaintTiming().FirstMeaningfulPaint(), after_layout2);
@@ -142,7 +139,7 @@ TEST_F(FirstMeaningfulPaintDetectorTest, TwoLayoutsSignificantFirst) {
SimulateLayoutAndPaint(10);
EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U);
ClearProvisionalFirstMeaningfulPaintSwapPromise();
- TimeTicks after_layout1 = AdvanceClockAndGetTime();
+ base::TimeTicks after_layout1 = AdvanceClockAndGetTime();
SimulateLayoutAndPaint(1);
EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 0U);
SimulateNetworkStable();
@@ -153,19 +150,21 @@ TEST_F(FirstMeaningfulPaintDetectorTest, TwoLayoutsSignificantFirst) {
TEST_F(FirstMeaningfulPaintDetectorTest, FirstMeaningfulPaintCandidate) {
MarkFirstContentfulPaintAndClearSwapPromise();
- EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaintCandidate(), TimeTicks());
+ EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaintCandidate(),
+ base::TimeTicks());
SimulateLayoutAndPaint(1);
EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U);
ClearProvisionalFirstMeaningfulPaintSwapPromise();
- TimeTicks after_paint = AdvanceClockAndGetTime();
+ base::TimeTicks after_paint = AdvanceClockAndGetTime();
// The first candidate gets ignored.
- EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaintCandidate(), TimeTicks());
+ EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaintCandidate(),
+ base::TimeTicks());
SimulateLayoutAndPaint(10);
EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U);
ClearProvisionalFirstMeaningfulPaintSwapPromise();
// The second candidate gets reported.
EXPECT_GT(GetPaintTiming().FirstMeaningfulPaintCandidate(), after_paint);
- TimeTicks candidate = GetPaintTiming().FirstMeaningfulPaintCandidate();
+ base::TimeTicks candidate = GetPaintTiming().FirstMeaningfulPaintCandidate();
// The third candidate gets ignored since we already saw the first candidate.
SimulateLayoutAndPaint(20);
EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U);
@@ -176,17 +175,19 @@ TEST_F(FirstMeaningfulPaintDetectorTest, FirstMeaningfulPaintCandidate) {
TEST_F(FirstMeaningfulPaintDetectorTest,
OnlyOneFirstMeaningfulPaintCandidateBeforeNetworkStable) {
MarkFirstContentfulPaintAndClearSwapPromise();
- EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaintCandidate(), TimeTicks());
- TimeTicks before_paint = AdvanceClockAndGetTime();
+ EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaintCandidate(),
+ base::TimeTicks());
+ base::TimeTicks before_paint = AdvanceClockAndGetTime();
SimulateLayoutAndPaint(1);
EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U);
ClearProvisionalFirstMeaningfulPaintSwapPromise();
// The first candidate is initially ignored.
- EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaintCandidate(), TimeTicks());
+ EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaintCandidate(),
+ base::TimeTicks());
SimulateNetworkStable();
// The networkStable then promotes the first candidate.
EXPECT_GT(GetPaintTiming().FirstMeaningfulPaintCandidate(), before_paint);
- TimeTicks candidate = GetPaintTiming().FirstMeaningfulPaintCandidate();
+ base::TimeTicks candidate = GetPaintTiming().FirstMeaningfulPaintCandidate();
// The second candidate is then ignored.
SimulateLayoutAndPaint(10);
EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 0U);
@@ -200,10 +201,10 @@ TEST_F(FirstMeaningfulPaintDetectorTest,
EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U);
ClearProvisionalFirstMeaningfulPaintSwapPromise();
SimulateNetworkStable();
- EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), TimeTicks());
+ EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), base::TimeTicks());
MarkFirstContentfulPaintAndClearSwapPromise();
SimulateNetworkStable();
- EXPECT_NE(GetPaintTiming().FirstMeaningfulPaint(), TimeTicks());
+ EXPECT_NE(GetPaintTiming().FirstMeaningfulPaint(), base::TimeTicks());
}
TEST_F(FirstMeaningfulPaintDetectorTest,
@@ -212,53 +213,13 @@ TEST_F(FirstMeaningfulPaintDetectorTest,
SimulateLayoutAndPaint(10);
EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U);
ClearProvisionalFirstMeaningfulPaintSwapPromise();
- platform_->AdvanceClock(TimeDelta::FromMilliseconds(1));
+ platform()->AdvanceClock(base::TimeDelta::FromMilliseconds(1));
MarkFirstContentfulPaintAndClearSwapPromise();
SimulateNetworkStable();
EXPECT_GE(GetPaintTiming().FirstMeaningfulPaint(),
GetPaintTiming().FirstContentfulPaint());
}
-TEST_F(FirstMeaningfulPaintDetectorTest, Network2QuietThen0Quiet) {
- MarkFirstContentfulPaintAndClearSwapPromise();
-
- SimulateLayoutAndPaint(1);
- EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U);
- TimeTicks after_first_paint = AdvanceClockAndGetTime();
- ClearProvisionalFirstMeaningfulPaintSwapPromise();
- TimeTicks after_first_paint_swap = AdvanceClockAndGetTime();
- SimulateNetwork2Quiet();
-
- SimulateLayoutAndPaint(10);
- EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 0U);
- SimulateNetwork0Quiet();
-
- // The first paint is FirstMeaningfulPaint.
- EXPECT_GT(GetPaintTiming().FirstMeaningfulPaint(), TimeTicks());
- EXPECT_GT(GetPaintTiming().FirstMeaningfulPaint(), after_first_paint);
- EXPECT_LT(GetPaintTiming().FirstMeaningfulPaint(), after_first_paint_swap);
-}
-
-TEST_F(FirstMeaningfulPaintDetectorTest, Network0QuietThen2Quiet) {
- MarkFirstContentfulPaintAndClearSwapPromise();
-
- SimulateLayoutAndPaint(1);
- EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U);
- ClearProvisionalFirstMeaningfulPaintSwapPromise();
- TimeTicks after_first_paint = AdvanceClockAndGetTime();
- SimulateNetwork0Quiet();
-
- SimulateLayoutAndPaint(10);
- EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U);
- ClearProvisionalFirstMeaningfulPaintSwapPromise();
- TimeTicks after_second_paint = AdvanceClockAndGetTime();
- SimulateNetwork2Quiet();
-
- // The second paint is FirstMeaningfulPaint.
- EXPECT_GT(GetPaintTiming().FirstMeaningfulPaint(), after_first_paint);
- EXPECT_LT(GetPaintTiming().FirstMeaningfulPaint(), after_second_paint);
-}
-
TEST_F(FirstMeaningfulPaintDetectorTest,
FirstMeaningfulPaintAfterUserInteraction) {
MarkFirstContentfulPaintAndClearSwapPromise();
@@ -267,7 +228,7 @@ TEST_F(FirstMeaningfulPaintDetectorTest,
EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U);
ClearProvisionalFirstMeaningfulPaintSwapPromise();
SimulateNetworkStable();
- EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), TimeTicks());
+ EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), base::TimeTicks());
}
TEST_F(FirstMeaningfulPaintDetectorTest, UserInteractionBeforeFirstPaint) {
@@ -277,7 +238,7 @@ TEST_F(FirstMeaningfulPaintDetectorTest, UserInteractionBeforeFirstPaint) {
EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U);
ClearProvisionalFirstMeaningfulPaintSwapPromise();
SimulateNetworkStable();
- EXPECT_NE(GetPaintTiming().FirstMeaningfulPaint(), TimeTicks());
+ EXPECT_NE(GetPaintTiming().FirstMeaningfulPaint(), base::TimeTicks());
}
TEST_F(FirstMeaningfulPaintDetectorTest,
@@ -286,9 +247,9 @@ TEST_F(FirstMeaningfulPaintDetectorTest,
SimulateLayoutAndPaint(10);
EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U);
SimulateNetworkStable();
- EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), TimeTicks());
+ EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), base::TimeTicks());
ClearProvisionalFirstMeaningfulPaintSwapPromise();
- EXPECT_NE(GetPaintTiming().FirstMeaningfulPaint(), TimeTicks());
+ EXPECT_NE(GetPaintTiming().FirstMeaningfulPaint(), base::TimeTicks());
}
TEST_F(FirstMeaningfulPaintDetectorTest,
@@ -296,21 +257,21 @@ TEST_F(FirstMeaningfulPaintDetectorTest,
MarkFirstContentfulPaintAndClearSwapPromise();
SimulateLayoutAndPaint(1);
EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U);
- platform_->AdvanceClock(TimeDelta::FromMilliseconds(1));
+ platform()->AdvanceClock(base::TimeDelta::FromMilliseconds(1));
SimulateLayoutAndPaint(10);
EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 2U);
// Having outstanding swap promises should defer setting FMP.
SimulateNetworkStable();
- EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), TimeTicks());
+ EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), base::TimeTicks());
// Clearing the first swap promise should have no effect on FMP.
ClearProvisionalFirstMeaningfulPaintSwapPromise();
EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U);
- EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), TimeTicks());
- TimeTicks after_first_swap = AdvanceClockAndGetTime();
+ EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), base::TimeTicks());
+ base::TimeTicks after_first_swap = AdvanceClockAndGetTime();
// Clearing the last outstanding swap promise should set FMP.
ClearProvisionalFirstMeaningfulPaintSwapPromise();
EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 0U);
- EXPECT_GT(GetPaintTiming().FirstMeaningfulPaint(), TimeTicks());
+ EXPECT_GT(GetPaintTiming().FirstMeaningfulPaint(), base::TimeTicks());
EXPECT_GT(GetPaintTiming().FirstMeaningfulPaint(), after_first_swap);
}
@@ -320,14 +281,14 @@ TEST_F(FirstMeaningfulPaintDetectorTest,
SimulateLayoutAndPaint(10);
EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U);
ClearProvisionalFirstMeaningfulPaintSwapPromise();
- platform_->AdvanceClock(TimeDelta::FromMilliseconds(1));
+ platform()->AdvanceClock(base::TimeDelta::FromMilliseconds(1));
GetPaintTiming().MarkFirstContentfulPaint();
// FCP > FMP candidate, but still waiting for FCP swap.
SimulateNetworkStable();
- EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), TimeTicks());
+ EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), base::TimeTicks());
// Trigger notifying the detector about the FCP swap.
ClearFirstContentfulPaintSwapPromise();
- EXPECT_GT(GetPaintTiming().FirstMeaningfulPaint(), TimeTicks());
+ EXPECT_GT(GetPaintTiming().FirstMeaningfulPaint(), base::TimeTicks());
EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(),
GetPaintTiming().FirstContentfulPaint());
}
@@ -338,16 +299,15 @@ TEST_F(FirstMeaningfulPaintDetectorTest,
SimulateLayoutAndPaint(1);
EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U);
- // Simulate only network 2-quiet so provisional FMP will be set on next
- // layout.
- TimeTicks pre_stable_timestamp = AdvanceClockAndGetTime();
- platform_->AdvanceClock(TimeDelta::FromMilliseconds(1));
- SimulateNetwork2Quiet();
- EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), TimeTicks());
+ // Simulate network stable so provisional FMP will be set on next layout.
+ base::TimeTicks pre_stable_timestamp = AdvanceClockAndGetTime();
+ platform()->AdvanceClock(base::TimeDelta::FromMilliseconds(1));
+ SimulateNetworkStable();
+ EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), base::TimeTicks());
// Force another FMP candidate while there is a pending swap promise and the
- // network 2-quiet FMP non-swap timestamp is set.
- platform_->AdvanceClock(TimeDelta::FromMilliseconds(1));
+ // FMP non-swap timestamp is set.
+ platform()->AdvanceClock(base::TimeDelta::FromMilliseconds(1));
SimulateLayoutAndPaint(10);
EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 1U);
@@ -356,7 +316,7 @@ TEST_F(FirstMeaningfulPaintDetectorTest,
// non-swap timestamp is used.
ClearProvisionalFirstMeaningfulPaintSwapPromise(pre_stable_timestamp);
EXPECT_EQ(OutstandingDetectorSwapPromiseCount(), 0U);
- EXPECT_GT(GetPaintTiming().FirstMeaningfulPaint(), TimeTicks());
+ EXPECT_GT(GetPaintTiming().FirstMeaningfulPaint(), base::TimeTicks());
EXPECT_EQ(GetPaintTiming().FirstMeaningfulPaint(), pre_stable_timestamp);
}
diff --git a/chromium/third_party/blink/renderer/core/paint/fragment_data.cc b/chromium/third_party/blink/renderer/core/paint/fragment_data.cc
index ad011e84092..91dd73c8bd9 100644
--- a/chromium/third_party/blink/renderer/core/paint/fragment_data.cc
+++ b/chromium/third_party/blink/renderer/core/paint/fragment_data.cc
@@ -15,21 +15,22 @@ FragmentData::RareData::RareData() : unique_id(NewUniqueObjectId()) {}
FragmentData::RareData::~RareData() = default;
void FragmentData::DestroyTail() {
- while (next_fragment_) {
- // Take the following (next-next) fragment, clearing
- // |next_fragment_->next_fragment_|.
- std::unique_ptr<FragmentData> next =
- std::move(next_fragment_->next_fragment_);
- // Point |next_fragment_| to the following fragment and destroy
- // the current |next_fragment_|.
- next_fragment_ = std::move(next);
+ if (!rare_data_)
+ return;
+ // Take next_fragment_ which clears it in this fragment.
+ std::unique_ptr<FragmentData> next = std::move(rare_data_->next_fragment_);
+ while (next && next->rare_data_) {
+ // Take next_fragment_ which clears it in that fragment, and the assignment
+ // deletes the previous |next|.
+ next = std::move(next->rare_data_->next_fragment_);
}
+ // The last |next| will be deleted on return.
}
FragmentData& FragmentData::EnsureNextFragment() {
- if (!next_fragment_)
- next_fragment_ = std::make_unique<FragmentData>();
- return *next_fragment_.get();
+ if (!NextFragment())
+ EnsureRareData().next_fragment_ = std::make_unique<FragmentData>();
+ return *rare_data_->next_fragment_;
}
FragmentData::RareData& FragmentData::EnsureRareData() {
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 8a35b7b317a..39e92e518a0 100644
--- a/chromium/third_party/blink/renderer/core/paint/fragment_data.h
+++ b/chromium/third_party/blink/renderer/core/paint/fragment_data.h
@@ -9,7 +9,7 @@
#include "third_party/blink/renderer/core/layout/geometry/physical_rect.h"
#include "third_party/blink/renderer/core/paint/object_paint_properties.h"
#include "third_party/blink/renderer/platform/graphics/paint/ref_counted_property_tree_state.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -23,7 +23,9 @@ class CORE_EXPORT FragmentData {
USING_FAST_MALLOC(FragmentData);
public:
- FragmentData* NextFragment() const { return next_fragment_.get(); }
+ FragmentData* NextFragment() const {
+ return rare_data_ ? rare_data_->next_fragment_.get() : nullptr;
+ }
FragmentData& EnsureNextFragment();
void ClearNextFragment() { DestroyTail(); }
@@ -227,13 +229,17 @@ class CORE_EXPORT FragmentData {
void MapRectToFragment(const FragmentData& fragment, IntRect&) const;
~FragmentData() {
- if (next_fragment_)
+ if (NextFragment())
DestroyTail();
}
private:
friend class FragmentDataTest;
+ // We could let the compiler generate code to automatically destroy the
+ // next_fragment_ chain, but the code would cause stack overflow in some
+ // cases (e.g. fast/multicol/infinitely-tall-content-in-outer-crash.html).
+ // This function destroy the next_fragment_ chain non-recursively.
void DestroyTail();
// Contains rare data that that is not needed on all fragments.
@@ -260,6 +266,7 @@ class CORE_EXPORT FragmentData {
bool is_clip_path_cache_valid = false;
base::Optional<IntRect> clip_path_bounding_box;
scoped_refptr<const RefCountedPath> clip_path_path;
+ std::unique_ptr<FragmentData> next_fragment_;
DISALLOW_COPY_AND_ASSIGN(RareData);
};
@@ -270,7 +277,6 @@ class CORE_EXPORT FragmentData {
PhysicalOffset paint_offset_;
std::unique_ptr<RareData> rare_data_;
- std::unique_ptr<FragmentData> next_fragment_;
};
} // namespace blink
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 b1b9a2e863a..a3cbfbc972d 100644
--- a/chromium/third_party/blink/renderer/core/paint/frame_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/frame_painter.cc
@@ -103,11 +103,6 @@ void FramePainter::PaintContents(GraphicsContext& context,
layer_painter.Paint(context, cull_rect, updated_global_paint_flags,
root_layer_paint_flags);
- if (root_layer->ContainsDirtyOverlayScrollbars()) {
- layer_painter.PaintOverlayScrollbars(context, cull_rect,
- updated_global_paint_flags);
- }
-
// Regions may have changed as a result of the visibility/z-index of element
// changing.
if (document->AnnotatedRegionsDirty())
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 8962aee07fd..e36e0c2f4c7 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
@@ -4,6 +4,7 @@
#include "third_party/blink/renderer/core/paint/frame_set_painter.h"
+#include "third_party/blink/renderer/core/display_lock/display_lock_context.h"
#include "third_party/blink/renderer/core/html/html_frame_set_element.h"
#include "third_party/blink/renderer/core/layout/layout_frame_set.h"
#include "third_party/blink/renderer/core/paint/paint_info.h"
@@ -126,6 +127,11 @@ void FrameSetPainter::PaintBorders(const PaintInfo& paint_info,
}
void FrameSetPainter::PaintChildren(const PaintInfo& paint_info) {
+ if (layout_frame_set_.PaintBlockedByDisplayLock(
+ DisplayLockContext::kChildren)) {
+ return;
+ }
+
// Paint only those children that fit in the grid.
// Remaining frames are "hidden".
// See also LayoutFrameSet::positionFrames.
diff --git a/chromium/third_party/blink/renderer/core/paint/frame_set_painter.h b/chromium/third_party/blink/renderer/core/paint/frame_set_painter.h
index 5839aa7b080..051a19924e1 100644
--- a/chromium/third_party/blink/renderer/core/paint/frame_set_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/frame_set_painter.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_FRAME_SET_PAINTER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_FRAME_SET_PAINTER_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/html_canvas_painter.h b/chromium/third_party/blink/renderer/core/paint/html_canvas_painter.h
index fdbaa3fb6fe..396ddd8a681 100644
--- a/chromium/third_party/blink/renderer/core/paint/html_canvas_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/html_canvas_painter.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_HTML_CANVAS_PAINTER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_HTML_CANVAS_PAINTER_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 a94a35e92b8..136e504e4be 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
@@ -5,33 +5,49 @@
#include "third_party/blink/renderer/core/paint/image_element_timing.h"
#include "third_party/blink/renderer/core/layout/layout_object.h"
-#include "third_party/blink/renderer/core/layout/layout_replaced.h"
-#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/loader/resource/image_resource_content.h"
#include "third_party/blink/renderer/core/page/chrome_client.h"
-#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
-#include "third_party/blink/renderer/core/style/style_image.h"
+#include "third_party/blink/renderer/core/paint/element_timing_utils.h"
+#include "third_party/blink/renderer/core/style/style_fetched_image.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/cross_thread_functional.h"
-#include "third_party/blink/renderer/platform/graphics/paint/geometry_mapper.h"
#include "third_party/blink/renderer/platform/graphics/paint/property_tree_state.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/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
namespace blink {
-// TODO(npm): decide on a reasonable value for the threshold.
-constexpr const float kImageTimingSizeThreshold = 0.15f;
+namespace internal {
-// The maximum amount of characters included in Element Timing for inline
-// images.
-constexpr const unsigned kInlineImageMaxChars = 100u;
+// "CORE_EXPORT" is needed to make this function visible to tests.
+bool CORE_EXPORT
+IsExplicitlyRegisteredForTiming(const LayoutObject* layout_object) {
+ DCHECK(layout_object);
+ const auto* element = DynamicTo<Element>(layout_object->GetNode());
+ if (!element)
+ return false;
+
+ // If the element has no 'elementtiming' attribute or an empty value, do not
+ // generate timing entries for the element. See
+ // https://wicg.github.io/element-timing/#sec-modifications-DOM for report
+ // vs. ignore criteria.
+ const AtomicString& attr =
+ element->FastGetAttribute(html_names::kElementtimingAttr);
+ return !attr.IsEmpty();
+}
+
+} // namespace internal
// static
const char ImageElementTiming::kSupplementName[] = "ImageElementTiming";
+AtomicString ImagePaintString() {
+ DEFINE_STATIC_LOCAL(const AtomicString, kImagePaint, ("image-paint"));
+ return kImagePaint;
+}
+
// static
ImageElementTiming& ImageElementTiming::From(LocalDOMWindow& window) {
ImageElementTiming* timing =
@@ -49,15 +65,47 @@ ImageElementTiming::ImageElementTiming(LocalDOMWindow& window)
GetSupplementable()->document()));
}
+void ImageElementTiming::NotifyImageFinished(
+ const LayoutObject& layout_object,
+ const ImageResourceContent* cached_image) {
+ if (!internal::IsExplicitlyRegisteredForTiming(&layout_object))
+ return;
+
+ const auto& insertion_result = images_notified_.insert(
+ std::make_pair(&layout_object, cached_image), ImageInfo());
+ if (insertion_result.is_new_entry)
+ insertion_result.stored_value->value.load_time_ = base::TimeTicks::Now();
+}
+
+void ImageElementTiming::NotifyBackgroundImageFinished(
+ const StyleFetchedImage* style_image) {
+ const auto& insertion_result =
+ background_image_timestamps_.insert(style_image, base::TimeTicks());
+ if (insertion_result.is_new_entry)
+ insertion_result.stored_value->value = base::TimeTicks::Now();
+}
+
+base::TimeTicks ImageElementTiming::GetBackgroundImageLoadTime(
+ const StyleFetchedImage* style_image) {
+ return background_image_timestamps_.at(style_image);
+}
+
void ImageElementTiming::NotifyImagePainted(
const LayoutObject* layout_object,
const ImageResourceContent* cached_image,
const PropertyTreeState& current_paint_chunk_properties) {
DCHECK(layout_object);
- auto result = images_notified_.insert(layout_object);
- if (result.is_new_entry && cached_image) {
+
+ if (!internal::IsExplicitlyRegisteredForTiming(layout_object))
+ return;
+
+ auto it = images_notified_.find(std::make_pair(layout_object, cached_image));
+ DCHECK(it != images_notified_.end());
+ if (!it->value.is_painted_ && cached_image) {
+ it->value.is_painted_ = true;
NotifyImagePaintedInternal(layout_object->GetNode(), *layout_object,
- *cached_image, current_paint_chunk_properties);
+ *cached_image, current_paint_chunk_properties,
+ it->value.load_time_);
}
}
@@ -65,14 +113,16 @@ void ImageElementTiming::NotifyImagePaintedInternal(
Node* node,
const LayoutObject& layout_object,
const ImageResourceContent& cached_image,
- const PropertyTreeState& current_paint_chunk_properties) {
+ const PropertyTreeState& current_paint_chunk_properties,
+ base::TimeTicks load_time) {
LocalFrame* frame = GetSupplementable()->GetFrame();
DCHECK(frame == layout_object.GetDocument().GetFrame());
DCHECK(node);
// Background images could cause |node| to not be an element. For example,
// style applied to body causes this node to be a Document Node. Therefore,
// bail out if that is the case.
- if (!frame || !node->IsElementNode())
+ auto* element = DynamicTo<Element>(node);
+ if (!frame || !element)
return;
// We do not expose elements in shadow trees, for now. We might expose
@@ -82,13 +132,17 @@ void ImageElementTiming::NotifyImagePaintedInternal(
if (node->IsInShadowTree())
return;
- FloatRect intersection_rect = ComputeIntersectionRect(
- frame, layout_object, current_paint_chunk_properties);
- Element* element = ToElement(node);
+ // Do not expose elements which should have effective zero opacity.
+ // We can afford to call this expensive method because this is only called
+ // once per image annotated with the elementtiming attribute.
+ if (!layout_object.HasNonZeroEffectiveOpacity())
+ return;
+
+ FloatRect intersection_rect = ElementTimingUtils::ComputeIntersectionRect(
+ frame, layout_object.FirstFragment().VisualRect(),
+ current_paint_chunk_properties);
const AtomicString attr =
element->FastGetAttribute(html_names::kElementtimingAttr);
- if (!ShouldReportElement(frame, attr, intersection_rect))
- return;
const AtomicString& id = element->GetIdAttribute();
@@ -104,13 +158,11 @@ void ImageElementTiming::NotifyImagePaintedInternal(
&layout_object.GetDocument())) {
WindowPerformance* performance =
DOMWindowPerformance::performance(*GetSupplementable());
- if (performance &&
- (performance->HasObserverFor(PerformanceEntry::kElement) ||
- performance->ShouldBufferEntries())) {
+ if (performance) {
// Create an entry with a |startTime| of 0.
performance->AddElementTiming(
- AtomicString(url.GetString()), intersection_rect, TimeTicks(),
- cached_image.LoadResponseEnd(), attr,
+ ImagePaintString(), url.GetString(), intersection_rect,
+ base::TimeTicks(), load_time, attr,
cached_image.IntrinsicSize(kDoNotRespectImageOrientation), id,
element);
}
@@ -121,12 +173,11 @@ void ImageElementTiming::NotifyImagePaintedInternal(
// PerformanceElementTiming entry should be the URL trimmed to 100 characters.
// If it is not, then pass in the full URL regardless of the length to be
// consistent with Resource Timing.
- const String& image_name = url.ProtocolIsData()
- ? url.GetString().Left(kInlineImageMaxChars)
- : url.GetString();
+ const String& image_url = url.ProtocolIsData()
+ ? url.GetString().Left(kInlineImageMaxChars)
+ : url.GetString();
element_timings_.emplace_back(MakeGarbageCollected<ElementTimingInfo>(
- AtomicString(image_name), intersection_rect,
- cached_image.LoadResponseEnd(), attr,
+ image_url, intersection_rect, load_time, attr,
cached_image.IntrinsicSize(kDoNotRespectImageOrientation), id, element));
// Only queue a swap promise when |element_timings_| was empty. All of the
// records in |element_timings_| will be processed when the promise succeeds
@@ -141,68 +192,46 @@ void ImageElementTiming::NotifyImagePaintedInternal(
void ImageElementTiming::NotifyBackgroundImagePainted(
Node* node,
- const StyleImage* background_image,
+ const StyleFetchedImage* background_image,
const PropertyTreeState& current_paint_chunk_properties) {
DCHECK(node);
DCHECK(background_image);
+
const LayoutObject* layout_object = node->GetLayoutObject();
if (!layout_object)
return;
+ if (!internal::IsExplicitlyRegisteredForTiming(layout_object))
+ return;
+
const ImageResourceContent* cached_image = background_image->CachedImage();
if (!cached_image || !cached_image->IsLoaded())
return;
- auto result = background_images_notified_.insert(
- std::make_pair(layout_object, cached_image));
- if (result.is_new_entry) {
- NotifyImagePaintedInternal(node, *layout_object, *cached_image,
- current_paint_chunk_properties);
- }
-}
-
-FloatRect ImageElementTiming::ComputeIntersectionRect(
- const LocalFrame* frame,
- const LayoutObject& layout_object,
- const PropertyTreeState& current_paint_chunk_properties) {
- // Compute the visible part of the image rect.
- IntRect image_visual_rect = layout_object.FirstFragment().VisualRect();
-
- FloatClipRect visual_rect = FloatClipRect(FloatRect(image_visual_rect));
- GeometryMapper::LocalToAncestorVisualRect(current_paint_chunk_properties,
- frame->View()
- ->GetLayoutView()
- ->FirstFragment()
- .LocalBorderBoxProperties(),
- visual_rect);
- return visual_rect.Rect();
-}
+ auto it = background_image_timestamps_.find(background_image);
+ DCHECK(it != background_image_timestamps_.end());
-bool ImageElementTiming::ShouldReportElement(
- const LocalFrame* frame,
- const AtomicString& element_timing,
- const FloatRect& intersection_rect) const {
- // Create an entry if 'elementtiming' is present or if the fraction of the
- // viewport occupied by the image is above a certain size threshold.
- return !element_timing.IsEmpty() ||
- intersection_rect.Size().Area() > frame->View()
- ->LayoutViewport()
- ->VisibleContentRect()
- .Size()
- .Area() *
- kImageTimingSizeThreshold;
+ ImageInfo& info =
+ images_notified_
+ .insert(std::make_pair(layout_object, cached_image), ImageInfo())
+ .stored_value->value;
+ if (!info.is_painted_) {
+ info.is_painted_ = true;
+ NotifyImagePaintedInternal(layout_object->GetNode(), *layout_object,
+ *cached_image, current_paint_chunk_properties,
+ it->value);
+ }
}
void ImageElementTiming::ReportImagePaintSwapTime(WebWidgetClient::SwapResult,
base::TimeTicks timestamp) {
WindowPerformance* performance =
DOMWindowPerformance::performance(*GetSupplementable());
- if (performance && (performance->HasObserverFor(PerformanceEntry::kElement) ||
- performance->ShouldBufferEntries())) {
+ if (performance) {
for (const auto& element_timing : element_timings_) {
performance->AddElementTiming(
- element_timing->name, element_timing->rect, timestamp,
- element_timing->response_end, element_timing->identifier,
+ ImagePaintString(), element_timing->url, element_timing->rect,
+ timestamp, element_timing->response_end, element_timing->identifier,
element_timing->intrinsic_size, element_timing->id,
element_timing->element);
}
@@ -210,18 +239,14 @@ void ImageElementTiming::ReportImagePaintSwapTime(WebWidgetClient::SwapResult,
element_timings_.clear();
}
-void ImageElementTiming::NotifyWillBeDestroyed(const LayoutObject* image) {
- images_notified_.erase(image);
-}
-
-void ImageElementTiming::NotifyBackgroundImageRemoved(
- const LayoutObject* layout_object,
- const ImageResourceContent* image) {
- background_images_notified_.erase(std::make_pair(layout_object, image));
+void ImageElementTiming::NotifyImageRemoved(const LayoutObject* layout_object,
+ const ImageResourceContent* image) {
+ images_notified_.erase(std::make_pair(layout_object, image));
}
void ImageElementTiming::Trace(blink::Visitor* visitor) {
visitor->Trace(element_timings_);
+ visitor->Trace(background_image_timestamps_);
Supplement<LocalDOMWindow>::Trace(visitor);
}
diff --git a/chromium/third_party/blink/renderer/core/paint/image_element_timing.h b/chromium/third_party/blink/renderer/core/paint/image_element_timing.h
index 72ab6368cec..2ca8e18da27 100644
--- a/chromium/third_party/blink/renderer/core/paint/image_element_timing.h
+++ b/chromium/third_party/blink/renderer/core/paint/image_element_timing.h
@@ -5,8 +5,12 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_IMAGE_ELEMENT_TIMING_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_IMAGE_ELEMENT_TIMING_H_
+#include <utility>
+
#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/frame/local_dom_window.h"
+#include "third_party/blink/renderer/platform/heap/heap_allocator.h"
#include "third_party/blink/renderer/platform/supplementable.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
@@ -16,9 +20,8 @@
namespace blink {
class ImageResourceContent;
-class LayoutImage;
class PropertyTreeState;
-class StyleImage;
+class StyleFetchedImage;
// ImageElementTiming is responsible for tracking the paint timings for <img>
// elements for a given window.
@@ -30,11 +33,20 @@ class CORE_EXPORT ImageElementTiming final
public:
static const char kSupplementName[];
+ // The maximum amount of characters included in Element Timing and Largest
+ // Contentful Paint for inline images.
+ static constexpr const unsigned kInlineImageMaxChars = 100;
+
explicit ImageElementTiming(LocalDOMWindow&);
virtual ~ImageElementTiming() = default;
static ImageElementTiming& From(LocalDOMWindow&);
+ void NotifyImageFinished(const LayoutObject&, const ImageResourceContent*);
+
+ void NotifyBackgroundImageFinished(const StyleFetchedImage*);
+ base::TimeTicks GetBackgroundImageLoadTime(const StyleFetchedImage*);
+
// Called when the LayoutObject has been painted. This method might queue a
// swap promise to compute and report paint timestamps.
void NotifyImagePainted(
@@ -44,14 +56,11 @@ class CORE_EXPORT ImageElementTiming final
void NotifyBackgroundImagePainted(
Node*,
- const StyleImage* background_image,
+ const StyleFetchedImage* background_image,
const PropertyTreeState& current_paint_chunk_properties);
- // Called when the LayoutImage will be destroyed.
- void NotifyWillBeDestroyed(const LayoutObject*);
-
- void NotifyBackgroundImageRemoved(const LayoutObject*,
- const ImageResourceContent* image);
+ void NotifyImageRemoved(const LayoutObject*,
+ const ImageResourceContent* image);
void Trace(blink::Visitor*) override;
@@ -62,17 +71,8 @@ class CORE_EXPORT ImageElementTiming final
Node*,
const LayoutObject&,
const ImageResourceContent& cached_image,
- const PropertyTreeState& current_paint_chunk_properties);
-
- // Computes the intersection rect.
- FloatRect ComputeIntersectionRect(const LocalFrame*,
- const LayoutObject&,
- const PropertyTreeState&);
- // Checks if the element must be reported, given its elementtiming attribute
- // and its intersection rect.
- bool ShouldReportElement(const LocalFrame*,
- const AtomicString& element_timing,
- const FloatRect&) const;
+ const PropertyTreeState& current_paint_chunk_properties,
+ base::TimeTicks load_time);
// Callback for the swap promise. Reports paint timestamps.
void ReportImagePaintSwapTime(WebWidgetClient::SwapResult,
@@ -82,14 +82,14 @@ class CORE_EXPORT ImageElementTiming final
class ElementTimingInfo
: public GarbageCollectedFinalized<ElementTimingInfo> {
public:
- ElementTimingInfo(const AtomicString& name,
+ ElementTimingInfo(const String& url,
const FloatRect& rect,
- const TimeTicks& response_end,
+ const base::TimeTicks& response_end,
const AtomicString& identifier,
const IntSize& intrinsic_size,
const AtomicString& id,
Element* element)
- : name(name),
+ : url(url),
rect(rect),
response_end(response_end),
identifier(identifier),
@@ -100,9 +100,9 @@ class CORE_EXPORT ImageElementTiming final
void Trace(blink::Visitor* visitor) { visitor->Trace(element); }
- AtomicString name;
+ String url;
FloatRect rect;
- TimeTicks response_end;
+ base::TimeTicks response_end;
AtomicString identifier;
IntSize intrinsic_size;
AtomicString id;
@@ -115,12 +115,24 @@ class CORE_EXPORT ImageElementTiming final
// Vector containing the element timing infos that will be reported during the
// next swap promise callback.
HeapVector<Member<ElementTimingInfo>> element_timings_;
- // Hashmap of LayoutObjects for which paint has already been notified.
- WTF::HashSet<const LayoutObject*> images_notified_;
- // Hashmap of pairs of elements, background images whose paint has been
- // observed.
- WTF::HashSet<std::pair<const LayoutObject*, const ImageResourceContent*>>
- background_images_notified_;
+ struct ImageInfo {
+ ImageInfo() {}
+
+ base::TimeTicks load_time_;
+ bool is_painted_ = false;
+ };
+ typedef std::pair<const LayoutObject*, const ImageResourceContent*> RecordId;
+ // Hashmap of pairs of elements, LayoutObjects (for the elements) and
+ // ImageResourceContent (for the src) which correspond to either images or
+ // background images whose paint has been observed. For background images,
+ // only the |is_painted_| bit is used, as the timestamp needs to be tracked by
+ // |background_image_timestamps_|.
+ WTF::HashMap<RecordId, ImageInfo> images_notified_;
+
+ // Hashmap of background images which contain information about the load time
+ // of the background image.
+ HeapHashMap<WeakMember<const StyleFetchedImage>, base::TimeTicks>
+ background_image_timestamps_;
DISALLOW_COPY_AND_ASSIGN(ImageElementTiming);
};
diff --git a/chromium/third_party/blink/renderer/core/paint/image_element_timing_test.cc b/chromium/third_party/blink/renderer/core/paint/image_element_timing_test.cc
index 8dbf7e40f54..bebc1d83a24 100644
--- a/chromium/third_party/blink/renderer/core/paint/image_element_timing_test.cc
+++ b/chromium/third_party/blink/renderer/core/paint/image_element_timing_test.cc
@@ -4,23 +4,45 @@
#include "third_party/blink/renderer/core/paint/image_element_timing.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/core/layout/layout_image.h"
#include "third_party/blink/renderer/core/layout/svg/layout_svg_image.h"
#include "third_party/blink/renderer/core/loader/resource/image_resource_content.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/testing/url_test_helpers.h"
#include "third_party/skia/include/core/SkImage.h"
#include "third_party/skia/include/core/SkSurface.h"
namespace blink {
-class ImageElementTimingTest : public RenderingTest {
+namespace internal {
+
+extern bool IsExplicitlyRegisteredForTiming(const LayoutObject* layout_object);
+
+}
+
+class ImageElementTimingTest : public testing::Test {
protected:
+ void SetUp() override {
+ web_view_helper_.Initialize();
+ frame_test_helpers::LoadFrame(
+ web_view_helper_.GetWebView()->MainFrameImpl(), "about:blank");
+ WebURL base_url_ = url_test_helpers::ToKURL("http://www.test.com/");
+ // Enable compositing on the page.
+ web_view_helper_.GetWebView()
+ ->GetPage()
+ ->GetSettings()
+ .SetAcceleratedCompositingEnabled(true);
+ GetDoc()->View()->SetParentVisible(true);
+ GetDoc()->View()->SetSelfVisible(true);
+ }
+
// Sets an image resource for the LayoutImage with the given |id| and return
// the LayoutImage.
LayoutImage* SetImageResource(const char* id, int width, int height) {
ImageResourceContent* content = CreateImageForTest(width, height);
- auto* layout_image = ToLayoutImage(GetLayoutObjectByElementId(id));
+ auto* layout_image = ToLayoutImage(GetLayoutObjectById(id));
layout_image->ImageResource()->SetImageResource(content);
return layout_image;
}
@@ -28,23 +50,46 @@ class ImageElementTimingTest : public RenderingTest {
// Similar to above but for a LayoutSVGImage.
LayoutSVGImage* SetSVGImageResource(const char* id, int width, int height) {
ImageResourceContent* content = CreateImageForTest(width, height);
- auto* layout_image = ToLayoutSVGImage(GetLayoutObjectByElementId(id));
+ auto* layout_image = ToLayoutSVGImage(GetLayoutObjectById(id));
layout_image->ImageResource()->SetImageResource(content);
return layout_image;
}
- const WTF::HashSet<const LayoutObject*>& GetImagesNotified() {
- return ImageElementTiming::From(*GetDocument().domWindow())
- .images_notified_;
+ bool ImagesNotifiedContains(
+ const std::pair<const LayoutObject*, const ImageResourceContent*>&
+ record_id) {
+ return ImageElementTiming::From(*GetDoc()->domWindow())
+ .images_notified_.Contains(record_id);
}
- const WTF::HashSet<
- std::pair<const LayoutObject*, const ImageResourceContent*>>&
- GetBackgroundImagesNotified() {
- return ImageElementTiming::From(*GetDocument().domWindow())
- .background_images_notified_;
+ unsigned ImagesNotifiedSize() {
+ return ImageElementTiming::From(*GetDoc()->domWindow())
+ .images_notified_.size();
}
+ Document* GetDoc() {
+ return web_view_helper_.GetWebView()
+ ->MainFrameImpl()
+ ->GetFrame()
+ ->GetDocument();
+ }
+
+ LayoutObject* GetLayoutObjectById(const char* id) {
+ return GetDoc()->getElementById(id)->GetLayoutObject();
+ }
+
+ void UpdateAllLifecyclePhases() {
+ web_view_helper_.GetWebView()
+ ->MainFrameImpl()
+ ->GetFrame()
+ ->View()
+ ->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
+ }
+
+ frame_test_helpers::WebViewHelper web_view_helper_;
+ WebURL base_url_;
+
private:
ImageResourceContent* CreateImageForTest(int width, int height) {
sk_sp<SkColorSpace> src_rgb_color_space = SkColorSpace::MakeSRGB();
@@ -59,86 +104,137 @@ class ImageElementTimingTest : public RenderingTest {
}
};
+TEST_F(ImageElementTimingTest, TestIsExplicitlyRegisteredForTiming) {
+ frame_test_helpers::LoadHTMLString(
+ web_view_helper_.GetWebView()->MainFrameImpl(), R"HTML(
+ <img id="missing-attribute" style='width: 100px; height: 100px;'/>
+ <img id="unset-attribute" elementtiming style='width: 100px; height: 100px;'/>
+ <img id="empty-attribute" elementtiming="" style='width: 100px; height: 100px;'/>
+ <img id="valid-attribute" elementtiming="valid-id" style='width: 100px; height: 100px;'/>
+ )HTML",
+ base_url_);
+
+ LayoutObject* without_attribute = GetLayoutObjectById("missing-attribute");
+ bool actual = internal::IsExplicitlyRegisteredForTiming(without_attribute);
+ EXPECT_FALSE(actual) << "Nodes without an 'elementtiming' attribute should "
+ "not be explicitly registered.";
+
+ LayoutObject* with_undefined_attribute =
+ GetLayoutObjectById("unset-attribute");
+ actual = internal::IsExplicitlyRegisteredForTiming(with_undefined_attribute);
+ EXPECT_FALSE(actual) << "Nodes with undefined 'elementtiming' attribute "
+ "should not be explicitly registered.";
+
+ LayoutObject* with_empty_attribute = GetLayoutObjectById("empty-attribute");
+ actual = internal::IsExplicitlyRegisteredForTiming(with_empty_attribute);
+ EXPECT_FALSE(actual) << "Nodes with an empty 'elementtiming' attribute "
+ "should not be explicitly registered.";
+
+ LayoutObject* with_explicit_element_timing =
+ GetLayoutObjectById("valid-attribute");
+ actual =
+ internal::IsExplicitlyRegisteredForTiming(with_explicit_element_timing);
+ EXPECT_TRUE(actual) << "Nodes with a non-empty 'elementtiming' attribute "
+ "should be explicitly registered.";
+}
+
+TEST_F(ImageElementTimingTest, IgnoresUnmarkedElement) {
+ // Tests that, if the 'elementtiming' attribute is missing, the element isn't
+ // considered by ImageElementTiming.
+ frame_test_helpers::LoadHTMLString(
+ web_view_helper_.GetWebView()->MainFrameImpl(), R"HTML(
+ <img id="target" style='width: 100px; height: 100px;'/>
+ )HTML",
+ base_url_);
+ LayoutImage* layout_image = SetImageResource("target", 5, 5);
+ ASSERT_TRUE(layout_image);
+ UpdateAllLifecyclePhases();
+ EXPECT_FALSE(ImagesNotifiedContains(
+ std::make_pair(layout_image, layout_image->CachedImage())));
+}
+
TEST_F(ImageElementTimingTest, ImageInsideSVG) {
- GetDocument().SetBaseURLOverride(KURL("http://test.com"));
- SetBodyInnerHTML(R"HTML(
+ frame_test_helpers::LoadHTMLString(
+ web_view_helper_.GetWebView()->MainFrameImpl(), R"HTML(
<svg mask="url(#mask)">
<mask id="mask">
<foreignObject width="100" height="100">
- <img id="target" style='width: 100px; height: 100px;'/>
+ <img elementtiming="image-inside-svg" id="target" style='width: 100px; height: 100px;'/>
</foreignObject>
</mask>
<rect width="100" height="100" fill="green"/>
</svg>
- )HTML");
+ )HTML",
+ base_url_);
LayoutImage* layout_image = SetImageResource("target", 5, 5);
ASSERT_TRUE(layout_image);
- // Enable compositing and also update document lifecycle.
- EnableCompositing();
+ UpdateAllLifecyclePhases();
// |layout_image| should have had its paint notified to ImageElementTiming.
- EXPECT_TRUE(GetImagesNotified().Contains(layout_image));
+ EXPECT_TRUE(ImagesNotifiedContains(
+ std::make_pair(layout_image, layout_image->CachedImage())));
}
TEST_F(ImageElementTimingTest, ImageRemoved) {
- EnableCompositing();
- GetDocument().SetBaseURLOverride(KURL("http://test.com"));
- SetBodyInnerHTML(R"HTML(
- <img id="target" style='width: 100px; height: 100px;'/>
- )HTML");
+ frame_test_helpers::LoadHTMLString(
+ web_view_helper_.GetWebView()->MainFrameImpl(), R"HTML(
+ <img elementtiming="will-be-removed" id="target" style='width: 100px; height: 100px;'/>
+ )HTML",
+ base_url_);
LayoutImage* layout_image = SetImageResource("target", 5, 5);
ASSERT_TRUE(layout_image);
- UpdateAllLifecyclePhasesForTest();
- EXPECT_TRUE(GetImagesNotified().Contains(layout_image));
+ UpdateAllLifecyclePhases();
+ EXPECT_TRUE(ImagesNotifiedContains(
+ std::make_pair(layout_image, layout_image->CachedImage())));
- GetDocument().getElementById("target")->remove();
+ GetDoc()->getElementById("target")->remove();
// |layout_image| should no longer be part of |images_notified| since it will
// be destroyed.
- EXPECT_TRUE(GetImagesNotified().IsEmpty());
+ EXPECT_EQ(ImagesNotifiedSize(), 0u);
}
TEST_F(ImageElementTimingTest, SVGImageRemoved) {
- EnableCompositing();
- GetDocument().SetBaseURLOverride(KURL("http://test.com"));
- SetBodyInnerHTML(R"HTML(
+ frame_test_helpers::LoadHTMLString(
+ web_view_helper_.GetWebView()->MainFrameImpl(), R"HTML(
<svg>
- <image id="target" style='width: 100px; height: 100px;'/>
+ <image elementtiming="svg-will-be-removed" id="target" style='width: 100px; height: 100px;'/>
</svg>
- )HTML");
+ )HTML",
+ base_url_);
LayoutSVGImage* layout_image = SetSVGImageResource("target", 5, 5);
ASSERT_TRUE(layout_image);
- UpdateAllLifecyclePhasesForTest();
- EXPECT_TRUE(GetImagesNotified().Contains(layout_image));
+ UpdateAllLifecyclePhases();
+ EXPECT_TRUE(ImagesNotifiedContains(std::make_pair(
+ layout_image, layout_image->ImageResource()->CachedImage())));
- GetDocument().getElementById("target")->remove();
+ GetDoc()->getElementById("target")->remove();
// |layout_image| should no longer be part of |images_notified| since it will
// be destroyed.
- EXPECT_TRUE(GetImagesNotified().IsEmpty());
+ EXPECT_EQ(ImagesNotifiedSize(), 0u);
}
TEST_F(ImageElementTimingTest, BackgroundImageRemoved) {
- EnableCompositing();
- GetDocument().SetBaseURLOverride(KURL("http://test.com"));
- SetBodyInnerHTML(R"HTML(
+ frame_test_helpers::LoadHTMLString(
+ web_view_helper_.GetWebView()->MainFrameImpl(), R"HTML(
<style>
#target {
+ width: 100px;
+ height: 100px;
background: url(data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==);
}
</style>
- <div id="target">/div>
- )HTML");
- LayoutObject* object = GetLayoutObjectByElementId("target");
- ImageResourceContent* content = object->MutableStyle()
- ->AccessBackgroundLayers()
- .GetImage()
- ->CachedImage();
- UpdateAllLifecyclePhasesForTest();
- EXPECT_EQ(GetBackgroundImagesNotified().size(), 1u);
- EXPECT_TRUE(
- GetBackgroundImagesNotified().Contains(std::make_pair(object, content)));
-
- GetDocument().getElementById("target")->remove();
- EXPECT_TRUE(GetBackgroundImagesNotified().IsEmpty());
+ <div elementtiming="time-my-background-image" id="target"></div>
+ )HTML",
+ base_url_);
+ LayoutObject* object = GetLayoutObjectById("target");
+ ImageResourceContent* content =
+ object->Style()->BackgroundLayers().GetImage()->CachedImage();
+ UpdateAllLifecyclePhases();
+ EXPECT_EQ(ImagesNotifiedSize(), 1u);
+ EXPECT_TRUE(ImagesNotifiedContains(std::make_pair(object, content)));
+
+ GetDoc()->getElementById("target")->remove();
+ EXPECT_EQ(ImagesNotifiedSize(), 0u);
}
} // namespace blink
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 bc11a911409..caef223f0cf 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
@@ -5,19 +5,13 @@
#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_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/image_element_timing.h"
+#include "third_party/blink/renderer/core/paint/largest_contentful_paint_calculator.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/image.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/traced_value.h"
@@ -47,6 +41,7 @@ uint64_t DownScaleIfIntrinsicSizeIsSmaller(
// |visual_size| * min(|displayed_image_size|, |intrinsic_image_size|) /
// |displayed_image_size|
if (intrinsic_image_size < displayed_image_size) {
+ DCHECK_GT(displayed_image_size, 0u);
return static_cast<double>(visual_size) * intrinsic_image_size /
displayed_image_size;
}
@@ -55,25 +50,23 @@ uint64_t DownScaleIfIntrinsicSizeIsSmaller(
} // namespace
-// Set a big enough limit for the number of nodes to ensure memory usage is
-// capped. Exceeding such limit will make the detactor stops recording entries.
-constexpr size_t kImageNodeNumberLimit = 5000;
-
static bool LargeImageFirst(const base::WeakPtr<ImageRecord>& a,
const base::WeakPtr<ImageRecord>& b) {
DCHECK(a);
DCHECK(b);
if (a->first_size != b->first_size)
return a->first_size > b->first_size;
- // This make sure that two different nodes with the same |first_size| wouldn't
- // be merged in the set.
- if (a->node_id != b->node_id)
- return a->node_id > b->node_id;
- return a->record_id > b->record_id;
+ // This make sure that two different |ImageRecord|s with the same |first_size|
+ // wouldn't be merged in the |size_ordered_set_|.
+ return a->insertion_index < b->insertion_index;
}
-ImagePaintTimingDetector::ImagePaintTimingDetector(LocalFrameView* frame_view)
- : frame_view_(frame_view) {}
+ImagePaintTimingDetector::ImagePaintTimingDetector(
+ LocalFrameView* frame_view,
+ PaintTimingCallbackManager* callback_manager)
+ : records_manager_(frame_view),
+ frame_view_(frame_view),
+ callback_manager_(callback_manager) {}
void ImagePaintTimingDetector::PopulateTraceValue(
TracedValue& value,
@@ -93,6 +86,8 @@ void ImagePaintTimingDetector::PopulateTraceValue(
void ImagePaintTimingDetector::ReportCandidateToTrace(
ImageRecord& largest_image_record) {
+ if (!PaintTimingDetector::IsTracing())
+ return;
DCHECK(!largest_image_record.paint_time.is_null());
auto value = std::make_unique<TracedValue>();
PopulateTraceValue(*value, largest_image_record);
@@ -103,6 +98,8 @@ void ImagePaintTimingDetector::ReportCandidateToTrace(
}
void ImagePaintTimingDetector::ReportNoCandidateToTrace() {
+ if (!PaintTimingDetector::IsTracing())
+ return;
auto value = std::make_unique<TracedValue>();
value->SetInteger("candidateIndex", ++count_candidates_);
value->SetBoolean("isMainFrame", frame_view_->GetFrame().IsMainFrame());
@@ -113,7 +110,7 @@ void ImagePaintTimingDetector::ReportNoCandidateToTrace() {
ToTraceValue(&frame_view_->GetFrame()));
}
-void ImagePaintTimingDetector::UpdateCandidate() {
+ImageRecord* ImagePaintTimingDetector::UpdateCandidate() {
ImageRecord* largest_image_record =
records_manager_.FindLargestPaintCandidate();
const base::TimeTicks time = largest_image_record
@@ -121,28 +118,28 @@ void ImagePaintTimingDetector::UpdateCandidate() {
: base::TimeTicks();
const uint64_t size =
largest_image_record ? largest_image_record->first_size : 0;
- bool changed =
- frame_view_->GetPaintTimingDetector().NotifyIfChangedLargestImagePaint(
- time, size);
- if (!changed)
- return;
- if (largest_image_record && !largest_image_record->paint_time.is_null()) {
- // If an image has paint time, it must have been loaded.
- DCHECK(largest_image_record->loaded);
- ReportCandidateToTrace(*largest_image_record);
- } else {
- ReportNoCandidateToTrace();
+ PaintTimingDetector& detector = frame_view_->GetPaintTimingDetector();
+ // Two different candidates are rare to have the same time and size.
+ // So when they are unchanged, the candidate is considered unchanged.
+ bool changed = detector.NotifyIfChangedLargestImagePaint(time, size);
+ if (changed) {
+ if (!time.is_null()) {
+ DCHECK(largest_image_record->loaded);
+ ReportCandidateToTrace(*largest_image_record);
+ } else {
+ ReportNoCandidateToTrace();
+ }
}
+ return largest_image_record;
}
void ImagePaintTimingDetector::OnPaintFinished() {
frame_index_++;
if (need_update_timing_at_frame_end_) {
need_update_timing_at_frame_end_ = false;
- UpdateCandidate();
+ frame_view_->GetPaintTimingDetector()
+ .UpdateLargestContentfulPaintCandidate();
}
- if (!records_manager_.NeedMeausuringPaintTime())
- return;
if (!records_manager_.HasUnregisteredRecordsInQueued(
last_registered_frame_index_))
@@ -152,232 +149,159 @@ void ImagePaintTimingDetector::OnPaintFinished() {
RegisterNotifySwapTime();
}
-void ImagePaintTimingDetector::NotifyNodeRemoved(DOMNodeId node_id) {
+void ImagePaintTimingDetector::LayoutObjectWillBeDestroyed(
+ const LayoutObject& object) {
if (!is_recording_)
return;
- // Todo: check whether it is visible background image.
- if (!records_manager_.IsRecordedVisibleNode(node_id))
- return;
- records_manager_.SetNodeDetached(node_id);
- need_update_timing_at_frame_end_ = true;
+
+ // The visible record removal has been handled by
+ // |NotifyImageRemoved|.
+ records_manager_.RemoveInvisibleRecordIfNeeded(object);
}
-void ImagePaintTimingDetector::NotifyBackgroundImageRemoved(
- DOMNodeId node_id,
+void ImagePaintTimingDetector::NotifyImageRemoved(
+ const LayoutObject& object,
const ImageResourceContent* cached_image) {
if (!is_recording_)
return;
- BackgroundImageId background_image_id = std::make_pair(node_id, cached_image);
- if (!records_manager_.IsRecordedVisibleNode(background_image_id))
+ RecordId record_id = std::make_pair(&object, cached_image);
+ records_manager_.RemoveImageFinishedRecord(record_id);
+ if (!records_manager_.IsRecordedVisibleImage(record_id))
return;
- records_manager_.SetNodeDetached(background_image_id.first);
+ records_manager_.RemoveVisibleRecord(record_id);
+ need_update_timing_at_frame_end_ = true;
}
void ImagePaintTimingDetector::RegisterNotifySwapTime() {
- auto callback = CrossThreadBindOnce(&ImagePaintTimingDetector::ReportSwapTime,
- WrapCrossThreadWeakPersistent(this),
- last_registered_frame_index_);
- if (notify_swap_time_override_for_testing_) {
- // Run is not to run the |callback|, but to queue it.
- notify_swap_time_override_for_testing_.Run(
- ConvertToBaseOnceCallback(std::move(callback)));
- num_pending_swap_callbacks_++;
- return;
- }
- // ReportSwapTime on layerTreeView will queue a swap-promise, the callback is
- // called when the swap for current render frame completes or fails to happen.
- LocalFrame& frame = frame_view_->GetFrame();
- if (!frame.GetPage())
- return;
-
- frame.GetPage()->GetChromeClient().NotifySwapTime(frame, std::move(callback));
+ auto callback = WTF::Bind(&ImagePaintTimingDetector::ReportSwapTime,
+ WrapCrossThreadWeakPersistent(this),
+ last_registered_frame_index_);
+ callback_manager_->RegisterCallback(std::move(callback));
num_pending_swap_callbacks_++;
}
void ImagePaintTimingDetector::ReportSwapTime(
unsigned last_queued_frame_index,
- WebWidgetClient::SwapResult result,
base::TimeTicks timestamp) {
+ if (!is_recording_)
+ return;
// The callback is safe from race-condition only when running on main-thread.
DCHECK(ThreadState::Current()->IsMainThread());
- records_manager_.AssignPaintTimeToRegisteredQueuedNodes(
+ records_manager_.AssignPaintTimeToRegisteredQueuedRecords(
timestamp, last_queued_frame_index);
- UpdateCandidate();
num_pending_swap_callbacks_--;
DCHECK_GE(num_pending_swap_callbacks_, 0);
}
-void ImageRecordsManager::AssignPaintTimeToRegisteredQueuedNodes(
+void ImageRecordsManager::AssignPaintTimeToRegisteredQueuedRecords(
const base::TimeTicks& timestamp,
unsigned last_queued_frame_index) {
- DCHECK(!images_queued_for_paint_time_.empty());
- while (!images_queued_for_paint_time_.empty()) {
+ // TODO(crbug.com/971419): should guarantee the queue not empty.
+ while (!images_queued_for_paint_time_.IsEmpty()) {
base::WeakPtr<ImageRecord>& record = images_queued_for_paint_time_.front();
+ if (!record) {
+ images_queued_for_paint_time_.pop_front();
+ continue;
+ }
if (record->frame_index > last_queued_frame_index)
break;
record->paint_time = timestamp;
- images_queued_for_paint_time_.pop();
+ images_queued_for_paint_time_.pop_front();
}
}
-void ImagePaintTimingDetector::RecordBackgroundImage(
+void ImagePaintTimingDetector::RecordImage(
const LayoutObject& object,
const IntSize& intrinsic_size,
const ImageResourceContent& cached_image,
- const PropertyTreeState& current_paint_chunk_properties) {
+ const PropertyTreeState& current_paint_chunk_properties,
+ const StyleFetchedImage* style_image) {
Node* node = object.GetNode();
if (!node)
return;
- DOMNodeId node_id = DOMNodeIds::IdForNode(node);
- DCHECK_NE(node_id, kInvalidDOMNodeId);
- if (records_manager_.IsRecordedInvisibleNode(node_id))
+ if (records_manager_.IsRecordedInvisibleImage(object))
return;
- records_manager_.SetNodeReattachedIfNeeded(node_id);
- BackgroundImageId background_image_id =
- std::make_pair(node_id, &cached_image);
- bool is_recored_visible_node =
- records_manager_.IsRecordedVisibleNode(background_image_id);
- if (is_recored_visible_node &&
- !records_manager_.WasVisibleNodeLoaded(background_image_id) &&
+ RecordId record_id = std::make_pair(&object, &cached_image);
+ bool is_recored_visible_image =
+ records_manager_.IsRecordedVisibleImage(record_id);
+ if (is_recored_visible_image &&
+ !records_manager_.IsVisibleImageLoaded(record_id) &&
cached_image.IsLoaded()) {
- records_manager_.OnImageLoaded(background_image_id, frame_index_);
+ records_manager_.OnImageLoaded(record_id, frame_index_, style_image);
need_update_timing_at_frame_end_ = true;
+ if (base::Optional<PaintTimingVisualizer>& visualizer =
+ frame_view_->GetPaintTimingDetector().Visualizer()) {
+ FloatRect mapped_visual_rect =
+ frame_view_->GetPaintTimingDetector().CalculateVisualRect(
+ object.FragmentsVisualRectBoundingBox(),
+ current_paint_chunk_properties);
+ visualizer->DumpImageDebuggingRect(object, mapped_visual_rect,
+ cached_image);
+ }
return;
}
- if (is_recored_visible_node || !is_recording_)
+ if (is_recored_visible_image || !is_recording_)
return;
IntRect visual_rect = object.FragmentsVisualRectBoundingBox();
// Before the image resource starts loading, <img> has no size info. We wait
// until the size is known.
if (visual_rect.IsEmpty())
return;
- uint64_t rect_size =
- frame_view_->GetPaintTimingDetector()
- .CalculateVisualRect(visual_rect, current_paint_chunk_properties)
- .Size()
- .Area();
+ FloatRect mapped_visual_rect =
+ frame_view_->GetPaintTimingDetector().CalculateVisualRect(
+ visual_rect, current_paint_chunk_properties);
+ if (base::Optional<PaintTimingVisualizer>& visualizer =
+ frame_view_->GetPaintTimingDetector().Visualizer()) {
+ visualizer->DumpImageDebuggingRect(object, mapped_visual_rect,
+ cached_image);
+ }
+ uint64_t rect_size = mapped_visual_rect.Size().Area();
+ // Transform visual rect to window before calling downscale.
+ WebFloatRect float_visual_rect = FloatRect(visual_rect);
+ frame_view_->GetPaintTimingDetector().ConvertViewportToWindow(
+ &float_visual_rect);
rect_size = DownScaleIfIntrinsicSizeIsSmaller(
rect_size, intrinsic_size.Area(),
- (visual_rect.Width() * visual_rect.Height()));
-
+ float_visual_rect.width * float_visual_rect.height);
if (rect_size == 0) {
- // Each invisible background image is tracked by its node id. In other
- // words, when a node is deemed as invisible, all of the background images
- // are deemed as invisible.
- records_manager_.RecordInvisibleNode(node_id);
+ records_manager_.RecordInvisible(object);
} else {
- records_manager_.RecordVisibleNode(background_image_id, rect_size);
+ records_manager_.RecordVisible(record_id, rect_size);
if (cached_image.IsLoaded()) {
- records_manager_.OnImageLoaded(background_image_id, frame_index_);
+ records_manager_.OnImageLoaded(record_id, frame_index_, style_image);
need_update_timing_at_frame_end_ = true;
}
}
-
- if (records_manager_.RecordedTooManyNodes())
- HandleTooManyNodes();
}
-void ImagePaintTimingDetector::RecordImage(
+void ImagePaintTimingDetector::NotifyImageFinished(
const LayoutObject& object,
- const IntSize& intrinsic_size,
- const ImageResourceContent& cached_image,
- const PropertyTreeState& current_paint_chunk_properties) {
- // TODO(crbug.com/933479): Use LayoutObject::GeneratingNode() to include
- // anonymous objects' rect.
- Node* node = object.GetNode();
- if (!node)
- return;
-
- DOMNodeId node_id = DOMNodeIds::IdForNode(node);
- DCHECK_NE(node_id, kInvalidDOMNodeId);
-
- if (records_manager_.IsRecordedInvisibleNode(node_id))
- return;
+ const ImageResourceContent* cached_image) {
+ RecordId record_id = std::make_pair(&object, cached_image);
+ records_manager_.NotifyImageFinished(record_id);
+}
- records_manager_.SetNodeReattachedIfNeeded(node_id);
+ImageRecordsManager::ImageRecordsManager(LocalFrameView* frame_view)
+ : size_ordered_set_(&LargeImageFirst), frame_view_(frame_view) {}
- bool is_loaded = cached_image.IsLoaded();
- bool is_recored_visible_node =
- records_manager_.IsRecordedVisibleNode(node_id);
- if (is_recored_visible_node &&
- !records_manager_.WasVisibleNodeLoaded(node_id) && is_loaded) {
- records_manager_.OnImageLoaded(node_id, frame_index_);
- need_update_timing_at_frame_end_ = true;
- return;
- }
-
- if (is_recored_visible_node || !is_recording_)
- return;
- IntRect visual_rect = object.FragmentsVisualRectBoundingBox();
- // Before the image resource starts loading, <img> has no size info. We wait
- // until the size is known.
- if (visual_rect.IsEmpty())
- return;
- uint64_t rect_size =
- frame_view_->GetPaintTimingDetector()
- .CalculateVisualRect(visual_rect, current_paint_chunk_properties)
- .Size()
- .Area();
- rect_size = DownScaleIfIntrinsicSizeIsSmaller(
- rect_size, intrinsic_size.Area(),
- visual_rect.Width() * visual_rect.Height());
- DVLOG(2) << "Node id (" << node_id << "): size=" << rect_size
- << ", type=" << object.DebugName();
- if (rect_size == 0) {
- records_manager_.RecordInvisibleNode(node_id);
+void ImageRecordsManager::OnImageLoaded(const RecordId& record_id,
+ unsigned current_frame_index,
+ const StyleFetchedImage* style_image) {
+ base::WeakPtr<ImageRecord> record = FindVisibleRecord(record_id);
+ DCHECK(record);
+ if (!style_image) {
+ record->load_time = image_finished_times_.at(record_id);
+ DCHECK(!record->load_time.is_null());
} else {
- records_manager_.RecordVisibleNode(node_id, rect_size);
- if (is_loaded) {
- records_manager_.OnImageLoaded(node_id, frame_index_);
- need_update_timing_at_frame_end_ = true;
+ Document* document = frame_view_->GetFrame().GetDocument();
+ if (document && document->domWindow() &&
+ RuntimeEnabledFeatures::ElementTimingEnabled(document)) {
+ record->load_time = ImageElementTiming::From(*document->domWindow())
+ .GetBackgroundImageLoadTime(style_image);
}
}
-
- if (records_manager_.RecordedTooManyNodes())
- HandleTooManyNodes();
-}
-
-void ImagePaintTimingDetector::HandleTooManyNodes() {
- TRACE_EVENT_INSTANT0("loading", "ImagePaintTimingDetector::OverNodeLimit",
- TRACE_EVENT_SCOPE_THREAD);
- StopRecordEntries();
-}
-
-ImageRecordsManager::ImageRecordsManager()
- : size_ordered_set_(&LargeImageFirst) {}
-
-void ImageRecordsManager::SetNodeReattachedIfNeeded(
- const DOMNodeId& visible_node_id) {
- if (!detached_ids_.Contains(visible_node_id))
- return;
- detached_ids_.erase(visible_node_id);
-}
-
-base::WeakPtr<ImageRecord> ImageRecordsManager::FindVisibleRecord(
- const BackgroundImageId& background_image_id) const {
- DCHECK(visible_background_image_map_.Contains(background_image_id));
- return visible_background_image_map_.find(background_image_id)
- ->value->AsWeakPtr();
-}
-
-base::WeakPtr<ImageRecord> ImageRecordsManager::FindVisibleRecord(
- const DOMNodeId& node_id) const {
- DCHECK(visible_node_map_.Contains(node_id));
- return visible_node_map_.find(node_id)->value->AsWeakPtr();
-}
-
-void ImageRecordsManager::OnImageLoaded(const DOMNodeId& node_id,
- unsigned current_frame_index) {
- base::WeakPtr<ImageRecord> record = FindVisibleRecord(node_id);
- OnImageLoadedInternal(record, current_frame_index);
-}
-
-void ImageRecordsManager::OnImageLoaded(
- const BackgroundImageId& background_image_id,
- unsigned current_frame_index) {
- base::WeakPtr<ImageRecord> record = FindVisibleRecord(background_image_id);
OnImageLoadedInternal(record, current_frame_index);
}
@@ -388,101 +312,35 @@ void ImageRecordsManager::OnImageLoadedInternal(
QueueToMeasurePaintTime(record, current_frame_index);
}
-void ImageRecordsManager::SetLoaded(base::WeakPtr<ImageRecord>& record) {
- record->loaded = true;
-}
-
-bool ImageRecordsManager::RecordedTooManyNodes() const {
- return visible_node_map_.size() + visible_background_image_map_.size() +
- invisible_node_ids_.size() >
- kImageNodeNumberLimit;
-}
-
-void ImageRecordsManager::SetNodeDetached(const DOMNodeId& visible_node_id) {
- detached_ids_.insert(visible_node_id);
-}
-
-bool ImageRecordsManager::HasUnregisteredRecordsInQueued(
- unsigned last_registered_frame_index) {
- DCHECK(last_registered_frame_index <= LastQueuedFrameIndex());
- return last_registered_frame_index < LastQueuedFrameIndex();
-}
-
-bool ImageRecordsManager::WasVisibleNodeLoaded(const DOMNodeId& node_id) const {
- DCHECK(visible_node_map_.Contains(node_id));
- return visible_node_map_.at(node_id)->loaded;
-}
-
-bool ImageRecordsManager::WasVisibleNodeLoaded(
- const BackgroundImageId& background_image_id) const {
- DCHECK(visible_background_image_map_.Contains(background_image_id));
- return visible_background_image_map_.at(background_image_id)->loaded;
-}
-
-void ImageRecordsManager::QueueToMeasurePaintTime(
- base::WeakPtr<ImageRecord>& record,
- unsigned current_frame_index) {
- images_queued_for_paint_time_.push(record);
- record->frame_index = current_frame_index;
-}
-
-void ImageRecordsManager::RecordInvisibleNode(const DOMNodeId& node_id) {
- DCHECK(!RecordedTooManyNodes());
- invisible_node_ids_.insert(node_id);
-}
-
-void ImageRecordsManager::RecordVisibleNode(const DOMNodeId& node_id,
- const uint64_t& visual_size) {
+void ImageRecordsManager::RecordVisible(const RecordId& record_id,
+ const uint64_t& visual_size) {
std::unique_ptr<ImageRecord> record =
- CreateImageRecord(node_id, nullptr, visual_size);
+ CreateImageRecord(*record_id.first, record_id.second, visual_size);
size_ordered_set_.insert(record->AsWeakPtr());
- visible_node_map_.insert(node_id, std::move(record));
-}
-
-void ImageRecordsManager::RecordVisibleNode(
- const BackgroundImageId& background_image_id,
- const uint64_t& visual_size) {
- std::unique_ptr<ImageRecord> record = CreateImageRecord(
- background_image_id.first, background_image_id.second, visual_size);
- size_ordered_set_.insert(record->AsWeakPtr());
- visible_background_image_map_.insert(background_image_id, std::move(record));
+ visible_images_.insert(record_id, std::move(record));
}
std::unique_ptr<ImageRecord> ImageRecordsManager::CreateImageRecord(
- const DOMNodeId& node_id,
+ const LayoutObject& object,
const ImageResourceContent* cached_image,
const uint64_t& visual_size) {
- DCHECK(!RecordedTooManyNodes());
DCHECK_GT(visual_size, 0u);
- std::unique_ptr<ImageRecord> record = std::make_unique<ImageRecord>();
- record->record_id = max_record_id_++;
- record->node_id = node_id;
- record->first_size = visual_size;
- record->cached_image = cached_image;
+ Node* node = object.GetNode();
+ DOMNodeId node_id = DOMNodeIds::IdForNode(node);
+ std::unique_ptr<ImageRecord> record =
+ std::make_unique<ImageRecord>(node_id, cached_image, visual_size);
return record;
}
-void ImagePaintTimingDetector::StopRecordEntries() {
- is_recording_ = false;
-}
-
-bool ImagePaintTimingDetector::FinishedReportingImages() const {
- return !is_recording_ && num_pending_swap_callbacks_ == 0;
-}
-
ImageRecord* ImageRecordsManager::FindLargestPaintCandidate() const {
- DCHECK_EQ(visible_node_map_.size() + visible_background_image_map_.size(),
- size_ordered_set_.size());
- for (auto it = size_ordered_set_.begin(); it != size_ordered_set_.end();
- ++it) {
- if (detached_ids_.Contains((*it)->node_id))
- continue;
- return (*it).get();
- }
- return nullptr;
+ DCHECK_EQ(visible_images_.size(), size_ordered_set_.size());
+ if (size_ordered_set_.size() == 0)
+ return nullptr;
+ return size_ordered_set_.begin()->get();
}
void ImagePaintTimingDetector::Trace(blink::Visitor* visitor) {
visitor->Trace(frame_view_);
+ visitor->Trace(callback_manager_);
}
} // namespace blink
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 ae21edd0535..7ad3119fb8f 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
@@ -9,9 +9,12 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_IMAGE_PAINT_TIMING_DETECTOR_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_IMAGE_PAINT_TIMING_DETECTOR_H_
+#include "base/memory/weak_ptr.h"
#include "third_party/blink/public/web/web_widget_client.h"
#include "third_party/blink/renderer/core/dom/dom_node_ids.h"
-#include "third_party/blink/renderer/platform/cross_thread_functional.h"
+#include "third_party/blink/renderer/core/loader/resource/image_resource_content.h"
+#include "third_party/blink/renderer/core/paint/paint_timing_detector.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
@@ -22,24 +25,36 @@ class LocalFrameView;
class PropertyTreeState;
class TracedValue;
class Image;
-class ImageResourceContent;
// TODO(crbug/960502): we should limit the access of these properties.
class ImageRecord : public base::SupportsWeakPtr<ImageRecord> {
public:
- unsigned record_id;
+ ImageRecord(DOMNodeId new_node_id,
+ const ImageResourceContent* new_cached_image,
+ uint64_t new_first_size)
+ : node_id(new_node_id),
+ cached_image(new_cached_image),
+ first_size(new_first_size) {
+ static unsigned next_insertion_index_ = 1;
+ insertion_index = next_insertion_index_++;
+ }
+
+ ImageRecord() {}
+
DOMNodeId node_id = kInvalidDOMNodeId;
+ WeakPersistent<const ImageResourceContent> cached_image;
// Mind that |first_size| has to be assigned before pusing to
// |size_ordered_set_| since it's the sorting key.
uint64_t first_size = 0;
unsigned frame_index = 0;
+ unsigned insertion_index;
// The time of the first paint after fully loaded. 0 means not painted yet.
base::TimeTicks paint_time = base::TimeTicks();
- WeakPersistent<const ImageResourceContent> cached_image;
+ base::TimeTicks load_time = base::TimeTicks();
bool loaded = false;
};
-typedef std::pair<DOMNodeId, const ImageResourceContent*> BackgroundImageId;
+typedef std::pair<const LayoutObject*, const ImageResourceContent*> RecordId;
// |ImageRecordsManager| is the manager of all of the images that Largest Image
// Paint cares about. Note that an image does not necessarily correspond to a
@@ -55,80 +70,116 @@ class CORE_EXPORT ImageRecordsManager {
std::set<base::WeakPtr<ImageRecord>, NodesQueueComparator>;
public:
- ImageRecordsManager();
+ explicit ImageRecordsManager(LocalFrameView*);
ImageRecord* FindLargestPaintCandidate() const;
- bool AreAllVisibleNodesDetached() const;
- void SetNodeDetached(const DOMNodeId& visible_node_id);
- void SetNodeReattachedIfNeeded(const DOMNodeId& visible_node_id);
+ inline void RemoveInvisibleRecordIfNeeded(const LayoutObject& object) {
+ invisible_images_.erase(&object);
+ }
- void RecordInvisibleNode(const DOMNodeId&);
- void RecordVisibleNode(const DOMNodeId&, const uint64_t& visual_size);
- void RecordVisibleNode(const BackgroundImageId& background_image_id,
- const uint64_t& visual_size);
- size_t CountVisibleNodes() const { return visible_node_map_.size(); }
- size_t CountInvisibleNodes() const { return invisible_node_ids_.size(); }
- bool IsRecordedVisibleNode(const DOMNodeId& node_id) const {
- return visible_node_map_.Contains(node_id);
+ inline void RemoveImageFinishedRecord(const RecordId& record_id) {
+ image_finished_times_.erase(record_id);
}
- bool IsRecordedVisibleNode(
- const BackgroundImageId& background_image_id) const {
- return visible_background_image_map_.Contains(background_image_id);
+
+ inline void RemoveVisibleRecord(const RecordId& record_id) {
+ base::WeakPtr<ImageRecord> record =
+ visible_images_.find(record_id)->value->AsWeakPtr();
+ size_ordered_set_.erase(record);
+ visible_images_.erase(record_id);
+ // Leave out |images_queued_for_paint_time_| intentionally because the null
+ // record will be removed in |AssignPaintTimeToRegisteredQueuedRecords|.
}
- bool IsRecordedInvisibleNode(const DOMNodeId& node_id) const {
- return invisible_node_ids_.Contains(node_id);
+
+ inline void RecordInvisible(const LayoutObject& object) {
+ invisible_images_.insert(&object);
+ }
+ void RecordVisible(const RecordId& record_id, const uint64_t& visual_size);
+ bool IsRecordedVisibleImage(const RecordId& record_id) const {
+ return visible_images_.Contains(record_id);
+ }
+ bool IsRecordedInvisibleImage(const LayoutObject& object) const {
+ return invisible_images_.Contains(&object);
}
- bool RecordedTooManyNodes() const;
+ void NotifyImageFinished(const RecordId& record_id) {
+ // TODO(npm): Ideally NotifyImageFinished() would only be called when the
+ // record has not yet been inserted in |image_finished_times_| but that's
+ // not currently the case. If we plumb some information from
+ // ImageResourceContent we may be able to ensure that this call does not
+ // require the Contains() check, which would save time.
+ if (!image_finished_times_.Contains(record_id))
+ image_finished_times_.insert(record_id, base::TimeTicks::Now());
+ }
- bool WasVisibleNodeLoaded(const DOMNodeId&) const;
- bool WasVisibleNodeLoaded(const BackgroundImageId& background_image_id) const;
- void OnImageLoaded(const DOMNodeId&, unsigned current_frame_index);
- void OnImageLoaded(const BackgroundImageId&, unsigned current_frame_index);
+ inline bool IsVisibleImageLoaded(const RecordId& record_id) const {
+ DCHECK(visible_images_.Contains(record_id));
+ return visible_images_.at(record_id)->loaded;
+ }
+ void OnImageLoaded(const RecordId&,
+ unsigned current_frame_index,
+ const StyleFetchedImage*);
void OnImageLoadedInternal(base::WeakPtr<ImageRecord>&,
unsigned current_frame_index);
- bool NeedMeausuringPaintTime() const {
- return !images_queued_for_paint_time_.empty();
+ inline bool NeedMeausuringPaintTime() const {
+ return !images_queued_for_paint_time_.IsEmpty();
}
// Compare the last frame index in queue with the last frame index that has
// registered for assigning paint time.
- bool HasUnregisteredRecordsInQueued(unsigned last_registered_frame_index);
- void AssignPaintTimeToRegisteredQueuedNodes(const base::TimeTicks&,
- unsigned last_queued_frame_index);
- unsigned LastQueuedFrameIndex() const {
+ inline bool HasUnregisteredRecordsInQueued(
+ unsigned last_registered_frame_index) {
+ while (!images_queued_for_paint_time_.IsEmpty() &&
+ !images_queued_for_paint_time_.back()) {
+ images_queued_for_paint_time_.pop_back();
+ }
+ if (images_queued_for_paint_time_.IsEmpty())
+ return false;
+ DCHECK(last_registered_frame_index <= LastQueuedFrameIndex());
+ return last_registered_frame_index < LastQueuedFrameIndex();
+ }
+ void AssignPaintTimeToRegisteredQueuedRecords(
+ const base::TimeTicks&,
+ unsigned last_queued_frame_index);
+ inline unsigned LastQueuedFrameIndex() const {
+ DCHECK(images_queued_for_paint_time_.back());
return images_queued_for_paint_time_.back()->frame_index;
}
private:
// Find the image record of an visible image.
- base::WeakPtr<ImageRecord> FindVisibleRecord(const DOMNodeId&) const;
- base::WeakPtr<ImageRecord> FindVisibleRecord(
- const BackgroundImageId& background_image_id) const;
+ inline base::WeakPtr<ImageRecord> FindVisibleRecord(
+ const RecordId& record_id) const {
+ DCHECK(visible_images_.Contains(record_id));
+ return visible_images_.find(record_id)->value->AsWeakPtr();
+ }
std::unique_ptr<ImageRecord> CreateImageRecord(
- const DOMNodeId&,
+ const LayoutObject& object,
const ImageResourceContent* cached_image,
const uint64_t& visual_size);
- void QueueToMeasurePaintTime(base::WeakPtr<ImageRecord>&,
- unsigned current_frame_index);
- void SetLoaded(base::WeakPtr<ImageRecord>&);
-
- unsigned max_record_id_ = 0;
- // We will never destroy the pointers within |visible_node_map_|. Once created
- // they will exist for the whole life cycle of |visible_node_map_|.
- HashMap<DOMNodeId, std::unique_ptr<ImageRecord>> visible_node_map_;
- HashMap<BackgroundImageId, std::unique_ptr<ImageRecord>>
- visible_background_image_map_;
- HashSet<DOMNodeId> invisible_node_ids_;
- // Use |DOMNodeId| instead of |ImageRecord|* for the efficiency of inserting
- // and erasing.
- HashSet<DOMNodeId> detached_ids_;
+ inline void QueueToMeasurePaintTime(base::WeakPtr<ImageRecord>& record,
+ unsigned current_frame_index) {
+ images_queued_for_paint_time_.push_back(record);
+ record->frame_index = current_frame_index;
+ }
+ inline void SetLoaded(base::WeakPtr<ImageRecord>& record) {
+ record->loaded = true;
+ }
+
+ HashMap<RecordId, std::unique_ptr<ImageRecord>> visible_images_;
+ HashSet<const LayoutObject*> invisible_images_;
+
// This stores the image records, which are ordered by size.
ImageRecordSet size_ordered_set_;
// |ImageRecord|s waiting for paint time are stored in this queue
// until they get a swap time.
- std::queue<base::WeakPtr<ImageRecord>> images_queued_for_paint_time_;
+ Deque<base::WeakPtr<ImageRecord>> images_queued_for_paint_time_;
+ // Map containing timestamps of when LayoutObject::ImageNotifyFinished is
+ // first called.
+ HashMap<RecordId, base::TimeTicks> image_finished_times_;
+ // ImageRecordsManager is always owned by ImagePaintTimingDetector, which
+ // contains the LocalFrameView as a Member.
+ UntracedMember<LocalFrameView> frame_view_;
DISALLOW_COPY_AND_ASSIGN(ImageRecordsManager);
};
@@ -158,47 +209,50 @@ class CORE_EXPORT ImagePaintTimingDetector final
friend class ImagePaintTimingDetectorTest;
public:
- ImagePaintTimingDetector(LocalFrameView*);
+ ImagePaintTimingDetector(LocalFrameView*, PaintTimingCallbackManager*);
+ // Record an image paint. This method covers both img and background image. In
+ // the case of a normal img, the last parameter will be nullptr. This
+ // parameter is needed only for the purposes of plumbing the correct loadTime
+ // value to the ImageRecord.
void RecordImage(const LayoutObject&,
const IntSize& intrinsic_size,
const ImageResourceContent&,
- const PropertyTreeState& current_paint_chunk_properties);
- void RecordBackgroundImage(
- const LayoutObject&,
- const IntSize& intrinsic_size,
- const ImageResourceContent& cached_image,
- const PropertyTreeState& current_paint_chunk_properties);
+ const PropertyTreeState& current_paint_chunk_properties,
+ const StyleFetchedImage*);
+ void NotifyImageFinished(const LayoutObject&, const ImageResourceContent*);
void OnPaintFinished();
- void NotifyNodeRemoved(DOMNodeId);
- void NotifyBackgroundImageRemoved(DOMNodeId, const ImageResourceContent*);
+ void LayoutObjectWillBeDestroyed(const LayoutObject&);
+ void NotifyImageRemoved(const LayoutObject&, const ImageResourceContent*);
// After the method being called, the detector stops to record new entries and
// node removal. But it still observe the loading status. In other words, if
// an image is recorded before stopping recording, and finish loading after
// stopping recording, the detector can still observe the loading being
// finished.
- void StopRecordEntries();
- bool IsRecording() const { return is_recording_; }
- bool FinishedReportingImages() const;
+ inline void StopRecordEntries() { is_recording_ = false; }
+ inline bool IsRecording() const { return is_recording_; }
+ inline bool FinishedReportingImages() const {
+ return !is_recording_ && num_pending_swap_callbacks_ == 0;
+ }
+ void ResetCallbackManager(PaintTimingCallbackManager* manager) {
+ callback_manager_ = manager;
+ }
+ void ReportSwapTime(unsigned last_queued_frame_index, base::TimeTicks);
+
+ // Return the candidate.
+ ImageRecord* UpdateCandidate();
+
void Trace(blink::Visitor*);
private:
+ friend class LargestContentfulPaintCalculatorTest;
+
ImageRecord* FindLargestPaintCandidate() const;
void PopulateTraceValue(TracedValue&, const ImageRecord& first_image_paint);
- // This is provided for unit test to force invoking swap promise callback.
- void ReportSwapTime(unsigned last_queued_frame_index,
- WebWidgetClient::SwapResult,
- base::TimeTicks);
void RegisterNotifySwapTime();
void ReportCandidateToTrace(ImageRecord&);
void ReportNoCandidateToTrace();
void Deactivate();
- void HandleTooManyNodes();
-
- void UpdateCandidate();
-
- base::RepeatingCallback<void(WebWidgetClient::ReportTimeCallback)>
- notify_swap_time_override_for_testing_;
// Used to find the last candidate.
unsigned count_candidates_ = 0;
@@ -221,6 +275,7 @@ class CORE_EXPORT ImagePaintTimingDetector final
ImageRecordsManager records_manager_;
Member<LocalFrameView> frame_view_;
+ Member<PaintTimingCallbackManager> callback_manager_;
};
} // 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 651ce562bbf..05b8b742da2 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
@@ -6,13 +6,16 @@
#include "base/bind.h"
#include "base/test/test_mock_time_task_runner.h"
+#include "base/test/trace_event_analyzer.h"
#include "build/build_config.h"
-#include "third_party/blink/public/platform/web_url_loader_mock_factory.h"
#include "third_party/blink/public/web/web_performance.h"
#include "third_party/blink/public/web/web_widget_client.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/core/html/html_image_element.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/paint/paint_timing_test_helper.h"
#include "third_party/blink/renderer/core/scroll/scroll_types.h"
#include "third_party/blink/renderer/core/svg/svg_image_element.h"
#include "third_party/blink/renderer/core/testing/core_unit_test_helper.h"
@@ -24,37 +27,44 @@
#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/skia/include/core/SkImage.h"
#include "third_party/skia/include/core/SkSurface.h"
namespace blink {
class ImagePaintTimingDetectorTest
- : public RenderingTest,
+ : public testing::Test,
private ScopedFirstContentfulPaintPlusPlusForTest {
- using CallbackQueue = std::queue<WebWidgetClient::ReportTimeCallback>;
-
public:
ImagePaintTimingDetectorTest()
- : RenderingTest(MakeGarbageCollected<SingleChildLocalFrameClient>()),
- ScopedFirstContentfulPaintPlusPlusForTest(true),
- test_task_runner_(base::MakeRefCounted<base::TestMockTimeTaskRunner>()),
- base_url_("http://www.test.com/") {}
-
- ~ImagePaintTimingDetectorTest() override {
- Platform::Current()
- ->GetURLLoaderMockFactory()
- ->UnregisterAllURLsAndClearMemoryCache();
- }
+ : ScopedFirstContentfulPaintPlusPlusForTest(true),
+ test_task_runner_(
+ base::MakeRefCounted<base::TestMockTimeTaskRunner>()) {}
void SetUp() override {
- RenderingTest::SetUp();
- RenderingTest::EnableCompositing();
- ReplaceCallBackQueue(GetPaintTimingDetector());
+ web_view_helper_.Initialize();
+
+ // Enable compositing on the page before running the document lifecycle.
+ web_view_helper_.GetWebView()
+ ->GetPage()
+ ->GetSettings()
+ .SetAcceleratedCompositingEnabled(true);
+
+ WebLocalFrameImpl& frame_impl = *web_view_helper_.LocalMainFrame();
+ frame_impl.ViewImpl()->MainFrameWidget()->Resize(WebSize(640, 480));
+
+ frame_test_helpers::LoadFrame(
+ web_view_helper_.GetWebView()->MainFrameImpl(), "about:blank");
+ GetDocument().View()->SetParentVisible(true);
+ GetDocument().View()->SetSelfVisible(true);
}
protected:
- LocalFrameView& GetFrameView() { return *GetFrame().View(); }
+ LocalFrameView& GetFrameView() { return *GetFrame()->View(); }
+ LocalFrameView& GetChildFrameView() { return *GetChildFrame()->View(); }
+ Document& GetDocument() { return *GetFrame()->GetDocument(); }
+ Document* GetChildDocument() { return GetChildFrame()->GetDocument(); }
PaintTimingDetector& GetPaintTimingDetector() {
return GetFrameView().GetPaintTimingDetector();
}
@@ -64,7 +74,7 @@ class ImagePaintTimingDetectorTest
const PerformanceTiming& GetPerformanceTiming() {
PerformanceTiming* performance =
- DOMWindowPerformance::performance(*GetFrame().DomWindow())->timing();
+ DOMWindowPerformance::performance(*GetFrame()->DomWindow())->timing();
return *performance;
}
@@ -74,14 +84,6 @@ class ImagePaintTimingDetectorTest
return scrollable_area->VisibleContentRect();
}
- LocalFrameView& GetChildFrameView() { return *ChildFrame().View(); }
-
- void ReplaceCallBackQueue(PaintTimingDetector& detector) {
- detector.GetImagePaintTimingDetector()
- ->notify_swap_time_override_for_testing_ =
- base::BindRepeating(&ImagePaintTimingDetectorTest::FakeNotifySwapTime,
- base::Unretained(this));
- }
ImageRecord* FindLargestPaintCandidate() {
return GetPaintTimingDetector()
.GetImagePaintTimingDetector()
@@ -96,24 +98,39 @@ class ImagePaintTimingDetectorTest
}
size_t CountVisibleImageRecords() {
- if (!GetPaintTimingDetector().GetImagePaintTimingDetector())
- return 0;
-
return GetPaintTimingDetector()
.GetImagePaintTimingDetector()
- ->records_manager_.visible_node_map_.size();
+ ->records_manager_.visible_images_.size();
}
- size_t CountVisibleBackgroundImageRecords() {
+ size_t CountInvisibleRecords() {
return GetPaintTimingDetector()
.GetImagePaintTimingDetector()
- ->records_manager_.visible_background_image_map_.size();
+ ->records_manager_.invisible_images_.size();
+ }
+
+ size_t ContainerTotalSize() {
+ return GetPaintTimingDetector()
+ .GetImagePaintTimingDetector()
+ ->records_manager_.invisible_images_.size() +
+ GetPaintTimingDetector()
+ .GetImagePaintTimingDetector()
+ ->records_manager_.visible_images_.size() +
+ GetPaintTimingDetector()
+ .GetImagePaintTimingDetector()
+ ->records_manager_.size_ordered_set_.size() +
+ GetPaintTimingDetector()
+ .GetImagePaintTimingDetector()
+ ->records_manager_.images_queued_for_paint_time_.size() +
+ GetPaintTimingDetector()
+ .GetImagePaintTimingDetector()
+ ->records_manager_.image_finished_times_.size();
}
size_t CountChildFrameRecords() {
return GetChildPaintTimingDetector()
.GetImagePaintTimingDetector()
- ->records_manager_.visible_node_map_.size();
+ ->records_manager_.visible_images_.size();
}
size_t CountRankingSetRecords() {
@@ -123,35 +140,71 @@ class ImagePaintTimingDetectorTest
}
void UpdateCandidate() {
- return GetPaintTimingDetector()
- .GetImagePaintTimingDetector()
- ->UpdateCandidate();
+ GetPaintTimingDetector().GetImagePaintTimingDetector()->UpdateCandidate();
}
- TimeTicks LargestPaintStoredResult() {
+ base::TimeTicks LargestPaintStoredResult() {
return GetPaintTimingDetector().largest_image_paint_time_;
}
- static constexpr TimeDelta kQuantumOfTime =
+ static constexpr base::TimeDelta kQuantumOfTime =
base::TimeDelta::FromMilliseconds(10);
void SimulatePassOfTime() {
test_task_runner_->FastForwardBy(kQuantumOfTime);
}
+ void UpdateAllLifecyclePhases() {
+ GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
+ }
+
void UpdateAllLifecyclePhasesAndInvokeCallbackIfAny() {
- UpdateAllLifecyclePhasesForTest();
+ UpdateAllLifecyclePhases();
SimulatePassOfTime();
- if (!callback_queue_.empty())
- InvokeCallback();
+ while (mock_callback_manager_->CountCallbacks() > 0)
+ InvokeSwapTimeCallback(mock_callback_manager_);
+ }
+
+ void SetBodyInnerHTML(const std::string& content) {
+ frame_test_helpers::LoadHTMLString(
+ web_view_helper_.GetWebView()->MainFrameImpl(), content,
+ KURL("http://test.com"));
+ mock_callback_manager_ =
+ MakeGarbageCollected<MockPaintTimingCallbackManager>();
+ GetPaintTimingDetector()
+ .GetImagePaintTimingDetector()
+ ->ResetCallbackManager(mock_callback_manager_);
+ UpdateAllLifecyclePhases();
+ }
+
+ void SetChildBodyInnerHTML(const String& content) {
+ GetChildDocument()->SetBaseURLOverride(KURL("http://test.com"));
+ GetChildDocument()->body()->SetInnerHTMLFromString(content,
+ ASSERT_NO_EXCEPTION);
+ child_mock_callback_manager_ =
+ MakeGarbageCollected<MockPaintTimingCallbackManager>();
+ GetChildPaintTimingDetector()
+ .GetImagePaintTimingDetector()
+ ->ResetCallbackManager(child_mock_callback_manager_);
+ UpdateAllLifecyclePhases();
}
void InvokeCallback() {
- DCHECK_GT(callback_queue_.size(), 0UL);
- std::move(callback_queue_.front())
- .Run(WebWidgetClient::SwapResult::kDidSwap,
- test_task_runner_->NowTicks());
- callback_queue_.pop();
+ DCHECK_GT(mock_callback_manager_->CountCallbacks(), 0UL);
+ InvokeSwapTimeCallback(mock_callback_manager_);
+ }
+
+ void InvokeChildFrameCallback() {
+ DCHECK_GT(child_mock_callback_manager_->CountCallbacks(), 0UL);
+ InvokeSwapTimeCallback(child_mock_callback_manager_);
+ }
+
+ void InvokeSwapTimeCallback(
+ MockPaintTimingCallbackManager* image_callback_manager) {
+ image_callback_manager->InvokeSwapTimeCallback(
+ test_task_runner_->NowTicks());
+ UpdateCandidate();
}
void SetImageAndPaint(AtomicString id, int width, int height) {
@@ -162,8 +215,8 @@ class ImagePaintTimingDetectorTest
}
void SetChildFrameImageAndPaint(AtomicString id, int width, int height) {
- DCHECK(ChildFrame().GetDocument());
- Element* element = ChildFrame().GetDocument()->getElementById(id);
+ DCHECK(GetChildDocument());
+ Element* element = GetChildDocument()->getElementById(id);
DCHECK(element);
// Set image and make it loaded.
ImageResourceContent* content = CreateImageForTest(width, height);
@@ -188,10 +241,14 @@ class ImagePaintTimingDetectorTest
void SimulateScroll() { GetPaintTimingDetector().NotifyScroll(kUserScroll); }
scoped_refptr<base::TestMockTimeTaskRunner> test_task_runner_;
+ frame_test_helpers::WebViewHelper web_view_helper_;
private:
- void FakeNotifySwapTime(WebWidgetClient::ReportTimeCallback callback) {
- callback_queue_.push(std::move(callback));
+ LocalFrame* GetFrame() {
+ return web_view_helper_.GetWebView()->MainFrameImpl()->GetFrame();
+ }
+ LocalFrame* GetChildFrame() {
+ return To<LocalFrame>(GetFrame()->Tree().FirstChild());
}
ImageResourceContent* CreateImageForTest(int width, int height) {
sk_sp<SkColorSpace> src_rgb_color_space = SkColorSpace::MakeSRGB();
@@ -205,11 +262,12 @@ class ImagePaintTimingDetectorTest
return original_image_resource;
}
- CallbackQueue callback_queue_;
- std::string base_url_;
+ PaintTimingCallbackManager::CallbackQueue callback_queue_;
+ Persistent<MockPaintTimingCallbackManager> mock_callback_manager_;
+ Persistent<MockPaintTimingCallbackManager> child_mock_callback_manager_;
};
-constexpr TimeDelta ImagePaintTimingDetectorTest::kQuantumOfTime;
+constexpr base::TimeDelta ImagePaintTimingDetectorTest::kQuantumOfTime;
TEST_F(ImagePaintTimingDetectorTest, LargestImagePaint_NoImage) {
SetBodyInnerHTML(R"HTML(
@@ -231,31 +289,145 @@ TEST_F(ImagePaintTimingDetectorTest, LargestImagePaint_OneImage) {
EXPECT_TRUE(record->loaded);
}
+TEST_F(ImagePaintTimingDetectorTest, InsertionOrderIsSecondaryRankingKey) {
+ SetBodyInnerHTML(R"HTML(
+ )HTML");
+
+ auto* image1 = MakeGarbageCollected<HTMLImageElement>(GetDocument());
+ image1->setAttribute("id", "image1");
+ GetDocument().body()->AppendChild(image1);
+ SetImageAndPaint("image1", 5, 5);
+
+ auto* image2 = MakeGarbageCollected<HTMLImageElement>(GetDocument());
+ image2->setAttribute("id", "image2");
+ GetDocument().body()->AppendChild(image2);
+ SetImageAndPaint("image2", 5, 5);
+
+ auto* image3 = MakeGarbageCollected<HTMLImageElement>(GetDocument());
+ image3->setAttribute("id", "image3");
+ GetDocument().body()->AppendChild(image3);
+ SetImageAndPaint("image3", 5, 5);
+
+ UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
+
+ EXPECT_EQ(FindLargestPaintCandidate()->node_id,
+ DOMNodeIds::ExistingIdForNode(image1));
+}
+
+TEST_F(ImagePaintTimingDetectorTest, LargestImagePaint_TraceEvent_Candidate) {
+ using trace_analyzer::Query;
+ trace_analyzer::Start("loading");
+ {
+ SetBodyInnerHTML(R"HTML(
+ <img id="target"></img>
+ )HTML");
+ SetImageAndPaint("target", 5, 5);
+ UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
+ }
+ auto analyzer = trace_analyzer::Stop();
+ trace_analyzer::TraceEventVector events;
+ Query q = Query::EventNameIs("LargestImagePaint::Candidate");
+ analyzer->FindEvents(q, &events);
+ EXPECT_EQ(1u, events.size());
+ EXPECT_EQ("loading", events[0]->category);
+
+ EXPECT_TRUE(events[0]->HasArg("frame"));
+
+ EXPECT_TRUE(events[0]->HasArg("data"));
+ std::unique_ptr<base::Value> arg;
+ EXPECT_TRUE(events[0]->GetArgAsValue("data", &arg));
+ base::DictionaryValue* arg_dict;
+ EXPECT_TRUE(arg->GetAsDictionary(&arg_dict));
+ DOMNodeId node_id;
+ EXPECT_TRUE(arg_dict->GetInteger("DOMNodeId", &node_id));
+ EXPECT_GT(node_id, 0);
+ int size;
+ EXPECT_TRUE(arg_dict->GetInteger("size", &size));
+ EXPECT_GT(size, 0);
+ DOMNodeId candidate_index;
+ EXPECT_TRUE(arg_dict->GetInteger("candidateIndex", &candidate_index));
+ EXPECT_EQ(candidate_index, 2);
+ bool isMainFrame;
+ EXPECT_TRUE(arg_dict->GetBoolean("isMainFrame", &isMainFrame));
+ EXPECT_EQ(true, isMainFrame);
+ bool isOOPIF;
+ EXPECT_TRUE(arg_dict->GetBoolean("isOOPIF", &isOOPIF));
+ EXPECT_EQ(false, isOOPIF);
+}
+
+TEST_F(ImagePaintTimingDetectorTest, LargestImagePaint_TraceEvent_NoCandidate) {
+ using trace_analyzer::Query;
+ trace_analyzer::Start("*");
+ {
+ SetBodyInnerHTML(R"HTML(
+ <img id="target"></img>
+ )HTML");
+ SetImageAndPaint("target", 5, 5);
+ UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
+ GetDocument().getElementById("target")->remove();
+ UpdateAllLifecyclePhases();
+ }
+ auto analyzer = trace_analyzer::Stop();
+ trace_analyzer::TraceEventVector events;
+ Query q = Query::EventNameIs("LargestImagePaint::NoCandidate");
+ analyzer->FindEvents(q, &events);
+ EXPECT_EQ(2u, events.size());
+
+ {
+ EXPECT_EQ("loading", events[0]->category);
+ EXPECT_TRUE(events[0]->HasArg("frame"));
+ EXPECT_TRUE(events[0]->HasArg("data"));
+ std::unique_ptr<base::Value> arg;
+ EXPECT_TRUE(events[0]->GetArgAsValue("data", &arg));
+ base::DictionaryValue* arg_dict;
+ EXPECT_TRUE(arg->GetAsDictionary(&arg_dict));
+ DOMNodeId candidate_index;
+ EXPECT_TRUE(arg_dict->GetInteger("candidateIndex", &candidate_index));
+ EXPECT_EQ(candidate_index, 1);
+ bool is_main_frame;
+ EXPECT_TRUE(arg_dict->GetBoolean("isMainFrame", &is_main_frame));
+ EXPECT_EQ(true, is_main_frame);
+ bool is_oopif;
+ EXPECT_TRUE(arg_dict->GetBoolean("isOOPIF", &is_oopif));
+ EXPECT_EQ(false, is_oopif);
+ }
+
+ // Use block to reuse the temp variable names.
+ {
+ EXPECT_TRUE(events[1]->HasArg("data"));
+ std::unique_ptr<base::Value> arg;
+ EXPECT_TRUE(events[1]->GetArgAsValue("data", &arg));
+ base::DictionaryValue* arg_dict;
+ EXPECT_TRUE(arg->GetAsDictionary(&arg_dict));
+ DOMNodeId candidate_index;
+ EXPECT_TRUE(arg_dict->GetInteger("candidateIndex", &candidate_index));
+ EXPECT_EQ(candidate_index, 3);
+ }
+}
+
TEST_F(ImagePaintTimingDetectorTest, UpdatePerformanceTiming) {
- const PerformanceTiming& performance_timing = GetPerformanceTiming();
- EXPECT_EQ(performance_timing.LargestImagePaintSize(), 0u);
- EXPECT_EQ(performance_timing.LargestImagePaint(), 0u);
+ EXPECT_EQ(GetPerformanceTiming().LargestImagePaintSize(), 0u);
+ EXPECT_EQ(GetPerformanceTiming().LargestImagePaint(), 0u);
SetBodyInnerHTML(R"HTML(
<img id="target"></img>
)HTML");
SetImageAndPaint("target", 5, 5);
UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
- EXPECT_EQ(performance_timing.LargestImagePaintSize(), 25u);
- EXPECT_GT(performance_timing.LargestImagePaint(), 0u);
+ EXPECT_EQ(GetPerformanceTiming().LargestImagePaintSize(), 25u);
+ EXPECT_GT(GetPerformanceTiming().LargestImagePaint(), 0u);
}
TEST_F(ImagePaintTimingDetectorTest,
PerformanceTimingHasZeroTimeNonZeroSizeWhenTheLargestIsNotPainted) {
- const PerformanceTiming& performance_timing = GetPerformanceTiming();
- EXPECT_EQ(performance_timing.LargestImagePaintSize(), 0u);
- EXPECT_EQ(performance_timing.LargestImagePaint(), 0u);
+ EXPECT_EQ(GetPerformanceTiming().LargestImagePaintSize(), 0u);
+ EXPECT_EQ(GetPerformanceTiming().LargestImagePaint(), 0u);
SetBodyInnerHTML(R"HTML(
<img id="target"></img>
)HTML");
SetImageAndPaint("target", 5, 5);
- UpdateAllLifecyclePhasesForTest();
- EXPECT_EQ(performance_timing.LargestImagePaintSize(), 25u);
- EXPECT_EQ(performance_timing.LargestImagePaint(), 0u);
+ UpdateAllLifecyclePhases();
+ EXPECT_EQ(GetPerformanceTiming().LargestImagePaintSize(), 25u);
+ EXPECT_EQ(GetPerformanceTiming().LargestImagePaint(), 0u);
}
TEST_F(ImagePaintTimingDetectorTest, UpdatePerformanceTimingToZero) {
@@ -264,13 +436,12 @@ TEST_F(ImagePaintTimingDetectorTest, UpdatePerformanceTimingToZero) {
)HTML");
SetImageAndPaint("target", 5, 5);
UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
- const PerformanceTiming& performance_timing = GetPerformanceTiming();
- EXPECT_EQ(performance_timing.LargestImagePaintSize(), 25u);
- EXPECT_GT(performance_timing.LargestImagePaint(), 0u);
+ EXPECT_EQ(GetPerformanceTiming().LargestImagePaintSize(), 25u);
+ EXPECT_GT(GetPerformanceTiming().LargestImagePaint(), 0u);
GetDocument().body()->RemoveChild(GetDocument().getElementById("target"));
UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
- EXPECT_EQ(performance_timing.LargestImagePaintSize(), 0u);
- EXPECT_EQ(performance_timing.LargestImagePaint(), 0u);
+ EXPECT_EQ(GetPerformanceTiming().LargestImagePaintSize(), 0u);
+ EXPECT_EQ(GetPerformanceTiming().LargestImagePaint(), 0u);
}
TEST_F(ImagePaintTimingDetectorTest, LargestImagePaint_OpacityZero) {
@@ -285,7 +456,6 @@ TEST_F(ImagePaintTimingDetectorTest, LargestImagePaint_OpacityZero) {
SetImageAndPaint("target", 5, 5);
UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
EXPECT_EQ(CountVisibleImageRecords(), 0u);
- EXPECT_EQ(CountVisibleBackgroundImageRecords(), 0u);
ImageRecord* record = FindLargestPaintCandidate();
EXPECT_FALSE(record);
}
@@ -302,7 +472,6 @@ TEST_F(ImagePaintTimingDetectorTest, LargestImagePaint_VisibilityHidden) {
SetImageAndPaint("target", 5, 5);
UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
EXPECT_EQ(CountVisibleImageRecords(), 0u);
- EXPECT_EQ(CountVisibleBackgroundImageRecords(), 0u);
ImageRecord* record = FindLargestPaintCandidate();
EXPECT_FALSE(record);
}
@@ -319,7 +488,6 @@ TEST_F(ImagePaintTimingDetectorTest, LargestImagePaint_DisplayNone) {
SetImageAndPaint("target", 5, 5);
UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
EXPECT_EQ(CountVisibleImageRecords(), 0u);
- EXPECT_EQ(CountVisibleBackgroundImageRecords(), 0u);
ImageRecord* record = FindLargestPaintCandidate();
EXPECT_FALSE(record);
}
@@ -336,7 +504,6 @@ TEST_F(ImagePaintTimingDetectorTest, LargestImagePaint_OpacityNonZero) {
SetImageAndPaint("target", 5, 5);
UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
EXPECT_EQ(CountVisibleImageRecords(), 1u);
- EXPECT_EQ(CountVisibleBackgroundImageRecords(), 0u);
ImageRecord* record = FindLargestPaintCandidate();
EXPECT_TRUE(record);
}
@@ -452,7 +619,7 @@ TEST_F(ImagePaintTimingDetectorTest,
</div>
)HTML");
SetImageAndPaint("target", 5, 5);
- UpdateAllLifecyclePhasesForTest();
+ UpdateAllLifecyclePhases();
GetDocument().getElementById("parent")->RemoveChild(
GetDocument().getElementById("target"));
@@ -465,7 +632,92 @@ TEST_F(ImagePaintTimingDetectorTest,
}
TEST_F(ImagePaintTimingDetectorTest,
- LargestImagePaint_ReattachedNodeUseFirstPaint) {
+ RemoveRecordFromAllContainersAfterImageRemoval) {
+ SetBodyInnerHTML(R"HTML(
+ <div id="parent">
+ <img id="target"></img>
+ </div>
+ )HTML");
+ SetImageAndPaint("target", 5, 5);
+ UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
+ EXPECT_EQ(ContainerTotalSize(), 3u);
+
+ GetDocument().getElementById("parent")->RemoveChild(
+ GetDocument().getElementById("target"));
+ EXPECT_EQ(ContainerTotalSize(), 0u);
+}
+
+TEST_F(ImagePaintTimingDetectorTest,
+ RemoveRecordFromAllContainersAfterInvisibleImageRemoved) {
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ #target {
+ position: relative;
+ left: 100px;
+ }
+ #parent {
+ background-color: yellow;
+ height: 50px;
+ width: 50px;
+ overflow: scroll;
+ }
+ </style>
+ <div id='parent'>
+ <img id='target'></img>
+ </div>
+ )HTML");
+ SetImageAndPaint("target", 5, 5);
+ UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
+ EXPECT_EQ(ContainerTotalSize(), 2u);
+ EXPECT_EQ(CountInvisibleRecords(), 1u);
+
+ GetDocument().body()->RemoveChild(GetDocument().getElementById("parent"));
+ EXPECT_EQ(ContainerTotalSize(), 0u);
+ EXPECT_EQ(CountInvisibleRecords(), 0u);
+}
+
+TEST_F(ImagePaintTimingDetectorTest,
+ RemoveRecordFromAllContainersAfterBackgroundImageRemoval) {
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ #target {
+ background-image: url(data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==);
+ }
+ </style>
+ <div id="parent">
+ <div id="target">
+ place-holder
+ </div>
+ </div>
+ )HTML");
+ UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
+ EXPECT_EQ(ContainerTotalSize(), 3u);
+
+ GetDocument().getElementById("parent")->RemoveChild(
+ GetDocument().getElementById("target"));
+ EXPECT_EQ(ContainerTotalSize(), 0u);
+}
+
+TEST_F(ImagePaintTimingDetectorTest,
+ RemoveRecordFromAllContainersAfterImageRemovedAndCallbackInvoked) {
+ SetBodyInnerHTML(R"HTML(
+ <div id="parent">
+ <img id="target"></img>
+ </div>
+ )HTML");
+ SetImageAndPaint("target", 5, 5);
+ UpdateAllLifecyclePhases();
+ EXPECT_EQ(ContainerTotalSize(), 4u);
+
+ GetDocument().getElementById("parent")->RemoveChild(
+ GetDocument().getElementById("target"));
+ EXPECT_EQ(ContainerTotalSize(), 1u);
+ InvokeCallback();
+ EXPECT_EQ(ContainerTotalSize(), 0u);
+}
+
+TEST_F(ImagePaintTimingDetectorTest,
+ LargestImagePaint_ReattachedNodeTreatedAsNew) {
SetBodyInnerHTML(R"HTML(
<div id="parent">
</div>
@@ -474,32 +726,34 @@ TEST_F(ImagePaintTimingDetectorTest,
image->setAttribute("id", "target");
GetDocument().getElementById("parent")->AppendChild(image);
SetImageAndPaint("target", 5, 5);
- test_task_runner_->FastForwardBy(TimeDelta::FromSecondsD(1));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromSecondsD(1));
UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
ImageRecord* record;
record = FindLargestPaintCandidate();
EXPECT_TRUE(record);
// UpdateAllLifecyclePhasesAndInvokeCallbackIfAny() moves time forward
// kQuantumOfTime so we should take that into account.
- EXPECT_EQ(record->paint_time,
- base::TimeTicks() + TimeDelta::FromSecondsD(1) + kQuantumOfTime);
+ EXPECT_EQ(
+ record->paint_time,
+ base::TimeTicks() + base::TimeDelta::FromSecondsD(1) + kQuantumOfTime);
GetDocument().getElementById("parent")->RemoveChild(image);
- test_task_runner_->FastForwardBy(TimeDelta::FromSecondsD(1));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromSecondsD(1));
UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
record = FindLargestPaintCandidate();
EXPECT_FALSE(record);
GetDocument().getElementById("parent")->AppendChild(image);
SetImageAndPaint("target", 5, 5);
- test_task_runner_->FastForwardBy(TimeDelta::FromSecondsD(1));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromSecondsD(1));
UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
record = FindLargestPaintCandidate();
EXPECT_TRUE(record);
// UpdateAllLifecyclePhasesAndInvokeCallbackIfAny() moves time forward
// kQuantumOfTime so we should take that into account.
- EXPECT_EQ(record->paint_time,
- base::TimeTicks() + TimeDelta::FromSecondsD(1) + kQuantumOfTime);
+ EXPECT_EQ(record->paint_time, base::TimeTicks() +
+ base::TimeDelta::FromSecondsD(3) +
+ 3 * kQuantumOfTime);
}
// This is to prove that a swap time is assigned only to nodes of the frame who
@@ -514,10 +768,10 @@ TEST_F(ImagePaintTimingDetectorTest, MatchSwapTimeToNodesOfDifferentFrames) {
)HTML");
SetImageAndPaint("larger", 9, 9);
- UpdateAllLifecyclePhasesForTest();
+ UpdateAllLifecyclePhases();
SimulatePassOfTime();
SetImageAndPaint("smaller", 5, 5);
- UpdateAllLifecyclePhasesForTest();
+ UpdateAllLifecyclePhases();
SimulatePassOfTime();
InvokeCallback();
// record1 is the larger.
@@ -525,7 +779,7 @@ TEST_F(ImagePaintTimingDetectorTest, MatchSwapTimeToNodesOfDifferentFrames) {
const base::TimeTicks record1Time = record1->paint_time;
GetDocument().getElementById("parent")->RemoveChild(
GetDocument().getElementById("larger"));
- UpdateAllLifecyclePhasesForTest();
+ UpdateAllLifecyclePhases();
SimulatePassOfTime();
InvokeCallback();
// record2 is the smaller.
@@ -535,7 +789,7 @@ TEST_F(ImagePaintTimingDetectorTest, MatchSwapTimeToNodesOfDifferentFrames) {
TEST_F(ImagePaintTimingDetectorTest,
LargestImagePaint_UpdateResultWhenLargestChanged) {
- TimeTicks time1 = test_task_runner_->NowTicks();
+ base::TimeTicks time1 = test_task_runner_->NowTicks();
SetBodyInnerHTML(R"HTML(
<div id="parent">
<img id="target1"></img>
@@ -544,15 +798,15 @@ TEST_F(ImagePaintTimingDetectorTest,
)HTML");
SetImageAndPaint("target1", 5, 5);
UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
- TimeTicks time2 = test_task_runner_->NowTicks();
- TimeTicks result1 = LargestPaintStoredResult();
+ base::TimeTicks time2 = test_task_runner_->NowTicks();
+ base::TimeTicks result1 = LargestPaintStoredResult();
EXPECT_GE(result1, time1);
EXPECT_GE(time2, result1);
SetImageAndPaint("target2", 10, 10);
UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
- TimeTicks time3 = test_task_runner_->NowTicks();
- TimeTicks result2 = LargestPaintStoredResult();
+ base::TimeTicks time3 = test_task_runner_->NowTicks();
+ base::TimeTicks result2 = LargestPaintStoredResult();
EXPECT_GE(result2, time2);
EXPECT_GE(time3, result2);
}
@@ -566,11 +820,11 @@ TEST_F(ImagePaintTimingDetectorTest, OneSwapPromiseForOneFrame) {
</div>
)HTML");
SetImageAndPaint("1", 5, 5);
- UpdateAllLifecyclePhasesForTest();
+ UpdateAllLifecyclePhases();
SimulatePassOfTime();
SetImageAndPaint("2", 9, 9);
- UpdateAllLifecyclePhasesForTest();
+ UpdateAllLifecyclePhases();
SimulatePassOfTime();
// This callback only assigns a time to the 5x5 image.
@@ -591,7 +845,7 @@ TEST_F(ImagePaintTimingDetectorTest, OneSwapPromiseForOneFrame) {
TEST_F(ImagePaintTimingDetectorTest, VideoImage) {
SetBodyInnerHTML(R"HTML(
- <video id="target" poster="http://example.com/nonexistant.gif"></video>
+ <video id="target"></video>
)HTML");
SetVideoImageAndPaint("target", 5, 5);
@@ -605,7 +859,7 @@ TEST_F(ImagePaintTimingDetectorTest, VideoImage) {
TEST_F(ImagePaintTimingDetectorTest, VideoImage_ImageNotLoaded) {
SetBodyInnerHTML(R"HTML(
- <video id="target" poster="http://example.com/nonexistant.gif"></video>
+ <video id="target"></video>
)HTML");
UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
@@ -616,8 +870,7 @@ TEST_F(ImagePaintTimingDetectorTest, VideoImage_ImageNotLoaded) {
TEST_F(ImagePaintTimingDetectorTest, SVGImage) {
SetBodyInnerHTML(R"HTML(
<svg>
- <image id="target" width="10" height="10"
- xlink:href="http://example.com/nonexistant.jpg"/>
+ <image id="target" width="10" height="10"/>
</svg>
)HTML");
@@ -643,7 +896,7 @@ TEST_F(ImagePaintTimingDetectorTest, BackgroundImage) {
)HTML");
ImageRecord* record = FindLargestPaintCandidate();
EXPECT_TRUE(record);
- EXPECT_EQ(CountVisibleBackgroundImageRecords(), 1u);
+ EXPECT_EQ(CountVisibleImageRecords(), 1u);
}
TEST_F(ImagePaintTimingDetectorTest,
@@ -660,8 +913,7 @@ TEST_F(ImagePaintTimingDetectorTest,
)HTML");
SetImageAndPaint("target", 1, 1);
UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
- EXPECT_EQ(CountVisibleBackgroundImageRecords(), 1u);
- EXPECT_EQ(CountVisibleImageRecords(), 1u);
+ EXPECT_EQ(CountVisibleImageRecords(), 2u);
ImageRecord* record = FindLargestPaintCandidate();
EXPECT_TRUE(record);
EXPECT_EQ(record->first_size, 1u);
@@ -675,7 +927,7 @@ TEST_F(ImagePaintTimingDetectorTest, BackgroundImage_IgnoreBody) {
}
</style>
)HTML");
- EXPECT_EQ(CountVisibleBackgroundImageRecords(), 0u);
+ EXPECT_EQ(CountVisibleImageRecords(), 0u);
}
TEST_F(ImagePaintTimingDetectorTest, BackgroundImage_IgnoreHtml) {
@@ -688,7 +940,7 @@ TEST_F(ImagePaintTimingDetectorTest, BackgroundImage_IgnoreHtml) {
</style>
</html>
)HTML");
- EXPECT_EQ(CountVisibleBackgroundImageRecords(), 0u);
+ EXPECT_EQ(CountVisibleImageRecords(), 0u);
}
TEST_F(ImagePaintTimingDetectorTest, BackgroundImage_IgnoreGradient) {
@@ -702,7 +954,7 @@ TEST_F(ImagePaintTimingDetectorTest, BackgroundImage_IgnoreGradient) {
place-holder
</div>
)HTML");
- EXPECT_EQ(CountVisibleBackgroundImageRecords(), 0u);
+ EXPECT_EQ(CountVisibleImageRecords(), 0u);
}
// We put two background images in the same object, and test whether FCP++ can
@@ -720,7 +972,7 @@ TEST_F(ImagePaintTimingDetectorTest, BackgroundImageTrackedDifferently) {
</style>
<div id="d"></div>
)HTML");
- EXPECT_EQ(CountVisibleBackgroundImageRecords(), 2u);
+ EXPECT_EQ(CountVisibleImageRecords(), 2u);
}
TEST_F(ImagePaintTimingDetectorTest, DeactivateAfterUserInput) {
@@ -732,7 +984,7 @@ TEST_F(ImagePaintTimingDetectorTest, DeactivateAfterUserInput) {
SimulateScroll();
SetImageAndPaint("target", 5, 5);
UpdateAllLifecyclePhasesAndInvokeCallbackIfAny();
- EXPECT_EQ(CountVisibleImageRecords(), 0u);
+ EXPECT_FALSE(GetPaintTimingDetector().GetImagePaintTimingDetector());
}
TEST_F(ImagePaintTimingDetectorTest, NullTimeNoCrash) {
@@ -740,7 +992,7 @@ TEST_F(ImagePaintTimingDetectorTest, NullTimeNoCrash) {
<img id="target"></img>
)HTML");
SetImageAndPaint("target", 5, 5);
- UpdateAllLifecyclePhasesForTest();
+ UpdateAllLifecyclePhases();
UpdateCandidate();
}
@@ -748,17 +1000,16 @@ TEST_F(ImagePaintTimingDetectorTest, Iframe) {
SetBodyInnerHTML(R"HTML(
<iframe width=100px height=100px></iframe>
)HTML");
- SetChildFrameHTML(R"HTML(
+ SetChildBodyInnerHTML(R"HTML(
<style>img { display:block }</style>
<img id="target"></img>
)HTML");
- ReplaceCallBackQueue(GetChildPaintTimingDetector());
SetChildFrameImageAndPaint("target", 5, 5);
- UpdateAllLifecyclePhasesForTest();
+ UpdateAllLifecyclePhases();
// Ensure main frame doesn't capture this image.
EXPECT_EQ(CountVisibleImageRecords(), 0u);
EXPECT_EQ(CountChildFrameRecords(), 1u);
- InvokeCallback();
+ InvokeChildFrameCallback();
ImageRecord* image = FindChildFrameLargestPaintCandidate();
EXPECT_TRUE(image);
// Ensure the image size is not clipped (5*5).
@@ -772,15 +1023,14 @@ TEST_F(ImagePaintTimingDetectorTest, Iframe_ClippedByMainFrameViewport) {
</style>
<iframe id="f" width=100px height=100px></iframe>
)HTML");
- SetChildFrameHTML(R"HTML(
+ SetChildBodyInnerHTML(R"HTML(
<style>img { display:block }</style>
<img id="target"></img>
)HTML");
// Make sure the iframe is out of main-frame's viewport.
DCHECK_LT(GetViewportRect(GetFrameView()).Height(), 1234567);
- ReplaceCallBackQueue(GetChildPaintTimingDetector());
SetChildFrameImageAndPaint("target", 5, 5);
- UpdateAllLifecyclePhasesForTest();
+ UpdateAllLifecyclePhases();
EXPECT_EQ(CountVisibleImageRecords(), 0u);
}
@@ -791,16 +1041,15 @@ TEST_F(ImagePaintTimingDetectorTest, Iframe_HalfClippedByMainFrameViewport) {
</style>
<iframe id="f" width=10px height=10px></iframe>
)HTML");
- SetChildFrameHTML(R"HTML(
+ SetChildBodyInnerHTML(R"HTML(
<style>img { display:block }</style>
<img id="target"></img>
)HTML");
- ReplaceCallBackQueue(GetChildPaintTimingDetector());
SetChildFrameImageAndPaint("target", 10, 10);
- UpdateAllLifecyclePhasesForTest();
+ UpdateAllLifecyclePhases();
EXPECT_EQ(CountVisibleImageRecords(), 0u);
EXPECT_EQ(CountChildFrameRecords(), 1u);
- InvokeCallback();
+ InvokeChildFrameCallback();
ImageRecord* image = FindChildFrameLargestPaintCandidate();
EXPECT_TRUE(image);
EXPECT_LT(image->first_size, 100ul);
diff --git a/chromium/third_party/blink/renderer/core/paint/image_painter.h b/chromium/third_party/blink/renderer/core/paint/image_painter.h
index 35bf83a5edd..0690b704051 100644
--- a/chromium/third_party/blink/renderer/core/paint/image_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/image_painter.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_IMAGE_PAINTER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_IMAGE_PAINTER_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/inline_box_painter_base.h b/chromium/third_party/blink/renderer/core/paint/inline_box_painter_base.h
index 1e1794ed3b7..0dc82e10ad0 100644
--- a/chromium/third_party/blink/renderer/core/paint/inline_box_painter_base.h
+++ b/chromium/third_party/blink/renderer/core/paint/inline_box_painter_base.h
@@ -9,7 +9,7 @@
#include "third_party/blink/renderer/core/style/shadow_data.h"
#include "third_party/blink/renderer/platform/graphics/graphics_types.h"
#include "third_party/blink/renderer/platform/text/text_direction.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 1c33d681c68..4c14b9f3a1c 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
@@ -4,7 +4,6 @@
#include "third_party/blink/renderer/core/paint/inline_flow_box_painter.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/frame/web_feature.h"
#include "third_party/blink/renderer/core/layout/api/line_layout_api_shim.h"
#include "third_party/blink/renderer/core/layout/line/inline_flow_box.h"
@@ -17,6 +16,7 @@
#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"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/inline_flow_box_painter.h b/chromium/third_party/blink/renderer/core/paint/inline_flow_box_painter.h
index 035b13561ba..9b239f13267 100644
--- a/chromium/third_party/blink/renderer/core/paint/inline_flow_box_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/inline_flow_box_painter.h
@@ -11,7 +11,7 @@
#include "third_party/blink/renderer/core/style/shadow_data.h"
#include "third_party/blink/renderer/platform/graphics/graphics_types.h"
#include "third_party/blink/renderer/platform/text/text_direction.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 d21a475f3da..1486dab891d 100644
--- a/chromium/third_party/blink/renderer/core/paint/inline_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/inline_painter.cc
@@ -52,13 +52,13 @@ void InlinePainter::Paint(const PaintInfo& paint_info) {
if (fragment->PhysicalFragment().IsText()) {
const auto& text_fragment =
To<NGPhysicalTextFragment>(fragment->PhysicalFragment());
- NodeHolder holder;
+ DOMNodeId node_id = kInvalidDOMNodeId;
if (auto* node = text_fragment.GetNode()) {
if (node->GetLayoutObject()->IsText())
- holder = ToLayoutText(node->GetLayoutObject())->EnsureNodeHolder();
+ node_id = ToLayoutText(node->GetLayoutObject())->EnsureNodeId();
}
NGTextFragmentPainter(*fragment).Paint(paint_info, child_offset,
- holder);
+ node_id);
} else {
NGInlineBoxFragmentPainter(*fragment).Paint(paint_info, child_offset);
@@ -80,7 +80,7 @@ void InlinePainter::Paint(const PaintInfo& paint_info) {
}
LineBoxListPainter(*layout_inline_.LineBoxes())
- .Paint(layout_inline_, local_paint_info, paint_offset.ToLayoutPoint());
+ .Paint(layout_inline_, local_paint_info, paint_offset);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/paint/inline_painter.h b/chromium/third_party/blink/renderer/core/paint/inline_painter.h
index 5f8020ad9eb..04a718ae67d 100644
--- a/chromium/third_party/blink/renderer/core/paint/inline_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/inline_painter.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_INLINE_PAINTER_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/allocator/allocator.h"
namespace blink {
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 70ff636d1a7..c1de70e127d 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
@@ -6,7 +6,6 @@
#include "base/optional.h"
#include "third_party/blink/renderer/core/content_capture/content_capture_manager.h"
-#include "third_party/blink/renderer/core/content_capture/content_holder.h"
#include "third_party/blink/renderer/core/editing/editor.h"
#include "third_party/blink/renderer/core/editing/markers/composition_marker.h"
#include "third_party/blink/renderer/core/editing/markers/document_marker_controller.h"
@@ -25,6 +24,7 @@
#include "third_party/blink/renderer/core/paint/paint_timing_detector.h"
#include "third_party/blink/renderer/core/paint/selection_painting_utils.h"
#include "third_party/blink/renderer/core/paint/text_painter.h"
+#include "third_party/blink/renderer/platform/graphics/dom_node_id.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/paint_record.h"
@@ -58,12 +58,12 @@ std::pair<unsigned, unsigned> GetTextMatchMarkerPaintOffsets(
return std::make_pair(start_offset, end_offset);
}
-NodeHolder GetNodeHolder(Node* node) {
+DOMNodeId GetNodeHolder(Node* node) {
if (node && node->GetLayoutObject()) {
DCHECK(node->GetLayoutObject()->IsText());
- return (ToLayoutText(node->GetLayoutObject()))->EnsureNodeHolder();
+ return (ToLayoutText(node->GetLayoutObject()))->EnsureNodeId();
}
- return NodeHolder::EmptyNodeHolder();
+ return kInvalidDOMNodeId;
}
} // anonymous namespace
@@ -168,7 +168,8 @@ void InlineTextBoxPainter::Paint(const PaintInfo& paint_info,
inline_text_box_.GetLineLayoutItem().StyleRef(
inline_text_box_.IsFirstLineStyle());
- LayoutPoint box_origin(inline_text_box_.PhysicalLocation() + paint_offset);
+ LayoutPoint box_origin(inline_text_box_.PhysicalLocation().ToLayoutPoint() +
+ paint_offset);
// We round the y-axis to ensure consistent line heights.
if (inline_text_box_.IsHorizontal()) {
@@ -340,7 +341,7 @@ void InlineTextBoxPainter::Paint(const PaintInfo& paint_info,
if (inline_text_box_.Truncation() != kCNoTruncation && ltr != flow_is_ltr)
text_painter.SetEllipsisOffset(inline_text_box_.Truncation());
- NodeHolder node_holder = GetNodeHolder(
+ DOMNodeId node_id = GetNodeHolder(
LineLayoutAPIShim::LayoutObjectFrom(inline_text_box_.GetLineLayoutItem())
->GetNode());
@@ -384,8 +385,7 @@ void InlineTextBoxPainter::Paint(const PaintInfo& paint_info,
start_offset = selection_end;
end_offset = selection_start;
}
- text_painter.Paint(start_offset, end_offset, length, text_style,
- node_holder);
+ text_painter.Paint(start_offset, end_offset, length, text_style, node_id);
// Paint line-through decoration if needed.
if (has_line_through_decoration) {
@@ -410,7 +410,7 @@ void InlineTextBoxPainter::Paint(const PaintInfo& paint_info,
GraphicsContextStateSaver state_saver(context);
context.ClipOut(FloatRect(selection_rect));
text_painter.Paint(selection_start, selection_end, length, text_style,
- node_holder);
+ node_id);
}
// the second time, we draw the glyphs inside the selection area, with
// the selection style.
@@ -418,7 +418,7 @@ void InlineTextBoxPainter::Paint(const PaintInfo& paint_info,
GraphicsContextStateSaver state_saver(context);
context.Clip(FloatRect(selection_rect));
text_painter.Paint(selection_start, selection_end, length,
- selection_style, node_holder);
+ selection_style, node_id);
}
}
@@ -858,8 +858,7 @@ void InlineTextBoxPainter::PaintTextMatchMarkerForeground(
inline_text_box_.IsHorizontal());
text_painter.Paint(paint_offsets.first, paint_offsets.second,
- inline_text_box_.Len(), text_style,
- NodeHolder::EmptyNodeHolder());
+ inline_text_box_.Len(), text_style, kInvalidDOMNodeId);
}
void InlineTextBoxPainter::PaintTextMatchMarkerBackground(
diff --git a/chromium/third_party/blink/renderer/core/paint/inline_text_box_painter.h b/chromium/third_party/blink/renderer/core/paint/inline_text_box_painter.h
index 533bc38b2f4..16fca0d2eeb 100644
--- a/chromium/third_party/blink/renderer/core/paint/inline_text_box_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/inline_text_box_painter.h
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/editing/markers/document_marker.h"
#include "third_party/blink/renderer/core/style/computed_style_constants.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/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/largest_contentful_paint_calculator.cc b/chromium/third_party/blink/renderer/core/paint/largest_contentful_paint_calculator.cc
new file mode 100644
index 00000000000..969a3548cb1
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/paint/largest_contentful_paint_calculator.cc
@@ -0,0 +1,162 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/paint/largest_contentful_paint_calculator.h"
+
+#include "third_party/blink/renderer/core/paint/image_element_timing.h"
+
+namespace blink {
+
+namespace {
+bool HasLargestTextChanged(const std::unique_ptr<TextRecord>& a,
+ const base::WeakPtr<TextRecord> b) {
+ if (!a && !b)
+ return false;
+ if (!a && b)
+ return true;
+ if (a && !b)
+ return true;
+ return a->node_id != b->node_id || a->first_size != b->first_size ||
+ a->paint_time != b->paint_time;
+}
+
+bool HasLargestImageChanged(const std::unique_ptr<ImageRecord>& a,
+ const ImageRecord* b) {
+ if (!a && !b)
+ return false;
+ if (!a && b)
+ return true;
+ if (a && !b)
+ return true;
+ return a->node_id != b->node_id || a->first_size != b->first_size ||
+ a->paint_time != b->paint_time || a->load_time != b->load_time;
+}
+} // namespace
+
+LargestContentfulPaintCalculator::LargestContentfulPaintCalculator(
+ WindowPerformance* window_performance)
+ : window_performance_(window_performance) {}
+
+void LargestContentfulPaintCalculator::OnLargestImageUpdated(
+ const ImageRecord* largest_image) {
+ largest_image_.reset();
+ if (largest_image) {
+ largest_image_ = std::make_unique<ImageRecord>();
+ largest_image_->node_id = largest_image->node_id;
+ largest_image_->first_size = largest_image->first_size;
+ largest_image_->paint_time = largest_image->paint_time;
+ largest_image_->cached_image = largest_image->cached_image;
+ largest_image_->load_time = largest_image->load_time;
+ }
+}
+
+void LargestContentfulPaintCalculator::OnLargestTextUpdated(
+ base::WeakPtr<TextRecord> largest_text) {
+ largest_text_.reset();
+ if (largest_text) {
+ largest_text_ = std::make_unique<TextRecord>(
+ largest_text->node_id, largest_text->first_size, FloatRect());
+ largest_text_->paint_time = largest_text->paint_time;
+ }
+}
+
+void LargestContentfulPaintCalculator::UpdateLargestContentPaintIfNeeded(
+ base::Optional<base::WeakPtr<TextRecord>> largest_text,
+ base::Optional<const ImageRecord*> largest_image) {
+ bool image_has_changed = false;
+ bool text_has_changed = false;
+ if (largest_image.has_value()) {
+ image_has_changed = HasLargestImageChanged(largest_image_, *largest_image);
+ OnLargestImageUpdated(*largest_image);
+ }
+ if (largest_text.has_value()) {
+ text_has_changed = HasLargestTextChanged(largest_text_, *largest_text);
+ OnLargestTextUpdated(*largest_text);
+ }
+ // If |largest_image| does not have value, the detector may have been
+ // destroyed. In this case, keep using its last candidate for comparison with
+ // the text candidate. The same for |largest_text|.
+ if ((!largest_image.has_value() || !image_has_changed) &&
+ (!largest_text.has_value() || !text_has_changed))
+ return;
+
+ if (!largest_text_ && !largest_image_)
+ return;
+ if (LargestTextSize() > LargestImageSize()) {
+ if (largest_text_->paint_time > base::TimeTicks())
+ UpdateLargestContentfulPaint(LargestContentType::kText);
+ } else {
+ if (largest_image_->paint_time > base::TimeTicks())
+ UpdateLargestContentfulPaint(LargestContentType::kImage);
+ }
+}
+
+void LargestContentfulPaintCalculator::UpdateLargestContentfulPaint(
+ LargestContentType type) {
+ DCHECK(window_performance_);
+ DCHECK(type != LargestContentType::kUnknown);
+ last_type_ = type;
+ if (type == LargestContentType::kImage) {
+ DCHECK(largest_image_);
+ const ImageResourceContent* cached_image = largest_image_->cached_image;
+ Node* image_node = DOMNodeIds::NodeForId(largest_image_->node_id);
+
+ // |cached_image| is a weak pointer, so it may be null. This can only happen
+ // if the image has been removed, which means that the largest image is not
+ // up-to-date. This can happen when this method call came from
+ // OnLargestTextUpdated(). It is safe to ignore the image in this case: the
+ // correct largest content should be identified on the next call to
+ // OnLargestImageUpdated().
+ // For similar reasons, |image_node| may be null and it is safe to ignore
+ // the |largest_image_| content in this case as well.
+ if (!cached_image || !image_node)
+ return;
+
+ const KURL& url = cached_image->Url();
+ auto* document = window_performance_->GetExecutionContext();
+ bool expose_paint_time_to_api = true;
+ if (!url.ProtocolIsData() &&
+ (!document || !Performance::PassesTimingAllowCheck(
+ cached_image->GetResponse(),
+ *document->GetSecurityOrigin(), document))) {
+ expose_paint_time_to_api = false;
+ }
+ const String& image_url =
+ url.ProtocolIsData()
+ ? url.GetString().Left(ImageElementTiming::kInlineImageMaxChars)
+ : url.GetString();
+ // Do not expose element attribution from shadow trees.
+ Element* image_element =
+ image_node->IsInShadowTree() ? nullptr : To<Element>(image_node);
+ const AtomicString& image_id =
+ image_element ? image_element->GetIdAttribute() : AtomicString();
+ window_performance_->OnLargestContentfulPaintUpdated(
+ expose_paint_time_to_api ? largest_image_->paint_time
+ : base::TimeTicks(),
+ largest_image_->first_size, largest_image_->load_time, image_id,
+ image_url, image_element);
+ } else {
+ DCHECK(largest_text_);
+ Node* text_node = DOMNodeIds::NodeForId(largest_text_->node_id);
+ // |text_node| could be null and |largest_text_| should be ignored in this
+ // case.
+ if (!text_node)
+ return;
+
+ // Do not expose element attribution from shadow trees.
+ Element* text_element =
+ text_node->IsInShadowTree() ? nullptr : To<Element>(text_node);
+ const AtomicString& text_id =
+ text_element ? text_element->GetIdAttribute() : AtomicString();
+ window_performance_->OnLargestContentfulPaintUpdated(
+ largest_text_->paint_time, largest_text_->first_size, base::TimeTicks(),
+ text_id, g_empty_string, text_element);
+ }
+}
+
+void LargestContentfulPaintCalculator::Trace(Visitor* visitor) {
+ visitor->Trace(window_performance_);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/paint/largest_contentful_paint_calculator.h b/chromium/third_party/blink/renderer/core/paint/largest_contentful_paint_calculator.h
new file mode 100644
index 00000000000..5bfe5dc75b3
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/paint/largest_contentful_paint_calculator.h
@@ -0,0 +1,63 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_LARGEST_CONTENTFUL_PAINT_CALCULATOR_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_LARGEST_CONTENTFUL_PAINT_CALCULATOR_H_
+
+#include "third_party/blink/renderer/core/paint/image_paint_timing_detector.h"
+#include "third_party/blink/renderer/core/paint/text_paint_timing_detector.h"
+#include "third_party/blink/renderer/core/timing/window_performance.h"
+
+namespace blink {
+
+// LargestContentfulPaintCalculator is responsible for tracking the largest
+// image paint and the largest text paint and notifying WindowPerformance
+// whenever a new LatestLargestContentfulPaint entry should be dispatched.
+class CORE_EXPORT LargestContentfulPaintCalculator final
+ : public GarbageCollectedFinalized<LargestContentfulPaintCalculator> {
+ public:
+ explicit LargestContentfulPaintCalculator(WindowPerformance*);
+
+ void UpdateLargestContentPaintIfNeeded(
+ base::Optional<base::WeakPtr<TextRecord>> largest_text,
+ base::Optional<const ImageRecord*> largest_image);
+
+ void Trace(blink::Visitor* visitor);
+
+ private:
+ friend class LargestContentfulPaintCalculatorTest;
+
+ enum class LargestContentType {
+ kUnknown,
+ kImage,
+ kText,
+ };
+ void OnLargestImageUpdated(const ImageRecord* largest_image);
+ void OnLargestTextUpdated(base::WeakPtr<TextRecord> largest_text);
+ void UpdateLargestContentfulPaint(LargestContentType type);
+
+ uint64_t LargestTextSize() {
+ return largest_text_ ? largest_text_->first_size : 0u;
+ }
+
+ uint64_t LargestImageSize() {
+ return largest_image_ ? largest_image_->first_size : 0u;
+ }
+
+ Member<WindowPerformance> window_performance_;
+
+ // Largest image information. Stores its own copy of the information so that
+ // the lifetime is not dependent on that of ImagePaintTimingDetector.
+ std::unique_ptr<ImageRecord> largest_image_;
+ // Largest text information. Stores its own copy of the information so that
+ // the lifetime is not dependent on that of TextPaintTimingDetector.
+ std::unique_ptr<TextRecord> largest_text_;
+ LargestContentType last_type_ = LargestContentType::kUnknown;
+
+ DISALLOW_COPY_AND_ASSIGN(LargestContentfulPaintCalculator);
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_LARGEST_CONTENTFUL_PAINT_CALCULATOR_H_
diff --git a/chromium/third_party/blink/renderer/core/paint/largest_contentful_paint_calculator_test.cc b/chromium/third_party/blink/renderer/core/paint/largest_contentful_paint_calculator_test.cc
new file mode 100644
index 00000000000..0173fe5841e
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/paint/largest_contentful_paint_calculator_test.cc
@@ -0,0 +1,276 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/paint/largest_contentful_paint_calculator.h"
+
+#include "base/test/simple_test_tick_clock.h"
+#include "third_party/blink/renderer/core/frame/web_local_frame_impl.h"
+#include "third_party/blink/renderer/core/html/html_image_element.h"
+#include "third_party/blink/renderer/core/paint/paint_timing_detector.h"
+#include "third_party/blink/renderer/core/paint/paint_timing_test_helper.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/skia/include/core/SkImage.h"
+#include "third_party/skia/include/core/SkSurface.h"
+
+namespace blink {
+
+class LargestContentfulPaintCalculatorTest : public RenderingTest {
+ public:
+ using LargestContentType =
+ LargestContentfulPaintCalculator::LargestContentType;
+ void SetUp() override {
+ // Advance the clock so we do not assign null TimeTicks.
+ simulated_clock_.Advance(base::TimeDelta::FromMilliseconds(100));
+ EnableCompositing();
+ RenderingTest::SetUp();
+
+ mock_text_callback_manager_ =
+ MakeGarbageCollected<MockPaintTimingCallbackManager>();
+ GetTextPaintTimingDetector()->ResetCallbackManager(
+ mock_text_callback_manager_);
+ mock_image_callback_manager_ =
+ MakeGarbageCollected<MockPaintTimingCallbackManager>();
+ GetImagePaintTimingDetector()->ResetCallbackManager(
+ mock_image_callback_manager_);
+ }
+
+ ImagePaintTimingDetector* GetImagePaintTimingDetector() {
+ return GetFrame()
+ .View()
+ ->GetPaintTimingDetector()
+ .GetImagePaintTimingDetector();
+ }
+ TextPaintTimingDetector* GetTextPaintTimingDetector() {
+ return GetFrame()
+ .View()
+ ->GetPaintTimingDetector()
+ .GetTextPaintTimingDetector();
+ }
+
+ void SetImage(const char* id, int width, int height) {
+ ToHTMLImageElement(GetDocument().getElementById(id))
+ ->SetImageForTest(CreateImageForTest(width, 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);
+ sk_sp<SkSurface> surface(SkSurface::MakeRaster(raster_image_info));
+ sk_sp<SkImage> image = surface->makeImageSnapshot();
+ ImageResourceContent* original_image_resource =
+ ImageResourceContent::CreateLoaded(
+ StaticBitmapImage::Create(image).get());
+ return original_image_resource;
+ }
+
+ LargestContentType LastReportedType() {
+ return GetLargestContentfulPaintCalculator()->last_type_;
+ }
+
+ uint64_t LargestImageSize() {
+ return GetLargestContentfulPaintCalculator()->LargestImageSize();
+ }
+
+ uint64_t LargestTextSize() {
+ return GetLargestContentfulPaintCalculator()->LargestTextSize();
+ }
+
+ void UpdateLargestContentfulPaintCandidate() {
+ GetFrame()
+ .View()
+ ->GetPaintTimingDetector()
+ .UpdateLargestContentfulPaintCandidate();
+ }
+
+ void SimulateContentSwapPromise() {
+ mock_text_callback_manager_->InvokeSwapTimeCallback(
+ simulated_clock_.NowTicks());
+ mock_image_callback_manager_->InvokeSwapTimeCallback(
+ simulated_clock_.NowTicks());
+ // Outside the tests, this is invoked by
+ // |PaintTimingCallbackManagerImpl::ReportPaintTime|.
+ UpdateLargestContentfulPaintCandidate();
+ }
+
+ // Outside the tests, the text callback and the image callback are run
+ // together, as in |SimulateContentSwapPromise|.
+ void SimulateImageSwapPromise() {
+ mock_image_callback_manager_->InvokeSwapTimeCallback(
+ simulated_clock_.NowTicks());
+ // Outside the tests, this is invoked by
+ // |PaintTimingCallbackManagerImpl::ReportPaintTime|.
+ UpdateLargestContentfulPaintCandidate();
+ }
+
+ // Outside the tests, the text callback and the image callback are run
+ // together, as in |SimulateContentSwapPromise|.
+ void SimulateTextSwapPromise() {
+ mock_text_callback_manager_->InvokeSwapTimeCallback(
+ simulated_clock_.NowTicks());
+ // Outside the tests, this is invoked by
+ // |PaintTimingCallbackManagerImpl::ReportPaintTime|.
+ UpdateLargestContentfulPaintCandidate();
+ }
+
+ private:
+ LargestContentfulPaintCalculator* GetLargestContentfulPaintCalculator() {
+ return GetFrame()
+ .View()
+ ->GetPaintTimingDetector()
+ .GetLargestContentfulPaintCalculator();
+ }
+
+ base::SimpleTestTickClock simulated_clock_;
+ Persistent<MockPaintTimingCallbackManager> mock_text_callback_manager_;
+ Persistent<MockPaintTimingCallbackManager> mock_image_callback_manager_;
+};
+
+TEST_F(LargestContentfulPaintCalculatorTest, SingleImage) {
+ SetBodyInnerHTML(R"HTML(
+ <!DOCTYPE html>
+ <img id='target'/>
+ )HTML");
+ SetImage("target", 100, 150);
+ UpdateAllLifecyclePhasesForTest();
+ SimulateImageSwapPromise();
+
+ EXPECT_EQ(LastReportedType(), LargestContentType::kImage);
+ EXPECT_EQ(LargestImageSize(), 15000u);
+ EXPECT_EQ(LargestTextSize(), 0u);
+}
+
+TEST_F(LargestContentfulPaintCalculatorTest, SingleText) {
+ SetBodyInnerHTML(R"HTML(
+ <!DOCTYPE html>
+ <p>This is some text</p>
+ )HTML");
+ UpdateAllLifecyclePhasesForTest();
+ SimulateTextSwapPromise();
+ EXPECT_EQ(LastReportedType(), LargestContentType::kText);
+}
+
+TEST_F(LargestContentfulPaintCalculatorTest, ImageLargerText) {
+ SetBodyInnerHTML(R"HTML(
+ <!DOCTYPE html>
+ <img id='target'/>
+ <p>This text should be larger than the image!!!!</p>
+ )HTML");
+ SetImage("target", 3, 3);
+ UpdateAllLifecyclePhasesForTest();
+ SimulateImageSwapPromise();
+ EXPECT_EQ(LastReportedType(), LargestContentType::kImage);
+ SimulateTextSwapPromise();
+
+ EXPECT_EQ(LastReportedType(), LargestContentType::kText);
+ EXPECT_EQ(LargestImageSize(), 9u);
+ EXPECT_GT(LargestTextSize(), 9u);
+}
+
+TEST_F(LargestContentfulPaintCalculatorTest, ImageSmallerText) {
+ SetBodyInnerHTML(R"HTML(
+ <!DOCTYPE html>
+ <img id='target'/>
+ <p>.</p>
+ )HTML");
+ SetImage("target", 100, 200);
+ UpdateAllLifecyclePhasesForTest();
+ SimulateImageSwapPromise();
+ EXPECT_EQ(LastReportedType(), LargestContentType::kImage);
+ SimulateTextSwapPromise();
+
+ // Text should not be reported, since it is smaller than the image.
+ EXPECT_EQ(LastReportedType(), LargestContentType::kImage);
+ EXPECT_EQ(LargestImageSize(), 20000u);
+ EXPECT_GT(LargestTextSize(), 0u);
+}
+
+TEST_F(LargestContentfulPaintCalculatorTest, TextLargerImage) {
+ SetBodyInnerHTML(R"HTML(
+ <!DOCTYPE html>
+ <img id='target'/>
+ <p>.</p>
+ )HTML");
+ SetImage("target", 100, 200);
+ UpdateAllLifecyclePhasesForTest();
+ SimulateContentSwapPromise();
+
+ EXPECT_EQ(LastReportedType(), LargestContentType::kImage);
+ EXPECT_EQ(LargestImageSize(), 20000u);
+ EXPECT_GT(LargestTextSize(), 0u);
+}
+
+TEST_F(LargestContentfulPaintCalculatorTest, TextSmallerImage) {
+ SetBodyInnerHTML(R"HTML(
+ <!DOCTYPE html>
+ <img id='target'/>
+ <p>This text should be larger than the image!!!!</p>
+ )HTML");
+ SetImage("target", 3, 3);
+ UpdateAllLifecyclePhasesForTest();
+ SimulateContentSwapPromise();
+
+ // Image should not be reported, since it is smaller than the text.
+ EXPECT_EQ(LastReportedType(), LargestContentType::kText);
+ EXPECT_EQ(LargestImageSize(), 9u);
+ EXPECT_GT(LargestTextSize(), 9u);
+}
+
+TEST_F(LargestContentfulPaintCalculatorTest, LargestImageRemoved) {
+ SetBodyInnerHTML(R"HTML(
+ <!DOCTYPE html>
+ <img id='large'/>
+ <img id='small'/>
+ <p>Larger than the second image</p>
+ )HTML");
+ SetImage("large", 100, 200);
+ SetImage("small", 3, 3);
+ UpdateAllLifecyclePhasesForTest();
+ SimulateImageSwapPromise();
+ SimulateTextSwapPromise();
+ // Image is larger than the text.
+ EXPECT_EQ(LastReportedType(), LargestContentType::kImage);
+ EXPECT_EQ(LargestImageSize(), 20000u);
+ EXPECT_GT(LargestTextSize(), 9u);
+
+ GetDocument().getElementById("large")->remove();
+ UpdateAllLifecyclePhasesForTest();
+ // The LCP should now be the text because it is larger than the remaining
+ // image.
+ EXPECT_EQ(LastReportedType(), LargestContentType::kText);
+ EXPECT_EQ(LargestImageSize(), 9u);
+ EXPECT_GT(LargestTextSize(), 9u);
+}
+
+TEST_F(LargestContentfulPaintCalculatorTest, LargestTextRemoved) {
+ SetBodyInnerHTML(R"HTML(
+ <!DOCTYPE html>
+ <img id='medium'/>
+ <p id='large'>
+ This text element should be larger than than the image!\n
+ These words ensure that this is the case.\n
+ But the image will be larger than the other paragraph!
+ </p>
+ <p id='small'>.</p>
+ )HTML");
+ SetImage("medium", 10, 5);
+ UpdateAllLifecyclePhasesForTest();
+ SimulateImageSwapPromise();
+ SimulateTextSwapPromise();
+ // Test is larger than the image.
+ EXPECT_EQ(LastReportedType(), LargestContentType::kText);
+ EXPECT_EQ(LargestImageSize(), 50u);
+ EXPECT_GT(LargestTextSize(), 50u);
+
+ GetDocument().getElementById("large")->remove();
+ UpdateAllLifecyclePhasesForTest();
+ // The LCP should now be the image because it is larger than the remaining
+ // text.
+ EXPECT_EQ(LastReportedType(), LargestContentType::kImage);
+ EXPECT_EQ(LargestImageSize(), 50u);
+ EXPECT_LT(LargestTextSize(), 50u);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/paint/layout_object_counter.h b/chromium/third_party/blink/renderer/core/paint/layout_object_counter.h
index 23441219a71..fdd37beae0e 100644
--- a/chromium/third_party/blink/renderer/core/paint/layout_object_counter.h
+++ b/chromium/third_party/blink/renderer/core/paint/layout_object_counter.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_LAYOUT_OBJECT_COUNTER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_LAYOUT_OBJECT_COUNTER_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/line_box_list_painter.cc b/chromium/third_party/blink/renderer/core/paint/line_box_list_painter.cc
index 577aa568fc7..58aa23f95a5 100644
--- a/chromium/third_party/blink/renderer/core/paint/line_box_list_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/line_box_list_painter.cc
@@ -19,14 +19,13 @@ namespace blink {
static void AddPDFURLRectsForInlineChildrenRecursively(
const LayoutObject& layout_object,
const PaintInfo& paint_info,
- const LayoutPoint& paint_offset) {
+ const PhysicalOffset& paint_offset) {
for (LayoutObject* child = layout_object.SlowFirstChild(); child;
child = child->NextSibling()) {
if (!child->IsLayoutInline() ||
ToLayoutBoxModelObject(child)->HasSelfPaintingLayer())
continue;
- ObjectPainter(*child).AddPDFURLRectIfNeeded(
- paint_info, PhysicalOffsetToBeNoop(paint_offset));
+ ObjectPainter(*child).AddPDFURLRectIfNeeded(paint_info, paint_offset);
AddPDFURLRectsForInlineChildrenRecursively(*child, paint_info,
paint_offset);
}
@@ -34,7 +33,7 @@ static void AddPDFURLRectsForInlineChildrenRecursively(
void LineBoxListPainter::Paint(const LayoutBoxModelObject& layout_object,
const PaintInfo& paint_info,
- const LayoutPoint& paint_offset) const {
+ const PhysicalOffset& paint_offset) const {
DCHECK(!ShouldPaintSelfOutline(paint_info.phase) &&
!ShouldPaintDescendantOutlines(paint_info.phase));
@@ -83,7 +82,8 @@ void LineBoxListPainter::Paint(const LayoutBoxModelObject& layout_object,
const_cast<LayoutBoxModelObject*>(&layout_object)),
curr, paint_info.GetCullRect(), paint_offset)) {
RootInlineBox& root = curr->Root();
- curr->Paint(paint_info, paint_offset, root.LineTop(), root.LineBottom());
+ curr->Paint(paint_info, paint_offset.ToLayoutPoint(), root.LineTop(),
+ root.LineBottom());
}
}
}
diff --git a/chromium/third_party/blink/renderer/core/paint/line_box_list_painter.h b/chromium/third_party/blink/renderer/core/paint/line_box_list_painter.h
index d2d4b46f4fd..9377a43820c 100644
--- a/chromium/third_party/blink/renderer/core/paint/line_box_list_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/line_box_list_painter.h
@@ -6,14 +6,14 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_LINE_BOX_LIST_PAINTER_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/allocator/allocator.h"
namespace blink {
-class LayoutPoint;
-struct PaintInfo;
class LayoutBoxModelObject;
class LineBoxList;
+struct PaintInfo;
+struct PhysicalOffset;
class LineBoxListPainter {
STACK_ALLOCATED();
@@ -24,7 +24,7 @@ class LineBoxListPainter {
void Paint(const LayoutBoxModelObject&,
const PaintInfo&,
- const LayoutPoint& paint_offset) const;
+ const PhysicalOffset& paint_offset) const;
private:
const LineBoxList& line_box_list_;
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 9f0eecf6a74..2fd5f1c50bf 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
@@ -58,6 +58,7 @@
#include "third_party/blink/renderer/platform/graphics/paint/foreign_layer_display_item.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/graphics/paint/transform_paint_property_node.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"
@@ -71,9 +72,19 @@ static constexpr float kStartOpacity = 1;
namespace {
-float HighlightTargetOpacity() {
- // For web tests we don't fade out.
- return WebTestSupport::IsRunningWebTest() ? kStartOpacity : 0;
+EffectPaintPropertyNode::State LinkHighlightEffectNodeState(
+ float opacity,
+ CompositorElementId element_id) {
+ EffectPaintPropertyNode::State state;
+ state.opacity = opacity;
+ state.local_transform_space = &TransformPaintPropertyNode::Root();
+ state.compositor_element_id = element_id;
+ state.direct_compositing_reasons = CompositingReason::kActiveOpacityAnimation;
+ // EffectPaintPropertyNode::Update does not pay attention to changes in
+ // has_active_opacity_animation so we assume that the effect node is
+ // always animating.
+ state.has_active_opacity_animation = true;
+ return state;
}
} // namespace
@@ -94,7 +105,7 @@ LinkHighlightImpl::LinkHighlightImpl(Node* node)
offset_from_transform_node_(FloatPoint()),
geometry_needs_update_(false),
is_animating_(false),
- start_time_(CurrentTimeTicks()),
+ start_time_(base::TimeTicks::Now()),
element_id_(NewElementId()) {
DCHECK(node_);
fragments_.emplace_back();
@@ -111,14 +122,9 @@ LinkHighlightImpl::LinkHighlightImpl(Node* node)
compositor_animation_->AttachElement(element_id_);
geometry_needs_update_ = true;
- EffectPaintPropertyNode::State state;
- state.opacity = HighlightTargetOpacity();
- state.local_transform_space = &TransformPaintPropertyNode::Root();
- state.compositor_element_id = element_id_;
- state.direct_compositing_reasons = CompositingReason::kActiveOpacityAnimation;
- state.has_active_opacity_animation = true;
- effect_ = EffectPaintPropertyNode::Create(EffectPaintPropertyNode::Root(),
- std::move(state));
+ effect_ = EffectPaintPropertyNode::Create(
+ EffectPaintPropertyNode::Root(),
+ LinkHighlightEffectNodeState(kStartOpacity, element_id_));
#if DCHECK_IS_ON()
effect_->SetDebugName("LinkHighlightEffect");
#endif
@@ -346,27 +352,36 @@ void LinkHighlightImpl::StartHighlightAnimationIfNeeded() {
is_animating_ = true;
// FIXME: Should duration be configurable?
- constexpr auto kFadeDuration = TimeDelta::FromMilliseconds(100);
- constexpr auto kMinPreFadeDuration = TimeDelta::FromMilliseconds(100);
+ constexpr auto kFadeDuration = base::TimeDelta::FromMilliseconds(100);
+ constexpr auto kMinPreFadeDuration = base::TimeDelta::FromMilliseconds(100);
auto curve = std::make_unique<CompositorFloatAnimationCurve>();
const auto& timing_function = *CubicBezierTimingFunction::Preset(
CubicBezierTimingFunction::EaseType::EASE);
+ float target_opacity = WebTestSupport::IsRunningWebTest() ? kStartOpacity : 0;
+
+ // Since the notification about the animation finishing may not arrive in
+ // time to remove the link highlight before it's drawn without an animation
+ // we set the opacity to the final target opacity to avoid a flash of the
+ // initial opacity. https://crbug.com/974160
+ UpdateOpacity(target_opacity);
+
curve->AddKeyframe(
CompositorFloatKeyframe(0, kStartOpacity, timing_function));
// Make sure we have displayed for at least minPreFadeDuration before starting
// to fade out.
- TimeDelta extra_duration_required = std::max(
- TimeDelta(), kMinPreFadeDuration - (CurrentTimeTicks() - start_time_));
+ base::TimeDelta extra_duration_required =
+ std::max(base::TimeDelta(),
+ kMinPreFadeDuration - (base::TimeTicks::Now() - start_time_));
if (!extra_duration_required.is_zero()) {
curve->AddKeyframe(CompositorFloatKeyframe(
extra_duration_required.InSecondsF(), kStartOpacity, timing_function));
}
curve->AddKeyframe(CompositorFloatKeyframe(
- (kFadeDuration + extra_duration_required).InSecondsF(),
- HighlightTargetOpacity(), timing_function));
+ (kFadeDuration + extra_duration_required).InSecondsF(), target_opacity,
+ timing_function));
auto keyframe_model = std::make_unique<CompositorKeyframeModel>(
*curve, compositor_target_property::OPACITY, 0, 0);
@@ -390,12 +405,17 @@ void LinkHighlightImpl::NotifyAnimationFinished(double, int) {
// release resources as soon as possible.
ClearGraphicsLayerLinkHighlightPointer();
ReleaseResources();
+
+ // Reset the link highlight opacity to clean up after the animation now that
+ // we have removed the node and it won't be displayed.
+ UpdateOpacity(kStartOpacity);
}
void LinkHighlightImpl::UpdateGeometry() {
DCHECK(!RuntimeEnabledFeatures::CompositeAfterPaintEnabled());
- if (!node_ || !node_->GetLayoutObject()) {
+ if (!node_ || !node_->GetLayoutObject() ||
+ node_->GetLayoutObject()->GetFrameView()->ShouldThrottleRendering()) {
ClearGraphicsLayerLinkHighlightPointer();
ReleaseResources();
return;
@@ -452,7 +472,8 @@ const EffectPaintPropertyNode& LinkHighlightImpl::Effect() const {
void LinkHighlightImpl::Paint(GraphicsContext& context) {
DCHECK(RuntimeEnabledFeatures::CompositeAfterPaintEnabled());
- if (!node_ || !node_->GetLayoutObject()) {
+ if (!node_ || !node_->GetLayoutObject() ||
+ node_->GetLayoutObject()->GetFrameView()->ShouldThrottleRendering()) {
ReleaseResources();
return;
}
@@ -531,4 +552,9 @@ void LinkHighlightImpl::SetPaintArtifactCompositorNeedsUpdate() {
}
}
+void LinkHighlightImpl::UpdateOpacity(float opacity) {
+ effect_->Update(EffectPaintPropertyNode::Root(),
+ LinkHighlightEffectNodeState(opacity, element_id_));
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/paint/link_highlight_impl.h b/chromium/third_party/blink/renderer/core/paint/link_highlight_impl.h
index 3da67481df5..cc2ff982c42 100644
--- a/chromium/third_party/blink/renderer/core/paint/link_highlight_impl.h
+++ b/chromium/third_party/blink/renderer/core/paint/link_highlight_impl.h
@@ -102,17 +102,21 @@ class CORE_EXPORT LinkHighlightImpl final : public LinkHighlight,
}
private:
- void ReleaseResources();
- void ComputeQuads(const Node&, Vector<FloatQuad>&) const;
+ // TODO(crbug.com/967281): These NOINLINEs are for more accurate crash stack
+ // in the crash reports.
+ NOINLINE void ReleaseResources();
+ NOINLINE void ComputeQuads(const Node&, Vector<FloatQuad>&) const;
- void AttachLinkHighlightToCompositingLayer(
+ NOINLINE void AttachLinkHighlightToCompositingLayer(
const LayoutBoxModelObject& paint_invalidation_container);
- void ClearGraphicsLayerLinkHighlightPointer();
+ NOINLINE void ClearGraphicsLayerLinkHighlightPointer();
// This function computes the highlight path, and returns true if it has
// changed size since the last call to this function.
- bool ComputeHighlightLayerPathAndPosition(const LayoutBoxModelObject&);
+ NOINLINE bool ComputeHighlightLayerPathAndPosition(
+ const LayoutBoxModelObject&);
void SetPaintArtifactCompositorNeedsUpdate();
+ void UpdateOpacity(float opacity);
class LinkHighlightFragment : private cc::ContentLayerClient {
public:
@@ -147,7 +151,7 @@ class CORE_EXPORT LinkHighlightImpl final : public LinkHighlight,
bool geometry_needs_update_;
bool is_animating_;
- TimeTicks start_time_;
+ base::TimeTicks start_time_;
CompositorElementId element_id_;
};
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 0c7b4deeb14..e4b7e0b8616 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
@@ -56,6 +56,7 @@
#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"
+#include "third_party/blink/renderer/platform/web_test_support.h"
namespace blink {
@@ -264,7 +265,7 @@ TEST_P(LinkHighlightImplTest, HighlightInvalidation) {
WebGestureDevice::kTouchscreen);
touch_event.SetPositionInWidget(WebFloatPoint(20, 20));
GestureEventWithHitTestResults targeted_event = GetTargetedEvent(touch_event);
- auto* touch_element = ToElement(web_view_impl->BestTapNode(targeted_event));
+ auto* touch_element = To<Element>(web_view_impl->BestTapNode(targeted_event));
web_view_impl->EnableTapHighlightAtPoint(targeted_event);
web_view_helper_.LocalMainFrame()
@@ -294,6 +295,8 @@ TEST_P(LinkHighlightImplTest, HighlightLayerEffectNode) {
!RuntimeEnabledFeatures::CompositeAfterPaintEnabled())
return;
+ bool was_running_web_test = WebTestSupport::IsRunningWebTest();
+ WebTestSupport::SetIsRunningWebTest(false);
int page_width = 640;
int page_height = 480;
WebViewImpl* web_view_impl = web_view_helper_.GetWebView();
@@ -317,7 +320,7 @@ TEST_P(LinkHighlightImplTest, HighlightLayerEffectNode) {
// The highlight should create one additional layer.
EXPECT_EQ(layer_count_before_highlight + 1, ContentLayerCount());
- const auto& highlights = web_view_impl->GetPage()->GetLinkHighlights();
+ auto& highlights = web_view_impl->GetPage()->GetLinkHighlights();
auto* highlight = highlights.link_highlights_.at(0).get();
ASSERT_TRUE(highlight);
@@ -336,12 +339,25 @@ TEST_P(LinkHighlightImplTest, HighlightLayerEffectNode) {
// node.
EXPECT_EQ(highlight->Effect().GetCompositorElementId(),
highlight->ElementIdForTesting());
+
+ // Initially the highlight node has full opacity as it is expected to remain
+ // visible until the user completes a tap. See https://crbug.com/974631
+ EXPECT_EQ(1.f, highlight->Effect().Opacity());
+ EXPECT_TRUE(highlight->Effect().HasActiveOpacityAnimation());
+
+ // After starting the highlight animation the effect node's opacity should
+ // be 0.f as it will be overridden bt the animation but may become visible
+ // before the animation is destructed. See https://crbug.com/974160
+ highlights.StartHighlightAnimationIfNeeded();
+ EXPECT_EQ(0.f, highlight->Effect().Opacity());
EXPECT_TRUE(highlight->Effect().HasActiveOpacityAnimation());
touch_node->remove(IGNORE_EXCEPTION_FOR_TESTING);
UpdateAllLifecyclePhases();
// Removing the highlight layer should drop the cc layer count by one.
EXPECT_EQ(layer_count_before_highlight, ContentLayerCount());
+
+ WebTestSupport::SetIsRunningWebTest(was_running_web_test);
}
TEST_P(LinkHighlightImplTest, MultiColumn) {
diff --git a/chromium/third_party/blink/renderer/core/paint/list_item_painter.h b/chromium/third_party/blink/renderer/core/paint/list_item_painter.h
index 8264747c009..2ea53d0a285 100644
--- a/chromium/third_party/blink/renderer/core/paint/list_item_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/list_item_painter.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_LIST_ITEM_PAINTER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_LIST_ITEM_PAINTER_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 38c587c46b3..5c2c56f4733 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
@@ -165,19 +165,17 @@ void ListMarkerPainter::Paint(const PaintInfo& paint_info) {
TextRunPaintInfo suffix_run_info(suffix_run);
if (layout_list_marker_.StyleRef().IsLeftToRightDirection()) {
- context.DrawText(font, text_run_paint_info, text_origin,
- NodeHolder::EmptyNodeHolder());
+ context.DrawText(font, text_run_paint_info, text_origin, kInvalidDOMNodeId);
context.DrawText(font, suffix_run_info,
text_origin + FloatSize(IntSize(font.Width(text_run), 0)),
- NodeHolder::EmptyNodeHolder());
+ kInvalidDOMNodeId);
} else {
- context.DrawText(font, suffix_run_info, text_origin,
- NodeHolder::EmptyNodeHolder());
+ context.DrawText(font, suffix_run_info, text_origin, kInvalidDOMNodeId);
// Is the truncation to IntSize below meaningful or a bug?
context.DrawText(
font, text_run_paint_info,
text_origin + FloatSize(IntSize(font.Width(suffix_run), 0)),
- NodeHolder::EmptyNodeHolder());
+ kInvalidDOMNodeId);
}
// TODO(npm): Check that there are non-whitespace characters. See
// crbug.com/788444.
diff --git a/chromium/third_party/blink/renderer/core/paint/list_marker_painter.h b/chromium/third_party/blink/renderer/core/paint/list_marker_painter.h
index fb39379adad..86c2023c7d2 100644
--- a/chromium/third_party/blink/renderer/core/paint/list_marker_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/list_marker_painter.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_LIST_MARKER_PAINTER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_LIST_MARKER_PAINTER_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/multi_column_set_painter.h b/chromium/third_party/blink/renderer/core/paint/multi_column_set_painter.h
index 065ae54aa7b..9b8e2ec361a 100644
--- a/chromium/third_party/blink/renderer/core/paint/multi_column_set_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/multi_column_set_painter.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_MULTI_COLUMN_SET_PAINTER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_MULTI_COLUMN_SET_PAINTER_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 098a44808a2..72be98d003a 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
@@ -54,12 +54,19 @@ LayoutRectOutsets BoxStrutToLayoutRectOutsets(
LayoutUnit(box_strut.bottom), LayoutUnit(box_strut.left));
}
-bool FragmentVisibleToHitTestRequest(const NGPaintFragment& fragment,
+inline bool IsVisibleToPaint(const NGPhysicalFragment& fragment,
+ const ComputedStyle& style) {
+ return !fragment.IsHiddenForPaint() &&
+ style.Visibility() == EVisibility::kVisible;
+}
+
+bool FragmentVisibleToHitTestRequest(const NGPaintFragment& paint_fragment,
const HitTestRequest& request) {
- return fragment.Style().Visibility() == EVisibility::kVisible &&
+ const NGPhysicalFragment& fragment = paint_fragment.PhysicalFragment();
+ const ComputedStyle& style = fragment.Style();
+ return IsVisibleToPaint(fragment, style) &&
(request.IgnorePointerEventsNone() ||
- fragment.Style().PointerEvents() != EPointerEvents::kNone) &&
- !(fragment.GetNode() && fragment.GetNode()->IsInert());
+ style.PointerEvents() != EPointerEvents::kNone);
}
// Hit tests inline ancestor elements of |fragment| who do not have their own
@@ -68,15 +75,15 @@ bool FragmentVisibleToHitTestRequest(const NGPaintFragment& fragment,
bool HitTestCulledInlineAncestors(HitTestResult& result,
const NGPaintFragment& fragment,
const NGPaintFragment* previous_sibling,
- const HitTestLocation& location_in_container,
- const LayoutPoint& physical_offset) {
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& physical_offset) {
DCHECK(fragment.Parent());
DCHECK(fragment.PhysicalFragment().IsInline());
const NGPaintFragment& parent = *fragment.Parent();
// To be passed as |accumulated_offset| to LayoutInline::HitTestCulledInline,
// where it equals the physical offset of the containing block in paint layer.
- const LayoutPoint fallback_accumulated_offset =
- physical_offset - fragment.InlineOffsetToContainerBox().ToLayoutSize();
+ const PhysicalOffset fallback_accumulated_offset =
+ physical_offset - fragment.InlineOffsetToContainerBox();
const LayoutObject* limit_layout_object =
parent.PhysicalFragment().IsLineBox() ? parent.Parent()->GetLayoutObject()
: parent.GetLayoutObject();
@@ -105,7 +112,7 @@ bool HitTestCulledInlineAncestors(HitTestResult& result,
if (culled_parent->IsLayoutInline() &&
ToLayoutInline(culled_parent)
- ->HitTestCulledInline(result, location_in_container,
+ ->HitTestCulledInline(result, hit_test_location,
fallback_accumulated_offset, &parent))
return true;
@@ -185,15 +192,18 @@ void NGBoxFragmentPainter::PaintInternal(const PaintInfo& paint_info) {
PaintObject(info, paint_offset);
}
- // Our scrollbar widgets paint exactly when we tell them to, so that they work
- // properly with z-index. We paint after we painted the background/border, so
- // that the scrollbars will sit above the background/border.
+ // We paint scrollbars after we painted other things, so that the scrollbars
+ // will sit above them.
info.phase = original_phase;
- PaintOverflowControlsIfNeeded(info, paint_offset);
+ if (box_fragment_.HasOverflowClip()) {
+ ScrollableAreaPainter(*PhysicalFragment().Layer()->GetScrollableArea())
+ .PaintOverflowControls(info, RoundedIntPoint(paint_offset));
+ }
}
-void NGBoxFragmentPainter::RecordHitTestData(const PaintInfo& paint_info,
- const LayoutPoint& paint_offset) {
+void NGBoxFragmentPainter::RecordHitTestData(
+ const PaintInfo& paint_info,
+ const PhysicalOffset& paint_offset) {
const NGPhysicalFragment& physical_fragment = PhysicalFragment();
// 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
@@ -203,7 +213,7 @@ void NGBoxFragmentPainter::RecordHitTestData(const PaintInfo& paint_info,
PhysicalRect border_box = physical_fragment.LocalRect();
if (physical_fragment.IsInline())
border_box.offset += box_fragment_.InlineOffsetToContainerBox();
- border_box.offset += PhysicalOffsetToBeNoop(paint_offset);
+ border_box.offset += paint_offset;
HitTestDisplayItem::Record(
paint_info.context, box_fragment_,
HitTestRect(border_box.ToLayoutRect(),
@@ -212,10 +222,10 @@ void NGBoxFragmentPainter::RecordHitTestData(const PaintInfo& paint_info,
void NGBoxFragmentPainter::RecordHitTestDataForLine(
const PaintInfo& paint_info,
- const LayoutPoint& paint_offset,
+ const PhysicalOffset& paint_offset,
const NGPaintFragment& line) {
PhysicalRect border_box = line.PhysicalFragment().LocalRect();
- border_box.offset += PhysicalOffsetToBeNoop(paint_offset);
+ border_box.offset += paint_offset;
HitTestDisplayItem::Record(
paint_info.context, line,
HitTestRect(border_box.ToLayoutRect(),
@@ -229,7 +239,7 @@ void NGBoxFragmentPainter::PaintObject(
const PaintPhase paint_phase = paint_info.phase;
const NGPhysicalBoxFragment& physical_box_fragment = PhysicalFragment();
const ComputedStyle& style = box_fragment_.Style();
- bool is_visible = style.Visibility() == EVisibility::kVisible;
+ bool is_visible = IsVisibleToPaint(physical_box_fragment, style);
if (ShouldPaintSelfBlockBackground(paint_phase)) {
if (!suppress_box_decoration_background && is_visible)
@@ -237,7 +247,7 @@ void NGBoxFragmentPainter::PaintObject(
if (NGFragmentPainter::ShouldRecordHitTestData(paint_info,
physical_box_fragment))
- RecordHitTestData(paint_info, paint_offset.ToLayoutPoint());
+ 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
@@ -357,7 +367,7 @@ void NGBoxFragmentPainter::PaintBlockChildren(const PaintInfo& paint_info) {
NGBoxFragmentPainter(*child).Paint(paint_info);
} else {
DCHECK(fragment.Type() == NGPhysicalFragment::kFragmentRenderedLegend)
- << fragment.ToString();
+ << fragment;
}
}
}
@@ -406,8 +416,9 @@ void NGBoxFragmentPainter::PaintFloats(const PaintInfo& paint_info) {
void NGBoxFragmentPainter::PaintMask(const PaintInfo& paint_info,
const PhysicalOffset& paint_offset) {
DCHECK_EQ(PaintPhase::kMask, paint_info.phase);
- const ComputedStyle& style = box_fragment_.Style();
- if (!style.HasMask() || style.Visibility() != EVisibility::kVisible)
+ const NGPhysicalBoxFragment& physical_box_fragment = PhysicalFragment();
+ const ComputedStyle& style = physical_box_fragment.Style();
+ if (!style.HasMask() || !IsVisibleToPaint(physical_box_fragment, style))
return;
if (DrawingRecorder::UseCachedDrawingIfPossible(
@@ -761,8 +772,7 @@ void NGBoxFragmentPainter::PaintLineBoxChildren(
if (paint_info.phase == PaintPhase::kForeground) {
if (NGFragmentPainter::ShouldRecordHitTestData(paint_info,
PhysicalFragment())) {
- RecordHitTestDataForLine(paint_info, child_offset.ToLayoutPoint(),
- *line);
+ RecordHitTestDataForLine(paint_info, child_offset, *line);
}
// Line boxes don't paint anything, except when its ::first-line style has
@@ -789,13 +799,14 @@ void NGBoxFragmentPainter::PaintInlineChildren(
for (const NGPaintFragment* child : inline_children) {
const NGPhysicalFragment& child_fragment = child->PhysicalFragment();
+ if (child_fragment.IsHiddenForPaint())
+ continue;
if (child_fragment.IsFloating())
continue;
// Skip if this child does not intersect with CullRect.
- if (!paint_info.GetCullRect().Intersects(
- child->InkOverflow().ToLayoutRect(),
- (paint_offset + child->Offset()).ToLayoutPoint()) &&
+ if (!paint_info.IntersectsCullRect(child->InkOverflow(),
+ paint_offset + child->Offset()) &&
// Don't skip empty size text in order to paint selection for <br>.
!(child_fragment.IsText() && child_fragment.Size().IsEmpty()))
continue;
@@ -847,14 +858,14 @@ void NGBoxFragmentPainter::PaintTextChild(const NGPaintFragment& paint_fragment,
const auto& text_fragment =
To<NGPhysicalTextFragment>(paint_fragment.PhysicalFragment());
- NodeHolder node_holder;
+ DOMNodeId node_id = kInvalidDOMNodeId;
if (auto* node = text_fragment.GetNode()) {
if (node->GetLayoutObject()->IsText())
- node_holder = ToLayoutText(node->GetLayoutObject())->EnsureNodeHolder();
+ node_id = ToLayoutText(node->GetLayoutObject())->EnsureNodeId();
}
NGTextFragmentPainter text_painter(paint_fragment);
- text_painter.Paint(paint_info, paint_offset, node_holder);
+ text_painter.Paint(paint_info, paint_offset, node_id);
}
void NGBoxFragmentPainter::PaintAtomicInline(const PaintInfo& paint_info) {
@@ -881,19 +892,6 @@ bool NGBoxFragmentPainter::IsPaintingScrollingBackground(
box_fragment_.GetLayoutObject() == paint_info.PaintContainer();
}
-// Clone of BlockPainter::PaintOverflowControlsIfNeeded
-void NGBoxFragmentPainter::PaintOverflowControlsIfNeeded(
- const PaintInfo& paint_info,
- const PhysicalOffset& paint_offset) {
- if (box_fragment_.HasOverflowClip() &&
- box_fragment_.Style().Visibility() == EVisibility::kVisible &&
- ShouldPaintSelfBlockBackground(paint_info.phase)) {
- ScrollableAreaPainter(*PhysicalFragment().Layer()->GetScrollableArea())
- .PaintOverflowControls(paint_info, RoundedIntPoint(paint_offset),
- false /* painting_overlay_controls */);
- }
-}
-
bool NGBoxFragmentPainter::ShouldPaint(
const ScopedPaintState& paint_state) const {
// TODO(layout-dev): Add support for scrolling, see BlockPainter::ShouldPaint.
@@ -983,14 +981,12 @@ bool NGBoxFragmentPainter::IsInSelfHitTestingPhase(HitTestAction action) const {
return action == kHitTestForeground;
}
-bool NGBoxFragmentPainter::NodeAtPoint(
- HitTestResult& result,
- const HitTestLocation& location_in_container,
- const LayoutPoint& physical_offset,
- HitTestAction action) {
+bool NGBoxFragmentPainter::NodeAtPoint(HitTestResult& result,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& physical_offset,
+ HitTestAction action) {
const NGPhysicalBoxFragment& fragment = PhysicalFragment();
- // TODO(eae): Switch to using NG geometry types.
- LayoutSize size(box_fragment_.Size().width, box_fragment_.Size().height);
+ const PhysicalSize& size = box_fragment_.Size();
const ComputedStyle& style = box_fragment_.Style();
bool hit_test_self = IsInSelfHitTestingPhase(action);
@@ -998,7 +994,7 @@ bool NGBoxFragmentPainter::NodeAtPoint(
// TODO(layout-dev): Add support for hit testing overflow controls once we
// overflow has been implemented.
// if (hit_test_self && HasOverflowClip() &&
- // HitTestOverflowControl(result, location_in_container, physical_offset))
+ // HitTestOverflowControl(result, hit_test_location, physical_offset))
// return true;
bool skip_children = result.GetHitTestRequest().GetStopNode() ==
@@ -1008,55 +1004,52 @@ bool NGBoxFragmentPainter::NodeAtPoint(
// foreground rect for intersection if a layer is self painting,
// so only do the overflow clip check here for non-self-painting layers.
if (!box_fragment_.HasSelfPaintingLayer() &&
- !location_in_container.Intersects(
- PhysicalFragment()
- .OverflowClipRect(PhysicalOffsetToBeNoop(physical_offset),
- kExcludeOverlayScrollbarSizeForHitTesting)
- .ToLayoutRect())) {
+ !hit_test_location.Intersects(PhysicalFragment().OverflowClipRect(
+ physical_offset, kExcludeOverlayScrollbarSizeForHitTesting))) {
skip_children = true;
}
if (!skip_children && style.HasBorderRadius()) {
- LayoutRect bounds_rect(physical_offset, size);
- skip_children = !location_in_container.Intersects(
- style.GetRoundedInnerBorderFor(bounds_rect));
+ PhysicalRect bounds_rect(physical_offset, size);
+ skip_children = !hit_test_location.Intersects(
+ style.GetRoundedInnerBorderFor(bounds_rect.ToLayoutRect()));
}
}
if (!skip_children) {
- const IntSize scrolled_offset =
- box_fragment_.HasOverflowClip()
- ? PhysicalFragment().ScrolledContentOffset()
- : IntSize();
- if (HitTestChildren(result, box_fragment_.Children(), location_in_container,
- physical_offset - scrolled_offset, action)) {
+ PhysicalOffset scrolled_offset = physical_offset;
+ if (box_fragment_.HasOverflowClip()) {
+ scrolled_offset -=
+ PhysicalOffset(PhysicalFragment().ScrolledContentOffset());
+ }
+ if (HitTestChildren(result, box_fragment_.Children(), hit_test_location,
+ scrolled_offset, action)) {
return true;
}
}
if (style.HasBorderRadius() &&
- HitTestClippedOutByBorder(location_in_container, physical_offset))
+ HitTestClippedOutByBorder(hit_test_location, physical_offset))
return false;
// Now hit test ourselves.
if (hit_test_self && VisibleToHitTestRequest(result.GetHitTestRequest())) {
- LayoutRect bounds_rect(physical_offset, size);
+ PhysicalRect bounds_rect(physical_offset, size);
if (UNLIKELY(result.GetHitTestRequest().GetType() &
HitTestRequest::kHitTestVisualOverflow)) {
- bounds_rect = box_fragment_.SelfInkOverflow().ToLayoutRect();
- bounds_rect.MoveBy(physical_offset);
+ bounds_rect = box_fragment_.SelfInkOverflow();
+ bounds_rect.Move(physical_offset);
}
// TODO(kojii): Don't have good explanation why only inline box needs to
// snap, but matches to legacy and fixes crbug.com/976606.
if (fragment.IsInlineBox())
- bounds_rect = LayoutRect(PixelSnappedIntRect(bounds_rect));
- if (location_in_container.Intersects(bounds_rect)) {
+ bounds_rect = PhysicalRect(PixelSnappedIntRect(bounds_rect));
+ if (hit_test_location.Intersects(bounds_rect)) {
Node* node = box_fragment_.NodeForHitTest();
if (!result.InnerNode() && node) {
- LayoutPoint point =
- location_in_container.Point() - ToLayoutSize(physical_offset);
- result.SetNodeAndPosition(node, PhysicalOffsetToBeNoop(point));
+ PhysicalOffset point = hit_test_location.Point() - physical_offset;
+ result.SetNodeAndPosition(node, point);
}
- if (result.AddNodeToListBasedTestResult(node, location_in_container,
+ if (result.AddNodeToListBasedTestResult(node, hit_test_location,
bounds_rect) == kStopHitTesting) {
return true;
}
@@ -1074,38 +1067,37 @@ bool NGBoxFragmentPainter::VisibleToHitTestRequest(
bool NGBoxFragmentPainter::HitTestTextFragment(
HitTestResult& result,
const NGPaintFragment& text_paint_fragment,
- const HitTestLocation& location_in_container,
- const LayoutPoint& physical_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& physical_offset,
HitTestAction action) {
if (action != kHitTestForeground)
return false;
const auto& text_fragment =
To<NGPhysicalTextFragment>(text_paint_fragment.PhysicalFragment());
- LayoutSize size(text_fragment.Size().width, text_fragment.Size().height);
- LayoutRect border_rect(physical_offset, size);
+ PhysicalSize size(text_fragment.Size().width, text_fragment.Size().height);
+ PhysicalRect border_rect(physical_offset, size);
// TODO(layout-dev): Clip to line-top/bottom.
- LayoutRect rect = LayoutRect(PixelSnappedIntRect(border_rect));
+ PhysicalRect rect(PixelSnappedIntRect(border_rect));
if (UNLIKELY(result.GetHitTestRequest().GetType() &
HitTestRequest::kHitTestVisualOverflow)) {
- rect = text_fragment.SelfInkOverflow().ToLayoutRect();
- rect.MoveBy(border_rect.Location());
+ rect = text_fragment.SelfInkOverflow();
+ rect.Move(border_rect.offset);
}
if (FragmentVisibleToHitTestRequest(text_paint_fragment,
result.GetHitTestRequest()) &&
- location_in_container.Intersects(rect)) {
+ hit_test_location.Intersects(rect)) {
Node* node = text_paint_fragment.NodeForHitTest();
if (!result.InnerNode() && node) {
- LayoutPoint point =
- location_in_container.Point() - ToLayoutSize(physical_offset) +
- text_paint_fragment.InlineOffsetToContainerBox().ToLayoutPoint();
- result.SetNodeAndPosition(node, PhysicalOffsetToBeNoop(point));
+ PhysicalOffset point = hit_test_location.Point() - physical_offset +
+ text_paint_fragment.InlineOffsetToContainerBox();
+ result.SetNodeAndPosition(node, point);
}
- if (result.AddNodeToListBasedTestResult(node, location_in_container,
- rect) == kStopHitTesting) {
+ if (result.AddNodeToListBasedTestResult(node, hit_test_location, rect) ==
+ kStopHitTesting) {
return true;
}
}
@@ -1117,10 +1109,10 @@ bool NGBoxFragmentPainter::HitTestTextFragment(
bool NGBoxFragmentPainter::HitTestLineBoxFragment(
HitTestResult& result,
const NGPaintFragment& fragment,
- const HitTestLocation& location_in_container,
- const LayoutPoint& physical_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& physical_offset,
HitTestAction action) {
- if (HitTestChildren(result, fragment.Children(), location_in_container,
+ if (HitTestChildren(result, fragment.Children(), hit_test_location,
physical_offset, action))
return true;
@@ -1130,22 +1122,22 @@ bool NGBoxFragmentPainter::HitTestLineBoxFragment(
if (!VisibleToHitTestRequest(result.GetHitTestRequest()))
return false;
- const LayoutPoint overflow_location =
- fragment.SelfInkOverflow().offset.ToLayoutPoint() + physical_offset;
- if (HitTestClippedOutByBorder(location_in_container, overflow_location))
+ const PhysicalOffset overflow_location =
+ fragment.SelfInkOverflow().offset + physical_offset;
+ if (HitTestClippedOutByBorder(hit_test_location, overflow_location))
return false;
- const LayoutSize size = fragment.Size().ToLayoutSize();
- const LayoutRect bounds_rect(physical_offset, size);
+ const PhysicalSize size = fragment.Size();
+ const PhysicalRect bounds_rect(physical_offset, size);
const ComputedStyle& containing_box_style = box_fragment_.Style();
if (containing_box_style.HasBorderRadius() &&
- !location_in_container.Intersects(
- containing_box_style.GetRoundedBorderFor(bounds_rect))) {
+ !hit_test_location.Intersects(containing_box_style.GetRoundedBorderFor(
+ bounds_rect.ToLayoutRect()))) {
return false;
}
// Now hit test ourselves.
- if (!location_in_container.Intersects(bounds_rect))
+ if (!hit_test_location.Intersects(bounds_rect))
return false;
// Floats will be hit-tested in |kHitTestFloat| phase, but
@@ -1157,7 +1149,7 @@ bool NGBoxFragmentPainter::HitTestLineBoxFragment(
const auto& line = To<NGPhysicalLineBoxFragment>(fragment.PhysicalFragment());
if (line.HasFloatingDescendants()) {
DCHECK_NE(action, kHitTestFloat);
- if (HitTestChildren(result, fragment.Children(), location_in_container,
+ if (HitTestChildren(result, fragment.Children(), hit_test_location,
physical_offset, kHitTestFloat)) {
return false;
}
@@ -1165,20 +1157,19 @@ bool NGBoxFragmentPainter::HitTestLineBoxFragment(
Node* node = fragment.NodeForHitTest();
if (!result.InnerNode() && node) {
- const LayoutPoint point =
- location_in_container.Point() - ToLayoutSize(physical_offset) +
- fragment.InlineOffsetToContainerBox().ToLayoutPoint();
- result.SetNodeAndPosition(node, PhysicalOffsetToBeNoop(point));
+ const PhysicalOffset point = hit_test_location.Point() - physical_offset +
+ fragment.InlineOffsetToContainerBox();
+ result.SetNodeAndPosition(node, point);
}
- return result.AddNodeToListBasedTestResult(node, location_in_container,
+ return result.AddNodeToListBasedTestResult(node, hit_test_location,
bounds_rect) == kStopHitTesting;
}
bool NGBoxFragmentPainter::HitTestChildBoxFragment(
HitTestResult& result,
const NGPaintFragment& paint_fragment,
- const HitTestLocation& location_in_container,
- const LayoutPoint& physical_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& physical_offset,
HitTestAction action) {
const NGPhysicalFragment& fragment = paint_fragment.PhysicalFragment();
@@ -1197,7 +1188,7 @@ bool NGBoxFragmentPainter::HitTestChildBoxFragment(
DCHECK(!fragment.IsAtomicInline());
DCHECK(!fragment.IsFloating());
return NGBoxFragmentPainter(paint_fragment)
- .NodeAtPoint(result, location_in_container, physical_offset, action);
+ .NodeAtPoint(result, hit_test_location, physical_offset, action);
}
if (fragment.IsInline() && action != kHitTestForeground)
@@ -1205,29 +1196,23 @@ bool NGBoxFragmentPainter::HitTestChildBoxFragment(
LayoutBox* const layout_box = ToLayoutBox(fragment.GetMutableLayoutObject());
- // To be passed as |accumulated_offset| to legacy hit test functions of
- // LayoutBox or subclass overrides, where it isn't in any well-defined
- // coordinate space, but only equals the difference below.
- const LayoutPoint fallback_accumulated_offset =
- physical_offset - ToLayoutSize(layout_box->Location());
-
// https://www.w3.org/TR/CSS22/zindex.html#painting-order
// Hit test all phases of inline blocks, inline tables, replaced elements and
// non-positioned floats as if they created their own stacking contexts.
const bool should_hit_test_all_phases =
fragment.IsAtomicInline() || fragment.IsFloating();
return should_hit_test_all_phases
- ? layout_box->HitTestAllPhases(result, location_in_container,
- fallback_accumulated_offset)
- : layout_box->NodeAtPoint(result, location_in_container,
- fallback_accumulated_offset, action);
+ ? layout_box->HitTestAllPhases(result, hit_test_location,
+ physical_offset)
+ : layout_box->NodeAtPoint(result, hit_test_location,
+ physical_offset, action);
}
bool NGBoxFragmentPainter::HitTestChildren(
HitTestResult& result,
NGPaintFragment::ChildList children,
- const HitTestLocation& location_in_container,
- const LayoutPoint& accumulated_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& accumulated_offset,
HitTestAction action) {
Vector<NGPaintFragment*, 16> child_vector;
children.ToList(&child_vector);
@@ -1238,21 +1223,20 @@ bool NGBoxFragmentPainter::HitTestChildren(
continue;
const NGPhysicalFragment& fragment = child->PhysicalFragment();
- const LayoutPoint child_physical_offset =
- accumulated_offset + offset.ToLayoutPoint();
+ const PhysicalOffset child_physical_offset = accumulated_offset + offset;
bool stop_hit_testing = false;
if (fragment.Type() == NGPhysicalFragment::kFragmentBox) {
stop_hit_testing = HitTestChildBoxFragment(
- result, *child, location_in_container, child_physical_offset, action);
+ result, *child, hit_test_location, child_physical_offset, action);
} else if (fragment.Type() == NGPhysicalFragment::kFragmentLineBox) {
stop_hit_testing = HitTestLineBoxFragment(
- result, *child, location_in_container, child_physical_offset, action);
+ result, *child, hit_test_location, child_physical_offset, action);
} else if (fragment.Type() == NGPhysicalFragment::kFragmentText) {
- stop_hit_testing = HitTestTextFragment(
- result, *child, location_in_container, child_physical_offset, action);
+ stop_hit_testing = HitTestTextFragment(result, *child, hit_test_location,
+ child_physical_offset, action);
}
if (stop_hit_testing)
return true;
@@ -1263,8 +1247,7 @@ bool NGBoxFragmentPainter::HitTestChildren(
// Hit test culled inline boxes between |fragment| and its parent fragment.
const NGPaintFragment* previous_sibling = i ? child_vector[i - 1] : nullptr;
if (HitTestCulledInlineAncestors(result, *child, previous_sibling,
- location_in_container,
- child_physical_offset))
+ hit_test_location, child_physical_offset))
return true;
}
@@ -1272,15 +1255,14 @@ bool NGBoxFragmentPainter::HitTestChildren(
}
bool NGBoxFragmentPainter::HitTestClippedOutByBorder(
- const HitTestLocation& location_in_container,
- const LayoutPoint& border_box_location) const {
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& border_box_location) const {
const ComputedStyle& style = box_fragment_.Style();
- LayoutRect rect =
- LayoutRect(LayoutPoint(), PhysicalFragment().Size().ToLayoutSize());
- rect.MoveBy(border_box_location);
+ PhysicalRect rect(PhysicalOffset(), PhysicalFragment().Size());
+ rect.Move(border_box_location);
const NGBorderEdges& border_edges = BorderEdges();
- return !location_in_container.Intersects(style.GetRoundedBorderFor(
- rect, border_edges.line_left, border_edges.line_right));
+ return !hit_test_location.Intersects(style.GetRoundedBorderFor(
+ rect.ToLayoutRect(), border_edges.line_left, border_edges.line_right));
}
} // namespace blink
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 946cc955a7c..91e7acebed7 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
@@ -13,7 +13,7 @@
#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"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -39,11 +39,12 @@ class NGBoxFragmentPainter : public BoxPainterBase {
bool suppress_box_decoration_background = false);
// Hit tests this box fragment.
- // @param physical_offset Physical offset of this box fragment in paint layer.
+ // @param physical_offset Physical offset of this box fragment in the
+ // coordinate space of |hit_test_location|.
// TODO(eae): Change to take a HitTestResult pointer instead as it mutates.
bool NodeAtPoint(HitTestResult&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& physical_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& physical_offset,
HitTestAction);
protected:
@@ -93,8 +94,6 @@ class NGBoxFragmentPainter : public BoxPainterBase {
void PaintFloatingChildren(NGPaintFragment::ChildList, const PaintInfo&);
void PaintFloats(const PaintInfo&);
void PaintMask(const PaintInfo&, const PhysicalOffset& paint_offset);
- void PaintOverflowControlsIfNeeded(const PaintInfo&,
- const PhysicalOffset& paint_offset);
void PaintAtomicInline(const PaintInfo&);
void PaintBackground(const PaintInfo&,
const PhysicalRect&,
@@ -103,10 +102,10 @@ class NGBoxFragmentPainter : public BoxPainterBase {
void PaintCarets(const PaintInfo&, const PhysicalOffset& paint_offset);
void RecordHitTestData(const PaintInfo& paint_info,
- const LayoutPoint& paint_offset);
+ const PhysicalOffset& paint_offset);
void RecordHitTestDataForLine(const PaintInfo& paint_info,
- const LayoutPoint& paint_offset,
+ const PhysicalOffset& paint_offset,
const NGPaintFragment& line);
bool IsInSelfHitTestingPhase(HitTestAction) const;
@@ -119,8 +118,8 @@ class NGBoxFragmentPainter : public BoxPainterBase {
// container has 'overflow: scroll'.
bool HitTestChildren(HitTestResult&,
NGPaintFragment::ChildList,
- const HitTestLocation& location_in_container,
- const LayoutPoint& physical_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& physical_offset,
HitTestAction);
// Hit tests a box fragment, which is a child of either |box_fragment_|, or
@@ -129,16 +128,16 @@ class NGBoxFragmentPainter : public BoxPainterBase {
// paint layer.
bool HitTestChildBoxFragment(HitTestResult&,
const NGPaintFragment&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& physical_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& physical_offset,
HitTestAction);
// Hit tests the given text fragment.
// @param physical_offset Physical offset of the text fragment in paint layer.
bool HitTestTextFragment(HitTestResult&,
const NGPaintFragment&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& physical_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& physical_offset,
HitTestAction);
// Hit tests the given line box fragment.
@@ -146,18 +145,15 @@ class NGBoxFragmentPainter : public BoxPainterBase {
// layer.
bool HitTestLineBoxFragment(HitTestResult&,
const NGPaintFragment&,
- const HitTestLocation& location_in_container,
- const LayoutPoint& physical_offset,
+ const HitTestLocation& hit_test_location,
+ const PhysicalOffset& physical_offset,
HitTestAction);
// Returns whether the hit test location is completely outside the border box,
// which possibly has rounded corners.
- bool HitTestClippedOutByBorder(const HitTestLocation&,
- const LayoutPoint& border_box_location) const;
-
- LayoutPoint FlipForWritingModeForChild(
- const NGPhysicalFragment& child_fragment,
- const LayoutPoint& offset);
+ bool HitTestClippedOutByBorder(
+ const HitTestLocation&,
+ const PhysicalOffset& border_box_location) const;
const NGPhysicalBoxFragment& PhysicalFragment() const;
const NGBorderEdges& BorderEdges() const;
diff --git a/chromium/third_party/blink/renderer/core/paint/ng/ng_fieldset_painter.h b/chromium/third_party/blink/renderer/core/paint/ng/ng_fieldset_painter.h
index b81aaf462a4..844c4d21153 100644
--- a/chromium/third_party/blink/renderer/core/paint/ng/ng_fieldset_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/ng/ng_fieldset_painter.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_NG_NG_FIELDSET_PAINTER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_NG_NG_FIELDSET_PAINTER_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/ng/ng_fragment_painter.cc b/chromium/third_party/blink/renderer/core/paint/ng/ng_fragment_painter.cc
index 2e8ab7587bd..885c404605f 100644
--- a/chromium/third_party/blink/renderer/core/paint/ng/ng_fragment_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/ng/ng_fragment_painter.cc
@@ -51,7 +51,7 @@ void NGFragmentPainter::AddPDFURLRectIfNeeded(
paint_fragment_.Style().Visibility() != EVisibility::kVisible)
return;
- KURL url = ToElement(paint_fragment_.GetNode())->HrefURL();
+ KURL url = To<Element>(paint_fragment_.GetNode())->HrefURL();
if (!url.IsValid())
return;
diff --git a/chromium/third_party/blink/renderer/core/paint/ng/ng_inline_box_fragment_painter.h b/chromium/third_party/blink/renderer/core/paint/ng/ng_inline_box_fragment_painter.h
index 235d8a9a28a..935f725ad95 100644
--- a/chromium/third_party/blink/renderer/core/paint/ng/ng_inline_box_fragment_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/ng/ng_inline_box_fragment_painter.h
@@ -9,7 +9,7 @@
#include "third_party/blink/renderer/core/layout/ng/inline/ng_physical_line_box_fragment.h"
#include "third_party/blink/renderer/core/paint/inline_box_painter_base.h"
#include "third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 674dbd82188..f0f18f20d20 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
@@ -140,12 +140,8 @@ base::Optional<PositionWithAffinity> PositionForPointInChild(
const bool should_fallback = child.PhysicalFragment().IsBlockFlow() ||
child.PhysicalFragment().IsLegacyLayoutRoot();
const PositionWithAffinity result =
- should_fallback
- ? child.GetLayoutObject()->PositionForPoint(
- // Flip because LayoutObject::PositionForPoint() requires
- // flipped physical coordinates.
- child.GetLayoutObject()->FlipForWritingMode(child_point))
- : child.PositionForPoint(child_point);
+ should_fallback ? child.GetLayoutObject()->PositionForPoint(child_point)
+ : child.PositionForPoint(child_point);
if (result.IsNotNull())
return result;
return base::nullopt;
@@ -171,6 +167,21 @@ bool IsLastBRInPage(const NGPhysicalTextFragment& text_fragment) {
!text_fragment.GetLayoutObject()->NextInPreOrder();
}
+const LayoutObject* ListMarkerFromMarkerOrMarkerContent(
+ const LayoutObject* object) {
+ if (object->IsLayoutNGListMarkerIncludingInside())
+ return object;
+
+ // Check if this is a marker content.
+ if (object->IsAnonymous()) {
+ const LayoutObject* parent = object->Parent();
+ if (parent && parent->IsLayoutNGListMarkerIncludingInside())
+ return parent;
+ }
+
+ return nullptr;
+}
+
} // namespace
NGPaintFragment::NGPaintFragment(
@@ -180,6 +191,7 @@ NGPaintFragment::NGPaintFragment(
: physical_fragment_(std::move(fragment)),
offset_(offset),
parent_(parent),
+ is_layout_object_destroyed_(false),
is_dirty_inline_(false) {
// TODO(crbug.com/924449): Once we get the caller passes null physical
// fragment, we'll change to DCHECK().
@@ -207,6 +219,14 @@ NGPaintFragment::~NGPaintFragment() {
RemoveChildren();
}
+void NGPaintFragment::CreateContext::SkipDestroyedPreviousInstances() {
+ while (UNLIKELY(previous_instance &&
+ previous_instance->is_layout_object_destroyed_)) {
+ previous_instance = std::move(previous_instance->next_sibling_);
+ painting_layer_needs_repaint = true;
+ }
+}
+
void NGPaintFragment::CreateContext::DestroyPreviousInstances() {
if (previous_instance) {
DestroyAll(previous_instance);
@@ -264,6 +284,7 @@ scoped_refptr<NGPaintFragment> NGPaintFragment::CreateOrReuse(
// If the previous instance is given, check if it is re-usable.
// Re-using NGPaintFragment allows the paint system to identify objects.
+ context->SkipDestroyedPreviousInstances();
if (context->previous_instance) {
// Take the first instance of previous instances, leaving its following
// siblings at |context->previous_instance|. There is a trade-off between
@@ -298,6 +319,7 @@ scoped_refptr<NGPaintFragment> NGPaintFragment::CreateOrReuse(
previous_instance->physical_fragment_ = std::move(fragment);
previous_instance->offset_ = offset;
previous_instance->next_for_same_layout_object_ = nullptr;
+ CHECK(!previous_instance->is_layout_object_destroyed_);
previous_instance->is_dirty_inline_ = false;
// Destroy children of previous instances if the new instance doesn't have
// any children. Otherwise keep them in case these previous children maybe
@@ -385,12 +407,12 @@ bool NGPaintFragment::IsDescendantOfNotSelf(
}
bool NGPaintFragment::HasSelfPaintingLayer() const {
- return physical_fragment_->HasSelfPaintingLayer();
+ return PhysicalFragment().HasSelfPaintingLayer();
}
bool NGPaintFragment::ShouldClipOverflow() const {
auto* box_physical_fragment =
- DynamicTo<NGPhysicalBoxFragment>(physical_fragment_.get());
+ DynamicTo<NGPhysicalBoxFragment>(&PhysicalFragment());
return box_physical_fragment && box_physical_fragment->ShouldClipOverflow();
}
@@ -408,6 +430,8 @@ void NGPaintFragment::PopulateDescendants(CreateContext* parent_context) {
!box_physical_fragment || box_physical_fragment->ChildrenInline();
for (const NGLink& child_fragment : container.Children()) {
+ child_fragment->CheckType();
+
// OOF objects are not needed because they always have self painting layer.
if (UNLIKELY(child_fragment->IsOutOfFlowPositioned()))
continue;
@@ -457,7 +481,16 @@ void NGPaintFragment::AssociateWithLayoutObject(
HashMap<const LayoutObject*, NGPaintFragment*>* last_fragment_map) {
DCHECK(layout_object);
DCHECK(!next_for_same_layout_object_);
- DCHECK(layout_object->IsInline() || layout_object->IsFloating());
+ DCHECK(layout_object->IsInline());
+ DCHECK(PhysicalFragment().IsInline());
+
+#if DCHECK_IS_ON()
+ // Check we don't add the same fragment twice.
+ for (const NGPaintFragment* fragment :
+ FragmentRange(layout_object->FirstInlineFragment())) {
+ DCHECK_NE(this, fragment);
+ }
+#endif
auto add_result = last_fragment_map->insert(layout_object, this);
if (add_result.is_new_entry) {
@@ -476,6 +509,34 @@ void NGPaintFragment::AssociateWithLayoutObject(
add_result.stored_value->value = this;
}
+// TODO(kojii): Consider unifying this with
+// NGInlineNode::ClearAssociatedFragments.
+void NGPaintFragment::ClearAssociationWithLayoutObject() {
+ // TODO(kojii): Support break_token for LayoutObject that spans across block
+ // fragmentation boundaries.
+ LayoutObject* last_object = nullptr;
+ for (NGPaintFragment* child : Children()) {
+ const NGPhysicalFragment& fragment = child->PhysicalFragment();
+ if (fragment.IsInline()) {
+ LayoutObject* object = fragment.GetMutableLayoutObject();
+ if (object && object != last_object) {
+ // |IsInLayoutNGInlineFormattingContext()| is cleared if its
+ // NGInlineItem was invalidted.
+ if (object->IsInLayoutNGInlineFormattingContext())
+ object->SetFirstInlineFragment(nullptr);
+ last_object = object;
+ }
+ }
+ if (fragment.IsLineBox() || fragment.IsInlineBox() ||
+ fragment.IsColumnBox()) {
+ child->ClearAssociationWithLayoutObject();
+ } else {
+ DCHECK(fragment.IsText() || fragment.IsBlockFormattingContextRoot());
+ DCHECK(child->Children().IsEmpty());
+ }
+ }
+}
+
const NGPaintFragment* NGPaintFragment::GetForInlineContainer(
const LayoutObject* layout_object) {
DCHECK(layout_object && layout_object->IsInline());
@@ -525,34 +586,6 @@ NGPaintFragment::FragmentRange NGPaintFragment::SafeInlineFragmentsFor(
return fragments;
}
-void NGPaintFragment::InlineFragmentsIncludingCulledFor(
- const LayoutObject& layout_object,
- Callback callback,
- void* context) {
- DCHECK(layout_object.IsInLayoutNGInlineFormattingContext());
-
- auto fragments = InlineFragmentsFor(&layout_object);
- if (!fragments.IsEmpty()) {
- for (NGPaintFragment* fragment : fragments)
- callback(fragment, context);
- return;
- }
-
- // This is a culled LayoutInline. Iterate children's fragments.
- if (const LayoutInline* layout_inline =
- ToLayoutInlineOrNull(&layout_object)) {
- for (LayoutObject* child = layout_inline->FirstChild(); child;
- child = child->NextSibling()) {
- // |layout_inline| may still have non-inline children, e.g.,
- // 'position:absolute'. Skip them as they don't contribute to the culled
- // rects of |layout_inline|.
- if (!child->IsInline())
- continue;
- InlineFragmentsIncludingCulledFor(*child, callback, context);
- }
- }
-}
-
const NGPaintFragment* NGPaintFragment::LastForSameLayoutObject() const {
return const_cast<NGPaintFragment*>(this)->LastForSameLayoutObject();
}
@@ -564,6 +597,13 @@ NGPaintFragment* NGPaintFragment::LastForSameLayoutObject() {
return fragment;
}
+void NGPaintFragment::LayoutObjectWillBeDestroyed() {
+ for (NGPaintFragment* fragment = this; fragment;
+ fragment = fragment->next_for_same_layout_object_) {
+ fragment->is_layout_object_destroyed_ = true;
+ }
+}
+
NGPaintFragment::NGInkOverflowModel::NGInkOverflowModel(
const PhysicalRect& self_ink_overflow,
const PhysicalRect& contents_ink_overflow)
@@ -748,6 +788,8 @@ base::Optional<PhysicalRect> NGPaintFragment::LocalVisualRectFor(
PhysicalRect visual_rect;
for (NGPaintFragment* fragment : fragments) {
+ if (fragment->PhysicalFragment().IsHiddenForPaint())
+ continue;
PhysicalRect child_visual_rect = fragment->SelfInkOverflow();
child_visual_rect.offset += fragment->InlineOffsetToContainerBox();
visual_rect.Unite(child_visual_rect);
@@ -884,9 +926,10 @@ bool NGPaintFragment::TryMarkLastLineBoxDirtyFor(
}
void NGPaintFragment::SetShouldDoFullPaintInvalidationRecursively() {
- if (LayoutObject* layout_object = GetMutableLayoutObject())
+ if (LayoutObject* layout_object = GetMutableLayoutObject()) {
+ layout_object->StyleRef().ClearCachedPseudoStyles();
layout_object->SetShouldDoFullPaintInvalidation();
-
+ }
for (NGPaintFragment* child : Children())
child->SetShouldDoFullPaintInvalidationRecursively();
}
@@ -897,6 +940,7 @@ void NGPaintFragment::SetShouldDoFullPaintInvalidationForFirstLine() const {
if (NGPaintFragment* line_box = FirstLineBox()) {
line_box->SetShouldDoFullPaintInvalidationRecursively();
+ GetLayoutObject()->StyleRef().ClearCachedPseudoStyles();
GetMutableLayoutObject()->SetShouldDoFullPaintInvalidation();
}
}
@@ -1123,11 +1167,14 @@ Node* NGPaintFragment::NodeForHitTest() const {
return Parent()->NodeForHitTest();
// When the fragment is a list marker, return the list item.
- const LayoutObject* object = GetLayoutObject();
- if (object && object->IsLayoutNGListMarker()) {
- if (LayoutNGListItem* list_item = LayoutNGListItem::FromMarker(*object))
- return list_item->GetNode();
- return nullptr;
+ if (const LayoutObject* object = GetLayoutObject()) {
+ if (const LayoutObject* marker =
+ ListMarkerFromMarkerOrMarkerContent(object)) {
+ if (const LayoutNGListItem* list_item =
+ LayoutNGListItem::FromMarker(*marker))
+ return list_item->GetNode();
+ return nullptr;
+ }
}
for (const NGPaintFragment* runner = Parent(); runner;
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 966cb8265a7..9dc56909e65 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
@@ -9,10 +9,11 @@
#include <memory>
#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/layout/layout_inline.h"
#include "third_party/blink/renderer/core/layout/ng/ng_physical_fragment.h"
#include "third_party/blink/renderer/core/scroll/scroll_types.h"
#include "third_party/blink/renderer/platform/graphics/paint/display_item_client.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -49,6 +50,7 @@ class CORE_EXPORT NGPaintFragment : public RefCounted<NGPaintFragment>,
scoped_refptr<NGPaintFragment> previous_instance = nullptr);
const NGPhysicalFragment& PhysicalFragment() const {
+ CHECK(!is_layout_object_destroyed_);
return *physical_fragment_;
}
@@ -114,7 +116,7 @@ class CORE_EXPORT NGPaintFragment : public RefCounted<NGPaintFragment>,
public:
static NGPaintFragment* Next(NGPaintFragment* current) {
- return current->next_sibling_.get();
+ return current->NextSibling();
}
};
using ChildList = List<TraverseNextSibling>;
@@ -123,9 +125,11 @@ class CORE_EXPORT NGPaintFragment : public RefCounted<NGPaintFragment>,
// 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_; }
- NGPaintFragment* FirstChild() const { return first_child_.get(); }
- NGPaintFragment* NextSibling() const { return next_sibling_.get(); }
- ChildList Children() const { return ChildList(first_child_.get()); }
+ NGPaintFragment* FirstChild() const { return FirstAlive(first_child_.get()); }
+ NGPaintFragment* NextSibling() const {
+ return FirstAlive(next_sibling_.get());
+ }
+ ChildList Children() const { return ChildList(FirstChild()); }
// Note, as the name implies, |IsDescendantOfNotSelf| returns false for the
// same object. This is different from |LayoutObject::IsDescendant| but is
@@ -262,13 +266,15 @@ class CORE_EXPORT NGPaintFragment : public RefCounted<NGPaintFragment>,
// Same as |InlineFragmentsFor()| but this function includes descendants if
// the |layout_object| is culled (i.e., did not generate fragments.)
- typedef void (*Callback)(NGPaintFragment*, void*);
+ template <typename Callback>
static void InlineFragmentsIncludingCulledFor(const LayoutObject&,
- Callback callback,
- void* context);
+ Callback callback);
const NGPaintFragment* LastForSameLayoutObject() const;
NGPaintFragment* LastForSameLayoutObject();
+ void LayoutObjectWillBeDestroyed();
+
+ void ClearAssociationWithLayoutObject();
// Called when lines containing |child| is dirty.
static void DirtyLinesFromChangedChild(LayoutObject* child);
@@ -288,6 +294,14 @@ class CORE_EXPORT NGPaintFragment : public RefCounted<NGPaintFragment>,
static base::Optional<PhysicalRect> LocalVisualRectFor(const LayoutObject&);
private:
+ // Returns the first "alive" fragment; i.e., fragment that doesn't have
+ // destroyed LayoutObject.
+ static NGPaintFragment* FirstAlive(NGPaintFragment* fragment) {
+ while (UNLIKELY(fragment && fragment->is_layout_object_destroyed_))
+ fragment = fragment->next_sibling_.get();
+ return fragment;
+ }
+
struct CreateContext {
STACK_ALLOCATED();
@@ -301,6 +315,7 @@ class CORE_EXPORT NGPaintFragment : public RefCounted<NGPaintFragment>,
last_fragment_map(parent_context->last_fragment_map),
previous_instance(std::move(parent->first_child_)) {}
+ void SkipDestroyedPreviousInstances();
void DestroyPreviousInstances();
NGPaintFragment* parent = nullptr;
@@ -372,6 +387,9 @@ class CORE_EXPORT NGPaintFragment : public RefCounted<NGPaintFragment>,
};
std::unique_ptr<NGInkOverflowModel> ink_overflow_;
+ // Set when the corresponding LayoutObject is destroyed.
+ unsigned is_layout_object_destroyed_ : 1;
+
// For a line box, this indicates it is dirty. This helps to determine if the
// fragment is re-usable when part of an inline formatting context is changed.
// For an inline box, this flag helps to avoid traversing up to its line box
@@ -379,6 +397,34 @@ class CORE_EXPORT NGPaintFragment : public RefCounted<NGPaintFragment>,
unsigned is_dirty_inline_ : 1;
};
+template <typename Callback>
+void NGPaintFragment::InlineFragmentsIncludingCulledFor(
+ const LayoutObject& layout_object,
+ Callback callback) {
+ DCHECK(layout_object.IsInLayoutNGInlineFormattingContext());
+
+ auto fragments = InlineFragmentsFor(&layout_object);
+ if (!fragments.IsEmpty()) {
+ for (const NGPaintFragment* fragment : fragments)
+ callback(fragment);
+ return;
+ }
+
+ // This is a culled LayoutInline. Iterate children's fragments.
+ if (const LayoutInline* layout_inline =
+ ToLayoutInlineOrNull(&layout_object)) {
+ for (LayoutObject* child = layout_inline->FirstChild(); child;
+ child = child->NextSibling()) {
+ // |layout_inline| may still have non-inline children, e.g.,
+ // 'position:absolute'. Skip them as they don't contribute to the culled
+ // rects of |layout_inline|.
+ if (!child->IsInline())
+ continue;
+ InlineFragmentsIncludingCulledFor(*child, callback);
+ }
+ }
+}
+
extern template class CORE_EXTERN_TEMPLATE_EXPORT
NGPaintFragment::List<NGPaintFragment::TraverseNextForSameLayoutObject>;
extern template class CORE_EXTERN_TEMPLATE_EXPORT
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 e2d33a82e47..581f020e606 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
@@ -696,6 +696,44 @@ TEST_F(NGPaintFragmentTest, MarkLineBoxesDirtyByRemoveBr) {
EXPECT_FALSE(ToList(container.Children())[2]->IsDirty());
}
+static const char* inline_child_data[] = {
+ "<span id='child'>XXX</span>",
+ "<span id='child' style='background: yellow'>XXX</span>",
+ "<span id='child' style='display: inline-block'>XXX</span>",
+};
+
+class InlineChildTest : public NGPaintFragmentTest,
+ public testing::WithParamInterface<const char*> {};
+
+INSTANTIATE_TEST_SUITE_P(NGPaintFragmentTest,
+ InlineChildTest,
+ testing::ValuesIn(inline_child_data));
+
+TEST_P(InlineChildTest, RemoveInlineChild) {
+ SetBodyInnerHTML(String(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ </style>
+ <body>
+ <div id="container">
+ 12345
+ )HTML") + GetParam() +
+ R"HTML(
+ 67890
+ </div>
+ </body>
+ )HTML");
+ const NGPaintFragment* container = GetPaintFragmentByElementId("container");
+ const NGPaintFragment& linebox = container->Children().front();
+ EXPECT_EQ(linebox.Children().size(), 3u);
+
+ Element* child = GetElementById("child");
+ child->remove();
+
+ // Destroyed children should be eliminated immediately.
+ EXPECT_EQ(linebox.Children().size(), 2u);
+}
+
TEST_F(NGPaintFragmentTest, MarkLineBoxesDirtyByRemoveChild) {
if (!RuntimeEnabledFeatures::LayoutNGLineCacheEnabled())
return;
diff --git a/chromium/third_party/blink/renderer/core/paint/ng/ng_text_fragment_painter.cc b/chromium/third_party/blink/renderer/core/paint/ng/ng_text_fragment_painter.cc
index 573e9deb94b..f320fa2dbb1 100644
--- a/chromium/third_party/blink/renderer/core/paint/ng/ng_text_fragment_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/ng/ng_text_fragment_painter.cc
@@ -192,7 +192,7 @@ void PaintDocumentMarkers(GraphicsContext& context,
break;
text_painter->Paint(paint_start_offset, paint_end_offset,
paint_end_offset - paint_start_offset, text_style,
- NodeHolder::EmptyNodeHolder());
+ kInvalidDOMNodeId);
} break;
case DocumentMarker::kComposition:
@@ -265,7 +265,7 @@ void NGTextFragmentPainter::PaintSymbol(const PaintInfo& paint_info,
// ltr, expanding new line wrap or so which uses InlineTextBox functions.
void NGTextFragmentPainter::Paint(const PaintInfo& paint_info,
const PhysicalOffset& paint_offset,
- const NodeHolder& node_holder) {
+ DOMNodeId node_id) {
const auto& text_fragment =
To<NGPhysicalTextFragment>(fragment_.PhysicalFragment());
const ComputedStyle& style = fragment_.Style();
@@ -430,15 +430,14 @@ void NGTextFragmentPainter::Paint(const PaintInfo& paint_info,
// Paint only the text that is not selected.
if (start_offset < selection_status->start) {
text_painter.Paint(start_offset, selection_status->start, length,
- text_style, node_holder);
+ text_style, node_id);
}
if (selection_status->end < end_offset) {
text_painter.Paint(selection_status->end, end_offset, length,
- text_style, node_holder);
+ text_style, node_id);
}
} else {
- text_painter.Paint(start_offset, end_offset, length, text_style,
- node_holder);
+ text_painter.Paint(start_offset, end_offset, length, text_style, node_id);
}
// Paint line-through decoration if needed.
@@ -453,7 +452,7 @@ void NGTextFragmentPainter::Paint(const PaintInfo& paint_info,
(paint_selected_text_only || paint_selected_text_separately)) {
// Paint only the text that is selected.
text_painter.Paint(selection_status->start, selection_status->end, length,
- selection_style, node_holder);
+ selection_style, node_id);
}
if (paint_info.phase != PaintPhase::kForeground)
diff --git a/chromium/third_party/blink/renderer/core/paint/ng/ng_text_fragment_painter.h b/chromium/third_party/blink/renderer/core/paint/ng/ng_text_fragment_painter.h
index 77d1c19c9cd..1b7b9c6b132 100644
--- a/chromium/third_party/blink/renderer/core/paint/ng/ng_text_fragment_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/ng/ng_text_fragment_painter.h
@@ -5,10 +5,10 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_NG_NG_TEXT_FRAGMENT_PAINTER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_NG_NG_TEXT_FRAGMENT_PAINTER_H_
-#include "third_party/blink/renderer/core/content_capture/content_holder.h"
#include "third_party/blink/renderer/core/style/computed_style_constants.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/graphics/dom_node_id.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -27,7 +27,7 @@ class NGTextFragmentPainter {
void Paint(const PaintInfo&,
const PhysicalOffset& paint_offset,
- const NodeHolder& node_holder);
+ DOMNodeId node_id);
private:
void PaintSymbol(const PaintInfo& paint_info,
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 f9d7ad1c87a..e3d7aa61aa1 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
@@ -27,17 +27,17 @@ void NGTextPainter::Paint(unsigned start_offset,
unsigned end_offset,
unsigned length,
const TextPaintStyle& text_style,
- const NodeHolder& node_holder) {
+ DOMNodeId node_id) {
GraphicsContextStateSaver state_saver(graphics_context_, false);
UpdateGraphicsContext(text_style, state_saver);
// TODO(layout-dev): Handle combine text here or elsewhere.
- PaintInternal<kPaintText>(start_offset, end_offset, length, node_holder);
+ PaintInternal<kPaintText>(start_offset, end_offset, length, node_id);
if (!emphasis_mark_.IsEmpty()) {
if (text_style.emphasis_mark_color != text_style.fill_color)
graphics_context_.SetFillColor(text_style.emphasis_mark_color);
PaintInternal<kPaintEmphasisMark>(start_offset, end_offset, length,
- node_holder);
+ node_id);
}
}
@@ -46,7 +46,7 @@ void NGTextPainter::PaintInternalFragment(
NGTextFragmentPaintInfo& fragment_paint_info,
unsigned from,
unsigned to,
- const NodeHolder& node_holder) {
+ DOMNodeId node_id) {
DCHECK(from <= fragment_paint_info.text.length());
DCHECK(to <= fragment_paint_info.text.length());
@@ -60,7 +60,7 @@ void NGTextPainter::PaintInternalFragment(
} else {
DCHECK(step == kPaintText);
graphics_context_.DrawText(font_, fragment_paint_info,
- FloatPoint(text_origin_), node_holder);
+ FloatPoint(text_origin_), node_id);
// TODO(npm): Check that there are non-whitespace characters. See
// crbug.com/788444.
graphics_context_.GetPaintController().SetTextPainted();
@@ -74,7 +74,7 @@ template <NGTextPainter::PaintInternalStep Step>
void NGTextPainter::PaintInternal(unsigned start_offset,
unsigned end_offset,
unsigned truncation_point,
- const NodeHolder& node_holder) {
+ DOMNodeId node_id) {
// TODO(layout-dev): We shouldn't be creating text fragments without text.
if (!fragment_.TextShapeResult())
return;
@@ -82,16 +82,15 @@ void NGTextPainter::PaintInternal(unsigned start_offset,
NGTextFragmentPaintInfo paint_info = fragment_.PaintInfo();
if (start_offset <= end_offset) {
- PaintInternalFragment<Step>(paint_info, start_offset, end_offset,
- node_holder);
+ PaintInternalFragment<Step>(paint_info, start_offset, end_offset, node_id);
} else {
if (end_offset > 0) {
PaintInternalFragment<Step>(paint_info, ellipsis_offset_, end_offset,
- node_holder);
+ node_id);
}
if (start_offset < truncation_point) {
PaintInternalFragment<Step>(paint_info, start_offset, truncation_point,
- node_holder);
+ node_id);
}
}
}
diff --git a/chromium/third_party/blink/renderer/core/paint/ng/ng_text_painter.h b/chromium/third_party/blink/renderer/core/paint/ng/ng_text_painter.h
index 4e448d1c0fc..62d9ed46454 100644
--- a/chromium/third_party/blink/renderer/core/paint/ng/ng_text_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/ng/ng_text_painter.h
@@ -5,10 +5,10 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_NG_NG_TEXT_PAINTER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_NG_NG_TEXT_PAINTER_H_
-#include "third_party/blink/renderer/core/content_capture/content_holder.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/paint/ng/ng_paint_fragment.h"
#include "third_party/blink/renderer/core/paint/text_painter_base.h"
+#include "third_party/blink/renderer/platform/graphics/dom_node_id.h"
namespace blink {
@@ -43,7 +43,7 @@ class CORE_EXPORT NGTextPainter : public TextPainterBase {
unsigned end_offset,
unsigned length,
const TextPaintStyle&,
- const NodeHolder&);
+ DOMNodeId);
static TextPaintStyle TextPaintingStyle(const NGPhysicalTextFragment*,
const ComputedStyle&,
@@ -59,13 +59,13 @@ class CORE_EXPORT NGTextPainter : public TextPainterBase {
void PaintInternalFragment(NGTextFragmentPaintInfo&,
unsigned from,
unsigned to,
- const NodeHolder& node_holder);
+ DOMNodeId node_id);
template <PaintInternalStep step>
void PaintInternal(unsigned start_offset,
unsigned end_offset,
unsigned truncation_point,
- const NodeHolder& node_holder);
+ DOMNodeId node_id);
void PaintEmphasisMarkForCombinedText();
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 777fbb5abc7..476685c9801 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
@@ -172,18 +172,6 @@ void ObjectPaintInvalidator::
Helper::Traverse(object_);
}
-namespace {
-bool IsClientNGPaintFragmentForObject(const DisplayItemClient& client,
- const LayoutObject& object) {
- if (!RuntimeEnabledFeatures::LayoutNGEnabled())
- return false;
- // TODO(crbug.com/880519): This hack only makes current invalidation tracking
- // web tests pass with LayoutNG. More work is needed if we want to launch
- // the invalidation tracking feature.
- return &client == object.PaintFragment();
-}
-} // namespace
-
void ObjectPaintInvalidator::InvalidateDisplayItemClient(
const DisplayItemClient& client,
PaintInvalidationReason reason) {
@@ -193,14 +181,6 @@ void ObjectPaintInvalidator::InvalidateDisplayItemClient(
// reduce the cost.
DCHECK(!object_.PaintingLayer() || object_.PaintingLayer()->NeedsRepaint());
- if (&client == &object_ ||
- IsClientNGPaintFragmentForObject(client, object_)) {
- TRACE_EVENT_INSTANT1(
- TRACE_DISABLED_BY_DEFAULT("devtools.timeline.invalidationTracking"),
- "PaintInvalidationTracking", TRACE_EVENT_SCOPE_THREAD, "data",
- inspector_paint_invalidation_tracking_event::Data(object_));
- }
-
client.Invalidate(reason);
if (LocalFrameView* frame_view = object_.GetFrameView())
diff --git a/chromium/third_party/blink/renderer/core/paint/object_paint_invalidator.h b/chromium/third_party/blink/renderer/core/paint/object_paint_invalidator.h
index a0605c26e95..a6f5f921a94 100644
--- a/chromium/third_party/blink/renderer/core/paint/object_paint_invalidator.h
+++ b/chromium/third_party/blink/renderer/core/paint/object_paint_invalidator.h
@@ -9,7 +9,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/graphics/paint_invalidation_reason.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 6622d70dbab..6500d54223f 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
@@ -15,7 +15,13 @@
namespace blink {
-using ObjectPaintInvalidatorTest = RenderingTest;
+class ObjectPaintInvalidatorTest : public RenderingTest {
+ protected:
+ void SetUp() override {
+ EnableCompositing();
+ RenderingTest::SetUp();
+ }
+};
using PaintInvalidation = LocalFrameView::ObjectPaintInvalidation;
using ::testing::ElementsAre;
@@ -25,7 +31,6 @@ TEST_F(ObjectPaintInvalidatorTest,
if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled())
return;
- EnableCompositing();
SetBodyInnerHTML(R"HTML(
<style>div { width: 10px; height: 10px; background-color: green;
}</style>
@@ -80,7 +85,6 @@ TEST_F(ObjectPaintInvalidatorTest, TraverseFloatUnderCompositedInline) {
if (RuntimeEnabledFeatures::LayoutNGEnabled())
return;
- EnableCompositing();
SetBodyInnerHTML(R"HTML(
<div id='compositedContainer' style='position: relative;
will-change: transform'>
@@ -167,7 +171,6 @@ TEST_F(ObjectPaintInvalidatorTest,
if (RuntimeEnabledFeatures::LayoutNGEnabled())
return;
- EnableCompositing();
SetBodyInnerHTML(R"HTML(
<div id='compositedContainer' style='position: relative;
will-change: transform'>
@@ -235,7 +238,6 @@ TEST_F(ObjectPaintInvalidatorTest, TraverseStackedFloatUnderCompositedInline) {
if (RuntimeEnabledFeatures::LayoutNGEnabled())
return;
- EnableCompositing();
SetBodyInnerHTML(R"HTML(
<span id='span' style='position: relative; will-change: transform'>
<div id='target' style='position: relative; float: right'></div>
@@ -272,7 +274,6 @@ TEST_F(ObjectPaintInvalidatorTest, TraverseStackedFloatUnderCompositedInline) {
}
TEST_F(ObjectPaintInvalidatorTest, InvalidatePaintRectangle) {
- EnableCompositing();
SetBodyInnerHTML(
"<div id='target' style='width: 200px; height: 200px; background: blue'>"
"</div>");
@@ -324,7 +325,6 @@ TEST_F(ObjectPaintInvalidatorTest, InvalidatePaintRectangle) {
}
TEST_F(ObjectPaintInvalidatorTest, Selection) {
- EnableCompositing();
SetBodyInnerHTML("<img id='target' style='width: 100px; height: 100px'>");
auto* target = GetLayoutObjectByElementId("target");
EXPECT_EQ(IntRect(), target->SelectionVisualRect());
diff --git a/chromium/third_party/blink/renderer/core/paint/object_paint_properties.h b/chromium/third_party/blink/renderer/core/paint/object_paint_properties.h
index c84ea9e5619..f943119aefa 100644
--- a/chromium/third_party/blink/renderer/core/paint/object_paint_properties.h
+++ b/chromium/third_party/blink/renderer/core/paint/object_paint_properties.h
@@ -16,7 +16,7 @@
#include "third_party/blink/renderer/platform/graphics/paint/effect_paint_property_node.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/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/object_painter.cc b/chromium/third_party/blink/renderer/core/paint/object_painter.cc
index 5e8436dc0d3..abbeddf9feb 100644
--- a/chromium/third_party/blink/renderer/core/paint/object_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/object_painter.cc
@@ -70,7 +70,7 @@ void ObjectPainter::AddPDFURLRectIfNeeded(const PaintInfo& paint_info,
layout_object_.StyleRef().Visibility() != EVisibility::kVisible)
return;
- KURL url = ToElement(layout_object_.GetNode())->HrefURL();
+ KURL url = To<Element>(layout_object_.GetNode())->HrefURL();
if (!url.IsValid())
return;
diff --git a/chromium/third_party/blink/renderer/core/paint/object_painter.h b/chromium/third_party/blink/renderer/core/paint/object_painter.h
index 7f05ee45160..12595d0c335 100644
--- a/chromium/third_party/blink/renderer/core/paint/object_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/object_painter.h
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/paint/object_painter_base.h"
#include "third_party/blink/renderer/core/style/computed_style_constants.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/object_painter_base.h b/chromium/third_party/blink/renderer/core/paint/object_painter_base.h
index 2890d897c9b..4b0d0f1234c 100644
--- a/chromium/third_party/blink/renderer/core/paint/object_painter_base.h
+++ b/chromium/third_party/blink/renderer/core/paint/object_painter_base.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_OBJECT_PAINTER_BASE_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/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
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 85d7346dcaf..2e3daa86fc0 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
@@ -795,7 +795,6 @@ TEST_P(PaintAndRasterInvalidationTest,
}
TEST_P(PaintAndRasterInvalidationTest, DelayedFullPaintInvalidation) {
- EnableCompositing();
SetBodyInnerHTML(R"HTML(
<style>body { margin: 0 }</style>
<div style='height: 4000px'></div>
@@ -845,7 +844,6 @@ TEST_P(PaintAndRasterInvalidationTest, DelayedFullPaintInvalidation) {
}
TEST_P(PaintAndRasterInvalidationTest, SVGHiddenContainer) {
- EnableCompositing();
SetBodyInnerHTML(R"HTML(
<svg style='position: absolute; top: 100px; left: 100px'>
<mask id='mask'>
@@ -868,7 +866,7 @@ TEST_P(PaintAndRasterInvalidationTest, SVGHiddenContainer) {
EXPECT_EQ(IntRect(55, 66, 7, 8), real_rect->FirstFragment().VisualRect());
GetDocument().View()->SetTracksPaintInvalidations(true);
- ToElement(mask_rect->GetNode())->setAttribute("x", "20");
+ To<Element>(mask_rect->GetNode())->setAttribute("x", "20");
UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(IntRect(), mask_rect->FirstFragment().VisualRect());
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 a842d22bf51..10d403fb7e8 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
@@ -30,7 +30,7 @@ TEST_P(PaintControllerPaintTest, FullDocumentPaintingWithCaret) {
"<div id='div' contentEditable='true' style='outline:none'>XYZ</div>");
GetDocument().GetPage()->GetFocusController().SetActive(true);
GetDocument().GetPage()->GetFocusController().SetFocused(true);
- Element& div = *ToElement(GetDocument().body()->firstChild());
+ auto& div = *To<Element>(GetDocument().body()->firstChild());
InlineTextBox& text_inline_box =
*ToLayoutText(div.firstChild()->GetLayoutObject())->FirstTextBox();
EXPECT_THAT(RootPaintController().GetDisplayItemList(),
@@ -54,7 +54,7 @@ TEST_P(PaintControllerPaintTest, InlineRelayout) {
SetBodyInnerHTML(
"<div id='div' style='width:100px; height: 200px'>AAAAAAAAAA "
"BBBBBBBBBB</div>");
- Element& div = *ToElement(GetDocument().body()->firstChild());
+ auto& div = *To<Element>(GetDocument().body()->firstChild());
auto& div_block =
*To<LayoutBlock>(GetDocument().body()->firstChild()->GetLayoutObject());
LayoutText& text = *ToLayoutText(div_block.FirstChild());
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 1a42a09c836..af9a0355f1a 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
@@ -36,8 +36,8 @@ class PaintControllerPaintTestBase : public RenderingTest {
}
void SetUp() override {
- RenderingTest::SetUp();
EnableCompositing();
+ RenderingTest::SetUp();
}
bool PaintWithoutCommit(
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 f5a5330a791..ef8d43a45bb 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_info.h
+++ b/chromium/third_party/blink/renderer/core/paint/paint_info.h
@@ -42,7 +42,7 @@
#include "third_party/blink/renderer/platform/graphics/paint/cull_rect.h"
#include "third_party/blink/renderer/platform/graphics/paint/display_item.h"
#include "third_party/blink/renderer/platform/transforms/affine_transform.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
#include <limits>
@@ -137,6 +137,12 @@ struct CORE_EXPORT PaintInfo {
const CullRect& GetCullRect() const { return cull_rect_; }
+ bool IntersectsCullRect(
+ const PhysicalRect& rect,
+ const PhysicalOffset& offset = PhysicalOffset()) const {
+ return cull_rect_.Intersects(rect.ToLayoutRect(), offset.ToLayoutPoint());
+ }
+
void ApplyInfiniteCullRect() { cull_rect_ = CullRect::Infinite(); }
void TransformCullRect(const TransformPaintPropertyNode& transform) {
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 00a1198947a..46bf7f6006f 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_invalidator.cc
+++ b/chromium/third_party/blink/renderer/core/paint/paint_invalidator.cc
@@ -9,8 +9,8 @@
#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/settings.h"
-#include "third_party/blink/renderer/core/layout/jank_tracker.h"
#include "third_party/blink/renderer/core/layout/layout_block_flow.h"
+#include "third_party/blink/renderer/core/layout/layout_shift_tracker.h"
#include "third_party/blink/renderer/core/layout/layout_table.h"
#include "third_party/blink/renderer/core/layout/layout_table_section.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
@@ -272,7 +272,7 @@ void PaintInvalidator::UpdateVisualRect(const LayoutObject& object,
fragment_data.SetVisualRect(ComputeVisualRect(object, context));
- object.GetFrameView()->GetJankTracker().NotifyObjectPrePaint(
+ object.GetFrameView()->GetLayoutShiftTracker().NotifyObjectPrePaint(
object,
PropertyTreeState(*context.tree_builder_context_->current.transform,
*context.tree_builder_context_->current.clip,
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_invalidator.h b/chromium/third_party/blink/renderer/core/paint/paint_invalidator.h
index 6aa6908d472..a8aed714d64 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_invalidator.h
+++ b/chromium/third_party/blink/renderer/core/paint/paint_invalidator.h
@@ -9,7 +9,7 @@
#include "third_party/blink/renderer/core/paint/paint_property_tree_builder.h"
#include "third_party/blink/renderer/platform/geometry/layout_rect.h"
#include "third_party/blink/renderer/platform/graphics/paint_invalidation_reason.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
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 6081229810c..ed1df076fa8 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_layer.cc
+++ b/chromium/third_party/blink/renderer/core/paint/paint_layer.cc
@@ -77,6 +77,7 @@
#include "third_party/blink/renderer/core/paint/filter_effect_builder.h"
#include "third_party/blink/renderer/core/paint/object_paint_invalidator.h"
#include "third_party/blink/renderer/core/paint/paint_info.h"
+#include "third_party/blink/renderer/core/paint/paint_layer_paint_order_iterator.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/style/reference_clip_path_operation.h"
@@ -94,7 +95,6 @@
#include "third_party/blink/renderer/platform/transforms/transformation_matrix.h"
#include "third_party/blink/renderer/platform/wtf/allocator/partitions.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
-#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
namespace blink {
@@ -147,7 +147,6 @@ PaintLayer::PaintLayer(LayoutBoxModelObject& layout_object)
needs_position_update_(!IsRootLayer()),
#endif
has3d_transformed_descendant_(false),
- contains_dirty_overlay_scrollbars_(false),
needs_ancestor_dependent_compositing_inputs_update_(
!RuntimeEnabledFeatures::CompositeAfterPaintEnabled()),
child_needs_compositing_inputs_update_(
@@ -165,6 +164,7 @@ PaintLayer::PaintLayer(LayoutBoxModelObject& layout_object)
has_fixed_position_descendant_(false),
has_sticky_position_descendant_(false),
has_non_contained_absolute_position_descendant_(false),
+ has_stacked_descendant_in_current_stacking_context_(false),
self_painting_status_changed_(false),
filter_on_effect_node_dirty_(false),
backdrop_filter_on_effect_node_dirty_(false),
@@ -176,7 +176,10 @@ PaintLayer::PaintLayer(LayoutBoxModelObject& layout_object)
needs_compositing_layer_assignment_(false),
descendant_needs_compositing_layer_assignment_(false),
has_self_painting_layer_descendant_(false),
- is_non_stacked_with_in_flow_stacked_descendant_(false),
+ needs_reorder_overlay_scrollbars_(false),
+#if DCHECK_IS_ON()
+ layer_list_mutation_allowed_(true),
+#endif
layout_object_(layout_object),
parent_(nullptr),
previous_(nullptr),
@@ -219,6 +222,12 @@ PaintLayer::~PaintLayer() {
ClearCompositedLayerMapping(true);
}
+ // Reset this flag before disposing scrollable_area_ to prevent
+ // PaintLayerScrollableArea::WillRemoveScrollbar() from dirtying the z-order
+ // list of the stacking context. If this layer is removed from the parent,
+ // the z-order list should have been invalidated in RemoveChild().
+ needs_reorder_overlay_scrollbars_ = false;
+
if (scrollable_area_)
scrollable_area_->Dispose();
@@ -317,31 +326,26 @@ void PaintLayer::UpdateLayerPositionsAfterLayout() {
}
}
-void PaintLayer::UpdateLayerPositionRecursive(
- UpdateLayerPositionBehavior behavior,
- bool dirty_compositing_if_needed) {
+void PaintLayer::UpdateLayerPositionRecursive() {
auto old_location = location_;
- switch (behavior) {
- case AllLayers:
- UpdateLayerPosition();
- break;
- case OnlyStickyLayers:
- if (GetLayoutObject().StyleRef().HasStickyConstrainedPosition())
- UpdateLayerPosition();
- if (PaintLayerScrollableArea* scroller = GetScrollableArea()) {
- if (!scroller->HasStickyDescendants())
- return;
- }
- break;
- default:
- NOTREACHED();
- }
+ auto old_offset_for_in_flow_rel_position =
+ rare_data_ ? rare_data_->offset_for_in_flow_rel_position
+ : PhysicalOffset();
+ UpdateLayerPosition();
- if (dirty_compositing_if_needed && location_ != old_location)
+ if (location_ != old_location) {
SetNeedsCompositingInputsUpdate();
+ } else {
+ // TODO(chrishtr): compute this invalidation in layout instead of here.
+ auto offset_for_in_flow_rel_position =
+ rare_data_ ? rare_data_->offset_for_in_flow_rel_position
+ : PhysicalOffset();
+ if (offset_for_in_flow_rel_position != old_offset_for_in_flow_rel_position)
+ SetNeedsCompositingInputsUpdate();
+ }
for (PaintLayer* child = FirstChild(); child; child = child->NextSibling())
- child->UpdateLayerPositionRecursive(behavior, dirty_compositing_if_needed);
+ child->UpdateLayerPositionRecursive();
}
bool PaintLayer::SticksToScroller() const {
@@ -387,22 +391,6 @@ bool PaintLayer::IsAffectedByScrollOf(const PaintLayer* ancestor) const {
return current_layer == ancestor;
}
-void PaintLayer::UpdateLayerPositionsAfterOverflowScroll() {
- if (IsRootLayer()) {
- // The root PaintLayer (i.e. the LayoutView) is special, in that scroll
- // offset is not included in clip rects. Therefore, we do not need to clear
- // them when that PaintLayer is scrolled. We also don't need to update layer
- // positions, because they also do not depend on the root's scroll offset.
- if (GetScrollableArea()->HasStickyDescendants()) {
- UpdateLayerPositionRecursive(OnlyStickyLayers,
- /* dirty_compositing */ false);
- }
- return;
- }
- ClearClipRects();
- UpdateLayerPositionRecursive(AllLayers, /* dirty_compositing */ false);
-}
-
void PaintLayer::UpdateTransformationMatrix() {
if (TransformationMatrix* transform = Transform()) {
LayoutBox* box = GetLayoutBox();
@@ -650,16 +638,12 @@ void PaintLayer::UpdateDescendantDependentFlags() {
has_fixed_position_descendant_ = false;
has_sticky_position_descendant_ = false;
has_non_contained_absolute_position_descendant_ = false;
+ has_stacked_descendant_in_current_stacking_context_ = false;
has_self_painting_layer_descendant_ = false;
- is_non_stacked_with_in_flow_stacked_descendant_ = false;
bool can_contain_abs =
GetLayoutObject().CanContainAbsolutePositionObjects();
- const ComputedStyle& style = GetLayoutObject().StyleRef();
- bool needs_stacking_node = style.IsStackingContext();
- bool is_stacked = style.IsStacked();
-
for (PaintLayer* child = FirstChild(); child;
child = child->NextSibling()) {
const ComputedStyle& child_style = child->GetLayoutObject().StyleRef();
@@ -670,9 +654,9 @@ void PaintLayer::UpdateDescendantDependentFlags() {
has_visible_descendant_ = true;
has_non_isolated_descendant_with_blend_mode_ |=
- (!child->GetLayoutObject().StyleRef().IsStackingContext() &&
+ (!child_style.IsStackingContext() &&
child->HasNonIsolatedDescendantWithBlendMode()) ||
- child->GetLayoutObject().StyleRef().HasBlendMode();
+ child_style.HasBlendMode();
has_descendant_with_clip_path_ |= child->HasDescendantWithClipPath() ||
child->GetLayoutObject().HasClipPath();
@@ -690,23 +674,22 @@ void PaintLayer::UpdateDescendantDependentFlags() {
child_style.GetPosition() == EPosition::kAbsolute);
}
- needs_stacking_node = needs_stacking_node || !child_style.IsStacked();
+ if (!has_stacked_descendant_in_current_stacking_context_) {
+ if (child_style.IsStacked()) {
+ has_stacked_descendant_in_current_stacking_context_ = true;
+ } else if (!child_style.IsStackingContext()) {
+ has_stacked_descendant_in_current_stacking_context_ =
+ child->has_stacked_descendant_in_current_stacking_context_;
+ }
+ }
has_self_painting_layer_descendant_ =
has_self_painting_layer_descendant_ ||
child->HasSelfPaintingLayerDescendant() ||
child->IsSelfPaintingLayer();
-
- if (!is_stacked) {
- if (child->IsNonStackedWithInFlowStackedDescendant())
- is_non_stacked_with_in_flow_stacked_descendant_ = true;
- else if (child_style.IsStacked() &&
- !child->GetLayoutObject().IsOutOfFlowPositioned())
- is_non_stacked_with_in_flow_stacked_descendant_ = true;
- }
}
- UpdateStackingNode(needs_stacking_node);
+ UpdateStackingNode();
if (old_has_non_isolated_descendant_with_blend_mode !=
static_cast<bool>(has_non_isolated_descendant_with_blend_mode_))
@@ -770,13 +753,9 @@ void PaintLayer::UpdateDescendantDependentFlags() {
void PaintLayer::Update3DTransformedDescendantStatus() {
has3d_transformed_descendant_ = false;
- if (!stacking_node_)
- return;
-
// Transformed or preserve-3d descendants can only be in the z-order lists,
// not in the normal flow list, so we only need to check those.
- PaintLayerStackingNodeIterator iterator(
- *stacking_node_.get(), kPositiveZOrderChildren | kNegativeZOrderChildren);
+ PaintLayerPaintOrderIterator iterator(*this, kStackedChildren);
while (PaintLayer* child_layer = iterator.Next()) {
bool child_has3d = false;
// If the child lives in a 3d hierarchy, then the layer at the root of
@@ -799,8 +778,8 @@ void PaintLayer::UpdateLayerPosition() {
// LayoutBoxes will call UpdateSizeAndScrollingAfterLayout() from
// LayoutBox::UpdateAfterLayout, but LayoutInlines will still need to update
// their size.
- if (GetLayoutObject().IsInline() && GetLayoutObject().IsLayoutInline())
- UpdateSizeAndScrollingAfterLayout();
+ if (GetLayoutObject().IsLayoutInline())
+ UpdateSize();
PhysicalOffset local_point;
if (LayoutBox* box = GetLayoutBox()) {
local_point += box->PhysicalLocation();
@@ -826,36 +805,27 @@ void PaintLayer::UpdateLayerPosition() {
}
if (PaintLayer* containing_layer = ContainingLayer()) {
- if (containing_layer->GetLayoutObject().HasOverflowClip() &&
- !containing_layer->IsRootLayer()) {
- // Subtract our container's scroll offset.
- IntSize offset =
- containing_layer->GetLayoutBox()->ScrolledContentOffset();
- local_point -= PhysicalOffset(offset);
- } else {
- auto& container = containing_layer->GetLayoutObject();
- if (GetLayoutObject().IsOutOfFlowPositioned() &&
- container.IsLayoutInline() &&
- container.CanContainOutOfFlowPositionedElement(
- GetLayoutObject().StyleRef().GetPosition())) {
- // Adjust offset for absolute under in-flow positioned inline.
- PhysicalOffset offset =
- ToLayoutInline(container).OffsetForInFlowPositionedInline(
- ToLayoutBox(GetLayoutObject()));
- local_point += offset;
- }
+ auto& container = containing_layer->GetLayoutObject();
+ if (GetLayoutObject().IsOutOfFlowPositioned() &&
+ container.IsLayoutInline() &&
+ container.CanContainOutOfFlowPositionedElement(
+ GetLayoutObject().StyleRef().GetPosition())) {
+ // Adjust offset for absolute under in-flow positioned inline.
+ PhysicalOffset offset =
+ ToLayoutInline(container).OffsetForInFlowPositionedInline(
+ ToLayoutBox(GetLayoutObject()));
+ local_point += offset;
}
}
- if (GetLayoutObject().IsInFlowPositioned()) {
- PhysicalOffset new_offset = GetLayoutObject().OffsetForInFlowPosition();
+ if (GetLayoutObject().IsInFlowPositioned() &&
+ GetLayoutObject().IsRelPositioned()) {
+ auto new_offset = GetLayoutObject().OffsetForInFlowPosition();
if (rare_data_ || !new_offset.IsZero())
- EnsureRareData().offset_for_in_flow_position = new_offset;
- local_point += new_offset;
+ EnsureRareData().offset_for_in_flow_rel_position = new_offset;
} else if (rare_data_) {
- rare_data_->offset_for_in_flow_position = PhysicalOffset();
+ rare_data_->offset_for_in_flow_rel_position = PhysicalOffset();
}
-
location_ = local_point;
#if DCHECK_IS_ON()
@@ -983,9 +953,15 @@ PaintLayer* PaintLayer::CompositingContainer() const {
return Parent();
if (!GetLayoutObject().StyleRef().IsStacked())
return IsSelfPaintingLayer() ? Parent() : ContainingLayer();
- if (PaintLayerStackingNode* ancestor_stacking_node =
- PaintLayerStackingNode::AncestorStackingContextNode(this))
- return ancestor_stacking_node->Layer();
+ return AncestorStackingContext();
+}
+
+PaintLayer* PaintLayer::AncestorStackingContext() const {
+ for (PaintLayer* ancestor = Parent(); ancestor;
+ ancestor = ancestor->Parent()) {
+ if (ancestor->GetLayoutObject().StyleRef().IsStackingContext())
+ return ancestor;
+ }
return nullptr;
}
@@ -1090,14 +1066,10 @@ void PaintLayer::SetNeedsCompositingInputsUpdateInternal() {
current->child_needs_compositing_inputs_update_ = true;
if (Compositor() &&
current->GetLayoutObject().ShouldApplyStrictContainment() &&
- // TODO(rego): Disable CompositingInputsRoot optimization if the
- // "contain: strict" element has "position: sticky". This was causing
- // crashes because PaintLayerScrollableArea::sticky_constraints_map_ was
- // not updated correctly in some cases (see crbug.com/949887).
- !current->GetLayoutObject().IsStickyPositioned() &&
- // TODO(rego): Disable CompositingInputsRoot optimization for iframes
- // (see crbug.com/953159).
- !current->GetLayoutObject().IsLayoutIFrame())
+ // TODO(rego) this condition should be removeable but doing so causes
+ // security asan errors (crbug.com/985646) as well as ubsan errors
+ // (crbug.com/986008).
+ !current->GetLayoutObject().IsStickyPositioned())
break;
}
@@ -1308,12 +1280,16 @@ void PaintLayer::operator delete(void* ptr) {
}
void PaintLayer::AddChild(PaintLayer* child, PaintLayer* before_child) {
+#if DCHECK_IS_ON()
+ DCHECK(layer_list_mutation_allowed_);
+#endif
+
PaintLayer* prev_sibling =
before_child ? before_child->PreviousSibling() : LastChild();
if (prev_sibling) {
child->SetPreviousSibling(prev_sibling);
prev_sibling->SetNextSibling(child);
- DCHECK(prev_sibling != child);
+ DCHECK_NE(prev_sibling, child);
} else {
SetFirstChild(child);
}
@@ -1321,7 +1297,7 @@ void PaintLayer::AddChild(PaintLayer* child, PaintLayer* before_child) {
if (before_child) {
before_child->SetPreviousSibling(child);
child->SetNextSibling(before_child);
- DCHECK(before_child != child);
+ DCHECK_NE(before_child, child);
} else {
SetLastChild(child);
}
@@ -1346,8 +1322,7 @@ void PaintLayer::AddChild(PaintLayer* child, PaintLayer* before_child) {
// ancestorStackingContextNode() can be null in the case where we're
// building up generated content layers. This is ok, since the lists will
// start off dirty in that case anyway.
- PaintLayerStackingNode::DirtyStackingContextZOrderLists(child);
- MarkAncestorChainForFlagsUpdate();
+ child->DirtyStackingContextZOrderLists();
}
// Non-self-painting children paint into this layer, so the visible contents
@@ -1363,7 +1338,11 @@ void PaintLayer::AddChild(PaintLayer* child, PaintLayer* before_child) {
child->SetNeedsRepaint();
}
-PaintLayer* PaintLayer::RemoveChild(PaintLayer* old_child) {
+void PaintLayer::RemoveChild(PaintLayer* old_child) {
+#if DCHECK_IS_ON()
+ DCHECK(layer_list_mutation_allowed_);
+#endif
+
old_child->MarkCompositingContainerChainForNeedsRepaint();
if (old_child->PreviousSibling())
@@ -1385,7 +1364,7 @@ PaintLayer* PaintLayer::RemoveChild(PaintLayer* old_child) {
Compositor()->SetNeedsCompositingUpdate(kCompositingUpdateRebuildTree);
}
// Dirty the z-order list in which we are contained.
- PaintLayerStackingNode::DirtyStackingContextZOrderLists(old_child);
+ old_child->DirtyStackingContextZOrderLists();
SetNeedsCompositingInputsUpdate();
}
@@ -1405,8 +1384,6 @@ PaintLayer* PaintLayer::RemoveChild(PaintLayer* old_child) {
if (old_child->EnclosingPaginationLayer())
old_child->ClearPaginationRecursive();
-
- return old_child;
}
void PaintLayer::ClearClipRects(ClipRectsCacheSlot cache_slot) {
@@ -1419,10 +1396,8 @@ void PaintLayer::RemoveOnlyThisLayerAfterStyleChange(
if (!parent_)
return;
- if (old_style && old_style->IsStacked()) {
- PaintLayerStackingNode::DirtyStackingContextZOrderLists(this);
- MarkAncestorChainForFlagsUpdate();
- }
+ if (old_style && old_style->IsStacked())
+ DirtyStackingContextZOrderLists();
bool did_set_paint_invalidation = false;
if (!RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) {
@@ -1557,6 +1532,13 @@ static inline const PaintLayer* AccumulateOffsetTowardsAncestor(
return nullptr;
location += layer->Location();
+ if (layer->GetLayoutObject().IsRelPositioned()) {
+ location += layer->OffsetForInFlowRelPosition();
+ } else if (layer->GetLayoutObject().IsInFlowPositioned()) {
+ location += layer->GetLayoutObject().OffsetForInFlowPosition();
+ }
+ location -= PhysicalOffset(containing_layer->ScrolledContentOffset());
+
return containing_layer;
}
@@ -1614,10 +1596,18 @@ void PaintLayer::DidUpdateScrollsOverflow() {
UpdateSelfPaintingLayer();
}
-void PaintLayer::UpdateStackingNode(bool needs_stacking_node) {
+void PaintLayer::UpdateStackingNode() {
+#if DCHECK_IS_ON()
+ DCHECK(layer_list_mutation_allowed_);
+#endif
+
+ bool needs_stacking_node =
+ has_stacked_descendant_in_current_stacking_context_ &&
+ GetLayoutObject().StyleRef().IsStackingContext();
+
if (needs_stacking_node != !!stacking_node_) {
if (needs_stacking_node)
- stacking_node_ = std::make_unique<PaintLayerStackingNode>(this);
+ stacking_node_ = std::make_unique<PaintLayerStackingNode>(*this);
else
stacking_node_ = nullptr;
}
@@ -1642,11 +1632,15 @@ bool PaintLayer::RequiresScrollableArea() const {
void PaintLayer::UpdateScrollableArea() {
if (RequiresScrollableArea() && !scrollable_area_) {
scrollable_area_ = PaintLayerScrollableArea::Create(*this);
- Compositor()->SetNeedsCompositingUpdate(kCompositingUpdateRebuildTree);
+ if (Compositor()) {
+ Compositor()->SetNeedsCompositingUpdate(kCompositingUpdateRebuildTree);
+ }
} else if (!RequiresScrollableArea() && scrollable_area_) {
scrollable_area_->Dispose();
scrollable_area_.Clear();
- Compositor()->SetNeedsCompositingUpdate(kCompositingUpdateRebuildTree);
+ if (Compositor()) {
+ Compositor()->SetNeedsCompositingUpdate(kCompositingUpdateRebuildTree);
+ }
}
}
@@ -1791,7 +1785,7 @@ void PaintLayer::CollectFragments(
}
PaintLayer::HitTestRecursionData::HitTestRecursionData(
- const LayoutRect& rect_arg,
+ const PhysicalRect& rect_arg,
const HitTestLocation& location_arg,
const HitTestLocation& original_location_arg)
: rect(rect_arg),
@@ -1801,7 +1795,7 @@ PaintLayer::HitTestRecursionData::HitTestRecursionData(
bool PaintLayer::HitTest(const HitTestLocation& hit_test_location,
HitTestResult& result,
- const LayoutRect& hit_test_area) {
+ const PhysicalRect& hit_test_area) {
DCHECK(IsSelfPaintingLayer() || HasSelfPaintingLayerDescendant());
// LayoutView should make sure to update layout before entering hit testing
@@ -1835,9 +1829,7 @@ bool PaintLayer::HitTest(const HitTestLocation& hit_test_location,
fallback = true;
}
if (fallback) {
- GetLayoutObject().UpdateHitTestResult(
- result, ToLayoutView(GetLayoutObject())
- .DeprecatedFlipForWritingMode(hit_test_location.Point()));
+ GetLayoutObject().UpdateHitTestResult(result, hit_test_location.Point());
inside_layer = this;
// Don't cache this result since it really wasn't a true hit.
@@ -1866,8 +1858,8 @@ Node* PaintLayer::EnclosingNode() const {
}
bool PaintLayer::IsInTopLayer() const {
- Node* node = GetLayoutObject().GetNode();
- return node && node->IsElementNode() && ToElement(node)->IsInTopLayer();
+ auto* element = DynamicTo<Element>(GetLayoutObject().GetNode());
+ return element && element->IsInTopLayer();
}
// Compute the z-offset of the point in the transformState.
@@ -1894,7 +1886,7 @@ HitTestingTransformState PaintLayer::CreateLocalTransformState(
PaintLayer* container_layer,
const HitTestRecursionData& recursion_data,
const HitTestingTransformState* container_transform_state,
- const LayoutPoint& translation_offset) const {
+ const PhysicalOffset& translation_offset) const {
// If we're already computing transform state, then it's relative to the
// container (which we know is non-null).
// If this is the first time we need to make transform state, then base it
@@ -1912,7 +1904,7 @@ HitTestingTransformState PaintLayer::CreateLocalTransformState(
else
ConvertToLayerCoords(root_layer, offset);
- offset += PhysicalOffsetToBeNoop(translation_offset);
+ offset += translation_offset;
LayoutObject* container_layout_object =
container_layer ? &container_layer->GetLayoutObject() : nullptr;
@@ -1979,9 +1971,6 @@ PaintLayer* PaintLayer::HitTestLayer(PaintLayer* root_layer,
HitTestingTransformState* transform_state,
double* z_offset) {
const LayoutObject& layout_object = GetLayoutObject();
- if (layout_object.PaintBlockedByDisplayLock())
- return nullptr;
-
DCHECK_GE(layout_object.GetDocument().Lifecycle().GetState(),
DocumentLifecycle::kCompositingClean);
@@ -2125,7 +2114,7 @@ PaintLayer* PaintLayer::HitTestLayer(PaintLayer* root_layer,
// Collect the fragments. This will compute the clip rectangles for each
// layer fragment.
base::Optional<PaintLayerFragments> layer_fragments;
- LayoutPoint offset;
+ PhysicalOffset offset;
if (recursion_data.intersects_location) {
layer_fragments.emplace();
if (applied_transform) {
@@ -2149,12 +2138,13 @@ PaintLayer* PaintLayer::HitTestLayer(PaintLayer* root_layer,
// Next we want to see if the mouse pos is inside the child LayoutObjects of
// the layer. Check every fragment in reverse order.
- if (IsSelfPaintingLayer()) {
- offset = -LayoutBoxLocation();
+ if (IsSelfPaintingLayer() && !layout_object.PaintBlockedByDisplayLock(
+ DisplayLockContext::kChildren)) {
// Hit test with a temporary HitTestResult, because we only want to commit
// to 'result' if we know we're frontmost.
HitTestResult temp_result(result.GetHitTestRequest(),
recursion_data.original_location);
+ temp_result.SetInertNode(result.InertNode());
bool inside_fragment_foreground_rect = false;
if (HitTestContentsForFragments(
@@ -2174,6 +2164,8 @@ PaintLayer* PaintLayer::HitTestLayer(PaintLayer* root_layer,
} else if (inside_fragment_foreground_rect &&
result.GetHitTestRequest().ListBased()) {
result.Append(temp_result);
+ } else if (result.GetHitTestRequest().RetargetForInert()) {
+ result.SetInertNode(temp_result.InertNode());
}
}
}
@@ -2197,6 +2189,7 @@ PaintLayer* PaintLayer::HitTestLayer(PaintLayer* root_layer,
if (recursion_data.intersects_location && IsSelfPaintingLayer()) {
HitTestResult temp_result(result.GetHitTestRequest(),
recursion_data.original_location);
+ temp_result.SetInertNode(result.InertNode());
bool inside_fragment_background_rect = false;
if (HitTestContentsForFragments(*layer_fragments, offset, temp_result,
recursion_data.location, kHitTestSelf,
@@ -2208,6 +2201,8 @@ PaintLayer* PaintLayer::HitTestLayer(PaintLayer* root_layer,
else
result = temp_result;
return this;
+ } else if (result.GetHitTestRequest().RetargetForInert()) {
+ result.SetInertNode(temp_result.InertNode());
}
if (inside_fragment_background_rect &&
result.GetHitTestRequest().ListBased())
@@ -2219,7 +2214,7 @@ PaintLayer* PaintLayer::HitTestLayer(PaintLayer* root_layer,
bool PaintLayer::HitTestContentsForFragments(
const PaintLayerFragments& layer_fragments,
- const LayoutPoint& offset,
+ const PhysicalOffset& offset,
HitTestResult& result,
const HitTestLocation& hit_test_location,
HitTestFilter hit_test_filter,
@@ -2235,8 +2230,8 @@ bool PaintLayer::HitTestContentsForFragments(
!fragment.foreground_rect.Intersects(hit_test_location)))
continue;
inside_clip_rect = true;
- LayoutPoint fragment_offset = offset;
- fragment_offset.MoveBy(fragment.layer_bounds.offset.ToLayoutPoint());
+ PhysicalOffset fragment_offset = offset;
+ fragment_offset += fragment.layer_bounds.offset;
if (HitTestContents(result, fragment_offset, hit_test_location,
hit_test_filter))
return true;
@@ -2265,12 +2260,12 @@ PaintLayer* PaintLayer::HitTestTransformedLayerInFragments(
// Apply the page/column clip for this fragment, as well as any clips
// established by layers in between us and the enclosing pagination layer.
PhysicalRect clip_rect = fragment.background_rect.Rect();
- if (!recursion_data.location.Intersects(clip_rect.ToLayoutRect()))
+ if (!recursion_data.location.Intersects(clip_rect))
continue;
PaintLayer* hit_layer = HitTestLayerByApplyingTransform(
root_layer, container_layer, result, recursion_data, transform_state,
- z_offset, fragment.fragment_data->PaginationOffset().ToLayoutPoint());
+ z_offset, fragment.fragment_data->PaginationOffset());
if (hit_layer)
return hit_layer;
}
@@ -2285,7 +2280,7 @@ PaintLayer* PaintLayer::HitTestLayerByApplyingTransform(
const HitTestRecursionData& recursion_data,
HitTestingTransformState* transform_state,
double* z_offset,
- const LayoutPoint& translation_offset) {
+ const PhysicalOffset& translation_offset) {
// Create a transform state to accumulate this transform.
HitTestingTransformState new_transform_state =
CreateLocalTransformState(root_layer, container_layer, recursion_data,
@@ -2304,7 +2299,7 @@ PaintLayer* PaintLayer::HitTestLayerByApplyingTransform(
// been flattened (losing z) by our container.
FloatPoint local_point = new_transform_state.MappedPoint();
FloatQuad local_point_quad = new_transform_state.MappedQuad();
- LayoutRect bounds_of_mapped_area = new_transform_state.BoundsOfMappedArea();
+ PhysicalRect bounds_of_mapped_area = new_transform_state.BoundsOfMappedArea();
base::Optional<HitTestLocation> new_location;
if (recursion_data.location.IsRectBasedTest())
new_location.emplace(local_point, local_point_quad);
@@ -2319,7 +2314,7 @@ PaintLayer* PaintLayer::HitTestLayerByApplyingTransform(
}
bool PaintLayer::HitTestContents(HitTestResult& result,
- const LayoutPoint& fragment_offset,
+ const PhysicalOffset& fragment_offset,
const HitTestLocation& hit_test_location,
HitTestFilter hit_test_filter) const {
DCHECK(IsSelfPaintingLayer() || HasSelfPaintingLayerDescendant());
@@ -2386,7 +2381,7 @@ void PaintLayer::SetNeedsCompositingRequirementsUpdate() {
}
PaintLayer* PaintLayer::HitTestChildren(
- ChildrenIteration childrento_visit,
+ PaintLayerIteration children_to_visit,
PaintLayer* root_layer,
HitTestResult& result,
const HitTestRecursionData& recursion_data,
@@ -2398,15 +2393,15 @@ PaintLayer* PaintLayer::HitTestChildren(
if (!HasSelfPaintingLayerDescendant())
return nullptr;
- if (!stacking_node_)
+ if (GetLayoutObject().PaintBlockedByDisplayLock(
+ DisplayLockContext::kChildren))
return nullptr;
const LayoutObject* stop_node = result.GetHitTestRequest().GetStopNode();
PaintLayer* stop_layer = stop_node ? stop_node->PaintingLayer() : nullptr;
PaintLayer* result_layer = nullptr;
- PaintLayerStackingNodeReverseIterator iterator(*stacking_node_,
- childrento_visit);
+ PaintLayerPaintOrderReverseIterator iterator(*this, children_to_visit);
while (PaintLayer* child_layer = iterator.Next()) {
if (child_layer->IsReplacedNormalFlowStacking())
continue;
@@ -2421,6 +2416,7 @@ PaintLayer* PaintLayer::HitTestChildren(
PaintLayer* hit_layer = nullptr;
HitTestResult temp_result(result.GetHitTestRequest(),
recursion_data.original_location);
+ temp_result.SetInertNode(result.InertNode());
hit_layer = child_layer->HitTestLayer(
root_layer, this, temp_result, recursion_data, false, transform_state,
z_offset_for_descendants);
@@ -2437,6 +2433,8 @@ PaintLayer* PaintLayer::HitTestChildren(
result = temp_result;
if (!depth_sort_descendants)
break;
+ } else if (result.GetHitTestRequest().RetargetForInert()) {
+ result.SetInertNode(temp_result.InertNode());
}
}
@@ -2453,6 +2451,8 @@ void PaintLayer::UpdateFilterReferenceBox() {
float zoom = GetLayoutObject().StyleRef().EffectiveZoom();
if (zoom != 1)
reference_box.Scale(1 / zoom);
+ if (!ResourceInfo() || ResourceInfo()->FilterReferenceBox() != reference_box)
+ GetLayoutObject().SetNeedsPaintPropertyUpdate();
EnsureResourceInfo().SetFilterReferenceBox(reference_box);
}
@@ -2503,7 +2503,7 @@ bool PaintLayer::HitTestClippedOutByClipPath(
else
ConvertToLayerCoords(root_layer, origin);
- FloatPoint point(hit_test_location.Point() - origin.offset.ToLayoutPoint());
+ FloatPoint point(hit_test_location.Point() - origin.offset);
FloatRect reference_box(
ClipPathClipper::LocalReferenceBox(GetLayoutObject()));
@@ -2623,18 +2623,7 @@ void PaintLayer::ExpandRectForStackingChildren(
const PaintLayer& composited_layer,
PhysicalRect& result,
PaintLayer::CalculateBoundsOptions options) const {
- if (!StackingNode())
- return;
-
- DCHECK(GetLayoutObject().StyleRef().IsStackingContext() ||
- !StackingNode()->HasPositiveZOrderList());
-
-#if DCHECK_IS_ON()
- LayerListMutationDetector mutation_checker(
- const_cast<PaintLayer*>(this)->StackingNode());
-#endif
-
- PaintLayerStackingNodeIterator iterator(*StackingNode(), kAllChildren);
+ PaintLayerPaintOrderIterator iterator(*this, kAllChildren);
while (PaintLayer* child_layer = iterator.Next()) {
// Here we exclude both directly composited layers and squashing layers
// because those Layers don't paint into the graphics layer
@@ -2806,16 +2795,19 @@ void PaintLayer::ClearCompositedLayerMapping(bool layer_being_destroyed) {
if (!RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) {
// The visual rects will be in a different coordinate space after losing
// their compositing container. Clear them before prepaint to avoid
- // spurious layout shift reports from JankTracker.
+ // spurious layout shift reports from LayoutShiftTracker.
// If the PaintLayer were not being destroyed, this would happen during
// the compositing update (PaintLayerCompositor::UpdateIfNeeded).
- // TODO: JankTracker's reliance on having visual rects cleared before
- // prepaint in the case of compositing changes is not ideal, and will not
- // work with CompositeAfterPaint. Some transform tree changes may still
- // produce incorrect behavior from JankTracker (see discussion on review
- // thread of http://crrev.com/c/1636403).
- Compositor()->ForceRecomputeVisualRectsIncludingNonCompositingDescendants(
- layout_object_);
+ // TODO: LayoutShiftTracker's reliance on having visual rects cleared
+ // before prepaint in the case of compositing changes is not ideal, and
+ // will not work with CompositeAfterPaint. Some transform tree changes may
+ // still produce incorrect behavior from LayoutShiftTracker (see
+ // discussion on review thread of http://crrev.com/c/1636403).
+ if (Compositor()) {
+ Compositor()
+ ->ForceRecomputeVisualRectsIncludingNonCompositingDescendants(
+ layout_object_);
+ }
}
} else {
// We need to make sure our decendants get a geometry update. In principle,
@@ -2948,12 +2940,7 @@ bool PaintLayer::BackgroundIsKnownToBeOpaqueInRect(
bool PaintLayer::ChildBackgroundIsKnownToBeOpaqueInRect(
const PhysicalRect& local_rect) const {
- if (!stacking_node_)
- return false;
-
- PaintLayerStackingNodeReverseIterator reverse_iterator(
- *stacking_node_,
- kPositiveZOrderChildren | kNormalFlowChildren | kNegativeZOrderChildren);
+ PaintLayerPaintOrderReverseIterator reverse_iterator(*this, kAllChildren);
while (PaintLayer* child_layer = reverse_iterator.Next()) {
// Stop at composited paint boundaries and non-self-painting layers.
if (child_layer->IsPaintInvalidationContainer())
@@ -3174,7 +3161,7 @@ void PaintLayer::StyleDidChange(StyleDifference diff,
return;
}
- if (PaintLayerStackingNode::StyleDidChange(this, old_style))
+ if (PaintLayerStackingNode::StyleDidChange(*this, old_style))
MarkAncestorChainForFlagsUpdate();
if (RequiresScrollableArea()) {
@@ -3249,15 +3236,10 @@ void PaintLayer::StyleDidChange(StyleDifference diff,
}
}
-PhysicalOffset PaintLayer::LocationInternal() const {
- PhysicalOffset result = location_;
- PaintLayer* containing_layer = ContainingLayer();
- if (containing_layer && containing_layer->IsRootLayer() &&
- containing_layer->GetLayoutObject().HasOverflowClip()) {
- result -= PhysicalOffset(
- containing_layer->GetLayoutBox()->ScrolledContentOffset());
- }
- return result;
+LayoutSize PaintLayer::ScrolledContentOffset() const {
+ if (GetLayoutObject().HasOverflowClip())
+ return GetLayoutBox()->ScrolledContentOffset();
+ return LayoutSize();
}
PaintLayerClipper PaintLayer::Clipper(
@@ -3339,7 +3321,9 @@ PaintLayer::CreateCompositorFilterOperationsForBackdropFilter() const {
return_value = FilterEffectBuilder(reference_box, zoom, nullptr, nullptr,
SkBlurImageFilter::kClamp_TileMode)
.BuildFilterOperations(filter_operations);
- DCHECK(!return_value.IsEmpty());
+ // Note that return_value may be empty here, if the |filter_operations| list
+ // contains only invalid filters (e.g. invalid reference filters). See
+ // https://crbug.com/983157 for details.
return return_value;
}
@@ -3512,6 +3496,25 @@ const PaintLayer* PaintLayer::CommonAncestor(const PaintLayer* other) const {
return nullptr;
}
+void PaintLayer::DirtyStackingContextZOrderLists() {
+ auto* stacking_context = AncestorStackingContext();
+ if (!stacking_context)
+ return;
+
+ // 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.
+ if (auto* mapping = stacking_context->GetCompositedLayerMapping())
+ mapping->SetNeedsGraphicsLayerUpdate(kGraphicsLayerUpdateSubtree);
+
+ if (stacking_context->StackingNode())
+ stacking_context->StackingNode()->DirtyZOrderLists();
+
+ MarkAncestorChainForFlagsUpdate();
+}
+
DisableCompositingQueryAsserts::DisableCompositingQueryAsserts()
: disabler_(&g_compositing_query_mode, kCompositingQueriesAreAllowed) {}
@@ -3537,7 +3540,7 @@ void showLayerTree(const blink::PaintLayer* layer) {
blink::kLayoutAsTextShowLayoutState |
blink::kLayoutAsTextShowPaintProperties,
layer);
- LOG(ERROR) << output.Utf8().data();
+ LOG(ERROR) << output.Utf8();
}
}
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 d0707842cf7..e9e2843d84c 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_layer.h
+++ b/chromium/third_party/blink/renderer/core/paint/paint_layer.h
@@ -56,13 +56,12 @@
#include "third_party/blink/renderer/core/paint/paint_layer_fragment.h"
#include "third_party/blink/renderer/core/paint/paint_layer_resource_info.h"
#include "third_party/blink/renderer/core/paint/paint_layer_stacking_node.h"
-#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/scroll_types.h"
#include "third_party/blink/renderer/platform/graphics/squashing_disallowed_reasons.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -87,6 +86,23 @@ enum CompositingQueryMode {
kCompositingQueriesAreOnlyAllowedInCertainDocumentLifecyclePhases
};
+// Used in PaintLayerPaintOrderIterator.
+enum PaintLayerIteration {
+ kNegativeZOrderChildren = 1,
+ // Normal flow children are not mandated by CSS 2.1 but are an artifact of
+ // our implementation: we allocate PaintLayers for elements that
+ // are not treated as stacking contexts and thus we need to walk them
+ // during painting and hit-testing.
+ kNormalFlowChildren = 1 << 1,
+ kPositiveZOrderChildren = 1 << 2,
+
+ kStackedChildren = kNegativeZOrderChildren | kPositiveZOrderChildren,
+ kNormalFlowAndPositiveZOrderChildren =
+ kNormalFlowChildren | kPositiveZOrderChildren,
+ kAllChildren =
+ kNegativeZOrderChildren | kNormalFlowChildren | kPositiveZOrderChildren
+};
+
// FIXME: remove this once the compositing query DCHECKS are no longer hit.
class CORE_EXPORT DisableCompositingQueryAsserts {
STACK_ALLOCATED();
@@ -106,8 +122,9 @@ struct PaintLayerRareData {
PaintLayerRareData();
~PaintLayerRareData();
- // Our current relative position offset.
- PhysicalOffset offset_for_in_flow_position;
+ // The offset for an in-flow relative-positioned PaintLayer. This is not
+ // set by any other style.
+ PhysicalOffset offset_for_in_flow_rel_position;
std::unique_ptr<TransformationMatrix> transform;
@@ -250,9 +267,10 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
// good but we can't use it for now because it conflicts with
// PaintInfo::paintContainer.
PaintLayer* CompositingContainer() const;
+ PaintLayer* AncestorStackingContext() const;
void AddChild(PaintLayer* new_child, PaintLayer* before_child = nullptr);
- PaintLayer* RemoveChild(PaintLayer*);
+ void RemoveChild(PaintLayer*);
void ClearClipRects(ClipRectsCacheSlot = kNumberOfClipRectsCacheSlots);
@@ -277,13 +295,18 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
return curr;
}
- PhysicalOffset Location() const {
+ // The physical offset from this PaintLayer to its ContainingLayer.
+ // Does not include any scroll offset of the ContainingLayer. Also does not
+ // include offsets for positioned elements.
+ const PhysicalOffset& Location() const {
#if DCHECK_IS_ON()
DCHECK(!needs_position_update_);
#endif
- return LocationInternal();
+ return location_;
}
+ LayoutSize ScrolledContentOffset() const;
+
// FIXME: size() should DCHECK(!needs_position_update_) as well, but that
// fails in some tests, for example, fast/repaint/clipped-relative.html.
const LayoutSize& Size() const { return size_; }
@@ -314,7 +337,6 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
void UpdateLayerPosition();
void UpdateLayerPositionsAfterLayout();
- void UpdateLayerPositionsAfterOverflowScroll();
PaintLayer* EnclosingPaginationLayer() const {
return rare_data_ ? rare_data_->enclosing_pagination_layer : nullptr;
@@ -324,14 +346,9 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
PaintLayer* RenderingContextRoot();
const PaintLayer* RenderingContextRoot() const;
- PhysicalOffset OffsetForInFlowPosition() const {
- return rare_data_ ? rare_data_->offset_for_in_flow_position
- : PhysicalOffset();
- }
-
- PaintLayerStackingNode* StackingNode() { return stacking_node_.get(); }
- const PaintLayerStackingNode* StackingNode() const {
- return stacking_node_.get();
+ bool IsStackingContextWithNegativeZOrderChildren() const {
+ DCHECK(!stacking_node_ || GetLayoutObject().StyleRef().IsStackingContext());
+ return stacking_node_ && !stacking_node_->NegZOrderList().IsEmpty();
}
bool SubtreeIsInvisible() const {
@@ -426,7 +443,7 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
// LayoutObject to consider for hit testing.
bool HitTest(const HitTestLocation& location,
HitTestResult&,
- const LayoutRect& hit_test_area);
+ const PhysicalRect& hit_test_area);
bool IntersectsDamageRect(const PhysicalRect& layer_bounds,
const PhysicalRect& damage_rect,
@@ -598,13 +615,6 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
bool BackgroundIsKnownToBeOpaqueInRect(const PhysicalRect&,
bool should_check_children) const;
- bool ContainsDirtyOverlayScrollbars() const {
- return contains_dirty_overlay_scrollbars_;
- }
- void SetContainsDirtyOverlayScrollbars(bool dirty_scrollbars) {
- contains_dirty_overlay_scrollbars_ = dirty_scrollbars;
- }
-
// If the input CompositorFilterOperation is not empty, it will be populated
// only if |filter_on_effect_node_dirty_| is true or the reference box has
// changed. Otherwise it will be populated unconditionally.
@@ -635,7 +645,9 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
void SetIsUnderSVGHiddenContainer(bool value) {
is_under_svg_hidden_container_ = value;
}
- bool IsUnderSVGHiddenContainer() { return is_under_svg_hidden_container_; }
+ bool IsUnderSVGHiddenContainer() const {
+ return is_under_svg_hidden_container_;
+ }
bool PaintsWithFilters() const;
@@ -868,9 +880,10 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
DCHECK(!needs_descendant_dependent_flags_update_);
return has_self_painting_layer_descendant_;
}
- bool IsNonStackedWithInFlowStackedDescendant() const {
- DCHECK(!needs_descendant_dependent_flags_update_);
- return is_non_stacked_with_in_flow_stacked_descendant_;
+
+ // See PaintLayerStackingNode::layer_to_overlay_scrollbars_painting_after_.
+ bool NeedsReorderOverlayScrollbars() const {
+ return needs_reorder_overlay_scrollbars_;
}
// Returns true if there is a descendant with blend-mode that is
@@ -955,11 +968,6 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
const PhysicalOffset* offset_from_root = nullptr,
const PhysicalOffset& sub_pixel_accumulation = PhysicalOffset()) const;
- LayoutPoint LayoutBoxLocation() const {
- return GetLayoutObject().IsBox() ? ToLayoutBox(GetLayoutObject()).Location()
- : LayoutPoint();
- }
-
enum TransparencyClipBoxBehavior {
kPaintingTransparencyClipBox,
kHitTestingTransparencyClipBox
@@ -1089,6 +1097,7 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
}
PaintLayerStackingNode* StackingParent() { return stacking_parent_; }
bool IsInStackingParentZOrderLists() const;
+ bool LayerListMutationAllowed() const { return layer_list_mutation_allowed_; }
#endif
void SetNeedsCompositingLayerAssignment();
@@ -1101,6 +1110,17 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
return descendant_needs_compositing_layer_assignment_;
}
+ void DirtyStackingContextZOrderLists();
+
+ bool NeedsVisualOverflowRecalcForTesting() const {
+ return needs_visual_overflow_recalc_;
+ }
+
+ PhysicalOffset OffsetForInFlowRelPosition() const {
+ return rare_data_ ? rare_data_->offset_for_in_flow_rel_position
+ : PhysicalOffset();
+ }
+
private:
void SetNeedsCompositingInputsUpdateInternal();
@@ -1111,9 +1131,7 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
bool HasOverflowControls() const;
- enum UpdateLayerPositionBehavior { AllLayers, OnlyStickyLayers };
- void UpdateLayerPositionRecursive(UpdateLayerPositionBehavior = AllLayers,
- bool dirty_compositing_if_needed = true);
+ void UpdateLayerPositionRecursive();
void SetNextSibling(PaintLayer* next) { next_ = next; }
void SetPreviousSibling(PaintLayer* prev) { previous_ = prev; }
@@ -1123,12 +1141,12 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
void UpdateHasSelfPaintingLayerDescendant() const;
struct HitTestRecursionData {
- const LayoutRect& rect;
+ const PhysicalRect& rect;
// Whether location.Intersects(rect) returns true.
const HitTestLocation& location;
const HitTestLocation& original_location;
const bool intersects_location;
- HitTestRecursionData(const LayoutRect& rect_arg,
+ HitTestRecursionData(const PhysicalRect& rect_arg,
const HitTestLocation& location_arg,
const HitTestLocation& original_location_arg);
};
@@ -1147,9 +1165,9 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
const HitTestRecursionData& recursion_data,
HitTestingTransformState* = nullptr,
double* z_offset = nullptr,
- const LayoutPoint& translation_offset = LayoutPoint());
+ const PhysicalOffset& translation_offset = PhysicalOffset());
PaintLayer* HitTestChildren(
- ChildrenIteration,
+ PaintLayerIteration,
PaintLayer* root_layer,
HitTestResult&,
const HitTestRecursionData& recursion_data,
@@ -1164,14 +1182,14 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
PaintLayer* container_layer,
const HitTestRecursionData& recursion_data,
const HitTestingTransformState* container_transform_state,
- const LayoutPoint& translation_offset = LayoutPoint()) const;
+ const PhysicalOffset& translation_offset = PhysicalOffset()) const;
bool HitTestContents(HitTestResult&,
- const LayoutPoint& fragment_offset,
+ const PhysicalOffset& fragment_offset,
const HitTestLocation&,
HitTestFilter) const;
bool HitTestContentsForFragments(const PaintLayerFragments&,
- const LayoutPoint& offset,
+ const PhysicalOffset& offset,
HitTestResult&,
const HitTestLocation&,
HitTestFilter,
@@ -1190,7 +1208,7 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
bool ShouldBeSelfPaintingLayer() const;
- void UpdateStackingNode(bool needs_stacking_node);
+ void UpdateStackingNode();
FilterOperations FilterOperationsIncludingReflection() const;
@@ -1251,8 +1269,6 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
bool NeedsFilterReferenceBox() const;
- PhysicalOffset LocationInternal() const;
-
AncestorDependentCompositingInputs& EnsureAncestorDependentCompositingInputs()
const {
if (!ancestor_dependent_compositing_inputs_) {
@@ -1262,6 +1278,14 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
return *ancestor_dependent_compositing_inputs_;
}
+ // This is private because PaintLayerStackingNode is only for PaintLayer and
+ // PaintLayerPaintOrderIterator.
+ PaintLayerStackingNode* StackingNode() const { return stacking_node_.get(); }
+
+ void SetNeedsReorderOverlayScrollbars(bool b) {
+ needs_reorder_overlay_scrollbars_ = b;
+ }
+
// Self-painting layer is an optimization where we avoid the heavy Layer
// painting machinery for a Layer allocated only to handle the overflow clip
// case.
@@ -1286,8 +1310,6 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
// in a preserves3D hierarchy. Hint to do 3D-aware hit testing.
unsigned has3d_transformed_descendant_ : 1;
- unsigned contains_dirty_overlay_scrollbars_ : 1;
-
unsigned needs_ancestor_dependent_compositing_inputs_update_ : 1;
unsigned child_needs_compositing_inputs_update_ : 1;
@@ -1319,6 +1341,7 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
unsigned has_fixed_position_descendant_ : 1;
unsigned has_sticky_position_descendant_ : 1;
unsigned has_non_contained_absolute_position_descendant_ : 1;
+ unsigned has_stacked_descendant_in_current_stacking_context_ : 1;
unsigned self_painting_status_changed_ : 1;
@@ -1341,7 +1364,12 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
unsigned descendant_needs_compositing_layer_assignment_ : 1;
unsigned has_self_painting_layer_descendant_ : 1;
- unsigned is_non_stacked_with_in_flow_stacked_descendant_ : 1;
+
+ unsigned needs_reorder_overlay_scrollbars_ : 1;
+
+#if DCHECK_IS_ON()
+ mutable unsigned layer_list_mutation_allowed_ : 1;
+#endif
LayoutBoxModelObject& layout_object_;
@@ -1385,6 +1413,14 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
PaintLayerStackingNode* stacking_parent_;
#endif
+ // For layer_list_mutation_allowed_.
+ friend class PaintLayerListMutationDetector;
+
+ // For stacking_node_ to avoid exposing it publicly.
+ friend class PaintLayerPaintOrderIterator;
+ friend class PaintLayerPaintOrderReverseIterator;
+ friend class PaintLayerStackingNode;
+
FRIEND_TEST_ALL_PREFIXES(PaintLayerTest,
DescendantDependentFlagsStopsAtThrottledFrames);
FRIEND_TEST_ALL_PREFIXES(PaintLayerTest,
@@ -1393,6 +1429,27 @@ class CORE_EXPORT PaintLayer : public DisplayItemClient {
DISALLOW_COPY_AND_ASSIGN(PaintLayer);
};
+#if DCHECK_IS_ON()
+class PaintLayerListMutationDetector {
+ STACK_ALLOCATED();
+
+ public:
+ explicit PaintLayerListMutationDetector(const PaintLayer& layer)
+ : layer_(layer),
+ previous_mutation_allowed_state_(layer.layer_list_mutation_allowed_) {
+ layer.layer_list_mutation_allowed_ = false;
+ }
+
+ ~PaintLayerListMutationDetector() {
+ layer_.layer_list_mutation_allowed_ = previous_mutation_allowed_state_;
+ }
+
+ private:
+ const PaintLayer& layer_;
+ bool previous_mutation_allowed_state_;
+};
+#endif
+
} // namespace blink
#if DCHECK_IS_ON()
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 b368608d5b0..0f24a005540 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
@@ -248,7 +248,7 @@ PhysicalRect PaintLayerClipper::LocalClipRect(
clipped_rect_in_local_space.MoveBy(
-FloatPoint(layer_.GetLayoutObject().FirstFragment().PaintOffset()));
- return PhysicalRect::EnclosingRect(clipped_rect_in_local_space);
+ return PhysicalRect::FastAndLossyFromFloatRect(clipped_rect_in_local_space);
}
PhysicalRect layer_bounds;
@@ -289,7 +289,7 @@ void PaintLayerClipper::CalculateRectsWithGeometryMapper(
fragment_data.PreTransform(),
context.root_fragment->LocalBorderBoxProperties().Transform(),
float_bounds);
- layer_bounds = PhysicalRect::EnclosingRect(float_bounds);
+ layer_bounds = PhysicalRect::FastAndLossyFromFloatRect(float_bounds);
layer_bounds.offset -= context.root_fragment->PaintOffset();
}
}
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 7f7f2c92786..bf102b160db 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
@@ -49,7 +49,7 @@
#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/graphics/scroll_types.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 d97067a797c..e3b26f79ac6 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
@@ -26,8 +26,8 @@ class PaintLayerClipperTest : public RenderingTest {
}
void TearDown() override {
- WebTestSupport::SetMockThemeEnabledForTest(false);
RenderingTest::TearDown();
+ WebTestSupport::SetMockThemeEnabledForTest(false);
}
};
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_layer_fragment.h b/chromium/third_party/blink/renderer/core/paint/paint_layer_fragment.h
index a159871ad6b..6b0d2e3a7d7 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_layer_fragment.h
+++ b/chromium/third_party/blink/renderer/core/paint/paint_layer_fragment.h
@@ -27,7 +27,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_PAINT_LAYER_FRAGMENT_H_
#include "third_party/blink/renderer/core/paint/clip_rect.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_layer_stacking_node_iterator.cc b/chromium/third_party/blink/renderer/core/paint/paint_layer_paint_order_iterator.cc
index 076e289a1a3..0456b7a1ad8 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_layer_stacking_node_iterator.cc
+++ b/chromium/third_party/blink/renderer/core/paint/paint_layer_paint_order_iterator.cc
@@ -28,28 +28,20 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#include "third_party/blink/renderer/core/paint/paint_layer_stacking_node_iterator.h"
+#include "third_party/blink/renderer/core/paint/paint_layer_paint_order_iterator.h"
-// FIXME: We should build our primitive on top of
-// PaintLayerStackingNode and remove this include.
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/paint_layer_stacking_node.h"
namespace blink {
-PaintLayerStackingNodeIterator::PaintLayerStackingNodeIterator(
- const PaintLayerStackingNode& root,
- unsigned which_children)
- : root_(root), remaining_children_(which_children), index_(0) {
- current_normal_flow_child_ = root.Layer()->FirstChild();
-}
-
-PaintLayer* PaintLayerStackingNodeIterator::Next() {
+PaintLayer* PaintLayerPaintOrderIterator::Next() {
if (remaining_children_ & kNegativeZOrderChildren) {
- PaintLayerStackingNode::PaintLayers* neg_z_order_list =
- root_.NegZOrderList();
- if (neg_z_order_list && index_ < neg_z_order_list->size())
- return neg_z_order_list->at(index_++);
+ if (root_.StackingNode()) {
+ const auto& neg_z_order_list = root_.StackingNode()->NegZOrderList();
+ if (index_ < neg_z_order_list.size())
+ return neg_z_order_list[index_++];
+ }
index_ = 0;
remaining_children_ &= ~kNegativeZOrderChildren;
@@ -59,25 +51,25 @@ PaintLayer* PaintLayerStackingNodeIterator::Next() {
for (; current_normal_flow_child_;
current_normal_flow_child_ =
current_normal_flow_child_->NextSibling()) {
- if (!current_normal_flow_child_->GetLayoutObject()
- .StyleRef()
- .IsStacked()) {
- PaintLayer* normal_flow_child = current_normal_flow_child_;
- current_normal_flow_child_ = current_normal_flow_child_->NextSibling();
- return normal_flow_child;
- }
+ if (current_normal_flow_child_->GetLayoutObject().StyleRef().IsStacked())
+ continue;
+
+ PaintLayer* normal_flow_child = current_normal_flow_child_;
+ current_normal_flow_child_ = current_normal_flow_child_->NextSibling();
+ return normal_flow_child;
}
// We reset the iterator in case we reuse it.
- current_normal_flow_child_ = root_.Layer()->FirstChild();
+ current_normal_flow_child_ = root_.FirstChild();
remaining_children_ &= ~kNormalFlowChildren;
}
if (remaining_children_ & kPositiveZOrderChildren) {
- PaintLayerStackingNode::PaintLayers* pos_z_order_list =
- root_.PosZOrderList();
- if (pos_z_order_list && index_ < pos_z_order_list->size())
- return pos_z_order_list->at(index_++);
+ if (root_.StackingNode()) {
+ const auto& pos_z_order_list = root_.StackingNode()->PosZOrderList();
+ if (index_ < pos_z_order_list.size())
+ return pos_z_order_list[index_++];
+ }
index_ = 0;
remaining_children_ &= ~kPositiveZOrderChildren;
@@ -86,12 +78,13 @@ PaintLayer* PaintLayerStackingNodeIterator::Next() {
return nullptr;
}
-PaintLayer* PaintLayerStackingNodeReverseIterator::Next() {
+PaintLayer* PaintLayerPaintOrderReverseIterator::Next() {
if (remaining_children_ & kNegativeZOrderChildren) {
- PaintLayerStackingNode::PaintLayers* neg_z_order_list =
- root_.NegZOrderList();
- if (neg_z_order_list && index_ >= 0)
- return neg_z_order_list->at(index_--);
+ if (root_.StackingNode()) {
+ const auto& neg_z_order_list = root_.StackingNode()->NegZOrderList();
+ if (index_ >= 0)
+ return neg_z_order_list[index_--];
+ }
remaining_children_ &= ~kNegativeZOrderChildren;
SetIndexToLastItem();
@@ -101,14 +94,13 @@ PaintLayer* PaintLayerStackingNodeReverseIterator::Next() {
for (; current_normal_flow_child_;
current_normal_flow_child_ =
current_normal_flow_child_->PreviousSibling()) {
- if (!current_normal_flow_child_->GetLayoutObject()
- .StyleRef()
- .IsStacked()) {
- PaintLayer* normal_flow_child = current_normal_flow_child_;
- current_normal_flow_child_ =
- current_normal_flow_child_->PreviousSibling();
- return normal_flow_child;
- }
+ if (current_normal_flow_child_->GetLayoutObject().StyleRef().IsStacked())
+ continue;
+
+ PaintLayer* normal_flow_child = current_normal_flow_child_;
+ current_normal_flow_child_ =
+ current_normal_flow_child_->PreviousSibling();
+ return normal_flow_child;
}
remaining_children_ &= ~kNormalFlowChildren;
@@ -116,10 +108,11 @@ PaintLayer* PaintLayerStackingNodeReverseIterator::Next() {
}
if (remaining_children_ & kPositiveZOrderChildren) {
- PaintLayerStackingNode::PaintLayers* pos_z_order_list =
- root_.PosZOrderList();
- if (pos_z_order_list && index_ >= 0)
- return pos_z_order_list->at(index_--);
+ if (root_.StackingNode()) {
+ const auto& pos_z_order_list = root_.StackingNode()->PosZOrderList();
+ if (index_ >= 0)
+ return pos_z_order_list[index_--];
+ }
remaining_children_ &= ~kPositiveZOrderChildren;
SetIndexToLastItem();
@@ -128,29 +121,31 @@ PaintLayer* PaintLayerStackingNodeReverseIterator::Next() {
return nullptr;
}
-void PaintLayerStackingNodeReverseIterator::SetIndexToLastItem() {
+void PaintLayerPaintOrderReverseIterator::SetIndexToLastItem() {
if (remaining_children_ & kNegativeZOrderChildren) {
- PaintLayerStackingNode::PaintLayers* neg_z_order_list =
- root_.NegZOrderList();
- if (neg_z_order_list) {
- index_ = neg_z_order_list->size() - 1;
- return;
+ if (root_.StackingNode()) {
+ const auto& neg_z_order_list = root_.StackingNode()->NegZOrderList();
+ if (!neg_z_order_list.IsEmpty()) {
+ index_ = neg_z_order_list.size() - 1;
+ return;
+ }
}
remaining_children_ &= ~kNegativeZOrderChildren;
}
if (remaining_children_ & kNormalFlowChildren) {
- current_normal_flow_child_ = root_.Layer()->LastChild();
+ current_normal_flow_child_ = root_.LastChild();
return;
}
if (remaining_children_ & kPositiveZOrderChildren) {
- PaintLayerStackingNode::PaintLayers* pos_z_order_list =
- root_.PosZOrderList();
- if (pos_z_order_list) {
- index_ = pos_z_order_list->size() - 1;
- return;
+ if (root_.StackingNode()) {
+ const auto& pos_z_order_list = root_.StackingNode()->PosZOrderList();
+ if (!pos_z_order_list.IsEmpty()) {
+ index_ = pos_z_order_list.size() - 1;
+ return;
+ }
}
remaining_children_ &= ~kPositiveZOrderChildren;
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_layer_stacking_node_iterator.h b/chromium/third_party/blink/renderer/core/paint/paint_layer_paint_order_iterator.h
index 40136836cad..5bd84d94e03 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_layer_stacking_node_iterator.h
+++ b/chromium/third_party/blink/renderer/core/paint/paint_layer_paint_order_iterator.h
@@ -28,57 +28,69 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_PAINT_LAYER_STACKING_NODE_ITERATOR_H_
-#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_PAINT_LAYER_STACKING_NODE_ITERATOR_H_
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_PAINT_LAYER_PAINT_ORDER_ITERATOR_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_PAINT_LAYER_PAINT_ORDER_ITERATOR_H_
-#include "base/macros.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/core/paint/paint_layer.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
-enum ChildrenIteration {
- kNegativeZOrderChildren = 1,
- // Normal flow children are not mandated by CSS 2.1 but are an artifact of
- // our implementation: we allocate PaintLayers for elements that
- // are not treated as stacking contexts and thus we need to walk them
- // during painting and hit-testing.
- kNormalFlowChildren = 1 << 1,
- kPositiveZOrderChildren = 1 << 2,
- kAllChildren =
- kNegativeZOrderChildren | kNormalFlowChildren | kPositiveZOrderChildren
-};
-
-class PaintLayerStackingNode;
-class PaintLayer;
-
-// This iterator walks the PaintLayerStackingNode lists in the following order:
+// This iterator walks the PaintLayer descendants in the following paint order:
// NegativeZOrderChildren -> NormalFlowChildren -> PositiveZOrderChildren.
-class PaintLayerStackingNodeIterator {
+class CORE_EXPORT PaintLayerPaintOrderIterator {
STACK_ALLOCATED();
public:
- PaintLayerStackingNodeIterator(const PaintLayerStackingNode& root,
- unsigned which_children);
+ PaintLayerPaintOrderIterator(const PaintLayer& root,
+ PaintLayerIteration which_children)
+ : root_(root),
+ remaining_children_(which_children),
+ index_(0),
+ current_normal_flow_child_(root.FirstChild())
+#if DCHECK_IS_ON()
+ ,
+ mutation_detector_(root)
+#endif
+ {
+ }
PaintLayer* Next();
+ const Vector<PaintLayer*>* LayersPaintingOverlayScrollbarsAfter(
+ const PaintLayer* layer) const {
+ return root_.stacking_node_
+ ? root_.stacking_node_->LayersPaintingOverlayScrollbarsAfter(
+ layer)
+ : nullptr;
+ }
+
private:
- const PaintLayerStackingNode& root_;
+ const PaintLayer& root_;
unsigned remaining_children_;
unsigned index_;
PaintLayer* current_normal_flow_child_;
- DISALLOW_COPY_AND_ASSIGN(PaintLayerStackingNodeIterator);
+#if DCHECK_IS_ON()
+ PaintLayerListMutationDetector mutation_detector_;
+#endif
+ DISALLOW_COPY_AND_ASSIGN(PaintLayerPaintOrderIterator);
};
-// This iterator is similar to PaintLayerStackingNodeIterator but it walks the
+// This iterator is similar to PaintLayerPaintOrderIterator but it walks the
// lists in reverse order (from the last item to the first one).
-class PaintLayerStackingNodeReverseIterator {
+class CORE_EXPORT PaintLayerPaintOrderReverseIterator {
STACK_ALLOCATED();
public:
- PaintLayerStackingNodeReverseIterator(const PaintLayerStackingNode& root,
- unsigned which_children)
- : root_(root), remaining_children_(which_children) {
+ PaintLayerPaintOrderReverseIterator(const PaintLayer& root,
+ unsigned which_children)
+ : root_(root),
+ remaining_children_(which_children)
+#if DCHECK_IS_ON()
+ ,
+ mutation_detector_(root)
+#endif
+ {
SetIndexToLastItem();
}
@@ -87,13 +99,16 @@ class PaintLayerStackingNodeReverseIterator {
private:
void SetIndexToLastItem();
- const PaintLayerStackingNode& root_;
+ const PaintLayer& root_;
unsigned remaining_children_;
int index_;
PaintLayer* current_normal_flow_child_;
- DISALLOW_COPY_AND_ASSIGN(PaintLayerStackingNodeReverseIterator);
+#if DCHECK_IS_ON()
+ PaintLayerListMutationDetector mutation_detector_;
+#endif
+ DISALLOW_COPY_AND_ASSIGN(PaintLayerPaintOrderReverseIterator);
};
} // namespace blink
-#endif // THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_PAINT_LAYER_STACKING_NODE_ITERATOR_H_
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_PAINT_LAYER_PAINT_ORDER_ITERATOR_H_
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 0fde0bacf58..3341c787498 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
@@ -13,6 +13,8 @@
#include "third_party/blink/renderer/core/paint/object_paint_properties.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_paint_order_iterator.h"
+#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/core/paint/scrollable_area_painter.h"
#include "third_party/blink/renderer/platform/geometry/float_point_3d.h"
#include "third_party/blink/renderer/platform/graphics/graphics_layer.h"
@@ -310,11 +312,15 @@ PaintResult PaintLayerPainter::PaintLayerContents(
return result;
// If we're blocked from painting by the display lock, return early.
- if (paint_layer_.GetLayoutObject().PaintBlockedByDisplayLock())
+ if (paint_layer_.GetLayoutObject().PaintBlockedByDisplayLock(
+ DisplayLockContext::kSelf)) {
return result;
+ }
+
// 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();
+ paint_layer_.GetLayoutObject().NotifyDisplayLockDidPaint(
+ DisplayLockContext::kSelf);
// A paint layer should always have LocalBorderBoxProperties when it's ready
// for paint.
@@ -486,13 +492,13 @@ PaintResult PaintLayerPainter::PaintLayerContents(
(is_painting_root_layer &&
!(paint_flags & kPaintLayerPaintingSkipRootBackground)));
bool should_paint_neg_z_order_list =
- (is_painting_scrolling_content && is_painting_overflow_contents) ||
- (!is_painting_scrolling_content && is_painting_composited_background);
+ !is_painting_overlay_scrollbars &&
+ (is_painting_scrolling_content ? is_painting_overflow_contents
+ : is_painting_composited_background);
bool should_paint_own_contents =
is_painting_composited_foreground && should_paint_content;
bool should_paint_normal_flow_and_pos_z_order_lists =
- is_painting_composited_foreground;
- bool should_paint_overlay_scrollbars = is_painting_overlay_scrollbars;
+ is_painting_composited_foreground && !is_painting_overlay_scrollbars;
bool is_video = paint_layer_.GetLayoutObject().IsVideo();
base::Optional<ScopedPaintChunkProperties>
@@ -546,14 +552,18 @@ PaintResult PaintLayerPainter::PaintLayerContents(
paint_layer_,
DisplayItem::kLayerChunkNormalFlowAndPositiveZOrderChildren);
}
- if (PaintChildren(kNormalFlowChildren | kPositiveZOrderChildren, context,
+ if (PaintChildren(kNormalFlowAndPositiveZOrderChildren, context,
painting_info, paint_flags) == kMayBeClippedByCullRect)
result = kMayBeClippedByCullRect;
}
- if (should_paint_overlay_scrollbars) {
- PaintOverflowControlsForFragments(layer_fragments, context,
- local_painting_info, paint_flags);
+ if (paint_layer_.GetScrollableArea() &&
+ paint_layer_.GetScrollableArea()->HasOverlayScrollbars()) {
+ if (is_painting_overlay_scrollbars ||
+ !paint_layer_.NeedsReorderOverlayScrollbars()) {
+ PaintOverlayScrollbarsForFragments(layer_fragments, context,
+ local_painting_info, paint_flags);
+ }
}
if (is_video && should_paint_self_outline) {
@@ -665,26 +675,21 @@ static void ForAllFragments(GraphicsContext& context,
}
PaintResult PaintLayerPainter::PaintChildren(
- unsigned children_to_visit,
+ PaintLayerIteration children_to_visit,
GraphicsContext& context,
const PaintLayerPaintingInfo& painting_info,
PaintLayerFlags paint_flags) {
PaintResult result = kFullyPainted;
if (!paint_layer_.HasSelfPaintingLayerDescendant())
return result;
- if (!paint_layer_.StackingNode())
- return result;
-#if DCHECK_IS_ON()
- LayerListMutationDetector mutation_checker(paint_layer_.StackingNode());
-#endif
-
- PaintLayerStackingNodeIterator iterator(*paint_layer_.StackingNode(),
- children_to_visit);
- PaintLayer* child = iterator.Next();
- if (!child)
+ if (paint_layer_.GetLayoutObject().PaintBlockedByDisplayLock(
+ DisplayLockContext::kChildren)) {
return result;
- for (; child; child = iterator.Next()) {
+ }
+
+ PaintLayerPaintOrderIterator iterator(paint_layer_, children_to_visit);
+ while (PaintLayer* child = iterator.Next()) {
// If this Layer should paint into its own backing or a grouped backing,
// that will be done via CompositedLayerMapping::PaintContents() and
// CompositedLayerMapping::DoPaintTask().
@@ -698,44 +703,44 @@ PaintResult PaintLayerPainter::PaintChildren(
if (PaintLayerPainter(*child).Paint(context, painting_info, paint_flags) ==
kMayBeClippedByCullRect)
result = kMayBeClippedByCullRect;
+
+ if (const auto* layers_painting_overlay_scrollbars_after =
+ iterator.LayersPaintingOverlayScrollbarsAfter(child)) {
+ for (auto* reparent_scrollbar_layer :
+ *layers_painting_overlay_scrollbars_after) {
+ DCHECK(reparent_scrollbar_layer->NeedsReorderOverlayScrollbars());
+ if (PaintLayerPainter(*reparent_scrollbar_layer)
+ .Paint(context, painting_info,
+ kPaintLayerPaintingOverlayScrollbars) ==
+ kMayBeClippedByCullRect)
+ result = kMayBeClippedByCullRect;
+ }
+ }
}
return result;
}
-void PaintLayerPainter::PaintOverflowControlsForFragments(
+void PaintLayerPainter::PaintOverlayScrollbarsForFragments(
const PaintLayerFragments& layer_fragments,
GraphicsContext& context,
const PaintLayerPaintingInfo& painting_info,
PaintLayerFlags paint_flags) {
- PaintLayerScrollableArea* scrollable_area = paint_layer_.GetScrollableArea();
- if (!scrollable_area)
+ DCHECK(paint_layer_.GetScrollableArea() &&
+ paint_layer_.GetScrollableArea()->HasOverlayScrollbars());
+
+ // We don't need to paint composited scrollbars.
+ if (paint_layer_.GetScrollableArea()->HasLayerForHorizontalScrollbar() ||
+ paint_layer_.GetScrollableArea()->HasLayerForVerticalScrollbar())
return;
ForAllFragments(
context, layer_fragments, [&](const PaintLayerFragment& fragment) {
- ScopedPaintChunkProperties fragment_paint_chunk_properties(
- context.GetPaintController(),
- fragment.fragment_data->LocalBorderBoxProperties(), paint_layer_,
- DisplayItem::kOverflowControls);
-
- // We need to apply the same clips and transforms that
- // paintFragmentWithPhase would have.
- PhysicalRect cull_rect = fragment.background_rect.Rect();
- PaintInfo paint_info(
- context, PixelSnappedIntRect(cull_rect),
- PaintPhase::kSelfBlockBackgroundOnly,
- painting_info.GetGlobalPaintFlags(), paint_flags,
- &painting_info.root_layer->GetLayoutObject(),
- fragment.fragment_data
- ? fragment.fragment_data->LogicalTopInFlowThread()
- : LayoutUnit());
- // We pass IntPoint() as the paint offset here, because
- // ScrollableArea::paintOverflowControls just ignores it and uses the
- // offset found in a previous pass.
- ScrollableAreaPainter(*scrollable_area)
- .PaintOverflowControls(paint_info, IntPoint(),
- true /* painting_overlay_controls */);
+ if (!fragment.background_rect.IsEmpty()) {
+ PaintFragmentWithPhase(PaintPhase::kOverlayScrollbars, fragment,
+ context, fragment.background_rect,
+ painting_info, paint_flags);
+ }
});
}
@@ -940,14 +945,9 @@ void PaintLayerPainter::PaintOverlayScrollbars(
GraphicsContext& context,
const CullRect& cull_rect,
const GlobalPaintFlags paint_flags) {
- if (!paint_layer_.ContainsDirtyOverlayScrollbars())
- return;
-
PaintLayerPaintingInfo painting_info(&paint_layer_, cull_rect, paint_flags,
PhysicalOffset());
Paint(context, painting_info, kPaintLayerPaintingOverlayScrollbars);
-
- paint_layer_.SetContainsDirtyOverlayScrollbars(false);
}
void PaintLayerPainter::FillMaskingFragment(GraphicsContext& context,
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 263079dad40..03be2fc8118 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
@@ -6,10 +6,11 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_PAINT_LAYER_PAINTER_H_
#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/paint_layer_fragment.h"
#include "third_party/blink/renderer/core/paint/paint_layer_painting_info.h"
#include "third_party/blink/renderer/core/paint/paint_result.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -17,7 +18,6 @@ class CullRect;
class ClipRect;
class ComputedStyle;
class DisplayItemClient;
-class PaintLayer;
class GraphicsContext;
struct PhysicalOffset;
@@ -60,7 +60,7 @@ class CORE_EXPORT PaintLayerPainter {
private:
friend class PaintLayerPainterTest;
- PaintResult PaintChildren(unsigned children_to_visit,
+ PaintResult PaintChildren(PaintLayerIteration children_to_visit,
GraphicsContext&,
const PaintLayerPaintingInfo&,
PaintLayerFlags);
@@ -94,10 +94,10 @@ class CORE_EXPORT PaintLayerPainter {
GraphicsContext&,
const PaintLayerPaintingInfo&,
PaintLayerFlags);
- void PaintOverflowControlsForFragments(const PaintLayerFragments&,
- GraphicsContext&,
- const PaintLayerPaintingInfo&,
- PaintLayerFlags);
+ void PaintOverlayScrollbarsForFragments(const PaintLayerFragments&,
+ GraphicsContext&,
+ const PaintLayerPaintingInfo&,
+ PaintLayerFlags);
void PaintMaskForFragments(const PaintLayerFragments&,
GraphicsContext&,
const PaintLayerPaintingInfo&,
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 028504f3435..58932aeb63b 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
@@ -44,12 +44,6 @@ class PaintLayerPainterTest : public PaintControllerPaintTest {
->GraphicsLayerBacking(&GetLayoutView())
->GetPaintController();
}
-
- private:
- void SetUp() override {
- PaintControllerPaintTest::SetUp();
- EnableCompositing();
- }
};
INSTANTIATE_PAINT_TEST_SUITE_P(PaintLayerPainterTest);
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 661f807b2fc..c3aa21efcfe 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
@@ -49,7 +49,7 @@
#include "third_party/blink/renderer/core/layout/geometry/physical_offset.h"
#include "third_party/blink/renderer/core/paint/paint_phase.h"
#include "third_party/blink/renderer/platform/graphics/paint/cull_rect.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#if DCHECK_IS_ON()
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
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 e3d58f8a356..64509cd015a 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
@@ -112,14 +112,6 @@ static const int kDefaultMinimumHeightForResizing = 15;
} // namespace
-static LayoutRect LocalToAbsolute(const LayoutBox& box, LayoutRect rect) {
- return box.LocalToAbsoluteRect(PhysicalRectToBeNoop(rect)).ToLayoutRect();
-}
-
-static LayoutRect AbsoluteToLocal(const LayoutBox& box, LayoutRect rect) {
- return box.AbsoluteToLocalRect(PhysicalRectToBeNoop(rect)).ToLayoutRect();
-}
-
PaintLayerScrollableAreaRareData::PaintLayerScrollableAreaRareData() = default;
const int kResizerControlExpandRatioForTouch = 2;
@@ -146,11 +138,9 @@ PaintLayerScrollableArea::PaintLayerScrollableArea(PaintLayer& layer)
horizontal_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()) {
+ if (auto* element = DynamicTo<Element>(GetLayoutBox()->GetNode())) {
// We save and restore only the scrollOffset as the other scroll values are
// recalculated.
- Element* element = ToElement(node);
scroll_offset_ = element->SavedLayerScrollOffset();
if (!scroll_offset_.IsZero())
GetScrollAnimator().SetCurrentOffset(scroll_offset_);
@@ -169,7 +159,9 @@ void PaintLayerScrollableArea::DidScroll(const FloatPoint& position) {
CHECK(!HasBeenDisposed());
}
-void PaintLayerScrollableArea::Dispose() {
+void PaintLayerScrollableArea::DisposeImpl() {
+ rare_data_.reset();
+
if (InResizeMode() && !GetLayoutBox()->DocumentBeingDestroyed()) {
if (LocalFrame* frame = GetLayoutBox()->GetFrame())
frame->GetEventHandler().ResizeScrollableAreaDestroyed();
@@ -188,10 +180,9 @@ void PaintLayerScrollableArea::Dispose() {
scrolling_coordinator->WillDestroyScrollableArea(this);
if (!GetLayoutBox()->DocumentBeingDestroyed()) {
- Node* node = GetLayoutBox()->GetNode();
// FIXME: Make setSavedLayerScrollOffset take DoubleSize. crbug.com/414283.
- if (node && node->IsElementNode())
- ToElement(node)->SetSavedLayerScrollOffset(scroll_offset_);
+ if (auto* element = DynamicTo<Element>(GetLayoutBox()->GetNode()))
+ element->SetSavedLayerScrollOffset(scroll_offset_);
}
if (LocalFrame* frame = GetLayoutBox()->GetFrame()) {
@@ -223,11 +214,9 @@ void PaintLayerScrollableArea::Dispose() {
if (SmoothScrollSequencer* sequencer = GetSmoothScrollSequencer())
sequencer->DidDisposeScrollableArea(*this);
- layer_ = nullptr;
-}
+ RunScrollCompleteCallbacks();
-bool PaintLayerScrollableArea::HasBeenDisposed() const {
- return !layer_;
+ layer_ = nullptr;
}
void PaintLayerScrollableArea::Trace(blink::Visitor* visitor) {
@@ -425,6 +414,11 @@ void PaintLayerScrollableArea::UpdateScrollOffset(
if (HasBeenDisposed() || GetScrollOffset() == new_offset)
return;
+ TRACE_EVENT2("blink", "PaintLayerScrollableArea::UpdateScrollOffset", "x",
+ new_offset.Width(), "y", new_offset.Height());
+ TRACE_EVENT_INSTANT1("blink", "Type", TRACE_EVENT_SCOPE_THREAD, "type",
+ scroll_type);
+
scroll_offset_ = new_offset;
LocalFrame* frame = GetLayoutBox()->GetFrame();
@@ -443,9 +437,11 @@ void PaintLayerScrollableArea::UpdateScrollOffset(
// Update the positions of our child layers (if needed as only fixed layers
// should be impacted by a scroll).
if (!frame_view->IsInPerformLayout()) {
- // If we're in the middle of layout, we'll just update layers once layout
- // has finished.
- Layer()->UpdateLayerPositionsAfterOverflowScroll();
+ if (!Layer()->IsRootLayer()) {
+ Layer()->SetNeedsCompositingInputsUpdate();
+ Layer()->ClearClipRects();
+ }
+
// Update regions, scrolling may change the clip of a particular region.
frame_view->UpdateDocumentAnnotatedRegions();
@@ -610,7 +606,7 @@ void PaintLayerScrollableArea::VisibleSizeChanged() {
ShowOverlayScrollbars();
}
-LayoutRect PaintLayerScrollableArea::LayoutContentRect(
+PhysicalRect PaintLayerScrollableArea::LayoutContentRect(
IncludeScrollbarsInRect scrollbar_inclusion) const {
// LayoutContentRect is conceptually the same as the box's client rect.
LayoutSize layer_size(Layer()->Size());
@@ -628,29 +624,29 @@ LayoutRect PaintLayerScrollableArea::LayoutContentRect(
: 0);
}
- return LayoutRect(
- LayoutPoint(ScrollPosition()),
- LayoutSize(
- layer_size.Width() - border_width - vertical_scrollbar_width,
- layer_size.Height() - border_height - horizontal_scrollbar_height)
- .ExpandedTo(LayoutSize()));
+ PhysicalSize size(
+ layer_size.Width() - border_width - vertical_scrollbar_width,
+ layer_size.Height() - border_height - horizontal_scrollbar_height);
+ size.ClampNegativeToZero();
+ return PhysicalRect(PhysicalOffset::FromFloatPointRound(ScrollPosition()),
+ size);
}
IntRect PaintLayerScrollableArea::VisibleContentRect(
IncludeScrollbarsInRect scrollbar_inclusion) const {
- LayoutRect layout_content_rect(LayoutContentRect(scrollbar_inclusion));
+ PhysicalRect layout_content_rect(LayoutContentRect(scrollbar_inclusion));
// TODO(szager): It's not clear that Floor() is the right thing to do here;
// what is the correct behavior for fractional scroll offsets?
- return IntRect(FlooredIntPoint(layout_content_rect.Location()),
- PixelSnappedIntSize(layout_content_rect.Size(),
+ return IntRect(FlooredIntPoint(layout_content_rect.offset),
+ PixelSnappedIntSize(layout_content_rect.size.ToLayoutSize(),
GetLayoutBox()->Location()));
}
-LayoutRect PaintLayerScrollableArea::VisibleScrollSnapportRect(
+PhysicalRect PaintLayerScrollableArea::VisibleScrollSnapportRect(
IncludeScrollbarsInRect scrollbar_inclusion) const {
const ComputedStyle* style = GetLayoutBox()->Style();
- LayoutRect layout_content_rect(LayoutContentRect(scrollbar_inclusion));
- layout_content_rect.MoveBy(LayoutPoint(-ScrollOrigin()));
+ PhysicalRect layout_content_rect(LayoutContentRect(scrollbar_inclusion));
+ layout_content_rect.Move(PhysicalOffset(-ScrollOrigin()));
LayoutRectOutsets padding(MinimumValueForLength(style->ScrollPaddingTop(),
layout_content_rect.Height()),
MinimumValueForLength(style->ScrollPaddingRight(),
@@ -673,7 +669,7 @@ IntSize PaintLayerScrollableArea::ContentsSize() const {
IntSize PaintLayerScrollableArea::PixelSnappedContentsSize(
const PhysicalOffset& paint_offset) const {
- return PixelSnappedIntRect(PhysicalRect(paint_offset, overflow_rect_.Size()))
+ return PixelSnappedIntRect(PhysicalRect(paint_offset, overflow_rect_.size))
.Size();
}
@@ -841,12 +837,12 @@ LayoutUnit PaintLayerScrollableArea::ScrollHeight() const {
void PaintLayerScrollableArea::UpdateScrollOrigin() {
// This should do nothing prior to first layout; the if-clause will catch
// that.
- if (OverflowRect().IsEmpty())
+ if (overflow_rect_.IsEmpty())
return;
- LayoutRect scrollable_overflow(overflow_rect_);
- scrollable_overflow.Move(-GetLayoutBox()->BorderLeft(),
- -GetLayoutBox()->BorderTop());
- IntPoint new_origin(FlooredIntPoint(-scrollable_overflow.Location()) +
+ PhysicalRect scrollable_overflow = overflow_rect_;
+ scrollable_overflow.Move(-PhysicalOffset(GetLayoutBox()->BorderLeft(),
+ GetLayoutBox()->BorderTop()));
+ IntPoint new_origin(FlooredIntPoint(-scrollable_overflow.offset) +
GetLayoutBox()->OriginAdjustmentForScrollbars());
if (new_origin != scroll_origin_)
scroll_origin_changed_ = true;
@@ -854,17 +850,15 @@ void PaintLayerScrollableArea::UpdateScrollOrigin() {
}
void PaintLayerScrollableArea::UpdateScrollDimensions() {
- LayoutRect new_overflow_rect = GetLayoutBox()->LayoutOverflowRect();
- GetLayoutBox()->DeprecatedFlipForWritingMode(new_overflow_rect);
+ PhysicalRect new_overflow_rect = GetLayoutBox()->PhysicalLayoutOverflowRect();
// The layout viewport can be larger than the document's layout overflow when
// top controls are hidden. Expand the overflow here to ensure that our
// contents size >= visible size.
- new_overflow_rect.Unite(
- LayoutRect(new_overflow_rect.Location(),
- LayoutContentRect(kExcludeScrollbars).Size()));
+ new_overflow_rect.Unite(PhysicalRect(
+ new_overflow_rect.offset, LayoutContentRect(kExcludeScrollbars).size));
- if (overflow_rect_.Size() != new_overflow_rect.Size())
+ if (overflow_rect_.size != new_overflow_rect.size)
ContentsResized();
overflow_rect_ = new_overflow_rect;
UpdateScrollOrigin();
@@ -1067,8 +1061,8 @@ void PaintLayerScrollableArea::DidChangeGlobalRootScroller() {
// Being the global root scroller will affect clipping size due to browser
// controls behavior so we need to update compositing based on updated clip
// geometry.
- if (GetLayoutBox()->GetNode()->IsElementNode())
- ToElement(GetLayoutBox()->GetNode())->SetNeedsCompositingUpdate();
+ if (auto* element = DynamicTo<Element>(GetLayoutBox()->GetNode()))
+ element->SetNeedsCompositingUpdate();
GetLayoutBox()->SetNeedsPaintPropertyUpdate();
// On Android, where the VisualViewport supplies scrollbars, we need to
@@ -1161,7 +1155,7 @@ static bool CanHaveOverflowScrollbars(const LayoutBox& box) {
void PaintLayerScrollableArea::UpdateAfterStyleChange(
const ComputedStyle* old_style) {
// Don't do this on first style recalc, before layout has ever happened.
- if (!OverflowRect().Size().IsZero()) {
+ if (!overflow_rect_.size.IsZero()) {
UpdateScrollableAreaSet();
}
@@ -1235,6 +1229,7 @@ void PaintLayerScrollableArea::UpdateAfterStyleChange(
void PaintLayerScrollableArea::UpdateAfterOverflowRecalc() {
UpdateScrollDimensions();
UpdateScrollbarProportions();
+ UpdateScrollbarEnabledState();
bool needs_horizontal_scrollbar;
bool needs_vertical_scrollbar;
@@ -1255,6 +1250,7 @@ void PaintLayerScrollableArea::UpdateAfterOverflowRecalc() {
}
ClampScrollOffsetAfterOverflowChange();
+ UpdateScrollableAreaSet();
}
IntRect PaintLayerScrollableArea::RectForHorizontalScrollbar(
@@ -1519,10 +1515,10 @@ bool PaintLayerScrollableArea::TryRemovingAutoScrollbars(
!GetLayoutBox()->HasAutoHorizontalScrollbar())
return false;
- LayoutSize client_size_with_scrollbars =
- LayoutContentRect(kIncludeScrollbars).Size();
- if (ScrollWidth() <= client_size_with_scrollbars.Width() &&
- ScrollHeight() <= client_size_with_scrollbars.Height()) {
+ PhysicalSize client_size_with_scrollbars =
+ LayoutContentRect(kIncludeScrollbars).size;
+ if (ScrollWidth() <= client_size_with_scrollbars.width &&
+ ScrollHeight() <= client_size_with_scrollbars.height) {
return true;
}
}
@@ -1894,12 +1890,6 @@ void PaintLayerScrollableArea::InvalidateStickyConstraintsFor(
}
}
-bool PaintLayerScrollableArea::HasStickyDescendants() const {
- if (const PaintLayerScrollableAreaRareData* d = RareData())
- return !d->sticky_constraints_map_.IsEmpty();
- return false;
-}
-
bool PaintLayerScrollableArea::HasNonCompositedStickyDescendants() const {
if (const PaintLayerScrollableAreaRareData* d = RareData()) {
for (const PaintLayer* sticky_layer : d->sticky_constraints_map_.Keys()) {
@@ -1954,7 +1944,7 @@ void PaintLayerScrollableArea::Resize(const IntPoint& pos,
return;
DCHECK(GetLayoutBox()->GetNode()->IsElementNode());
- Element* element = ToElement(GetLayoutBox()->GetNode());
+ auto* element = To<Element>(GetLayoutBox()->GetNode());
Document& document = element->GetDocument();
@@ -2036,17 +2026,23 @@ void PaintLayerScrollableArea::Resize(const IntPoint& pos,
// keep the point under the cursor in view.
}
-LayoutRect PaintLayerScrollableArea::ScrollIntoView(
- const LayoutRect& absolute_rect,
+PhysicalRect PaintLayerScrollableArea::ScrollIntoView(
+ const PhysicalRect& absolute_rect,
const WebScrollIntoViewParams& params) {
- LayoutRect local_expose_rect =
- AbsoluteToLocal(*GetLayoutBox(), absolute_rect);
- LayoutSize border_origin_to_scroll_origin =
- LayoutSize(-GetLayoutBox()->BorderLeft(), -GetLayoutBox()->BorderTop()) +
- LayoutSize(GetScrollOffset());
+ PhysicalRect local_expose_rect =
+ GetLayoutBox()->AbsoluteToLocalRect(absolute_rect);
+ PhysicalOffset border_origin_to_scroll_origin(-GetLayoutBox()->BorderLeft(),
+ -GetLayoutBox()->BorderTop());
+ // There might be scroll bar between border_origin and scroll_origin.
+ IntSize scroll_bar_adjustment =
+ GetLayoutBox()->OriginAdjustmentForScrollbars();
+ border_origin_to_scroll_origin.left -= scroll_bar_adjustment.Width();
+ border_origin_to_scroll_origin.top -= scroll_bar_adjustment.Height();
+ border_origin_to_scroll_origin +=
+ PhysicalOffset::FromFloatSizeFloor(GetScrollOffset());
// Represent the rect in the container's scroll-origin coordinate.
local_expose_rect.Move(border_origin_to_scroll_origin);
- LayoutRect scroll_snapport_rect = VisibleScrollSnapportRect();
+ PhysicalRect scroll_snapport_rect = VisibleScrollSnapportRect();
ScrollOffset target_offset = ScrollAlignment::GetScrollOffsetToExpose(
scroll_snapport_rect, local_expose_rect, params.GetScrollAlignmentX(),
@@ -2090,18 +2086,20 @@ LayoutRect PaintLayerScrollableArea::ScrollIntoView(
// The container hasn't performed the scroll yet if it's for scroll sequence.
// To calculate the result from the scroll, we move the |local_expose_rect| to
// the will-be-scrolled location.
- local_expose_rect.Move(-LayoutSize(scroll_offset_difference));
+ local_expose_rect.Move(
+ -PhysicalOffset::FromFloatSizeRound(scroll_offset_difference));
// Represent the rects in the container's border-box coordinate.
local_expose_rect.Move(-border_origin_to_scroll_origin);
scroll_snapport_rect.Move(-border_origin_to_scroll_origin);
- LayoutRect intersect = Intersection(scroll_snapport_rect, local_expose_rect);
+ PhysicalRect intersect =
+ Intersection(scroll_snapport_rect, local_expose_rect);
if (intersect.IsEmpty() && !scroll_snapport_rect.IsEmpty() &&
!local_expose_rect.IsEmpty()) {
- return LocalToAbsolute(*GetLayoutBox(), local_expose_rect);
+ return GetLayoutBox()->LocalToAbsoluteRect(local_expose_rect);
}
- intersect = LocalToAbsolute(*GetLayoutBox(), intersect);
+ intersect = GetLayoutBox()->LocalToAbsoluteRect(intersect);
return intersect;
}
@@ -2152,6 +2150,13 @@ void PaintLayerScrollableArea::UpdateScrollableAreaSet() {
// PaintPropertyTreeBuilder::updateScrollAndScrollTranslation).
GetLayoutBox()->SetNeedsPaintPropertyUpdate();
+ if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) {
+ // Scroll hit test display items depend on whether the box scrolls overflow.
+ // The scroll hit test display items paint in the background phase
+ // (see: BoxPainter::PaintBoxDecorationBackground).
+ GetLayoutBox()->SetBackgroundNeedsFullPaintInvalidation();
+ }
+
if (scrolls_overflow_) {
DCHECK(CanHaveOverflowScrollbars(*GetLayoutBox()));
frame_view->AddScrollableArea(this);
@@ -2429,7 +2434,7 @@ Scrollbar* PaintLayerScrollableArea::ScrollbarManager::CreateScrollbar(
if (has_custom_scrollbar_style) {
DCHECK(style_source.GetNode() && style_source.GetNode()->IsElementNode());
scrollbar = LayoutScrollbar::CreateCustomScrollbar(
- ScrollableArea(), orientation, ToElement(style_source.GetNode()));
+ ScrollableArea(), orientation, To<Element>(style_source.GetNode()));
} else {
ScrollbarControlSize scrollbar_size = kRegularScrollbar;
if (style_source.StyleRef().HasAppearance()) {
@@ -2626,9 +2631,25 @@ ScrollbarTheme& PaintLayerScrollableArea::GetPageScrollbarTheme() const {
return page->GetScrollbarTheme();
}
+void PaintLayerScrollableArea::DidAddScrollbar(
+ Scrollbar& scrollbar,
+ ScrollbarOrientation orientation) {
+ // Z-order of reparented scrollbar is updated along with the z-order lists.
+ if (scrollbar.IsOverlayScrollbar())
+ layer_->DirtyStackingContextZOrderLists();
+
+ ScrollableArea::DidAddScrollbar(scrollbar, orientation);
+}
+
void PaintLayerScrollableArea::WillRemoveScrollbar(
Scrollbar& scrollbar,
ScrollbarOrientation orientation) {
+ if (layer_->NeedsReorderOverlayScrollbars()) {
+ // Z-order of reparented scrollbar is updated along with the z-order lists.
+ DCHECK(scrollbar.IsOverlayScrollbar());
+ layer_->DirtyStackingContextZOrderLists();
+ }
+
if (!scrollbar.IsCustomScrollbar() &&
!(orientation == kHorizontalScrollbar ? LayerForHorizontalScrollbar()
: LayerForVerticalScrollbar())) {
@@ -2844,10 +2865,17 @@ void PaintLayerScrollableArea::DidScrollWithScrollbar(
: WebFeature::kScrollbarUseHorizontalScrollbarButton);
break;
case kThumbPart:
- scrollbar_use_uma =
- (orientation == kVerticalScrollbar
- ? WebFeature::kScrollbarUseVerticalScrollbarThumb
- : WebFeature::kScrollbarUseHorizontalScrollbarThumb);
+ if (orientation == kVerticalScrollbar) {
+ scrollbar_use_uma =
+ (WebInputEvent::IsMouseEventType(type)
+ ? WebFeature::kVerticalScrollbarThumbScrollingWithMouse
+ : WebFeature::kVerticalScrollbarThumbScrollingWithTouch);
+ } else {
+ scrollbar_use_uma =
+ (WebInputEvent::IsMouseEventType(type)
+ ? WebFeature::kHorizontalScrollbarThumbScrollingWithMouse
+ : WebFeature::kHorizontalScrollbarThumbScrollingWithTouch);
+ }
break;
case kBackTrackPart:
case kForwardTrackPart:
@@ -2862,24 +2890,7 @@ void PaintLayerScrollableArea::DidScrollWithScrollbar(
Document& document = GetLayoutBox()->GetDocument();
- // TODO(alpastew): Remove the UseCounters kScrollbarUseVerticalScrollbarThumb
- // and kScrollbarUseHorizontalScrollbarThumb to avoid redundancy in metrics.
UseCounter::Count(document, scrollbar_use_uma);
-
- if (scrollbar_use_uma == WebFeature::kScrollbarUseVerticalScrollbarThumb) {
- WebFeature input_specific_uma =
- (WebInputEvent::IsMouseEventType(type)
- ? WebFeature::kVerticalScrollbarThumbScrollingWithMouse
- : WebFeature::kVerticalScrollbarThumbScrollingWithTouch);
- UseCounter::Count(document, input_specific_uma);
- } else if (scrollbar_use_uma ==
- WebFeature::kScrollbarUseHorizontalScrollbarThumb) {
- WebFeature input_specific_uma =
- (WebInputEvent::IsMouseEventType(type)
- ? WebFeature::kHorizontalScrollbarThumbScrollingWithMouse
- : WebFeature::kHorizontalScrollbarThumbScrollingWithTouch);
- UseCounter::Count(document, input_specific_uma);
- }
}
CompositorElementId PaintLayerScrollableArea::GetCompositorElementId() const {
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 ddd09a9c196..cf3c0bf2dfd 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
@@ -249,8 +249,6 @@ class CORE_EXPORT PaintLayerScrollableArea final
explicit PaintLayerScrollableArea(PaintLayer&);
~PaintLayerScrollableArea() override;
- void Dispose();
- bool HasBeenDisposed() const override;
void ForceVerticalScrollbarForFirstLayout() { SetHasVerticalScrollbar(true); }
bool HasHorizontalScrollbar() const { return HorizontalScrollbar(); }
@@ -315,7 +313,7 @@ class CORE_EXPORT PaintLayerScrollableArea final
IntSize MaximumScrollOffsetInt() const override;
IntRect VisibleContentRect(
IncludeScrollbarsInRect = kExcludeScrollbars) const override;
- LayoutRect VisibleScrollSnapportRect(
+ PhysicalRect VisibleScrollSnapportRect(
IncludeScrollbarsInRect = kExcludeScrollbars) const override;
IntSize ContentsSize() const override;
@@ -347,9 +345,6 @@ class CORE_EXPORT PaintLayerScrollableArea final
IntPoint ScrollOrigin() const { return scroll_origin_; }
bool ScrollOriginChanged() const { return scroll_origin_changed_; }
- // FIXME: We shouldn't allow access to m_overflowRect outside this class.
- LayoutRect OverflowRect() const { return overflow_rect_; }
-
void ScrollToAbsolutePosition(
const FloatPoint& position,
ScrollBehavior scroll_behavior = kScrollBehaviorInstant,
@@ -425,8 +420,8 @@ class CORE_EXPORT PaintLayerScrollableArea final
// Returns the new offset, after scrolling, of the given rect in absolute
// coordinates, clipped by the parent's client rect.
- LayoutRect ScrollIntoView(const LayoutRect&,
- const WebScrollIntoViewParams&) override;
+ PhysicalRect ScrollIntoView(const PhysicalRect&,
+ const WebScrollIntoViewParams&) override;
// Returns true if scrollable area is in the FrameView's collection of
// scrollable areas. This can only happen if we're scrollable, visible to hit
@@ -447,13 +442,6 @@ class CORE_EXPORT PaintLayerScrollableArea final
LayoutScrollbarPart* Resizer() const { return resizer_; }
- const IntPoint& CachedOverlayScrollbarOffset() {
- return cached_overlay_scrollbar_offset_;
- }
- void SetCachedOverlayScrollbarOffset(const IntPoint& offset) {
- cached_overlay_scrollbar_offset_ = offset;
- }
-
IntRect RectForHorizontalScrollbar(const IntRect& border_box_rect) const;
IntRect RectForVerticalScrollbar(const IntRect& border_box_rect) const;
@@ -515,7 +503,6 @@ class CORE_EXPORT PaintLayerScrollableArea final
void InvalidateStickyConstraintsFor(PaintLayer*,
bool needs_compositing_update = true);
void InvalidatePaintForStickyDescendants();
- bool HasStickyDescendants() const;
bool HasNonCompositedStickyDescendants() const;
uint32_t GetNonCompositedMainThreadScrollingReasons() {
return non_composited_main_thread_scrolling_reasons_;
@@ -531,6 +518,7 @@ class CORE_EXPORT PaintLayerScrollableArea final
// scrollbar.
int HypotheticalScrollbarThickness(ScrollbarOrientation) const;
+ void DidAddScrollbar(Scrollbar&, ScrollbarOrientation) override;
void WillRemoveScrollbar(Scrollbar&, ScrollbarOrientation) override;
void InvalidatePaintOfScrollControlsIfNeeded(const PaintInvalidatorContext&);
@@ -554,6 +542,8 @@ class CORE_EXPORT PaintLayerScrollableArea final
return scrolling_background_display_item_client_;
}
+ void DisposeImpl() override;
+
private:
bool NeedsScrollbarReconstruction() const;
@@ -592,7 +582,7 @@ class CORE_EXPORT PaintLayerScrollableArea final
void UpdateScrollCornerStyle();
LayoutSize MinimumSizeForResizing(float zoom_factor);
- LayoutRect LayoutContentRect(IncludeScrollbarsInRect) const;
+ PhysicalRect LayoutContentRect(IncludeScrollbarsInRect) const;
// See comments on isPointInResizeControl.
void UpdateResizerAreaSet();
@@ -673,7 +663,7 @@ class CORE_EXPORT PaintLayerScrollableArea final
// This is OverflowModel's layout overflow translated to physical
// coordinates. See OverflowModel for the different overflow and
// LayoutBoxModelObject for the coordinate systems.
- LayoutRect overflow_rect_;
+ PhysicalRect overflow_rect_;
// ScrollbarManager holds the Scrollbar instances.
ScrollbarManager scrollbar_manager_;
@@ -681,8 +671,6 @@ class CORE_EXPORT PaintLayerScrollableArea final
// This is the offset from the beginning of content flow.
ScrollOffset scroll_offset_;
- IntPoint cached_overlay_scrollbar_offset_;
-
// LayoutObject to hold our custom scroll corner.
LayoutScrollbarPart* scroll_corner_;
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 898e247548a..ad7149706fb 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
@@ -53,8 +53,8 @@ class PaintLayerScrollableAreaTestBase : public RenderingTest {
private:
void SetUp() override {
- RenderingTest::SetUp();
EnableCompositing();
+ RenderingTest::SetUp();
}
Persistent<ScrollableAreaMockChromeClient> chrome_client_;
@@ -983,22 +983,22 @@ TEST_P(PaintLayerScrollableAreaTest, HitTestOverlayScrollbars) {
scrollable_area->SetScrollbarsHiddenIfOverlay(true);
HitTestRequest hit_request(HitTestRequest::kMove | HitTestRequest::kReadOnly);
- HitTestLocation location(LayoutPoint(95, 5));
+ HitTestLocation location(PhysicalOffset(95, 5));
HitTestResult hit_result(hit_request, location);
GetDocument().GetLayoutView()->HitTest(location, hit_result);
EXPECT_EQ(hit_result.GetScrollbar(), nullptr);
- location = HitTestLocation(LayoutPoint(5, 95));
+ location = HitTestLocation(PhysicalOffset(5, 95));
hit_result = HitTestResult(hit_request, location);
GetDocument().GetLayoutView()->HitTest(location, hit_result);
EXPECT_EQ(hit_result.GetScrollbar(), nullptr);
scrollable_area->SetScrollbarsHiddenIfOverlay(false);
- location = HitTestLocation(LayoutPoint(95, 5));
+ location = HitTestLocation(PhysicalOffset(95, 5));
hit_result = HitTestResult(hit_request, location);
GetDocument().GetLayoutView()->HitTest(location, hit_result);
EXPECT_EQ(hit_result.GetScrollbar(), scrollable_area->VerticalScrollbar());
- location = HitTestLocation(LayoutPoint(5, 95));
+ location = HitTestLocation(PhysicalOffset(5, 95));
hit_result = HitTestResult(hit_request, location);
GetDocument().GetLayoutView()->HitTest(location, hit_result);
EXPECT_EQ(hit_result.GetScrollbar(), scrollable_area->HorizontalScrollbar());
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 fd5c1149ce0..0a9abfba915 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
@@ -53,128 +53,124 @@
#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"
namespace blink {
// FIXME: This should not require PaintLayer. There is currently a cycle where
// in order to determine if we isStacked() we have to ask the paint
// layer about some of its state.
-PaintLayerStackingNode::PaintLayerStackingNode(PaintLayer* layer)
- : layer_(layer)
-#if DCHECK_IS_ON()
- ,
- layer_list_mutation_allowed_(true)
-#endif
-{
- // Non-stacking contexts should have empty z-order lists. As this is already
- // the case, there is no need to dirty / recompute these lists.
- z_order_lists_dirty_ =
- layer->GetLayoutObject().StyleRef().IsStackingContext();
+PaintLayerStackingNode::PaintLayerStackingNode(PaintLayer& layer)
+ : layer_(layer), z_order_lists_dirty_(true) {
+ DCHECK(layer.GetLayoutObject().StyleRef().IsStackingContext());
}
PaintLayerStackingNode::~PaintLayerStackingNode() {
#if DCHECK_IS_ON()
- if (!Layer()->GetLayoutObject().DocumentBeingDestroyed())
+ if (!layer_.GetLayoutObject().DocumentBeingDestroyed())
UpdateStackingParentForZOrderLists(nullptr);
#endif
}
-PaintLayerStackingNode::PaintLayers* PaintLayerStackingNode::PosZOrderList()
- const {
- DCHECK(!z_order_lists_dirty_);
- DCHECK(Layer()->GetLayoutObject().StyleRef().IsStackingContext() ||
- !pos_z_order_list_);
- return pos_z_order_list_.get();
-}
-
-PaintLayerStackingNode::PaintLayers* PaintLayerStackingNode::NegZOrderList()
- const {
- DCHECK(!z_order_lists_dirty_);
- DCHECK(Layer()->GetLayoutObject().StyleRef().IsStackingContext() ||
- !neg_z_order_list_);
- return neg_z_order_list_.get();
-}
-
-bool PaintLayerStackingNode::IsDirtyStackingContext() const {
- return z_order_lists_dirty_ &&
- Layer()->GetLayoutObject().StyleRef().IsStackingContext();
-}
-
PaintLayerCompositor* PaintLayerStackingNode::Compositor() const {
- DCHECK(Layer()->GetLayoutObject().View());
- if (!Layer()->GetLayoutObject().View())
+ DCHECK(layer_.GetLayoutObject().View());
+ if (!layer_.GetLayoutObject().View())
return nullptr;
- return Layer()->GetLayoutObject().View()->Compositor();
+ return layer_.GetLayoutObject().View()->Compositor();
}
void PaintLayerStackingNode::DirtyZOrderLists() {
#if DCHECK_IS_ON()
- DCHECK(layer_list_mutation_allowed_);
-#endif
- DCHECK(Layer()->GetLayoutObject().StyleRef().IsStackingContext());
-
-#if DCHECK_IS_ON()
+ DCHECK(layer_.LayerListMutationAllowed());
UpdateStackingParentForZOrderLists(nullptr);
#endif
- if (pos_z_order_list_)
- pos_z_order_list_->clear();
- if (neg_z_order_list_)
- neg_z_order_list_->clear();
+ pos_z_order_list_.clear();
+ neg_z_order_list_.clear();
+
+ for (auto& entry : layer_to_overlay_scrollbars_painting_after_.Values()) {
+ for (PaintLayer* layer : entry)
+ layer->SetNeedsReorderOverlayScrollbars(false);
+ }
+ layer_to_overlay_scrollbars_painting_after_.clear();
+
z_order_lists_dirty_ = true;
- if (!Layer()->GetLayoutObject().DocumentBeingDestroyed() && Compositor())
+ if (!layer_.GetLayoutObject().DocumentBeingDestroyed() && Compositor())
Compositor()->SetNeedsCompositingUpdate(kCompositingUpdateRebuildTree);
}
-void PaintLayerStackingNode::DirtyStackingContextZOrderLists(
- PaintLayer* layer) {
- if (PaintLayerStackingNode* stacking_node =
- 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);
- }
+static bool ZIndexLessThan(const PaintLayer* first, const PaintLayer* second) {
+ DCHECK(first->GetLayoutObject().StyleRef().IsStacked());
+ DCHECK(second->GetLayoutObject().StyleRef().IsStacked());
+ return first->GetLayoutObject().StyleRef().ZIndex() <
+ second->GetLayoutObject().StyleRef().ZIndex();
+}
- stacking_node->DirtyZOrderLists();
- }
+static void SetIfHigher(const PaintLayer*& first, const PaintLayer* second) {
+ if (!second)
+ return;
+ DCHECK_GE(second->GetLayoutObject().StyleRef().ZIndex(), 0);
+ // |second| appears later in the tree, so it's higher than |first| if its
+ // z-index >= |first|'s z-index.
+ if (!first || !ZIndexLessThan(second, first))
+ first = second;
}
+// For finding the proper z-order of reparented overlay scrollbars.
+struct PaintLayerStackingNode::HighestLayers {
+ const PaintLayer* highest_absolute_position = nullptr;
+ const PaintLayer* highest_fixed_position = nullptr;
+ const PaintLayer* highest_in_flow_stacked = nullptr;
+
+ void Update(const PaintLayer& layer) {
+ const auto& style = layer.GetLayoutObject().StyleRef();
+ // We only need to consider zero or positive z-index stacked child for
+ // candidates of causing reparent of overlay scrollbars of ancestors.
+ // A negative z-index child will not cause reparent of overlay scrollbars
+ // because the ancestor scroller either has auto z-index which is above
+ // the child or has negative z-index which is a stacking context.
+ if (!style.IsStacked() || style.ZIndex() < 0)
+ return;
+
+ if (style.GetPosition() == EPosition::kAbsolute)
+ SetIfHigher(highest_absolute_position, &layer);
+ else if (style.GetPosition() == EPosition::kFixed)
+ SetIfHigher(highest_fixed_position, &layer);
+ else
+ SetIfHigher(highest_in_flow_stacked, &layer);
+ }
+
+ void Merge(HighestLayers& child) {
+ SetIfHigher(highest_absolute_position, child.highest_absolute_position);
+ SetIfHigher(highest_fixed_position, child.highest_fixed_position);
+ SetIfHigher(highest_in_flow_stacked, child.highest_in_flow_stacked);
+ }
+};
+
void PaintLayerStackingNode::RebuildZOrderLists() {
#if DCHECK_IS_ON()
- DCHECK(layer_list_mutation_allowed_);
+ DCHECK(layer_.LayerListMutationAllowed());
#endif
- DCHECK(IsDirtyStackingContext());
+ DCHECK(z_order_lists_dirty_);
- for (PaintLayer* child = Layer()->FirstChild(); child;
+ layer_.SetNeedsReorderOverlayScrollbars(false);
+ for (PaintLayer* child = layer_.FirstChild(); child;
child = child->NextSibling())
- CollectLayers(child, pos_z_order_list_, neg_z_order_list_);
-
- auto CompareZIndex = [](PaintLayer* first, PaintLayer* second) {
- return first->GetLayoutObject().StyleRef().ZIndex() <
- second->GetLayoutObject().StyleRef().ZIndex();
- };
+ CollectLayers(*child, nullptr);
// Sort the two lists.
- if (pos_z_order_list_)
- std::stable_sort(pos_z_order_list_->begin(), pos_z_order_list_->end(),
- CompareZIndex);
-
- if (neg_z_order_list_)
- std::stable_sort(neg_z_order_list_->begin(), neg_z_order_list_->end(),
- CompareZIndex);
+ std::stable_sort(pos_z_order_list_.begin(), pos_z_order_list_.end(),
+ ZIndexLessThan);
+ std::stable_sort(neg_z_order_list_.begin(), neg_z_order_list_.end(),
+ ZIndexLessThan);
// Append layers for top layer elements after normal layer collection, to
// ensure they are on top regardless of z-indexes. The layoutObjects of top
// layer elements are children of the view, sorted in top layer stacking
// order.
- if (Layer()->IsRootLayer()) {
- LayoutBlockFlow* root_block = Layer()->GetLayoutObject().View();
+ if (layer_.IsRootLayer()) {
+ LayoutBlockFlow* root_block = layer_.GetLayoutObject().View();
// If the viewport is paginated, everything (including "top-layer" elements)
// gets redirected to the flow thread. So that's where we have to look, in
// that case.
@@ -183,19 +179,10 @@ void PaintLayerStackingNode::RebuildZOrderLists() {
root_block = multi_column_flow_thread;
for (LayoutObject* child = root_block->FirstChild(); child;
child = child->NextSibling()) {
- Element* child_element =
- (child->GetNode() && child->GetNode()->IsElementNode())
- ? ToElement(child->GetNode())
- : nullptr;
- if (child_element && child_element->IsInTopLayer()) {
- PaintLayer* layer = ToLayoutBoxModelObject(child)->Layer();
- if (layer->StackingNode()) {
- // Create the buffer if it doesn't exist yet.
- if (!pos_z_order_list_) {
- pos_z_order_list_ = std::make_unique<PaintLayers>();
- }
- pos_z_order_list_->push_back(layer);
- }
+ auto* child_element = DynamicTo<Element>(child->GetNode());
+ if (child_element && child_element->IsInTopLayer() &&
+ child->StyleRef().IsStacked()) {
+ pos_z_order_list_.push_back(ToLayoutBoxModelObject(child)->Layer());
}
}
}
@@ -207,48 +194,76 @@ void PaintLayerStackingNode::RebuildZOrderLists() {
z_order_lists_dirty_ = false;
}
-void PaintLayerStackingNode::CollectLayers(
- PaintLayer* paint_layer,
- std::unique_ptr<PaintLayers>& pos_buffer,
- std::unique_ptr<PaintLayers>& neg_buffer) {
- if (paint_layer->IsInTopLayer())
+void PaintLayerStackingNode::CollectLayers(PaintLayer& paint_layer,
+ HighestLayers* highest_layers) {
+ paint_layer.SetNeedsReorderOverlayScrollbars(false);
+
+ if (paint_layer.IsInTopLayer())
return;
- const ComputedStyle& style = paint_layer->GetLayoutObject().StyleRef();
+ if (highest_layers)
+ highest_layers->Update(paint_layer);
+
+ const auto& object = paint_layer.GetLayoutObject();
+ const auto& style = object.StyleRef();
if (style.IsStacked()) {
- std::unique_ptr<PaintLayers>& buffer =
- (style.ZIndex() >= 0) ? pos_buffer : neg_buffer;
- if (!buffer)
- buffer = std::make_unique<PaintLayers>();
- buffer->push_back(paint_layer);
+ auto& list = style.ZIndex() >= 0 ? pos_z_order_list_ : neg_z_order_list_;
+ list.push_back(&paint_layer);
}
- if (!style.IsStackingContext()) {
- for (PaintLayer* child = paint_layer->FirstChild(); child;
- child = child->NextSibling()) {
- CollectLayers(child, pos_buffer, neg_buffer);
+ if (style.IsStackingContext())
+ return;
+
+ base::Optional<HighestLayers> subtree_highest_layers;
+ bool has_overlay_scrollbars =
+ paint_layer.GetScrollableArea() &&
+ paint_layer.GetScrollableArea()->HasOverlayScrollbars();
+ if (has_overlay_scrollbars)
+ subtree_highest_layers.emplace();
+
+ for (PaintLayer* child = paint_layer.FirstChild(); child;
+ child = child->NextSibling()) {
+ CollectLayers(*child, subtree_highest_layers ? &*subtree_highest_layers
+ : highest_layers);
+ }
+
+ if (has_overlay_scrollbars) {
+ const PaintLayer* layer_to_paint_overlay_scrollbars_after =
+ subtree_highest_layers->highest_in_flow_stacked;
+ if (object.CanContainFixedPositionObjects()) {
+ SetIfHigher(layer_to_paint_overlay_scrollbars_after,
+ subtree_highest_layers->highest_fixed_position);
}
+ if (object.CanContainAbsolutePositionObjects()) {
+ SetIfHigher(layer_to_paint_overlay_scrollbars_after,
+ subtree_highest_layers->highest_absolute_position);
+ }
+ if (layer_to_paint_overlay_scrollbars_after) {
+ layer_to_overlay_scrollbars_painting_after_
+ .insert(layer_to_paint_overlay_scrollbars_after, PaintLayers())
+ .stored_value->value.push_back(&paint_layer);
+ }
+ paint_layer.SetNeedsReorderOverlayScrollbars(
+ !!layer_to_paint_overlay_scrollbars_after);
+
+ if (highest_layers)
+ highest_layers->Merge(*subtree_highest_layers);
}
}
#if DCHECK_IS_ON()
void PaintLayerStackingNode::UpdateStackingParentForZOrderLists(
PaintLayerStackingNode* stacking_parent) {
- if (pos_z_order_list_) {
- for (wtf_size_t i = 0; i < pos_z_order_list_->size(); ++i)
- pos_z_order_list_->at(i)->SetStackingParent(stacking_parent);
- }
-
- if (neg_z_order_list_) {
- for (wtf_size_t i = 0; i < neg_z_order_list_->size(); ++i)
- neg_z_order_list_->at(i)->SetStackingParent(stacking_parent);
- }
+ for (auto* layer : pos_z_order_list_)
+ layer->SetStackingParent(stacking_parent);
+ for (auto* layer : neg_z_order_list_)
+ layer->SetStackingParent(stacking_parent);
}
#endif
-bool PaintLayerStackingNode::StyleDidChange(PaintLayer* paint_layer,
+bool PaintLayerStackingNode::StyleDidChange(PaintLayer& paint_layer,
const ComputedStyle* old_style) {
bool was_stacking_context = false;
bool was_stacked = false;
@@ -259,7 +274,7 @@ bool PaintLayerStackingNode::StyleDidChange(PaintLayer* paint_layer,
was_stacked = old_style->IsStacked();
}
- const ComputedStyle& new_style = paint_layer->GetLayoutObject().StyleRef();
+ const ComputedStyle& new_style = paint_layer.GetLayoutObject().StyleRef();
bool should_be_stacking_context = new_style.IsStackingContext();
bool should_be_stacked = new_style.IsStacked();
@@ -268,58 +283,25 @@ bool PaintLayerStackingNode::StyleDidChange(PaintLayer* paint_layer,
return false;
// Need to force requirements update, due to change of stacking order.
- paint_layer->SetNeedsCompositingRequirementsUpdate();
- DirtyStackingContextZOrderLists(paint_layer);
+ paint_layer.SetNeedsCompositingRequirementsUpdate();
+ paint_layer.DirtyStackingContextZOrderLists();
- if (paint_layer->StackingNode()) {
- if (should_be_stacking_context)
- paint_layer->StackingNode()->DirtyZOrderLists();
- else
- paint_layer->StackingNode()->ClearZOrderLists();
- }
+ if (paint_layer.StackingNode())
+ paint_layer.StackingNode()->DirtyZOrderLists();
if (was_stacked != should_be_stacked) {
- if (!paint_layer->GetLayoutObject().DocumentBeingDestroyed() &&
- !paint_layer->IsRootLayer() && paint_layer->Compositor()) {
- paint_layer->Compositor()->SetNeedsCompositingUpdate(
+ if (!paint_layer.GetLayoutObject().DocumentBeingDestroyed() &&
+ !paint_layer.IsRootLayer() && paint_layer.Compositor()) {
+ paint_layer.Compositor()->SetNeedsCompositingUpdate(
kCompositingUpdateRebuildTree);
}
}
return true;
}
-PaintLayerStackingNode* PaintLayerStackingNode::AncestorStackingContextNode(
- const PaintLayer* layer) {
- for (PaintLayer* ancestor = layer->Parent(); ancestor;
- ancestor = ancestor->Parent()) {
- if (ancestor->GetLayoutObject().StyleRef().IsStackingContext())
- return ancestor->StackingNode();
- }
- return nullptr;
-}
-
-void PaintLayerStackingNode::ClearZOrderLists() {
- DCHECK(!Layer()->GetLayoutObject().StyleRef().IsStackingContext());
-
-#if DCHECK_IS_ON()
- UpdateStackingParentForZOrderLists(nullptr);
-#endif
-
- pos_z_order_list_.reset();
- neg_z_order_list_.reset();
-}
-
void PaintLayerStackingNode::UpdateZOrderLists() {
- if (!z_order_lists_dirty_)
- return;
-
- if (!Layer()->GetLayoutObject().StyleRef().IsStackingContext()) {
- ClearZOrderLists();
- z_order_lists_dirty_ = false;
- return;
- }
-
- RebuildZOrderLists();
+ if (z_order_lists_dirty_)
+ RebuildZOrderLists();
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_layer_stacking_node.h b/chromium/third_party/blink/renderer/core/paint/paint_layer_stacking_node.h
index 76ad5db6e5f..7f0f3c24c65 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_layer_stacking_node.h
+++ b/chromium/third_party/blink/renderer/core/paint/paint_layer_stacking_node.h
@@ -49,7 +49,8 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/layout/layout_box_model_object.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/hash_map.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
@@ -58,6 +59,9 @@ class PaintLayer;
class PaintLayerCompositor;
class ComputedStyle;
+// This class is only for PaintLayer, PaintLayerPaintOrderIterator and
+// PaintLayerPaintOrderReverseIterator. Other classes should not use this class.
+//
// PaintLayerStackingNode represents a stacked element which is either a
// stacking context or a positioned element.
// See
@@ -74,131 +78,122 @@ class ComputedStyle;
//
// Stacked elements form a subtree over the layout tree. Ideally we would want
// objects of this class to be a node in this tree but there are potential
-// issues with stale pointers so we rely on PaintLayer's tree
-// structure.
+// issues with stale pointers so we rely on PaintLayer's tree structure.
//
// This class's purpose is to represent a node in the stacked element tree
// (aka paint tree). It currently caches the z-order lists for painting and
// hit-testing.
//
-// To implement any z-order list iterations, use
-// PaintLayerStackingNodeIterator and
-// PaintLayerStackingNodeReverseIterator.
+// To implement any paint order iterations, use PaintLayerPaintOrderIterator and
+// PaintLayerZOrderReverseIterator.
//
-// Only a real stacking context can have non-empty z-order lists thus contain
-// child nodes in the tree. The z-order lists of a positioned element with auto
-// z-index are always empty (i.e. it's a leaf of the stacked element tree).
-// A real stacking context can also be a leaf if it doesn't contain any stacked
-// elements.
+// We create PaintLayerStackingNode only for real stacking contexts with stacked
+// children. PaintLayerPaintOrder[Reverse]Iterator can iterate normal flow
+// children in paint order with or without a stacking node.
class CORE_EXPORT PaintLayerStackingNode {
USING_FAST_MALLOC(PaintLayerStackingNode);
public:
- explicit PaintLayerStackingNode(PaintLayer*);
+ explicit PaintLayerStackingNode(PaintLayer&);
~PaintLayerStackingNode();
- bool ZOrderListsDirty() const { return z_order_lists_dirty_; }
void DirtyZOrderLists();
void UpdateZOrderLists();
- void ClearZOrderLists();
- static void DirtyStackingContextZOrderLists(PaintLayer*);
-
- bool HasPositiveZOrderList() const {
- return PosZOrderList() && PosZOrderList()->size();
- }
- bool HasNegativeZOrderList() const {
- return NegZOrderList() && NegZOrderList()->size();
- }
// Returns whether a relevant style changed.
- static bool StyleDidChange(PaintLayer* paint_layer,
+ static bool StyleDidChange(PaintLayer& paint_layer,
const ComputedStyle* old_style);
- PaintLayer* Layer() const { return layer_; }
-
-#if DCHECK_IS_ON()
- bool LayerListMutationAllowed() const { return layer_list_mutation_allowed_; }
- void SetLayerListMutationAllowed(bool flag) {
- layer_list_mutation_allowed_ = flag;
- }
-#endif
-
- static PaintLayerStackingNode* AncestorStackingContextNode(const PaintLayer*);
using PaintLayers = Vector<PaintLayer*>;
- private:
- friend class PaintLayerStackingNodeIterator;
- friend class PaintLayerStackingNodeReverseIterator;
- friend class LayoutTreeAsText;
-
-#if DCHECK_IS_ON()
- friend class PaintLayer;
-#endif
+ const PaintLayers& PosZOrderList() const {
+ DCHECK(!z_order_lists_dirty_);
+ return pos_z_order_list_;
+ }
+ const PaintLayers& NegZOrderList() const {
+ DCHECK(!z_order_lists_dirty_);
+ return neg_z_order_list_;
+ }
- PaintLayers* PosZOrderList() const;
+ const PaintLayers* LayersPaintingOverlayScrollbarsAfter(
+ const PaintLayer* layer) const {
+ DCHECK(!z_order_lists_dirty_);
+ auto it = layer_to_overlay_scrollbars_painting_after_.find(layer);
+ return it == layer_to_overlay_scrollbars_painting_after_.end() ? nullptr
+ : &it->value;
+ }
- PaintLayers* NegZOrderList() const;
+ void ClearNeedsReorderOverlayScrollbars();
+ private:
void RebuildZOrderLists();
- static void CollectLayers(PaintLayer*,
- std::unique_ptr<PaintLayers>& pos_z_order_list,
- std::unique_ptr<PaintLayers>& neg_z_order_list);
+ struct HighestLayers;
+ void CollectLayers(PaintLayer&, HighestLayers*);
#if DCHECK_IS_ON()
void UpdateStackingParentForZOrderLists(
PaintLayerStackingNode* stacking_parent);
#endif
- bool IsDirtyStackingContext() const;
-
PaintLayerCompositor* Compositor() const;
- PaintLayer* layer_;
-
- // m_posZOrderList holds a sorted list of all the descendant nodes within
- // that have z-indices of 0 (or is treated as 0 for positioned objects) or
- // greater.
- std::unique_ptr<PaintLayers> pos_z_order_list_;
- // m_negZOrderList holds descendants within our stacking context with
- // negative z-indices.
- std::unique_ptr<PaintLayers> neg_z_order_list_;
-
- // This boolean caches whether the z-order lists above are dirty.
- // It is only ever set for stacking contexts, as no other element can
- // have z-order lists.
+ PaintLayer& layer_;
+
+ // Holds a sorted list of all the descendant nodes within that have z-indices
+ // of 0 (or is treated as 0 for positioned objects) or greater.
+ PaintLayers pos_z_order_list_;
+ // Holds descendants within our stacking context with negative z-indices.
+ PaintLayers neg_z_order_list_;
+
+ // Overlay scrollbars need to be painted above all scrollable contents, even
+ // if the contents are stacked in a stacking context which is an ancestor of
+ // the scrolling layer, for example:
+ // <div id="stacking-context" style="opacity: 0.5">
+ // <div id="other" style="position: relative; z-index: 10></div>
+ // <div id="scroller" style="overflow: scroll">
+ // <div id="child" style="position: relative">CHILD</div>
+ // </div>
+ // </div>
+ // and
+ // <div id="stacking-context" style="opacity: 0.5">
+ // <div id="other" style="position: relative; z-index: 10></div>
+ // <div id="scroller" style="overflow: scroll; position: relative">
+ // <div id="child" style="position: absolute; z-index: 5">CHILD</div>
+ // </div>
+ // </div>
+ //
+ // The paint order without reordering overlay scrollbars would be:
+ // stacking-context
+ // / | \
+ // scroller child other
+ // |
+ // overlay scrollbars
+ // where the overlay scrollbars would be painted incorrectly below |child|
+ // which is scrollable by |scroller|.
+ //
+ // To paint the overlay scrollbars above all scrollable contents, we need to
+ // reorder the z-order of overlay scrollbars in the stacking context:
+ // stacking-context
+ // / | | \
+ // scroller child | other
+ // |
+ // overlay scrollbars
+ //
+ // This map records which PaintLayers (the values of the map) have overlay
+ // scrollbars which should paint after the given PaintLayer (the key of the
+ // map). The value of the map is a list of PaintLayers because there may be
+ // more than one scroller in the same stacking context with overlay
+ // scrollbars.
+ HashMap<const PaintLayer*, PaintLayers>
+ layer_to_overlay_scrollbars_painting_after_;
+
+ // Indicates whether the z-order lists above are dirty.
bool z_order_lists_dirty_ : 1;
-#if DCHECK_IS_ON()
- bool layer_list_mutation_allowed_ : 1;
-#endif
-
DISALLOW_COPY_AND_ASSIGN(PaintLayerStackingNode);
};
-#if DCHECK_IS_ON()
-class LayerListMutationDetector {
- STACK_ALLOCATED();
-
- public:
- explicit LayerListMutationDetector(PaintLayerStackingNode* stacking_node)
- : stacking_node_(stacking_node),
- previous_mutation_allowed_state_(
- stacking_node->LayerListMutationAllowed()) {
- stacking_node_->SetLayerListMutationAllowed(false);
- }
-
- ~LayerListMutationDetector() {
- stacking_node_->SetLayerListMutationAllowed(
- previous_mutation_allowed_state_);
- }
-
- private:
- PaintLayerStackingNode* stacking_node_;
- bool previous_mutation_allowed_state_;
-};
-#endif
-
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_PAINT_LAYER_STACKING_NODE_H_
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 cce4f67edc2..ca57e30b166 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
@@ -4,10 +4,12 @@
#include "third_party/blink/renderer/core/paint/paint_layer.h"
+#include "testing/gmock/include/gmock/gmock.h"
#include "third_party/blink/renderer/core/dom/pseudo_element.h"
#include "third_party/blink/renderer/core/html/html_iframe_element.h"
#include "third_party/blink/renderer/core/layout/layout_box_model_object.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
+#include "third_party/blink/renderer/core/paint/paint_layer_paint_order_iterator.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/platform/testing/paint_test_configurations.h"
@@ -15,14 +17,17 @@
namespace blink {
+using ::testing::ElementsAre;
+using ::testing::Pointee;
+
class PaintLayerTest : public PaintTestConfigurations, public RenderingTest {
public:
PaintLayerTest()
: RenderingTest(MakeGarbageCollected<SingleChildLocalFrameClient>()) {}
void SetUp() override {
- RenderingTest::SetUp();
EnableCompositing();
+ RenderingTest::SetUp();
}
};
@@ -231,7 +236,9 @@ TEST_P(PaintLayerTest, CompositedScrollingNoNeedsRepaint) {
scroll_layer->GetScrollableArea()->SetScrollOffset(ScrollOffset(1000, 1000),
kProgrammaticScroll);
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
- EXPECT_EQ(PhysicalOffset(-1000, -1000), content_layer->Location());
+ EXPECT_EQ(PhysicalOffset(0, 0), content_layer->Location());
+ EXPECT_EQ(LayoutSize(1000, 1000),
+ content_layer->ContainingLayer()->ScrolledContentOffset());
EXPECT_FALSE(content_layer->NeedsRepaint());
EXPECT_FALSE(scroll_layer->NeedsRepaint());
UpdateAllLifecyclePhasesForTest();
@@ -261,7 +268,10 @@ TEST_P(PaintLayerTest, NonCompositedScrollingNeedsRepaint) {
scroll_layer->GetScrollableArea()->SetScrollOffset(ScrollOffset(1000, 1000),
kProgrammaticScroll);
GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint();
- EXPECT_EQ(PhysicalOffset(-1000, -1000), content_layer->Location());
+ EXPECT_EQ(PhysicalOffset(0, 0), content_layer->Location());
+ EXPECT_EQ(LayoutSize(1000, 1000),
+ content_layer->ContainingLayer()->ScrolledContentOffset());
+
EXPECT_TRUE(scroll_layer->NeedsRepaint());
EXPECT_FALSE(content_layer->NeedsRepaint());
UpdateAllLifecyclePhasesForTest();
@@ -444,79 +454,333 @@ TEST_P(PaintLayerTest, HasSelfPaintingParentNotSelfPainting) {
EXPECT_FALSE(child->HasSelfPaintingLayerDescendant());
}
-TEST_P(PaintLayerTest, NonStackedWithInFlowDescendant) {
+static const Vector<PaintLayer*>* LayersPaintingOverlayScrollbarsAfter(
+ const PaintLayer* layer) {
+ return PaintLayerPaintOrderIterator(*layer->AncestorStackingContext(),
+ kPositiveZOrderChildren)
+ .LayersPaintingOverlayScrollbarsAfter(layer);
+}
+
+TEST_P(PaintLayerTest, ReorderOverlayScrollbars_StackedWithInFlowDescendant) {
SetBodyInnerHTML(R"HTML(
- <div id='parent' style='overflow: auto'>
- <div id='child' style='position: relative'>
- <div></div>
- </div>
+ <div id='parent' style='overflow: auto; position: relative;
+ width: 100px; height: 100px'>
+ <div id='child' style='position: relative; height: 200px'></div>
</div>
)HTML");
- PaintLayer* parent = GetPaintLayerByElementId("parent");
- PaintLayer* child = GetPaintLayerByElementId("child");
+ auto* parent = GetPaintLayerByElementId("parent");
+ auto* child = GetPaintLayerByElementId("child");
+ EXPECT_TRUE(parent->NeedsReorderOverlayScrollbars());
+ EXPECT_FALSE(child->NeedsReorderOverlayScrollbars());
+ EXPECT_THAT(LayersPaintingOverlayScrollbarsAfter(child),
+ Pointee(ElementsAre(parent)));
- EXPECT_TRUE(parent->IsNonStackedWithInFlowStackedDescendant());
- EXPECT_FALSE(child->IsNonStackedWithInFlowStackedDescendant());
+ GetDocument().getElementById("child")->setAttribute(
+ html_names::kStyleAttr, "position: relative; height: 80px");
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_FALSE(parent->NeedsReorderOverlayScrollbars());
+ EXPECT_FALSE(LayersPaintingOverlayScrollbarsAfter(child));
+
+ GetDocument().getElementById("child")->setAttribute(
+ html_names::kStyleAttr, "position: relative; width: 200px; height: 80px");
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_TRUE(parent->NeedsReorderOverlayScrollbars());
+ EXPECT_THAT(LayersPaintingOverlayScrollbarsAfter(child),
+ Pointee(ElementsAre(parent)));
+
+ GetDocument().getElementById("child")->setAttribute(
+ html_names::kStyleAttr, "width: 200px; height: 80px");
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_FALSE(parent->NeedsReorderOverlayScrollbars());
+
+ GetDocument().getElementById("child")->setAttribute(
+ html_names::kStyleAttr, "position: relative; width: 200px; height: 80px");
+ UpdateAllLifecyclePhasesForTest();
+ child = GetPaintLayerByElementId("child");
+ EXPECT_TRUE(parent->NeedsReorderOverlayScrollbars());
+ EXPECT_THAT(LayersPaintingOverlayScrollbarsAfter(child),
+ Pointee(ElementsAre(parent)));
}
-TEST_P(PaintLayerTest, NonStackedWithOutOfFlowDescendant) {
+TEST_P(PaintLayerTest,
+ ReorderOverlayScrollbars_StackedWithOutOfFlowDescendant) {
SetBodyInnerHTML(R"HTML(
- <div id='parent' style='overflow: auto'>
- <div id='child' style='position: absolute'>
- <div></div>
- </div>
+ <style>#child { width: 200px; height: 200px; }</style>
+ <div id='parent' style='overflow: auto; position: relative; height: 100px'>
+ <div id='child' style='position: absolute'></div>
</div>
)HTML");
- PaintLayer* parent = GetPaintLayerByElementId("parent");
- PaintLayer* child = GetPaintLayerByElementId("child");
+ auto* parent = GetPaintLayerByElementId("parent");
+ auto* child = GetPaintLayerByElementId("child");
+ EXPECT_TRUE(parent->NeedsReorderOverlayScrollbars());
+ EXPECT_FALSE(child->NeedsReorderOverlayScrollbars());
+ EXPECT_THAT(LayersPaintingOverlayScrollbarsAfter(child),
+ Pointee(ElementsAre(parent)));
+
+ GetDocument().getElementById("child")->setAttribute(html_names::kStyleAttr,
+ "");
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_FALSE(parent->NeedsReorderOverlayScrollbars());
- EXPECT_FALSE(parent->IsNonStackedWithInFlowStackedDescendant());
- EXPECT_FALSE(child->IsNonStackedWithInFlowStackedDescendant());
+ GetDocument().getElementById("child")->setAttribute(html_names::kStyleAttr,
+ "position: absolute");
+ UpdateAllLifecyclePhasesForTest();
+ child = GetPaintLayerByElementId("child");
+ EXPECT_TRUE(parent->NeedsReorderOverlayScrollbars());
+ EXPECT_THAT(LayersPaintingOverlayScrollbarsAfter(child),
+ Pointee(ElementsAre(parent)));
}
-TEST_P(PaintLayerTest, NonStackedWithNonStackedDescendant) {
+TEST_P(PaintLayerTest, ReorderOverlayScrollbars_StackedWithZIndexDescendant) {
SetBodyInnerHTML(R"HTML(
- <div id='parent' style='overflow: auto'>
- <div id='child' style='overflow: auto'>
- <div></div>
+ <style>#child { position: absolute; width: 200px; height: 200px; }</style>
+ <div id='parent' style='overflow: auto; position: relative; height: 100px'>
+ <div id='child' style='position: absolute; z-index: 1;
+ width: 200px; height: 200px'></div>
+ </div>
+ )HTML");
+ auto* parent = GetPaintLayerByElementId("parent");
+ auto* child = GetPaintLayerByElementId("child");
+ EXPECT_TRUE(parent->NeedsReorderOverlayScrollbars());
+ EXPECT_FALSE(child->NeedsReorderOverlayScrollbars());
+ EXPECT_THAT(LayersPaintingOverlayScrollbarsAfter(child),
+ Pointee(ElementsAre(parent)));
+
+ GetDocument().getElementById("child")->setAttribute(html_names::kStyleAttr,
+ "z-index: -1");
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_FALSE(parent->NeedsReorderOverlayScrollbars());
+ EXPECT_FALSE(LayersPaintingOverlayScrollbarsAfter(child));
+
+ GetDocument().getElementById("child")->setAttribute(html_names::kStyleAttr,
+ "z-index: 2");
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_TRUE(parent->NeedsReorderOverlayScrollbars());
+ EXPECT_THAT(LayersPaintingOverlayScrollbarsAfter(child),
+ Pointee(ElementsAre(parent)));
+}
+
+TEST_P(PaintLayerTest,
+ ReorderOverlayScrollbars_NestedStackedWithInFlowStackedChild) {
+ SetBodyInnerHTML(R"HTML(
+ <div id='ancestor'
+ style='overflow: auto; position: relative; height: 100px'>
+ <div id='parent' style='overflow: auto; height: 200px'>
+ <div id="child" style='position: relative; height: 300px'></div>
</div>
</div>
)HTML");
- PaintLayer* parent = GetPaintLayerByElementId("parent");
- PaintLayer* child = GetPaintLayerByElementId("child");
+ auto* ancestor = GetPaintLayerByElementId("ancestor");
+ auto* parent = GetPaintLayerByElementId("parent");
+ auto* child = GetPaintLayerByElementId("child");
+ EXPECT_TRUE(ancestor->NeedsReorderOverlayScrollbars());
+ EXPECT_TRUE(parent->NeedsReorderOverlayScrollbars());
+ EXPECT_FALSE(child->NeedsReorderOverlayScrollbars());
+ EXPECT_THAT(LayersPaintingOverlayScrollbarsAfter(child),
+ Pointee(ElementsAre(parent, ancestor)));
+}
- EXPECT_FALSE(parent->IsNonStackedWithInFlowStackedDescendant());
- EXPECT_FALSE(child->IsNonStackedWithInFlowStackedDescendant());
+TEST_P(PaintLayerTest,
+ ReorderOverlayScrollbars_NestedStackedWithOutOfFlowStackedChild) {
+ SetBodyInnerHTML(R"HTML(
+ <div id='ancestor'
+ style='overflow: auto; position: relative; height: 100px'>
+ <div id='parent' style='overflow: auto; position: absolute;
+ width: 200px; height: 200px'>
+ <div id="child" style='position: absolute; width: 300px; height: 300px'>
+ </div>
+ </div>
+ </div>
+ )HTML");
+ auto* ancestor = GetPaintLayerByElementId("ancestor");
+ auto* parent = GetPaintLayerByElementId("parent");
+ auto* child = GetPaintLayerByElementId("child");
+ EXPECT_TRUE(ancestor->NeedsReorderOverlayScrollbars());
+ EXPECT_TRUE(parent->NeedsReorderOverlayScrollbars());
+ EXPECT_FALSE(child->NeedsReorderOverlayScrollbars());
+ EXPECT_THAT(LayersPaintingOverlayScrollbarsAfter(child),
+ Pointee(ElementsAre(parent, ancestor)));
}
-TEST_P(PaintLayerTest, NonStackedWithInFlowStackedGrandchild) {
+TEST_P(PaintLayerTest, ReorderOverlayScrollbars_MultipleChildren) {
SetBodyInnerHTML(R"HTML(
- <div id='parent' style='overflow: auto'>
- <div id='child' style='overflow: auto'>
- <div style='position: relative'></div>
+ <style>
+ div { width: 200px; height: 200px; }
+ #parent { overflow: auto; width: 100px; height: 100px; }
+ </style>
+ <div id='parent'>
+ <div id="low-child" style='position: absolute; z-index: 1'></div>
+ <div id="middle-child" style='position: relative; z-index: 2'></div>
+ <div id="high-child" style='position: absolute; z-index: 3'></div>
+ </div>
+ )HTML");
+
+ auto* parent = GetPaintLayerByElementId("parent");
+ auto* low_child = GetPaintLayerByElementId("low-child");
+ auto* middle_child = GetPaintLayerByElementId("middle-child");
+ auto* high_child = GetPaintLayerByElementId("high-child");
+ EXPECT_TRUE(parent->NeedsReorderOverlayScrollbars());
+ EXPECT_FALSE(LayersPaintingOverlayScrollbarsAfter(low_child));
+ // The highest contained child by parent is middle_child because the
+ // absolute-position children are not contained.
+ EXPECT_THAT(LayersPaintingOverlayScrollbarsAfter(middle_child),
+ Pointee(ElementsAre(parent)));
+ EXPECT_FALSE(LayersPaintingOverlayScrollbarsAfter(high_child));
+
+ GetDocument().getElementById("parent")->setAttribute(
+ html_names::kStyleAttr, "position: absolute; z-index: 1");
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_FALSE(parent->NeedsReorderOverlayScrollbars());
+ EXPECT_FALSE(LayersPaintingOverlayScrollbarsAfter(low_child));
+ EXPECT_FALSE(LayersPaintingOverlayScrollbarsAfter(middle_child));
+ EXPECT_FALSE(LayersPaintingOverlayScrollbarsAfter(high_child));
+
+ GetDocument().getElementById("parent")->setAttribute(html_names::kStyleAttr,
+ "position: absolute");
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_TRUE(parent->NeedsReorderOverlayScrollbars());
+ EXPECT_FALSE(LayersPaintingOverlayScrollbarsAfter(low_child));
+ EXPECT_FALSE(LayersPaintingOverlayScrollbarsAfter(middle_child));
+ EXPECT_THAT(LayersPaintingOverlayScrollbarsAfter(high_child),
+ Pointee(ElementsAre(parent)));
+}
+
+TEST_P(PaintLayerTest,
+ ReorderOverlayScrollbars_NonStackedWithInFlowDescendant) {
+ SetBodyInnerHTML(R"HTML(
+ <div id='parent' style='overflow: auto; width: 100px; height: 100px'>
+ <div id='child' style='position: relative; height: 200px'></div>
+ </div>
+ )HTML");
+ auto* parent = GetPaintLayerByElementId("parent");
+ auto* child = GetPaintLayerByElementId("child");
+ EXPECT_TRUE(parent->NeedsReorderOverlayScrollbars());
+ EXPECT_FALSE(child->NeedsReorderOverlayScrollbars());
+ EXPECT_THAT(LayersPaintingOverlayScrollbarsAfter(child),
+ Pointee(ElementsAre(parent)));
+
+ GetDocument().getElementById("child")->setAttribute(
+ html_names::kStyleAttr, "position: relative; height: 80px");
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_FALSE(parent->NeedsReorderOverlayScrollbars());
+ EXPECT_FALSE(LayersPaintingOverlayScrollbarsAfter(child));
+
+ GetDocument().getElementById("child")->setAttribute(
+ html_names::kStyleAttr, "position: relative; width: 200px; height: 80px");
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_TRUE(parent->NeedsReorderOverlayScrollbars());
+ EXPECT_THAT(LayersPaintingOverlayScrollbarsAfter(child),
+ Pointee(ElementsAre(parent)));
+
+ GetDocument().getElementById("child")->setAttribute(
+ html_names::kStyleAttr, "width: 200px; height: 80px");
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_FALSE(parent->NeedsReorderOverlayScrollbars());
+
+ GetDocument().getElementById("child")->setAttribute(
+ html_names::kStyleAttr, "position: relative; width: 200px; height: 80px");
+ UpdateAllLifecyclePhasesForTest();
+ child = GetPaintLayerByElementId("child");
+ EXPECT_TRUE(parent->NeedsReorderOverlayScrollbars());
+ EXPECT_THAT(LayersPaintingOverlayScrollbarsAfter(child),
+ Pointee(ElementsAre(parent)));
+}
+
+TEST_P(PaintLayerTest,
+ ReorderOverlayScrollbars_NonStackedWithZIndexInFlowDescendant) {
+ SetBodyInnerHTML(R"HTML(
+ <style>#child { position: relative; height: 200px; }</style>
+ <div id='parent' style='overflow: auto; height: 100px'>
+ <div id='child' style='z-index: 1'>
</div>
</div>
)HTML");
- PaintLayer* parent = GetPaintLayerByElementId("parent");
- PaintLayer* child = GetPaintLayerByElementId("child");
+ auto* parent = GetPaintLayerByElementId("parent");
+ auto* child = GetPaintLayerByElementId("child");
+ EXPECT_TRUE(parent->NeedsReorderOverlayScrollbars());
+ EXPECT_FALSE(child->NeedsReorderOverlayScrollbars());
+ EXPECT_THAT(LayersPaintingOverlayScrollbarsAfter(child),
+ Pointee(ElementsAre(parent)));
+
+ GetDocument().getElementById("child")->setAttribute(html_names::kStyleAttr,
+ "z-index: -1");
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_FALSE(parent->NeedsReorderOverlayScrollbars());
+ EXPECT_FALSE(LayersPaintingOverlayScrollbarsAfter(child));
- EXPECT_TRUE(parent->IsNonStackedWithInFlowStackedDescendant());
- EXPECT_TRUE(child->IsNonStackedWithInFlowStackedDescendant());
+ GetDocument().getElementById("child")->setAttribute(html_names::kStyleAttr,
+ "z-index: 2");
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_TRUE(parent->NeedsReorderOverlayScrollbars());
+ EXPECT_THAT(LayersPaintingOverlayScrollbarsAfter(child),
+ Pointee(ElementsAre(parent)));
}
-TEST_P(PaintLayerTest, NonStackedWithOutOfFlowStackedGrandchild) {
+TEST_P(PaintLayerTest,
+ ReorderOverlayScrollbars_NonStackedWithOutOfFlowDescendant) {
+ SetBodyInnerHTML(R"HTML(
+ <div id='parent' style='overflow: auto; height: 100px'>
+ <div id='child' style='position: absolute;
+ width: 200px; height: 200px'></div>
+ </div>
+ )HTML");
+ auto* parent = GetPaintLayerByElementId("parent");
+ auto* child = GetPaintLayerByElementId("child");
+ EXPECT_FALSE(parent->NeedsReorderOverlayScrollbars());
+ EXPECT_FALSE(child->NeedsReorderOverlayScrollbars());
+ EXPECT_FALSE(LayersPaintingOverlayScrollbarsAfter(child));
+}
+
+TEST_P(PaintLayerTest,
+ ReorderOverlayScrollbars_NonStackedWithNonStackedDescendant) {
SetBodyInnerHTML(R"HTML(
<div id='parent' style='overflow: auto'>
- <div id='child' style='overflow: auto'>
- <div style='position: absolute'></div>
+ <div id='child' style='overflow: auto'></div>
+ </div>
+ )HTML");
+ auto* parent = GetPaintLayerByElementId("parent");
+ auto* child = GetPaintLayerByElementId("child");
+ EXPECT_FALSE(parent->NeedsReorderOverlayScrollbars());
+ EXPECT_FALSE(child->NeedsReorderOverlayScrollbars());
+ EXPECT_FALSE(LayersPaintingOverlayScrollbarsAfter(child));
+}
+
+TEST_P(PaintLayerTest,
+ ReorderOverlayScrollbars_NestedNonStackedWithInFlowStackedChild) {
+ SetBodyInnerHTML(R"HTML(
+ <div id='ancestor' style='overflow: auto; height: 100px'>
+ <div id='parent' style='overflow: auto; height: 200px'>
+ <div id="child" style='position: relative; height: 300px'></div>
</div>
</div>
)HTML");
- PaintLayer* parent = GetPaintLayerByElementId("parent");
- PaintLayer* child = GetPaintLayerByElementId("child");
+ auto* ancestor = GetPaintLayerByElementId("ancestor");
+ auto* parent = GetPaintLayerByElementId("parent");
+ auto* child = GetPaintLayerByElementId("child");
+ EXPECT_TRUE(ancestor->NeedsReorderOverlayScrollbars());
+ EXPECT_TRUE(parent->NeedsReorderOverlayScrollbars());
+ EXPECT_FALSE(child->NeedsReorderOverlayScrollbars());
+ EXPECT_THAT(LayersPaintingOverlayScrollbarsAfter(child),
+ Pointee(ElementsAre(parent, ancestor)));
+}
- EXPECT_FALSE(parent->IsNonStackedWithInFlowStackedDescendant());
- EXPECT_FALSE(child->IsNonStackedWithInFlowStackedDescendant());
+TEST_P(PaintLayerTest,
+ ReorderOverlayScrollbars_NestedNonStackedWithOutOfFlowStackedChild) {
+ SetBodyInnerHTML(R"HTML(
+ <div id='ancestor' style='overflow: auto; height: 100px'>
+ <div id='parent' style='overflow: auto; height: 200px'>
+ <div id="child" style='position: absolute; width: 300px; height: 300px'>
+ </div>
+ </div>
+ </div>
+ )HTML");
+ auto* ancestor = GetPaintLayerByElementId("ancestor");
+ auto* parent = GetPaintLayerByElementId("parent");
+ auto* child = GetPaintLayerByElementId("child");
+ EXPECT_FALSE(ancestor->NeedsReorderOverlayScrollbars());
+ EXPECT_FALSE(parent->NeedsReorderOverlayScrollbars());
+ EXPECT_FALSE(child->NeedsReorderOverlayScrollbars());
+ EXPECT_FALSE(LayersPaintingOverlayScrollbarsAfter(child));
}
TEST_P(PaintLayerTest, SubsequenceCachingStackingContexts) {
@@ -588,15 +852,19 @@ TEST_P(PaintLayerTest, NegativeZIndexChangeToPositive) {
PaintLayer* target = GetPaintLayerByElementId("target");
- EXPECT_TRUE(target->StackingNode()->HasNegativeZOrderList());
- EXPECT_FALSE(target->StackingNode()->HasPositiveZOrderList());
+ EXPECT_TRUE(
+ PaintLayerPaintOrderIterator(*target, kNegativeZOrderChildren).Next());
+ EXPECT_FALSE(
+ PaintLayerPaintOrderIterator(*target, kPositiveZOrderChildren).Next());
GetDocument().getElementById("child")->setAttribute(html_names::kStyleAttr,
"z-index: 1");
UpdateAllLifecyclePhasesForTest();
- EXPECT_FALSE(target->StackingNode()->HasNegativeZOrderList());
- EXPECT_TRUE(target->StackingNode()->HasPositiveZOrderList());
+ EXPECT_FALSE(
+ PaintLayerPaintOrderIterator(*target, kNegativeZOrderChildren).Next());
+ EXPECT_TRUE(
+ PaintLayerPaintOrderIterator(*target, kPositiveZOrderChildren).Next());
}
TEST_P(PaintLayerTest, HasDescendantWithClipPath) {
@@ -1085,12 +1353,18 @@ TEST_P(PaintLayerTest, FloatLayerAndAbsoluteUnderInlineLayer) {
EXPECT_EQ(container, span->ContainingLayer());
if (RuntimeEnabledFeatures::LayoutNGEnabled()) {
- EXPECT_EQ(PhysicalOffset(50, 50), floating->Location());
+ EXPECT_EQ(PhysicalOffset(0, 0), floating->Location());
+ EXPECT_EQ(PhysicalOffset(50, 50),
+ floating->GetLayoutObject().OffsetForInFlowPosition());
} else {
- EXPECT_EQ(PhysicalOffset(83, 83), floating->Location());
+ EXPECT_EQ(PhysicalOffset(33, 33), floating->Location());
+ EXPECT_EQ(PhysicalOffset(50, 50),
+ floating->GetLayoutObject().OffsetForInFlowPosition());
}
EXPECT_EQ(PhysicalOffset(50, 50), absolute->Location());
- EXPECT_EQ(PhysicalOffset(133, 133), span->Location());
+ EXPECT_EQ(PhysicalOffset(33, 33), span->Location());
+ EXPECT_EQ(PhysicalOffset(100, 100),
+ span->GetLayoutObject().OffsetForInFlowPosition());
EXPECT_EQ(PhysicalOffset(20, 20), container->Location());
if (RuntimeEnabledFeatures::LayoutNGEnabled()) {
@@ -1135,14 +1409,24 @@ TEST_P(PaintLayerTest, FloatLayerUnderInlineLayerScrolled) {
EXPECT_EQ(container, span->Parent());
EXPECT_EQ(container, span->ContainingLayer());
- EXPECT_EQ(PhysicalOffset(100, -300), span->Location());
+ EXPECT_EQ(PhysicalOffset(0, 0), span->Location());
+ EXPECT_EQ(PhysicalOffset(100, 100),
+ span->GetLayoutObject().OffsetForInFlowPosition());
+ EXPECT_EQ(LayoutSize(0, 400),
+ span->ContainingLayer()->ScrolledContentOffset());
if (RuntimeEnabledFeatures::LayoutNGEnabled()) {
- EXPECT_EQ(PhysicalOffset(50, 50), floating->Location());
+ EXPECT_EQ(PhysicalOffset(0, 0), floating->Location());
+ EXPECT_EQ(PhysicalOffset(50, 50),
+ floating->GetLayoutObject().OffsetForInFlowPosition());
EXPECT_EQ(PhysicalOffset(50, 50), floating->VisualOffsetFromAncestor(span));
EXPECT_EQ(PhysicalOffset(150, -250),
floating->VisualOffsetFromAncestor(container));
} else {
- EXPECT_EQ(PhysicalOffset(50, -350), floating->Location());
+ EXPECT_EQ(PhysicalOffset(0, 0), floating->Location());
+ EXPECT_EQ(PhysicalOffset(50, 50),
+ floating->GetLayoutObject().OffsetForInFlowPosition());
+ EXPECT_EQ(LayoutSize(0, 400),
+ floating->ContainingLayer()->ScrolledContentOffset());
EXPECT_EQ(PhysicalOffset(-50, -50),
floating->VisualOffsetFromAncestor(span));
EXPECT_EQ(PhysicalOffset(50, -350),
@@ -1168,8 +1452,12 @@ TEST_P(PaintLayerTest, FloatLayerUnderBlockUnderInlineLayer) {
EXPECT_EQ(span, floating->Parent());
EXPECT_EQ(span, floating->ContainingLayer());
- EXPECT_EQ(PhysicalOffset(83, 83), floating->Location());
- EXPECT_EQ(PhysicalOffset(100, 100), span->Location());
+ EXPECT_EQ(PhysicalOffset(33, 33), floating->Location());
+ EXPECT_EQ(PhysicalOffset(50, 50),
+ floating->GetLayoutObject().OffsetForInFlowPosition());
+ EXPECT_EQ(PhysicalOffset(0, 0), span->Location());
+ EXPECT_EQ(PhysicalOffset(100, 100),
+ span->GetLayoutObject().OffsetForInFlowPosition());
EXPECT_EQ(PhysicalOffset(83, 83), floating->VisualOffsetFromAncestor(span));
EXPECT_EQ(PhysicalOffset(183, 183),
floating->VisualOffsetFromAncestor(
@@ -1198,8 +1486,12 @@ TEST_P(PaintLayerTest, FloatLayerUnderFloatUnderInlineLayer) {
EXPECT_EQ(span->Parent(), floating->ContainingLayer());
}
- EXPECT_EQ(PhysicalOffset(83, 83), floating->Location());
- EXPECT_EQ(PhysicalOffset(100, 100), span->Location());
+ EXPECT_EQ(PhysicalOffset(33, 33), floating->Location());
+ EXPECT_EQ(PhysicalOffset(50, 50),
+ floating->GetLayoutObject().OffsetForInFlowPosition());
+ EXPECT_EQ(PhysicalOffset(0, 0), span->Location());
+ EXPECT_EQ(PhysicalOffset(100, 100),
+ span->GetLayoutObject().OffsetForInFlowPosition());
if (RuntimeEnabledFeatures::LayoutNGEnabled()) {
EXPECT_EQ(PhysicalOffset(83, 83), floating->VisualOffsetFromAncestor(span));
EXPECT_EQ(PhysicalOffset(183, 183),
@@ -1240,9 +1532,13 @@ TEST_P(PaintLayerTest, FloatLayerUnderFloatLayerUnderInlineLayer) {
EXPECT_EQ(span->Parent(), floating_parent->ContainingLayer());
}
- EXPECT_EQ(PhysicalOffset(50, 50), floating->Location());
+ EXPECT_EQ(PhysicalOffset(0, 0), floating->Location());
+ EXPECT_EQ(PhysicalOffset(50, 50),
+ floating->GetLayoutObject().OffsetForInFlowPosition());
EXPECT_EQ(PhysicalOffset(33, 33), floating_parent->Location());
- EXPECT_EQ(PhysicalOffset(100, 100), span->Location());
+ EXPECT_EQ(PhysicalOffset(0, 0), span->Location());
+ EXPECT_EQ(PhysicalOffset(100, 100),
+ span->GetLayoutObject().OffsetForInFlowPosition());
if (RuntimeEnabledFeatures::LayoutNGEnabled()) {
EXPECT_EQ(PhysicalOffset(83, 83), floating->VisualOffsetFromAncestor(span));
EXPECT_EQ(PhysicalOffset(33, 33),
@@ -1284,8 +1580,12 @@ TEST_P(PaintLayerTest, LayerUnderFloatUnderInlineLayer) {
EXPECT_EQ(span->Parent(), child->ContainingLayer());
}
- EXPECT_EQ(PhysicalOffset(83, 83), child->Location());
- EXPECT_EQ(PhysicalOffset(100, 100), span->Location());
+ EXPECT_EQ(PhysicalOffset(33, 33), child->Location());
+ EXPECT_EQ(PhysicalOffset(50, 50),
+ child->GetLayoutObject().OffsetForInFlowPosition());
+ EXPECT_EQ(PhysicalOffset(0, 0), span->Location());
+ EXPECT_EQ(PhysicalOffset(100, 100),
+ span->GetLayoutObject().OffsetForInFlowPosition());
if (RuntimeEnabledFeatures::LayoutNGEnabled()) {
EXPECT_EQ(PhysicalOffset(83, 83), child->VisualOffsetFromAncestor(span));
EXPECT_EQ(PhysicalOffset(183, 183),
@@ -1385,8 +1685,15 @@ TEST_P(PaintLayerTest, ColumnSpanLayerUnderExtraLayerScrolled) {
EXPECT_EQ(columns, extra_layer->Parent()->Parent());
EXPECT_EQ(columns, extra_layer->ContainingLayer()->Parent());
- EXPECT_EQ(PhysicalOffset(-150, 50), spanner->Location());
- EXPECT_EQ(PhysicalOffset(100, 100), extra_layer->Location());
+ EXPECT_EQ(PhysicalOffset(0, 0), spanner->Location());
+ EXPECT_EQ(PhysicalOffset(50, 50),
+ spanner->GetLayoutObject().OffsetForInFlowPosition());
+
+ EXPECT_EQ(LayoutSize(200, 0),
+ spanner->ContainingLayer()->ScrolledContentOffset());
+ EXPECT_EQ(PhysicalOffset(0, 0), extra_layer->Location());
+ EXPECT_EQ(PhysicalOffset(100, 100),
+ extra_layer->GetLayoutObject().OffsetForInFlowPosition());
// -60 = 2nd-column-x(40) - scroll-offset-x(200) + x-location(100)
// 20 = y-location(100) - column-height(80)
EXPECT_EQ(PhysicalOffset(-60, 20),
@@ -1610,7 +1917,7 @@ TEST_P(PaintLayerTest, HitTestWithStopNode) {
// Regular hit test over 'child'
HitTestRequest request(HitTestRequest::kReadOnly | HitTestRequest::kActive);
- HitTestLocation location((LayoutPoint(50, 25)));
+ HitTestLocation location((PhysicalOffset(50, 25)));
HitTestResult result(request, location);
GetDocument().GetLayoutView()->HitTest(location, result);
EXPECT_EQ(child, result.InnerNode());
@@ -1624,7 +1931,7 @@ TEST_P(PaintLayerTest, HitTestWithStopNode) {
// Regular hit test over 'overlap'
request = HitTestRequest(HitTestRequest::kReadOnly | HitTestRequest::kActive);
- location = HitTestLocation((LayoutPoint(50, 75)));
+ location = HitTestLocation((PhysicalOffset(50, 75)));
result = HitTestResult(request, location);
GetDocument().GetLayoutView()->HitTest(location, result);
EXPECT_EQ(overlap, result.InnerNode());
@@ -1641,7 +1948,7 @@ TEST_P(PaintLayerTest, HitTestWithStopNode) {
request = HitTestRequest(HitTestRequest::kReadOnly | HitTestRequest::kActive |
HitTestRequest::kListBased,
hit->GetLayoutObject());
- location = HitTestLocation((LayoutRect(40, 15, 20, 20)));
+ location = HitTestLocation((PhysicalRect(40, 15, 20, 20)));
result = HitTestResult(request, location);
GetDocument().GetLayoutView()->HitTest(location, result);
EXPECT_EQ(1u, result.ListBasedTestResult().size());
@@ -1670,7 +1977,7 @@ TEST_P(PaintLayerTest, HitTestTableWithStopNode) {
Element* table = GetDocument().getElementById("table");
Element* cell11 = GetDocument().getElementById("cell11");
HitTestRequest request(HitTestRequest::kReadOnly | HitTestRequest::kActive);
- HitTestLocation location((LayoutPoint(50, 50)));
+ HitTestLocation location((PhysicalOffset(50, 50)));
HitTestResult result(request, location);
GetDocument().GetLayoutView()->HitTest(location, result);
EXPECT_EQ(cell11, result.InnerNode());
@@ -1691,7 +1998,7 @@ TEST_P(PaintLayerTest, HitTestSVGWithStopNode) {
Element* svg = GetDocument().getElementById("svg");
Element* circle = GetDocument().getElementById("circle");
HitTestRequest request(HitTestRequest::kReadOnly | HitTestRequest::kActive);
- HitTestLocation location((LayoutPoint(50, 50)));
+ HitTestLocation location((PhysicalOffset(50, 50)));
HitTestResult result(request, location);
GetDocument().GetLayoutView()->HitTest(location, result);
EXPECT_EQ(circle, result.InnerNode());
@@ -1744,7 +2051,7 @@ TEST_P(PaintLayerTest, HitTestPseudoElementWithContinuation) {
)HTML");
Element* target = GetDocument().getElementById("target");
HitTestRequest request(HitTestRequest::kReadOnly | HitTestRequest::kActive);
- HitTestLocation location(LayoutPoint(10, 10));
+ HitTestLocation location(PhysicalOffset(10, 10));
HitTestResult result(request, location);
GetDocument().GetLayoutView()->HitTest(location, result);
EXPECT_EQ(target, result.InnerNode());
@@ -1768,7 +2075,7 @@ TEST_P(PaintLayerTest, HitTestFirstLetterPseudoElement) {
Element* target = GetDocument().getElementById("target");
Element* container = GetDocument().getElementById("container");
HitTestRequest request(HitTestRequest::kReadOnly | HitTestRequest::kActive);
- HitTestLocation location(LayoutPoint(10, 10));
+ HitTestLocation location(PhysicalOffset(10, 10));
HitTestResult result(request, location);
GetDocument().GetLayoutView()->HitTest(location, result);
EXPECT_EQ(target, result.InnerNode());
@@ -1793,7 +2100,7 @@ TEST_P(PaintLayerTest, HitTestFirstLetterInBeforePseudoElement) {
Element* target = GetDocument().getElementById("target");
Element* container = GetDocument().getElementById("container");
HitTestRequest request(HitTestRequest::kReadOnly | HitTestRequest::kActive);
- HitTestLocation location(LayoutPoint(10, 10));
+ HitTestLocation location(PhysicalOffset(10, 10));
HitTestResult result(request, location);
GetDocument().GetLayoutView()->HitTest(location, result);
EXPECT_EQ(target, result.InnerNode());
@@ -1819,7 +2126,7 @@ TEST_P(PaintLayerTest, HitTestFloatInsideInlineBoxContainer) {
)HTML");
Node* target = GetDocument().getElementById("target")->firstChild();
HitTestRequest request(HitTestRequest::kReadOnly | HitTestRequest::kActive);
- HitTestLocation location(LayoutPoint(55, 5)); // At the center of "bar"
+ HitTestLocation location(PhysicalOffset(55, 5)); // At the center of "bar"
HitTestResult result(request, location);
GetDocument().GetLayoutView()->HitTest(location, result);
EXPECT_EQ(target, result.InnerNode());
@@ -1842,7 +2149,7 @@ TEST_P(PaintLayerTest, HitTestFirstLetterPseudoElementDisplayContents) {
Element* target = GetDocument().getElementById("target");
Element* container = GetDocument().getElementById("container");
HitTestRequest request(HitTestRequest::kReadOnly | HitTestRequest::kActive);
- HitTestLocation location(LayoutPoint(10, 10));
+ HitTestLocation location(PhysicalOffset(10, 10));
HitTestResult result(request, location);
GetDocument().GetLayoutView()->HitTest(location, result);
EXPECT_EQ(target, result.InnerNode());
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_phase.h b/chromium/third_party/blink/renderer/core/paint/paint_phase.h
index bf0770390ba..34e57bf4782 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_phase.h
+++ b/chromium/third_party/blink/renderer/core/paint/paint_phase.h
@@ -45,7 +45,7 @@ enum class PaintPhase {
// Background phase
//
// Paint background of the current object and non-self-painting descendants.
- kBlockBackground = 0,
+ kBlockBackground,
//
// The following two values are added besides the normal
// kBlockBackground to distinguish backgrounds for the object itself
@@ -53,39 +53,40 @@ enum class PaintPhase {
// different scroll offsets and clips.
//
// Paint background of the current object only.
- kSelfBlockBackgroundOnly = 1,
+ kSelfBlockBackgroundOnly,
// Paint backgrounds of non-self-painting descendants only. The painter should
// call each non-self-painting child's paint method by passing
// paintInfo.forDescendants() which converts kDescendantBlockBackgroundsOnly
// to kBlockBackground.
- kDescendantBlockBackgroundsOnly = 2,
+ kDescendantBlockBackgroundsOnly,
// Float phase
- kFloat = 3,
+ kFloat,
// Foreground phase
- kForeground = 4,
+ kForeground,
// Outline phase
//
// Paint outline for the current object and non-self-painting descendants.
- kOutline = 5,
+ kOutline,
//
// Similar to the background phase, the following two values are added for
// painting outlines of the object itself and for descendants.
//
// Paint outline for the current object only.
- kSelfOutlineOnly = 6,
+ kSelfOutlineOnly,
// Paint outlines of non-self-painting descendants only. The painter should
// call each non-self-painting child's paint method by passing
// paintInfo.forDescendants() which converts kDescendantOutlinesOnly to
// kOutline.
- kDescendantOutlinesOnly = 7,
+ kDescendantOutlinesOnly,
// The below are auxiliary phases which are used to paint special effects.
- kSelection = 8,
- kTextClip = 9,
- kMask = 10,
+ kOverlayScrollbars,
+ kSelection,
+ kTextClip,
+ kMask,
kMax = kMask,
// These values must be kept in sync with DisplayItem::Type and
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 7165fc52d61..94e393c51ef 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
@@ -8,6 +8,7 @@
#include "cc/input/main_thread_scrolling_reason.h"
#include "cc/input/overscroll_behavior.h"
+#include "third_party/blink/renderer/core/animation/element_animations.h"
#include "third_party/blink/renderer/core/dom/dom_node_ids.h"
#include "third_party/blink/renderer/core/frame/link_highlights.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
@@ -29,6 +30,7 @@
#include "third_party/blink/renderer/core/layout/svg/svg_resources_cache.h"
#include "third_party/blink/renderer/core/page/page.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/paint/clip_path_clipper.h"
#include "third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.h"
#include "third_party/blink/renderer/core/paint/compositing/compositing_reason_finder.h"
@@ -100,6 +102,13 @@ PaintPropertyChangeType VisualViewportPaintPropertyTreeBuilder::Update(
context.absolute_position.scroll = visual_viewport.GetScrollNode();
context.fixed_position.scroll = visual_viewport.GetScrollNode();
+ if (property_changed >= PaintPropertyChangeType::kNodeAddedOrRemoved) {
+ // Force piercing subtree update for the worst case (scroll node added/
+ // removed). Not a big deal for performance because this is rare.
+ full_context.force_subtree_update_reasons |=
+ PaintPropertyTreeBuilderContext::kSubtreeUpdateIsolationPiercing;
+ }
+
#if DCHECK_IS_ON()
paint_property_tree_printer::UpdateDebugNames(visual_viewport);
#endif
@@ -280,7 +289,12 @@ static bool NeedsScrollOrScrollTranslation(
CompositingReasons direct_compositing_reasons) {
if (!object.HasOverflowClip())
return false;
- IntSize scroll_offset = ToLayoutBox(object).ScrolledContentOffset();
+
+ const LayoutBox& box = ToLayoutBox(object);
+ if (!box.GetScrollableArea())
+ return false;
+
+ ScrollOffset scroll_offset = box.GetScrollableArea()->GetScrollOffset();
return !scroll_offset.IsZero() ||
NeedsScrollNode(object, direct_compositing_reasons);
}
@@ -460,8 +474,15 @@ void FragmentPaintPropertyTreeBuilder::UpdateForPaintOffsetTranslation(
bool FragmentPaintPropertyTreeBuilder::IsAffectedByOuterViewportBoundsDelta()
const {
if (object_.StyleRef().GetPosition() != EPosition::kFixed ||
- !object_.StyleRef().IsFixedToBottom() ||
- !object_.GetFrame()->IsMainFrame())
+ !object_.StyleRef().IsFixedToBottom())
+ return false;
+
+ // Objects inside an iframe that's the root scroller should get the same
+ // "pushed by top controls" behavior as for the main frame.
+ auto& controller =
+ object_.GetFrame()->GetPage()->GlobalRootScrollerController();
+ if (!object_.GetFrame()->IsMainFrame() &&
+ object_.GetFrame()->GetDocument() != controller.GlobalRootScroller())
return false;
// It's affected by viewport only if the container is the LayoutView.
@@ -480,6 +501,9 @@ void FragmentPaintPropertyTreeBuilder::UpdatePaintOffsetTranslation(
context_.current.should_flatten_inherited_transform;
state.affected_by_outer_viewport_bounds_delta =
IsAffectedByOuterViewportBoundsDelta();
+ state.direct_compositing_reasons =
+ full_context_.direct_compositing_reasons &
+ CompositingReason::kScrollDependentPosition;
if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled() ||
RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled())
state.rendering_context_id = context_.current.rendering_context_id;
@@ -542,7 +566,7 @@ void FragmentPaintPropertyTreeBuilder::UpdateStickyTranslation() {
constraint->top_offset = layout_constraint.top_offset;
constraint->bottom_offset = layout_constraint.bottom_offset;
constraint->constraint_box_rect =
- box_model.ComputeStickyConstrainingRect();
+ RoundedIntRect(box_model.ComputeStickyConstrainingRect());
constraint->scroll_container_relative_sticky_box_rect = RoundedIntRect(
layout_constraint.scroll_container_relative_sticky_box_rect);
constraint
@@ -668,6 +692,20 @@ static bool NeedsTransform(const LayoutObject& object,
return false;
}
+static bool ActiveTransformAnimationIsAxisAligned(
+ const LayoutObject& object,
+ CompositingReasons compositing_reasons) {
+ if (!(compositing_reasons & CompositingReason::kActiveTransformAnimation))
+ return false;
+
+ if (!object.GetNode() || !object.GetNode()->IsElementNode())
+ return false;
+ const Element* element = To<Element>(object.GetNode());
+ const auto* animations = element->GetElementAnimations();
+ DCHECK(animations);
+ return animations->AnimationsPreserveAxisAlignment();
+}
+
void FragmentPaintPropertyTreeBuilder::UpdateTransform() {
if (object_.IsSVGChild()) {
UpdateTransformForNonRootSVG();
@@ -720,6 +758,13 @@ void FragmentPaintPropertyTreeBuilder::UpdateTransform() {
state.direct_compositing_reasons =
full_context_.direct_compositing_reasons &
CompositingReasonsForTransformProperty();
+ // TODO(flackr): This only needs to consider composited transform
+ // animations. This is currently a cyclic dependency but we could
+ // calculate most of the compositable animation reasons up front to
+ // only consider animations which are candidates for compositing.
+ state.animation_is_axis_aligned =
+ ActiveTransformAnimationIsAxisAligned(
+ object_, full_context_.direct_compositing_reasons);
}
}
@@ -978,6 +1023,13 @@ void FragmentPaintPropertyTreeBuilder::UpdateEffect() {
OnClearClip(properties_->ClearMaskClip());
}
+ CompositorElementId mask_compositor_element_id;
+ if (RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled() &&
+ (mask_clip || has_spv1_composited_clip_path)) {
+ mask_compositor_element_id = CompositorElementIdFromUniqueObjectId(
+ object_.UniqueId(), CompositorElementIdNamespace::kEffectMask);
+ }
+
EffectPaintPropertyNode::State state;
state.local_transform_space = context_.current.transform;
state.output_clip = output_clip;
@@ -994,16 +1046,12 @@ void FragmentPaintPropertyTreeBuilder::UpdateEffect() {
state.backdrop_filter_bounds =
properties_->Effect()->BackdropFilterBounds();
}
- // With BGPT disabled, UpdateFilterReferenceBox gets called from
- // CompositedLayerMapping::UpdateGraphicsLayerGeometry, but only
- // for composited layers.
- if (RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled() ||
- layer->GetCompositingState() != kPaintsIntoOwnBacking) {
- layer->UpdateFilterReferenceBox();
- }
layer->UpdateCompositorFilterOperationsForBackdropFilter(
state.backdrop_filter, &state.backdrop_filter_bounds);
layer->ClearBackdropFilterOnEffectNodeDirty();
+ if (!state.backdrop_filter.IsEmpty()) {
+ state.backdrop_mask_element_id = mask_compositor_element_id;
+ }
}
}
if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled() ||
@@ -1072,10 +1120,7 @@ void FragmentPaintPropertyTreeBuilder::UpdateEffect() {
mask_state.blend_mode = SkBlendMode::kDstIn;
if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled() ||
RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) {
- mask_state.compositor_element_id =
- CompositorElementIdFromUniqueObjectId(
- object_.UniqueId(),
- CompositorElementIdNamespace::kEffectMask);
+ mask_state.compositor_element_id = mask_compositor_element_id;
}
OnUpdate(properties_->UpdateMask(*properties_->Effect(),
std::move(mask_state)));
@@ -1250,8 +1295,8 @@ void FragmentPaintPropertyTreeBuilder::UpdateFilter() {
}
}
-static FloatRoundedRect ToClipRect(const PhysicalRect& rect) {
- return FloatRoundedRect(FloatRect(PixelSnappedIntRect(rect)));
+static FloatRoundedRect ToSnappedClipRect(const PhysicalRect& rect) {
+ return FloatRoundedRect(PixelSnappedIntRect(rect));
}
void FragmentPaintPropertyTreeBuilder::UpdateFragmentClip() {
@@ -1259,10 +1304,10 @@ void FragmentPaintPropertyTreeBuilder::UpdateFragmentClip() {
if (NeedsPaintPropertyUpdate()) {
if (context_.fragment_clip) {
+ const auto& clip_rect = ToSnappedClipRect(*context_.fragment_clip);
OnUpdateClip(properties_->UpdateFragmentClip(
*context_.current.clip,
- ClipPaintPropertyNode::State{context_.current.transform,
- ToClipRect(*context_.fragment_clip)}));
+ ClipPaintPropertyNode::State{context_.current.transform, clip_rect}));
} else {
OnClearClip(properties_->ClearFragmentClip());
}
@@ -1290,11 +1335,11 @@ void FragmentPaintPropertyTreeBuilder::UpdateCssClip() {
// object must be a container for absolute position descendants, and will
// copy from in-flow context later at updateOutOfFlowContext() step.
DCHECK(object_.CanContainAbsolutePositionObjects());
+ const auto& clip_rect = ToSnappedClipRect(
+ ToLayoutBox(object_).ClipRect(context_.current.paint_offset));
OnUpdateClip(properties_->UpdateCssClip(
*context_.current.clip,
- ClipPaintPropertyNode::State{context_.current.transform,
- ToClipRect(ToLayoutBox(object_).ClipRect(
- context_.current.paint_offset))}));
+ ClipPaintPropertyNode::State{context_.current.transform, clip_rect}));
} else {
OnClearClip(properties_->ClearCssClip());
}
@@ -1321,8 +1366,7 @@ void FragmentPaintPropertyTreeBuilder::UpdateClipPathClip(
} else {
ClipPaintPropertyNode::State state;
state.local_transform_space = context_.current.transform;
- state.clip_rect =
- FloatRoundedRect(FloatRect(*fragment_data_.ClipPathBoundingBox()));
+ state.clip_rect = FloatRoundedRect(*fragment_data_.ClipPathBoundingBox());
state.clip_path = fragment_data_.ClipPathPath();
OnUpdateClip(properties_->UpdateClipPathClip(*context_.current.clip,
std::move(state)));
@@ -1480,12 +1524,11 @@ void FragmentPaintPropertyTreeBuilder::UpdateOverflowControlsClip() {
if (NeedsOverflowControlsClip()) {
// Clip overflow controls to the border box rect. Not wrapped with
// OnUpdateClip() because this clip doesn't affect descendants.
+ const auto& clip_rect = ToSnappedClipRect(PhysicalRect(
+ context_.current.paint_offset, ToLayoutBox(object_).Size()));
properties_->UpdateOverflowControlsClip(
*context_.current.clip,
- ClipPaintPropertyNode::State{
- context_.current.transform,
- ToClipRect(PhysicalRect(context_.current.paint_offset,
- ToLayoutBox(object_).Size()))});
+ ClipPaintPropertyNode::State{context_.current.transform, clip_rect});
} else {
properties_->ClearOverflowControlsClip();
}
@@ -1517,6 +1560,18 @@ void FragmentPaintPropertyTreeBuilder::UpdateInnerBorderRadiusClip() {
context_.current.clip = border_radius_clip;
}
+static PhysicalRect OverflowClipRect(const LayoutBox& box,
+ const PhysicalOffset& offset) {
+ // TODO(pdr): We should ignore CSS overlay scrollbars for non-root scrollers
+ // but cannot due to compositing bugs (crbug.com/984167). This special-case is
+ // here instead of LayoutBox::OverflowClipRect because the layout size of the
+ // scrolling content is still affected by overlay scrollbar behavior, just not
+ // the clip.
+ auto behavior = box.IsLayoutView() ? kIgnorePlatformAndCSSOverlayScrollbarSize
+ : kIgnorePlatformOverlayScrollbarSize;
+ return box.OverflowClipRect(offset, behavior);
+}
+
static bool CanOmitOverflowClip(const LayoutObject& object) {
DCHECK(NeedsOverflowClip(object));
@@ -1540,7 +1595,7 @@ static bool CanOmitOverflowClip(const LayoutObject& object) {
// We need OverflowClip for hit-testing if the clip rect excluding overlay
// scrollbars is different from the normal clip rect.
- auto clip_rect = block->OverflowClipRect(PhysicalOffset());
+ auto clip_rect = OverflowClipRect(*block, PhysicalOffset());
auto clip_rect_excluding_overlay_scrollbars = block->OverflowClipRect(
PhysicalOffset(), kExcludeOverlayScrollbarSizeForHitTesting);
if (clip_rect != clip_rect_excluding_overlay_scrollbars)
@@ -1600,12 +1655,12 @@ void FragmentPaintPropertyTreeBuilder::UpdateOverflowClip() {
state.clip_rect.SetRect(adjusted_rect);
}
} else if (object_.IsBox()) {
- state.clip_rect = ToClipRect(ToLayoutBox(object_).OverflowClipRect(
- context_.current.paint_offset));
- state.clip_rect_excluding_overlay_scrollbars =
- ToClipRect(ToLayoutBox(object_).OverflowClipRect(
+ state.clip_rect = ToSnappedClipRect(OverflowClipRect(
+ ToLayoutBox(object_), context_.current.paint_offset));
+ state.clip_rect_excluding_overlay_scrollbars = FloatClipRect(
+ FloatRect(PixelSnappedIntRect(ToLayoutBox(object_).OverflowClipRect(
context_.current.paint_offset,
- kExcludeOverlayScrollbarSizeForHitTesting));
+ kExcludeOverlayScrollbarSizeForHitTesting))));
} else {
DCHECK(object_.IsSVGViewportContainer());
const auto& viewport_container = ToLayoutSVGViewportContainer(object_);
@@ -1716,6 +1771,8 @@ void FragmentPaintPropertyTreeBuilder::UpdateReplacedContentTransform() {
if (!content_to_parent_space.IsIdentity()) {
TransformPaintPropertyNode::State state{
TransformationMatrix(content_to_parent_space)};
+ state.flattens_inherited_transform =
+ context_.current.should_flatten_inherited_transform;
OnUpdate(properties_->UpdateReplacedContentTransform(
*context_.current.transform, std::move(state)));
} else {
@@ -1733,6 +1790,8 @@ void FragmentPaintPropertyTreeBuilder::UpdateReplacedContentTransform() {
// replaced object fit.
if (properties_->ReplacedContentTransform()) {
context_.current.transform = properties_->ReplacedContentTransform();
+ // TODO(pdr): SVG does not support 3D transforms so this should be
+ // should_flatten_inherited_transform = true.
context_.current.should_flatten_inherited_transform = false;
context_.current.rendering_context_id = 0;
}
@@ -1815,6 +1874,11 @@ void FragmentPaintPropertyTreeBuilder::UpdateScrollAndScrollTranslation() {
state.scrolls_outer_viewport = box.IsGlobalRootScroller();
+ // TODO(bokan): We probably don't need to pass ancestor reasons down the
+ // scroll tree. On the compositor, in
+ // LayerTreeHostImpl::FindScrollNodeForDeviceViewportPoint, we walk up
+ // the scroll tree looking at all the ancestor MainThreadScrollingReasons.
+ // https://crbug.com/985127.
auto ancestor_reasons =
context_.current.scroll->GetMainThreadScrollingReasons();
state.main_thread_scrolling_reasons =
@@ -1891,11 +1955,13 @@ void FragmentPaintPropertyTreeBuilder::UpdateScrollAndScrollTranslation() {
if (NeedsScrollOrScrollTranslation(
object_, full_context_.direct_compositing_reasons)) {
const auto& box = ToLayoutBox(object_);
+ DCHECK(box.GetScrollableArea());
+
// Bake ScrollOrigin into ScrollTranslation. See comments for
// ScrollTranslation in object_paint_properties.h for details.
- auto scroll_position = box.ScrollOrigin() + box.ScrolledContentOffset();
- TransformPaintPropertyNode::State state{
- -FloatSize(ToIntSize(scroll_position))};
+ FloatPoint scroll_position = FloatPoint(box.ScrollOrigin()) +
+ box.GetScrollableArea()->GetScrollOffset();
+ TransformPaintPropertyNode::State state{-ToFloatSize(scroll_position)};
state.flattens_inherited_transform =
context_.current.should_flatten_inherited_transform;
state.direct_compositing_reasons =
@@ -1955,14 +2021,17 @@ void FragmentPaintPropertyTreeBuilder::UpdateOutOfFlowContext() {
if (object_.IsLayoutView()) {
const auto* initial_fixed_transform = context_.fixed_position.transform;
- const auto* initial_fixed_scroll = context_.fixed_position.scroll;
context_.fixed_position = context_.current;
context_.fixed_position.fixed_position_children_fixed_to_root = true;
- // Fixed position transform and scroll nodes should not be affected.
+ // Fixed position transform should not be affected.
context_.fixed_position.transform = initial_fixed_transform;
- context_.fixed_position.scroll = initial_fixed_scroll;
+
+ // Scrolling in a fixed position element should chain up through the
+ // LayoutView.
+ if (properties_->Scroll())
+ context_.fixed_position.scroll = properties_->Scroll();
if (properties_->ScrollTranslation()) {
// Also undo the ScrollOrigin part in paint offset that was added when
// ScrollTranslation was updated.
@@ -2279,6 +2348,17 @@ void FragmentPaintPropertyTreeBuilder::UpdatePaintOffset() {
}
void FragmentPaintPropertyTreeBuilder::SetNeedsPaintPropertyUpdateIfNeeded() {
+ if (object_.HasLayer()) {
+ PaintLayer* layer = ToLayoutBoxModelObject(object_).Layer();
+ // With BGPT disabled, UpdateFilterReferenceBox gets called from
+ // CompositedLayerMapping::UpdateGraphicsLayerGeometry, but only
+ // for composited layers.
+ if (RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled() ||
+ layer->GetCompositingState() != kPaintsIntoOwnBacking) {
+ layer->UpdateFilterReferenceBox();
+ }
+ }
+
if (!object_.IsBox())
return;
@@ -3014,10 +3094,10 @@ void PaintPropertyTreeBuilder::CreateFragmentContextsInFlowThread(
old_fragment_clip = properties->FragmentClip();
const base::Optional<PhysicalRect>& new_fragment_clip =
new_fragment_contexts.back().fragment_clip;
- fragments_changed =
- !!old_fragment_clip != !!new_fragment_clip ||
- (old_fragment_clip && new_fragment_clip &&
- old_fragment_clip->ClipRect() != ToClipRect(*new_fragment_clip));
+ fragments_changed = !!old_fragment_clip != !!new_fragment_clip ||
+ (old_fragment_clip && new_fragment_clip &&
+ old_fragment_clip->ClipRect() !=
+ ToSnappedClipRect(*new_fragment_clip));
}
InitFragmentPaintProperties(
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_property_tree_builder.h b/chromium/third_party/blink/renderer/core/paint/paint_property_tree_builder.h
index 9b7c6d6604f..3e0e8747d3c 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_property_tree_builder.h
+++ b/chromium/third_party/blink/renderer/core/paint/paint_property_tree_builder.h
@@ -12,7 +12,7 @@
#include "third_party/blink/renderer/platform/graphics/paint/effect_paint_property_node.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/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 7d477eac10c..524cf4ee1b9 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
@@ -84,8 +84,8 @@ PaintPropertyTreeBuilderTest::PaintPropertiesForElement(const char* name) {
}
void PaintPropertyTreeBuilderTest::SetUp() {
- RenderingTest::SetUp();
EnableCompositing();
+ RenderingTest::SetUp();
}
#define CHECK_VISUAL_RECT(expected, source_object, ancestor, slop_factor) \
@@ -108,9 +108,9 @@ void PaintPropertyTreeBuilderTest::SetUp() {
inflated_expected.Inflate(LayoutUnit(slop_factor)); \
SCOPED_TRACE(String::Format( \
"Slow path rect: %s, Expected: %s, Inflated expected: %s", \
- slow_path_rect.ToString().Ascii().data(), \
- expected.ToString().Ascii().data(), \
- inflated_expected.ToString().Ascii().data())); \
+ slow_path_rect.ToString().Ascii().c_str(), \
+ expected.ToString().Ascii().c_str(), \
+ inflated_expected.ToString().Ascii().c_str())); \
EXPECT_TRUE( \
PhysicalRect(EnclosingIntRect(slow_path_rect)).Contains(expected)); \
EXPECT_TRUE(inflated_expected.Contains(slow_path_rect)); \
@@ -308,7 +308,7 @@ TEST_P(PaintPropertyTreeBuilderTest, OverflowScrollExcludeScrollbars) {
->VerticalScrollbar()
->IsOverlayScrollbar());
- EXPECT_EQ(FloatRoundedRect(10, 10, 93, 93),
+ EXPECT_EQ(FloatClipRect(FloatRect(10, 10, 93, 93)),
overflow_clip->ClipRectExcludingOverlayScrollbars());
}
@@ -336,10 +336,30 @@ TEST_P(PaintPropertyTreeBuilderTest, OverflowScrollExcludeScrollbarsSubpixel) {
->VerticalScrollbar()
->IsOverlayScrollbar());
- EXPECT_EQ(FloatRoundedRect(10, 10, 94, 93),
+ EXPECT_EQ(FloatClipRect(FloatRect(10, 10, 94, 93)),
overflow_clip->ClipRectExcludingOverlayScrollbars());
}
+TEST_P(PaintPropertyTreeBuilderTest, OverflowScrollExcludeCssOverlayScrollbar) {
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ ::-webkit-scrollbar { background-color: transparent; }
+ ::-webkit-scrollbar:vertical { width: 200px; }
+ ::-webkit-scrollbar-thumb { background: transparent; }
+ body {
+ margin: 0 30px 0 0;
+ background: lightgreen;
+ overflow-y: overlay;
+ overflow-x: hidden;
+ }
+ </style>
+ <div style="height: 5000px; width: 100%; background: lightblue;"></div>
+ )HTML");
+ // The document content should not be clipped by the overlay scrollbar because
+ // the scrollbar can be transparent and the content needs to paint below.
+ EXPECT_EQ(DocContentClip()->ClipRect(), FloatRoundedRect(0, 0, 800, 600));
+}
+
TEST_P(PaintPropertyTreeBuilderTest, OverflowScrollVerticalRL) {
SetBodyInnerHTML(R"HTML(
<style>::-webkit-scrollbar {width: 15px; height: 15px}</style>
@@ -3459,6 +3479,24 @@ TEST_P(PaintPropertyTreeBuilderTest, ReplacedSvgContentWithIsolation) {
svg_properties->ReplacedContentTransform());
}
+TEST_P(PaintPropertyTreeBuilderTest, ReplacedContentTransformFlattening) {
+ SetBodyInnerHTML(R"HTML(
+ <svg id="svg"
+ style="transform: perspective(100px) rotateY(0deg);"
+ width="100px"
+ height="200px"
+ viewBox="50 50 100 100">
+ </svg>
+ )HTML");
+
+ const auto* svg = ToLayoutBoxModelObject(GetLayoutObjectByElementId("svg"));
+ const auto* svg_properties = svg->FirstFragment().PaintProperties();
+
+ const auto* replaced_transform = svg_properties->ReplacedContentTransform();
+ EXPECT_TRUE(replaced_transform->FlattensInheritedTransform());
+ EXPECT_TRUE(replaced_transform->Parent()->FlattensInheritedTransform());
+}
+
TEST_P(PaintPropertyTreeBuilderTest, ContainPaintOrStyleLayoutTreeState) {
for (const char* containment : {"paint", "style layout"}) {
SCOPED_TRACE(containment);
@@ -3999,14 +4037,9 @@ TEST_P(PaintPropertyTreeBuilderTest, PositionedScrollerIsNotNested) {
auto* fixed_scroll_translation =
fixed_overflow_scroll_properties->ScrollTranslation();
auto* fixed_overflow_scroll_node = fixed_scroll_translation->ScrollNode();
- // The fixed position overflow scroll node is parented under the root, not the
- // dom-order parent or frame's scroll.
- EXPECT_EQ(GetDocument()
- .GetPage()
- ->GetVisualViewport()
- .GetScrollTranslationNode()
- ->ScrollNode(),
- fixed_overflow_scroll_node->Parent());
+ // The fixed position overflow scroll node is parented under the frame, not
+ // the dom-order parent.
+ EXPECT_EQ(DocScroll(), fixed_overflow_scroll_node->Parent());
EXPECT_EQ(FloatSize(0, -43), fixed_scroll_translation->Translation2D());
EXPECT_EQ(IntRect(0, 0, 13, 11), fixed_overflow_scroll_node->ContainerRect());
EXPECT_EQ(IntSize(13, 4000), fixed_overflow_scroll_node->ContentsSize());
@@ -4263,19 +4296,10 @@ TEST_P(PaintPropertyTreeBuilderTest,
ASSERT_TRUE(multicol_container->FirstFragment().NextFragment());
ASSERT_FALSE(
multicol_container->FirstFragment().NextFragment()->NextFragment());
- if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) {
- EXPECT_EQ(PhysicalOffset(8, 8),
- multicol_container->FirstFragment().PaintOffset());
- EXPECT_EQ(
- PhysicalOffset(59, -12),
- multicol_container->FirstFragment().NextFragment()->PaintOffset());
- } else {
- EXPECT_EQ(PhysicalOffset(),
- multicol_container->FirstFragment().PaintOffset());
- EXPECT_EQ(
- PhysicalOffset(51, -20),
- multicol_container->FirstFragment().NextFragment()->PaintOffset());
- }
+ EXPECT_EQ(PhysicalOffset(),
+ multicol_container->FirstFragment().PaintOffset());
+ EXPECT_EQ(PhysicalOffset(51, -20),
+ multicol_container->FirstFragment().NextFragment()->PaintOffset());
GetDocument().View()->LayoutViewport()->ScrollBy(ScrollOffset(0, 25),
kUserScroll);
@@ -4284,15 +4308,10 @@ TEST_P(PaintPropertyTreeBuilderTest,
ASSERT_TRUE(multicol_container->FirstFragment().NextFragment());
ASSERT_FALSE(
multicol_container->FirstFragment().NextFragment()->NextFragment());
-
- if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) {
- EXPECT_EQ(PhysicalOffset(8, 8),
- multicol_container->FirstFragment().PaintOffset());
- EXPECT_EQ(
- PhysicalOffset(59, -12),
- multicol_container->FirstFragment().NextFragment()->PaintOffset());
- } else {
- }
+ EXPECT_EQ(PhysicalOffset(),
+ multicol_container->FirstFragment().PaintOffset());
+ EXPECT_EQ(PhysicalOffset(51, -20),
+ multicol_container->FirstFragment().NextFragment()->PaintOffset());
}
TEST_P(PaintPropertyTreeBuilderTest, FragmentsUnderMultiColumn) {
@@ -4842,7 +4861,7 @@ TEST_P(PaintPropertyTreeBuilderTest, ChangePositionUpdateDescendantProperties) {
EXPECT_EQ(ancestor->FirstFragment().PaintProperties()->OverflowClip(),
&descendant->FirstFragment().LocalBorderBoxProperties().Clip());
- ToElement(ancestor->GetNode())
+ To<Element>(ancestor->GetNode())
->setAttribute(html_names::kStyleAttr, "position: static");
UpdateAllLifecyclePhasesForTest();
EXPECT_NE(ancestor->FirstFragment().PaintProperties()->OverflowClip(),
@@ -5360,7 +5379,7 @@ TEST_P(PaintPropertyTreeBuilderTest, BackfaceHidden) {
EXPECT_EQ(nullptr, transform);
}
- ToElement(target->GetNode())->setAttribute(html_names::kStyleAttr, "");
+ To<Element>(target->GetNode())->setAttribute(html_names::kStyleAttr, "");
UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(PhysicalOffset(60, 50), target->FirstFragment().PaintOffset());
EXPECT_EQ(nullptr, target->FirstFragment().PaintProperties());
@@ -6272,6 +6291,26 @@ TEST_P(PaintPropertyTreeBuilderTest, StickyConstraintChain) {
->nearest_element_shifting_containing_block);
}
+TEST_P(PaintPropertyTreeBuilderTest, RoundedStickyConstraints) {
+ // This test verifies that sticky constraint rects are rounded to the nearest
+ // integer.
+ SetBodyInnerHTML(R"HTML(
+ <div id="scroller" style="overflow:scroll; width:300px; height:199.5px;">
+ <div id="outer" style="position:sticky; top:10px; height:300px">
+ </div>
+ <div style="height:1000px;"></div>
+ </div>
+ )HTML");
+ GetDocument().getElementById("scroller")->setScrollTop(50);
+ UpdateAllLifecyclePhasesForTest();
+
+ const auto* outer_properties = PaintPropertiesForElement("outer");
+ ASSERT_TRUE(outer_properties && outer_properties->StickyTranslation());
+ EXPECT_EQ(gfx::Rect(0, 0, 300, 200), outer_properties->StickyTranslation()
+ ->GetStickyConstraint()
+ ->constraint_box_rect);
+}
+
TEST_P(PaintPropertyTreeBuilderTest, NonScrollableSticky) {
// This test verifies the property tree builder applies sticky offset
// correctly when the clipping container cannot be scrolled, and
@@ -6527,7 +6566,7 @@ TEST_P(PaintPropertyTreeBuilderTest, SimpleOpacityChangeDoesNotCausePacUpdate) {
properties->Effect()->GetCompositorElementId());
ASSERT_TRUE(cc_effect);
EXPECT_FLOAT_EQ(cc_effect->opacity, 0.5f);
- EXPECT_FALSE(cc_effect->effect_changed);
+ EXPECT_TRUE(cc_effect->effect_changed);
EXPECT_FALSE(GetChromeClient()
.layer_tree_host()
->property_trees()
@@ -6836,4 +6875,49 @@ TEST_P(PaintPropertyTreeBuilderTest, IsAffectedByOuterViewportBoundsDelta) {
false);
}
+TEST_P(PaintPropertyTreeBuilderTest, TransformAnimationAxisAlignment) {
+ if (!RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled())
+ return;
+ SetBodyInnerHTML(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ @keyframes transform_translation {
+ 0% { transform: translate(10px, 11px); }
+ 100% { transform: translate(20px, 21px); }
+ }
+ #translation_animation {
+ animation-name: transform_translation;
+ animation-duration: 1s;
+ width: 100px;
+ height: 100px;
+ will-change: transform;
+ }
+ @keyframes transform_rotation {
+ 0% { transform: rotateZ(10deg); }
+ 100% { transform: rotateZ(20deg); }
+ }
+ #rotation_animation {
+ animation-name: transform_rotation;
+ animation-duration: 1s;
+ width: 100px;
+ height: 100px;
+ will-change: transform;
+ }
+ </style>
+ <div id="translation_animation"></div>
+ <div id="rotation_animation"></div>
+ )HTML");
+ UpdateAllLifecyclePhasesForTest();
+
+ const auto* translation =
+ PaintPropertiesForElement("translation_animation")->Transform();
+ EXPECT_TRUE(translation->HasActiveTransformAnimation());
+ EXPECT_TRUE(translation->TransformAnimationIsAxisAligned());
+
+ const auto* rotation =
+ PaintPropertiesForElement("rotation_animation")->Transform();
+ EXPECT_TRUE(rotation->HasActiveTransformAnimation());
+ EXPECT_FALSE(rotation->TransformAnimationIsAxisAligned());
+}
+
} // namespace blink
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 6b0ee864223..057f90eb7a5 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
@@ -229,22 +229,21 @@ CORE_EXPORT void showAllPropertyTrees(const blink::LocalFrameView& rootFrame) {
void showTransformPropertyTree(const blink::LocalFrameView& rootFrame) {
LOG(ERROR) << "Transform tree:\n"
- << transformPropertyTreeAsString(rootFrame).Utf8().data();
+ << transformPropertyTreeAsString(rootFrame).Utf8();
}
void showClipPropertyTree(const blink::LocalFrameView& rootFrame) {
- LOG(ERROR) << "Clip tree:\n"
- << clipPropertyTreeAsString(rootFrame).Utf8().data();
+ LOG(ERROR) << "Clip tree:\n" << clipPropertyTreeAsString(rootFrame).Utf8();
}
void showEffectPropertyTree(const blink::LocalFrameView& rootFrame) {
LOG(ERROR) << "Effect tree:\n"
- << effectPropertyTreeAsString(rootFrame).Utf8().data();
+ << effectPropertyTreeAsString(rootFrame).Utf8();
}
void showScrollPropertyTree(const blink::LocalFrameView& rootFrame) {
LOG(ERROR) << "Scroll tree:\n"
- << scrollPropertyTreeAsString(rootFrame).Utf8().data();
+ << scrollPropertyTreeAsString(rootFrame).Utf8();
}
String transformPropertyTreeAsString(const blink::LocalFrameView& rootFrame) {
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 6eda8647c7f..9b0744e0da9 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
@@ -22,8 +22,8 @@ class PaintPropertyTreePrinterTest : public PaintControllerPaintTest {
private:
void SetUp() override {
- RenderingTest::SetUp();
EnableCompositing();
+ RenderingTest::SetUp();
}
};
@@ -33,7 +33,7 @@ TEST_P(PaintPropertyTreePrinterTest, SimpleTransformTree) {
SetBodyInnerHTML("hello world");
String transform_tree_as_string =
transformPropertyTreeAsString(*GetDocument().View());
- EXPECT_THAT(transform_tree_as_string.Ascii().data(),
+ EXPECT_THAT(transform_tree_as_string.Ascii(),
testing::MatchesRegex("root .*"
" .*Translation \\(.*\\) .*"));
}
@@ -41,7 +41,7 @@ TEST_P(PaintPropertyTreePrinterTest, SimpleTransformTree) {
TEST_P(PaintPropertyTreePrinterTest, SimpleClipTree) {
SetBodyInnerHTML("hello world");
String clip_tree_as_string = clipPropertyTreeAsString(*GetDocument().View());
- EXPECT_THAT(clip_tree_as_string.Ascii().data(),
+ EXPECT_THAT(clip_tree_as_string.Ascii().c_str(),
testing::MatchesRegex("root .*"
" .*Clip \\(.*\\) .*"));
}
@@ -51,7 +51,7 @@ TEST_P(PaintPropertyTreePrinterTest, SimpleEffectTree) {
String effect_tree_as_string =
effectPropertyTreeAsString(*GetDocument().View());
EXPECT_THAT(
- effect_tree_as_string.Ascii().data(),
+ effect_tree_as_string.Ascii().c_str(),
testing::MatchesRegex("root .*"
" Effect \\(LayoutN?G?BlockFlow DIV\\) .*"));
}
@@ -60,7 +60,7 @@ TEST_P(PaintPropertyTreePrinterTest, SimpleScrollTree) {
SetBodyInnerHTML("<div style='height: 4000px;'>hello world</div>");
String scroll_tree_as_string =
scrollPropertyTreeAsString(*GetDocument().View());
- EXPECT_THAT(scroll_tree_as_string.Ascii().data(),
+ EXPECT_THAT(scroll_tree_as_string.Ascii().c_str(),
testing::MatchesRegex("root .*"
" Scroll \\(.*\\) .*"));
}
@@ -75,7 +75,7 @@ TEST_P(PaintPropertyTreePrinterTest, SimpleTransformTreePath) {
transformed_object->FirstFragment().PaintProperties();
String transform_path_as_string =
transformed_object_properties->Transform()->ToTreeString();
- EXPECT_THAT(transform_path_as_string.Ascii().data(),
+ EXPECT_THAT(transform_path_as_string.Ascii().c_str(),
testing::MatchesRegex("root .*\"scroll\".*"
" .*\"parent\".*"
" .*\"translation2d\".*"
@@ -92,7 +92,7 @@ TEST_P(PaintPropertyTreePrinterTest, SimpleClipTreePath) {
clipped_object->FirstFragment().PaintProperties();
String clip_path_as_string =
clipped_object_properties->CssClip()->ToTreeString();
- EXPECT_THAT(clip_path_as_string.Ascii().data(),
+ EXPECT_THAT(clip_path_as_string.Ascii().c_str(),
testing::MatchesRegex("root .*\"rect\".*"
" .*\"rect\".*"
" .*\"rect\".*"));
@@ -106,7 +106,7 @@ TEST_P(PaintPropertyTreePrinterTest, SimpleEffectTreePath) {
effect_object->FirstFragment().PaintProperties();
String effect_path_as_string =
effect_object_properties->Effect()->ToTreeString();
- EXPECT_THAT(effect_path_as_string.Ascii().data(),
+ EXPECT_THAT(effect_path_as_string.Ascii().c_str(),
testing::MatchesRegex("root .*\"outputClip\".*"
" .*\"parent\".*\"opacity\".*"));
}
@@ -124,7 +124,7 @@ TEST_P(PaintPropertyTreePrinterTest, SimpleScrollTreePath) {
String scroll_path_as_string = scroll_object_properties->ScrollTranslation()
->ScrollNode()
->ToTreeString();
- EXPECT_THAT(scroll_path_as_string.Ascii().data(),
+ EXPECT_THAT(scroll_path_as_string.Ascii().c_str(),
testing::MatchesRegex("root .* \\{\\}.*"
" .*\"parent\".*"));
}
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 87ea6a3db73..69725ba5a28 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
@@ -270,8 +270,6 @@ TEST_P(PaintPropertyTreeUpdateTest,
)HTML");
Element* overflow_a = GetDocument().getElementById("overflowA");
Element* overflow_b = GetDocument().getElementById("overflowB");
- VisualViewport& visual_viewport =
- GetDocument().GetPage()->GetVisualViewport();
// This should be false. We are not as strict about main thread scrolling
// reasons as we could be.
@@ -281,18 +279,21 @@ TEST_P(PaintPropertyTreeUpdateTest,
->ScrollTranslation()
->ScrollNode()
->HasBackgroundAttachmentFixedDescendants());
- EXPECT_FALSE(overflow_b->GetLayoutObject()
- ->FirstFragment()
- .PaintProperties()
- ->ScrollTranslation()
- ->ScrollNode()
- ->HasBackgroundAttachmentFixedDescendants());
- EXPECT_EQ(visual_viewport.GetScrollNode(), overflow_b->GetLayoutObject()
- ->FirstFragment()
- .PaintProperties()
- ->ScrollTranslation()
- ->ScrollNode()
- ->Parent());
+ // This could be false since it's fixed with respect to the layout viewport.
+ // However, it would be simpler to avoid the main thread by doing this check
+ // on the compositor thread. https://crbug.com/985127.
+ EXPECT_TRUE(overflow_b->GetLayoutObject()
+ ->FirstFragment()
+ .PaintProperties()
+ ->ScrollTranslation()
+ ->ScrollNode()
+ ->HasBackgroundAttachmentFixedDescendants());
+ EXPECT_EQ(DocScroll(), overflow_b->GetLayoutObject()
+ ->FirstFragment()
+ .PaintProperties()
+ ->ScrollTranslation()
+ ->ScrollNode()
+ ->Parent());
// Removing a main thread scrolling reason should update the entire tree.
overflow_b->removeAttribute("class");
@@ -835,6 +836,61 @@ TEST_P(PaintPropertyTreeUpdateTest,
EXPECT_EQ(IntSize(800, 600), visual_viewport.GetScrollNode()->ContentsSize());
}
+TEST_P(PaintPropertyTreeUpdateTest, ViewportAddRemoveDeviceEmulationNode) {
+ SetBodyInnerHTML(
+ "<style>body {height: 10000px; width: 10000px; margin: 0;}</style>");
+
+ auto& visual_viewport = GetDocument().GetPage()->GetVisualViewport();
+ EXPECT_FALSE(visual_viewport.GetDeviceEmulationTransformNode());
+ // The LayoutView (instead of VisualViewport) creates scrollbars because
+ // viewport is disabled.
+ ASSERT_FALSE(GetDocument().GetPage()->GetSettings().GetViewportEnabled());
+ EXPECT_FALSE(visual_viewport.LayerForHorizontalScrollbar());
+ EXPECT_FALSE(visual_viewport.LayerForVerticalScrollbar());
+ ASSERT_TRUE(GetLayoutView().GetScrollableArea());
+ auto* scrollbar_layer =
+ GetLayoutView().GetScrollableArea()->LayerForHorizontalScrollbar();
+ if (!RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) {
+ ASSERT_TRUE(scrollbar_layer);
+ EXPECT_EQ(&TransformPaintPropertyNode::Root(),
+ &scrollbar_layer->GetPropertyTreeState().Transform());
+ } else {
+ // TODO(wangxianzhu): Test for CompositeAfterPaint.
+ EXPECT_FALSE(scrollbar_layer);
+ }
+
+ // These emulate WebViewImpl::SetDeviceEmulationTransform().
+ GetChromeClient().SetDeviceEmulationTransform(
+ TransformationMatrix().Scale(2));
+ visual_viewport.SetNeedsPaintPropertyUpdate();
+
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_TRUE(visual_viewport.GetDeviceEmulationTransformNode());
+ if (!RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) {
+ ASSERT_TRUE(scrollbar_layer);
+ EXPECT_EQ(visual_viewport.GetDeviceEmulationTransformNode(),
+ &scrollbar_layer->GetPropertyTreeState().Transform());
+ } else {
+ // TODO(wangxianzhu): Test for CompositeAfterPaint.
+ EXPECT_FALSE(scrollbar_layer);
+ }
+
+ // These emulate WebViewImpl::SetDeviceEmulationTransform().
+ GetChromeClient().SetDeviceEmulationTransform(TransformationMatrix());
+ visual_viewport.SetNeedsPaintPropertyUpdate();
+
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_FALSE(visual_viewport.GetDeviceEmulationTransformNode());
+ if (!RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) {
+ ASSERT_TRUE(scrollbar_layer);
+ EXPECT_EQ(&TransformPaintPropertyNode::Root(),
+ &scrollbar_layer->GetPropertyTreeState().Transform());
+ } else {
+ // TODO(wangxianzhu): Test for CompositeAfterPaint.
+ EXPECT_FALSE(scrollbar_layer);
+ }
+}
+
TEST_P(PaintPropertyTreeUpdateTest, ScrollbarWidthChange) {
SetBodyInnerHTML(R"HTML(
<style>::-webkit-scrollbar {width: 20px; height: 20px}</style>
@@ -1068,14 +1124,14 @@ TEST_P(PaintPropertyTreeUpdateTest, WillTransformChangeAboveFixed) {
EXPECT_EQ(container->FirstFragment().PaintProperties()->Transform(),
&fixed->FirstFragment().LocalBorderBoxProperties().Transform());
- ToElement(container->GetNode())
+ To<Element>(container->GetNode())
->setAttribute(html_names::kStyleAttr, "will-change: top");
UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(
&GetLayoutView().FirstFragment().LocalBorderBoxProperties().Transform(),
&fixed->FirstFragment().LocalBorderBoxProperties().Transform());
- ToElement(container->GetNode())
+ To<Element>(container->GetNode())
->setAttribute(html_names::kStyleAttr, "will-change: transform");
UpdateAllLifecyclePhasesForTest();
EXPECT_EQ(container->FirstFragment().PaintProperties()->Transform(),
@@ -1621,7 +1677,23 @@ TEST_P(PaintPropertyTreeUpdateTest, ChangeDuringAnimation) {
!RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled())
return;
- SetBodyInnerHTML("<div id='target' style='width: 100px; height: 100px'>");
+ SetBodyInnerHTML(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ @keyframes animation {
+ 0% { opacity: 0.3; }
+ 100% { opacity: 0.4; }
+ }
+ #target {
+ animation-name: animation;
+ animation-duration: 1s;
+ width: 100px;
+ height: 100px;
+ }
+ </style>
+ <div id='target'></div>
+ )HTML");
+
auto* target = GetLayoutObjectByElementId("target");
auto style = ComputedStyle::Clone(target->StyleRef());
GetDocument().Lifecycle().AdvanceTo(DocumentLifecycle::kInStyleRecalc);
@@ -1701,4 +1773,49 @@ TEST_P(PaintPropertyTreeUpdateTest, BackfaceVisibilityInvalidatesProperties) {
EXPECT_TRUE(span->GetLayoutObject()->NeedsPaintPropertyUpdate());
}
+TEST_P(PaintPropertyTreeUpdateTest, FixedPositionCompositing) {
+ SetBodyInnerHTML(R"HTML(
+ <div id="space" style="height: 200px"></div>
+ <div id="fixed" style="position: fixed; top: 50px; left: 60px">Fixed</div>
+ )HTML");
+
+ EXPECT_FALSE(PaintPropertiesForElement("fixed"));
+
+ auto* space = GetDocument().getElementById("space");
+ space->setAttribute(html_names::kStyleAttr, "height: 2000px");
+ UpdateAllLifecyclePhasesForTest();
+ auto* properties = PaintPropertiesForElement("fixed");
+ ASSERT_TRUE(properties);
+ auto* paint_offset_translation = properties->PaintOffsetTranslation();
+ ASSERT_TRUE(paint_offset_translation);
+ EXPECT_EQ(FloatSize(60, 50), paint_offset_translation->Translation2D());
+ EXPECT_TRUE(paint_offset_translation->HasDirectCompositingReasons());
+ EXPECT_FALSE(properties->Transform());
+
+ space->setAttribute(html_names::kStyleAttr, "height: 100px");
+ UpdateAllLifecyclePhasesForTest();
+ EXPECT_FALSE(PaintPropertiesForElement("fixed"));
+}
+
+TEST_P(PaintPropertyTreeUpdateTest, InlineFilterReferenceBoxChange) {
+ SetBodyInnerHTML(R"HTML(
+ <div id="spacer" style="display: inline-block; height: 20px"></div>
+ <br>
+ <span id="span" style="filter: blur(1px); font-size: 20px">SPAN</span>
+ )HTML");
+
+ const auto* properties = PaintPropertiesForElement("span");
+ ASSERT_TRUE(properties);
+ ASSERT_TRUE(properties->Filter());
+ EXPECT_EQ(FloatPoint(0, 20),
+ properties->Filter()->Filter().ReferenceBox().Location());
+
+ GetDocument().getElementById("spacer")->setAttribute(
+ html_names::kStyleAttr, "display: inline-block; height: 100px");
+ UpdateAllLifecyclePhasesForTest();
+ ASSERT_EQ(properties, PaintPropertiesForElement("span"));
+ EXPECT_EQ(FloatPoint(0, 100),
+ properties->Filter()->Filter().ReferenceBox().Location());
+}
+
} // 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 1b5e445b042..ce45f3ede9a 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_timing.cc
+++ b/chromium/third_party/blink/renderer/core/paint/paint_timing.cc
@@ -7,6 +7,7 @@
#include <memory>
#include <utility>
+#include "base/time/default_tick_clock.h"
#include "third_party/blink/public/platform/web_layer_tree_view.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
@@ -20,10 +21,10 @@
#include "third_party/blink/renderer/core/probe/core_probes.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/cross_thread_functional.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/scheduler/public/frame_scheduler.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/wtf/wtf.h"
namespace blink {
@@ -59,7 +60,7 @@ void PaintTiming::MarkFirstPaint() {
// markFirstPaint().
if (!first_paint_.is_null())
return;
- SetFirstPaint(CurrentTimeTicks());
+ SetFirstPaint(clock_->NowTicks());
}
void PaintTiming::MarkFirstContentfulPaint() {
@@ -69,18 +70,18 @@ void PaintTiming::MarkFirstContentfulPaint() {
// markFirstContentfulPaint().
if (!first_contentful_paint_.is_null())
return;
- SetFirstContentfulPaint(CurrentTimeTicks());
+ SetFirstContentfulPaint(clock_->NowTicks());
}
void PaintTiming::MarkFirstImagePaint() {
if (!first_image_paint_.is_null())
return;
- first_image_paint_ = CurrentTimeTicks();
+ first_image_paint_ = clock_->NowTicks();
SetFirstContentfulPaint(first_image_paint_);
RegisterNotifySwapTime(PaintEvent::kFirstImagePaint);
}
-void PaintTiming::SetFirstMeaningfulPaintCandidate(TimeTicks timestamp) {
+void PaintTiming::SetFirstMeaningfulPaintCandidate(base::TimeTicks timestamp) {
if (!first_meaningful_paint_candidate_.is_null())
return;
first_meaningful_paint_candidate_ = timestamp;
@@ -90,7 +91,7 @@ void PaintTiming::SetFirstMeaningfulPaintCandidate(TimeTicks timestamp) {
}
void PaintTiming::SetFirstMeaningfulPaint(
- TimeTicks swap_stamp,
+ base::TimeTicks swap_stamp,
FirstMeaningfulPaintDetector::HadUserInput had_input) {
DCHECK(first_meaningful_paint_swap_.is_null());
DCHECK(!swap_stamp.is_null());
@@ -111,19 +112,6 @@ void PaintTiming::SetFirstMeaningfulPaint(
first_meaningful_paint_swap_ = swap_stamp;
NotifyPaintTimingChanged();
}
-
- ReportUserInputHistogram(had_input);
-}
-
-void PaintTiming::ReportUserInputHistogram(
- FirstMeaningfulPaintDetector::HadUserInput had_input) {
- DEFINE_STATIC_LOCAL(EnumerationHistogram, had_user_input_histogram,
- ("PageLoad.Internal.PaintTiming."
- "HadUserInputBeforeFirstMeaningfulPaint",
- FirstMeaningfulPaintDetector::kHadUserInputEnumMax));
-
- if (GetFrame() && GetFrame()->IsMainFrame())
- had_user_input_histogram.Count(had_input);
}
void PaintTiming::NotifyPaint(bool is_first_paint,
@@ -138,6 +126,10 @@ void PaintTiming::NotifyPaint(bool is_first_paint,
fmp_detector_->NotifyPaint();
}
+void PaintTiming::SetTickClockForTesting(const base::TickClock* clock) {
+ clock_ = clock;
+}
+
void PaintTiming::Trace(blink::Visitor* visitor) {
visitor->Trace(fmp_detector_);
Supplement<Document>::Trace(visitor);
@@ -145,7 +137,8 @@ void PaintTiming::Trace(blink::Visitor* visitor) {
PaintTiming::PaintTiming(Document& document)
: Supplement<Document>(document),
- fmp_detector_(MakeGarbageCollected<FirstMeaningfulPaintDetector>(this)) {}
+ fmp_detector_(MakeGarbageCollected<FirstMeaningfulPaintDetector>(this)),
+ clock_(base::DefaultTickClock::GetInstance()) {}
LocalFrame* PaintTiming::GetFrame() const {
return GetSupplementable()->GetFrame();
@@ -156,14 +149,14 @@ void PaintTiming::NotifyPaintTimingChanged() {
GetSupplementable()->Loader()->DidChangePerformanceTiming();
}
-void PaintTiming::SetFirstPaint(TimeTicks stamp) {
+void PaintTiming::SetFirstPaint(base::TimeTicks stamp) {
if (!first_paint_.is_null())
return;
first_paint_ = stamp;
RegisterNotifySwapTime(PaintEvent::kFirstPaint);
}
-void PaintTiming::SetFirstContentfulPaint(TimeTicks stamp) {
+void PaintTiming::SetFirstContentfulPaint(base::TimeTicks stamp) {
if (!first_contentful_paint_.is_null())
return;
SetFirstPaint(stamp);
@@ -171,10 +164,10 @@ void PaintTiming::SetFirstContentfulPaint(TimeTicks stamp) {
RegisterNotifySwapTime(PaintEvent::kFirstContentfulPaint);
// Restart commits that may have been deferred.
- if (!GetFrame() || !GetFrame()->GetPage())
+ if (!GetFrame() || !GetFrame()->IsMainFrame())
return;
GetFrame()->GetPage()->GetChromeClient().StopDeferringCommits(
- cc::PaintHoldingCommitTrigger::kFirstContentfulPaint);
+ *GetFrame(), cc::PaintHoldingCommitTrigger::kFirstContentfulPaint);
}
void PaintTiming::RegisterNotifySwapTime(PaintEvent event) {
@@ -226,7 +219,7 @@ void PaintTiming::ReportSwapTime(PaintEvent event,
}
}
-void PaintTiming::SetFirstPaintSwap(TimeTicks stamp) {
+void PaintTiming::SetFirstPaintSwap(base::TimeTicks stamp) {
DCHECK(first_paint_swap_.is_null());
first_paint_swap_ = stamp;
probe::PaintTiming(GetSupplementable(), "firstPaint",
@@ -237,7 +230,7 @@ void PaintTiming::SetFirstPaintSwap(TimeTicks stamp) {
NotifyPaintTimingChanged();
}
-void PaintTiming::SetFirstContentfulPaintSwap(TimeTicks stamp) {
+void PaintTiming::SetFirstContentfulPaintSwap(base::TimeTicks stamp) {
DCHECK(first_contentful_paint_swap_.is_null());
TRACE_EVENT_INSTANT_WITH_TIMESTAMP0("loading", "FirstContentfulPaint",
TRACE_EVENT_SCOPE_GLOBAL, stamp);
@@ -253,7 +246,7 @@ void PaintTiming::SetFirstContentfulPaintSwap(TimeTicks stamp) {
fmp_detector_->NotifyFirstContentfulPaint(first_contentful_paint_swap_);
}
-void PaintTiming::SetFirstImagePaintSwap(TimeTicks stamp) {
+void PaintTiming::SetFirstImagePaintSwap(base::TimeTicks stamp) {
DCHECK(first_image_paint_swap_.is_null());
first_image_paint_swap_ = stamp;
probe::PaintTiming(GetSupplementable(), "firstImagePaint",
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 3279e1795e2..b901928e476 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_timing.h
+++ b/chromium/third_party/blink/renderer/core/paint/paint_timing.h
@@ -17,6 +17,10 @@
#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
+namespace base {
+class TickClock;
+}
+
namespace blink {
class LocalFrame;
@@ -54,9 +58,9 @@ class CORE_EXPORT PaintTiming final
// contentful paint hasn't been recorded yet.
void MarkFirstImagePaint();
- void SetFirstMeaningfulPaintCandidate(TimeTicks timestamp);
+ void SetFirstMeaningfulPaintCandidate(base::TimeTicks timestamp);
void SetFirstMeaningfulPaint(
- TimeTicks swap_stamp,
+ base::TimeTicks swap_stamp,
FirstMeaningfulPaintDetector::HadUserInput had_input);
void NotifyPaint(bool is_first_paint, bool text_painted, bool image_painted);
@@ -66,21 +70,21 @@ class CORE_EXPORT PaintTiming final
// FirstPaint returns the first time that anything was painted for the
// current document.
- TimeTicks FirstPaint() const { return first_paint_swap_; }
+ base::TimeTicks FirstPaint() const { return first_paint_swap_; }
// FirstContentfulPaint returns the first time that 'contentful' content was
// painted. For instance, the first time that text or image content was
// painted.
- TimeTicks FirstContentfulPaint() const {
+ base::TimeTicks FirstContentfulPaint() const {
return first_contentful_paint_swap_;
}
// FirstImagePaint returns the first time that image content was painted.
- TimeTicks FirstImagePaint() const { return first_image_paint_swap_; }
+ base::TimeTicks FirstImagePaint() const { return first_image_paint_swap_; }
// FirstMeaningfulPaint returns the first time that page's primary content
// was painted.
- TimeTicks FirstMeaningfulPaint() const {
+ base::TimeTicks FirstMeaningfulPaint() const {
return first_meaningful_paint_swap_;
}
@@ -88,7 +92,7 @@ class CORE_EXPORT PaintTiming final
// paint to qualify as the potentially first meaningful paint. Unlike
// firstMeaningfulPaint, this signal is available in real time, but it may be
// an optimistic (i.e., too early) estimate.
- TimeTicks FirstMeaningfulPaintCandidate() const {
+ base::TimeTicks FirstMeaningfulPaintCandidate() const {
return first_meaningful_paint_candidate_;
}
@@ -103,6 +107,9 @@ class CORE_EXPORT PaintTiming final
void ReportSwapResultHistogram(WebWidgetClient::SwapResult);
+ // The caller owns the |clock| which must outlive the PaintTiming.
+ void SetTickClockForTesting(const base::TickClock* clock);
+
void Trace(blink::Visitor*) override;
private:
@@ -115,45 +122,45 @@ class CORE_EXPORT PaintTiming final
// or Set*() methods to make sure that first paint is marked as part of
// marking first contentful paint, or that first contentful paint is marked as
// part of marking first text/image paint, for example.
- void SetFirstPaint(TimeTicks stamp);
+ void SetFirstPaint(base::TimeTicks stamp);
// setFirstContentfulPaint will also set first paint time if first paint
// time has not yet been recorded.
- void SetFirstContentfulPaint(TimeTicks stamp);
+ void SetFirstContentfulPaint(base::TimeTicks stamp);
// Set*Swap() are called when the SwapPromise is fulfilled and the swap
// timestamp is available. These methods will record trace events, update Web
// Perf API (FP and FCP only), and notify that paint timing has changed, which
// triggers UMAs and UKMS.
// |stamp| is the swap timestamp used for tracing, UMA, UKM, and Web Perf API.
- void SetFirstPaintSwap(TimeTicks stamp);
- void SetFirstContentfulPaintSwap(TimeTicks stamp);
- void SetFirstImagePaintSwap(TimeTicks stamp);
+ void SetFirstPaintSwap(base::TimeTicks stamp);
+ void SetFirstContentfulPaintSwap(base::TimeTicks stamp);
+ void SetFirstImagePaintSwap(base::TimeTicks stamp);
void RegisterNotifySwapTime(PaintEvent);
- void ReportUserInputHistogram(
- FirstMeaningfulPaintDetector::HadUserInput had_input);
- TimeTicks FirstPaintRendered() const { return first_paint_; }
+ base::TimeTicks FirstPaintRendered() const { return first_paint_; }
- TimeTicks FirstContentfulPaintRendered() const {
+ base::TimeTicks FirstContentfulPaintRendered() const {
return first_contentful_paint_;
}
// TODO(crbug/738235): Non first_*_swap_ variables are only being tracked to
// compute deltas for reporting histograms and should be removed once we
// confirm the deltas and discrepancies look reasonable.
- TimeTicks first_paint_;
- TimeTicks first_paint_swap_;
- TimeTicks first_image_paint_;
- TimeTicks first_image_paint_swap_;
- TimeTicks first_contentful_paint_;
- TimeTicks first_contentful_paint_swap_;
- TimeTicks first_meaningful_paint_swap_;
- TimeTicks first_meaningful_paint_candidate_;
+ base::TimeTicks first_paint_;
+ base::TimeTicks first_paint_swap_;
+ base::TimeTicks first_image_paint_;
+ base::TimeTicks first_image_paint_swap_;
+ base::TimeTicks first_contentful_paint_;
+ base::TimeTicks first_contentful_paint_swap_;
+ base::TimeTicks first_meaningful_paint_swap_;
+ base::TimeTicks first_meaningful_paint_candidate_;
Member<FirstMeaningfulPaintDetector> fmp_detector_;
+ const base::TickClock* clock_;
+
FRIEND_TEST_ALL_PREFIXES(FirstMeaningfulPaintDetectorTest, NoFirstPaint);
FRIEND_TEST_ALL_PREFIXES(FirstMeaningfulPaintDetectorTest, OneLayout);
FRIEND_TEST_ALL_PREFIXES(FirstMeaningfulPaintDetectorTest,
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
index 469d3fe2581..3a369e59a11 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_timing_detector.cc
+++ b/chromium/third_party/blink/renderer/core/paint/paint_timing_detector.cc
@@ -7,20 +7,29 @@
#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/frame/web_frame_widget_base.h"
+#include "third_party/blink/renderer/core/frame/web_local_frame_impl.h"
#include "third_party/blink/renderer/core/layout/layout_box_model_object.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/loader/resource/image_resource_content.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/image_paint_timing_detector.h"
+#include "third_party/blink/renderer/core/paint/largest_contentful_paint_calculator.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/core/style/style_fetched_image.h"
+#include "third_party/blink/renderer/core/timing/dom_window_performance.h"
#include "third_party/blink/renderer/platform/geometry/int_rect.h"
#include "third_party/blink/renderer/platform/graphics/image.h"
#include "third_party/blink/renderer/platform/graphics/paint/float_clip_rect.h"
#include "third_party/blink/renderer/platform/graphics/paint/geometry_mapper.h"
#include "third_party/blink/renderer/platform/graphics/paint/property_tree_state.h"
#include "third_party/blink/renderer/platform/graphics/paint/scoped_paint_chunk_properties.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
+#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
@@ -52,31 +61,53 @@ bool IsBackgroundImageContentful(const LayoutObject& object,
PaintTimingDetector::PaintTimingDetector(LocalFrameView* frame_view)
: frame_view_(frame_view),
text_paint_timing_detector_(
- MakeGarbageCollected<TextPaintTimingDetector>(frame_view)),
+ MakeGarbageCollected<TextPaintTimingDetector>(frame_view,
+ this,
+ nullptr /*set later*/)),
image_paint_timing_detector_(
- MakeGarbageCollected<ImagePaintTimingDetector>(frame_view)) {}
+ MakeGarbageCollected<ImagePaintTimingDetector>(
+ frame_view,
+ nullptr /*set later*/)),
+ callback_manager_(
+ MakeGarbageCollected<PaintTimingCallbackManagerImpl>(frame_view)) {
+ if (PaintTimingVisualizer::IsTracingEnabled())
+ visualizer_.emplace();
+ text_paint_timing_detector_->ResetCallbackManager(callback_manager_.Get());
+ image_paint_timing_detector_->ResetCallbackManager(callback_manager_.Get());
+}
void PaintTimingDetector::NotifyPaintFinished() {
+ if (PaintTimingVisualizer::IsTracingEnabled()) {
+ if (!visualizer_)
+ visualizer_.emplace();
+ visualizer_->RecordMainFrameViewport(*frame_view_);
+ } else {
+ visualizer_.reset();
+ }
if (text_paint_timing_detector_) {
text_paint_timing_detector_->OnPaintFinished();
- if (text_paint_timing_detector_->FinishedReportingText())
+ if (text_paint_timing_detector_->FinishedReportingText()) {
+ text_paint_timing_detector_->StopRecordEntries();
text_paint_timing_detector_ = nullptr;
+ }
}
if (image_paint_timing_detector_) {
image_paint_timing_detector_->OnPaintFinished();
if (image_paint_timing_detector_->FinishedReportingImages())
image_paint_timing_detector_ = nullptr;
}
+ if (callback_manager_->CountCallbacks() > 0)
+ callback_manager_->RegisterPaintTimeCallbackForCombinedCallbacks();
}
// static
void PaintTimingDetector::NotifyBackgroundImagePaint(
const Node* node,
const Image* image,
- const ImageResourceContent* cached_image,
+ const StyleFetchedImage* style_image,
const PropertyTreeState& current_paint_chunk_properties) {
DCHECK(image);
- DCHECK(cached_image);
+ DCHECK(style_image->CachedImage());
if (!node)
return;
LayoutObject* object = node->GetLayoutObject();
@@ -90,8 +121,9 @@ void PaintTimingDetector::NotifyBackgroundImagePaint(
return;
if (!IsBackgroundImageContentful(*object, *image))
return;
- detector.GetImagePaintTimingDetector()->RecordBackgroundImage(
- *object, image->Size(), *cached_image, current_paint_chunk_properties);
+ detector.GetImagePaintTimingDetector()->RecordImage(
+ *object, image->Size(), *style_image->CachedImage(),
+ current_paint_chunk_properties, style_image);
}
// static
@@ -106,41 +138,38 @@ void PaintTimingDetector::NotifyImagePaint(
if (!cached_image)
return;
PaintTimingDetector& detector = frame_view->GetPaintTimingDetector();
- if (detector.GetImagePaintTimingDetector()) {
- detector.GetImagePaintTimingDetector()->RecordImage(
- object, intrinsic_size, *cached_image, current_paint_chunk_properties);
- }
+ if (!detector.GetImagePaintTimingDetector())
+ return;
+ detector.GetImagePaintTimingDetector()->RecordImage(
+ object, intrinsic_size, *cached_image, current_paint_chunk_properties,
+ nullptr);
}
-void PaintTimingDetector::NotifyNodeRemoved(const LayoutObject& object) {
- DOMNodeId node_id = DOMNodeIds::ExistingIdForNode(object.GetNode());
- if (node_id == kInvalidDOMNodeId)
- return;
+void PaintTimingDetector::NotifyImageFinished(
+ const LayoutObject& object,
+ const ImageResourceContent* cached_image) {
+ if (image_paint_timing_detector_)
+ image_paint_timing_detector_->NotifyImageFinished(object, cached_image);
+}
+void PaintTimingDetector::LayoutObjectWillBeDestroyed(
+ const LayoutObject& object) {
if (text_paint_timing_detector_)
- text_paint_timing_detector_->NotifyNodeRemoved(node_id);
+ text_paint_timing_detector_->LayoutObjectWillBeDestroyed(object);
+
if (image_paint_timing_detector_)
- image_paint_timing_detector_->NotifyNodeRemoved(node_id);
+ image_paint_timing_detector_->LayoutObjectWillBeDestroyed(object);
}
-void PaintTimingDetector::NotifyBackgroundImageRemoved(
+void PaintTimingDetector::NotifyImageRemoved(
const LayoutObject& object,
const ImageResourceContent* cached_image) {
- DOMNodeId node_id = DOMNodeIds::ExistingIdForNode(object.GetNode());
- if (node_id == kInvalidDOMNodeId)
- return;
if (image_paint_timing_detector_) {
- image_paint_timing_detector_->NotifyBackgroundImageRemoved(node_id,
- cached_image);
+ image_paint_timing_detector_->NotifyImageRemoved(object, cached_image);
}
}
-void PaintTimingDetector::NotifyInputEvent(WebInputEvent::Type type) {
- if (type == WebInputEvent::kMouseMove || type == WebInputEvent::kMouseEnter ||
- type == WebInputEvent::kMouseLeave ||
- WebInputEvent::IsPinchGestureEventType(type)) {
- return;
- }
+void PaintTimingDetector::StopRecordingIfNeeded() {
DCHECK(frame_view_);
if (text_paint_timing_detector_) {
text_paint_timing_detector_->StopRecordingLargestTextPaint();
@@ -151,21 +180,22 @@ void PaintTimingDetector::NotifyInputEvent(WebInputEvent::Type type) {
}
if (image_paint_timing_detector_)
image_paint_timing_detector_->StopRecordEntries();
+ largest_contentful_paint_calculator_ = nullptr;
+}
+
+void PaintTimingDetector::NotifyInputEvent(WebInputEvent::Type type) {
+ if (type == WebInputEvent::kMouseMove || type == WebInputEvent::kMouseEnter ||
+ type == WebInputEvent::kMouseLeave ||
+ WebInputEvent::IsPinchGestureEventType(type)) {
+ return;
+ }
+ StopRecordingIfNeeded();
}
void PaintTimingDetector::NotifyScroll(ScrollType scroll_type) {
if (scroll_type != kUserScroll && scroll_type != kCompositorScroll)
return;
- DCHECK(frame_view_);
- if (text_paint_timing_detector_) {
- text_paint_timing_detector_->StopRecordingLargestTextPaint();
- if (!RuntimeEnabledFeatures::ElementTimingEnabled(
- frame_view_->GetFrame().GetDocument())) {
- text_paint_timing_detector_->StopRecordEntries();
- }
- }
- if (image_paint_timing_detector_)
- image_paint_timing_detector_->StopRecordEntries();
+ StopRecordingIfNeeded();
}
bool PaintTimingDetector::NeedToNotifyInputOrScroll() const {
@@ -175,6 +205,24 @@ bool PaintTimingDetector::NeedToNotifyInputOrScroll() const {
image_paint_timing_detector_->IsRecording());
}
+LargestContentfulPaintCalculator*
+PaintTimingDetector::GetLargestContentfulPaintCalculator() {
+ if (!RuntimeEnabledFeatures::LargestContentfulPaintEnabled())
+ return nullptr;
+
+ if (largest_contentful_paint_calculator_)
+ return largest_contentful_paint_calculator_;
+
+ auto* dom_window = frame_view_->GetFrame().DomWindow();
+ if (!dom_window)
+ return nullptr;
+
+ largest_contentful_paint_calculator_ =
+ MakeGarbageCollected<LargestContentfulPaintCalculator>(
+ DOMWindowPerformance::performance(*dom_window));
+ return largest_contentful_paint_calculator_;
+}
+
bool PaintTimingDetector::NotifyIfChangedLargestImagePaint(
base::TimeTicks image_paint_time,
uint64_t image_paint_size) {
@@ -221,6 +269,18 @@ void PaintTimingDetector::DidChangePerformanceTiming() {
loader->DidChangePerformanceTiming();
}
+void PaintTimingDetector::ConvertViewportToWindow(
+ WebFloatRect* float_rect) const {
+ WebLocalFrameImpl* web_frame =
+ WebLocalFrameImpl::FromFrame(&frame_view_->GetFrame());
+ // May be nullptr in some tests.
+ if (!web_frame)
+ return;
+ WebFrameWidgetBase* widget = web_frame->LocalRootFrameWidget();
+ DCHECK(widget);
+ widget->Client()->ConvertViewportToWindow(float_rect);
+}
+
FloatRect PaintTimingDetector::CalculateVisualRect(
const IntRect& visual_rect,
const PropertyTreeState& current_paint_chunk_properties) const {
@@ -233,9 +293,11 @@ FloatRect PaintTimingDetector::CalculateVisualRect(
GeometryMapper::LocalToAncestorVisualRect(current_paint_chunk_properties,
PropertyTreeState::Root(),
float_clip_visual_rect);
- FloatRect& float_visual_rect = float_clip_visual_rect.Rect();
- if (frame_view_->GetFrame().LocalFrameRoot().IsMainFrame())
+ WebFloatRect float_visual_rect = float_clip_visual_rect.Rect();
+ if (frame_view_->GetFrame().LocalFrameRoot().IsMainFrame()) {
+ ConvertViewportToWindow(&float_visual_rect);
return float_visual_rect;
+ }
// OOPIF. The final rect lives in the iframe's root frame space. We need to
// project it to the top frame space.
auto layout_visual_rect = PhysicalRect::EnclosingRect(float_visual_rect);
@@ -243,7 +305,36 @@ FloatRect PaintTimingDetector::CalculateVisualRect(
.LocalFrameRoot()
.View()
->MapToVisualRectInTopFrameSpace(layout_visual_rect);
- return FloatRect(layout_visual_rect);
+ WebFloatRect float_rect = FloatRect(layout_visual_rect);
+ ConvertViewportToWindow(&float_rect);
+ return float_rect;
+}
+
+void PaintTimingDetector::UpdateLargestContentfulPaintCandidate() {
+ auto* lcp_calculator = GetLargestContentfulPaintCalculator();
+ if (!lcp_calculator)
+ return;
+
+ // Optional, WeakPtr, Record have different roles:
+ // * !Optional means |UpdateCandidate() is not reachable, e.g., user input
+ // has been given to stop LCP. In this case, we still use the last recorded
+ // result.
+ // * !Weak means there is no candidate, e.g., no content show up on the page.
+ // * Record.paint_time == 0 means there is an image but the image is still
+ // loading. The perf API should wait until the paint-time is available.
+ base::Optional<base::WeakPtr<TextRecord>> largest_text_record;
+ base::Optional<const ImageRecord*> largest_image_record;
+ if (auto* text_timing_detector = GetTextPaintTimingDetector()) {
+ if (text_timing_detector->IsRecordingLargestTextPaint()) {
+ largest_text_record.emplace(text_timing_detector->UpdateCandidate());
+ }
+ }
+ if (auto* image_timing_detector = GetImagePaintTimingDetector()) {
+ largest_image_record.emplace(image_timing_detector->UpdateCandidate());
+ }
+
+ lcp_calculator->UpdateLargestContentPaintIfNeeded(largest_text_record,
+ largest_image_record);
}
ScopedPaintTimingDetectorBlockPaintHook*
@@ -252,12 +343,19 @@ ScopedPaintTimingDetectorBlockPaintHook*
void ScopedPaintTimingDetectorBlockPaintHook::EmplaceIfNeeded(
const LayoutBoxModelObject& aggregator,
const PropertyTreeState& property_tree_state) {
+ // |reset_top_| is unset when |aggregator| is anonymous so that each
+ // aggregation corresponds to an element. See crbug.com/988593. When set,
+ // |top_| becomes |this|, and |top_| is restored to the previous value when
+ // the ScopedPaintTimingDetectorBlockPaintHook goes out of scope.
+ if (aggregator.GetNode())
+ reset_top_.emplace(&top_, this);
+
TextPaintTimingDetector* detector = aggregator.GetFrameView()
->GetPaintTimingDetector()
.GetTextPaintTimingDetector();
- if (!detector || !detector->ShouldWalkObject(aggregator))
- return;
- data_.emplace(aggregator, property_tree_state, detector);
+ // Only set |data_| if we need to walk the object.
+ if (detector && detector->ShouldWalkObject(aggregator))
+ data_.emplace(aggregator, property_tree_state, detector);
}
ScopedPaintTimingDetectorBlockPaintHook::Data::Data(
@@ -270,9 +368,14 @@ ScopedPaintTimingDetectorBlockPaintHook::Data::Data(
ScopedPaintTimingDetectorBlockPaintHook::
~ScopedPaintTimingDetectorBlockPaintHook() {
- DCHECK_EQ(top_, this);
if (!data_ || data_->aggregated_visual_rect_.IsEmpty())
return;
+ // TODO(crbug.com/987804): Checking |ShouldWalkObject| again is necessary
+ // because the result can change, but more investigation is needed as to why
+ // the change is possible.
+ if (!data_->detector_ ||
+ !data_->detector_->ShouldWalkObject(data_->aggregator_))
+ return;
data_->detector_->RecordAggregatedText(data_->aggregator_,
data_->aggregated_visual_rect_,
data_->property_tree_state_);
@@ -282,6 +385,45 @@ void PaintTimingDetector::Trace(Visitor* visitor) {
visitor->Trace(text_paint_timing_detector_);
visitor->Trace(image_paint_timing_detector_);
visitor->Trace(frame_view_);
+ visitor->Trace(largest_contentful_paint_calculator_);
+ visitor->Trace(callback_manager_);
+ visitor->Trace(visualizer_);
+}
+
+void PaintTimingCallbackManagerImpl::
+ RegisterPaintTimeCallbackForCombinedCallbacks() {
+ DCHECK(!frame_callbacks_->empty());
+ LocalFrame& frame = frame_view_->GetFrame();
+ if (!frame.GetPage())
+ return;
+
+ auto combined_callback = CrossThreadBindOnce(
+ &PaintTimingCallbackManagerImpl::ReportPaintTime,
+ WrapCrossThreadWeakPersistent(this), std::move(frame_callbacks_));
+ frame_callbacks_ =
+ std::make_unique<PaintTimingCallbackManager::CallbackQueue>();
+
+ // |ReportPaintTime| on |layerTreeView| will queue a swap-promise, the
+ // callback is called when the swap for current render frame completes or
+ // fails to happen.
+ frame.GetPage()->GetChromeClient().NotifySwapTime(
+ frame, std::move(combined_callback));
+}
+
+void PaintTimingCallbackManagerImpl::ReportPaintTime(
+ std::unique_ptr<PaintTimingCallbackManager::CallbackQueue> frame_callbacks,
+ WebWidgetClient::SwapResult result,
+ base::TimeTicks paint_time) {
+ while (!frame_callbacks->empty()) {
+ std::move(frame_callbacks->front()).Run(paint_time);
+ frame_callbacks->pop();
+ }
+ frame_view_->GetPaintTimingDetector().UpdateLargestContentfulPaintCandidate();
+}
+
+void PaintTimingCallbackManagerImpl::Trace(Visitor* visitor) {
+ visitor->Trace(frame_view_);
+ PaintTimingCallbackManager::Trace(visitor);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_timing_detector.h b/chromium/third_party/blink/renderer/core/paint/paint_timing_detector.h
index e123bc766c0..2c325beb0c6 100644
--- a/chromium/third_party/blink/renderer/core/paint/paint_timing_detector.h
+++ b/chromium/third_party/blink/renderer/core/paint/paint_timing_detector.h
@@ -1,4 +1,4 @@
-// Copyright 2018 The Chromium Authors. All rights reserved.
+// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@@ -6,20 +6,104 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_PAINT_TIMING_DETECTOR_H_
#include "third_party/blink/public/platform/web_input_event.h"
+#include "third_party/blink/public/web/web_widget_client.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/layout/layout_box_model_object.h"
+#include "third_party/blink/renderer/core/paint/paint_timing_visualizer.h"
#include "third_party/blink/renderer/core/scroll/scroll_types.h"
#include "third_party/blink/renderer/platform/heap/member.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
namespace blink {
class Image;
class ImagePaintTimingDetector;
class ImageResourceContent;
+class LargestContentfulPaintCalculator;
class LayoutObject;
class LocalFrameView;
class PropertyTreeState;
+class StyleFetchedImage;
class TextPaintTimingDetector;
+struct WebFloatRect;
+
+// |PaintTimingCallbackManager| is an interface between
+// |ImagePaintTimingDetector|/|TextPaintTimingDetector| and |ChromeClient|.
+// As |ChromeClient| is shared among the paint-timing-detecters, it
+// makes it hard to test each detector without being affected other detectors.
+// The interface, however, allows unit tests to mock |ChromeClient| for each
+// detector. With the mock, |ImagePaintTimingDetector|'s callback does not need
+// to store in the same queue as |TextPaintTimingDetector|'s. The separate
+// queue makes it possible to pop an |ImagePaintTimingDetector|'s callback
+// without having to popping the |TextPaintTimingDetector|'s.
+class PaintTimingCallbackManager : public GarbageCollectedMixin {
+ public:
+ using LocalThreadCallback = base::OnceCallback<void(base::TimeTicks)>;
+ using CallbackQueue = std::queue<LocalThreadCallback>;
+
+ virtual void RegisterCallback(
+ PaintTimingCallbackManager::LocalThreadCallback) = 0;
+};
+
+// This class is responsible for managing the swap-time callback for Largest
+// Image Paint and Largest Text Paint. In frames where both text and image are
+// painted, Largest Image Paint and Largest Text Paint need to assign the same
+// paint-time for their records. In this case, |PaintTimeCallbackManager|
+// requests a swap-time callback and share the swap-time with LIP and LTP.
+// Otherwise LIP and LTP would have to request their own swap-time callbacks.
+// An extra benefit of this design is that |LargestContentfulPaintCalculator|
+// can thus hook to the end of the LIP and LTP's record assignments.
+//
+// |GarbageCollectedFinalized| inheritance is required by the swap-time callback
+// registration.
+class PaintTimingCallbackManagerImpl final
+ : public GarbageCollectedFinalized<PaintTimingCallbackManagerImpl>,
+ public PaintTimingCallbackManager {
+ USING_GARBAGE_COLLECTED_MIXIN(PaintTimingCallbackManagerImpl);
+
+ public:
+ PaintTimingCallbackManagerImpl(LocalFrameView* frame_view)
+ : frame_view_(frame_view),
+ frame_callbacks_(
+ std::make_unique<std::queue<
+ PaintTimingCallbackManager::LocalThreadCallback>>()) {}
+ ~PaintTimingCallbackManagerImpl() { frame_callbacks_.reset(); }
+
+ // Instead of registering the callback right away, this impl of the interface
+ // combine the callback into |frame_callbacks_| before registering a separate
+ // swap-time callback for the combined callbacks. When the swap-time callback
+ // is invoked, the swap-time is then assigned to each callback of
+ // |frame_callbacks_|.
+ void RegisterCallback(
+ PaintTimingCallbackManager::LocalThreadCallback callback) override {
+ frame_callbacks_->push(std::move(callback));
+ }
+
+ void RegisterPaintTimeCallbackForCombinedCallbacks();
+
+ inline size_t CountCallbacks() { return frame_callbacks_->size(); }
+
+ void ReportPaintTime(
+ std::unique_ptr<std::queue<
+ PaintTimingCallbackManager::LocalThreadCallback>> frame_callbacks,
+ WebWidgetClient::SwapResult,
+ base::TimeTicks paint_time);
+
+ void Trace(Visitor* visitor) override;
+
+ private:
+ Member<LocalFrameView> frame_view_;
+ // |frame_callbacks_| stores the callbacks of |TextPaintTimingDetector| and
+ // |ImagePaintTimingDetector| in an (animated) frame. It is passed as an
+ // argument of a swap-time callback which once is invoked, invokes every
+ // callback in |frame_callbacks_|. This hierarchical callback design is to
+ // reduce the need of calling ChromeClient to register swap-time callbacks for
+ // both detectos.
+ // Although |frame_callbacks_| intends to store callbacks
+ // of a frame, it occasionally has to do that for more than one frame, when it
+ // fails to register a swap-time callback.
+ std::unique_ptr<PaintTimingCallbackManager::CallbackQueue> frame_callbacks_;
+};
// PaintTimingDetector contains some of paint metric detectors,
// providing common infrastructure for these detectors.
@@ -39,7 +123,7 @@ class CORE_EXPORT PaintTimingDetector
static void NotifyBackgroundImagePaint(
const Node*,
const Image*,
- const ImageResourceContent* cached_image,
+ const StyleFetchedImage*,
const PropertyTreeState& current_paint_chunk_properties);
static void NotifyImagePaint(
const LayoutObject&,
@@ -48,9 +132,9 @@ class CORE_EXPORT PaintTimingDetector
const PropertyTreeState& current_paint_chunk_properties);
inline static void NotifyTextPaint(const IntRect& text_visual_rect);
- void NotifyNodeRemoved(const LayoutObject&);
- void NotifyBackgroundImageRemoved(const LayoutObject&,
- const ImageResourceContent*);
+ void NotifyImageFinished(const LayoutObject&, const ImageResourceContent*);
+ void LayoutObjectWillBeDestroyed(const LayoutObject&);
+ void NotifyImageRemoved(const LayoutObject&, const ImageResourceContent*);
void NotifyPaintFinished();
void NotifyInputEvent(WebInputEvent::Type);
bool NeedToNotifyInputOrScroll() const;
@@ -61,6 +145,13 @@ class CORE_EXPORT PaintTimingDetector
void DidChangePerformanceTiming();
+ inline static bool IsTracing() {
+ bool tracing_enabled;
+ TRACE_EVENT_CATEGORY_GROUP_ENABLED("loading", &tracing_enabled);
+ return tracing_enabled;
+ }
+
+ void ConvertViewportToWindow(WebFloatRect* float_rect) const;
FloatRect CalculateVisualRect(const IntRect& visual_rect,
const PropertyTreeState&) const;
@@ -70,15 +161,23 @@ class CORE_EXPORT PaintTimingDetector
ImagePaintTimingDetector* GetImagePaintTimingDetector() const {
return image_paint_timing_detector_;
}
+
+ LargestContentfulPaintCalculator* GetLargestContentfulPaintCalculator();
+
base::TimeTicks LargestImagePaint() const {
return largest_image_paint_time_;
}
uint64_t LargestImagePaintSize() const { return largest_image_paint_size_; }
base::TimeTicks LargestTextPaint() const { return largest_text_paint_time_; }
uint64_t LargestTextPaintSize() const { return largest_text_paint_size_; }
+
+ void UpdateLargestContentfulPaintCandidate();
+
+ base::Optional<PaintTimingVisualizer>& Visualizer() { return visualizer_; }
void Trace(Visitor* visitor);
private:
+ void StopRecordingIfNeeded();
bool HasLargestImagePaintChanged(base::TimeTicks, uint64_t size) const;
bool HasLargestTextPaintChanged(base::TimeTicks, uint64_t size) const;
Member<LocalFrameView> frame_view_;
@@ -89,6 +188,12 @@ class CORE_EXPORT PaintTimingDetector
// image paint is found.
Member<ImagePaintTimingDetector> image_paint_timing_detector_;
+ Member<LargestContentfulPaintCalculator> largest_contentful_paint_calculator_;
+
+ Member<PaintTimingCallbackManagerImpl> callback_manager_;
+
+ base::Optional<PaintTimingVisualizer> visualizer_;
+
// Largest image information.
base::TimeTicks largest_image_paint_time_;
uint64_t largest_image_paint_size_ = 0;
@@ -112,9 +217,11 @@ class ScopedPaintTimingDetectorBlockPaintHook {
STACK_ALLOCATED();
public:
- // This sets |top_| to |this|, and will restore |top_| to the previous
- // value when this object destructs.
- ScopedPaintTimingDetectorBlockPaintHook() : reset_top_(&top_, this) {}
+ // This constructor does nothing by itself. It will only set relevant
+ // variables when EmplaceIfNeeded() is called successfully. The lifetime of
+ // the object helps keeping the lifetime of |reset_top_| and |data_| to the
+ // appropriate scope.
+ ScopedPaintTimingDetectorBlockPaintHook() {}
void EmplaceIfNeeded(const LayoutBoxModelObject&, const PropertyTreeState&);
~ScopedPaintTimingDetectorBlockPaintHook();
@@ -122,12 +229,18 @@ class ScopedPaintTimingDetectorBlockPaintHook {
private:
friend class PaintTimingDetector;
inline static void AggregateTextPaint(const IntRect& visual_rect) {
- DCHECK(top_);
- if (top_->data_)
+ // Ideally we'd assert that |top_| exists, but there may be text nodes that
+ // do not have an ancestor non-anonymous block layout objects in the layout
+ // tree. An example of this is a multicol div, since the
+ // LayoutMultiColumnFlowThread is in a different layer from the DIV. In
+ // these cases, |top_| will be null. This is a known bug, see the related
+ // crbug.com/933479.
+ if (top_ && top_->data_)
top_->data_->aggregated_visual_rect_.Unite(visual_rect);
}
- base::AutoReset<ScopedPaintTimingDetectorBlockPaintHook*> reset_top_;
+ base::Optional<base::AutoReset<ScopedPaintTimingDetectorBlockPaintHook*>>
+ reset_top_;
struct Data {
STACK_ALLOCATED();
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_timing_test_helper.h b/chromium/third_party/blink/renderer/core/paint/paint_timing_test_helper.h
new file mode 100644
index 00000000000..8d1dfb20eb2
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/paint/paint_timing_test_helper.h
@@ -0,0 +1,36 @@
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_PAINT_TIMING_TEST_HELPER_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_PAINT_TIMING_TEST_HELPER_H_
+
+#include "third_party/blink/renderer/core/paint/paint_timing_detector.h"
+namespace blink {
+
+// |MockPaintTimingCallbackManager| is used to mock
+// |ChromeClient::NotifySwapTime()|'s swap-time queueing and invoking for
+// unit-tests. Find more details in |PaintTimingCallbackManager|.
+class MockPaintTimingCallbackManager final
+ : public GarbageCollectedFinalized<MockPaintTimingCallbackManager>,
+ public PaintTimingCallbackManager {
+ USING_GARBAGE_COLLECTED_MIXIN(MockPaintTimingCallbackManager);
+
+ public:
+ ~MockPaintTimingCallbackManager() {}
+ void RegisterCallback(
+ PaintTimingCallbackManager::LocalThreadCallback callback) override {
+ callback_queue_.push(std::move(callback));
+ }
+ void InvokeSwapTimeCallback(base::TimeTicks swap_time) {
+ DCHECK_GT(callback_queue_.size(), 0UL);
+ std::move(callback_queue_.front()).Run(swap_time);
+ callback_queue_.pop();
+ }
+
+ size_t CountCallbacks() { return callback_queue_.size(); }
+
+ void Trace(Visitor* visitor) override {}
+
+ private:
+ PaintTimingCallbackManager::CallbackQueue callback_queue_;
+};
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_PAINT_TIMING_TEST_HELPER_H_
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_timing_visualizer.cc b/chromium/third_party/blink/renderer/core/paint/paint_timing_visualizer.cc
new file mode 100644
index 00000000000..a9bb39c9396
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/paint/paint_timing_visualizer.cc
@@ -0,0 +1,111 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/paint/paint_timing_visualizer.h"
+
+#include "third_party/blink/public/platform/web_float_rect.h"
+#include "third_party/blink/renderer/core/dom/dom_node_ids.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/loader/resource/image_resource_content.h"
+#include "third_party/blink/renderer/core/paint/paint_timing_detector.h"
+#include "third_party/blink/renderer/core/scroll/scrollable_area.h"
+#include "third_party/blink/renderer/platform/geometry/int_rect.h"
+#include "third_party/blink/renderer/platform/instrumentation/tracing/traced_value.h"
+
+namespace blink {
+
+namespace {
+static void CreateQuad(TracedValue* value,
+ const char* name,
+ const FloatQuad& quad) {
+ value->BeginArray(name);
+ value->PushDouble(quad.P1().X());
+ value->PushDouble(quad.P1().Y());
+ value->PushDouble(quad.P2().X());
+ value->PushDouble(quad.P2().Y());
+ value->PushDouble(quad.P3().X());
+ value->PushDouble(quad.P3().Y());
+ value->PushDouble(quad.P4().X());
+ value->PushDouble(quad.P4().Y());
+ value->EndArray();
+}
+
+} // namespace
+
+void PaintTimingVisualizer::RecordRects(const IntRect& rect,
+ std::unique_ptr<TracedValue>& value) {
+ CreateQuad(value.get(), "rect", FloatRect(rect));
+}
+void PaintTimingVisualizer::RecordObject(const LayoutObject& object,
+ std::unique_ptr<TracedValue>& value) {
+ value->SetString("object_name", object.GetName());
+ DCHECK(object.GetFrame());
+ value->SetString("frame", String::FromUTF8(ToTraceValue(object.GetFrame())));
+ value->SetBoolean("is_in_main_frame", object.GetFrame()->IsMainFrame());
+ if (object.GetNode())
+ value->SetInteger("dom_node_id", DOMNodeIds::IdForNode(object.GetNode()));
+}
+
+void PaintTimingVisualizer::DumpTextDebuggingRect(const LayoutObject& object,
+ const FloatRect& rect) {
+ std::unique_ptr<TracedValue> value = std::make_unique<TracedValue>();
+ RecordObject(object, value);
+ RecordRects(RoundedIntRect(rect), value);
+ value->SetBoolean("is_aggregation_text", true);
+ value->SetBoolean("is_svg", object.IsSVG());
+ DumpTrace(std::move(value));
+}
+
+void PaintTimingVisualizer::DumpImageDebuggingRect(
+ const LayoutObject& object,
+ const FloatRect& rect,
+ const ImageResourceContent& cached_image) {
+ std::unique_ptr<TracedValue> value = std::make_unique<TracedValue>();
+ RecordObject(object, value);
+ RecordRects(RoundedIntRect(rect), value);
+ value->SetBoolean("is_image", true);
+ value->SetBoolean("is_svg", object.IsSVG());
+ value->SetBoolean("is_image_loaded", cached_image.IsLoaded());
+ value->SetString("image_url",
+ String(cached_image.Url().StrippedForUseAsReferrer()));
+ DumpTrace(std::move(value));
+}
+
+void PaintTimingVisualizer::DumpTrace(std::unique_ptr<TracedValue> value) {
+ TRACE_EVENT_INSTANT1("loading", "PaintTimingVisualizer::LayoutObjectPainted",
+ TRACE_EVENT_SCOPE_THREAD, "data", std::move(value));
+}
+
+void PaintTimingVisualizer::RecordMainFrameViewport(
+ LocalFrameView& frame_view) {
+ if (!need_recording_viewport)
+ return;
+ if (!frame_view.GetFrame().IsMainFrame())
+ return;
+ ScrollableArea* scrollable_area = frame_view.GetScrollableArea();
+ DCHECK(scrollable_area);
+ IntRect viewport_rect = scrollable_area->VisibleContentRect();
+
+ FloatClipRect float_clip_visual_rect =
+ FloatClipRect(FloatRect(viewport_rect));
+ WebFloatRect float_visual_rect = float_clip_visual_rect.Rect();
+ frame_view.GetPaintTimingDetector().ConvertViewportToWindow(
+ &float_visual_rect);
+
+ std::unique_ptr<TracedValue> value = std::make_unique<TracedValue>();
+ CreateQuad(value.get(), "viewport_rect", FloatQuad(float_visual_rect));
+ TRACE_EVENT_INSTANT1("loading", "PaintTimingVisualizer::Viewport",
+ TRACE_EVENT_SCOPE_THREAD, "data", std::move(value));
+ need_recording_viewport = false;
+}
+
+// static
+bool PaintTimingVisualizer::IsTracingEnabled() {
+ bool enabled;
+ TRACE_EVENT_CATEGORY_GROUP_ENABLED("loading", &enabled);
+ return enabled;
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/paint/paint_timing_visualizer.h b/chromium/third_party/blink/renderer/core/paint/paint_timing_visualizer.h
new file mode 100644
index 00000000000..4a6b2521c27
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/paint/paint_timing_visualizer.h
@@ -0,0 +1,44 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_PAINT_TIMING_VISUALIZER_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_PAINT_TIMING_VISUALIZER_H_
+
+#include "third_party/blink/renderer/core/core_export.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/platform/instrumentation/tracing/traced_value.h"
+
+namespace blink {
+
+class IntRect;
+
+// While Largest Contentful Paint only concerns about the largest contentful
+// rect, the smaller rects used in its computation are helpful for debugging
+// purpose. This helper class generates debugging traces that contains these
+// intermediate rects. These debugging events, as well as their intermediate
+// rects, can be visualized by third-party visualization tools.
+class CORE_EXPORT PaintTimingVisualizer {
+ public:
+ static bool IsTracingEnabled();
+
+ void DumpTextDebuggingRect(const LayoutObject&, const FloatRect&);
+ void DumpImageDebuggingRect(const LayoutObject&,
+ const FloatRect&,
+ const ImageResourceContent&);
+ void RecordMainFrameViewport(LocalFrameView& frame_view);
+ inline void OnViewportChanged() { need_recording_viewport = true; }
+
+ private:
+ void RecordObject(const LayoutObject&, std::unique_ptr<TracedValue>&);
+ void RecordRects(const IntRect& rect, std::unique_ptr<TracedValue>&);
+ void RecordMainFrameViewport(const IntRect&);
+ void DumpTrace(std::unique_ptr<TracedValue>);
+
+ bool need_recording_viewport = true;
+};
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_PAINT_TIMING_VISUALIZER_H_
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 884717d06ea..caccba060d8 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
@@ -12,9 +12,9 @@
#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/visual_viewport.h"
-#include "third_party/blink/renderer/core/layout/jank_tracker.h"
#include "third_party/blink/renderer/core/layout/layout_embedded_content.h"
#include "third_party/blink/renderer/core/layout/layout_multi_column_spanner_placeholder.h"
+#include "third_party/blink/renderer/core/layout/layout_shift_tracker.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"
@@ -141,7 +141,7 @@ void PrePaintTreeWalk::Walk(LocalFrameView& frame_view) {
#endif
}
- frame_view.GetJankTracker().NotifyPrePaintFinished();
+ frame_view.GetLayoutShiftTracker().NotifyPrePaintFinished();
context_storage_.pop_back();
}
@@ -274,8 +274,9 @@ bool PrePaintTreeWalk::ContextRequiresPrePaint(
bool PrePaintTreeWalk::ObjectRequiresTreeBuilderContext(
const LayoutObject& object) {
return object.NeedsPaintPropertyUpdate() ||
- object.DescendantNeedsPaintPropertyUpdate() ||
- object.DescendantNeedsPaintOffsetAndVisualRectUpdate();
+ (!object.PrePaintBlockedByDisplayLock(DisplayLockContext::kChildren) &&
+ (object.DescendantNeedsPaintPropertyUpdate() ||
+ object.DescendantNeedsPaintOffsetAndVisualRectUpdate()));
}
bool PrePaintTreeWalk::ContextRequiresTreeBuilderContext(
@@ -405,24 +406,6 @@ void PrePaintTreeWalk::Walk(const LayoutObject& object) {
ContextRequiresTreeBuilderContext(parent_context(), object) ||
ObjectRequiresTreeBuilderContext(object);
- if (object.PrePaintBlockedByDisplayLock()) {
- // If we need a subtree walk due to context flags, we need to store that
- // information on the display lock, since subsequent walks might not set the
- // same bits on the parent context.
- if (ContextRequiresTreeBuilderContext(parent_context(), object) ||
- ContextRequiresPrePaint(parent_context())) {
- // Note that effective allowed touch action changed is special in that
- // it requires us to specifically recalculate this value on each subtree
- // element. Other flags simply need a subtree walk. Some consideration
- // needs to be given to |clip_changed| which ensures that we repaint every
- // layer, but for the purposes of PrePaint, this flag is just forcing a
- // subtree walk.
- object.GetDisplayLockContext()->SetNeedsPrePaintSubtreeWalk(
- parent_context().effective_allowed_touch_action_changed);
- }
- return;
- }
-
// The following is for debugging crbug.com/974639.
CheckTreeBuilderContextState(object, parent_context());
@@ -432,11 +415,6 @@ void PrePaintTreeWalk::Walk(const LayoutObject& object) {
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();
-
// Note that because we're emplacing an object constructed from
// parent_context() (which is a reference to the vector itself), it's
// important to first ensure that there's sufficient capacity in the vector.
@@ -459,31 +437,54 @@ void PrePaintTreeWalk::Walk(const LayoutObject& object) {
}
WalkInternal(object, context());
+ object.NotifyDisplayLockDidPrePaint(DisplayLockContext::kSelf);
+
+ bool child_walk_blocked =
+ object.PrePaintBlockedByDisplayLock(DisplayLockContext::kChildren);
+ // If we need a subtree walk due to context flags, we need to store that
+ // information on the display lock, since subsequent walks might not set the
+ // same bits on the context.
+ if (child_walk_blocked &&
+ (ContextRequiresTreeBuilderContext(context(), object) ||
+ ContextRequiresPrePaint(context()))) {
+ // Note that effective allowed touch action changed is special in that
+ // it requires us to specifically recalculate this value on each subtree
+ // element. Other flags simply need a subtree walk. Some consideration
+ // needs to be given to |clip_changed| which ensures that we repaint every
+ // layer, but for the purposes of PrePaint, this flag is just forcing a
+ // subtree walk.
+ object.GetDisplayLockContext()->SetNeedsPrePaintSubtreeWalk(
+ context().effective_allowed_touch_action_changed);
+ }
- for (const LayoutObject* child = object.SlowFirstChild(); child;
- child = child->NextSibling()) {
- if (child->IsLayoutMultiColumnSpannerPlaceholder()) {
- child->GetMutableForPainting().ClearPaintFlags();
- continue;
+ if (!child_walk_blocked) {
+ for (const LayoutObject* child = object.SlowFirstChild(); child;
+ child = child->NextSibling()) {
+ if (child->IsLayoutMultiColumnSpannerPlaceholder()) {
+ child->GetMutableForPainting().ClearPaintFlags();
+ continue;
+ }
+ Walk(*child);
}
- Walk(*child);
- }
- if (object.IsLayoutEmbeddedContent()) {
- const LayoutEmbeddedContent& layout_embedded_content =
- ToLayoutEmbeddedContent(object);
- FrameView* frame_view = layout_embedded_content.ChildFrameView();
- if (auto* local_frame_view = DynamicTo<LocalFrameView>(frame_view)) {
- if (context().tree_builder_context) {
- auto& offset =
- context().tree_builder_context->fragments[0].current.paint_offset;
- offset += layout_embedded_content.ReplacedContentRect().offset;
- offset -= PhysicalOffset(local_frame_view->FrameRect().Location());
- offset = PhysicalOffset(RoundedIntPoint(offset));
+ if (object.IsLayoutEmbeddedContent()) {
+ const LayoutEmbeddedContent& layout_embedded_content =
+ ToLayoutEmbeddedContent(object);
+ FrameView* frame_view = layout_embedded_content.ChildFrameView();
+ if (auto* local_frame_view = DynamicTo<LocalFrameView>(frame_view)) {
+ if (context().tree_builder_context) {
+ auto& offset =
+ context().tree_builder_context->fragments[0].current.paint_offset;
+ offset += layout_embedded_content.ReplacedContentRect().offset;
+ offset -= PhysicalOffset(local_frame_view->FrameRect().Location());
+ offset = PhysicalOffset(RoundedIntPoint(offset));
+ }
+ Walk(*local_frame_view);
}
- Walk(*local_frame_view);
+ // TODO(pdr): Investigate RemoteFrameView (crbug.com/579281).
}
- // TODO(pdr): Investigate RemoteFrameView (crbug.com/579281).
+
+ object.NotifyDisplayLockDidPrePaint(DisplayLockContext::kChildren);
}
object.GetMutableForPainting().ClearPaintFlags();
diff --git a/chromium/third_party/blink/renderer/core/paint/pre_paint_tree_walk.h b/chromium/third_party/blink/renderer/core/paint/pre_paint_tree_walk.h
index 933b88544cd..fa95f4bd2fe 100644
--- a/chromium/third_party/blink/renderer/core/paint/pre_paint_tree_walk.h
+++ b/chromium/third_party/blink/renderer/core/paint/pre_paint_tree_walk.h
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/paint/clip_rect.h"
#include "third_party/blink/renderer/core/paint/paint_invalidator.h"
#include "third_party/blink/renderer/core/paint/paint_property_tree_builder.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 e9523c471f6..13c74e63608 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
@@ -49,8 +49,8 @@ class PrePaintTreeWalkTest : public PaintControllerPaintTest {
private:
void SetUp() override {
- RenderingTest::SetUp();
EnableCompositing();
+ RenderingTest::SetUp();
}
};
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 59a32561175..7a987fda13a 100644
--- a/chromium/third_party/blink/renderer/core/paint/replaced_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/replaced_painter.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_REPLACED_PAINTER_H_
#include "third_party/blink/renderer/platform/geometry/layout_point.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/root_inline_box_painter.h b/chromium/third_party/blink/renderer/core/paint/root_inline_box_painter.h
index 01aa375eb2e..5072a09b844 100644
--- a/chromium/third_party/blink/renderer/core/paint/root_inline_box_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/root_inline_box_painter.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_ROOT_INLINE_BOX_PAINTER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_ROOT_INLINE_BOX_PAINTER_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/rounded_inner_rect_clipper.h b/chromium/third_party/blink/renderer/core/paint/rounded_inner_rect_clipper.h
index 2a98bb7f0f2..58e13f85308 100644
--- a/chromium/third_party/blink/renderer/core/paint/rounded_inner_rect_clipper.h
+++ b/chromium/third_party/blink/renderer/core/paint/rounded_inner_rect_clipper.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_ROUNDED_INNER_RECT_CLIPPER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_ROUNDED_INNER_RECT_CLIPPER_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 2dc2294f1f4..22a3963480f 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
@@ -124,56 +124,23 @@ void ScrollableAreaPainter::DrawPlatformResizerImage(
void ScrollableAreaPainter::PaintOverflowControls(
const PaintInfo& paint_info,
- const IntPoint& paint_offset,
- bool painting_overlay_controls) {
+ const IntPoint& paint_offset) {
// Don't do anything if we have no overflow.
- if (!GetScrollableArea().GetLayoutBox()->HasOverflowClip())
+ const auto& box = *GetScrollableArea().GetLayoutBox();
+ if (!box.HasOverflowClip() ||
+ box.StyleRef().Visibility() != EVisibility::kVisible)
return;
- IntPoint adjusted_paint_offset = paint_offset;
- if (painting_overlay_controls)
- adjusted_paint_offset = GetScrollableArea().CachedOverlayScrollbarOffset();
-
- 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
- // root layer that there are overlay scrollbars that need to be painted. That
- // will cause the second pass through the layer tree to run, and we'll paint
- // the scrollbars then. In the meantime, cache tx and ty so that the second
- // pass doesn't need to re-enter the LayoutTree to get it right.
- if (GetScrollableArea().HasOverlayScrollbars() &&
- !painting_overlay_controls) {
- GetScrollableArea().SetCachedOverlayScrollbarOffset(paint_offset);
- // It's not necessary to do the second pass if the scrollbars paint into
- // layers.
- if ((GetScrollableArea().HorizontalScrollbar() &&
- GetScrollableArea().LayerForHorizontalScrollbar()) ||
- (GetScrollableArea().VerticalScrollbar() &&
- GetScrollableArea().LayerForVerticalScrollbar()))
+ // Overlay scrollbars are painted in the dedicated paint phase, and normal
+ // scrollbars are painted in the background paint phase.
+ if (GetScrollableArea().HasOverlayScrollbars()) {
+ if (paint_info.phase != PaintPhase::kOverlayScrollbars)
return;
- if (!OverflowControlsIntersectRect(adjusted_cull_rect))
- return;
-
- LayoutView* layout_view = GetScrollableArea().GetLayoutBox()->View();
-
- PaintLayer* painting_root =
- GetScrollableArea().Layer()->EnclosingLayerWithCompositedLayerMapping(
- kIncludeSelf);
- if (!painting_root)
- painting_root = layout_view->Layer();
-
- painting_root->SetContainsDirtyOverlayScrollbars(true);
+ } else if (!ShouldPaintSelfBlockBackground(paint_info.phase)) {
return;
}
- // This check is required to avoid painting custom CSS scrollbars twice.
- if (painting_overlay_controls && !GetScrollableArea().HasOverlayScrollbars())
- return;
-
GraphicsContext& context = paint_info.context;
- const auto& box = *GetScrollableArea().GetLayoutBox();
const auto* fragment = paint_info.FragmentToPaint(box);
if (!fragment)
return;
@@ -191,6 +158,9 @@ void ScrollableAreaPainter::PaintOverflowControls(
}
}
+ CullRect adjusted_cull_rect = paint_info.GetCullRect();
+ adjusted_cull_rect.MoveBy(-paint_offset);
+
if (GetScrollableArea().HorizontalScrollbar() &&
!GetScrollableArea().LayerForHorizontalScrollbar()) {
GetScrollableArea().HorizontalScrollbar()->Paint(context,
@@ -200,51 +170,27 @@ void ScrollableAreaPainter::PaintOverflowControls(
!GetScrollableArea().LayerForVerticalScrollbar()) {
GetScrollableArea().VerticalScrollbar()->Paint(context, adjusted_cull_rect);
}
+
if (!GetScrollableArea().LayerForScrollCorner()) {
// We fill our scroll corner with white if we have a scrollbar that doesn't
// run all the way up to the edge of the box.
- PaintScrollCorner(context, adjusted_paint_offset, paint_info.GetCullRect());
+ PaintScrollCorner(context, paint_offset, paint_info.GetCullRect());
// Paint our resizer last, since it sits on top of the scroll corner.
- PaintResizer(context, adjusted_paint_offset, paint_info.GetCullRect());
+ PaintResizer(context, paint_offset, paint_info.GetCullRect());
}
}
-bool ScrollableAreaPainter::OverflowControlsIntersectRect(
- const CullRect& cull_rect) const {
- const IntRect border_box =
- GetScrollableArea().GetLayoutBox()->PixelSnappedBorderBoxRect(
- GetScrollableArea().Layer()->SubpixelAccumulation());
-
- if (cull_rect.Intersects(
- GetScrollableArea().RectForHorizontalScrollbar(border_box)))
- return true;
-
- if (cull_rect.Intersects(
- GetScrollableArea().RectForVerticalScrollbar(border_box)))
- return true;
-
- if (cull_rect.Intersects(GetScrollableArea().ScrollCornerRect()))
- return true;
-
- if (cull_rect.Intersects(GetScrollableArea().ResizerCornerRect(
- border_box, kResizerForPointer)))
- return true;
-
- return false;
-}
-
-void ScrollableAreaPainter::PaintScrollCorner(
- GraphicsContext& context,
- const IntPoint& paint_offset,
- const CullRect& adjusted_cull_rect) {
+void ScrollableAreaPainter::PaintScrollCorner(GraphicsContext& context,
+ const IntPoint& paint_offset,
+ const CullRect& cull_rect) {
IntRect abs_rect = GetScrollableArea().ScrollCornerRect();
if (abs_rect.IsEmpty())
return;
abs_rect.MoveBy(paint_offset);
if (const auto* scroll_corner = GetScrollableArea().ScrollCorner()) {
- if (!adjusted_cull_rect.Intersects(abs_rect))
+ if (!cull_rect.Intersects(abs_rect))
return;
ScrollbarPainter::PaintIntoRect(*scroll_corner, context,
PhysicalOffset(paint_offset),
diff --git a/chromium/third_party/blink/renderer/core/paint/scrollable_area_painter.h b/chromium/third_party/blink/renderer/core/paint/scrollable_area_painter.h
index d6c884aaa67..86346c3d385 100644
--- a/chromium/third_party/blink/renderer/core/paint/scrollable_area_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/scrollable_area_painter.h
@@ -26,10 +26,7 @@ class ScrollableAreaPainter {
PaintLayerScrollableArea& paint_layer_scrollable_area)
: scrollable_area_(&paint_layer_scrollable_area) {}
- void PaintOverflowControls(const PaintInfo&,
- const IntPoint& paint_offset,
- bool painting_overlay_controls);
-
+ void PaintOverflowControls(const PaintInfo&, const IntPoint& paint_offset);
void PaintResizer(GraphicsContext&,
const IntPoint& paint_offset,
const CullRect&);
@@ -39,7 +36,6 @@ class ScrollableAreaPainter {
private:
void DrawPlatformResizerImage(GraphicsContext&, IntRect resizer_corner_rect);
- bool OverflowControlsIntersectRect(const CullRect&) const;
PaintLayerScrollableArea& GetScrollableArea() const;
const DisplayItemClient& DisplayItemClientForCorner() const;
diff --git a/chromium/third_party/blink/renderer/core/paint/selection_painting_utils.cc b/chromium/third_party/blink/renderer/core/paint/selection_painting_utils.cc
index 5426d6fb347..8db7227c000 100644
--- a/chromium/third_party/blink/renderer/core/paint/selection_painting_utils.cc
+++ b/chromium/third_party/blink/renderer/core/paint/selection_painting_utils.cc
@@ -9,6 +9,7 @@
#include "third_party/blink/renderer/core/dom/element_traversal.h"
#include "third_party/blink/renderer/core/dom/node.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/editing/frame_selection.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/layout/layout_theme.h"
@@ -46,10 +47,19 @@ scoped_refptr<ComputedStyle> GetUncachedSelectionStyle(Node* node) {
// If we request ::selection style for LayoutText, query ::selection style on
// the parent element instead, as that is the node for which ::selection
- // matches.
+ // matches. This should must likely have used FlatTreeTraversal, but since we
+ // don't implement inheritance of ::selection styles, it would probably break
+ // cases where you style a shadow host with ::selection and expect light tree
+ // text children to be affected by that style.
Element* element = Traversal<Element>::FirstAncestorOrSelf(*node);
- if (!element || element->IsPseudoElement())
+
+ // <content> and <shadow> elements do not have ComputedStyle, hence they will
+ // return null for StyleForPseudoElement(). Return early to avoid DCHECK
+ // failure for GetComputedStyle() inside StyleForPseudoElement() below.
+ if (!element || element->IsPseudoElement() ||
+ IsActiveV0InsertionPoint(*element)) {
return nullptr;
+ }
return element->StyleForPseudoElement(PseudoStyleRequest(kPseudoIdSelection));
}
diff --git a/chromium/third_party/blink/renderer/core/paint/selection_painting_utils.h b/chromium/third_party/blink/renderer/core/paint/selection_painting_utils.h
index bd0ff15d94b..f8953a4348a 100644
--- a/chromium/third_party/blink/renderer/core/paint/selection_painting_utils.h
+++ b/chromium/third_party/blink/renderer/core/paint/selection_painting_utils.h
@@ -8,7 +8,7 @@
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/paint/paint_phase.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/svg_container_painter.h b/chromium/third_party/blink/renderer/core/paint/svg_container_painter.h
index b81b9e653b9..9c13032ac32 100644
--- a/chromium/third_party/blink/renderer/core/paint/svg_container_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/svg_container_painter.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_SVG_CONTAINER_PAINTER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_SVG_CONTAINER_PAINTER_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/svg_filter_painter.h b/chromium/third_party/blink/renderer/core/paint/svg_filter_painter.h
index d0989c4235d..7dd90ff7c54 100644
--- a/chromium/third_party/blink/renderer/core/paint/svg_filter_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/svg_filter_painter.h
@@ -9,7 +9,7 @@
#include "base/macros.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/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/svg_foreign_object_painter.h b/chromium/third_party/blink/renderer/core/paint/svg_foreign_object_painter.h
index 095518a2849..520aac14283 100644
--- a/chromium/third_party/blink/renderer/core/paint/svg_foreign_object_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/svg_foreign_object_painter.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_SVG_FOREIGN_OBJECT_PAINTER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_SVG_FOREIGN_OBJECT_PAINTER_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/svg_image_painter.h b/chromium/third_party/blink/renderer/core/paint/svg_image_painter.h
index 84904b89ef5..f7177fa3fc5 100644
--- a/chromium/third_party/blink/renderer/core/paint/svg_image_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/svg_image_painter.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_SVG_IMAGE_PAINTER_H_
#include "third_party/blink/renderer/platform/geometry/float_size.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/svg_inline_flow_box_painter.h b/chromium/third_party/blink/renderer/core/paint/svg_inline_flow_box_painter.h
index 53adfa63184..99e5ac0225c 100644
--- a/chromium/third_party/blink/renderer/core/paint/svg_inline_flow_box_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/svg_inline_flow_box_painter.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_SVG_INLINE_FLOW_BOX_PAINTER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_SVG_INLINE_FLOW_BOX_PAINTER_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 18bc8342ec2..287e4da15b4 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
@@ -466,7 +466,7 @@ void SVGInlineTextBoxPainter::PaintText(const PaintInfo& paint_info,
text_run_paint_info.to = end_position;
context.DrawText(scaled_font, text_run_paint_info, text_origin, flags,
- text_layout_object.EnsureNodeHolder());
+ text_layout_object.EnsureNodeId());
// TODO(npm): Check that there are non-whitespace characters. See
// crbug.com/788444.
context.GetPaintController().SetTextPainted();
diff --git a/chromium/third_party/blink/renderer/core/paint/svg_inline_text_box_painter.h b/chromium/third_party/blink/renderer/core/paint/svg_inline_text_box_painter.h
index 2fd216fce31..69e1fe53a13 100644
--- a/chromium/third_party/blink/renderer/core/paint/svg_inline_text_box_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/svg_inline_text_box_painter.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/layout/svg/layout_svg_resource_paint_server.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/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/svg_mask_painter.h b/chromium/third_party/blink/renderer/core/paint/svg_mask_painter.h
index 3e854ad3e9b..af65990bf2e 100644
--- a/chromium/third_party/blink/renderer/core/paint/svg_mask_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/svg_mask_painter.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_SVG_MASK_PAINTER_H_
#include "third_party/blink/renderer/platform/geometry/float_rect.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/svg_model_object_painter.h b/chromium/third_party/blink/renderer/core/paint/svg_model_object_painter.h
index 12d300447c8..7498f380893 100644
--- a/chromium/third_party/blink/renderer/core/paint/svg_model_object_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/svg_model_object_painter.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_SVG_MODEL_OBJECT_PAINTER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_SVG_MODEL_OBJECT_PAINTER_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/svg_object_painter.h b/chromium/third_party/blink/renderer/core/paint/svg_object_painter.h
index b209d6b1521..9e4c5947bfa 100644
--- a/chromium/third_party/blink/renderer/core/paint/svg_object_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/svg_object_painter.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/layout/layout_object.h"
#include "third_party/blink/renderer/core/layout/svg/layout_svg_resource_paint_server.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/svg_root_inline_box_painter.h b/chromium/third_party/blink/renderer/core/paint/svg_root_inline_box_painter.h
index a84b66fb116..05319d2f3fa 100644
--- a/chromium/third_party/blink/renderer/core/paint/svg_root_inline_box_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/svg_root_inline_box_painter.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_SVG_ROOT_INLINE_BOX_PAINTER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_SVG_ROOT_INLINE_BOX_PAINTER_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/svg_root_painter.h b/chromium/third_party/blink/renderer/core/paint/svg_root_painter.h
index 7dfb8bc7e11..aacce7f02c2 100644
--- a/chromium/third_party/blink/renderer/core/paint/svg_root_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/svg_root_painter.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_SVG_ROOT_PAINTER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_SVG_ROOT_PAINTER_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/svg_shape_painter.h b/chromium/third_party/blink/renderer/core/paint/svg_shape_painter.h
index 29bf5087648..9c3ce882071 100644
--- a/chromium/third_party/blink/renderer/core/paint/svg_shape_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/svg_shape_painter.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_SVG_SHAPE_PAINTER_H_
#include "third_party/blink/renderer/platform/graphics/paint/paint_flags.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/skia/include/core/SkPath.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/svg_text_painter.h b/chromium/third_party/blink/renderer/core/paint/svg_text_painter.h
index ff43ec26180..cb4e44505c4 100644
--- a/chromium/third_party/blink/renderer/core/paint/svg_text_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/svg_text_painter.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_SVG_TEXT_PAINTER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_SVG_TEXT_PAINTER_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/table_cell_paint_invalidator.h b/chromium/third_party/blink/renderer/core/paint/table_cell_paint_invalidator.h
index e5a30863bac..787643f3b89 100644
--- a/chromium/third_party/blink/renderer/core/paint/table_cell_paint_invalidator.h
+++ b/chromium/third_party/blink/renderer/core/paint/table_cell_paint_invalidator.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_TABLE_CELL_PAINT_INVALIDATOR_H_
#include "third_party/blink/renderer/platform/graphics/paint_invalidation_reason.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/table_cell_painter.h b/chromium/third_party/blink/renderer/core/paint/table_cell_painter.h
index 1d8d6a3a4ba..94f569b4f5e 100644
--- a/chromium/third_party/blink/renderer/core/paint/table_cell_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/table_cell_painter.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_TABLE_CELL_PAINTER_H_
#include "third_party/blink/renderer/platform/graphics/paint/display_item.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/table_paint_invalidator.h b/chromium/third_party/blink/renderer/core/paint/table_paint_invalidator.h
index 2bcadfbd4b5..a75671905b4 100644
--- a/chromium/third_party/blink/renderer/core/paint/table_paint_invalidator.h
+++ b/chromium/third_party/blink/renderer/core/paint/table_paint_invalidator.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_TABLE_PAINT_INVALIDATOR_H_
#include "third_party/blink/renderer/platform/graphics/paint_invalidation_reason.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 1a3d51366ab..dc4d8bf81a4 100644
--- a/chromium/third_party/blink/renderer/core/paint/table_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/table_painter.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_TABLE_PAINTER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_TABLE_PAINTER_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/table_row_painter.h b/chromium/third_party/blink/renderer/core/paint/table_row_painter.h
index 298526c21b1..09716046eb4 100644
--- a/chromium/third_party/blink/renderer/core/paint/table_row_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/table_row_painter.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_TABLE_ROW_PAINTER_H_
#include "third_party/blink/renderer/core/style/shadow_data.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 f4fc4c89737..6641f3e2275 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
@@ -119,7 +119,7 @@ LayoutRect TableSectionPainter::TableAlignedRect(
LayoutRect table_aligned_rect =
layout_table_section_.LogicalRectForWritingModeAndDirection(
- local_cull_rect.ToLayoutRect());
+ local_cull_rect);
return table_aligned_rect;
}
diff --git a/chromium/third_party/blink/renderer/core/paint/table_section_painter.h b/chromium/third_party/blink/renderer/core/paint/table_section_painter.h
index 68159e9f4ea..4f19519e899 100644
--- a/chromium/third_party/blink/renderer/core/paint/table_section_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/table_section_painter.h
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/paint/paint_phase.h"
#include "third_party/blink/renderer/core/style/shadow_data.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/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/text_control_single_line_painter.h b/chromium/third_party/blink/renderer/core/paint/text_control_single_line_painter.h
index 8c9f898fef5..cd8bc96bf05 100644
--- a/chromium/third_party/blink/renderer/core/paint/text_control_single_line_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/text_control_single_line_painter.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_TEXT_CONTROL_SINGLE_LINE_PAINTER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_TEXT_CONTROL_SINGLE_LINE_PAINTER_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/paint/text_element_timing.cc b/chromium/third_party/blink/renderer/core/paint/text_element_timing.cc
index 68db930d2bf..53caeae3f97 100644
--- a/chromium/third_party/blink/renderer/core/paint/text_element_timing.cc
+++ b/chromium/third_party/blink/renderer/core/paint/text_element_timing.cc
@@ -5,7 +5,15 @@
#include "third_party/blink/renderer/core/paint/text_element_timing.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/layout/layout_view.h"
+#include "third_party/blink/renderer/core/paint/element_timing_utils.h"
+#include "third_party/blink/renderer/core/paint/image_element_timing.h"
#include "third_party/blink/renderer/core/paint/text_paint_timing_detector.h"
+#include "third_party/blink/renderer/core/timing/dom_window_performance.h"
+#include "third_party/blink/renderer/platform/geometry/int_rect.h"
+#include "third_party/blink/renderer/platform/graphics/paint/float_clip_rect.h"
+#include "third_party/blink/renderer/platform/graphics/paint/geometry_mapper.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
namespace blink {
@@ -25,18 +33,60 @@ TextElementTiming& TextElementTiming::From(LocalDOMWindow& window) {
}
TextElementTiming::TextElementTiming(LocalDOMWindow& window)
- : Supplement<LocalDOMWindow>(window) {
+ : Supplement<LocalDOMWindow>(window),
+ performance_(DOMWindowPerformance::performance(window)) {
DCHECK(RuntimeEnabledFeatures::ElementTimingEnabled(
GetSupplementable()->document()));
}
-void TextElementTiming::OnTextNodesPainted(
+// static
+FloatRect TextElementTiming::ComputeIntersectionRect(
+ const LayoutObject& object,
+ const IntRect& aggregated_visual_rect,
+ const PropertyTreeState& property_tree_state,
+ const LocalFrameView* frame_view) {
+ Node* node = object.GetNode();
+ DCHECK(node);
+ if (!NeededForElementTiming(*node))
+ return FloatRect();
+
+ return ElementTimingUtils::ComputeIntersectionRect(
+ &frame_view->GetFrame(), aggregated_visual_rect, property_tree_state);
+}
+
+void TextElementTiming::OnTextObjectsPainted(
const Deque<base::WeakPtr<TextRecord>>& text_nodes_painted) {
- // TODO(npm): implement entry creation.
+ DCHECK(performance_);
+ // If the entries cannot be exposed via PerformanceObserver nor added to the
+ // buffer, bail out.
+ if (!performance_->HasObserverFor(PerformanceEntry::kElement) &&
+ performance_->IsElementTimingBufferFull()) {
+ return;
+ }
+ for (const auto record : text_nodes_painted) {
+ Node* node = DOMNodeIds::NodeForId(record->node_id);
+ if (!node || node->IsInShadowTree())
+ continue;
+
+ // Text aggregators should be Elements!
+ DCHECK(node->IsElementNode());
+ auto* element = To<Element>(node);
+ const AtomicString& attr =
+ element->FastGetAttribute(html_names::kElementtimingAttr);
+ if (attr.IsEmpty())
+ continue;
+
+ const AtomicString& id = element->GetIdAttribute();
+ DEFINE_STATIC_LOCAL(const AtomicString, kTextPaint, ("text-paint"));
+ performance_->AddElementTiming(
+ kTextPaint, g_empty_string, record->element_timing_rect_,
+ record->paint_time, base::TimeTicks(), attr, IntSize(), id, element);
+ }
}
void TextElementTiming::Trace(blink::Visitor* visitor) {
Supplement<LocalDOMWindow>::Trace(visitor);
+ visitor->Trace(performance_);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/paint/text_element_timing.h b/chromium/third_party/blink/renderer/core/paint/text_element_timing.h
index 70b9e0174ea..f3a4c40902a 100644
--- a/chromium/third_party/blink/renderer/core/paint/text_element_timing.h
+++ b/chromium/third_party/blink/renderer/core/paint/text_element_timing.h
@@ -6,12 +6,18 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_TEXT_ELEMENT_TIMING_H_
#include "base/memory/weak_ptr.h"
+#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
+#include "third_party/blink/renderer/core/layout/layout_object.h"
+#include "third_party/blink/renderer/core/timing/window_performance.h"
#include "third_party/blink/renderer/platform/supplementable.h"
#include "third_party/blink/renderer/platform/wtf/deque.h"
namespace blink {
+class IntRect;
+class LocalFrameView;
+class PropertyTreeState;
class TextRecord;
// TextElementTiming is responsible for tracking the paint timings for groups of
@@ -28,12 +34,26 @@ class CORE_EXPORT TextElementTiming final
static TextElementTiming& From(LocalDOMWindow&);
+ static inline bool NeededForElementTiming(Node& node) {
+ auto* element = DynamicTo<Element>(node);
+ return !node.IsInShadowTree() && element &&
+ !element->FastGetAttribute(html_names::kElementtimingAttr).IsEmpty();
+ }
+
+ static FloatRect ComputeIntersectionRect(
+ const LayoutObject&,
+ const IntRect& aggregated_visual_rect,
+ const PropertyTreeState&,
+ const LocalFrameView*);
+
// Called when the swap promise queued by TextPaintTimingDetector has been
// resolved. Dispatches PerformanceElementTiming entries to WindowPerformance.
- void OnTextNodesPainted(const Deque<base::WeakPtr<TextRecord>>&);
+ void OnTextObjectsPainted(const Deque<base::WeakPtr<TextRecord>>&);
void Trace(blink::Visitor* visitor) override;
+ Member<WindowPerformance> performance_;
+
DISALLOW_COPY_AND_ASSIGN(TextElementTiming);
};
diff --git a/chromium/third_party/blink/renderer/core/paint/text_paint_style.h b/chromium/third_party/blink/renderer/core/paint/text_paint_style.h
index b333afebf69..e5411fdebd5 100644
--- a/chromium/third_party/blink/renderer/core/paint/text_paint_style.h
+++ b/chromium/third_party/blink/renderer/core/paint/text_paint_style.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/graphics/color.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 cc6f96ada4d..ae719505e1f 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
@@ -8,58 +8,42 @@
#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_file_upload_control.h"
-#include "third_party/blink/renderer/core/layout/layout_text.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/largest_contentful_paint_calculator.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"
#include "third_party/blink/renderer/platform/instrumentation/tracing/traced_value.h"
-#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
-// Calculate metrics candidate every 1 second after the first text pre-paint.
-static constexpr TimeDelta kTimerDelay = TimeDelta::FromSeconds(1);
-constexpr size_t kTextNodeNumberLimit = 5000;
+namespace {
-static bool LargeTextFirst(const base::WeakPtr<TextRecord>& a,
- const base::WeakPtr<TextRecord>& b) {
+bool LargeTextFirst(const base::WeakPtr<TextRecord>& a,
+ const base::WeakPtr<TextRecord>& b) {
DCHECK(a);
DCHECK(b);
if (a->first_size != b->first_size)
return a->first_size > b->first_size;
// This make sure that two different nodes with the same |first_size| wouldn't
// be merged in the set.
- return a->node_id > b->node_id;
+ return a->insertion_index_ < b->insertion_index_;
}
-TextPaintTimingDetector::TextPaintTimingDetector(LocalFrameView* frame_view)
- : records_manager_(),
- timer_(frame_view->GetFrame().GetTaskRunner(TaskType::kInternalDefault),
- this,
- &TextPaintTimingDetector::TimerFired),
- frame_view_(frame_view) {
- Document* document = frame_view_->GetFrame().GetDocument();
- if (document && RuntimeEnabledFeatures::ElementTimingEnabled(document)) {
- LocalDOMWindow* window = document->domWindow();
- if (window)
- records_manager_.SetTextElementTiming(&TextElementTiming::From(*window));
- }
-}
+} // namespace
+
+TextPaintTimingDetector::TextPaintTimingDetector(
+ LocalFrameView* frame_view,
+ PaintTimingDetector* paint_timing_detector,
+ PaintTimingCallbackManager* callback_manager)
+ : records_manager_(frame_view, paint_timing_detector),
+ callback_manager_(callback_manager),
+ frame_view_(frame_view) {}
-void TextPaintTimingDetector::PopulateTraceValue(
+void LargestTextPaintManager::PopulateTraceValue(
TracedValue& value,
const TextRecord& first_text_paint) {
+ // TODO(crbug.com/976893): Remove DOMNodeId.
value.SetInteger("DOMNodeId", static_cast<int>(first_text_paint.node_id));
-#ifndef NDEBUG
- value.SetString("text", first_text_paint.text);
-#endif
value.SetInteger("size", static_cast<int>(first_text_paint.first_size));
value.SetInteger("candidateIndex", ++count_candidates_);
value.SetBoolean("isMainFrame", frame_view_->GetFrame().IsMainFrame());
@@ -67,8 +51,10 @@ void TextPaintTimingDetector::PopulateTraceValue(
!frame_view_->GetFrame().LocalFrameRoot().IsMainFrame());
}
-void TextPaintTimingDetector::ReportCandidateToTrace(
+void LargestTextPaintManager::ReportCandidateToTrace(
const TextRecord& largest_text_record) {
+ if (!PaintTimingDetector::IsTracing())
+ return;
auto value = std::make_unique<TracedValue>();
PopulateTraceValue(*value, largest_text_record);
TRACE_EVENT_MARK_WITH_TIMESTAMP2("loading", "LargestTextPaint::Candidate",
@@ -77,7 +63,9 @@ void TextPaintTimingDetector::ReportCandidateToTrace(
ToTraceValue(&frame_view_->GetFrame()));
}
-void TextPaintTimingDetector::ReportNoCandidateToTrace() {
+void LargestTextPaintManager::ReportNoCandidateToTrace() {
+ if (!PaintTimingDetector::IsTracing())
+ return;
auto value = std::make_unique<TracedValue>();
value->SetInteger("candidateIndex", ++count_candidates_);
value->SetBoolean("isMainFrame", frame_view_->GetFrame().IsMainFrame());
@@ -88,79 +76,75 @@ void TextPaintTimingDetector::ReportNoCandidateToTrace() {
ToTraceValue(&frame_view_->GetFrame()));
}
-void TextPaintTimingDetector::TimerFired(TimerBase* time) {
- // Wrap |UpdateCandidate| method in TimerFired so that we can drop |time| for
- // |UpdateCandidate| in testing.
- UpdateCandidate();
-}
-
-void TextPaintTimingDetector::UpdateCandidate() {
- if (!records_manager_.IsRecordingLargestTextPaint())
- return;
-
- DCHECK(RuntimeEnabledFeatures::FirstContentfulPaintPlusPlusEnabled());
- TextRecord* largest_text_record =
- records_manager_.FindLargestPaintCandidate();
+base::WeakPtr<TextRecord> LargestTextPaintManager::UpdateCandidate() {
+ base::WeakPtr<TextRecord> largest_text_record = FindLargestPaintCandidate();
const base::TimeTicks time =
largest_text_record ? largest_text_record->paint_time : base::TimeTicks();
const uint64_t size =
largest_text_record ? largest_text_record->first_size : 0;
+ DCHECK(paint_timing_detector_);
bool changed =
- frame_view_->GetPaintTimingDetector().NotifyIfChangedLargestTextPaint(
- time, size);
- if (!changed)
- return;
-
- if (largest_text_record && !largest_text_record->paint_time.is_null())
- ReportCandidateToTrace(*largest_text_record);
- else
- ReportNoCandidateToTrace();
+ paint_timing_detector_->NotifyIfChangedLargestTextPaint(time, size);
+ if (changed) {
+ if (!time.is_null())
+ ReportCandidateToTrace(*largest_text_record);
+ else
+ ReportNoCandidateToTrace();
+ }
+ return largest_text_record;
}
void TextPaintTimingDetector::OnPaintFinished() {
if (need_update_timing_at_frame_end_) {
need_update_timing_at_frame_end_ = false;
- UpdateCandidate();
+ frame_view_->GetPaintTimingDetector()
+ .UpdateLargestContentfulPaintCandidate();
}
if (records_manager_.NeedMeausuringPaintTime()) {
- // Start repeating timer only once at the first text paint.
- if (!timer_.IsActive() && is_recording_ltp_)
- timer_.StartRepeating(kTimerDelay, FROM_HERE);
if (!awaiting_swap_promise_) {
- RegisterNotifySwapTime(
- CrossThreadBindOnce(&TextPaintTimingDetector::ReportSwapTime,
- WrapCrossThreadWeakPersistent(this)));
+ // |WrapCrossThreadWeakPersistent| guarantees that when |this| is killed,
+ // the callback function will not be invoked.
+ RegisterNotifySwapTime(WTF::Bind(&TextPaintTimingDetector::ReportSwapTime,
+ WrapCrossThreadWeakPersistent(this)));
}
}
- // Delete unneeded information from |records_manager_| if no longer recording
- // LargestTextPaint.
- if (!is_recording_ltp_ && records_manager_.IsRecordingLargestTextPaint())
- records_manager_.StopRecordingLargestTextPaint();
}
-void TextPaintTimingDetector::NotifyNodeRemoved(DOMNodeId node_id) {
+void TextPaintTimingDetector::LayoutObjectWillBeDestroyed(
+ const LayoutObject& object) {
if (!is_recording_)
return;
- if (!records_manager_.IsKnownVisibleNode(node_id))
- return;
- records_manager_.SetNodeDetachedIfNeeded(node_id);
- need_update_timing_at_frame_end_ = true;
+ if (records_manager_.IsKnownVisible(object)) {
+ records_manager_.RemoveVisibleRecord(object);
+ need_update_timing_at_frame_end_ = true;
+ } else if (records_manager_.IsKnownInvisible(object)) {
+ records_manager_.RemoveInvisibleRecord(object);
+ need_update_timing_at_frame_end_ = true;
+ }
}
void TextPaintTimingDetector::RegisterNotifySwapTime(
- ReportTimeCallback callback) {
- // ReportSwapTime on layerTreeView will queue a swap-promise, the callback is
- // called when the swap for current render frame completes or fails to happen.
- LocalFrame& frame = frame_view_->GetFrame();
- if (!frame.GetPage())
- return;
- frame.GetPage()->GetChromeClient().NotifySwapTime(frame, std::move(callback));
+ PaintTimingCallbackManager::LocalThreadCallback callback) {
+ callback_manager_->RegisterCallback(std::move(callback));
awaiting_swap_promise_ = true;
}
-void TextPaintTimingDetector::ReportSwapTime(WebWidgetClient::SwapResult result,
- base::TimeTicks timestamp) {
- records_manager_.AssignPaintTimeToQueuedNodes(timestamp);
+void TextPaintTimingDetector::ReportSwapTime(base::TimeTicks timestamp) {
+ if (!is_recording_)
+ return;
+ if (!records_manager_.HasTextElementTiming()) {
+ Document* document = frame_view_->GetFrame().GetDocument();
+ if (document && RuntimeEnabledFeatures::ElementTimingEnabled(document)) {
+ LocalDOMWindow* window = document->domWindow();
+ if (window) {
+ records_manager_.SetTextElementTiming(
+ &TextElementTiming::From(*window));
+ }
+ }
+ }
+ records_manager_.AssignPaintTimeToQueuedRecords(timestamp);
+ if (IsRecordingLargestTextPaint())
+ UpdateCandidate();
awaiting_swap_promise_ = false;
}
@@ -173,12 +157,19 @@ bool TextPaintTimingDetector::ShouldWalkObject(
Node* node = object.GetNode();
if (!node)
return false;
+ // If we have finished recording Largest Text Paint and the element is a
+ // shadow element or has no elementtiming attribute, then we should not record
+ // its text.
+ if (!records_manager_.IsRecordingLargestTextPaint() &&
+ !TextElementTiming::NeededForElementTiming(*node))
+ return false;
+
DOMNodeId node_id = DOMNodeIds::ExistingIdForNode(node);
if (node_id == kInvalidDOMNodeId)
return true;
// This metric defines the size of a text block by its first size, so we
// should not walk the object if it has been recorded.
- return !records_manager_.HasRecorded(node_id);
+ return !records_manager_.HasRecorded(object);
}
void TextPaintTimingDetector::RecordAggregatedText(
@@ -186,14 +177,6 @@ void TextPaintTimingDetector::RecordAggregatedText(
const IntRect& aggregated_visual_rect,
const PropertyTreeState& property_tree_state) {
DCHECK(ShouldWalkObject(aggregator));
- DCHECK(!records_manager_.HasTooManyNodes());
-
- Node* node = aggregator.GetNode();
- DCHECK(node);
- DOMNodeId node_id = DOMNodeIds::IdForNode(node);
- DCHECK_NE(node_id, kInvalidDOMNodeId);
-
- records_manager_.MarkNodeReattachedIfNeeded(node_id);
// The caller should check this.
DCHECK(!aggregated_visual_rect.IsEmpty());
@@ -204,143 +187,120 @@ void TextPaintTimingDetector::RecordAggregatedText(
uint64_t aggregated_size = mapped_visual_rect.Size().Area();
if (aggregated_size == 0) {
- records_manager_.RecordInvisibleNode(node_id);
+ records_manager_.RecordInvisibleObject(aggregator);
} else {
- records_manager_.RecordVisibleNode(node_id, aggregated_size, aggregator);
- }
-
- if (records_manager_.HasTooManyNodes()) {
- TRACE_EVENT_INSTANT2("loading", "TextPaintTimingDetector::OverNodeLimit",
- TRACE_EVENT_SCOPE_THREAD, "count_size_non_zero_nodes",
- records_manager_.CountVisibleNodes(),
- "count_size_zero_nodes",
- records_manager_.CountInvisibleNodes());
- StopRecordEntries();
+ records_manager_.RecordVisibleObject(
+ aggregator, aggregated_size,
+ TextElementTiming::ComputeIntersectionRect(
+ aggregator, aggregated_visual_rect, property_tree_state,
+ frame_view_));
+ if (base::Optional<PaintTimingVisualizer>& visualizer =
+ frame_view_->GetPaintTimingDetector().Visualizer()) {
+ visualizer->DumpTextDebuggingRect(aggregator, mapped_visual_rect);
+ }
}
}
-TextRecord* TextPaintTimingDetector::FindLargestPaintCandidate() {
- return records_manager_.FindLargestPaintCandidate();
-}
-
void TextPaintTimingDetector::StopRecordEntries() {
- timer_.Stop();
is_recording_ = false;
+ records_manager_.CleanUp();
}
void TextPaintTimingDetector::StopRecordingLargestTextPaint() {
- // This does not immediately call TextRecordsManager's
- // StopRecordingLargestTextPaint(). However, it stops the timer, and the next
- // time OnPaintFinished() is called, the TextRecordsManager has the last
- // chance to update LargestTextPaint (based on elements that had already been
- // painted), and THEN we call its StopRecordingLargestTextPaint() so that the
- // LargestTextPaint-only information is cleared.
- timer_.Stop();
- is_recording_ltp_ = false;
+ records_manager_.CleanUpLargestTextPaint();
}
void TextPaintTimingDetector::Trace(blink::Visitor* visitor) {
visitor->Trace(records_manager_);
visitor->Trace(frame_view_);
+ visitor->Trace(callback_manager_);
}
-TextRecordsManager::TextRecordsManager() : size_ordered_set_(&LargeTextFirst) {}
+LargestTextPaintManager::LargestTextPaintManager(
+ LocalFrameView* frame_view,
+ PaintTimingDetector* paint_timing_detector)
+ : size_ordered_set_(&LargeTextFirst),
+ frame_view_(frame_view),
+ paint_timing_detector_(paint_timing_detector) {}
-void TextRecordsManager::SetNodeDetachedIfNeeded(const DOMNodeId& node_id) {
- if (!visible_node_map_.Contains(node_id))
- return;
- if (detached_ids_.Contains(node_id))
- return;
- detached_ids_.insert(node_id);
- is_result_invalidated_ = true;
+void LargestTextPaintManager::Trace(blink::Visitor* visitor) {
+ visitor->Trace(frame_view_);
+ visitor->Trace(paint_timing_detector_);
+}
+
+void TextRecordsManager::RemoveVisibleRecord(const LayoutObject& object) {
+ DCHECK(visible_objects_.Contains(&object));
+ if (ltp_manager_) {
+ ltp_manager_->RemoveVisibleRecord(
+ visible_objects_.at(&object)->AsWeakPtr());
+ }
+ visible_objects_.erase(&object);
+ // We don't need to remove elements in |texts_queued_for_paint_time_| and
+ // |cached_largest_paint_candidate_| as they are weak ptr.
+}
+
+void TextRecordsManager::CleanUpLargestTextPaint() {
+ ltp_manager_.reset();
}
-void TextRecordsManager::AssignPaintTimeToQueuedNodes(
+void TextRecordsManager::RemoveInvisibleRecord(const LayoutObject& object) {
+ DCHECK(invisible_objects_.Contains(&object));
+ invisible_objects_.erase(&object);
+}
+
+void TextRecordsManager::AssignPaintTimeToQueuedRecords(
const base::TimeTicks& timestamp) {
// If texts_queued_for_paint_time_.size == 0, it means the array has been
// consumed in a callback earlier than this one. That violates the assumption
// that only one or zero callback will be called after one OnPaintFinished.
DCHECK_GT(texts_queued_for_paint_time_.size(), 0UL);
- for (auto& record : texts_queued_for_paint_time_) {
- DCHECK(visible_node_map_.Contains(record->node_id));
+ for (auto iterator = texts_queued_for_paint_time_.begin();
+ iterator != texts_queued_for_paint_time_.end(); ++iterator) {
+ // The record may have been removed between the callback registration and
+ // invoking.
+ base::WeakPtr<TextRecord>& record = *iterator;
+ if (!record) {
+ texts_queued_for_paint_time_.erase(iterator);
+ continue;
+ }
DCHECK_EQ(record->paint_time, base::TimeTicks());
record->paint_time = timestamp;
}
if (text_element_timing_)
- text_element_timing_->OnTextNodesPainted(texts_queued_for_paint_time_);
+ text_element_timing_->OnTextObjectsPainted(texts_queued_for_paint_time_);
texts_queued_for_paint_time_.clear();
- is_result_invalidated_ = true;
-}
-
-void TextRecordsManager::MarkNodeReattachedIfNeeded(const DOMNodeId& node_id) {
- if (!detached_ids_.Contains(node_id))
- return;
- DCHECK(visible_node_map_.Contains(node_id) ||
- invisible_node_ids_.Contains(node_id));
- detached_ids_.erase(node_id);
- is_result_invalidated_ = true;
-}
-
-bool TextRecordsManager::HasRecorded(const DOMNodeId& node_id) const {
- return visible_node_map_.Contains(node_id) ||
- invisible_node_ids_.Contains(node_id);
-}
-
-void TextRecordsManager::RecordInvisibleNode(const DOMNodeId& node_id) {
- DCHECK(!HasTooManyNodes());
- invisible_node_ids_.insert(node_id);
+ if (ltp_manager_)
+ ltp_manager_->SetCachedResultInvalidated(true);
}
-void TextRecordsManager::RecordVisibleNode(const DOMNodeId& node_id,
- const uint64_t& visual_size,
- const LayoutObject& text_object) {
- DCHECK(!HasTooManyNodes());
+void TextRecordsManager::RecordVisibleObject(
+ const LayoutObject& object,
+ const uint64_t& visual_size,
+ const FloatRect& element_timing_rect) {
DCHECK_GT(visual_size, 0u);
- std::unique_ptr<TextRecord> record =
- std::make_unique<TextRecord>(node_id, visual_size);
-#ifndef NDEBUG
- String text;
- if (text_object.IsText()) {
- text = ToLayoutText(&text_object)->GetText();
- } else if (text_object.IsFileUploadControl()) {
- text = ToLayoutFileUploadControl(&text_object)->FileTextValue();
- } else {
- text = String("NON-TEXT-OBJECT");
- }
- record->text = text;
-#endif
- if (is_recording_ltp_)
- size_ordered_set_.emplace(record->AsWeakPtr());
- QueueToMeasurePaintTime(record->AsWeakPtr());
- visible_node_map_.insert(node_id, std::move(record));
- is_result_invalidated_ = true;
-}
-void TextRecordsManager::QueueToMeasurePaintTime(
- base::WeakPtr<TextRecord> record) {
- texts_queued_for_paint_time_.push_back(std::move(record));
-}
+ Node* node = object.GetNode();
+ DCHECK(node);
+ DOMNodeId node_id = DOMNodeIds::IdForNode(node);
+ DCHECK_NE(node_id, kInvalidDOMNodeId);
+ std::unique_ptr<TextRecord> record =
+ std::make_unique<TextRecord>(node_id, visual_size, element_timing_rect);
+ base::WeakPtr<TextRecord> record_weak_ptr = record->AsWeakPtr();
+ if (ltp_manager_)
+ ltp_manager_->InsertRecord(record_weak_ptr);
-bool TextRecordsManager::HasTooManyNodes() const {
- return visible_node_map_.size() + invisible_node_ids_.size() >=
- kTextNodeNumberLimit;
+ QueueToMeasurePaintTime(record_weak_ptr);
+ visible_objects_.insert(&object, std::move(record));
}
-TextRecord* TextRecordsManager::FindLargestPaintCandidate() {
- DCHECK(is_recording_ltp_);
- DCHECK_EQ(visible_node_map_.size(), size_ordered_set_.size());
- if (!is_result_invalidated_)
+base::WeakPtr<TextRecord> LargestTextPaintManager::FindLargestPaintCandidate() {
+ if (!is_result_invalidated_ && cached_largest_paint_candidate_)
return cached_largest_paint_candidate_;
- TextRecord* new_largest_paint_candidate = nullptr;
- for (auto it = size_ordered_set_.begin(); it != size_ordered_set_.end();
- ++it) {
- // WeakPtr::IsValid() is expensive. We use raw pointer to reduce the checks.
- TextRecord* text_record = (*it).get();
+ base::WeakPtr<TextRecord> new_largest_paint_candidate = nullptr;
+ for (const auto& text_record : size_ordered_set_) {
DCHECK(text_record);
- if (detached_ids_.Contains(text_record->node_id) ||
- text_record->paint_time.is_null())
+ if (text_record->paint_time.is_null())
continue;
- DCHECK(visible_node_map_.Contains(text_record->node_id));
new_largest_paint_candidate = text_record;
break;
}
@@ -349,14 +309,23 @@ TextRecord* TextRecordsManager::FindLargestPaintCandidate() {
return new_largest_paint_candidate;
}
-void TextRecordsManager::StopRecordingLargestTextPaint() {
- is_recording_ltp_ = false;
- size_ordered_set_.clear();
- cached_largest_paint_candidate_ = nullptr;
+TextRecordsManager::TextRecordsManager(
+ LocalFrameView* frame_view,
+ PaintTimingDetector* paint_timing_detector) {
+ if (RuntimeEnabledFeatures::FirstContentfulPaintPlusPlusEnabled())
+ ltp_manager_.emplace(frame_view, paint_timing_detector);
+}
+
+void TextRecordsManager::CleanUp() {
+ visible_objects_.clear();
+ invisible_objects_.clear();
+ texts_queued_for_paint_time_.clear();
+ CleanUpLargestTextPaint();
}
void TextRecordsManager::Trace(blink::Visitor* visitor) {
visitor->Trace(text_element_timing_);
+ visitor->Trace(ltp_manager_);
}
} // namespace blink
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 196e179d494..39c878dfaf0 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
@@ -11,17 +11,14 @@
#include "third_party/blink/public/web/web_widget_client.h"
#include "third_party/blink/renderer/core/dom/dom_node_ids.h"
+#include "third_party/blink/renderer/core/paint/paint_timing_detector.h"
#include "third_party/blink/renderer/core/paint/text_element_timing.h"
-#include "third_party/blink/renderer/platform/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
-#include "third_party/blink/renderer/platform/timer.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
-#include "third_party/blink/renderer/platform/wtf/time.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
class LayoutBoxModelObject;
-class LayoutObject;
class LocalFrameView;
class PropertyTreeState;
class TextElementTiming;
@@ -29,83 +26,152 @@ class TracedValue;
class TextRecord : public base::SupportsWeakPtr<TextRecord> {
public:
- TextRecord(DOMNodeId new_node_id, uint64_t new_first_size)
- : node_id(new_node_id), first_size(new_first_size) {}
+ TextRecord(DOMNodeId new_node_id,
+ uint64_t new_first_size,
+ const FloatRect& element_timing_rect)
+ : node_id(new_node_id),
+ first_size(new_first_size),
+ element_timing_rect_(element_timing_rect) {
+ static unsigned next_insertion_index_ = 1;
+ insertion_index_ = next_insertion_index_++;
+ }
DOMNodeId node_id = kInvalidDOMNodeId;
uint64_t first_size = 0;
+ // |insertion_index_| is ordered by insertion time, used as a secondary key
+ // for ranking.
+ unsigned insertion_index_ = 0;
+ FloatRect element_timing_rect_;
// The time of the first paint after fully loaded.
base::TimeTicks paint_time = base::TimeTicks();
-#ifndef NDEBUG
- String text = "";
-#endif
DISALLOW_COPY_AND_ASSIGN(TextRecord);
};
-class TextRecordsManager {
+class CORE_EXPORT LargestTextPaintManager {
DISALLOW_NEW();
using TextRecordSetComparator = bool (*)(const base::WeakPtr<TextRecord>&,
const base::WeakPtr<TextRecord>&);
using TextRecordSet =
std::set<base::WeakPtr<TextRecord>, TextRecordSetComparator>;
- friend class TextPaintTimingDetectorTest;
public:
- TextRecordsManager();
- TextRecord* FindLargestPaintCandidate();
+ LargestTextPaintManager(LocalFrameView*, PaintTimingDetector*);
+
+ inline void RemoveVisibleRecord(base::WeakPtr<TextRecord> record) {
+ DCHECK(record);
+ size_ordered_set_.erase(record);
+ if (cached_largest_paint_candidate_.get() == record.get())
+ cached_largest_paint_candidate_ = nullptr;
+ is_result_invalidated_ = true;
+ }
+
+ base::WeakPtr<TextRecord> FindLargestPaintCandidate();
+
+ void ReportCandidateToTrace(const TextRecord&);
+ void ReportNoCandidateToTrace();
+ base::WeakPtr<TextRecord> UpdateCandidate();
+ void PopulateTraceValue(TracedValue&, const TextRecord& first_text_paint);
+ inline void SetCachedResultInvalidated(bool value) {
+ is_result_invalidated_ = value;
+ }
+
+ inline void InsertRecord(base::WeakPtr<TextRecord> record) {
+ size_ordered_set_.emplace(record);
+ SetCachedResultInvalidated(true);
+ }
+
+ void Trace(blink::Visitor*);
+
+ private:
+ friend class LargestContentfulPaintCalculatorTest;
+ friend class TextPaintTimingDetectorTest;
+
+ TextRecordSet size_ordered_set_;
+ base::WeakPtr<TextRecord> cached_largest_paint_candidate_;
+ // This is used to cache the largest text paint result for better
+ // efficiency.
+ // The result will be invalidated whenever any change is done to the
+ // variables used in |FindLargestPaintCandidate|.
+ bool is_result_invalidated_ = false;
+ unsigned count_candidates_ = 0;
+
+ Member<const LocalFrameView> frame_view_;
+ Member<PaintTimingDetector> paint_timing_detector_;
+ DISALLOW_COPY_AND_ASSIGN(LargestTextPaintManager);
+};
- void SetNodeDetachedIfNeeded(const DOMNodeId&);
- void MarkNodeReattachedIfNeeded(const DOMNodeId&);
+class CORE_EXPORT TextRecordsManager {
+ DISALLOW_NEW();
+ friend class TextPaintTimingDetectorTest;
- void RecordInvisibleNode(const DOMNodeId&);
- void RecordVisibleNode(const DOMNodeId&,
- const uint64_t& visual_size,
- const LayoutObject&);
+ public:
+ TextRecordsManager(LocalFrameView*, PaintTimingDetector*);
+
+ void RemoveVisibleRecord(const LayoutObject&);
+ void RemoveInvisibleRecord(const LayoutObject&);
+ inline void RecordInvisibleObject(const LayoutObject& object) {
+ invisible_objects_.insert(&object);
+ }
+ void RecordVisibleObject(const LayoutObject&,
+ const uint64_t& visual_size,
+ const FloatRect& element_timing_rect);
bool NeedMeausuringPaintTime() const {
return !texts_queued_for_paint_time_.IsEmpty();
}
- void AssignPaintTimeToQueuedNodes(const base::TimeTicks&);
+ void AssignPaintTimeToQueuedRecords(const base::TimeTicks&);
- bool HasTooManyNodes() const;
- bool HasRecorded(const DOMNodeId&) const;
+ inline bool HasRecorded(const LayoutObject& object) const {
+ return visible_objects_.Contains(&object) ||
+ invisible_objects_.Contains(&object);
+ }
+
+ size_t CountVisibleObjects() const { return visible_objects_.size(); }
+ size_t CountInvisibleObjects() const { return invisible_objects_.size(); }
- size_t CountVisibleNodes() const { return visible_node_map_.size(); }
- size_t CountInvisibleNodes() const { return invisible_node_ids_.size(); }
+ inline bool IsKnownVisible(const LayoutObject& object) const {
+ return visible_objects_.Contains(&object);
+ }
- bool IsKnownVisibleNode(const DOMNodeId& node_id) const {
- return visible_node_map_.Contains(node_id);
+ inline bool IsKnownInvisible(const LayoutObject& object) const {
+ return invisible_objects_.Contains(&object);
}
+ void CleanUp();
+ void CleanUpLargestTextPaint();
void StopRecordingLargestTextPaint();
- bool IsRecordingLargestTextPaint() const { return is_recording_ltp_; }
+ bool HasTextElementTiming() const { return text_element_timing_; }
void SetTextElementTiming(TextElementTiming* text_element_timing) {
text_element_timing_ = text_element_timing;
}
+ inline base::WeakPtr<TextRecord> UpdateCandidate() {
+ DCHECK(ltp_manager_);
+ return ltp_manager_->UpdateCandidate();
+ }
+
+ inline bool IsRecordingLargestTextPaint() const {
+ return ltp_manager_.has_value();
+ }
+
void Trace(blink::Visitor*);
private:
- void QueueToMeasurePaintTime(base::WeakPtr<TextRecord>);
- // This is used to cache the largest text paint result for better efficiency.
- // The result will be invalidated whenever any change is done to the variables
- // used in |FindLargestPaintCandidate|.
- bool is_result_invalidated_ = false;
- // This is used to know whether |size_ordered_set_| should be populated or
- // not, since this is used by Largest Text Paint but not by Text Element
- // Timing.
- bool is_recording_ltp_ =
- RuntimeEnabledFeatures::FirstContentfulPaintPlusPlusEnabled();
- HashMap<DOMNodeId, std::unique_ptr<TextRecord>> visible_node_map_;
- HashSet<DOMNodeId> invisible_node_ids_;
- HashSet<DOMNodeId> detached_ids_;
- // This is used to order the nodes in |visible_node_map_| so that we can find
- // the largest node efficiently. Note that the entries in |size_ordered_set_|
- // and |visible_node_map_| should always be added/deleted together.
- TextRecordSet size_ordered_set_;
+ friend class LargestContentfulPaintCalculatorTest;
+ friend class TextPaintTimingDetectorTest;
+ inline void QueueToMeasurePaintTime(base::WeakPtr<TextRecord>& record) {
+ texts_queued_for_paint_time_.push_back(std::move(record));
+ }
+
+ // Once LayoutObject* is destroyed, |visible_objects_| and
+ // |invisible_objects_| must immediately clear the corresponding record from
+ // themselves.
+ HashMap<const LayoutObject*, std::unique_ptr<TextRecord>> visible_objects_;
+ HashSet<const LayoutObject*> invisible_objects_;
+
Deque<base::WeakPtr<TextRecord>> texts_queued_for_paint_time_;
- TextRecord* cached_largest_paint_candidate_;
- WeakMember<TextElementTiming> text_element_timing_;
+ base::Optional<LargestTextPaintManager> ltp_manager_;
+ Member<TextElementTiming> text_element_timing_;
DISALLOW_COPY_AND_ASSIGN(TextRecordsManager);
};
@@ -128,53 +194,51 @@ class TextRecordsManager {
// https://docs.google.com/document/d/1DRVd4a2VU8-yyWftgOparZF-sf16daf0vfbsHuz2rws/edit#heading=h.lvno2v283uls
class CORE_EXPORT TextPaintTimingDetector final
: public GarbageCollectedFinalized<TextPaintTimingDetector> {
- using ReportTimeCallback =
- WTF::CrossThreadOnceFunction<void(WebWidgetClient::SwapResult,
- base::TimeTicks)>;
friend class TextPaintTimingDetectorTest;
public:
- TextPaintTimingDetector(LocalFrameView* frame_view);
+ explicit TextPaintTimingDetector(LocalFrameView*,
+ PaintTimingDetector*,
+ PaintTimingCallbackManager*);
bool ShouldWalkObject(const LayoutBoxModelObject&) const;
void RecordAggregatedText(const LayoutBoxModelObject& aggregator,
const IntRect& aggregated_visual_rect,
const PropertyTreeState&);
void OnPaintFinished();
- void NotifyNodeRemoved(DOMNodeId);
- TextRecord* FindLargestPaintCandidate();
+ void LayoutObjectWillBeDestroyed(const LayoutObject&);
void StopRecordEntries();
void StopRecordingLargestTextPaint();
bool IsRecording() const { return is_recording_; }
- bool FinishedReportingText() const {
- return !is_recording_ && !need_update_timing_at_frame_end_;
+ inline bool FinishedReportingText() const { return !is_recording_; }
+ void ResetCallbackManager(PaintTimingCallbackManager* manager) {
+ callback_manager_ = manager;
+ }
+ inline bool IsRecordingLargestTextPaint() const {
+ return records_manager_.IsRecordingLargestTextPaint();
+ }
+ inline base::WeakPtr<TextRecord> UpdateCandidate() {
+ return records_manager_.UpdateCandidate();
}
+ void ReportSwapTime(base::TimeTicks timestamp);
void Trace(blink::Visitor*);
private:
- void PopulateTraceValue(TracedValue&, const TextRecord& first_text_paint);
- void TimerFired(TimerBase*);
- void UpdateCandidate();
+ friend class LargestContentfulPaintCalculatorTest;
- void ReportSwapTime(WebWidgetClient::SwapResult result,
- base::TimeTicks timestamp);
- void RegisterNotifySwapTime(ReportTimeCallback callback);
- void ReportCandidateToTrace(const TextRecord&);
- void ReportNoCandidateToTrace();
+ void RegisterNotifySwapTime(
+ PaintTimingCallbackManager::LocalThreadCallback callback);
TextRecordsManager records_manager_;
+ Member<PaintTimingCallbackManager> callback_manager_;
+
// Make sure that at most one swap promise is ongoing.
bool awaiting_swap_promise_ = false;
- unsigned count_candidates_ = 0;
bool is_recording_ = true;
- bool is_recording_ltp_ =
- RuntimeEnabledFeatures::FirstContentfulPaintPlusPlusEnabled();
- bool has_records_changed_ = true;
bool need_update_timing_at_frame_end_ = false;
- TaskRunnerTimer<TextPaintTimingDetector> timer_;
- Member<LocalFrameView> frame_view_;
+ Member<const LocalFrameView> frame_view_;
DISALLOW_COPY_AND_ASSIGN(TextPaintTimingDetector);
};
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 aeda73d2dea..87aa2a4e2a2 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
@@ -5,7 +5,11 @@
#include "third_party/blink/renderer/core/paint/text_paint_timing_detector.h"
#include "base/test/test_mock_time_task_runner.h"
+#include "base/test/trace_event_analyzer.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/core/paint/paint_timing_detector.h"
+#include "third_party/blink/renderer/core/paint/paint_timing_test_helper.h"
#include "third_party/blink/renderer/core/svg/svg_text_content_element.h"
#include "third_party/blink/renderer/core/testing/core_unit_test_helper.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
@@ -14,25 +18,40 @@
namespace blink {
class TextPaintTimingDetectorTest
- : public RenderingTest,
+ : public testing::Test,
private ScopedFirstContentfulPaintPlusPlusForTest {
public:
TextPaintTimingDetectorTest()
- : RenderingTest(MakeGarbageCollected<SingleChildLocalFrameClient>()),
- ScopedFirstContentfulPaintPlusPlusForTest(true) {}
+ : ScopedFirstContentfulPaintPlusPlusForTest(true),
+ test_task_runner_(
+ base::MakeRefCounted<base::TestMockTimeTaskRunner>()) {}
+
void SetUp() override {
- RenderingTest::SetUp();
- RenderingTest::EnableCompositing();
- test_task_runner_ = base::MakeRefCounted<base::TestMockTimeTaskRunner>();
+ web_view_helper_.Initialize();
+
+ // Enable compositing on the page before running the document lifecycle.
+ web_view_helper_.GetWebView()
+ ->GetPage()
+ ->GetSettings()
+ .SetAcceleratedCompositingEnabled(true);
+
+ WebLocalFrameImpl& frame_impl = *web_view_helper_.LocalMainFrame();
+ frame_impl.ViewImpl()->MainFrameWidget()->Resize(WebSize(640, 480));
+
+ frame_test_helpers::LoadFrame(
+ web_view_helper_.GetWebView()->MainFrameImpl(), "about:blank");
+ GetDocument().View()->SetParentVisible(true);
+ GetDocument().View()->SetSelfVisible(true);
// Advance clock so it isn't 0 as rendering code asserts in that case.
AdvanceClock(base::TimeDelta::FromMicroseconds(1));
}
protected:
- LocalFrameView& GetFrameView() { return *GetFrame().View(); }
+ LocalFrameView& GetFrameView() { return *GetFrame()->View(); }
PaintTimingDetector& GetPaintTimingDetector() {
return GetFrameView().GetPaintTimingDetector();
}
+ Document& GetDocument() { return *GetFrame()->GetDocument(); }
IntRect GetViewportRect(LocalFrameView& view) {
ScrollableArea* scrollable_area = view.GetScrollableArea();
@@ -40,53 +59,110 @@ class TextPaintTimingDetectorTest
return scrollable_area->VisibleContentRect();
}
- LocalFrameView& GetChildFrameView() { return *ChildFrame().View(); }
+ LocalFrameView& GetChildFrameView() {
+ return *To<LocalFrame>(GetFrame()->Tree().FirstChild())->View();
+ }
+ Document* GetChildDocument() {
+ return To<LocalFrame>(GetFrame()->Tree().FirstChild())->GetDocument();
+ }
+
+ TextPaintTimingDetector* GetTextPaintTimingDetector() {
+ return GetPaintTimingDetector().GetTextPaintTimingDetector();
+ }
- unsigned CountVisibleTexts() {
- if (!GetPaintTimingDetector().GetTextPaintTimingDetector())
- return 0u;
+ TextPaintTimingDetector* GetChildFrameTextPaintTimingDetector() {
+ return GetChildFrameView()
+ .GetPaintTimingDetector()
+ .GetTextPaintTimingDetector();
+ }
- return GetPaintTimingDetector()
- .GetTextPaintTimingDetector()
- ->records_manager_.visible_node_map_.size() -
- GetPaintTimingDetector()
- .GetTextPaintTimingDetector()
- ->records_manager_.detached_ids_.size();
+ base::Optional<LargestTextPaintManager>& GetLargestTextPaintManager() {
+ return GetTextPaintTimingDetector()->records_manager_.ltp_manager_;
}
- unsigned CountRankingSetSize() {
- return GetPaintTimingDetector()
- .GetTextPaintTimingDetector()
- ->records_manager_.size_ordered_set_.size();
+ wtf_size_t CountVisibleTexts() {
+ DCHECK(GetTextPaintTimingDetector());
+ return GetTextPaintTimingDetector()
+ ->records_manager_.visible_objects_.size();
}
- unsigned CountDetachedTexts() {
- return GetPaintTimingDetector()
- .GetTextPaintTimingDetector()
- ->records_manager_.detached_ids_.size();
+ wtf_size_t CountRankingSetSize() {
+ DCHECK(GetTextPaintTimingDetector());
+ return GetLargestTextPaintManager()->size_ordered_set_.size();
+ }
+
+ wtf_size_t CountInvisibleTexts() {
+ return GetTextPaintTimingDetector()
+ ->records_manager_.invisible_objects_.size();
+ }
+
+ wtf_size_t TextQueuedForPaintTimeSize() {
+ return GetTextPaintTimingDetector()
+ ->records_manager_.texts_queued_for_paint_time_.size();
+ }
+
+ wtf_size_t ContainerTotalSize() {
+ return CountVisibleTexts() + CountRankingSetSize() + CountInvisibleTexts() +
+ TextQueuedForPaintTimeSize();
+ }
+
+ void SimulateInputEvent() {
+ GetPaintTimingDetector().NotifyInputEvent(WebInputEvent::Type::kMouseDown);
}
void InvokeCallback() {
- TextPaintTimingDetector* detector =
- GetPaintTimingDetector().GetTextPaintTimingDetector();
- detector->ReportSwapTime(WebWidgetClient::SwapResult::kDidSwap,
- test_task_runner_->NowTicks());
+ DCHECK_GT(mock_callback_manager_->CountCallbacks(), 0u);
+ InvokeSwapTimeCallback(mock_callback_manager_);
+ }
+
+ void ChildFrameSwapTimeCallBack() {
+ DCHECK_GT(child_frame_mock_callback_manager_->CountCallbacks(), 0u);
+ InvokeSwapTimeCallback(child_frame_mock_callback_manager_);
+ }
+
+ void InvokeSwapTimeCallback(
+ MockPaintTimingCallbackManager* callback_manager) {
+ callback_manager->InvokeSwapTimeCallback(test_task_runner_->NowTicks());
+ // Outside the tests, this is invoked by
+ // |PaintTimingCallbackManagerImpl::ReportPaintTime|.
+ GetLargestTextPaintManager()->UpdateCandidate();
}
- TimeTicks LargestPaintStoredResult() {
+ base::TimeTicks LargestPaintStoredResult() {
return GetPaintTimingDetector().largest_text_paint_time_;
}
+ void SetBodyInnerHTML(const std::string& content) {
+ frame_test_helpers::LoadHTMLString(
+ web_view_helper_.GetWebView()->MainFrameImpl(), content,
+ KURL("http://test.com"));
+ mock_callback_manager_ =
+ MakeGarbageCollected<MockPaintTimingCallbackManager>();
+ GetTextPaintTimingDetector()->ResetCallbackManager(mock_callback_manager_);
+ UpdateAllLifecyclePhases();
+ }
+
+ void SetChildBodyInnerHTML(const String& content) {
+ GetChildDocument()->SetBaseURLOverride(KURL("http://test.com"));
+ GetChildDocument()->body()->SetInnerHTMLFromString(content,
+ ASSERT_NO_EXCEPTION);
+ child_frame_mock_callback_manager_ =
+ MakeGarbageCollected<MockPaintTimingCallbackManager>();
+ GetChildFrameTextPaintTimingDetector()->ResetCallbackManager(
+ child_frame_mock_callback_manager_);
+ UpdateAllLifecyclePhases();
+ }
+
+ void UpdateAllLifecyclePhases() {
+ GetDocument().View()->UpdateAllLifecyclePhases(
+ DocumentLifecycle::LifecycleUpdateReason::kTest);
+ }
+
// This only triggers ReportSwapTime in main frame.
void UpdateAllLifecyclePhasesAndSimulateSwapTime() {
- UpdateAllLifecyclePhasesForTest();
- TextPaintTimingDetector* detector =
- GetPaintTimingDetector().GetTextPaintTimingDetector();
- if (detector &&
- !detector->records_manager_.texts_queued_for_paint_time_.empty()) {
- detector->ReportSwapTime(WebWidgetClient::SwapResult::kDidSwap,
- test_task_runner_->NowTicks());
- }
+ UpdateAllLifecyclePhases();
+ while (mock_callback_manager_->CountCallbacks() > 0)
+ InvokeCallback();
}
size_t CountPendingSwapTime(LocalFrameView& frame_view) {
@@ -95,18 +171,6 @@ class TextPaintTimingDetectorTest
return detector->records_manager_.texts_queued_for_paint_time_.size();
}
- void ChildFrameSwapTimeCallBack() {
- GetChildFrameView()
- .GetPaintTimingDetector()
- .GetTextPaintTimingDetector()
- ->ReportSwapTime(WebWidgetClient::SwapResult::kDidSwap,
- test_task_runner_->NowTicks());
- }
-
- void UpdateCandidate() {
- GetPaintTimingDetector().GetTextPaintTimingDetector()->UpdateCandidate();
- }
-
Element* AppendFontBlockToBody(String content) {
Element* font = GetDocument().CreateRawElement(html_names::kFontTag);
font->setAttribute(html_names::kSizeAttr, AtomicString("5"));
@@ -127,18 +191,15 @@ class TextPaintTimingDetectorTest
return div;
}
- TextRecord* TextRecordOfLargestTextPaint() {
- return GetFrameView()
- .GetPaintTimingDetector()
- .GetTextPaintTimingDetector()
- ->FindLargestPaintCandidate();
+ base::WeakPtr<TextRecord> TextRecordOfLargestTextPaint() {
+ return GetLargestTextPaintManager()->FindLargestPaintCandidate();
}
- TextRecord* ChildFrameTextRecordOfLargestTextPaint() {
+ base::WeakPtr<TextRecord> ChildFrameTextRecordOfLargestTextPaint() {
return GetChildFrameView()
.GetPaintTimingDetector()
.GetTextPaintTimingDetector()
- ->FindLargestPaintCandidate();
+ ->records_manager_.ltp_manager_->FindLargestPaintCandidate();
}
void SetFontSize(Element* font_element, uint16_t font_size) {
@@ -161,8 +222,17 @@ class TextPaintTimingDetectorTest
test_task_runner_->FastForwardBy(delta);
}
+ void LoadAhem() { web_view_helper_.LoadAhem(); }
+
private:
+ LocalFrame* GetFrame() {
+ return web_view_helper_.GetWebView()->MainFrameImpl()->GetFrame();
+ }
+
+ frame_test_helpers::WebViewHelper web_view_helper_;
scoped_refptr<base::TestMockTimeTaskRunner> test_task_runner_;
+ Persistent<MockPaintTimingCallbackManager> mock_callback_manager_;
+ Persistent<MockPaintTimingCallbackManager> child_frame_mock_callback_manager_;
};
TEST_F(TextPaintTimingDetectorTest, LargestTextPaint_NoText) {
@@ -181,6 +251,93 @@ TEST_F(TextPaintTimingDetectorTest, LargestTextPaint_OneText) {
DOMNodeIds::ExistingIdForNode(only_text));
}
+TEST_F(TextPaintTimingDetectorTest, InsertionOrderIsSecondaryRankingKey) {
+ SetBodyInnerHTML(R"HTML(
+ )HTML");
+ Element* first = AppendDivElementToBody("text");
+ AppendDivElementToBody("text");
+ AppendDivElementToBody("text");
+ UpdateAllLifecyclePhasesAndSimulateSwapTime();
+ EXPECT_EQ(TextRecordOfLargestTextPaint()->node_id,
+ DOMNodeIds::ExistingIdForNode(first));
+}
+
+TEST_F(TextPaintTimingDetectorTest, LargestTextPaint_TraceEvent_Candidate) {
+ using trace_analyzer::Query;
+ trace_analyzer::Start("*");
+ {
+ SetBodyInnerHTML(R"HTML(
+ )HTML");
+ AppendDivElementToBody("The only text");
+ UpdateAllLifecyclePhasesAndSimulateSwapTime();
+ }
+ auto analyzer = trace_analyzer::Stop();
+ trace_analyzer::TraceEventVector events;
+ Query q = Query::EventNameIs("LargestTextPaint::Candidate");
+ analyzer->FindEvents(q, &events);
+ EXPECT_EQ(1u, events.size());
+ EXPECT_EQ("loading", events[0]->category);
+
+ EXPECT_TRUE(events[0]->HasArg("frame"));
+
+ EXPECT_TRUE(events[0]->HasArg("data"));
+ std::unique_ptr<base::Value> arg;
+ EXPECT_TRUE(events[0]->GetArgAsValue("data", &arg));
+ base::DictionaryValue* arg_dict;
+ EXPECT_TRUE(arg->GetAsDictionary(&arg_dict));
+ DOMNodeId node_id;
+ EXPECT_TRUE(arg_dict->GetInteger("DOMNodeId", &node_id));
+ EXPECT_GT(node_id, 0);
+ int size;
+ EXPECT_TRUE(arg_dict->GetInteger("size", &size));
+ EXPECT_GT(size, 0);
+ DOMNodeId candidate_index;
+ EXPECT_TRUE(arg_dict->GetInteger("candidateIndex", &candidate_index));
+ EXPECT_EQ(candidate_index, 1);
+ bool is_main_frame;
+ EXPECT_TRUE(arg_dict->GetBoolean("isMainFrame", &is_main_frame));
+ EXPECT_EQ(true, is_main_frame);
+ bool is_oopif;
+ EXPECT_TRUE(arg_dict->GetBoolean("isOOPIF", &is_oopif));
+ EXPECT_EQ(false, is_oopif);
+}
+
+TEST_F(TextPaintTimingDetectorTest, LargestTextPaint_TraceEvent_NoCandidate) {
+ using trace_analyzer::Query;
+ trace_analyzer::Start("*");
+ {
+ SetBodyInnerHTML(R"HTML(
+ )HTML");
+ Element* element = AppendDivElementToBody("text");
+ UpdateAllLifecyclePhasesAndSimulateSwapTime();
+ RemoveElement(element);
+ UpdateAllLifecyclePhases();
+ }
+ auto analyzer = trace_analyzer::Stop();
+ trace_analyzer::TraceEventVector events;
+ Query q = Query::EventNameIs("LargestTextPaint::NoCandidate");
+ analyzer->FindEvents(q, &events);
+ EXPECT_EQ(1u, events.size());
+ EXPECT_EQ("loading", events[0]->category);
+
+ EXPECT_TRUE(events[0]->HasArg("frame"));
+
+ EXPECT_TRUE(events[0]->HasArg("data"));
+ std::unique_ptr<base::Value> arg;
+ EXPECT_TRUE(events[0]->GetArgAsValue("data", &arg));
+ base::DictionaryValue* arg_dict;
+ EXPECT_TRUE(arg->GetAsDictionary(&arg_dict));
+ DOMNodeId candidate_index;
+ EXPECT_TRUE(arg_dict->GetInteger("candidateIndex", &candidate_index));
+ EXPECT_EQ(candidate_index, 2);
+ bool is_main_frame;
+ EXPECT_TRUE(arg_dict->GetBoolean("isMainFrame", &is_main_frame));
+ EXPECT_EQ(true, is_main_frame);
+ bool is_oopif;
+ EXPECT_TRUE(arg_dict->GetBoolean("isOOPIF", &is_oopif));
+ EXPECT_EQ(false, is_oopif);
+}
+
TEST_F(TextPaintTimingDetectorTest, AggregationBySelfPaintingInlineElement) {
SetBodyInnerHTML(R"HTML(
<div style="background: yellow">
@@ -215,12 +372,11 @@ TEST_F(TextPaintTimingDetectorTest, NodeRemovedBeforeAssigningSwapTime) {
<div id="remove">The only text</div>
</div>
)HTML");
- UpdateAllLifecyclePhasesForTest();
+ UpdateAllLifecyclePhases();
GetDocument().getElementById("parent")->RemoveChild(
GetDocument().getElementById("remove"));
InvokeCallback();
EXPECT_EQ(CountVisibleTexts(), 0u);
- EXPECT_EQ(CountDetachedTexts(), 1u);
}
TEST_F(TextPaintTimingDetectorTest, LargestTextPaint_LargestText) {
@@ -240,22 +396,20 @@ TEST_F(TextPaintTimingDetectorTest, LargestTextPaint_LargestText) {
}
TEST_F(TextPaintTimingDetectorTest, UpdateResultWhenCandidateChanged) {
- TimeTicks time1 = NowTicks();
+ base::TimeTicks time1 = NowTicks();
SetBodyInnerHTML(R"HTML(
<div>small text</div>
)HTML");
UpdateAllLifecyclePhasesAndSimulateSwapTime();
- UpdateCandidate();
- TimeTicks time2 = NowTicks();
- TimeTicks first_largest = LargestPaintStoredResult();
+ base::TimeTicks time2 = NowTicks();
+ base::TimeTicks first_largest = LargestPaintStoredResult();
EXPECT_GE(first_largest, time1);
EXPECT_GE(time2, first_largest);
AppendDivElementToBody("a long-long-long text");
UpdateAllLifecyclePhasesAndSimulateSwapTime();
- UpdateCandidate();
- TimeTicks time3 = NowTicks();
- TimeTicks second_largest = LargestPaintStoredResult();
+ base::TimeTicks time3 = NowTicks();
+ base::TimeTicks second_largest = LargestPaintStoredResult();
EXPECT_GE(second_largest, time2);
EXPECT_GE(time3, second_largest);
}
@@ -292,19 +446,19 @@ TEST_F(TextPaintTimingDetectorTest, VisitSameNodeTwiceBeforePaintTimeIsSet) {
TEST_F(TextPaintTimingDetectorTest, LargestTextPaint_ReportFirstPaintTime) {
base::TimeTicks start_time = NowTicks();
- AdvanceClock(TimeDelta::FromSecondsD(1));
+ AdvanceClock(base::TimeDelta::FromSecondsD(1));
SetBodyInnerHTML(R"HTML(
)HTML");
Element* text = AppendDivElementToBody("text");
UpdateAllLifecyclePhasesAndSimulateSwapTime();
- AdvanceClock(TimeDelta::FromSecondsD(1));
+ AdvanceClock(base::TimeDelta::FromSecondsD(1));
text->setAttribute(html_names::kStyleAttr,
AtomicString("position:fixed;left:30px"));
UpdateAllLifecyclePhasesAndSimulateSwapTime();
- AdvanceClock(TimeDelta::FromSecondsD(1));
- TextRecord* record = TextRecordOfLargestTextPaint();
+ AdvanceClock(base::TimeDelta::FromSecondsD(1));
+ base::WeakPtr<TextRecord> record = TextRecordOfLargestTextPaint();
EXPECT_TRUE(record);
- EXPECT_EQ(record->paint_time, start_time + TimeDelta::FromSecondsD(1));
+ EXPECT_EQ(record->paint_time, start_time + base::TimeDelta::FromSecondsD(1));
}
TEST_F(TextPaintTimingDetectorTest,
@@ -339,19 +493,67 @@ TEST_F(TextPaintTimingDetectorTest, LargestTextPaint_IgnoreRemovedText) {
DOMNodeIds::ExistingIdForNode(small_text));
}
+TEST_F(TextPaintTimingDetectorTest,
+ RemoveRecordFromAllContainerAfterTextRemoval) {
+ SetBodyInnerHTML(R"HTML(
+ )HTML");
+ Element* text = AppendDivElementToBody("text");
+ UpdateAllLifecyclePhasesAndSimulateSwapTime();
+ EXPECT_EQ(ContainerTotalSize(), 2u);
+
+ RemoveElement(text);
+ EXPECT_EQ(ContainerTotalSize(), 0u);
+}
+
+TEST_F(TextPaintTimingDetectorTest,
+ RemoveRecordFromAllContainerAfterRepeatedAttachAndDetach) {
+ SetBodyInnerHTML(R"HTML(
+ )HTML");
+ Element* text1 = AppendDivElementToBody("text");
+ UpdateAllLifecyclePhasesAndSimulateSwapTime();
+ EXPECT_EQ(ContainerTotalSize(), 2u);
+
+ Element* text2 = AppendDivElementToBody("text2");
+ UpdateAllLifecyclePhasesAndSimulateSwapTime();
+ EXPECT_EQ(ContainerTotalSize(), 4u);
+
+ RemoveElement(text1);
+ EXPECT_EQ(ContainerTotalSize(), 2u);
+
+ GetDocument().body()->AppendChild(text1);
+ UpdateAllLifecyclePhasesAndSimulateSwapTime();
+ EXPECT_EQ(ContainerTotalSize(), 4u);
+
+ RemoveElement(text1);
+ EXPECT_EQ(ContainerTotalSize(), 2u);
+
+ RemoveElement(text2);
+ EXPECT_EQ(ContainerTotalSize(), 0u);
+}
+
+TEST_F(TextPaintTimingDetectorTest,
+ DestroyLargestTextPaintMangerAfterUserInput) {
+ SetBodyInnerHTML(R"HTML(
+ )HTML");
+ AppendDivElementToBody("text");
+ UpdateAllLifecyclePhasesAndSimulateSwapTime();
+ EXPECT_TRUE(GetLargestTextPaintManager());
+
+ SimulateInputEvent();
+ EXPECT_FALSE(GetLargestTextPaintManager());
+}
+
TEST_F(TextPaintTimingDetectorTest, LargestTextPaint_ReportLastNullCandidate) {
SetBodyInnerHTML(R"HTML(
)HTML");
Element* text = AppendDivElementToBody("text to remove");
UpdateAllLifecyclePhasesAndSimulateSwapTime();
- UpdateCandidate();
EXPECT_EQ(TextRecordOfLargestTextPaint()->node_id,
DOMNodeIds::ExistingIdForNode(text));
EXPECT_NE(LargestPaintStoredResult(), base::TimeTicks());
RemoveElement(text);
UpdateAllLifecyclePhasesAndSimulateSwapTime();
- UpdateCandidate();
EXPECT_FALSE(TextRecordOfLargestTextPaint());
EXPECT_EQ(LargestPaintStoredResult(), base::TimeTicks());
}
@@ -367,7 +569,6 @@ TEST_F(TextPaintTimingDetectorTest,
DOMNodeIds::ExistingIdForNode(short_text));
}
-// Depite that the l
TEST_F(TextPaintTimingDetectorTest, LargestTextPaint_CompareSizesAtFirstPaint) {
SetBodyInnerHTML(R"HTML(
)HTML");
@@ -405,18 +606,18 @@ TEST_F(TextPaintTimingDetectorTest, CaptureFileUploadController) {
DOMNodeIds::ExistingIdForNode(element));
}
-TEST_F(TextPaintTimingDetectorTest, NotCapturingListMarkers) {
+TEST_F(TextPaintTimingDetectorTest, CapturingListMarkers) {
SetBodyInnerHTML(R"HTML(
<ul>
- <li></li>
+ <li>List item</li>
</ul>
<ol>
- <li></li>
+ <li>Another list item</li>
</ol>
)HTML");
UpdateAllLifecyclePhasesAndSimulateSwapTime();
- EXPECT_EQ(CountVisibleTexts(), 0u);
+ EXPECT_EQ(CountVisibleTexts(), 2u);
}
TEST_F(TextPaintTimingDetectorTest, CaptureSVGText) {
@@ -426,8 +627,7 @@ TEST_F(TextPaintTimingDetectorTest, CaptureSVGText) {
</svg>
)HTML");
- SVGTextContentElement* elem =
- ToSVGTextContentElement(GetDocument().QuerySelector("text"));
+ auto* elem = To<SVGTextContentElement>(GetDocument().QuerySelector("text"));
UpdateAllLifecyclePhasesAndSimulateSwapTime();
EXPECT_EQ(CountVisibleTexts(), 1u);
@@ -435,26 +635,6 @@ TEST_F(TextPaintTimingDetectorTest, CaptureSVGText) {
DOMNodeIds::ExistingIdForNode(elem));
}
-TEST_F(TextPaintTimingDetectorTest, StopRecordingOverNodeLimit) {
- SetBodyInnerHTML(R"HTML(
- )HTML");
- UpdateAllLifecyclePhasesAndSimulateSwapTime();
-
- for (int i = 1; i <= 4999; i++)
- AppendDivElementToBody(WTF::String::Number(i), "position:fixed;left:0px");
-
- UpdateAllLifecyclePhasesAndSimulateSwapTime();
-
- AppendDivElementToBody(WTF::String::Number(5000));
- UpdateAllLifecyclePhasesAndSimulateSwapTime();
- // Reached limit, so stopped recording and now should have 0 texts.
- EXPECT_EQ(CountVisibleTexts(), 0u);
-
- AppendDivElementToBody(WTF::String::Number(5001));
- UpdateAllLifecyclePhasesAndSimulateSwapTime();
- EXPECT_EQ(CountVisibleTexts(), 0u);
-}
-
// This is for comparison with the ClippedByViewport test.
TEST_F(TextPaintTimingDetectorTest, NormalTextUnclipped) {
SetBodyInnerHTML(R"HTML(
@@ -528,11 +708,11 @@ TEST_F(TextPaintTimingDetectorTest, Iframe) {
SetBodyInnerHTML(R"HTML(
<iframe width=100px height=100px></iframe>
)HTML");
- SetChildFrameHTML("A");
- UpdateAllLifecyclePhasesForTest();
+ SetChildBodyInnerHTML("A");
+ UpdateAllLifecyclePhases();
EXPECT_EQ(CountPendingSwapTime(GetChildFrameView()), 1u);
ChildFrameSwapTimeCallBack();
- TextRecord* text = ChildFrameTextRecordOfLargestTextPaint();
+ base::WeakPtr<TextRecord> text = ChildFrameTextRecordOfLargestTextPaint();
EXPECT_TRUE(text);
}
@@ -540,14 +720,14 @@ TEST_F(TextPaintTimingDetectorTest, Iframe_ClippedByViewport) {
SetBodyInnerHTML(R"HTML(
<iframe width=100px height=100px></iframe>
)HTML");
- SetChildFrameHTML(R"HTML(
+ SetChildBodyInnerHTML(R"HTML(
<style>
#d { margin-top: 200px }
</style>
<div id='d'>text</div>
)HTML");
DCHECK_EQ(GetViewportRect(GetChildFrameView()).Height(), 100);
- UpdateAllLifecyclePhasesForTest();
+ UpdateAllLifecyclePhases();
EXPECT_EQ(CountPendingSwapTime(GetChildFrameView()), 0u);
}
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 9bf5699f0dd..e1eafe0ac1d 100644
--- a/chromium/third_party/blink/renderer/core/paint/text_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/text_painter.cc
@@ -30,17 +30,17 @@ void TextPainter::Paint(unsigned start_offset,
unsigned end_offset,
unsigned length,
const TextPaintStyle& text_style,
- const NodeHolder& node_holder) {
+ DOMNodeId node_id) {
GraphicsContextStateSaver state_saver(graphics_context_, false);
UpdateGraphicsContext(text_style, state_saver);
if (combined_text_) {
graphics_context_.Save();
combined_text_->TransformToInlineCoordinates(graphics_context_,
text_bounds_.ToLayoutRect());
- PaintInternal<kPaintText>(start_offset, end_offset, length, node_holder);
+ PaintInternal<kPaintText>(start_offset, end_offset, length, node_id);
graphics_context_.Restore();
} else {
- PaintInternal<kPaintText>(start_offset, end_offset, length, node_holder);
+ PaintInternal<kPaintText>(start_offset, end_offset, length, node_id);
}
if (!emphasis_mark_.IsEmpty()) {
@@ -51,7 +51,7 @@ void TextPainter::Paint(unsigned start_offset,
PaintEmphasisMarkForCombinedText();
} else {
PaintInternal<kPaintEmphasisMark>(start_offset, end_offset, length,
- node_holder);
+ node_id);
}
}
}
@@ -60,7 +60,7 @@ template <TextPainter::PaintInternalStep step>
void TextPainter::PaintInternalRun(TextRunPaintInfo& text_run_paint_info,
unsigned from,
unsigned to,
- const NodeHolder& node_holder) {
+ DOMNodeId node_id) {
DCHECK(from <= text_run_paint_info.run.length());
DCHECK(to <= text_run_paint_info.run.length());
@@ -74,7 +74,7 @@ void TextPainter::PaintInternalRun(TextRunPaintInfo& text_run_paint_info,
} else {
DCHECK(step == kPaintText);
graphics_context_.DrawText(font_, text_run_paint_info,
- FloatPoint(text_origin_), node_holder);
+ FloatPoint(text_origin_), node_id);
}
}
@@ -82,19 +82,19 @@ template <TextPainter::PaintInternalStep Step>
void TextPainter::PaintInternal(unsigned start_offset,
unsigned end_offset,
unsigned truncation_point,
- const NodeHolder& node_holder) {
+ DOMNodeId node_id) {
TextRunPaintInfo text_run_paint_info(run_);
if (start_offset <= end_offset) {
PaintInternalRun<Step>(text_run_paint_info, start_offset, end_offset,
- node_holder);
+ node_id);
} else {
if (end_offset > 0) {
PaintInternalRun<Step>(text_run_paint_info, ellipsis_offset_, end_offset,
- node_holder);
+ node_id);
}
if (start_offset < truncation_point) {
PaintInternalRun<Step>(text_run_paint_info, start_offset,
- truncation_point, node_holder);
+ truncation_point, node_id);
}
}
}
diff --git a/chromium/third_party/blink/renderer/core/paint/text_painter.h b/chromium/third_party/blink/renderer/core/paint/text_painter.h
index 8ab421041e5..e6d2208d392 100644
--- a/chromium/third_party/blink/renderer/core/paint/text_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/text_painter.h
@@ -5,9 +5,9 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_TEXT_PAINTER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_TEXT_PAINTER_H_
-#include "third_party/blink/renderer/core/content_capture/content_holder.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/paint/text_painter_base.h"
+#include "third_party/blink/renderer/platform/graphics/dom_node_id.h"
namespace blink {
@@ -47,20 +47,20 @@ class CORE_EXPORT TextPainter : public TextPainterBase {
unsigned end_offset,
unsigned length,
const TextPaintStyle&,
- const NodeHolder& node_holder);
+ DOMNodeId node_id);
private:
template <PaintInternalStep step>
void PaintInternalRun(TextRunPaintInfo&,
unsigned from,
unsigned to,
- const NodeHolder& node_holder);
+ DOMNodeId node_id);
template <PaintInternalStep step>
void PaintInternal(unsigned start_offset,
unsigned end_offset,
unsigned truncation_point,
- const NodeHolder& node_holder);
+ DOMNodeId node_id);
void PaintEmphasisMarkForCombinedText();
diff --git a/chromium/third_party/blink/renderer/core/paint/text_painter_base.h b/chromium/third_party/blink/renderer/core/paint/text_painter_base.h
index 4c6bf8bf2f9..4b139148cd4 100644
--- a/chromium/third_party/blink/renderer/core/paint/text_painter_base.h
+++ b/chromium/third_party/blink/renderer/core/paint/text_painter_base.h
@@ -13,7 +13,7 @@
#include "third_party/blink/renderer/platform/fonts/font.h"
#include "third_party/blink/renderer/platform/graphics/color.h"
#include "third_party/blink/renderer/platform/transforms/affine_transform.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
namespace blink {
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 0a907d2e14d..e63a1c9e5aa 100644
--- a/chromium/third_party/blink/renderer/core/paint/theme_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/theme_painter.cc
@@ -24,14 +24,15 @@
#include "build/build_config.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_rect.h"
+#include "third_party/blink/renderer/core/frame/deprecation.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/html/forms/html_data_list_element.h"
#include "third_party/blink/renderer/core/html/forms/html_data_list_options_collection.h"
#include "third_party/blink/renderer/core/html/forms/html_input_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"
#include "third_party/blink/renderer/core/html/forms/html_text_area_element.h"
+#include "third_party/blink/renderer/core/html/forms/spin_button_element.h"
#include "third_party/blink/renderer/core/html/parser/html_parser_idioms.h"
#include "third_party/blink/renderer/core/html/shadow/shadow_element_names.h"
#include "third_party/blink/renderer/core/input_type_names.h"
@@ -42,6 +43,7 @@
#include "third_party/blink/renderer/core/style/computed_style.h"
#include "third_party/blink/renderer/platform/graphics/graphics_context_state_saver.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_canvas.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "ui/native_theme/native_theme.h"
// The methods in this file are shared by all themes on every platform.
@@ -94,6 +96,34 @@ ThemePainter::ThemePainter() = default;
#define COUNT_APPEARANCE(doc, feature) \
doc.CountUse(WebFeature::kCSSValueAppearance##feature##Rendered)
+#define DEPRECATE_APPEARANCE(doc, feature) \
+ Deprecation::CountDeprecation( \
+ doc, WebFeature::kCSSValueAppearance##feature##Rendered)
+
+void CountAppearanceTextFieldPart(const Node* node) {
+ if (!node) {
+ return;
+ }
+ UseCounter::Count(node->GetDocument(),
+ WebFeature::kCSSValueAppearanceTextFieldRendered);
+ WebFeature feature =
+ WebFeature::kCSSValueAppearanceTextFieldForOthersRendered;
+ if (auto* input = ToHTMLInputElementOrNull(node)) {
+ const AtomicString& type = input->type();
+ if (type == input_type_names::kSearch) {
+ feature = WebFeature::kCSSValueAppearanceTextFieldForSearch;
+ } else if (input->IsTextField()) {
+ feature = WebFeature::kCSSValueAppearanceTextFieldForTextField;
+ } else if (IsMultipleFieldsTemporalInput(type)) {
+ feature = WebFeature::kCSSValueAppearanceTextFieldForTemporalRendered;
+ }
+ }
+ if (feature == WebFeature::kCSSValueAppearanceTextFieldForOthersRendered) {
+ Deprecation::CountDeprecation(node->GetDocument(), feature);
+ } else {
+ UseCounter::Count(node->GetDocument(), feature);
+ }
+}
// Returns true; Needs CSS painting and/or PaintBorderOnly().
bool ThemePainter::Paint(const LayoutObject& o,
@@ -109,7 +139,8 @@ bool ThemePainter::Paint(const LayoutObject& o,
if (part == kButtonPart && node) {
if (IsHTMLAnchorElement(node)) {
- UseCounter::Count(doc, WebFeature::kCSSValueAppearanceButtonForAnchor);
+ Deprecation::CountDeprecation(
+ doc, WebFeature::kCSSValueAppearanceButtonForAnchor);
COUNT_APPEARANCE(doc, ButtonForNonButton);
} else if (IsHTMLButtonElement(node)) {
UseCounter::Count(doc, WebFeature::kCSSValueAppearanceButtonForButton);
@@ -122,6 +153,19 @@ bool ThemePainter::Paint(const LayoutObject& o,
} else {
COUNT_APPEARANCE(doc, ButtonForNonButton);
COUNT_APPEARANCE(doc, ButtonForOthers);
+ if (IsA<HTMLSelectElement>(node) &&
+ To<HTMLSelectElement>(node)->UsesMenuList()) {
+ DEPRECATE_APPEARANCE(doc, ButtonForSelect);
+ } else {
+ const AtomicString& type =
+ To<Element>(node)->getAttribute(html_names::kTypeAttr);
+ // https://github.com/twbs/bootstrap/pull/29053
+ if (type == "button" || type == "reset" || type == "submit") {
+ COUNT_APPEARANCE(doc, ButtonForBootstrapLooseSelector);
+ } else {
+ COUNT_APPEARANCE(doc, ButtonForOthers2);
+ }
+ }
}
}
@@ -131,28 +175,28 @@ bool ThemePainter::Paint(const LayoutObject& o,
COUNT_APPEARANCE(doc, Checkbox);
auto* input = ToHTMLInputElementOrNull(node);
if (!input || input->type() != input_type_names::kCheckbox)
- COUNT_APPEARANCE(doc, CheckboxForOthers);
+ DEPRECATE_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() != input_type_names::kRadio)
- COUNT_APPEARANCE(doc, RadioForOthers);
+ DEPRECATE_APPEARANCE(doc, RadioForOthers);
return PaintRadio(node, o.GetDocument(), style, paint_info, r);
}
case kPushButtonPart: {
COUNT_APPEARANCE(doc, PushButton);
auto* input = ToHTMLInputElementOrNull(node);
if (!input || !input->IsTextButton())
- COUNT_APPEARANCE(doc, PushButtonForOthers);
+ DEPRECATE_APPEARANCE(doc, PushButtonForOthers);
return PaintButton(node, o.GetDocument(), style, paint_info, r);
}
case kSquareButtonPart: {
COUNT_APPEARANCE(doc, SquareButton);
auto* input = ToHTMLInputElementOrNull(node);
if (!input || input->type() != input_type_names::kColor)
- COUNT_APPEARANCE(doc, SquareButtonForOthers);
+ DEPRECATE_APPEARANCE(doc, SquareButtonForOthers);
return PaintButton(node, o.GetDocument(), style, paint_info, r);
}
case kButtonPart:
@@ -160,36 +204,38 @@ bool ThemePainter::Paint(const LayoutObject& o,
return PaintButton(node, o.GetDocument(), style, paint_info, r);
case kInnerSpinButtonPart: {
COUNT_APPEARANCE(doc, InnerSpinButton);
- auto* element = ToElementOrNull(node);
- if (!element || !element->IsSpinButtonElement())
- COUNT_APPEARANCE(doc, InnerSpinButtonForOthers);
+ if (!DynamicTo<SpinButtonElement>(node))
+ DEPRECATE_APPEARANCE(doc, InnerSpinButtonForOthers);
return PaintInnerSpinButton(node, style, paint_info, r);
}
case kMenulistPart:
COUNT_APPEARANCE(doc, MenuList);
if (!IsHTMLSelectElement(node) && !IsMenulistInput(node))
- COUNT_APPEARANCE(doc, MenuListForOthers);
+ DEPRECATE_APPEARANCE(doc, MenuListForOthers);
return PaintMenuList(node, o.GetDocument(), style, paint_info, r);
case kMeterPart:
+ if (node && !IsA<HTMLMeterElement>(node) &&
+ !IsA<HTMLMeterElement>(node->OwnerShadowHost()))
+ DEPRECATE_APPEARANCE(doc, MeterForOthers);
return true;
case kProgressBarPart:
COUNT_APPEARANCE(doc, ProgressBar);
if (!o.IsProgress())
- COUNT_APPEARANCE(doc, ProgressBarForOthers);
+ DEPRECATE_APPEARANCE(doc, ProgressBarForOthers);
// Note that |-webkit-appearance: progress-bar| works only for <progress>.
return PaintProgressBar(o, paint_info, r);
case kSliderHorizontalPart: {
COUNT_APPEARANCE(doc, SliderHorizontal);
auto* input = ToHTMLInputElementOrNull(node);
if (!input || input->type() != input_type_names::kRange)
- COUNT_APPEARANCE(doc, SliderHorizontalForOthers);
+ DEPRECATE_APPEARANCE(doc, SliderHorizontalForOthers);
return PaintSliderTrack(o, paint_info, r);
}
case kSliderVerticalPart: {
COUNT_APPEARANCE(doc, SliderVertical);
auto* input = ToHTMLInputElementOrNull(node);
if (!input || input->type() != input_type_names::kRange)
- COUNT_APPEARANCE(doc, SliderVerticalForOthers);
+ DEPRECATE_APPEARANCE(doc, SliderVerticalForOthers);
return PaintSliderTrack(o, paint_info, r);
}
case kSliderThumbHorizontalPart: {
@@ -197,7 +243,7 @@ bool ThemePainter::Paint(const LayoutObject& o,
auto* input =
ToHTMLInputElementOrNull(node ? node->OwnerShadowHost() : nullptr);
if (!input || input->type() != input_type_names::kRange)
- COUNT_APPEARANCE(doc, SliderThumbHorizontalForOthers);
+ DEPRECATE_APPEARANCE(doc, SliderThumbHorizontalForOthers);
return PaintSliderThumb(node, style, paint_info, r);
}
case kSliderThumbVerticalPart: {
@@ -205,7 +251,7 @@ bool ThemePainter::Paint(const LayoutObject& o,
auto* input =
ToHTMLInputElementOrNull(node ? node->OwnerShadowHost() : nullptr);
if (!input || input->type() != input_type_names::kRange)
- COUNT_APPEARANCE(doc, SliderThumbVerticalForOthers);
+ DEPRECATE_APPEARANCE(doc, SliderThumbVerticalForOthers);
return PaintSliderThumb(node, style, paint_info, r);
}
case kMediaSliderPart:
@@ -214,22 +260,37 @@ bool ThemePainter::Paint(const LayoutObject& o,
case kMediaVolumeSliderThumbPart:
return true;
case kMenulistButtonPart:
+ return true;
case kTextFieldPart:
+ if (!RuntimeEnabledFeatures::FormControlsRefreshEnabled()) {
+ return true;
+ }
+ CountAppearanceTextFieldPart(node);
+ return PaintTextField(node, style, paint_info, r);
case kTextAreaPart:
- return true;
+ if (!RuntimeEnabledFeatures::FormControlsRefreshEnabled()) {
+ return true;
+ }
+ if (node) {
+ const auto& doc = node->GetDocument();
+ COUNT_APPEARANCE(doc, TextArea);
+ if (!IsHTMLTextAreaElement(node))
+ DEPRECATE_APPEARANCE(doc, TextAreaForOthers);
+ }
+ return PaintTextArea(node, style, paint_info, r);
case kSearchFieldPart: {
COUNT_APPEARANCE(doc, SearchField);
auto* input = ToHTMLInputElementOrNull(node);
if (!input || input->type() != input_type_names::kSearch)
- COUNT_APPEARANCE(doc, SearchFieldForOthers);
+ DEPRECATE_APPEARANCE(doc, SearchFieldForOthers);
return PaintSearchField(node, style, paint_info, r);
}
case kSearchFieldCancelButtonPart: {
COUNT_APPEARANCE(doc, SearchCancel);
- auto* element = ToElementOrNull(node);
+ auto* element = DynamicTo<Element>(node);
if (!element || !element->OwnerShadowHost()) {
COUNT_APPEARANCE(doc, SearchCancelForOthers);
- COUNT_APPEARANCE(doc, SearchCancelForOthers2);
+ DEPRECATE_APPEARANCE(doc, SearchCancelForOthers2);
} else {
const AtomicString& shadow_id =
element->FastGetAttribute(html_names::kIdAttr);
@@ -239,11 +300,16 @@ bool ThemePainter::Paint(const LayoutObject& o,
COUNT_APPEARANCE(doc, SearchCancelForOthers);
} else {
COUNT_APPEARANCE(doc, SearchCancelForOthers);
- COUNT_APPEARANCE(doc, SearchCancelForOthers2);
+ DEPRECATE_APPEARANCE(doc, SearchCancelForOthers2);
}
}
return PaintSearchFieldCancelButton(o, paint_info, r);
}
+ case kListboxPart:
+ if (!IsA<HTMLSelectElement>(node) ||
+ To<HTMLSelectElement>(node)->UsesMenuList())
+ DEPRECATE_APPEARANCE(doc, ListboxForOthers);
+ return true;
default:
break;
}
@@ -260,31 +326,20 @@ bool ThemePainter::PaintBorderOnly(const Node* node,
// Call the appropriate paint method based off the appearance value.
switch (style.Appearance()) {
case kTextFieldPart:
- if (node) {
- UseCounter::Count(node->GetDocument(),
- WebFeature::kCSSValueAppearanceTextFieldRendered);
- WebFeature feature =
- WebFeature::kCSSValueAppearanceTextFieldForOthersRendered;
- if (auto* input = ToHTMLInputElementOrNull(node)) {
- const AtomicString& type = input->type();
- if (type == input_type_names::kSearch) {
- feature = WebFeature::kCSSValueAppearanceTextFieldForSearch;
- } else if (input->IsTextField()) {
- feature = WebFeature::kCSSValueAppearanceTextFieldForTextField;
- } else if (IsMultipleFieldsTemporalInput(type)) {
- feature =
- WebFeature::kCSSValueAppearanceTextFieldForTemporalRendered;
- }
- }
- UseCounter::Count(node->GetDocument(), feature);
+ if (RuntimeEnabledFeatures::FormControlsRefreshEnabled()) {
+ return false;
}
+ CountAppearanceTextFieldPart(node);
return PaintTextField(node, style, paint_info, r);
case kTextAreaPart:
+ if (RuntimeEnabledFeatures::FormControlsRefreshEnabled()) {
+ return false;
+ }
if (node) {
const auto& doc = node->GetDocument();
COUNT_APPEARANCE(doc, TextArea);
if (!IsHTMLTextAreaElement(node))
- COUNT_APPEARANCE(doc, TextAreaForOthers);
+ DEPRECATE_APPEARANCE(doc, TextAreaForOthers);
}
return PaintTextArea(node, style, paint_info, r);
case kMenulistButtonPart:
@@ -330,7 +385,7 @@ bool ThemePainter::PaintDecorations(const Node* node,
case kMenulistButtonPart:
COUNT_APPEARANCE(document, MenuListButton);
if (!IsHTMLSelectElement(node) && !IsMenulistInput(node))
- COUNT_APPEARANCE(document, MenuListButtonForOthers);
+ DEPRECATE_APPEARANCE(document, MenuListButtonForOthers);
return PaintMenuListButton(node, document, style, paint_info, r);
case kTextFieldPart:
case kTextAreaPart:
diff --git a/chromium/third_party/blink/renderer/core/paint/theme_painter.h b/chromium/third_party/blink/renderer/core/paint/theme_painter.h
index 6ab02542b7c..4ffa1cae58d 100644
--- a/chromium/third_party/blink/renderer/core/paint/theme_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/theme_painter.h
@@ -24,7 +24,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_THEME_PAINTER_H_
#include "third_party/blink/renderer/platform/theme_types.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 61a4d03687f..3468fe9691b 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
@@ -28,6 +28,8 @@
#include "third_party/blink/public/platform/web_rect.h"
#include "third_party/blink/public/platform/web_theme_engine.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.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/layout/layout_object.h"
#include "third_party/blink/renderer/core/layout/layout_progress.h"
#include "third_party/blink/renderer/core/layout/layout_theme_default.h"
@@ -149,6 +151,7 @@ bool ThemePainterDefault::PaintCheckbox(const Node* node,
const IntRect& rect) {
WebThemeEngine::ExtraParams extra_params;
cc::PaintCanvas* canvas = paint_info.context.Canvas();
+ extra_params.button = WebThemeEngine::ButtonExtraParams();
extra_params.button.checked = LayoutTheme::IsChecked(node);
extra_params.button.indeterminate = LayoutTheme::IsIndeterminate(node);
@@ -177,6 +180,7 @@ bool ThemePainterDefault::PaintRadio(const Node* node,
const IntRect& rect) {
WebThemeEngine::ExtraParams extra_params;
cc::PaintCanvas* canvas = paint_info.context.Canvas();
+ extra_params.button = WebThemeEngine::ButtonExtraParams();
extra_params.button.checked = LayoutTheme::IsChecked(node);
Platform::Current()->ThemeEngine()->Paint(canvas, WebThemeEngine::kPartRadio,
@@ -192,6 +196,7 @@ bool ThemePainterDefault::PaintButton(const Node* node,
const IntRect& rect) {
WebThemeEngine::ExtraParams extra_params;
cc::PaintCanvas* canvas = paint_info.context.Canvas();
+ extra_params.button = WebThemeEngine::ButtonExtraParams();
extra_params.button.has_border = true;
extra_params.button.background_color =
UseMockTheme() ? 0xffc0c0c0 : kDefaultButtonBackgroundColor;
@@ -326,8 +331,10 @@ void ThemePainterDefault::SetupMenuListArrow(
extra_params.menu_list.arrow_size = arrow_size;
} else {
// TODO(tkent): This should be 7.0 to match scroll bar buttons.
- float arrow_size = 6.0 * arrow_scale_factor;
- // Put the 6px arrow at the center of paddingForArrow area.
+ float arrow_size =
+ (RuntimeEnabledFeatures::FormControlsRefreshEnabled() ? 12.0 : 6.0) *
+ arrow_scale_factor;
+ // Put the arrow at the center of paddingForArrow area.
// |arrowX| is the left position for Aura theme engine.
extra_params.menu_list.arrow_x =
(style.Direction() == TextDirection::kRtl)
@@ -346,6 +353,7 @@ bool ThemePainterDefault::PaintSliderTrack(const LayoutObject& o,
cc::PaintCanvas* canvas = i.context.Canvas();
extra_params.slider.vertical =
o.StyleRef().Appearance() == kSliderVerticalPart;
+ extra_params.slider.in_drag = false;
PaintSliderTicks(o, i, rect);
@@ -362,6 +370,23 @@ bool ThemePainterDefault::PaintSliderTrack(const LayoutObject& o,
i.context.Translate(-unzoomed_rect.X(), -unzoomed_rect.Y());
}
+ const Node* node = o.GetNode();
+ auto* input = ToHTMLInputElementOrNull(node);
+ extra_params.slider.thumb_x = 0;
+ extra_params.slider.thumb_y = 0;
+ if (input) {
+ Element* thumb_element = input->UserAgentShadowRoot()
+ ? input->UserAgentShadowRoot()->getElementById(
+ shadow_element_names::SliderThumb())
+ : nullptr;
+ LayoutBox* thumb = thumb_element ? thumb_element->GetLayoutBox() : nullptr;
+ if (thumb) {
+ IntRect thumb_rect = PixelSnappedIntRect(thumb->FrameRect());
+ extra_params.slider.thumb_x = thumb_rect.X() / zoom_level;
+ extra_params.slider.thumb_y = thumb_rect.Y() / zoom_level;
+ }
+ }
+
Platform::Current()->ThemeEngine()->Paint(
canvas, WebThemeEngine::kPartSliderTrack, GetWebThemeState(o.GetNode()),
WebRect(unzoomed_rect), &extra_params);
diff --git a/chromium/third_party/blink/renderer/core/paint/video_painter.h b/chromium/third_party/blink/renderer/core/paint/video_painter.h
index 8dd89eaa995..c8f0ccbd4ac 100644
--- a/chromium/third_party/blink/renderer/core/paint/video_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/video_painter.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_VIDEO_PAINTER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_VIDEO_PAINTER_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 01f4ca725ad..0fddf98bf04 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
@@ -67,8 +67,8 @@ class VideoPainterTestForCAP : private ScopedCompositeAfterPaintForTest,
MakeGarbageCollected<VideoStubLocalFrameClient>()) {}
void SetUp() override {
- PaintControllerPaintTestBase::SetUp();
EnableCompositing();
+ PaintControllerPaintTestBase::SetUp();
GetDocument().SetURL(KURL(NullURL(), "https://example.com/"));
}
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 0e72fb2b251..aca247eda9d 100644
--- a/chromium/third_party/blink/renderer/core/paint/view_painter.cc
+++ b/chromium/third_party/blink/renderer/core/paint/view_painter.cc
@@ -37,7 +37,12 @@ void ViewPainter::PaintBoxDecorationBackground(const PaintInfo& paint_info) {
return;
bool has_touch_action_rect = layout_view_.HasEffectiveAllowedTouchAction();
- if (!layout_view_.HasBoxDecorationBackground() && !has_touch_action_rect)
+ bool paints_scroll_hit_test =
+ RuntimeEnabledFeatures::CompositeAfterPaintEnabled() &&
+ (layout_view_.GetScrollableArea() &&
+ layout_view_.GetScrollableArea()->ScrollsOverflow());
+ if (!layout_view_.HasBoxDecorationBackground() && !has_touch_action_rect &&
+ !paints_scroll_hit_test)
return;
// The background rect always includes at least the visible content size.
@@ -50,8 +55,10 @@ void ViewPainter::PaintBoxDecorationBackground(const PaintInfo& paint_info) {
const DisplayItemClient* background_client = &layout_view_;
base::Optional<ScopedPaintChunkProperties> scoped_scroll_property;
- if (BoxDecorationData::IsPaintingScrollingBackground(paint_info,
- layout_view_)) {
+ bool painting_scrolling_background =
+ BoxDecorationData::IsPaintingScrollingBackground(paint_info,
+ layout_view_);
+ if (painting_scrolling_background) {
// 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
@@ -76,6 +83,16 @@ void ViewPainter::PaintBoxDecorationBackground(const PaintInfo& paint_info) {
.RecordHitTestData(paint_info, PhysicalRect(background_rect),
*background_client);
}
+
+ if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) {
+ // 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 non-scrolling background.
+ if (paints_scroll_hit_test && !painting_scrolling_background) {
+ BoxPainter(layout_view_)
+ .RecordScrollHitTestData(paint_info, *background_client);
+ }
+ }
}
// This function handles background painting for the LayoutView.
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 36563c5a9c3..652ffd6cb9e 100644
--- a/chromium/third_party/blink/renderer/core/paint/view_painter.h
+++ b/chromium/third_party/blink/renderer/core/paint/view_painter.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_VIEW_PAINTER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_VIEW_PAINTER_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
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 01c0508e406..e9b0e289f30 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
@@ -9,6 +9,7 @@
#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/scroll_hit_test_display_item.h"
using testing::ElementsAre;
@@ -126,6 +127,9 @@ TEST_P(ViewPainterTest, DocumentBackgroundWithScroll) {
)HTML");
if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) {
+ // The scroll hit test should be before the scrolled contents to ensure the
+ // hit test does not prevent the background squashing with the scrolling
+ // contents.
EXPECT_THAT(
RootPaintController().GetDisplayItemList(),
ElementsAre(IsSameId(&GetLayoutView(), DisplayItem::kScrollHitTest),
@@ -157,6 +161,81 @@ TEST_P(ViewPainterTest, DocumentBackgroundWithScroll) {
}
}
+TEST_P(ViewPainterTest, FrameScrollHitTestProperties) {
+ // This test depends on the CompositeAfterPaint behavior of painting solid
+ // color backgrounds into both the non-scrolled and scrolled spaces.
+ if (!RuntimeEnabledFeatures::CompositeAfterPaintEnabled())
+ return;
+ SetBodyInnerHTML(R"HTML(
+ <style>
+ ::-webkit-scrollbar { display: none; }
+ body { margin: 0; }
+ #child { width: 100px; height: 2000px; background: green; }
+ </style>
+ <div id='child'></div>
+ )HTML");
+
+ auto& html =
+ To<LayoutBlock>(*GetDocument().documentElement()->GetLayoutObject());
+ auto& child = *GetLayoutObjectByElementId("child");
+
+ // The scroll hit test should be before the scrolled contents to ensure the
+ // hit test does not prevent the background squashing with the scrolling
+ // contents.
+ EXPECT_THAT(RootPaintController().GetDisplayItemList(),
+ ElementsAre(IsSameId(&GetLayoutView(), kScrollHitTestType),
+ IsSameId(&ViewScrollingBackgroundClient(),
+ kDocumentBackgroundType),
+ IsSameId(&child, kBackgroundType)));
+
+ const auto& paint_chunks = RootPaintController().PaintChunks();
+ const auto& view_contents_properties =
+ GetLayoutView().FirstFragment().ContentsProperties();
+ EXPECT_THAT(
+ paint_chunks,
+ ElementsAre(
+ IsPaintChunk(
+ 0, 1,
+ PaintChunk::Id(*GetLayoutView().Layer(),
+ DisplayItem::kLayerChunkBackground),
+ GetLayoutView().FirstFragment().LocalBorderBoxProperties()),
+ IsPaintChunk(1, 2,
+ PaintChunk::Id(ViewScrollingBackgroundClient(),
+ kDocumentBackgroundType),
+ view_contents_properties),
+ IsPaintChunk(2, 3,
+ PaintChunk::Id(*html.Layer(),
+ kNonScrollingContentsBackgroundChunkType),
+ html.FirstFragment().ContentsProperties())));
+
+ // The scroll hit test should not be scrolled and should not be clipped.
+ 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());
+ 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.
+ 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());
+ 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
+ // translation node and the contents should be scrolled by this node.
+ const auto& scroll_hit_test_display_item =
+ static_cast<const ScrollHitTestDisplayItem&>(
+ RootPaintController()
+ .GetDisplayItemList()[scroll_hit_test_chunk.begin_index]);
+ EXPECT_EQ(&contents_transform,
+ &scroll_hit_test_display_item.scroll_offset_node());
+}
+
class ViewPainterTouchActionRectTest : public ViewPainterTest {
public:
void SetUp() override {
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 f0277aaffa3..59539512869 100644
--- a/chromium/third_party/blink/renderer/core/probe/core_probes.cc
+++ b/chromium/third_party/blink/renderer/core/probe/core_probes.cc
@@ -47,19 +47,19 @@ void* AsyncId(void* task) {
}
} // namespace
-TimeTicks ProbeBase::CaptureStartTime() const {
+base::TimeTicks ProbeBase::CaptureStartTime() const {
if (start_time_.is_null())
- start_time_ = CurrentTimeTicks();
+ start_time_ = base::TimeTicks::Now();
return start_time_;
}
-TimeTicks ProbeBase::CaptureEndTime() const {
+base::TimeTicks ProbeBase::CaptureEndTime() const {
if (end_time_.is_null())
- end_time_ = CurrentTimeTicks();
+ end_time_ = base::TimeTicks::Now();
return end_time_;
}
-TimeDelta ProbeBase::Duration() const {
+base::TimeDelta ProbeBase::Duration() const {
DCHECK(!start_time_.is_null());
return CaptureEndTime() - start_time_;
}
diff --git a/chromium/third_party/blink/renderer/core/probe/core_probes.h b/chromium/third_party/blink/renderer/core/probe/core_probes.h
index fd043739a99..841b31d43cb 100644
--- a/chromium/third_party/blink/renderer/core/probe/core_probes.h
+++ b/chromium/third_party/blink/renderer/core/probe/core_probes.h
@@ -56,13 +56,13 @@ class CORE_EXPORT ProbeBase {
STACK_ALLOCATED();
public:
- TimeTicks CaptureStartTime() const;
- TimeTicks CaptureEndTime() const;
- TimeDelta Duration() const;
+ base::TimeTicks CaptureStartTime() const;
+ base::TimeTicks CaptureEndTime() const;
+ base::TimeDelta Duration() const;
private:
- mutable TimeTicks start_time_;
- mutable TimeTicks end_time_;
+ mutable base::TimeTicks start_time_;
+ mutable base::TimeTicks end_time_;
};
class CORE_EXPORT AsyncTask {
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 f170f74c46c..ae60ed0922f 100644
--- a/chromium/third_party/blink/renderer/core/probe/core_probes.pidl
+++ b/chromium/third_party/blink/renderer/core/probe/core_probes.pidl
@@ -97,7 +97,7 @@ interface CoreProbes {
void DidReceiveData(CoreProbeSink*, uint64_t identifier, DocumentLoader*, const char* data, uint64_t data_length);
void DidReceiveBlob(CoreProbeSink*, uint64_t identifier, DocumentLoader*, BlobDataHandle*);
void DidReceiveEncodedDataLength(CoreProbeSink*, DocumentLoader* loader, uint64_t identifier, size_t encoded_data_length);
- void DidFinishLoading(CoreProbeSink*, uint64_t identifier, DocumentLoader*, TimeTicks finish_time, int64_t encoded_data_length, int64_t decoded_body_length, bool should_report_corb_blocking);
+ void DidFinishLoading(CoreProbeSink*, uint64_t identifier, DocumentLoader*, base::TimeTicks finish_time, int64_t encoded_data_length, int64_t decoded_body_length, bool should_report_corb_blocking);
void DidReceiveCorsRedirectResponse(ExecutionContext*, uint64_t identifier, DocumentLoader*, const ResourceResponse&, Resource*);
void DidFailLoading(CoreProbeSink*, uint64_t identifier, DocumentLoader*, const ResourceError&);
void WillSendEventSourceRequest(ExecutionContext*);
@@ -127,7 +127,7 @@ interface CoreProbes {
void WillSendWebSocketHandshakeRequest([Keep] ExecutionContext*, uint64_t identifier, network::mojom::blink::WebSocketHandshakeRequest* request);
void DidReceiveWebSocketHandshakeResponse([Keep] ExecutionContext*, uint64_t identifier, network::mojom::blink::WebSocketHandshakeRequest* request, network::mojom::blink::WebSocketHandshakeResponse* response);
void DidCloseWebSocket([Keep] ExecutionContext*, uint64_t identifier);
- void DidReceiveWebSocketMessage(ExecutionContext*, uint64_t identifier, int opcode, bool masked, const char* payload, size_t payload_length);
+ void DidReceiveWebSocketMessage(ExecutionContext*, uint64_t identifier, int opcode, bool masked, const Vector<base::span<const char>>& data);
void DidSendWebSocketMessage(ExecutionContext*, uint64_t identifier, int opcode, bool masked, const char* payload, size_t payload_length);
void DidReceiveWebSocketMessageError(ExecutionContext*, uint64_t identifier, const String& error_message);
void NetworkStateChanged([Keep] LocalFrame*, bool online);
diff --git a/chromium/third_party/blink/renderer/core/resize_observer/resize_observation.cc b/chromium/third_party/blink/renderer/core/resize_observer/resize_observation.cc
index 8b1cb60c1c3..df02d02ff3f 100644
--- a/chromium/third_party/blink/renderer/core/resize_observer/resize_observation.cc
+++ b/chromium/third_party/blink/renderer/core/resize_observer/resize_observation.cc
@@ -39,10 +39,9 @@ size_t ResizeObservation::TargetDepth() {
LayoutSize ResizeObservation::ComputeTargetSize() const {
if (target_) {
if (LayoutObject* layout_object = target_->GetLayoutObject()) {
- auto* svg_element = DynamicTo<SVGElement>(target_.Get());
- if (svg_element && svg_element->IsSVGGraphicsElement()) {
- SVGGraphicsElement& svg = ToSVGGraphicsElement(*target_);
- return LayoutSize(svg.GetBBox().Size());
+ if (auto* svg_graphics_element =
+ DynamicTo<SVGGraphicsElement>(target_.Get())) {
+ return LayoutSize(svg_graphics_element->GetBBox().Size());
}
if (layout_object->IsBox())
return ToLayoutBox(layout_object)->ContentSize();
diff --git a/chromium/third_party/blink/renderer/core/resize_observer/resize_observer.idl b/chromium/third_party/blink/renderer/core/resize_observer/resize_observer.idl
index 11ccfc826ac..8e09fdd4212 100644
--- a/chromium/third_party/blink/renderer/core/resize_observer/resize_observer.idl
+++ b/chromium/third_party/blink/renderer/core/resize_observer/resize_observer.idl
@@ -2,13 +2,14 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// https://wicg.github.io/ResizeObserver/#resize-observer-callback
+// https://drafts.csswg.org/resize-observer-1/#resize-observer-callback
callback ResizeObserverCallback = void (sequence<ResizeObserverEntry> entries, ResizeObserver observer);
-// https://wicg.github.io/ResizeObserver/#resize-observer-interface
+// https://drafts.csswg.org/resize-observer-1/#resize-observer-interface
[
+ Exposed=Window,
ActiveScriptWrappable,
Constructor(ResizeObserverCallback callback),
MeasureAs=ResizeObserver_Constructor,
diff --git a/chromium/third_party/blink/renderer/core/resize_observer/resize_observer_entry.idl b/chromium/third_party/blink/renderer/core/resize_observer/resize_observer_entry.idl
index 835d47f6dff..969b0f53a73 100644
--- a/chromium/third_party/blink/renderer/core/resize_observer/resize_observer_entry.idl
+++ b/chromium/third_party/blink/renderer/core/resize_observer/resize_observer_entry.idl
@@ -2,8 +2,9 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// https://wicg.github.io/ResizeObserver/#resize-observer-entry-interface
+// https://drafts.csswg.org/resize-observer-1/#resize-observer-entry-interface
+[Exposed=Window]
interface ResizeObserverEntry {
readonly attribute Element target;
readonly attribute DOMRectReadOnly contentRect;
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 f1e7866fa6b..f45c6a764c0 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
@@ -64,14 +64,14 @@ class FrameThrottlingTest : public PaintTestConfigurations, public SimTest {
if (own_graphics_layer) {
result += own_graphics_layer->CcLayer()
->touch_action_region()
- .region()
+ .GetAllRegions()
.GetRegionComplexity();
}
GraphicsLayer* child_graphics_layer = layer->GraphicsLayerBacking();
if (child_graphics_layer && child_graphics_layer != own_graphics_layer) {
result += child_graphics_layer->CcLayer()
->touch_action_region()
- .region()
+ .GetAllRegions()
.GetRegionComplexity();
}
return result;
diff --git a/chromium/third_party/blink/renderer/core/scheduler/scheduler_affecting_features_test.cc b/chromium/third_party/blink/renderer/core/scheduler/scheduler_affecting_features_test.cc
index 2725de3acf0..7c1c09e8b94 100644
--- a/chromium/third_party/blink/renderer/core/scheduler/scheduler_affecting_features_test.cc
+++ b/chromium/third_party/blink/renderer/core/scheduler/scheduler_affecting_features_test.cc
@@ -30,8 +30,8 @@ class SchedulingAffectingFeaturesTest : public SimTest {
// Some features (e.g. document.load) are expected to appear in almost
// any output. Filter them out to make most of the tests simpler.
- std::vector<SchedulingPolicy::Feature> GetNonTrivialMainFrameFeatures() {
- std::vector<SchedulingPolicy::Feature> result;
+ Vector<SchedulingPolicy::Feature> GetNonTrivialMainFrameFeatures() {
+ Vector<SchedulingPolicy::Feature> result;
for (SchedulingPolicy::Feature feature :
MainFrameScheduler()
->GetActiveFeaturesTrackedForBackForwardCacheMetrics()) {
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 2420d3bad75..f3e336e9ac3 100644
--- a/chromium/third_party/blink/renderer/core/scheduler/throttling_test.cc
+++ b/chromium/third_party/blink/renderer/core/scheduler/throttling_test.cc
@@ -48,7 +48,7 @@ TEST_F(DisableBackgroundThrottlingIsRespectedTest,
// Run delayed tasks for 1 second. All tasks should be completed
// with throttling disabled.
- test::RunDelayedTasks(TimeDelta::FromSeconds(1));
+ test::RunDelayedTasks(base::TimeDelta::FromSeconds(1));
EXPECT_THAT(ConsoleMessages(), ElementsAre("called f", "called f", "called f",
"called f", "called f"));
@@ -74,7 +74,7 @@ TEST_F(BackgroundPageThrottlingTest, BackgroundPagesAreThrottled) {
GetDocument().GetPage()->GetPageScheduler()->SetPageVisible(false);
// Make sure that we run no more than one task a second.
- test::RunDelayedTasks(TimeDelta::FromMilliseconds(3000));
+ test::RunDelayedTasks(base::TimeDelta::FromMilliseconds(3000));
EXPECT_THAT(
ConsoleMessages(),
AnyOf(ElementsAre("called f", "called f", "called f"),
diff --git a/chromium/third_party/blink/renderer/core/scheduler/virtual_time_test.cc b/chromium/third_party/blink/renderer/core/scheduler/virtual_time_test.cc
index 2174623fb76..c5e9daa2f7e 100644
--- a/chromium/third_party/blink/renderer/core/scheduler/virtual_time_test.cc
+++ b/chromium/third_party/blink/renderer/core/scheduler/virtual_time_test.cc
@@ -51,10 +51,11 @@ class VirtualTimeTest : public SimTest {
}
void TearDown() override {
- // The SimTest destructor calls runPendingTasks. This is a problem because
+ // SimTest::TearDown() calls RunPendingTasks. This is a problem because
// if there are any repeating tasks, advancing virtual time will cause the
// runloop to busy loop. Disabling virtual time here fixes that.
WebView().Scheduler()->DisableVirtualTimeForTesting();
+ SimTest::TearDown();
}
void StopVirtualTimeAndExitRunLoop() {
@@ -70,7 +71,7 @@ class VirtualTimeTest : public SimTest {
FROM_HERE,
WTF::Bind(&VirtualTimeTest::StopVirtualTimeAndExitRunLoop,
WTF::Unretained(this)),
- TimeDelta::FromMillisecondsD(delay_ms));
+ base::TimeDelta::FromMillisecondsD(delay_ms));
test::EnterRunLoop();
}
};
diff --git a/chromium/third_party/blink/renderer/core/script/BUILD.gn b/chromium/third_party/blink/renderer/core/script/BUILD.gn
index 1346b025962..ac7886ede65 100644
--- a/chromium/third_party/blink/renderer/core/script/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/script/BUILD.gn
@@ -58,6 +58,8 @@ blink_core_sources("script") {
"script_runner.cc",
"script_runner.h",
"script_scheduling_type.h",
+ "value_wrapper_synthetic_module_script.cc",
+ "value_wrapper_synthetic_module_script.h",
"worker_modulator_impl.cc",
"worker_modulator_impl.h",
"worklet_modulator_impl.cc",
@@ -73,3 +75,24 @@ blink_core_sources("script") {
jumbo_excluded_sources = [ "modulator.cc" ] # https://crbug.com/716395
}
+
+copy("layered_apis_elements_virtual_scroller_js") {
+ testonly = true
+
+ sources = [
+ "resources/layered_api/elements/virtual-scroller/find-element.mjs",
+ "resources/layered_api/elements/virtual-scroller/sets.mjs",
+ "resources/layered_api/elements/virtual-scroller/visibility-manager.mjs",
+ ]
+
+ outputs = [
+ "{{source_gen_dir}}/{{source_file_part}}",
+ ]
+}
+
+group("js_files_for_web_tests") {
+ testonly = true
+ data_deps = [
+ ":layered_apis_elements_virtual_scroller_js",
+ ]
+}
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 3bd0f996731..67703f93bfd 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
@@ -18,10 +18,11 @@
#include "third_party/blink/renderer/core/script/document_write_intervention.h"
#include "third_party/blink/renderer/core/script/script_loader.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/loader/allowed_by_nosniff.h"
#include "third_party/blink/renderer/platform/loader/fetch/cached_metadata.h"
+#include "third_party/blink/renderer/platform/loader/fetch/detachable_use_counter.h"
#include "third_party/blink/renderer/platform/loader/fetch/memory_cache.h"
#include "third_party/blink/renderer/platform/loader/fetch/raw_resource.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_client.h"
@@ -249,10 +250,13 @@ void ClassicPendingScript::NotifyFinished(Resource* resource) {
// It is possible to get back a script resource with integrity metadata
// for a request with an empty integrity attribute. In that case, the
- // integrity check should be skipped, so this check ensures that the
- // integrity attribute isn't empty in addition to checking if the
- // resource has empty integrity metadata.
- if (!element->IntegrityAttributeValue().IsEmpty()) {
+ // integrity check should be skipped, as the integrity may not have been
+ // "meant" for this specific request. If the resource is being served from
+ // the preload cache however, we know any associated integrity metadata and
+ // checks were destined for this request, so we cannot skip the integrity
+ // check.
+ if (!element->IntegrityAttributeValue().IsEmpty() ||
+ GetResource()->IsLinkPreload()) {
integrity_failure_ = GetResource()->IntegrityDisposition() !=
ResourceIntegrityDisposition::kPassed;
}
@@ -276,7 +280,7 @@ void ClassicPendingScript::NotifyFinished(Resource* resource) {
AdvanceReadyState(error_occurred ? kErrorOccurred : kReady);
}
-void ClassicPendingScript::Trace(blink::Visitor* visitor) {
+void ClassicPendingScript::Trace(Visitor* visitor) {
ResourceClient::Trace(visitor);
MemoryPressureListener::Trace(visitor);
PendingScript::Trace(visitor);
@@ -342,7 +346,7 @@ ClassicScript* ClassicPendingScript::GetSource(const KURL& document_url) const {
auto* fetcher = GetElement()->GetDocument().ContextDocument()->Fetcher();
// If the MIME check fails, which is considered as load failure.
if (!AllowedByNosniff::MimeTypeAsScript(
- fetcher->Context(), &fetcher->GetConsoleLogger(),
+ fetcher->GetUseCounter(), &fetcher->GetConsoleLogger(),
resource->GetResponse(), AllowedByNosniff::MimeTypeCheck::kLax)) {
return nullptr;
}
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 c9e135de659..ca495ebdd16 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
@@ -10,8 +10,8 @@
#include "third_party/blink/renderer/core/loader/resource/script_resource.h"
#include "third_party/blink/renderer/core/script/classic_script.h"
#include "third_party/blink/renderer/core/script/pending_script.h"
+#include "third_party/blink/renderer/platform/instrumentation/memory_pressure_listener.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h"
-#include "third_party/blink/renderer/platform/memory_pressure_listener.h"
namespace blink {
@@ -58,7 +58,7 @@ class CORE_EXPORT ClassicPendingScript final : public PendingScript,
void SetStreamer(ScriptStreamer*);
void StreamingFinished();
- void Trace(blink::Visitor*) override;
+ void Trace(Visitor*) override;
mojom::ScriptType GetScriptType() const override {
return mojom::ScriptType::kClassic;
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 afe840f1bb7..df884115ba2 100644
--- a/chromium/third_party/blink/renderer/core/script/classic_script.cc
+++ b/chromium/third_party/blink/renderer/core/script/classic_script.cc
@@ -13,7 +13,7 @@
namespace blink {
-void ClassicScript::Trace(blink::Visitor* visitor) {
+void ClassicScript::Trace(Visitor* visitor) {
Script::Trace(visitor);
visitor->Trace(script_source_code_);
}
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 b5da0ea28d7..e64a2118b1e 100644
--- a/chromium/third_party/blink/renderer/core/script/classic_script.h
+++ b/chromium/third_party/blink/renderer/core/script/classic_script.h
@@ -24,7 +24,7 @@ class CORE_EXPORT ClassicScript final : public Script {
script_source_code_(script_source_code),
sanitize_script_errors_(sanitize_script_errors) {}
- void Trace(blink::Visitor*) override;
+ void Trace(Visitor*) override;
const ScriptSourceCode& GetScriptSourceCode() const {
return script_source_code_;
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 fbe4bfc38f9..e4bb75221db 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
@@ -4,7 +4,7 @@
#include "third_party/blink/renderer/core/script/document_write_intervention.h"
-#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-shared.h"
+#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h"
#include "third_party/blink/public/platform/web_effective_connection_type.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_client.h"
@@ -34,7 +34,7 @@ void EmitWarningMayBeBlocked(const String& url, Document& document) {
document.AddConsoleMessage(
ConsoleMessage::Create(mojom::ConsoleMessageSource::kJavaScript,
mojom::ConsoleMessageLevel::kWarning, message));
- DVLOG(1) << message.Utf8().data();
+ DVLOG(1) << message.Utf8();
}
void EmitWarningNotBlocked(const String& url, Document& document) {
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 b8249e5a431..63ffbe076b0 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
@@ -27,7 +27,7 @@ class DynamicImportTreeClient final : public ModuleTreeClient {
ScriptPromiseResolver* promise_resolver)
: url_(url), modulator_(modulator), promise_resolver_(promise_resolver) {}
- void Trace(blink::Visitor*) override;
+ void Trace(Visitor*) override;
private:
// Implements ModuleTreeClient:
@@ -54,31 +54,30 @@ void DynamicImportTreeClient::NotifyModuleTreeLoadFinished(
ScriptState::Scope scope(script_state);
v8::Isolate* isolate = script_state->GetIsolate();
- // <spec step="2.5">If result is null, then:</spec>
+ // <spec step="6">If result is null, then:</spec>
if (!module_script) {
- // <spec step="2.5.1">Let completion be Completion { [[Type]]: throw,
+ // <spec step="6.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());
- // <spec step="2.5.2">Perform FinishDynamicImport(referencingScriptOrModule,
+ // <spec step="6.2">Perform FinishDynamicImport(referencingScriptOrModule,
// specifier, promiseCapability, completion).</spec>
promise_resolver_->Reject(error);
- // <spec step="2.5.3">Return.</spec>
+ // <spec step="6.3">Return.</spec>
return;
}
- // <spec step="2.6">Run the module script result, with the rethrow errors
+ // <spec step="7">Run the module script result, with the rethrow errors
// boolean set to true.</spec>
ScriptValue error = modulator_->ExecuteModule(
module_script, Modulator::CaptureEvalErrorFlag::kCapture);
- // <spec step="2.7">If running the module script throws an exception,
- // ...</spec>
+ // <spec step="8">If running the module script throws an exception, ...</spec>
if (!error.IsEmpty()) {
- // <spec step="2.7">... then perform
+ // <spec step="8">... then perform
// FinishDynamicImport(referencingScriptOrModule, specifier,
// promiseCapability, the thrown exception completion).</spec>
//
@@ -93,7 +92,7 @@ void DynamicImportTreeClient::NotifyModuleTreeLoadFinished(
return;
}
- // <spec step="2.8">Otherwise, perform
+ // <spec step="9">Otherwise, perform
// FinishDynamicImport(referencingScriptOrModule, specifier,
// promiseCapability, NormalCompletion(undefined)).</spec>
//
@@ -142,7 +141,7 @@ void DynamicImportTreeClient::NotifyModuleTreeLoadFinished(
promise_resolver_->Resolve(module_namespace);
}
-void DynamicImportTreeClient::Trace(blink::Visitor* visitor) {
+void DynamicImportTreeClient::Trace(Visitor* visitor) {
visitor->Trace(modulator_);
visitor->Trace(promise_resolver_);
ModuleTreeClient::Trace(visitor);
@@ -150,7 +149,7 @@ void DynamicImportTreeClient::Trace(blink::Visitor* visitor) {
} // namespace
-void DynamicModuleResolver::Trace(blink::Visitor* visitor) {
+void DynamicModuleResolver::Trace(Visitor* visitor) {
visitor->Trace(modulator_);
}
@@ -173,13 +172,10 @@ void DynamicModuleResolver::ResolveDynamically(
// (in ResolveModuleSpecifier()) and we need to clear the flag before that.
modulator_->ClearIsAcquiringImportMaps();
- // <spec step="1">Let referencing script be
+ // <spec step="4.1">Let referencing script be
// referencingScriptOrModule.[[HostDefined]].</spec>
- // <spec step="2">Run the following steps in parallel:</spec>
-
- // <spec step="2.1">Let url be the result of resolving a module specifier
- // given referencing script's base URL and specifier.</spec>
+ // <spec step="4.3">Set base URL to referencing script's base URL.</spec>
KURL base_url = referrer_info.BaseURL();
if (base_url.IsNull()) {
// ReferrerScriptInfo::BaseURL returns null if it should defer to referrer
@@ -187,25 +183,39 @@ void DynamicModuleResolver::ResolveDynamically(
base_url = referrer_resource_url;
}
if (base_url.IsNull()) {
- // In some cases, "referencing script" may not exist. Use the document's
- // base URL as last resort.
- // TODO(kouhei): Revisit this after
- // https://github.com/whatwg/html/issues/3295 resolved.
+ // The case where "referencing script" doesn't exist.
+ //
+ // <spec step="1">Let settings object be the current settings object.</spec>
+ //
+ // <spec step="2">Let base URL be settings object's API base URL.</spec>
base_url = ExecutionContext::From(modulator_->GetScriptState())->BaseURL();
}
DCHECK(!base_url.IsNull());
+ // <spec step="5">Fetch an import() module script graph given specifier, base
+ // URL, settings object, and fetch options. Wait until the algorithm
+ // asynchronously completes with result.</spec>
+ //
+ // <specdef label="fetch-an-import()-module-script-graph"
+ // href="https://html.spec.whatwg.org/C/#fetch-an-import()-module-script-graph">
+
+ // <spec label="fetch-an-import()-module-script-graph" step="1">Let url be the
+ // result of resolving a module specifier given base URL and specifier.</spec>
KURL url = modulator_->ResolveModuleSpecifier(specifier, base_url);
+
+ // <spec label="fetch-an-import()-module-script-graph" step="2">If url is
+ // failure, then asynchronously complete this algorithm with null, and abort
+ // these steps.</spec>
if (!url.IsValid()) {
- // <spec step="2.2">If url is failure, then:</spec>
+ // <spec step="6">If result is null, then:</spec>
//
- // <spec step="2.2.1">Let completion be Completion { [[Type]]: throw,
+ // <spec step="6.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 + "'");
- // <spec step="2.2.2">Perform FinishDynamicImport(referencingScriptOrModule,
+ // <spec step="6.2">Perform FinishDynamicImport(referencingScriptOrModule,
// specifier, promiseCapability, completion).</spec>
//
// <spec
@@ -215,18 +225,19 @@ void DynamicModuleResolver::ResolveDynamically(
// »).</spec>
promise_resolver->Reject(error);
- // <spec step="2.2.3">Return.</spec>
+ // <spec step="6.3">Return.</spec>
return;
}
- // <spec step="2.3">Let options be the descendant script fetch options for
- // referencing script's fetch options.</spec>
+ // <spec step="4.4">Set fetch options to the descendant script fetch options
+ // for referencing script's fetch options.</spec>
//
// <spec
// href="https://html.spec.whatwg.org/C/#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 string.</spec>
+ //
// TODO(domfarolino): It has not yet been decided how a script's "importance"
// should affect its dynamic imports. There is discussion at
// https://github.com/whatwg/html/issues/3670, but for now there is no effect,
@@ -239,9 +250,12 @@ void DynamicModuleResolver::ResolveDynamically(
referrer_info.GetReferrerPolicy(),
mojom::FetchImportanceMode::kImportanceAuto);
- // <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>
+ // <spec label="fetch-an-import()-module-script-graph" step="3">Fetch a single
+ // module script given url, settings object, "script", options, settings
+ // object, "client", and with the top-level module fetch flag set. If the
+ // caller of this algorithm specified custom perform the fetch steps, pass
+ // those along as well. Wait until the algorithm asynchronously completes with
+ // result.</spec>
auto* tree_client = MakeGarbageCollected<DynamicImportTreeClient>(
url, modulator_.Get(), promise_resolver);
// TODO(kouhei): ExecutionContext::From(modulator_->GetScriptState()) is
@@ -254,10 +268,10 @@ void DynamicModuleResolver::ResolveDynamically(
mojom::RequestContextType::SCRIPT, options,
ModuleScriptCustomFetchType::kNone, tree_client);
- // Steps 2.[5-8] are implemented at
+ // Steps 6-9 are implemented at
// DynamicImportTreeClient::NotifyModuleLoadFinished.
- // <spec step="3">Return undefined.</spec>
+ // <spec step="10">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 b97df2d5d5b..e73c78d383b 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
@@ -23,7 +23,7 @@ class ScriptPromiseResolver;
class CORE_EXPORT DynamicModuleResolver final
: public GarbageCollected<DynamicModuleResolver> {
public:
- void Trace(blink::Visitor*);
+ void Trace(Visitor*);
explicit DynamicModuleResolver(Modulator* modulator)
: 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 90b5bbb5ef7..c85586c2393 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
@@ -47,7 +47,7 @@ class DynamicModuleResolverTestModulator final : public DummyModulator {
}
bool fetch_tree_was_called() const { return fetch_tree_was_called_; }
- void Trace(blink::Visitor*) override;
+ void Trace(Visitor*) override;
private:
// Implements Modulator:
@@ -101,7 +101,7 @@ class DynamicModuleResolverTestModulator final : public DummyModulator {
bool fetch_tree_was_called_ = false;
};
-void DynamicModuleResolverTestModulator::Trace(blink::Visitor* visitor) {
+void DynamicModuleResolverTestModulator::Trace(Visitor* visitor) {
visitor->Trace(script_state_);
visitor->Trace(pending_client_);
DummyModulator::Trace(visitor);
@@ -110,7 +110,7 @@ void DynamicModuleResolverTestModulator::Trace(blink::Visitor* visitor) {
// CaptureExportedStringFunction implements a javascript function
// with a single argument of type module namespace.
// CaptureExportedStringFunction captures the exported string value
-// from the module namespace as a blink::String, exposed via CapturedValue().
+// from the module namespace as a WTF::String, exposed via CapturedValue().
class CaptureExportedStringFunction final : public ScriptFunction {
public:
CaptureExportedStringFunction(ScriptState* script_state,
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 1be2d76fbaf..a01b4a1df40 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,14 +5,14 @@
#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 "services/network/public/mojom/referrer_policy.mojom-blink.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/security_origin.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_copier.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/script/generate_lapi_grdp.py b/chromium/third_party/blink/renderer/core/script/generate_lapi_grdp.py
index a05172b2019..fcb15ba5047 100755
--- a/chromium/third_party/blink/renderer/core/script/generate_lapi_grdp.py
+++ b/chromium/third_party/blink/renderer/core/script/generate_lapi_grdp.py
@@ -5,6 +5,7 @@
import sys
import os
+import re
def main():
@@ -40,42 +41,42 @@ def main():
-->'''
resource_list_in_header_file = ''
- modules = set()
-
+ # A list of (name, path)
+ modules = []
for root, _, filenames in sorted(os.walk(input_path)):
- relroot = os.path.relpath(root, input_path)
- if relroot == '.':
- # We don't include top-level files under resources/layered_api,
- # including generated resources.grdp.
- continue
-
- # Get e.g. "kKvStorage" for kv-storage.
- module_name = relroot.split('/')[0]
- module_name = "k" + module_name.title().replace('-', '')
- modules.add(module_name)
-
- for filename in sorted(filenames):
- if filename.startswith('.') or filename.startswith(
- 'README') or filename.startswith('OWNERS'):
- continue
- relpath = os.path.relpath(os.path.join(root, filename), input_path)
- relpath = relpath.replace('\\', '/')
- resource_id = relpath
- resource_id = resource_id.replace('/', '_')
- resource_id = resource_id.replace('-', '_')
- resource_id = resource_id.replace('.', '_')
- resource_id = resource_id.upper()
- resource_id = "IDR_LAYERED_API_" + resource_id
- resource_list_in_header_file += \
- ' {"%s",\n %s,\n Module::%s},\n' % (relpath, resource_id, module_name)
- print >> output_grdp_file, (
- ' <include name="%s" file="%s/%s" type="BINDATA" skip_minify="true" compress="gzip"/>'
- % (resource_id, input_relative_path, relpath))
- resource_list_in_header_file += '\n'
+ # A directory represents a built-in module if
+ # - it contains index.mjs (web-exposed module) or
+ # - the directory name is 'internal' (private module)
+ if 'index.mjs' in filenames or re.search(r'\binternal$', root):
+ # Get e.g. "kKvStorage" for kv-storage.
+ module_name = os.path.relpath(root, input_path)
+ module_name = "k" + re.sub(r'\W', '', module_name.title())
+ modules.append((module_name, root))
+
+ for module_name, module_path in modules:
+ for root, _, filenames in sorted(os.walk(module_path)):
+ for filename in sorted(filenames):
+ if filename.startswith('.') or filename.startswith(
+ 'README') or filename.startswith('OWNERS'):
+ continue
+ relpath = os.path.relpath(os.path.join(root, filename), input_path)
+ relpath = relpath.replace('\\', '/')
+ resource_id = relpath
+ resource_id = resource_id.replace('/', '_')
+ resource_id = resource_id.replace('-', '_')
+ resource_id = resource_id.replace('.', '_')
+ resource_id = resource_id.upper()
+ resource_id = "IDR_LAYERED_API_" + resource_id
+ resource_list_in_header_file += \
+ ' {"%s",\n %s,\n Module::%s},\n' % (relpath, resource_id, module_name)
+ print >> output_grdp_file, (
+ ' <include name="%s" file="%s/%s" type="BINDATA" skip_minify="true" compress="gzip"/>'
+ % (resource_id, input_relative_path, relpath))
+ resource_list_in_header_file += '\n'
print >> output_grdp_file, '</grit-part>'
module_list_in_header_file = ''
- for module in modules:
+ for module, _ in modules:
module_list_in_header_file += (' %s,\n' % module)
print >> output_module_header_file, '''// Copyright 2019 The Chromium Authors. All rights reserved.
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 2a22c04baf2..2bd8365bb0e 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
@@ -27,6 +27,7 @@
#include <inttypes.h>
#include <memory>
+#include "services/metrics/public/cpp/ukm_builders.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/renderer/core/dom/document_parser_timing.h"
@@ -39,7 +40,7 @@
#include "third_party/blink/renderer/core/script/script_loader.h"
#include "third_party/blink/renderer/platform/bindings/microtask.h"
#include "third_party/blink/renderer/platform/bindings/v8_per_isolate_data.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/traced_value.h"
@@ -160,6 +161,11 @@ void HTMLParserScriptRunner::Detach() {
parser_blocking_script_->Dispose();
parser_blocking_script_ = nullptr;
+ while (!force_deferred_scripts_.IsEmpty()) {
+ PendingScript* pending_script = force_deferred_scripts_.TakeFirst();
+ pending_script->Dispose();
+ }
+
while (!scripts_to_execute_after_parsing_.IsEmpty()) {
PendingScript* pending_script =
scripts_to_execute_after_parsing_.TakeFirst();
@@ -299,7 +305,14 @@ void HTMLParserScriptRunner::PendingScriptFinished(
return;
}
- host_->NotifyScriptLoaded(pending_script);
+ // Posting the script execution part to a new task so that we can allow
+ // yielding for cooperative scheduling. Cooperative scheduling requires that
+ // the Blink C++ stack be thin when it executes JavaScript.
+ document_->GetTaskRunner(TaskType::kInternalContinueScriptLoading)
+ ->PostTask(FROM_HERE,
+ WTF::Bind(&HTMLParserScriptRunnerHost::NotifyScriptLoaded,
+ WrapPersistent(host_.Get()),
+ WrapPersistent(pending_script)));
}
// <specdef href="https://html.spec.whatwg.org/C/#scriptEndTag">
@@ -412,38 +425,61 @@ void HTMLParserScriptRunner::ExecuteScriptsWaitingForResources() {
ExecuteParsingBlockingScripts();
}
+PendingScript* HTMLParserScriptRunner::TryTakeReadyScriptWaitingForParsing(
+ HeapDeque<Member<PendingScript>>* waiting_scripts) {
+ DCHECK(!waiting_scripts->IsEmpty());
+
+ // <spec step="3.1">Spin the event loop until the first script in the list
+ // of scripts that will execute when the document has finished parsing has
+ // its "ready to be parser-executed" flag set and the parser's Document has
+ // no style sheet that is blocking scripts.</spec>
+ //
+ // TODO(hiroshige): Add check for style sheet blocking defer scripts
+ // https://github.com/whatwg/html/issues/3890
+ if (!waiting_scripts->front()->IsReady()) {
+ waiting_scripts->front()->WatchForLoad(this);
+ TraceParserBlockingScript(waiting_scripts->front().Get(),
+ !document_->IsScriptExecutionReady());
+ waiting_scripts->front()->MarkParserBlockingLoadStartTime();
+ return nullptr;
+ }
+ return waiting_scripts->TakeFirst();
+}
+
// <specdef href="https://html.spec.whatwg.org/C/#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>
+//
+// This will also run any forced deferred scripts before running any developer
+// deferred scripts.
bool HTMLParserScriptRunner::ExecuteScriptsWaitingForParsing() {
TRACE_EVENT0("blink",
"HTMLParserScriptRunner::executeScriptsWaitingForParsing");
- while (!scripts_to_execute_after_parsing_.IsEmpty()) {
+ while (!force_deferred_scripts_.IsEmpty() ||
+ !scripts_to_execute_after_parsing_.IsEmpty()) {
DCHECK(!IsExecutingScript());
DCHECK(!HasParserBlockingScript());
- DCHECK(scripts_to_execute_after_parsing_.front()->IsExternalOrModule());
-
- // <spec step="3.1">Spin the event loop until the first script in the list
- // of scripts that will execute when the document has finished parsing has
- // its "ready to be parser-executed" flag set and the parser's Document has
- // no style sheet that is blocking scripts.</spec>
- //
- // TODO(hiroshige): Is the latter part checked anywhere?
- if (!scripts_to_execute_after_parsing_.front()->IsReady()) {
- scripts_to_execute_after_parsing_.front()->WatchForLoad(this);
- TraceParserBlockingScript(scripts_to_execute_after_parsing_.front().Get(),
- !document_->IsScriptExecutionReady());
- scripts_to_execute_after_parsing_.front()
- ->MarkParserBlockingLoadStartTime();
- return false;
- }
+ DCHECK(scripts_to_execute_after_parsing_.IsEmpty() ||
+ scripts_to_execute_after_parsing_.front()->IsExternalOrModule());
// <spec step="3.3">Remove the first script element from the list of scripts
// that will execute when the document has finished parsing (i.e. shift out
// the first entry in the list).</spec>
- PendingScript* first = scripts_to_execute_after_parsing_.TakeFirst();
+ PendingScript* first = nullptr;
+
+ // First execute the scripts that were forced-deferred. If no such scripts
+ // are present, then try executing scripts that were deferred by the web
+ // developer.
+ if (!force_deferred_scripts_.IsEmpty()) {
+ first = TryTakeReadyScriptWaitingForParsing(&force_deferred_scripts_);
+ } else {
+ first = TryTakeReadyScriptWaitingForParsing(
+ &scripts_to_execute_after_parsing_);
+ }
+ if (!first)
+ return false;
// <spec step="3.2">Execute the first script in the list of scripts that
// will execute when the document has finished parsing.</spec>
@@ -494,6 +530,7 @@ void HTMLParserScriptRunner::RequestDeferredScript(
pending_script->StartStreamingIfPossible();
}
+ DCHECK(!script_loader->IsForceDeferred());
DCHECK(pending_script->IsExternalOrModule());
// <spec href="https://html.spec.whatwg.org/C/#prepare-a-script"
@@ -503,6 +540,25 @@ void HTMLParserScriptRunner::RequestDeferredScript(
scripts_to_execute_after_parsing_.push_back(pending_script);
}
+void HTMLParserScriptRunner::RequestForceDeferredScript(
+ ScriptLoader* script_loader) {
+ PendingScript* pending_script =
+ script_loader->TakePendingScript(ScriptSchedulingType::kForceDefer);
+ if (!pending_script)
+ return;
+
+ if (!pending_script->IsReady()) {
+ pending_script->StartStreamingIfPossible();
+ }
+
+ DCHECK(script_loader->IsForceDeferred());
+
+ // Add the element to the end of the list of forced deferred scripts that will
+ // execute when the document has finished parsing associated with the Document
+ // of the parser that created the element.
+ force_deferred_scripts_.push_back(pending_script);
+}
+
// The initial steps for 'An end tag whose tag name is "script"'
// <specdef href="https://html.spec.whatwg.org/C/#scriptEndTag">
// <specdef label="prepare-a-script"
@@ -544,7 +600,11 @@ void HTMLParserScriptRunner::ProcessScriptElementInternal(
return;
if (script_loader->WillExecuteWhenDocumentFinishedParsing()) {
+ // Developer deferred.
RequestDeferredScript(script_loader);
+ } else if (script_loader->IsForceDeferred()) {
+ // Force defer this otherwise parser-blocking script.
+ RequestForceDeferredScript(script_loader);
} else if (script_loader->ReadyToBeParserExecuted()) {
// <spec label="prepare-a-script" step="26.E">... it's an HTML parser
// whose script nesting level is not greater than one, ...</spec>
@@ -589,10 +649,48 @@ void HTMLParserScriptRunner::ProcessScriptElementInternal(
}
}
-void HTMLParserScriptRunner::Trace(blink::Visitor* visitor) {
+void HTMLParserScriptRunner::RecordMetricsAtParseEnd() const {
+ // This method is called just before starting execution of force defer
+ // scripts in order to capture the all force deferred scripts in
+ // |force_deferred_scripts_| before any are popped for execution.
+
+ if (!document_->GetFrame())
+ return;
+
+ if (!force_deferred_scripts_.IsEmpty()) {
+ uint32_t force_deferred_external_script_count = 0;
+ for (const auto& pending_script : force_deferred_scripts_) {
+ if (pending_script->IsExternal())
+ force_deferred_external_script_count++;
+ }
+ if (document_->IsInMainFrame()) {
+ UMA_HISTOGRAM_COUNTS_100("Blink.Script.ForceDeferredScripts.Mainframe",
+ force_deferred_scripts_.size());
+ UMA_HISTOGRAM_COUNTS_100(
+ "Blink.Script.ForceDeferredScripts.Mainframe.External",
+ force_deferred_external_script_count);
+ if (document_->UkmRecorder()) {
+ ukm::builders::PreviewsDeferAllScript(document_->UkmSourceID())
+ .Setforce_deferred_scripts_mainframe(force_deferred_scripts_.size())
+ .Setforce_deferred_scripts_mainframe_external(
+ force_deferred_external_script_count)
+ .Record(document_->UkmRecorder());
+ }
+ } else {
+ UMA_HISTOGRAM_COUNTS_100("Blink.Script.ForceDeferredScripts.Subframe",
+ force_deferred_scripts_.size());
+ UMA_HISTOGRAM_COUNTS_100(
+ "Blink.Script.ForceDeferredScripts.Subframe.External",
+ force_deferred_external_script_count);
+ }
+ }
+}
+
+void HTMLParserScriptRunner::Trace(Visitor* visitor) {
visitor->Trace(document_);
visitor->Trace(host_);
visitor->Trace(parser_blocking_script_);
+ visitor->Trace(force_deferred_scripts_);
visitor->Trace(scripts_to_execute_after_parsing_);
PendingScriptClient::Trace(visitor);
}
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 f9b1dce95a2..a3f88c0dff3 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
@@ -93,6 +93,8 @@ class HTMLParserScriptRunner final
void ExecuteScriptsWaitingForResources();
// Invoked when parsing is stopping, to execute any deferred scripts.
+ // This includes forced deferred scripts as well as developer deferred
+ // scripts.
bool ExecuteScriptsWaitingForParsing();
bool HasParserBlockingScript() const;
@@ -100,7 +102,11 @@ class HTMLParserScriptRunner final
return !!reentry_permit_->ScriptNestingLevel();
}
- void Trace(blink::Visitor*) override;
+ // Records metrics related to the parsing phase. To be called when parsing
+ // is preparing to stop but before |ExecuteScriptsWaitingForParsing|.
+ void RecordMetricsAtParseEnd() const;
+
+ void Trace(Visitor*) override;
const char* NameInHeapSnapshot() const override {
return "HTMLParserScriptRunner";
}
@@ -115,6 +121,7 @@ class HTMLParserScriptRunner final
void RequestParsingBlockingScript(ScriptLoader*);
void RequestDeferredScript(ScriptLoader*);
+ void RequestForceDeferredScript(ScriptLoader*);
// Processes the provided script element, but does not execute any
// parsing-blocking scripts that may remain after execution.
@@ -129,6 +136,12 @@ class HTMLParserScriptRunner final
void PossiblyFetchBlockedDocWriteScript(PendingScript*);
+ // Takes and returns the first PendingScript from |waiting_scripts| if it is
+ // ready for execution. Otherwise, informs it that |this| is a
+ // PendingScriptClient to be informed when it is ready.
+ PendingScript* TryTakeReadyScriptWaitingForParsing(
+ HeapDeque<Member<PendingScript>>* waiting_scripts);
+
scoped_refptr<HTMLParserReentryPermit> reentry_permit_;
Member<Document> document_;
Member<HTMLParserScriptRunnerHost> host_;
@@ -136,6 +149,13 @@ class HTMLParserScriptRunner final
// https://html.spec.whatwg.org/C/#pending-parsing-blocking-script
Member<PendingScript> parser_blocking_script_;
+ // Scripts that were force deferred by the defer all script optimization.
+ // These scripts will be executed after parsing but before
+ // |scripts_to_execute_after_parsing_|. This is an ordered list.
+ // https://crbug.com/976061
+ HeapDeque<Member<PendingScript>> force_deferred_scripts_;
+
+ // Scripts that were deferred by the web developer. This is an ordered list.
// https://html.spec.whatwg.org/C/#list-of-scripts-that-will-execute-when-the-document-has-finished-parsing
HeapDeque<Member<PendingScript>> scripts_to_execute_after_parsing_;
diff --git a/chromium/third_party/blink/renderer/core/script/html_parser_script_runner_host.h b/chromium/third_party/blink/renderer/core/script/html_parser_script_runner_host.h
index dd5f4fbe1c4..1a4770c0a2a 100644
--- a/chromium/third_party/blink/renderer/core/script/html_parser_script_runner_host.h
+++ b/chromium/third_party/blink/renderer/core/script/html_parser_script_runner_host.h
@@ -37,7 +37,7 @@ class PendingScript;
class CORE_EXPORT HTMLParserScriptRunnerHost : public GarbageCollectedMixin {
public:
virtual ~HTMLParserScriptRunnerHost() = default;
- void Trace(blink::Visitor* visitor) override {}
+ void Trace(Visitor* visitor) override {}
virtual void NotifyScriptLoaded(PendingScript*) = 0;
virtual HTMLInputStream& InputStream() = 0;
diff --git a/chromium/third_party/blink/renderer/core/script/ignore_destructive_write_count_incrementer.h b/chromium/third_party/blink/renderer/core/script/ignore_destructive_write_count_incrementer.h
index cedad851068..02738ad8bc5 100644
--- a/chromium/third_party/blink/renderer/core/script/ignore_destructive_write_count_incrementer.h
+++ b/chromium/third_party/blink/renderer/core/script/ignore_destructive_write_count_incrementer.h
@@ -28,7 +28,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/dom/document.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/script/import_map.cc b/chromium/third_party/blink/renderer/core/script/import_map.cc
index fceaddd75a9..c78d79dda49 100644
--- a/chromium/third_party/blink/renderer/core/script/import_map.cc
+++ b/chromium/third_party/blink/renderer/core/script/import_map.cc
@@ -187,7 +187,7 @@ ImportMap* ImportMap::Create(const Modulator& modulator_for_built_in_modules,
values.clear();
}
if (values.size() == 2) {
- if (blink::layered_api::GetBuiltinPath(values[0]).IsNull()) {
+ if (layered_api::GetBuiltinPath(values[0]).IsNull()) {
AddIgnoredValueMessage(
logger, entry.first,
"Fallback from a non-builtin URL is not yet supported.");
@@ -282,8 +282,8 @@ base::Optional<KURL> ImportMap::Resolve(const ParsedSpecifier& parsed_specifier,
for (const KURL& value : matched->value) {
const KURL complete_url = postfix.IsEmpty() ? value : KURL(value, postfix);
- if (blink::layered_api::ResolveFetchingURL(*modulator_for_built_in_modules_,
- complete_url)
+ if (layered_api::ResolveFetchingURL(*modulator_for_built_in_modules_,
+ complete_url)
.IsValid()) {
*debug_message = "Import Map: \"" + key + "\" matches with \"" +
matched->key + "\" and is mapped to " +
diff --git a/chromium/third_party/blink/renderer/core/script/js_module_script.cc b/chromium/third_party/blink/renderer/core/script/js_module_script.cc
index d53409bf7c6..8b12c6ac851 100644
--- a/chromium/third_party/blink/renderer/core/script/js_module_script.cc
+++ b/chromium/third_party/blink/renderer/core/script/js_module_script.cc
@@ -6,8 +6,6 @@
#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
#include "third_party/blink/renderer/core/script/module_record_resolver.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/platform/bindings/script_state.h"
#include "v8/include/v8.h"
@@ -166,21 +164,6 @@ JSModuleScript::JSModuleScript(Modulator* settings_object,
start_position_(start_position),
produce_cache_data_(produce_cache_data) {}
-void JSModuleScript::RunScriptOnWorker(WorkerGlobalScope& worker_global_scope) {
- DCHECK(worker_global_scope.IsContextThread());
-
- WorkerReportingProxy& worker_reporting_proxy =
- worker_global_scope.ReportingProxy();
-
- 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 = SettingsObject()->ExecuteModule(
- this, Modulator::CaptureEvalErrorFlag::kReport);
- worker_reporting_proxy.DidEvaluateModuleScript(error.IsEmpty());
-}
-
String JSModuleScript::InlineSourceTextForCSP() const {
return source_text_.ToString();
}
@@ -199,7 +182,7 @@ void JSModuleScript::ProduceCache() {
produce_cache_data_ = nullptr;
}
-void JSModuleScript::Trace(blink::Visitor* visitor) {
+void JSModuleScript::Trace(Visitor* visitor) {
visitor->Trace(produce_cache_data_);
ModuleScript::Trace(visitor);
}
diff --git a/chromium/third_party/blink/renderer/core/script/js_module_script.h b/chromium/third_party/blink/renderer/core/script/js_module_script.h
index db070c73340..61089f896de 100644
--- a/chromium/third_party/blink/renderer/core/script/js_module_script.h
+++ b/chromium/third_party/blink/renderer/core/script/js_module_script.h
@@ -57,7 +57,7 @@ class CORE_EXPORT JSModuleScript final : public ModuleScript,
void ProduceCache() override;
- void Trace(blink::Visitor*) override;
+ void Trace(Visitor*) override;
const char* NameInHeapSnapshot() const override { return "JSModuleScript"; }
private:
@@ -74,7 +74,6 @@ class CORE_EXPORT JSModuleScript final : public ModuleScript,
ModuleRecordProduceCacheData* produce_cache_data);
const TextPosition& StartPosition() const { return start_position_; }
- void RunScriptOnWorker(WorkerGlobalScope&) override;
String InlineSourceTextForCSP() const override;
// For CSP check.
diff --git a/chromium/third_party/blink/renderer/core/script/layered_api_module.h b/chromium/third_party/blink/renderer/core/script/layered_api_module.h
index 28809a991c0..7dd7d687dab 100644
--- a/chromium/third_party/blink/renderer/core/script/layered_api_module.h
+++ b/chromium/third_party/blink/renderer/core/script/layered_api_module.h
@@ -15,7 +15,10 @@ namespace layered_api {
enum class Module {
kBlank,
- kVirtualScroller,
+ kElementsInternal,
+ kElementsSwitch,
+ kElementsToast,
+ kElementsVirtualScroller,
kKvStorage,
};
diff --git a/chromium/third_party/blink/renderer/core/script/layered_api_resources.h b/chromium/third_party/blink/renderer/core/script/layered_api_resources.h
index f822934e6ff..98be4b31e1a 100644
--- a/chromium/third_party/blink/renderer/core/script/layered_api_resources.h
+++ b/chromium/third_party/blink/renderer/core/script/layered_api_resources.h
@@ -29,6 +29,35 @@ struct LayeredAPIResource {
const LayeredAPIResource kLayeredAPIResources[] = {
{"blank/index.mjs", IDR_LAYERED_API_BLANK_INDEX_MJS, Module::kBlank},
+ {"elements/internal/reflection.mjs",
+ IDR_LAYERED_API_ELEMENTS_INTERNAL_REFLECTION_MJS,
+ Module::kElementsInternal},
+
+ {"elements/switch/face_utils.mjs",
+ IDR_LAYERED_API_ELEMENTS_SWITCH_FACE_UTILS_MJS, Module::kElementsSwitch},
+ {"elements/switch/index.mjs", IDR_LAYERED_API_ELEMENTS_SWITCH_INDEX_MJS,
+ Module::kElementsSwitch},
+ {"elements/switch/style.mjs", IDR_LAYERED_API_ELEMENTS_SWITCH_STYLE_MJS,
+ Module::kElementsSwitch},
+ {"elements/switch/track.mjs", IDR_LAYERED_API_ELEMENTS_SWITCH_TRACK_MJS,
+ Module::kElementsSwitch},
+
+ {"elements/toast/index.mjs", IDR_LAYERED_API_ELEMENTS_TOAST_INDEX_MJS,
+ Module::kElementsToast},
+
+ {"elements/virtual-scroller/find-element.mjs",
+ IDR_LAYERED_API_ELEMENTS_VIRTUAL_SCROLLER_FIND_ELEMENT_MJS,
+ Module::kElementsVirtualScroller},
+ {"elements/virtual-scroller/index.mjs",
+ IDR_LAYERED_API_ELEMENTS_VIRTUAL_SCROLLER_INDEX_MJS,
+ Module::kElementsVirtualScroller},
+ {"elements/virtual-scroller/sets.mjs",
+ IDR_LAYERED_API_ELEMENTS_VIRTUAL_SCROLLER_SETS_MJS,
+ Module::kElementsVirtualScroller},
+ {"elements/virtual-scroller/visibility-manager.mjs",
+ IDR_LAYERED_API_ELEMENTS_VIRTUAL_SCROLLER_VISIBILITY_MANAGER_MJS,
+ Module::kElementsVirtualScroller},
+
{"kv-storage/async_iterator.mjs",
IDR_LAYERED_API_KV_STORAGE_ASYNC_ITERATOR_MJS, Module::kKvStorage},
{"kv-storage/idb_utils.mjs", IDR_LAYERED_API_KV_STORAGE_IDB_UTILS_MJS,
@@ -36,28 +65,6 @@ const LayeredAPIResource kLayeredAPIResources[] = {
{"kv-storage/index.mjs", IDR_LAYERED_API_KV_STORAGE_INDEX_MJS,
Module::kKvStorage},
- {"virtual-scroller/index.mjs", IDR_LAYERED_API_VIRTUAL_SCROLLER_INDEX_MJS,
- Module::kVirtualScroller},
- {"virtual-scroller/item-source.mjs",
- IDR_LAYERED_API_VIRTUAL_SCROLLER_ITEM_SOURCE_MJS,
- Module::kVirtualScroller},
- {"virtual-scroller/virtual-repeater.mjs",
- IDR_LAYERED_API_VIRTUAL_SCROLLER_VIRTUAL_REPEATER_MJS,
- Module::kVirtualScroller},
- {"virtual-scroller/virtual-scroller.mjs",
- IDR_LAYERED_API_VIRTUAL_SCROLLER_VIRTUAL_SCROLLER_MJS,
- Module::kVirtualScroller},
-
- {"virtual-scroller/layouts/layout-1d-base.mjs",
- IDR_LAYERED_API_VIRTUAL_SCROLLER_LAYOUTS_LAYOUT_1D_BASE_MJS,
- Module::kVirtualScroller},
- {"virtual-scroller/layouts/layout-1d-grid.mjs",
- IDR_LAYERED_API_VIRTUAL_SCROLLER_LAYOUTS_LAYOUT_1D_GRID_MJS,
- Module::kVirtualScroller},
- {"virtual-scroller/layouts/layout-1d.mjs",
- IDR_LAYERED_API_VIRTUAL_SCROLLER_LAYOUTS_LAYOUT_1D_MJS,
- Module::kVirtualScroller},
-
};
} // namespace
diff --git a/chromium/third_party/blink/renderer/core/script/layered_api_test.cc b/chromium/third_party/blink/renderer/core/script/layered_api_test.cc
index 28ac45737df..f318f7fc807 100644
--- a/chromium/third_party/blink/renderer/core/script/layered_api_test.cc
+++ b/chromium/third_party/blink/renderer/core/script/layered_api_test.cc
@@ -16,9 +16,7 @@ namespace {
class LayeredAPITestModulator final : public DummyModulator {
public:
bool BuiltInModuleInfraEnabled() const override { return true; }
- bool BuiltInModuleEnabled(blink::layered_api::Module) const override {
- return true;
- }
+ bool BuiltInModuleEnabled(layered_api::Module) const override { return true; }
};
class LayeredAPITest : public testing::Test {
diff --git a/chromium/third_party/blink/renderer/core/script/mock_script_element_base.h b/chromium/third_party/blink/renderer/core/script/mock_script_element_base.h
index 2afb66aefb4..2722f3a7971 100644
--- a/chromium/third_party/blink/renderer/core/script/mock_script_element_base.h
+++ b/chromium/third_party/blink/renderer/core/script/mock_script_element_base.h
@@ -55,9 +55,7 @@ class MockScriptElementBase
void(HTMLScriptElementOrSVGScriptElement&));
MOCK_CONST_METHOD0(Loader, ScriptLoader*());
- void Trace(blink::Visitor* visitor) override {
- ScriptElementBase::Trace(visitor);
- }
+ void Trace(Visitor* visitor) override { ScriptElementBase::Trace(visitor); }
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/script/modulator.h b/chromium/third_party/blink/renderer/core/script/modulator.h
index 350858d9972..9f67b4e5afa 100644
--- a/chromium/third_party/blink/renderer/core/script/modulator.h
+++ b/chromium/third_party/blink/renderer/core/script/modulator.h
@@ -6,7 +6,7 @@
#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 "services/network/public/mojom/referrer_policy.mojom-blink.h"
#include "third_party/blink/public/platform/web_url_request.h"
#include "third_party/blink/renderer/bindings/core/v8/module_record.h"
#include "third_party/blink/renderer/bindings/core/v8/sanitize_script_errors.h"
@@ -44,7 +44,7 @@ class CORE_EXPORT SingleModuleClient
public NameClient {
public:
virtual ~SingleModuleClient() = default;
- virtual void Trace(blink::Visitor* visitor) {}
+ virtual void Trace(Visitor* visitor) {}
const char* NameInHeapSnapshot() const override {
return "SingleModuleClient";
}
@@ -59,7 +59,7 @@ class CORE_EXPORT ModuleTreeClient
public NameClient {
public:
virtual ~ModuleTreeClient() = default;
- virtual void Trace(blink::Visitor* visitor) {}
+ virtual void Trace(Visitor* visitor) {}
const char* NameInHeapSnapshot() const override { return "ModuleTreeClient"; }
virtual void NotifyModuleTreeLoadFinished(ModuleScript*) = 0;
@@ -107,7 +107,7 @@ class CORE_EXPORT Modulator : public GarbageCollectedFinalized<Modulator>,
static void SetModulator(ScriptState*, Modulator*);
static void ClearModulator(ScriptState*);
- void Trace(blink::Visitor* visitor) override {}
+ void Trace(Visitor* visitor) override {}
const char* NameInHeapSnapshot() const override { return "Modulator"; }
virtual ModuleRecordResolver* GetModuleRecordResolver() = 0;
@@ -122,8 +122,8 @@ class CORE_EXPORT Modulator : public GarbageCollectedFinalized<Modulator>,
virtual bool IsScriptingDisabled() const = 0;
virtual bool BuiltInModuleInfraEnabled() const = 0;
- virtual bool BuiltInModuleEnabled(blink::layered_api::Module) const = 0;
- virtual void BuiltInModuleUseCount(blink::layered_api::Module) const = 0;
+ virtual bool BuiltInModuleEnabled(layered_api::Module) const = 0;
+ virtual void BuiltInModuleUseCount(layered_api::Module) const = 0;
// https://html.spec.whatwg.org/C/#fetch-a-module-script-tree
// https://html.spec.whatwg.org/C/#fetch-a-module-worker-script-tree
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 441862b5a36..a3bcbe4b6ae 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,7 +7,6 @@
#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"
@@ -18,6 +17,7 @@
#include "third_party/blink/renderer/core/script/module_record_resolver_impl.h"
#include "third_party/blink/renderer/core/script/parsed_specifier.h"
#include "third_party/blink/renderer/platform/bindings/v8_throw_exception.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
namespace blink {
@@ -52,33 +52,49 @@ bool ModulatorImplBase::BuiltInModuleInfraEnabled() const {
GetExecutionContext());
}
-bool ModulatorImplBase::BuiltInModuleEnabled(
- blink::layered_api::Module module) const {
+bool ModulatorImplBase::BuiltInModuleEnabled(layered_api::Module module) const {
DCHECK(BuiltInModuleInfraEnabled());
+ if (RuntimeEnabledFeatures::BuiltInModuleAllEnabled())
+ return true;
switch (module) {
- case blink::layered_api::Module::kBlank:
+ case layered_api::Module::kBlank:
return true;
- case blink::layered_api::Module::kVirtualScroller:
+ case layered_api::Module::kKvStorage:
+ return RuntimeEnabledFeatures::BuiltInModuleKvStorageEnabled(
+ GetExecutionContext());
+ case layered_api::Module::kElementsInternal:
+ // Union of conditions of KElementsSwitch and kElementsToast.
+ return RuntimeEnabledFeatures::BuiltInModuleSwitchElementEnabled();
+ case layered_api::Module::kElementsSwitch:
+ return RuntimeEnabledFeatures::BuiltInModuleSwitchElementEnabled();
+ case layered_api::Module::kElementsToast:
return RuntimeEnabledFeatures::BuiltInModuleAllEnabled();
- case blink::layered_api::Module::kKvStorage:
- return RuntimeEnabledFeatures::BuiltInModuleAllEnabled() ||
- RuntimeEnabledFeatures::BuiltInModuleKvStorageEnabled(
- GetExecutionContext());
+ case layered_api::Module::kElementsVirtualScroller:
+ return false;
}
}
void ModulatorImplBase::BuiltInModuleUseCount(
- blink::layered_api::Module module) const {
+ layered_api::Module module) const {
DCHECK(BuiltInModuleInfraEnabled());
DCHECK(BuiltInModuleEnabled(module));
switch (module) {
- case blink::layered_api::Module::kBlank:
+ case layered_api::Module::kBlank:
break;
- case blink::layered_api::Module::kVirtualScroller:
+ case layered_api::Module::kElementsInternal:
+ break;
+ case layered_api::Module::kElementsSwitch:
+ UseCounter::Count(GetExecutionContext(),
+ WebFeature::kBuiltInModuleSwitchImported);
+ break;
+ case layered_api::Module::kElementsToast:
+ UseCounter::Count(GetExecutionContext(), WebFeature::kBuiltInModuleToast);
+ break;
+ case layered_api::Module::kElementsVirtualScroller:
UseCounter::Count(GetExecutionContext(),
WebFeature::kBuiltInModuleVirtualScroller);
break;
- case blink::layered_api::Module::kKvStorage:
+ case layered_api::Module::kKvStorage:
UseCounter::Count(GetExecutionContext(),
WebFeature::kBuiltInModuleKvStorage);
break;
@@ -96,32 +112,9 @@ void ModulatorImplBase::FetchTree(
const ScriptFetchOptions& options,
ModuleScriptCustomFetchType custom_fetch_type,
ModuleTreeClient* client) {
- // <spec label="fetch-a-module-script-tree" step="2">Perform the internal
- // module script graph fetching procedure given url, settings object,
- // destination, options, settings object, visited set, "client", and with the
- // top-level module fetch flag set. If the caller of this algorithm specified
- // custom perform the fetch steps, pass those along as well.</spec>
-
- // <spec label="fetch-a-module-worker-script-tree" step="3">Perform the
- // internal module script graph fetching procedure given url, fetch client
- // settings object, destination, options, module map settings object, visited
- // set, "client", and with the top-level module fetch flag set. If the caller
- // of this algorithm specified custom perform the fetch steps, pass those
- // along as well.</spec>
-
ModuleTreeLinker::Fetch(url, fetch_client_settings_object_fetcher,
destination, options, this, custom_fetch_type,
tree_linker_registry_, client);
-
- // <spec label="fetch-a-module-script-tree" step="3">When the internal module
- // script graph fetching procedure asynchronously completes with result,
- // asynchronously complete this algorithm with result.</spec>
-
- // <spec label="fetch-a-module-worker-script-tree" step="4">When the internal
- // module script graph fetching procedure asynchronously completes with
- // result, asynchronously complete this algorithm with result.</spec>
-
- // Note: We delegate to ModuleTreeLinker to notify ModuleTreeClient.
}
void ModulatorImplBase::FetchDescendantsForInlineScript(
@@ -265,14 +258,14 @@ ModuleImportMeta ModulatorImplBase::HostGetImportMetaProperties(
ModuleRecord record) const {
// <spec step="1">Let module script be moduleRecord.[[HostDefined]].</spec>
const ModuleScript* module_script =
- module_record_resolver_->GetHostDefined(record);
+ module_record_resolver_->GetModuleScriptFromModuleRecord(record);
DCHECK(module_script);
- // <spec step="2">Let urlString be module script's base URL,
+ // <spec step="3">Let urlString be module script's base URL,
// serialized.</spec>
String url_string = module_script->BaseURL().GetString();
- // <spec step="3">Return « Record { [[Key]]: "url", [[Value]]: urlString }
+ // <spec step="4">Return « Record { [[Key]]: "url", [[Value]]: urlString }
// ».</spec>
return ModuleImportMeta(url_string);
}
@@ -416,7 +409,7 @@ ScriptValue ModulatorImplBase::ExecuteModule(
return ScriptValue();
}
-void ModulatorImplBase::Trace(blink::Visitor* visitor) {
+void ModulatorImplBase::Trace(Visitor* visitor) {
visitor->Trace(script_state_);
visitor->Trace(map_);
visitor->Trace(tree_linker_registry_);
diff --git a/chromium/third_party/blink/renderer/core/script/modulator_impl_base.h b/chromium/third_party/blink/renderer/core/script/modulator_impl_base.h
index 53780b19229..6721f1cb8af 100644
--- a/chromium/third_party/blink/renderer/core/script/modulator_impl_base.h
+++ b/chromium/third_party/blink/renderer/core/script/modulator_impl_base.h
@@ -27,7 +27,7 @@ class ScriptState;
class ModulatorImplBase : public Modulator {
public:
~ModulatorImplBase() override;
- void Trace(blink::Visitor*) override;
+ void Trace(Visitor*) override;
protected:
explicit ModulatorImplBase(ScriptState*);
@@ -42,8 +42,8 @@ class ModulatorImplBase : public Modulator {
bool IsScriptingDisabled() const override;
bool BuiltInModuleInfraEnabled() const override;
- bool BuiltInModuleEnabled(blink::layered_api::Module) const override;
- void BuiltInModuleUseCount(blink::layered_api::Module) const override;
+ bool BuiltInModuleEnabled(layered_api::Module) const override;
+ void BuiltInModuleUseCount(layered_api::Module) const override;
ModuleRecordResolver* GetModuleRecordResolver() override {
return module_record_resolver_.Get();
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 f8fc91cf97f..d38ecfd0038 100644
--- a/chromium/third_party/blink/renderer/core/script/module_map.cc
+++ b/chromium/third_party/blink/renderer/core/script/module_map.cc
@@ -25,7 +25,7 @@ class ModuleMap::Entry final : public GarbageCollectedFinalized<Entry>,
explicit Entry(ModuleMap*);
~Entry() override {}
- void Trace(blink::Visitor*) override;
+ void Trace(Visitor*) override;
const char* NameInHeapSnapshot() const override { return "ModuleMap::Entry"; }
// Notify fetched |m_moduleScript| to the client asynchronously.
@@ -53,7 +53,7 @@ ModuleMap::Entry::Entry(ModuleMap* map) : map_(map) {
DCHECK(map_);
}
-void ModuleMap::Entry::Trace(blink::Visitor* visitor) {
+void ModuleMap::Entry::Trace(Visitor* visitor) {
visitor->Trace(module_script_);
visitor->Trace(map_);
visitor->Trace(clients_);
@@ -100,7 +100,7 @@ ModuleMap::ModuleMap(Modulator* modulator)
DCHECK(modulator);
}
-void ModuleMap::Trace(blink::Visitor* visitor) {
+void ModuleMap::Trace(Visitor* visitor) {
visitor->Trace(map_);
visitor->Trace(modulator_);
visitor->Trace(loader_registry_);
@@ -137,7 +137,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="12">Set moduleMap[url] to module script, and asynchronously
+ // <spec step="14">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 fa0018a3cf9..46d98e67aa3 100644
--- a/chromium/third_party/blink/renderer/core/script/module_map.h
+++ b/chromium/third_party/blink/renderer/core/script/module_map.h
@@ -33,7 +33,7 @@ class CORE_EXPORT ModuleMap final : public GarbageCollected<ModuleMap>,
public:
explicit ModuleMap(Modulator*);
- void Trace(blink::Visitor*);
+ void Trace(Visitor*);
const char* NameInHeapSnapshot() const override { return "ModuleMap"; }
// https://html.spec.whatwg.org/C/#fetch-a-single-module-script
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 da2f4ab72f2..6df17a931d6 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
@@ -30,7 +30,7 @@ class TestSingleModuleClient final : public SingleModuleClient {
TestSingleModuleClient() = default;
~TestSingleModuleClient() override {}
- void Trace(blink::Visitor* visitor) override {
+ void Trace(Visitor* visitor) override {
visitor->Trace(module_script_);
SingleModuleClient::Trace(visitor);
}
@@ -64,7 +64,8 @@ class TestModuleRecordResolver final : public ModuleRecordResolver {
FAIL() << "UnregisterModuleScript shouldn't be called in ModuleMapTest";
}
- const ModuleScript* GetHostDefined(const ModuleRecord&) const override {
+ const ModuleScript* GetModuleScriptFromModuleRecord(
+ const ModuleRecord&) const override {
NOTREACHED();
return nullptr;
}
@@ -87,7 +88,7 @@ class ModuleMapTestModulator final : public DummyModulator {
explicit ModuleMapTestModulator(ScriptState*);
~ModuleMapTestModulator() override {}
- void Trace(blink::Visitor*) override;
+ void Trace(Visitor*) override;
TestModuleRecordResolver* GetTestModuleRecordResolver() {
return resolver_.Get();
@@ -117,12 +118,12 @@ class ModuleMapTestModulator final : public DummyModulator {
TestRequest* test_request = MakeGarbageCollected<TestRequest>(
ModuleScriptCreationParams(
request.Url(), ParkableString(String("").ReleaseImpl()), nullptr,
- request.GetResourceRequest().GetFetchCredentialsMode()),
+ request.GetResourceRequest().GetCredentialsMode()),
client);
modulator_->test_requests_.push_back(test_request);
}
String DebugName() const override { return "TestModuleScriptFetcher"; }
- void Trace(blink::Visitor* visitor) override {
+ void Trace(Visitor* visitor) override {
ModuleScriptFetcher::Trace(visitor);
visitor->Trace(modulator_);
}
@@ -152,7 +153,7 @@ class ModuleMapTestModulator final : public DummyModulator {
client_->NotifyFetchFinished(*params_,
HeapVector<Member<ConsoleMessage>>());
}
- void Trace(blink::Visitor* visitor) { visitor->Trace(client_); }
+ void Trace(Visitor* visitor) { visitor->Trace(client_); }
private:
base::Optional<ModuleScriptCreationParams> params_;
@@ -168,7 +169,7 @@ ModuleMapTestModulator::ModuleMapTestModulator(ScriptState* script_state)
: script_state_(script_state),
resolver_(MakeGarbageCollected<TestModuleRecordResolver>()) {}
-void ModuleMapTestModulator::Trace(blink::Visitor* visitor) {
+void ModuleMapTestModulator::Trace(Visitor* visitor) {
visitor->Trace(test_requests_);
visitor->Trace(script_state_);
visitor->Trace(resolver_);
@@ -198,8 +199,7 @@ class ModuleMapTest : public PageTestBase {
void ModuleMapTest::SetUp() {
PageTestBase::SetUp(IntSize(500, 500));
- GetDocument().SetURL(KURL("https://example.com"));
- GetDocument().SetSecurityOrigin(SecurityOrigin::Create(GetDocument().Url()));
+ NavigateTo(KURL("https://example.com"));
modulator_ = MakeGarbageCollected<ModuleMapTestModulator>(
ToScriptStateForMainWorld(&GetFrame()));
map_ = MakeGarbageCollected<ModuleMap>(modulator_);
diff --git a/chromium/third_party/blink/renderer/core/script/module_pending_script.cc b/chromium/third_party/blink/renderer/core/script/module_pending_script.cc
index cfe0735ec4f..29449ea2056 100644
--- a/chromium/third_party/blink/renderer/core/script/module_pending_script.cc
+++ b/chromium/third_party/blink/renderer/core/script/module_pending_script.cc
@@ -31,7 +31,7 @@ void ModulePendingScriptTreeClient::NotifyModuleTreeLoadFinished(
pending_script_->NotifyModuleTreeLoadFinished();
}
-void ModulePendingScriptTreeClient::Trace(blink::Visitor* visitor) {
+void ModulePendingScriptTreeClient::Trace(Visitor* visitor) {
visitor->Trace(module_script_);
visitor->Trace(pending_script_);
ModuleTreeClient::Trace(visitor);
@@ -54,7 +54,7 @@ void ModulePendingScript::DisposeInternal() {
module_tree_client_ = nullptr;
}
-void ModulePendingScript::Trace(blink::Visitor* visitor) {
+void ModulePendingScript::Trace(Visitor* visitor) {
visitor->Trace(module_tree_client_);
PendingScript::Trace(visitor);
}
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 b0253af0d6c..230d4632c4d 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
@@ -29,7 +29,7 @@ class ModulePendingScriptTreeClient final : public ModuleTreeClient {
ModuleScript* GetModuleScript() const { return module_script_; }
- void Trace(blink::Visitor*) override;
+ void Trace(Visitor*) override;
private:
// Implements ModuleTreeClient
@@ -55,7 +55,7 @@ class CORE_EXPORT ModulePendingScript : public PendingScript {
return module_tree_client_->GetModuleScript();
}
- void Trace(blink::Visitor*) override;
+ void Trace(Visitor*) override;
private:
// PendingScript
diff --git a/chromium/third_party/blink/renderer/core/script/module_record_resolver.h b/chromium/third_party/blink/renderer/core/script/module_record_resolver.h
index fb075478d8f..5fb8d6c3b7f 100644
--- a/chromium/third_party/blink/renderer/core/script/module_record_resolver.h
+++ b/chromium/third_party/blink/renderer/core/script/module_record_resolver.h
@@ -26,7 +26,7 @@ class CORE_EXPORT ModuleRecordResolver
: public GarbageCollectedFinalized<ModuleRecordResolver> {
public:
virtual ~ModuleRecordResolver() = default;
- virtual void Trace(blink::Visitor* visitor) {}
+ virtual void Trace(Visitor* visitor) {}
// Notifies the ModuleRecordResolver that a ModuleScript exists.
// This hook gives a chance for the resolver impl to populate module record
@@ -36,8 +36,8 @@ class CORE_EXPORT ModuleRecordResolver
// Notifies the ModuleRecordResolver to clear its ModuleScript mapping.
virtual void UnregisterModuleScript(const ModuleScript*) = 0;
- // Corresponds to the spec concept "[[HostDefined]]".
- virtual const ModuleScript* GetHostDefined(const ModuleRecord&) const = 0;
+ virtual const ModuleScript* GetModuleScriptFromModuleRecord(
+ const ModuleRecord&) const = 0;
// Implements "Runtime Semantics: HostResolveImportedModule"
// https://tc39.github.io/ecma262/#sec-hostresolveimportedmodule
diff --git a/chromium/third_party/blink/renderer/core/script/module_record_resolver_impl.cc b/chromium/third_party/blink/renderer/core/script/module_record_resolver_impl.cc
index 212ee50da5e..46b15431539 100644
--- a/chromium/third_party/blink/renderer/core/script/module_record_resolver_impl.cc
+++ b/chromium/third_party/blink/renderer/core/script/module_record_resolver_impl.cc
@@ -40,7 +40,7 @@ void ModuleRecordResolverImpl::UnregisterModuleScript(
record_to_module_script_map_.erase(module_script->Record());
}
-const ModuleScript* ModuleRecordResolverImpl::GetHostDefined(
+const ModuleScript* ModuleRecordResolverImpl::GetModuleScriptFromModuleRecord(
const ModuleRecord& record) const {
const auto it = record_to_module_script_map_.find(record);
CHECK_NE(it, record_to_module_script_map_.end())
@@ -58,38 +58,47 @@ ModuleRecord ModuleRecordResolverImpl::Resolve(
ExceptionState& exception_state) {
DVLOG(1) << "ModuleRecordResolverImpl::resolve(specifier=\"" << specifier
<< ", referrer.hash=" << ModuleRecordHash::GetHash(referrer) << ")";
+ // <spec step="3">If referencingScriptOrModule is not null, then:</spec>
+ //
+ // Currently this function implements the spec before
+ // https://github.com/tc39/proposal-dynamic-import is applied, i.e. where
+ // |referencingScriptOrModule| was always a non-null module script.
- // <spec step="1">Let referencing script be
- // referencingScriptOrModule.[[HostDefined]].</spec>
- const ModuleScript* referrer_module = GetHostDefined(referrer);
-
- // <spec step="2">Let moduleMap be referencing script's settings object's
- // module map.</spec>
+ // <spec step="3.2">Set settings object to referencing script's settings
+ // object.</spec>
//
- // Note: Blink finds out "module script's settings object"
- // (Modulator) from context where HostResolveImportedModule was called.
+ // <spec step="4">Let moduleMap be settings object's module map.</spec>
+ //
+ // These are |modulator_| and |this|, respectively, because module script's
+ // settings object is always the current settings object in Blink.
+
+ // <spec step="3.1">Let referencing script be
+ // referencingScriptOrModule.[[HostDefined]].</spec>
+ const ModuleScript* referrer_module =
+ GetModuleScriptFromModuleRecord(referrer);
- // <spec step="3">Let url be the result of resolving a module specifier given
- // referencing script's base URL and specifier.</spec>
+ // <spec step="3.3">Set base URL to referencing script's base URL.</spec>
+ // <spec step="5">Let url be the result of resolving a module specifier given
+ // base URL and specifier.</spec>
KURL url = referrer_module->ResolveModuleSpecifier(specifier);
- // <spec step="4">Assert: url is never failure, because resolving a module
+ // <spec step="6">Assert: url is never failure, because resolving a module
// specifier must have been previously successful with these same two
- // arguments.</spec>
+ // arguments ...</spec>
DCHECK(url.IsValid());
- // <spec step="5">Let resolved module script be moduleMap[url]. (This entry
+ // <spec step="7">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);
- // <spec step="6">Assert: resolved module script is a module script (i.e., is
+ // <spec step="8">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>
+ // <spec step="9">Assert: resolved module script's record is not null.</spec>
DCHECK(module_script);
CHECK(!module_script->Record().IsNull());
- // <spec step="8">Return resolved module script's record.</spec>
+ // <spec step="10">Return resolved module script's record.</spec>
return module_script->Record();
}
@@ -99,7 +108,7 @@ void ModuleRecordResolverImpl::ContextDestroyed(ExecutionContext*) {
record_to_module_script_map_.clear();
}
-void ModuleRecordResolverImpl::Trace(blink::Visitor* visitor) {
+void ModuleRecordResolverImpl::Trace(Visitor* visitor) {
ModuleRecordResolver::Trace(visitor);
ContextLifecycleObserver::Trace(visitor);
visitor->Trace(record_to_module_script_map_);
diff --git a/chromium/third_party/blink/renderer/core/script/module_record_resolver_impl.h b/chromium/third_party/blink/renderer/core/script/module_record_resolver_impl.h
index ecd381f27e3..ee9ec555b52 100644
--- a/chromium/third_party/blink/renderer/core/script/module_record_resolver_impl.h
+++ b/chromium/third_party/blink/renderer/core/script/module_record_resolver_impl.h
@@ -30,7 +30,7 @@ class CORE_EXPORT ModuleRecordResolverImpl final
ExecutionContext* execution_context)
: ContextLifecycleObserver(execution_context), modulator_(modulator) {}
- void Trace(blink::Visitor*) override;
+ void Trace(Visitor*) override;
USING_GARBAGE_COLLECTED_MIXIN(ModuleRecordResolverImpl);
private:
@@ -38,7 +38,8 @@ class CORE_EXPORT ModuleRecordResolverImpl final
void RegisterModuleScript(const ModuleScript*) final;
void UnregisterModuleScript(const ModuleScript*) final;
- const ModuleScript* GetHostDefined(const ModuleRecord&) const final;
+ const ModuleScript* GetModuleScriptFromModuleRecord(
+ const ModuleRecord&) const final;
// Implements "Runtime Semantics: HostResolveImportedModule" per HTML spec.
// https://html.spec.whatwg.org/C/#hostresolveimportedmodule(referencingscriptormodule,-specifier))
diff --git a/chromium/third_party/blink/renderer/core/script/module_record_resolver_impl_test.cc b/chromium/third_party/blink/renderer/core/script/module_record_resolver_impl_test.cc
index d369141fc7b..0b59125c96c 100644
--- a/chromium/third_party/blink/renderer/core/script/module_record_resolver_impl_test.cc
+++ b/chromium/third_party/blink/renderer/core/script/module_record_resolver_impl_test.cc
@@ -25,7 +25,7 @@ class ModuleRecordResolverImplTestModulator final : public DummyModulator {
ModuleRecordResolverImplTestModulator() {}
~ModuleRecordResolverImplTestModulator() override {}
- void Trace(blink::Visitor*) override;
+ void Trace(Visitor*) override;
void SetScriptState(ScriptState* script_state) {
script_state_ = script_state;
@@ -57,7 +57,7 @@ class ModuleRecordResolverImplTestModulator final : public DummyModulator {
Member<ModuleScript> module_script_;
};
-void ModuleRecordResolverImplTestModulator::Trace(blink::Visitor* visitor) {
+void ModuleRecordResolverImplTestModulator::Trace(Visitor* visitor) {
visitor->Trace(script_state_);
visitor->Trace(module_script_);
DummyModulator::Trace(visitor);
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 4879fe71667..16fbb40347e 100644
--- a/chromium/third_party/blink/renderer/core/script/module_script.cc
+++ b/chromium/third_party/blink/renderer/core/script/module_script.cc
@@ -6,6 +6,8 @@
#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
#include "third_party/blink/renderer/core/script/module_record_resolver.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/platform/bindings/script_state.h"
#include "v8/include/v8.h"
@@ -90,7 +92,7 @@ KURL ModuleScript::ResolveModuleSpecifier(const String& module_request,
return url;
}
-void ModuleScript::Trace(blink::Visitor* visitor) {
+void ModuleScript::Trace(Visitor* visitor) {
visitor->Trace(settings_object_);
visitor->Trace(record_.UnsafeCast<v8::Value>());
visitor->Trace(parse_error_);
@@ -104,6 +106,21 @@ void ModuleScript::RunScript(LocalFrame* frame, const SecurityOrigin*) {
Modulator::CaptureEvalErrorFlag::kReport);
}
+void ModuleScript::RunScriptOnWorker(WorkerGlobalScope& worker_global_scope) {
+ DCHECK(worker_global_scope.IsContextThread());
+
+ WorkerReportingProxy& worker_reporting_proxy =
+ worker_global_scope.ReportingProxy();
+
+ 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 = SettingsObject()->ExecuteModule(
+ this, Modulator::CaptureEvalErrorFlag::kReport);
+ worker_reporting_proxy.DidEvaluateModuleScript(error.IsEmpty());
+}
+
std::ostream& operator<<(std::ostream& stream,
const ModuleScript& module_script) {
stream << "ModuleScript[" << &module_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 45e7fe86874..50d32f0ed33 100644
--- a/chromium/third_party/blink/renderer/core/script/module_script.h
+++ b/chromium/third_party/blink/renderer/core/script/module_script.h
@@ -48,7 +48,7 @@ class CORE_EXPORT ModuleScript : public Script {
KURL ResolveModuleSpecifier(const String& module_request,
String* failure_reason = nullptr) const;
- void Trace(blink::Visitor*) override;
+ void Trace(Visitor*) override;
virtual void ProduceCache() {}
@@ -67,6 +67,7 @@ class CORE_EXPORT ModuleScript : public Script {
return mojom::ScriptType::kModule;
}
void RunScript(LocalFrame*, const SecurityOrigin*) override;
+ void RunScriptOnWorker(WorkerGlobalScope&) override;
friend class ModuleTreeLinkerTestModulator;
diff --git a/chromium/third_party/blink/renderer/core/script/module_script_test.cc b/chromium/third_party/blink/renderer/core/script/module_script_test.cc
index 204391421b7..6d1849c14f5 100644
--- a/chromium/third_party/blink/renderer/core/script/module_script_test.cc
+++ b/chromium/third_party/blink/renderer/core/script/module_script_test.cc
@@ -11,6 +11,7 @@
#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/script/js_module_script.h"
+#include "third_party/blink/renderer/core/script/value_wrapper_synthetic_module_script.h"
#include "third_party/blink/renderer/core/testing/dummy_modulator.h"
#include "third_party/blink/renderer/core/testing/page_test_base.h"
#include "third_party/blink/renderer/platform/loader/fetch/cached_metadata.h"
@@ -35,7 +36,7 @@ class ModuleScriptTestModulator final : public DummyModulator {
return Vector<ModuleRequest>();
}
- void Trace(blink::Visitor* visitor) override {
+ void Trace(Visitor* visitor) override {
visitor->Trace(script_state_);
DummyModulator::Trace(visitor);
}
@@ -82,6 +83,14 @@ class ModuleScriptTest : public ::testing::Test {
ScriptFetchOptions());
}
+ static ValueWrapperSyntheticModuleScript*
+ CreateValueWrapperSyntheticModuleScript(Modulator* modulator,
+ v8::Local<v8::Value> local_value) {
+ return ValueWrapperSyntheticModuleScript::CreateWithDefaultExport(
+ local_value, modulator, KURL("https://fox.url/script.js"),
+ KURL("https://fox.url/"), ScriptFetchOptions());
+ }
+
// Tests |window.foo| is set correctly, and reset |window.foo| for the next
// test.
static void TestFoo(V8TestingScope& scope) {
@@ -239,4 +248,14 @@ TEST_F(ModuleScriptTest, V8CodeCache) {
V8CodeCache::TagForCodeCache(cache_handler)));
}
-} // namespace blink
+TEST_F(ModuleScriptTest, ValueWrapperSyntheticModuleScript) {
+ V8TestingScope scope;
+ v8::Local<v8::Value> local_value(v8::Number::New(scope.GetIsolate(), 1234));
+ Modulator* modulator =
+ MakeGarbageCollected<ModuleScriptTestModulator>(scope.GetScriptState());
+ ValueWrapperSyntheticModuleScript* module_script =
+ CreateValueWrapperSyntheticModuleScript(modulator, local_value);
+ ASSERT_FALSE(module_script->Record().IsNull());
+}
+
+} // namespace blink \ No newline at end of file
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 b43e498c25a..b8fe2d8ab33 100644
--- a/chromium/third_party/blink/renderer/core/script/pending_script.cc
+++ b/chromium/third_party/blink/renderer/core/script/pending_script.cc
@@ -25,15 +25,15 @@
#include "third_party/blink/renderer/core/script/pending_script.h"
-#include "third_party/blink/public/mojom/web_feature/web_feature.mojom-shared.h"
+#include "third_party/blink/public/mojom/web_feature/web_feature.mojom-blink.h"
#include "third_party/blink/renderer/bindings/core/v8/script_controller.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/document_parser_timing.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.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/script/ignore_destructive_write_count_incrementer.h"
#include "third_party/blink/renderer/core/script/script_element_base.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/scheduler/public/frame_scheduler.h"
namespace blink {
@@ -72,7 +72,7 @@ void PendingScript::Dispose() {
DCHECK(!IsWatchingForLoad());
starting_position_ = TextPosition::BelowRangePosition();
- parser_blocking_load_start_time_ = TimeTicks();
+ parser_blocking_load_start_time_ = base::TimeTicks();
DisposeInternal();
element_ = nullptr;
@@ -122,7 +122,7 @@ ScriptElementBase* PendingScript::GetElement() const {
void PendingScript::MarkParserBlockingLoadStartTime() {
DCHECK(parser_blocking_load_start_time_.is_null());
- parser_blocking_load_start_time_ = CurrentTimeTicks();
+ parser_blocking_load_start_time_ = base::TimeTicks::Now();
}
// <specdef href="https://html.spec.whatwg.org/C/#execute-the-script-block">
@@ -172,7 +172,7 @@ void PendingScript::ExecuteScriptBlock(const KURL& document_url) {
const bool was_canceled = WasCanceled();
const bool is_external = IsExternal();
const bool created_during_document_write = WasCreatedDuringDocumentWrite();
- const TimeTicks parser_blocking_load_start_time =
+ const base::TimeTicks parser_blocking_load_start_time =
ParserBlockingLoadStartTime();
const bool is_controlled_by_script_runner = IsControlledByScriptRunner();
ScriptElementBase* element = element_;
@@ -192,7 +192,7 @@ void PendingScript::ExecuteScriptBlockInternal(
bool was_canceled,
bool is_external,
bool created_during_document_write,
- TimeTicks parser_blocking_load_start_time,
+ base::TimeTicks parser_blocking_load_start_time,
bool is_controlled_by_script_runner) {
Document& element_document = element->GetDocument();
Document* context_document = element_document.ContextDocument();
@@ -204,17 +204,17 @@ void PendingScript::ExecuteScriptBlockInternal(
return;
}
- if (parser_blocking_load_start_time > TimeTicks()) {
+ if (parser_blocking_load_start_time > base::TimeTicks()) {
DocumentParserTiming::From(element_document)
.RecordParserBlockedOnScriptLoadDuration(
- CurrentTimeTicks() - parser_blocking_load_start_time,
+ base::TimeTicks::Now() - parser_blocking_load_start_time,
created_during_document_write);
}
if (was_canceled)
return;
- TimeTicks script_exec_start_time = CurrentTimeTicks();
+ base::TimeTicks script_exec_start_time = base::TimeTicks::Now();
{
if (element->ElementHasDuplicateAttributes()) {
@@ -235,48 +235,51 @@ void PendingScript::ExecuteScriptBlockInternal(
IgnoreDestructiveWriteCountIncrementer incrementer(
needs_increment ? context_document : nullptr);
- // <spec step="4">Let old script element be the value to which the script
- // element's node document's currentScript object was most recently
+ // <spec step="4.A.1">Let old script element be the value to which the
+ // script element's node document's currentScript object was most recently
// set.</spec>
//
// This is implemented as push/popCurrentScript().
- // <spec step="5">Switch on the script's type:</spec>
- //
- // <spec step="5.A">"classic"</spec>
+ // <spec step="4">Switch on the script's type:</spec>
+
+ // <spec step="4.A">"classic"</spec>
//
- // <spec step="5.A.1">If the script element's root is not a shadow root,
+ // <spec step="4.A.2">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>
//
- // <spec step="5.B">"module"</spec>
+ // Note: The shadow root check is implemented in
+ // HTMLScriptElement::SetScriptElementForBinding().
+
+ // <spec step="4.B">"module"</spec>
//
- // <spec step="5.B.1">Set the script element's node document's currentScript
- // attribute to null.</spec>
+ // <spec step="4.B.1">Assert: The script element's node document's
+ // currentScript attribute is null.</spec>
ScriptElementBase* current_script = nullptr;
if (script->GetScriptType() == mojom::ScriptType::kClassic)
current_script = element;
context_document->PushCurrentScript(current_script);
- // <spec step="5.A">"classic"</spec>
+ // <spec step="4.A">"classic"</spec>
//
- // <spec step="5.A.2">Run the classic script given by the script's
+ // <spec step="4.A.3">Run the classic script given by the script's
// script.</spec>
//
// Note: This is where the script is compiled and actually executed.
//
- // <spec step="5.B">"module"</spec>
+ // <spec step="4.B">"module"</spec>
//
- // <spec step="5.B.2">Run the module script given by the script's
+ // <spec step="4.B.2">Run the module script given by the script's
// script.</spec>
script->RunScript(context_document->GetFrame(),
element_document.GetSecurityOrigin());
- // <spec step="6">Set the script element's node document's currentScript
+ // <spec step="4.A.4">Set the script element's node document's currentScript
// attribute to old script element.</spec>
context_document->PopCurrentScript(current_script);
- // <spec step="7">Decrement the ignore-destructive-writes counter of
+ // <spec step="5">Decrement the ignore-destructive-writes counter of
// neutralized doc, if it was incremented in the earlier step.</spec>
//
// Implemented as the scope out of IgnoreDestructiveWriteCountIncrementer.
@@ -289,17 +292,17 @@ void PendingScript::ExecuteScriptBlockInternal(
if (!is_controlled_by_script_runner) {
DocumentParserTiming::From(element_document)
.RecordParserBlockedOnScriptExecutionDuration(
- CurrentTimeTicks() - script_exec_start_time,
+ base::TimeTicks::Now() - script_exec_start_time,
created_during_document_write);
}
- // <spec step="8">If the script is from an external file, then fire an event
+ // <spec step="6">If the script is from an external file, then fire an event
// named load at the script element.</spec>
if (is_external)
element->DispatchLoadEvent();
}
-void PendingScript::Trace(blink::Visitor* visitor) {
+void PendingScript::Trace(Visitor* visitor) {
visitor->Trace(element_);
visitor->Trace(client_);
visitor->Trace(original_context_document_);
@@ -315,6 +318,7 @@ bool PendingScript::IsControlledByScriptRunner() const {
case ScriptSchedulingType::kParserBlocking:
case ScriptSchedulingType::kParserBlockingInline:
case ScriptSchedulingType::kImmediate:
+ case ScriptSchedulingType::kForceDefer:
return false;
case ScriptSchedulingType::kInOrder:
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 cfc8a018ca8..08b44d08616 100644
--- a/chromium/third_party/blink/renderer/core/script/pending_script.h
+++ b/chromium/third_party/blink/renderer/core/script/pending_script.h
@@ -53,7 +53,7 @@ class CORE_EXPORT PendingScriptClient : public GarbageCollectedMixin {
// streaming finishes.
virtual void PendingScriptFinished(PendingScript*) = 0;
- void Trace(blink::Visitor* visitor) override {}
+ void Trace(Visitor* visitor) override {}
};
// A container for an script after "prepare a script" until it is executed.
@@ -73,7 +73,7 @@ class CORE_EXPORT PendingScript
// Returns the time the load of this script started blocking the parser, or
// zero if this script hasn't yet blocked the parser, in
// monotonicallyIncreasingTime.
- TimeTicks ParserBlockingLoadStartTime() const {
+ base::TimeTicks ParserBlockingLoadStartTime() const {
return parser_blocking_load_start_time_;
}
@@ -85,7 +85,7 @@ class CORE_EXPORT PendingScript
virtual mojom::ScriptType GetScriptType() const = 0;
- virtual void Trace(blink::Visitor*);
+ virtual void Trace(Visitor*);
const char* NameInHeapSnapshot() const override { return "PendingScript"; }
// Returns nullptr when "script's script is null", i.e. an error occurred.
@@ -153,7 +153,7 @@ class CORE_EXPORT PendingScript
bool was_canceled,
bool is_external,
bool created_during_document_write,
- TimeTicks parser_blocking_load_start_time,
+ base::TimeTicks parser_blocking_load_start_time,
bool is_controlled_by_script_runner);
// |m_element| must points to the corresponding ScriptLoader's
@@ -162,7 +162,7 @@ class CORE_EXPORT PendingScript
Member<ScriptElementBase> element_;
TextPosition starting_position_; // Only used for inline script tags.
- TimeTicks parser_blocking_load_start_time_;
+ base::TimeTicks parser_blocking_load_start_time_;
ScriptSchedulingType scheduling_type_ = ScriptSchedulingType::kNotSet;
diff --git a/chromium/third_party/blink/renderer/core/script/resources/layered_api/PRESUBMIT.py b/chromium/third_party/blink/renderer/core/script/resources/layered_api/PRESUBMIT.py
new file mode 100644
index 00000000000..4364aafa726
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/script/resources/layered_api/PRESUBMIT.py
@@ -0,0 +1,39 @@
+# Copyright 2019 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+
+import sys
+
+
+def _CommonChecks(input_api, output_api):
+ results = []
+ # TODO(tkent): {kv-storage,toast,virtual-scroller}/.eslintrc.js specify babel-eslint parser, which
+ # is not in third_party/node/node_modules/.
+ mjs_files = input_api.AffectedFiles(
+ file_filter=lambda f: (f.LocalPath().endswith('.mjs') and
+ not '/virtual-scroller/' in f.LocalPath() and
+ not '/kv-storage/' in f.LocalPath() and
+ not '/toast/' in f.LocalPath()),
+ include_deletes=False)
+ if not mjs_files:
+ return results
+ try:
+ old_sys_path = sys.path[:]
+ cwd = input_api.PresubmitLocalPath()
+ sys.path += [input_api.os_path.join(cwd, '..', '..', '..', '..', '..',
+ '..', '..', 'tools')]
+ import web_dev_style.js_checker
+ checker = web_dev_style.js_checker.JSChecker(input_api, output_api)
+ results += checker.RunEsLintChecks(mjs_files)
+ finally:
+ sys.path = old_sys_path
+ return results
+
+
+def CheckChangeOnUpload(input_api, output_api):
+ return _CommonChecks(input_api, output_api)
+
+
+def CheckChangeOnCommit(input_api, output_api):
+ return _CommonChecks(input_api, output_api)
diff --git a/chromium/third_party/blink/renderer/core/script/resources/layered_api/README.md b/chromium/third_party/blink/renderer/core/script/resources/layered_api/README.md
index 270d8117aa5..479818efa35 100644
--- a/chromium/third_party/blink/renderer/core/script/resources/layered_api/README.md
+++ b/chromium/third_party/blink/renderer/core/script/resources/layered_api/README.md
@@ -22,11 +22,27 @@ and commit these files together with the changes under resources/layered_api/.
## Which files are bundled
-All files under this directory will be included in the grdp and thus bundled
-in the Chromium binary, except for
+All files under
-- Files directly under `core/script/resources/layered_api`, or
-- Files starting with '.', 'README', or 'OWNERS'.
+- Sub-directories which have 'index.mjs' or
+- Directories of which last path component is 'internal'
+
+will be included in the grdp and thus bundled in the Chrome binary,
+except for files starting with '.', 'README', or 'OWNERS'.
So be careful about binary size increase when you add new files or add more
contents to existing files.
+
+## What are exposed
+
+All bundled resources are mapped to `std-internal://path-relative-to-here`, and
+`std-internal:` resources are not accessible from the web. Resources loaded as
+`std-internal:` can import other `std-internal:` resources.
+
+For example, `layered_api/foo/bar/baz.mjs` is mapped to
+`std-internal://foo/bar/baz.mjs`.
+
+All `index.mjs` resources are mapped to `std:directory-name-relative-to-here`
+too, and they are web-exposed. For example,
+`layered_api/elements/toast/index.mjs` is mapped to `std:elements/toast` as
+well as `std-internal://elements/toast/index.mjs`.
diff --git a/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/internal/reflection.mjs b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/internal/reflection.mjs
new file mode 100644
index 00000000000..989a4aa1ff1
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/internal/reflection.mjs
@@ -0,0 +1,63 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+/**
+ * @file Manage attribute-property reflections.
+ * https://html.spec.whatwg.org/C/common-dom-interfaces.html#reflecting-content-attributes-in-idl-attributes
+ */
+
+/**
+ * Add a bool reflection property to the specified prototype for the specified
+ * attribute.
+ *
+ * @param {!Object} proto An element prototype
+ * @param {string} attrName An attribute name
+ * @param {string} propName An optional property name. attrName will be used if
+ * this argument is omitted.
+ */
+export function installBool(proto, attrName, propName = attrName) {
+ let getter = function() {
+ return this.hasAttribute(attrName);
+ };
+ let setter = function(value) {
+ this.toggleAttribute(attrName, Boolean(value));
+ };
+ Object.defineProperty(
+ getter, 'name',
+ {configurable: true, enumerable: false, value: 'get ' + propName});
+ Object.defineProperty(
+ setter, 'name',
+ {configurable: true, enumerable: false, value: 'set ' + propName});
+ Object.defineProperty(
+ proto, propName,
+ {configurable: true, enumerable: true, get: getter, set: setter});
+}
+
+/**
+ * Add a DOMString reflection property to the specified prototype for the
+ * specified attribute.
+ *
+ * @param {!Element} element An element prototype
+ * @param {string} attrName An attribute name
+ * @param {string} propName An optional property name. attrName will be used if
+ * this argument is omitted.
+ */
+export function installString(proto, attrName, propName = attrName) {
+ let getter = function() {
+ let value = this.getAttribute(attrName);
+ return value === null ? '' : value;
+ };
+ let setter = function(value) {
+ this.setAttribute(attrName, value);
+ };
+ Object.defineProperty(
+ getter, 'name',
+ {configurable: true, enumerable: false, value: 'get ' + propName});
+ Object.defineProperty(
+ setter, 'name',
+ {configurable: true, enumerable: false, value: 'set ' + propName});
+ Object.defineProperty(
+ proto, propName,
+ {configurable: true, enumerable: true, get: getter, set: setter});
+}
diff --git a/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/switch/README.md b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/switch/README.md
new file mode 100644
index 00000000000..c8962f767cb
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/switch/README.md
@@ -0,0 +1,3 @@
+# Switch control element
+
+https://github.com/tkent-google/std-switch/blob/master/README.md
diff --git a/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/switch/face_utils.mjs b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/switch/face_utils.mjs
new file mode 100644
index 00000000000..8db1f4177ff
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/switch/face_utils.mjs
@@ -0,0 +1,75 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+/**
+ * @file Utilities for form-associated custom elements
+ */
+
+import * as reflection from '../internal/reflection.mjs';
+
+function installGetter(proto, propName, getter) {
+ Object.defineProperty(
+ getter, 'name',
+ {configurable: true, enumerable: false, value: 'get ' + propName});
+ Object.defineProperty(
+ proto, propName, {configurable: true, enumerable: true, get: getter});
+}
+
+/**
+ * Add the following properties to |proto|.
+ * - disabled
+ * - name
+ * - type
+ * - form
+ * - willValidate
+ * - validity
+ * - validationMessage
+ * - labels
+ * - checkValidity()
+ * - reportValidity()
+ * - setCustomValidity(error)
+ *
+ * @param {!Object} proto An Element prototype which will have properties
+ * @param {!Symbol} internals A Symbol of the ElementInternals property of the
+ * element
+ */
+export function installPropertiesAndFunctions(proto, internals) {
+ reflection.installBool(proto, 'disabled');
+ reflection.installString(proto, 'name');
+ installGetter(proto, 'type', function() {
+ if (!(this instanceof proto.constructor)) {
+ throw TypeError(
+ 'The context object is not an instance of ' + proto.contructor.name);
+ }
+ return this.localName;
+ });
+
+ installGetter(proto, 'form', function() {
+ return this[internals].form;
+ });
+ installGetter(proto, 'willValidate', function() {
+ return this[internals].willValidate;
+ });
+ installGetter(proto, 'validity', function() {
+ return this[internals].validity;
+ });
+ installGetter(proto, 'validationMessage', function() {
+ return this[internals].validationMessage;
+ });
+ installGetter(proto, 'labels', function() {
+ return this[internals].labels;
+ });
+ proto.checkValidity = function() {
+ return this[internals].checkValidity();
+ };
+ proto.reportValidity = function() {
+ return this[internals].reportValidity();
+ };
+ proto.setCustomValidity = function(error) {
+ if (error === undefined) {
+ throw new TypeError('Too few arguments');
+ }
+ this[internals].setValidity({customError: true}, error);
+ };
+}
diff --git a/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/switch/index.mjs b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/switch/index.mjs
new file mode 100644
index 00000000000..6c7be3d46fc
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/switch/index.mjs
@@ -0,0 +1,128 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+import * as face from './face_utils.mjs';
+import * as reflection from '../internal/reflection.mjs';
+import { SwitchTrack } from './track.mjs';
+import * as style from './style.mjs';
+
+// https://github.com/tkent-google/std-switch/issues/2
+const STATE_ATTR = 'on';
+
+// Private property symbols
+// TODO(tkent): Use private fields.
+const _internals = Symbol();
+const _track = Symbol();
+const _rippleElement = Symbol();
+const _containerElement = Symbol();
+
+export class StdSwitchElement extends HTMLElement {
+ // TODO(tkent): The following should be |static fooBar = value;|
+ // after enabling babel-eslint.
+ static get formAssociated() {
+ return true;
+ }
+ static get observedAttributes() {
+ return [STATE_ATTR];
+ }
+
+ constructor() {
+ super();
+ if (new.target !== StdSwitchElement) {
+ throw new TypeError('Illegal constructor: StdSwitchElement is not ' +
+ 'extensible for now');
+ }
+ this[_internals] = this.attachInternals();
+ this._initializeDOM();
+
+ this.addEventListener('click', this._onClick);
+ this.addEventListener('keypress', this._onKeyPress);
+ }
+
+ attributeChangedCallback(attrName, oldValue, newValue) {
+ if (attrName == STATE_ATTR) {
+ this[_track].value = newValue !== null;
+ // TODO(tkent): We should not add aria-checked attribute.
+ // https://github.com/WICG/aom/issues/127
+ this.setAttribute('aria-checked', newValue !== null ? 'true' : 'false');
+ }
+ }
+
+ connectedCallback() {
+ // TODO(tkent): We should not add tabindex attribute.
+ // https://github.com/w3c/webcomponents/issues/762
+ if (!this.hasAttribute('tabindex')) {
+ this.setAttribute('tabindex', '0');
+ }
+
+ // TODO(tkent): We should not add role attribute.
+ // https://github.com/WICG/aom/issues/127
+ if (!this.hasAttribute('role')) {
+ this.setAttribute('role', 'switch');
+ }
+ }
+
+ // TODO(tkent): Make this private.
+ _initializeDOM() {
+ let factory = this.ownerDocument;
+ let root = this.attachShadow({mode: 'closed'});
+ this[_containerElement] = factory.createElement('span');
+ this[_containerElement].id = 'container';
+ // Shadow elements should be invisible for a11y technologies.
+ this[_containerElement].setAttribute('aria-hidden', 'true');
+ root.appendChild(this[_containerElement]);
+
+ this[_track] = new SwitchTrack(factory);
+ this[_containerElement].appendChild(this[_track].element);
+ this[_track].value = this.on;
+
+ let thumbElement = this[_containerElement].appendChild(factory.createElement('span'));
+ thumbElement.id = 'thumb';
+ thumbElement.part.add('thumb');
+
+ this[_rippleElement] = thumbElement.appendChild(factory.createElement('span'));
+ this[_rippleElement].id = 'ripple';
+
+ root.adoptedStyleSheets = [style.styleSheetFactory()()];
+ }
+
+ // TODO(tkent): Make this private.
+ _onClick(event) {
+ for (let element of this[_containerElement].querySelectorAll('*')) {
+ style.markTransition(element);
+ }
+ this.on = !this.on;
+ this.dispatchEvent(new Event('input', {bubbles: true}));
+ this.dispatchEvent(new Event('change', {bubbles: true}));
+ }
+
+ // TODO(tkent): Make this private.
+ _onKeyPress(event) {
+ if (event.code == 'Space') {
+ // Do not scroll the page.
+ event.preventDefault();
+ this._onClick(event);
+ }
+ }
+}
+
+reflection.installBool(StdSwitchElement.prototype, STATE_ATTR);
+reflection.installBool(
+ StdSwitchElement.prototype, 'default' + STATE_ATTR,
+ 'default' + STATE_ATTR.charAt(0).toUpperCase() + STATE_ATTR.substring(1));
+face.installPropertiesAndFunctions(StdSwitchElement.prototype, _internals);
+
+// This is necessary for anyObject.toString.call(switchInstance).
+Object.defineProperty(StdSwitchElement.prototype, Symbol.toStringTag, {
+ configurable: true,
+ enumerable: false,
+ value: 'StdSwitchElement',
+ writable: false
+});
+
+customElements.define('std-switch', StdSwitchElement);
+delete StdSwitchElement.formAssociated;
+delete StdSwitchElement.observedAttributes;
+delete StdSwitchElement.prototype.attributeChangedCallback;
+delete StdSwitchElement.prototype.connectedCallback;
diff --git a/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/switch/style.mjs b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/switch/style.mjs
new file mode 100644
index 00000000000..6b0bc2eca78
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/switch/style.mjs
@@ -0,0 +1,224 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// Style constant values.
+const COLOR_ON = '#0077FF';
+const TRACK_RADIUS = '13px';
+const TRACK_BORDER_WIDTH = '2px';
+const THUMB_HEIGHT = '22px';
+const THUMB_WIDTH = '22px';
+const THUMB_MARGIN_START = '2px';
+const THUMB_MARGIN_END = '2px';
+
+// Returns a function returning a CSSStyleSheet().
+// TODO(tkent): Share this stylesheet factory feature with elements/toast/.
+export function styleSheetFactory() {
+ let styleSheet;
+ return () => {
+ if (!styleSheet) {
+ styleSheet = new CSSStyleSheet();
+ styleSheet.replaceSync(`
+:host {
+ block-size: 26px;
+ border: none;
+ box-sizing: border-box;
+ display: inline-block;
+ inline-size: 54px;
+ user-select: none;
+ vertical-align: middle;
+}
+
+#container {
+ align-items: center;
+ block-size: 100%;
+ display: inline-flex;
+ inline-size: 100%;
+}
+
+#thumb {
+ background: white;
+ block-size: ${THUMB_HEIGHT};
+ border-radius: calc(${THUMB_HEIGHT} / 2);
+ border: 1px solid black;
+ box-sizing: border-box;
+ display: inline-block;
+ margin-inline-start: calc(-100% + ${THUMB_MARGIN_START});
+ inline-size: ${THUMB_WIDTH};
+}
+
+/* :host::part(thumb-transitioning) doesn't work. crbug.com/980506 */
+#thumb[part~="thumb-transitioning"] {
+ transition: all linear 0.1s;
+}
+
+:host([on]) #thumb {
+ border: 1px solid ${COLOR_ON};
+ margin-inline-start: calc(0px - ${THUMB_WIDTH} - ${THUMB_MARGIN_END});
+}
+
+#track {
+ block-size: 100%;
+ border-radius: ${TRACK_RADIUS};
+ border: ${TRACK_BORDER_WIDTH} solid #dddddd;
+ box-shadow: 0 0 0 1px #f8f8f8;
+ box-sizing: border-box;
+ display: inline-block;
+ inline-size: 100%;
+ overflow: hidden;
+ padding: 0px;
+}
+
+#trackFill {
+ background: ${COLOR_ON};
+ block-size: 100%;
+ border-radius: calc(${TRACK_RADIUS}) - ${TRACK_BORDER_WIDTH});
+ box-shadow: none;
+ box-sizing: border-box;
+ display: inline-block;
+ inline-size: 0%;
+ vertical-align: top;
+}
+
+#trackFill[part~="track-fill-transitioning"] {
+ transition: all linear 0.1s;
+}
+
+:host([on]) #track {
+ border: ${TRACK_BORDER_WIDTH} solid ${COLOR_ON};
+}
+
+:host(:focus) {
+ outline-offset: 4px;
+}
+
+:host(:focus) #track {
+ box-shadow: 0 0 0 2px #f8f8f8;
+}
+
+:host([on]:focus) #track {
+ box-shadow: 0 0 0 2px #dddddd;
+}
+
+:host(:focus) #thumb {
+ border: 2px solid black;
+}
+
+:host([on]:focus) #thumb {
+ border: 2px solid ${COLOR_ON};
+}
+
+:host(:not(:focus-visible):focus) {
+ outline: none;
+}
+
+:host(:not(:disabled):hover) #thumb {
+ inline-size: 26px;
+}
+
+:host([on]:not(:disabled):hover) #thumb {
+ margin-inline-start: calc(0px - 26px - ${THUMB_MARGIN_END});
+}
+
+:host(:active) #track {
+ background: #dddddd;
+}
+
+:host([on]:active) #track {
+ border: 2px solid #77bbff;
+ box-shadow: 0 0 0 2px #f8f8f8;
+}
+
+:host([on]:active) #trackFill {
+ background: #77bbff;
+}
+
+:host(:disabled) {
+ opacity: 0.38;
+}
+
+/*
+ * display:inline-block in the :host ruleset overrides 'hidden' handling
+ * by the user agent.
+ */
+:host([hidden]) {
+ display: none;
+}
+
+`);
+ }
+ return styleSheet;
+ };
+}
+
+/**
+ * @param {!Element} element
+ */
+function setupTransitionCounter(element) {
+ if (element.runningTransitions !== undefined) {
+ return;
+ }
+ element.runningTransitions = 0;
+ element.addEventListener('transitionrun', e => {
+ if (e.target === element) {
+ ++element.runningTransitions;
+ }
+ });
+ let handleEndOrCancel = e => {
+ // Need to check runningTransitions>0 due to superfluous transitioncancel
+ // events; crbug.com/979556.
+ if (e.target === element && element.runningTransitions > 0) {
+ --element.runningTransitions;
+ }
+ };
+ element.addEventListener('transitionend', handleEndOrCancel);
+ element.addEventListener('transitioncancel', handleEndOrCancel);
+}
+
+/**
+ * Add '$part-transitioning' part to the element, and remove it on 'transitionend'
+ * event or remove it immediately if the element has no transitions.
+ *
+ * TODO(tkent): We should apply custom state.
+ *
+ * @param {!Element} element
+ */
+export function markTransition(element) {
+ // Should check hasAttribute() to avoid creating a DOMTokenList instance.
+ if (!element.hasAttribute('part') || element.part.length < 1) {
+ return;
+ }
+
+ setupTransitionCounter(element);
+
+ const partName = element.part[0] + '-transitioning';
+ if (element.part.contains(partName)) {
+ return;
+ }
+ // The style with partName might have transitions, and might have no
+ // transitions. We need to add partName anyway because we have no other
+ // ways to check existence of transitions. Then, we need to remove
+ // partName because state change without markTransition() should have
+ // style without partName.
+ //
+ // We add partName in an animation frame, and continue to request
+ // animation frames until runningTransitions becomes 0. If the style with
+ // partName has no transitions, runningTransitions keeps 0, and the second
+ // animation frame removes partName.
+ window.requestAnimationFrame(() => {
+ element.part.add(partName);
+
+ // If the element has a transition, it must start on the rendering just
+ // after this rAF callback. So we check runningTransitions in the next
+ // frame.
+ const removeIfNoTransitions = () => {
+ // No transitions started, or all transitions were completed.
+ if (element.runningTransitions === 0) {
+ element.part.remove(partName);
+ } else {
+ window.requestAnimationFrame(removeIfNoTransitions);
+ }
+ };
+ window.requestAnimationFrame(removeIfNoTransitions);
+ });
+}
diff --git a/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/switch/track.mjs b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/switch/track.mjs
new file mode 100644
index 00000000000..aa8fc00c3d1
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/switch/track.mjs
@@ -0,0 +1,74 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// Private property symbols
+// TODO(tkent): Use private fields.
+const _value = Symbol();
+const _trackElement = Symbol();
+const _fillElement = Symbol();
+const _slotElement = Symbol();
+
+export class SwitchTrack {
+
+ /**
+ * @param {!Document} factory A factory for elements created for this track.
+ */
+ constructor(factory) {
+ this[_value] = false;
+ this._initializeDOM(factory);
+ }
+
+ /**
+ * @return {!Element}
+ */
+ get element() {
+ return this[_trackElement];
+ }
+
+ /**
+ * @param {Boolean} newValue
+ */
+ set value(newValue) {
+ let oldValue = this[_value];
+ this[_value] = Boolean(newValue);
+
+ let bar = this[_fillElement];
+ if (bar) {
+ bar.style.inlineSize = this[_value] ? '100%' : '0%';
+ if (oldValue != this[_value]) {
+ this._addSlot();
+ }
+ }
+ }
+
+ // TODO(tkent): Use private fields. #initializeDOM = factory => { ...};
+ /**
+ * @param {!Document} factory A factory for elements created for this track.
+ */
+ _initializeDOM(factory) {
+ this[_trackElement] = factory.createElement('div');
+ this[_trackElement].id = 'track';
+ this[_trackElement].part.add('track');
+ this[_fillElement] = factory.createElement('span');
+ this[_fillElement].id = 'trackFill';
+ this[_fillElement].part.add('track-fill');
+ this[_trackElement].appendChild(this[_fillElement]);
+ this[_slotElement] = factory.createElement('slot');
+ this._addSlot();
+ }
+
+ /**
+ * Add the <slot>
+ * - next to _fillElement if _value is true
+ * - as a child of _fillElement if _value is false
+ * This behavior is helpful to show text in the track.
+ */
+ _addSlot() {
+ if (this[_value]) {
+ this[_fillElement].appendChild(this[_slotElement]);
+ } else {
+ this[_trackElement].appendChild(this[_slotElement]);
+ }
+ }
+}
diff --git a/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/toast/.eslintrc.js b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/toast/.eslintrc.js
new file mode 100644
index 00000000000..8f9a67630c4
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/toast/.eslintrc.js
@@ -0,0 +1,338 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+module.exports = {
+ root: true,
+ env: {
+ es6: true,
+ browser: true
+ },
+ 'parser': 'babel-eslint',
+ parserOptions: {
+ sourceType: 'module',
+ ecmaVersion: 2019
+ },
+ rules: {
+ 'for-direction': 'error',
+ 'getter-return': 'error',
+ 'no-async-promise-executor': 'error',
+ 'no-await-in-loop': 'error',
+ 'no-compare-neg-zero': 'error',
+ 'no-cond-assign': ['error', 'except-parens'],
+ 'no-console': 'error',
+ 'no-constant-condition': ['error', {checkLoops: false}],
+ 'no-control-regex': 'error',
+ 'no-debugger': 'error',
+ 'no-dupe-args': 'error',
+ 'no-dupe-keys': 'error',
+ 'no-duplicate-case': 'error',
+ 'no-empty': 'error',
+ 'no-empty-character-class': 'error',
+ 'no-ex-assign': 'error',
+ 'no-extra-boolean-cast': 'error',
+ 'no-extra-parens': [
+ 'error',
+ 'all',
+ {
+ conditionalAssign: false,
+ nestedBinaryExpressions: false,
+ returnAssign: false
+ }
+ ],
+ 'no-extra-semi': 'error',
+ 'no-func-assign': 'error',
+ 'no-inner-declarations': 'off',
+ 'no-invalid-regexp': 'error',
+ 'no-irregular-whitespace': 'error',
+ 'no-misleading-character-class': 'error',
+ 'no-obj-calls': 'error',
+ 'no-prototype-builtins': 'error',
+ 'no-regex-spaces': 'error',
+ 'no-sparse-arrays': 'error',
+ 'no-template-curly-in-string': 'error',
+ 'no-unexpected-multiline': 'error',
+ 'no-unreachable': 'error',
+ 'no-unsafe-finally': 'off',
+ 'no-unsafe-negation': 'error',
+ 'use-isnan': 'error',
+ 'valid-typeof': 'error',
+ 'accessor-pairs': 'error',
+ 'array-callback-return': 'error',
+ 'block-scoped-var': 'off',
+ 'class-methods-use-this': 'off',
+ 'complexity': 'off',
+ 'consistent-return': 'error',
+ 'curly': ['error', 'all'],
+ 'default-case': 'off',
+ 'dot-location': ['error', 'property'],
+ 'dot-notation': 'error',
+ 'eqeqeq': 'error',
+ 'guard-for-in': 'off',
+ 'no-alert': 'error',
+ 'no-caller': 'error',
+ 'no-case-declarations': 'error',
+ 'no-div-regex': 'off',
+ 'no-else-return': 'error',
+ 'no-empty-function': 'off',
+ 'no-empty-pattern': 'error',
+ 'no-eq-null': 'error',
+ 'no-eval': 'error',
+ 'no-extend-native': 'error',
+ 'no-extra-bind': 'error',
+ 'no-extra-label': 'error',
+ 'no-fallthrough': 'error',
+ 'no-floating-decimal': 'error',
+ 'no-global-assign': 'error',
+ 'no-implicit-coercion': 'error',
+ 'no-implicit-globals': 'error',
+ 'no-implied-eval': 'error',
+ 'no-invalid-this': 'error',
+ 'no-iterator': 'error',
+ 'no-labels': ['error', {allowLoop: true}],
+ 'no-lone-blocks': 'error',
+ 'no-loop-func': 'error',
+ 'no-magic-numbers': ['error', {ignore: [0, 1]}],
+ 'no-multi-spaces': ['error', {ignoreEOLComments: true}],
+ 'no-multi-str': 'error',
+ 'no-new': 'error',
+ 'no-new-func': 'error',
+ 'no-new-wrappers': 'error',
+ 'no-octal': 'error',
+ 'no-octal-escape': 'error',
+ 'no-param-reassign': 'off',
+ 'no-process-env': 'error',
+ 'no-proto': 'error',
+ 'no-redeclare': 'error',
+ 'no-restricted-properties': 'off',
+ 'no-return-assign': ['error', 'except-parens'],
+ 'no-return-await': 'error',
+ 'no-script-url': 'off',
+ 'no-self-assign': 'error',
+ 'no-self-compare': 'error',
+ 'no-sequences': 'error',
+ 'no-throw-literal': 'error',
+ 'no-unmodified-loop-condition': 'error',
+ 'no-unused-expressions': 'error',
+ 'no-unused-labels': 'error',
+ 'no-useless-call': 'error',
+ 'no-useless-concat': 'error',
+ 'no-useless-escape': 'error',
+ 'no-useless-return': 'error',
+ 'no-void': 'error',
+ 'no-warning-comments': 'off',
+ 'no-with': 'error',
+ 'prefer-promise-reject-errors': 'error',
+ 'radix': ['error', 'as-needed'],
+ 'require-await': 'off',
+ 'vars-on-top': 'off',
+ 'wrap-iife': ['error', 'outside'],
+ 'yoda': ['error', 'never'],
+ 'strict': ['error', 'global'],
+ 'init-declarations': 'off',
+ 'no-delete-var': 'error',
+ 'no-label-var': 'error',
+ 'no-restricted-globals': 'off',
+ 'no-shadow': 'error',
+ 'no-shadow-restricted-names': 'error',
+ 'no-undef': 'error',
+ 'no-undef-init': 'error',
+ 'no-undefined': 'off',
+ 'no-unused-vars': 'error',
+ 'no-use-before-define': ['error', 'nofunc'],
+ 'callback-return': 'off',
+ 'global-require': 'error',
+ 'handle-callback-err': 'error',
+ 'no-buffer-constructor': 'error',
+ 'no-mixed-requires': ['error', true],
+ 'no-new-require': 'error',
+ 'no-path-concat': 'error',
+ 'no-process-exit': 'error',
+ 'no-restricted-modules': 'off',
+ 'no-sync': 'off',
+ 'array-bracket-newline': ['error', {multiline: true}],
+ 'array-bracket-spacing': ['error', 'never'],
+ 'array-element-newline': 'off',
+ 'block-spacing': ['error', 'always'],
+ 'brace-style': [
+ 'error',
+ '1tbs',
+ {allowSingleLine: false}
+ ],
+ camelcase: ['error', {properties: 'always'}],
+ 'capitalized-comments': 'off',
+ 'comma-dangle': ['error', 'always-multiline'],
+ 'comma-spacing': [
+ 'error',
+ {
+ before: false,
+ after: true
+ }
+ ],
+ 'comma-style': ['error', 'last'],
+ 'computed-property-spacing': ['error', 'never'],
+ 'consistent-this': 'off',
+ 'eol-last': 'error',
+ 'func-call-spacing': ['error', 'never'],
+ 'func-name-matching': 'error',
+ 'func-names': 'off',
+ 'func-style': ['error', 'declaration'],
+ 'function-paren-newline': 'off',
+ 'id-blacklist': 'off',
+ 'id-length': 'off',
+ 'id-match': 'off',
+ indent: 'off', // not really compatible with clang-format
+ 'jsx-quotes': 'off',
+ 'key-spacing': [
+ 'error',
+ {
+ beforeColon: false,
+ afterColon: true,
+ mode: 'strict'
+ }
+ ],
+ 'keyword-spacing': [
+ 'error',
+ {
+ before: true,
+ after: true
+ }
+ ],
+ 'line-comment-position': 'off',
+ 'linebreak-style': ['error', 'unix'],
+ 'lines-around-comment': 'off',
+ 'max-depth': 'off',
+ 'max-len': 'off',
+ 'max-lines': 'off',
+ 'max-nested-callbacks': 'off',
+ 'max-params': 'off',
+ 'max-statements': 'off',
+ 'max-statements-per-line': ['error', {max: 1}],
+ 'multiline-ternary': ['error', 'always-multiline'],
+ 'new-cap': 'error',
+ 'new-parens': 'error',
+ 'newline-per-chained-call': 'off',
+ 'no-array-constructor': 'error',
+ 'no-bitwise': 'off',
+ 'no-continue': 'off',
+ 'no-inline-comments': 'off',
+ 'no-lonely-if': 'error',
+ 'no-mixed-operators': [
+ 'error',
+ {
+ groups: [
+ ['&', '|', '^', '~', '<<', '>>', '>>>'],
+ ['==', '!=', '===', '!==', '>', '>=', '<', '<='],
+ ['&&', '||'],
+ ['in', 'instanceof']
+ ]
+ }
+ ],
+ 'no-mixed-spaces-and-tabs': 'error',
+ 'no-multi-assign': 'off',
+ 'no-multiple-empty-lines': 'error',
+ 'no-negated-condition': 'off',
+ 'no-nested-ternary': 'error',
+ 'no-new-object': 'error',
+ 'no-plusplus': 'off',
+ 'no-restricted-syntax': 'off',
+ 'no-tabs': 'error',
+ 'no-ternary': 'off',
+ 'no-trailing-spaces': 'error',
+ 'no-underscore-dangle': 'off',
+ 'no-unneeded-ternary': 'error',
+ 'no-whitespace-before-property': 'error',
+ 'nonblock-statement-body-position': 'error',
+ 'object-curly-newline': ['error', {consistent: true}],
+ 'object-curly-spacing': ['error', 'never'],
+ 'object-property-newline': 'off',
+ 'one-var': ['error', 'never'],
+ 'one-var-declaration-per-line': ['error', 'initializations'],
+ 'operator-assignment': ['error', 'always'],
+ 'operator-linebreak': ['error', 'after'],
+ 'padded-blocks': ['error', 'never'],
+ 'padding-line-between-statements': 'off',
+ 'quote-props': ['error', 'as-needed'],
+ quotes: [
+ 'error',
+ 'single',
+ {
+ avoidEscape: true,
+ allowTemplateLiterals: true
+ }
+ ],
+ semi: ['error', 'always'],
+ 'semi-spacing': 'error',
+ 'semi-style': 'error',
+ 'sort-keys': 'off',
+ 'sort-vars': 'off',
+ 'space-before-blocks': ['error', 'always'],
+ 'space-before-function-paren': [
+ 'error',
+ {
+ anonymous: 'always',
+ named: 'never'
+ }
+ ],
+ 'space-in-parens': ['error', 'never'],
+ 'space-infix-ops': 'error',
+ 'space-unary-ops': [
+ 'error',
+ {
+ words: true,
+ nonwords: false
+ }
+ ],
+ 'spaced-comment': ['error', 'always'],
+ 'switch-colon-spacing': 'error',
+ 'template-tag-spacing': 'error',
+ 'unicode-bom': 'error',
+ 'wrap-regex': 'off',
+ 'arrow-body-style': 'off',
+ 'arrow-parens': ['error', 'as-needed'],
+ 'arrow-spacing': 'error',
+ 'constructor-super': 'error',
+ 'generator-star-spacing': ['error', 'neither'],
+ 'no-class-assign': 'error',
+ 'no-confusing-arrow': 'off',
+ 'no-const-assign': 'error',
+ 'no-dupe-class-members': 'error',
+ 'no-duplicate-imports': 'error',
+ 'no-new-symbol': 'error',
+ 'no-restricted-imports': 'off',
+ 'no-this-before-super': 'error',
+ 'no-useless-computed-key': 'error',
+ 'no-useless-constructor': 'error',
+ 'no-useless-rename': 'error',
+ 'no-var': 'error',
+ 'object-shorthand': 'error',
+ 'prefer-arrow-callback': 'error',
+ 'prefer-const': ['error', {ignoreReadBeforeAssign: true}],
+ 'prefer-destructuring': [
+ 'error',
+ {
+ VariableDeclarator: {
+ array: false,
+ object: true
+ },
+ AssignmentExpression: {
+ array: false,
+ object: false
+ }
+ },
+ {
+ enforceForRenamedProperties: false
+ }
+ ],
+ 'prefer-numeric-literals': 'error',
+ 'prefer-rest-params': 'error',
+ 'prefer-spread': 'error',
+ 'prefer-template': 'off',
+ 'require-yield': 'error',
+ 'rest-spread-spacing': 'error',
+ 'sort-imports': 'off',
+ 'symbol-description': 'error',
+ 'template-curly-spacing': ['error', 'never'],
+ 'yield-star-spacing': ['error', 'after']
+ }
+};
diff --git a/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/toast/OWNERS b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/toast/OWNERS
new file mode 100644
index 00000000000..d76cdfa11f0
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/toast/OWNERS
@@ -0,0 +1 @@
+fergal@chromium.org
diff --git a/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/toast/index.mjs b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/toast/index.mjs
new file mode 100644
index 00000000000..69232f8475a
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/toast/index.mjs
@@ -0,0 +1,280 @@
+/**
+ * Copyright 2019 The Chromium Authors. All rights reserved.
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ *
+ * @fileoverview This file defines the class for the Standard Toast LAPI
+ * and the accompanying showToast() function.
+ * EXPLAINER: https://github.com/jackbsteinberg/std-toast
+ * TEST PATH: /chromium/src/third_party/blink/web_tests/external/wpt/std-toast/*
+ * @package
+ */
+
+import * as reflection from '../internal/reflection.mjs';
+
+const DEFAULT_DURATION = 3000;
+const TYPES = new Set(['success', 'warning', 'error']);
+
+function stylesheetFactory() {
+ let stylesheet;
+ return function generate() {
+ if (!stylesheet) {
+ stylesheet = new CSSStyleSheet();
+ stylesheet.replaceSync(`
+ :host {
+ position: fixed;
+ bottom: 1em;
+ right: 1em;
+ border: solid;
+ padding: 1em;
+ background: white;
+ color: black;
+ z-index: 1;
+ }
+
+ :host(:not([open])) {
+ display: none;
+ }
+
+ .default-closebutton {
+ user-select: none;
+ }
+
+ :host([type=success i]) {
+ border-color: green;
+ }
+
+ :host([type=warning i]) {
+ border-color: orange;
+ }
+
+ :host([type=error i]) {
+ border-color: red;
+ }
+ `);
+ // TODO(jacksteinberg): use offset-block-end: / offset-inline-end: over bottom: / right:
+ // when implemented https://bugs.chromium.org/p/chromium/issues/detail?id=538475
+ }
+ return stylesheet;
+ };
+}
+
+const generateStylesheet = stylesheetFactory();
+
+export class StdToastElement extends HTMLElement {
+ static observedAttributes = ['open', 'closebutton'];
+ #shadow = this.attachShadow({mode: 'closed'});
+ #timeoutID;
+ #actionSlot;
+ #closeButtonElement;
+ #setCloseTimeout = duration => {
+ clearTimeout(this.#timeoutID);
+
+ if (duration === Infinity) {
+ this.#timeoutID = null;
+ } else {
+ this.#timeoutID = setTimeout(() => {
+ this.removeAttribute('open');
+ }, duration);
+ }
+ };
+
+ constructor(message) {
+ super();
+
+ this.#shadow.adoptedStyleSheets = [generateStylesheet()];
+
+ this.#shadow.appendChild(document.createElement('slot'));
+
+ this.#actionSlot = document.createElement('slot');
+ this.#actionSlot.setAttribute('name', 'action');
+ this.#shadow.appendChild(this.#actionSlot);
+
+ this.#closeButtonElement = document.createElement('button');
+ this.#closeButtonElement.setAttribute('part', 'closebutton');
+ setDefaultCloseButton(this.#closeButtonElement);
+ this.#shadow.appendChild(this.#closeButtonElement);
+
+ this.#closeButtonElement.addEventListener('click', () => {
+ this.hide();
+ });
+
+ if (message !== undefined) {
+ this.textContent = message;
+ }
+ }
+
+ connectedCallback() {
+ if (!this.hasAttribute('role')) {
+ this.setAttribute('role', 'status');
+ }
+ // TODO(jacksteinberg): use https://github.com/whatwg/html/pull/4658 when implemented
+ }
+
+ get action() {
+ return this.#actionSlot.assignedNodes().length !== 0 ?
+ this.#actionSlot.assignedNodes()[0] :
+ null;
+ }
+
+ set action(val) {
+ const previousAction = this.action;
+ if (val !== null) {
+ if (!isElement(val)) {
+ throw new TypeError('Invalid argument: must be type Element');
+ }
+
+ val.setAttribute('slot', 'action');
+ this.insertBefore(val, previousAction);
+ }
+
+ if (previousAction !== null) {
+ previousAction.remove();
+ }
+ }
+
+ get closeButton() {
+ if (this.hasAttribute('closebutton')) {
+ const closeAttr = this.getAttribute('closebutton');
+ return closeAttr === '' ? true : closeAttr;
+ }
+ return false;
+ }
+
+ set closeButton(val) {
+ if (val === true) {
+ this.setAttribute('closebutton', '');
+ } else if (val === false) {
+ this.removeAttribute('closebutton');
+ } else {
+ this.setAttribute('closebutton', val);
+ }
+ }
+
+ get type() {
+ const typeAttr = this.getAttribute('type');
+ if (typeAttr === null) {
+ return '';
+ }
+
+ const typeAttrLower = typeAttr.toLowerCase();
+
+ if (TYPES.has(typeAttrLower)) {
+ return typeAttrLower;
+ }
+
+ return '';
+ }
+
+ set type(val) {
+ this.setAttribute('type', val);
+ }
+
+ show({duration = DEFAULT_DURATION} = {}) {
+ if (duration <= 0) {
+ throw new RangeError(`Invalid Argument: duration must be greater than 0 [${duration} given]`);
+ }
+
+ this.setAttribute('open', '');
+ this.#setCloseTimeout(duration);
+ }
+
+ hide() {
+ this.removeAttribute('open');
+ }
+
+ toggle(force) {
+ this.toggleAttribute('open', force);
+ }
+
+ attributeChangedCallback(name, oldValue, newValue) {
+ switch (name) {
+ case 'open':
+ if (newValue !== null && oldValue === null) {
+ this.dispatchEvent(new Event('show'));
+ } else if (newValue === null) {
+ this.dispatchEvent(new Event('hide'));
+ this.#setCloseTimeout(Infinity);
+ }
+ break;
+ case 'closebutton':
+ if (newValue !== null) {
+ if (newValue === '') {
+ setDefaultCloseButton(this.#closeButtonElement);
+ } else {
+ replaceDefaultCloseButton(this.#closeButtonElement, newValue);
+ }
+ }
+ // if newValue === null we do nothing, since CSS will hide the button
+ break;
+ }
+ }
+}
+
+reflection.installBool(StdToastElement.prototype, 'open');
+
+customElements.define('std-toast', StdToastElement);
+
+delete StdToastElement.prototype.attributeChangedCallback;
+delete StdToastElement.prototype.observedAttributes;
+delete StdToastElement.prototype.connectedCallback;
+
+export function showToast(message, options = {}) {
+ const toast = new StdToastElement(message);
+
+ const {
+ action,
+ closeButton,
+ type,
+ ...showOptions
+ } = options;
+
+ if (isElement(action)) {
+ toast.action = action;
+ } else if (action !== undefined) {
+ const actionButton = document.createElement('button');
+
+ // Unlike String(), this performs the desired JavaScript ToString operation.
+ // https://gist.github.com/domenic/82adbe7edc4a33a70f42f255479cec39
+ actionButton.textContent = `${action}`;
+
+ actionButton.setAttribute('slot', 'action');
+ toast.appendChild(actionButton);
+ }
+
+ if (closeButton !== undefined) {
+ toast.closeButton = closeButton;
+ }
+
+ if (type !== undefined) {
+ toast.type = type;
+ }
+
+ document.body.append(toast);
+ toast.show(showOptions);
+
+ return toast;
+}
+
+const idGetter =
+ Object.getOwnPropertyDescriptor(Element.prototype, 'id').get;
+function isElement(value) {
+ try {
+ idGetter.call(value);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+function setDefaultCloseButton(closeButton) {
+ closeButton.setAttribute('aria-label', 'close');
+ closeButton.setAttribute('class', 'default-closebutton');
+ closeButton.textContent = '×';
+}
+
+function replaceDefaultCloseButton(closeButton, value) {
+ closeButton.textContent = value;
+ closeButton.removeAttribute('aria-label');
+ closeButton.removeAttribute('class');
+}
diff --git a/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/.eslintrc.js b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/.eslintrc.js
new file mode 100644
index 00000000000..90e626a41fc
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/.eslintrc.js
@@ -0,0 +1,337 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+module.exports = {
+ root: true,
+ env: {
+ es6: true,
+ browser: true
+ },
+ 'parser': 'babel-eslint',
+ parserOptions: {
+ sourceType: 'module',
+ ecmaVersion: 2019
+ },
+ rules: {
+ 'for-direction': 'error',
+ 'getter-return': 'error',
+ 'no-async-promise-executor': 'error',
+ 'no-await-in-loop': 'error',
+ 'no-compare-neg-zero': 'error',
+ 'no-cond-assign': ['error', 'except-parens'],
+ 'no-console': 'error',
+ 'no-constant-condition': ['error', {checkLoops: false}],
+ 'no-control-regex': 'error',
+ 'no-debugger': 'error',
+ 'no-dupe-args': 'error',
+ 'no-dupe-keys': 'error',
+ 'no-duplicate-case': 'error',
+ 'no-empty': 'error',
+ 'no-empty-character-class': 'error',
+ 'no-ex-assign': 'error',
+ 'no-extra-boolean-cast': 'error',
+ 'no-extra-parens': [
+ 'error',
+ 'all',
+ {
+ conditionalAssign: false,
+ nestedBinaryExpressions: false,
+ returnAssign: false
+ }
+ ],
+ 'no-extra-semi': 'error',
+ 'no-func-assign': 'error',
+ 'no-inner-declarations': 'off',
+ 'no-invalid-regexp': 'error',
+ 'no-irregular-whitespace': 'error',
+ 'no-misleading-character-class': 'error',
+ 'no-obj-calls': 'error',
+ 'no-prototype-builtins': 'error',
+ 'no-regex-spaces': 'error',
+ 'no-sparse-arrays': 'error',
+ 'no-template-curly-in-string': 'error',
+ 'no-unexpected-multiline': 'error',
+ 'no-unreachable': 'error',
+ 'no-unsafe-finally': 'off',
+ 'no-unsafe-negation': 'error',
+ 'use-isnan': 'error',
+ 'valid-typeof': 'error',
+ 'accessor-pairs': 'error',
+ 'array-callback-return': 'error',
+ 'block-scoped-var': 'off',
+ 'class-methods-use-this': 'off',
+ 'complexity': 'off',
+ 'consistent-return': 'error',
+ 'curly': ['error', 'all'],
+ 'default-case': 'off',
+ 'dot-location': ['error', 'property'],
+ 'dot-notation': 'error',
+ 'eqeqeq': 'error',
+ 'guard-for-in': 'off',
+ 'no-alert': 'error',
+ 'no-caller': 'error',
+ 'no-case-declarations': 'error',
+ 'no-div-regex': 'off',
+ 'no-empty-function': 'off',
+ 'no-empty-pattern': 'error',
+ 'no-eq-null': 'error',
+ 'no-eval': 'error',
+ 'no-extend-native': 'error',
+ 'no-extra-bind': 'error',
+ 'no-extra-label': 'error',
+ 'no-fallthrough': 'error',
+ 'no-floating-decimal': 'error',
+ 'no-global-assign': 'error',
+ 'no-implicit-coercion': 'error',
+ 'no-implicit-globals': 'error',
+ 'no-implied-eval': 'error',
+ 'no-iterator': 'error',
+ 'no-labels': ['error', {allowLoop: true}],
+ 'no-lone-blocks': 'error',
+ 'no-loop-func': 'error',
+ 'no-magic-numbers': ['error', {ignore: [0, 1, 2]}],
+ 'no-multi-spaces': ['error', {ignoreEOLComments: true}],
+ 'no-multi-str': 'error',
+ 'no-new': 'error',
+ 'no-new-func': 'error',
+ 'no-new-wrappers': 'error',
+ 'no-octal': 'error',
+ 'no-octal-escape': 'error',
+ 'no-param-reassign': 'off',
+ 'no-process-env': 'error',
+ 'no-proto': 'error',
+ 'no-redeclare': 'error',
+ 'no-restricted-properties': 'off',
+ 'no-return-assign': ['error', 'except-parens'],
+ 'no-return-await': 'error',
+ 'no-script-url': 'off',
+ 'no-self-assign': 'error',
+ 'no-self-compare': 'error',
+ 'no-sequences': 'error',
+ 'no-throw-literal': 'error',
+ 'no-unmodified-loop-condition': 'error',
+ 'no-unused-expressions': 'error',
+ 'no-unused-labels': 'error',
+ 'no-useless-call': 'error',
+ 'no-useless-concat': 'error',
+ 'no-useless-escape': 'error',
+ 'no-useless-return': 'error',
+ 'no-void': 'error',
+ 'no-warning-comments': 'off',
+ 'no-with': 'error',
+ 'prefer-promise-reject-errors': 'error',
+ 'radix': ['error', 'as-needed'],
+ 'require-await': 'off',
+ 'vars-on-top': 'off',
+ 'wrap-iife': ['error', 'outside'],
+ 'yoda': ['error', 'never'],
+ 'strict': ['error', 'global'],
+ 'init-declarations': 'off',
+ 'no-delete-var': 'error',
+ 'no-label-var': 'error',
+ 'no-restricted-globals': 'off',
+ 'no-shadow': 'error',
+ 'no-shadow-restricted-names': 'error',
+ 'no-undef': 'error',
+ 'no-undef-init': 'error',
+ 'no-undefined': 'off',
+ 'no-unused-vars': 'error',
+ 'no-use-before-define': ['error', 'nofunc'],
+ 'callback-return': 'off',
+ 'global-require': 'error',
+ 'handle-callback-err': 'error',
+ 'no-buffer-constructor': 'error',
+ 'no-mixed-requires': ['error', true],
+ 'no-new-require': 'error',
+ 'no-path-concat': 'error',
+ 'no-process-exit': 'error',
+ 'no-restricted-modules': 'off',
+ 'no-sync': 'off',
+ 'array-bracket-newline': ['error', {multiline: true}],
+ 'array-bracket-spacing': ['error', 'never'],
+ 'array-element-newline': 'off',
+ 'block-spacing': ['error', 'always'],
+ 'brace-style': [
+ 'error',
+ '1tbs',
+ {allowSingleLine: false}
+ ],
+ camelcase: ['error', {properties: 'always'}],
+ 'capitalized-comments': 'off',
+ 'comma-dangle': ['error', 'always-multiline'],
+ 'comma-spacing': [
+ 'error',
+ {
+ before: false,
+ after: true
+ }
+ ],
+ 'comma-style': ['error', 'last'],
+ 'computed-property-spacing': ['error', 'never'],
+ 'consistent-this': 'off',
+ 'eol-last': 'error',
+ 'func-call-spacing': ['error', 'never'],
+ 'func-name-matching': 'error',
+ 'func-names': 'off',
+ 'func-style': ['error', 'declaration'],
+ 'function-paren-newline': 'off',
+ 'id-blacklist': 'off',
+ 'id-length': 'off',
+ 'id-match': 'off',
+ indent: 'off', // not really compatible with clang-format
+ 'jsx-quotes': 'off',
+ 'key-spacing': [
+ 'error',
+ {
+ beforeColon: false,
+ afterColon: true,
+ mode: 'strict'
+ }
+ ],
+ 'keyword-spacing': [
+ 'error',
+ {
+ before: true,
+ after: true
+ }
+ ],
+ 'line-comment-position': 'off',
+ 'linebreak-style': ['error', 'unix'],
+ 'lines-around-comment': 'off',
+ 'max-depth': 'off',
+ 'max-len': ['error', {
+ tabWidth: 2,
+ ignorePattern: "(^import |// eslint-disable-line )"}],
+ 'max-lines': 'off',
+ 'max-nested-callbacks': 'off',
+ 'max-params': 'off',
+ 'max-statements': 'off',
+ 'max-statements-per-line': ['error', {max: 1}],
+ 'multiline-ternary': ['error', 'always-multiline'],
+ 'new-cap': 'error',
+ 'new-parens': 'error',
+ 'newline-per-chained-call': 'off',
+ 'no-array-constructor': 'error',
+ 'no-bitwise': 'off',
+ 'no-continue': 'off',
+ 'no-inline-comments': 'off',
+ 'no-mixed-operators': [
+ 'error',
+ {
+ groups: [
+ ['&', '|', '^', '~', '<<', '>>', '>>>'],
+ ['==', '!=', '===', '!==', '>', '>=', '<', '<='],
+ ['&&', '||'],
+ ['in', 'instanceof']
+ ]
+ }
+ ],
+ 'no-mixed-spaces-and-tabs': 'error',
+ 'no-multi-assign': 'off',
+ 'no-multiple-empty-lines': 'error',
+ 'no-negated-condition': 'off',
+ 'no-nested-ternary': 'error',
+ 'no-new-object': 'error',
+ 'no-plusplus': 'off',
+ 'no-restricted-syntax': 'off',
+ 'no-tabs': 'error',
+ 'no-ternary': 'off',
+ 'no-trailing-spaces': 'error',
+ 'no-underscore-dangle': 'off',
+ 'no-unneeded-ternary': 'error',
+ 'no-whitespace-before-property': 'error',
+ 'nonblock-statement-body-position': 'error',
+ 'object-curly-newline': ['error', {consistent: true}],
+ 'object-curly-spacing': ['error', 'never'],
+ 'object-property-newline': 'off',
+ 'one-var': ['error', 'never'],
+ 'one-var-declaration-per-line': ['error', 'initializations'],
+ 'operator-assignment': ['error', 'always'],
+ 'operator-linebreak': ['error', 'after'],
+ 'padded-blocks': ['error', 'never'],
+ 'padding-line-between-statements': 'off',
+ 'quote-props': ['error', 'as-needed'],
+ quotes: [
+ 'error',
+ 'single',
+ {
+ avoidEscape: true,
+ allowTemplateLiterals: true
+ }
+ ],
+ semi: ['error', 'always'],
+ 'semi-spacing': 'error',
+ 'semi-style': 'error',
+ 'sort-keys': 'off',
+ 'sort-vars': 'off',
+ 'space-before-blocks': ['error', 'always'],
+ 'space-before-function-paren': [
+ 'error',
+ {
+ anonymous: 'always',
+ named: 'never'
+ }
+ ],
+ 'space-in-parens': ['error', 'never'],
+ 'space-infix-ops': 'error',
+ 'space-unary-ops': [
+ 'error',
+ {
+ words: true,
+ nonwords: false
+ }
+ ],
+ 'spaced-comment': ['error', 'always'],
+ 'switch-colon-spacing': 'error',
+ 'template-tag-spacing': 'error',
+ 'unicode-bom': 'error',
+ 'wrap-regex': 'off',
+ 'arrow-body-style': 'off',
+ 'arrow-parens': ['error', 'as-needed'],
+ 'arrow-spacing': 'error',
+ 'constructor-super': 'error',
+ 'generator-star-spacing': ['error', 'neither'],
+ 'no-class-assign': 'error',
+ 'no-confusing-arrow': 'off',
+ 'no-const-assign': 'error',
+ 'no-dupe-class-members': 'error',
+ 'no-duplicate-imports': 'error',
+ 'no-new-symbol': 'error',
+ 'no-restricted-imports': 'off',
+ 'no-this-before-super': 'error',
+ 'no-useless-computed-key': 'error',
+ 'no-useless-constructor': 'error',
+ 'no-useless-rename': 'error',
+ 'no-var': 'error',
+ 'object-shorthand': 'error',
+ 'prefer-arrow-callback': 'error',
+ 'prefer-const': ['error', {ignoreReadBeforeAssign: true}],
+ 'prefer-destructuring': [
+ 'error',
+ {
+ VariableDeclarator: {
+ array: false,
+ object: true
+ },
+ AssignmentExpression: {
+ array: false,
+ object: false
+ }
+ },
+ {
+ enforceForRenamedProperties: false
+ }
+ ],
+ 'prefer-numeric-literals': 'error',
+ 'prefer-rest-params': 'error',
+ 'prefer-spread': 'error',
+ 'prefer-template': 'off',
+ 'require-yield': 'error',
+ 'rest-spread-spacing': 'error',
+ 'sort-imports': 'off',
+ 'symbol-description': 'error',
+ 'template-curly-spacing': ['error', 'never'],
+ 'yield-star-spacing': ['error', 'after']
+ }
+};
diff --git a/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/OWNERS b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/OWNERS
new file mode 100644
index 00000000000..d76cdfa11f0
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/OWNERS
@@ -0,0 +1 @@
+fergal@chromium.org
diff --git a/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/docs/README.md b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/docs/README.md
new file mode 100644
index 00000000000..c5ea6fc86c3
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/docs/README.md
@@ -0,0 +1,297 @@
+# Virtual Scroller Notes
+
+This is Blink's implementation of the [`<virtual-scroller>`](https://github.com/WICG/virtual-scroller) element.
+
+## Status
+
+This is a prototype with many known issues.
+
+## Principles
+
+- Avoid operations that are O(number of children)
+- Ensure that we only perform operations that cause DOM, style or rendering work in the browser
+ that is O(number of visible elements).
+- Avoid forcing layout from JS.
+
+## Current Implementation Strategy
+
+The prototype uses a custom element implemented in JS.
+It only handles vertical block layout,
+so this talks only about height.
+This custom element manages the display-locking status of its child items.
+It considers a range of pixels to be the "unlocked range".
+This range is determined from the window size.
+
+TODO(crbug.com/983052): Be smarter about determining the buffer size,
+given that the window can be resized.
+
+Items which are within the unlocked range are left unlocked.
+All other items are locked
+so that they do not incur style and rendering costs for their contents.
+They are locked with a height that is our best guess at their rendered height.
+This guess is based on
+- a fixed default
+- a previously measured height of this item
+- an average of previous observed heights of items
+
+The virtual scroller listens to observers to know when it needs to reconsider which items should be locked.
+It keeps a resize observer on itself since if it is resized,
+items may need to be newly locked or unlocked.
+It keeps an intersection observer on all unlocked child items.
+Along with the buffer around the screen,
+this allows it to know when the state has changed such that we may need to lock or unlock different items.
+
+TODO(crbug.com/983050): Observe one item above and below the unlocked items too,
+without this, if the edge item is larger than the window,
+we can scroll empty space into the visible region.
+
+TODO(crbug.com/983046): Keep an intersection observer on the scroller.
+This allows us to know whether the scroller is offscreen.
+In that case we lock all elements
+and pause all activity.
+This includes if the scroller is contained in a locked element
+(e.g. nested in another virtual scroller).
+
+The virtual scroller keeps a mutation observer on itself
+so that it can react to elements being added, removed or moved around.
+When dealing with mutations,
+elements which are newly added are treated differently
+to elements which are removed and re-added.
+Newly added elements are immediately locked.
+This allows a large number of elements to be added,
+without a large rendering/style cost for these elements.
+
+The virtual scroller does not listen directly for scroll events
+and does not know or care whether it is in a scrollable region.
+It is tempting to try discover whether the scroller is contained in a scrolling region
+and then listen for scroll events,
+however the scroller may be contained in any number of nested scrollable regions
+and DOM changes can cause it to be reparented.
+Also, we only need to change state when an item enters or leaves the visible range
+but scroll events may occur much more frequently than that.
+
+The virtual scroller takes no action directly in response to these events.
+It simply ensures that a `requestAnimationFrame` (RAF) callback will run this frame
+(max one per frame).
+This callback is the "sync" callback.
+It will attempt to react to the new state of the world
+and try to ensure that the scroller is in sync with it.
+This is where we determine which elements to lock or unlock.
+
+When determining which items should be locked and which should be unlocked,
+the virtual scroller uses `getBoundingClientRect`
+to get the coordinates of its items,
+relative to the root viewport.
+It binary searches on the array of items
+to find the element at the top and bottom of the visible range.
+At the end of the sync,
+these and the elements in between them will be unlocked
+and all other elements will be locked.
+The scroller knows which elements are currently unlocked
+and does the minimal amount of locking and unlocking
+to bring it to the desired state.
+Also the intersection observers will be updated to match this range of elements.
+
+It is very possible that the range of elements we have unlocked
+is too big or too small for the viewport.
+We cannot know the rendered size of these elements
+until we have unlocked and measured them.
+In order to avoid extra forced layouts,
+we simply queue another sync callback for the next frame.
+We continue to queue sync callbacks until one of them makes no changes.
+
+Internally, the virtual scroller slots all children into a single slot.
+It changes the locked state of the light tree children directly.
+
+## Known issues specific to the current prototype
+
+### Display locking items directly
+
+The current prototype changes the locked state of the light tree children directly.
+This means that the scroller's actions can be detected from outside.
+It also means that an author cannot (in general) safely use display locking
+on the children of a virtual scroller.
+
+Other approaches do not have this issue,
+because they slot the items into more than one slot,
+however, this requires either manipulating the `slot` attribute on the items
+or [imperative slotting](https://www.chromestatus.com/feature/5711021289242624).
+
+### Binary searching the items
+
+The first problem with this is that it requires forced layout (see below).
+
+The second (potential) problem is that
+while JS presents an `Array` interface for the children of the virtual scroller,
+the reality is that in Blink,
+the elements are stored in a linked list
+with some extra logic to remember the most recent indexed access
+and use that to speed up subsequent index accesses
+(e.g. accessing `[n+1]` after `[n]` is fast).
+This makes the binary search actually O(number of children)
+because the C++ code must traverse a linked list.
+However C++ traversing a link list is very fast
+so this tends not to be noticeable.
+
+### Locked elements still have a cost
+
+While the descendants of locked elements are skipped for style and layout,
+the locked elements themselves are still traversed
+and participate in style and layout.
+In the scroller,
+the elements are locked with a size
+and behave just as an empty div with that size.
+This means that when we add many children to the virtual scroller,
+even though most of them are locked,
+there can still be quite a large style and rendering cost
+from the locked elements in aggregate.
+
+## Known issues common to many approaches
+
+### Intersection observers are slow
+
+Intersection observers signal the intersection state *after* it has happened.
+This means that by only reacting to intersection observers,
+the scroller may react late to scrolls and jumps.
+Once a scroll begins,
+it's likely that the element will keep up,
+since it is not using the details of the events to compute the state of the scroller.
+
+### Forced layouts to measure item sizes
+
+After unlocking, the scroller needs to know the rendered size of an element.
+In order to do that it must call `getBoundingClientRect`.
+This forces the browser to have clean style and layout
+for all unlocked elements in the document
+(whether this is expensive depends on what has changed since the last time layout).
+It may be better to perform these measurements in a
+[post animation frame callback](https://github.com/WICG/requestPostAnimationFrame/blob/master/explainer.md)
+when that feature becomes available
+because this callback guarantees that style and layout are clean,
+so measuring elements should be inexpensive.
+
+## Alternative approaches
+
+### Unlocked tree of divs with `<slot>`s for leaves (rejected)
+
+We could avoid the O(number of children) run of locked divs
+by building a tree of divs (e.g. a binary tree)
+and locking all of the slots except those containing the visible items.
+
+*PROBLEM:* This breaks margin collapsing between items
+and maybe other layout or style features.
+In order to make margin collapsing work correctly
+we would need to make all of the divs in this tree have style `display: contents`
+but for layout, this would have exactly the same performance problem as placing them all as siblings in one slot.
+
+### One visible slot in the middle (rejected)
+
+We could assign all of the visible items to a single slot,
+ensuring they behave correctly with respect to margin collapsing
+and keep all other items in other slots.
+
+We need to ensure that elements are slotted in their light-tree order
+for find-in-page, accessibility etc to work correctly.
+The simplest form of this is a three-slot approach
+with one slot for the invisible items at the top,
+another slot for the visible items in the middle
+and a third slot for the invisible items at the bottom.
+The top and bottom slot remain locked always
+and items are moved into the visible slot when they should be visible.
+The top and bottom slots are inside a locked div.
+These divs are locked with a size estimated to be the correct aggregate size for their slotted elements.
+
+*PROBLEM:* Gradually scrolling down moves items one at a time
+from the bottom slot, to the visible slot and then into the top slot
+but long-range jumps require moving O(number of children) items between slots.
+E.g. if the top items are visible and we jump to make the bottom items visible,
+then we have to assign almost all of the items that were in the bottom slot to the top slot.
+
+### Roaming visible slot (not preferred)
+
+This is similar to [One visible slot in the middle](#One-visible-slot-in-the-middle) approach
+but rather than a top and bottom slot,
+item assignment is divided over many slots.
+Each item has a natural "leaf" slot that it should be assigned to.
+All of the leaf slots are kept locked.
+There is a single visible slot that contains the currently unlocked items
+and it roams around between the leaf slots
+to ensure that order is correct for find-in-page etc.
+If we keep the number of items per slot low,
+then long jumps never cause a large number of items to be reassigned,
+at worst we need to reassign the currently visible items back to their leaf slots,
+move the visible slot to a new place
+and fill it with newly visible items.
+
+It's possible that there will be so many slots
+that once again we run into the problem of large numbers of empty divs.
+So we may need to maintain a tree of divs and `<slot>`s.
+Most of this tree would be locked
+but the path from the visible slot to the root would be unlocked.
+
+It looks like this:
+
+![Diagram of a sample roaming visible slot tree](roaming-slot.png)
+
+Original diagram [here](https://docs.google.com/drawings/d/1oZ8U16GzkxO3GaYLDygPsrmXiHO7SLNFXvVUK6WkG4I/edit)
+
+*CHALLENGES:* This approach does not seem to have any insurmountable problems,
+however it is not simple:
+- We need to ensure that the tree remains balanced in the face of mutations of the virtual scrollers contents.
+- A tree may introduce a large number of tree-only elements.
+ With a binary tree, this would be equal to the number of items in the scroller.
+ It might be worth using a larger branching factor, to reduce this cost.
+ E.g. in a 10-way tree the overhead is only 1/9 the number of leaves.
+- There is a lot of re-slotting of items.
+- The visible slot may contain a large number of elements (if elements are small)
+ and Blink has some [optimizations](https://cs.chromium.org/chromium/src/third_party/blink/renderer/core/html/html_slot_element.cc?q=symbol:HTMLSlotElement::NotifySlottedNodesOfFlatTreeChange)
+ that only work when slots contain <= 16 elements.
+- Adding slots and/or assigning elements to slots currently involves operations that are O(number of children).
+ Adding N slots can take O(N^2) time.
+ This was previously not a concern in Blink
+ because, in general, the style and layout costs dominated.
+ However display locking eliminates these costs,
+ leaving the slotting costs as the bottleneck when there are large numbers of items.
+
+### One slot per item (most promising alternative)
+
+This is similar to [Roaming visible slot](#Roaming-visible-slot).
+We have a tree of divs with slots as leaves
+but in this approach we have exactly one slot per item.
+For any item that should be unlocked,
+we ensure that all of its tree ancestors are unlocked
+and have style `display: contents`.
+All other nodes in the tree have style `display: block; contain: style layout`,
+to allow them to be locked.
+
+This has the effect of making all of the visible items siblings,
+from the perspective of layout,
+so that margin collapsing, etc. works correctly.
+It also ensures that not only are the invisible items and tree divs locked
+but they are *inside* locked ancestors,
+so do not incur *any* costs.
+
+There is no need to maintain spacer divs above and below the visible region.
+Instead, when we lock any tree element,
+we set its locked size to be its current visible size.
+If its contents don't change then this element has the correct aggregate size for its contents.
+If this element's parent is unlocked then this correct size will be used in sizing the parent.
+
+Mutations to the tree require size updates to propagate up the ancestor chain.
+E.g. inserting an element causes all of the elements ancestors to grow by our best guess at its size.
+So, the initial state of the tree
+(which comes from an initial insert)
+is that everything is an estimate or sum of estimates,
+with the sizes getting more accurate
+as more elements are rendered, measured and re-locked with correct sizes.
+
+It's likely that the sizes above will be off by some amount due to margins
+but they should be good enough for maintaining a usable scrollbar.
+
+*CHALLENGES:* This approach does not seem to have any insurmountable problems,
+however it is not so simple.
+It has a subset of the challenges of [Roaming visible slot](#Roaming-visible-slot):
+
+- Needs a balanced tree.
+- Possible large number of tree-only elements.
+- Slot performance issues.
diff --git a/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/docs/roaming-slot.png b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/docs/roaming-slot.png
new file mode 100644
index 00000000000..2f9b6844694
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/docs/roaming-slot.png
Binary files differ
diff --git a/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/find-element.mjs b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/find-element.mjs
new file mode 100644
index 00000000000..c25edc0a7fd
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/find-element.mjs
@@ -0,0 +1,104 @@
+/**
+ * Copyright 2019 The Chromium Authors. All rights reserved.
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ *
+ * @fileoverview Utilities for binary searching by layed-out pixed offset in a
+ * list of elements.
+ * @package
+ */
+
+/** Symbols for use with @see findElement */
+export const BIAS_LOW = Symbol('BIAS_LOW');
+export const BIAS_HIGH = Symbol('BIAS_HIGH');
+
+function getBound(elements, edgeIndex) {
+ const element = elements[Math.floor(edgeIndex / 2)];
+ const rect = element.getBoundingClientRect();
+ return edgeIndex % 2 ? rect.bottom : rect.top;
+}
+
+/**
+ * Does the actual work of binary searching. This searches amongst the 2*N edges
+ * of the N elements. Returns the index of an edge found, 2i is the low edge of
+ * the ith element, 2i+1 is the high edge of the ith element. If |bias| is low
+ * then we find the index of the lowest edge >= offset. Otherwise we find index
+ * of the highest edge > offset.
+ */
+function findEdgeIndex(elements, offset, bias) {
+ let low = 0;
+ let high = elements.length * 2 - 1;
+ while (low < high) {
+ const i = Math.floor((low + high) / 2);
+ const bound = getBound(elements, i);
+ if (bias === BIAS_LOW) {
+ if (bound < offset) {
+ low = i + 1;
+ } else {
+ high = i;
+ }
+ } else {
+ if (offset < bound) {
+ high = i;
+ } else {
+ low = i + 1;
+ }
+ }
+ }
+ return low;
+}
+
+/**
+ * Binary searches inside the array |elements| to find an element containing or
+ * nearest to |offset| (based on @see Element#getBoundingClientRect()). Assumes
+ * that the elements are already sorted in increasing pixel order. |bias|
+ * controls what happens if |offset| is not contained within any element or if
+ * |offset| is contained with 2 elements (this only happens if there is no
+ * margin between the elements). If |bias| is BIAS_LOW, then this selects the
+ * lower element nearest |offset|, otherwise it selects the higher element.
+ *
+ * Returns null if |offset| is not within any element.
+ *
+ * @param {!Element[]} elements An array of Elements in display order,
+ * i.e. the pixel offsets of later element are higher than those of earlier
+ * elements.
+ * @param {!number} offset The target offset in pixels to search for.
+ * @param {!Symbol} bias Controls whether we prefer a higher or lower element
+ * when there is a choice between two elements.
+ */
+export function findElement(elements, offset, bias) {
+ if (elements.length === 0) {
+ return null;
+ }
+ // Check if the offset is outside the range entirely.
+ if (offset < getBound(elements, 0) ||
+ offset > getBound(elements, elements.length * 2 - 1)) {
+ return null;
+ }
+
+ let edgeIndex = findEdgeIndex(elements, offset, bias);
+
+ // Fix up edge cases.
+ if (bias === BIAS_LOW) {
+ // bound(0)..bound(edgeIndex) < offset <= bound(edgeIndex+1) ...
+ // If we bias low and we got a low edge and we weren't exactly on the edge
+ // then we want to select the element that's lower.
+ if (edgeIndex % 2 === 0) {
+ const bound = getBound(elements, edgeIndex);
+ if (offset < bound) {
+ edgeIndex--;
+ }
+ }
+ } else {
+ // bound(0)..bound(edgeIndex - 1) <= offset < bound(edgeIndex) ...
+ // If we bias high and we got a low edge, we need to check if we were
+ // exactly on the edge of the previous element.
+ if (edgeIndex % 2 === 0) {
+ const bound = getBound(elements, edgeIndex - 1);
+ if (offset === bound) {
+ edgeIndex--;
+ }
+ }
+ }
+ return elements[Math.floor(edgeIndex / 2)];
+}
diff --git a/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/index.mjs b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/index.mjs
new file mode 100644
index 00000000000..daef60f7232
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/index.mjs
@@ -0,0 +1,57 @@
+/**
+ * Copyright 2019 The Chromium Authors. All rights reserved.
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ *
+ * @fileoverview This file defines virtual-scroller element.
+ * EXPLAINER: https://github.com/fergald/virtual-scroller/blob/master/README.md
+ * TEST PATH: third_party/blink/web_tests/http/tests/virtual-scroller/*
+ * third_party/blink/web_tests/wpt_internal/virtual-scroller/*
+ * @package
+ */
+import {VisibilityManager} from './visibility-manager.mjs';
+
+function styleSheetFactory() {
+ let styleSheet;
+ return () => {
+ if (!styleSheet) {
+ styleSheet = new CSSStyleSheet();
+ styleSheet.replaceSync(`
+:host {
+ display: block;
+}
+
+::slotted(*) {
+ display: block !important;
+ contain: layout style;
+}
+`);
+ }
+ return styleSheet;
+ };
+}
+
+/**
+ * The class backing the virtual-scroller custom element.
+ */
+export class VirtualScrollerElement extends HTMLElement {
+ constructor() {
+ super();
+
+ const shadowRoot = this.attachShadow({mode: 'closed'});
+ shadowRoot.adoptedStyleSheets = [styleSheetFactory()()];
+ shadowRoot.appendChild(document.createElement('slot'));
+
+ const visibilityManager = new VisibilityManager(this.children);
+
+ new ResizeObserver(() => {
+ visibilityManager.scheduleSync();
+ }).observe(this);
+
+ new MutationObserver(records => {
+ visibilityManager.applyMutationObserverRecords(records);
+ }).observe(this, {childList: true});
+ }
+}
+
+customElements.define('virtual-scroller', VirtualScrollerElement);
diff --git a/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/sets.mjs b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/sets.mjs
new file mode 100644
index 00000000000..9b1aff8eca1
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/sets.mjs
@@ -0,0 +1,24 @@
+/**
+ * Copyright 2019 The Chromium Authors. All rights reserved.
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ *
+ * @fileoverview Utility functions for set operations.
+ * @package
+ */
+
+/*
+ * Returns the set of elements in |a| that are not in |b|.
+ *
+ * @param {!Set} a A set of elements.
+ * @param {!Set} b A set of elements.
+*/
+export function difference(a, b) {
+ const result = new Set();
+ for (const element of a) {
+ if (!b.has(element)) {
+ result.add(element);
+ }
+ }
+ return result;
+}
diff --git a/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/visibility-manager.mjs b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/visibility-manager.mjs
new file mode 100644
index 00000000000..ecc160f9f0d
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/script/resources/layered_api/elements/virtual-scroller/visibility-manager.mjs
@@ -0,0 +1,407 @@
+/**
+ * Copyright 2019 The Chromium Authors. All rights reserved.
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ *
+ * @fileoverview This file provides the class backing the virtual-scroller
+ * element.
+ * @package
+ */
+import * as sets from './sets.mjs';
+import * as findElement from './find-element.mjs';
+
+
+// This controls how much above and below the current screen we
+// reveal, e.g. 1 = 1 screen of content.
+const BUFFER = 0.2;
+// When we know about the heights of elements we default this height.
+const DEFAULT_HEIGHT_ESTIMATE_PX = 100;
+// When we lock an element, we use this as the width. We use 1px because locked
+// items will not resize when their container changes and so could result in a
+// horizontal scroll-bar appearing if it they are wide enough.
+const LOCKED_WIDTH_PX = 1;
+
+/**
+ * Represents a range of elements from |low| to |high|, inclusive.
+ * If either |low| or |high| are null then we treat this as an empty range.
+ */
+class ElementBounds {
+ /** @const {Element} */
+ low;
+ /** @const {Element} */
+ high;
+
+ constructor(low, high) {
+ this.low = low;
+ this.high = high;
+ }
+
+ // Returns a Set containing all of the elements from low to high.
+ elementSet() {
+ const result = new Set();
+ if (this.low === null || this.high === null) {
+ return result;
+ }
+ let element = this.low;
+ while (element) {
+ result.add(element);
+ if (element === this.high) {
+ break;
+ }
+ element = element.nextElementSibling;
+ }
+ return result;
+ }
+}
+
+const EMPTY_ELEMENT_BOUNDS = new ElementBounds(null, null);
+
+/**
+ * Manages measuring and estimating sizes of elements.
+ *
+ * This tracks an average measured element size as elements are added
+ * and removed.
+*/
+class SizeManager {
+ #sizes = new WeakMap();
+
+ #totalMeasuredSize = 0;
+ #measuredCount = 0;
+
+ /**
+ * Measures and stores |element|'s size. If |element| was measured
+ * previously, this updates everything to use the new current size.
+ *
+ * @param {!Element} element The element to measure.
+ */
+ measure(element) {
+ let oldSize = this.#sizes.get(element);
+ if (oldSize === undefined) {
+ oldSize = 0;
+ this.#measuredCount++;
+ }
+ const newSize = element.getBoundingClientRect().height;
+ this.#totalMeasuredSize += newSize - oldSize;
+ this.#sizes.set(element, newSize);
+ }
+
+ /**
+ * Returns a size for |element|, either the last stored size or an
+ * estimate based on all other previously measured elements or a
+ * default.
+ *
+ * @param {!Element} element The element to produce a size for.
+ */
+ getHopefulSize(element) {
+ const size = this.#sizes.get(element);
+ return size === undefined ? this.#getAverageSize() : size;
+ }
+
+ #getAverageSize = () => {
+ return this.#measuredCount > 0 ?
+ this.#totalMeasuredSize / this.#measuredCount :
+ DEFAULT_HEIGHT_ESTIMATE_PX;
+ }
+
+ /**
+ * Removes all data related to |element| from the manager.
+ *
+ * @param {!Element} element The element to remove.
+ */
+ remove(element) {
+ const oldSize = this.#sizes.get(element);
+ if (oldSize === undefined) {
+ return;
+ }
+ this.#totalMeasuredSize -= oldSize;
+ this.#measuredCount--;
+ this.#sizes.delete(element);
+ }
+}
+
+/**
+ * Manages the visibility (locked/unlocked state) of a list of
+ * elements. This list of elements is assumed to be in vertical
+ * display order (e.g. from lowest to highest offset).
+ *
+ * It uses resize and intersection observers on all of the visible
+ * elements to ensure that changes that impact visibility cause us to
+ * recalulate things (e.g. scrolling, restyling).
+*/
+export class VisibilityManager {
+ #sizeManager = new SizeManager();
+ #elements;
+ #syncRAFToken;
+
+ #elementIntersectionObserver;
+ #elementResizeObserver;
+
+ #revealed = new Set();
+
+ constructor(elements) {
+ this.#elements = elements;
+
+ // We want to sync if any element's size changes or if it becomes
+ // more/less visible.
+ this.#elementIntersectionObserver = new IntersectionObserver(() => {
+ this.scheduleSync();
+ });
+ // TODO(fergal): Remove this? I'm not sure that we need the resize
+ // observer. Any resize that is important to us seems like it will
+ // also involve an intersection change.
+ this.#elementResizeObserver = new ResizeObserver(() => {
+ this.scheduleSync();
+ });
+
+ for (const element of this.#elements) {
+ this.#didAdd(element);
+ }
+ this.scheduleSync();
+ }
+
+ /**
+ * Attempts to unlock a range of elements suitable for the current
+ * viewport. This causes one forced layout.
+ */
+ #sync = () => {
+ if (this.#elements.length === 0) {
+ return;
+ }
+
+ // The basic idea is ...
+ // The forced layout occurs at the start. We then use the laid out
+ // coordinates (which are based on a mix of real sizes for
+ // unlocked elements and the estimated sizes at the time of
+ // locking for locked elements) to calculate a set of elements
+ // which should be revealed. We use unlock/lock to move to this
+ // new set of revealed elements. We will check in the next frame
+ // whether we got it correct.
+
+ // This causes a forced layout and takes measurements of all
+ // currently revealed elements.
+ this.#measureRevealed();
+
+ // Compute the pixel bounds of what we would like to reveal. Then
+ // find the elements corresponding to these bounds.
+ // TODO(fergal): Use nearest scrolling ancestor?
+ const desiredLow = 0 - window.innerHeight * BUFFER;
+ const desiredHigh = window.innerHeight + window.innerHeight * BUFFER;
+ const newBounds = this.#findElementBounds(desiredLow, desiredHigh);
+ const newRevealed = newBounds.elementSet();
+
+ // TODO(fergal): We need to observe 1 element off the end of the
+ // list, to cope with e.g. the scrolling region suddenly growing.
+
+ // Lock and unlock the minimal set of elements to get us to the
+ // new state.
+ const toHide = sets.difference(this.#revealed, newRevealed);
+ toHide.forEach(e => this.#hide(e));
+ const toReveal = sets.difference(newRevealed, this.#revealed);
+ toReveal.forEach(e => this.#reveal(e));
+
+ // Now we have revealed what we hope will fill the screen. It
+ // could be incorrect. Rather than measuring now and correcting it
+ // which would involve an unknown number of forced layouts, we
+ // come back next frame and try to make it better. We know we can
+ // stop when we didn't hide or reveal any elements.
+ if (toHide.size > 0 || toReveal.size > 0) {
+ this.scheduleSync();
+ }
+ }
+
+ /**
+ * Searches within the managed elements and returns an ElementBounds
+ * object. This object may represent an empty range or a range whose low
+ * element contains or is lower than |low| (or the lowest element
+ * possible). Similarly for |high|.
+ *
+ * @param {!number} low The lower bound to locate.
+ * @param {!number} high The upper bound to locate.
+ */
+ #findElementBounds = (low, high) => {
+ const lowElement = findElement.findElement(
+ this.#elements, low, findElement.BIAS_LOW);
+ const highElement = findElement.findElement(
+ this.#elements, high, findElement.BIAS_HIGH);
+
+ if (lowElement === null) {
+ if (highElement === null) {
+ return EMPTY_ELEMENT_BOUNDS;
+ } else {
+ return new ElementBounds(this.#elements[0], highElement);
+ }
+ } else if (highElement === null) {
+ return new ElementBounds(
+ lowElement, this.#elements[this.#elements.length - 1]);
+ }
+ return new ElementBounds(lowElement, highElement);
+ }
+
+ /**
+ * Updates the size manager with all of the currently revealed
+ * elements' sizes. This will cause a forced layout.
+ */
+ #measureRevealed = () => {
+ for (const element of this.#revealed) {
+ this.#sizeManager.measure(element);
+ }
+ }
+
+ /**
+ * Reveals |element| so that it can be rendered. This includes
+ * unlocking and adding to various observers.
+ *
+ * @param {!Element} element The element to reveal.
+ */
+ #reveal = element => {
+ this.#revealed.add(element);
+ this.#elementIntersectionObserver.observe(element);
+ this.#elementResizeObserver.observe(element);
+ this.#unlock(element);
+ }
+
+ #logLockingError = (operation, reason, element) => {
+ // TODO: Figure out the LAPIs error/warning logging story.
+ console.error('Rejected: ', operation, element, reason); // eslint-disable-line no-console
+ }
+
+ /**
+ * Unlocks |element|.
+ *
+ * @param {!Element} element The element to unlock.
+ */
+ #unlock = element => {
+ element.displayLock.commit().catch(reason => {
+ // Only warn if the unlocked failed and we should be revealed.
+ if (this.#revealed.has(element)) {
+ this.#logLockingError('Commit', reason, element);
+ }
+ });
+ }
+
+ /**
+ * Hides |element| so that it cannot be rendered. This includes
+ * locking and removing from various observers.
+ *
+ * @param {!Element} element The element to hide.
+ */
+ #hide = element => {
+ this.#revealed.delete(element);
+ this.#elementIntersectionObserver.unobserve(element);
+ this.#elementResizeObserver.unobserve(element);
+ element.displayLock.acquire({
+ timeout: Infinity,
+ activatable: true,
+ size: [LOCKED_WIDTH_PX, this.#sizeManager.getHopefulSize(element)],
+ }).catch(reason => {
+ // Only warn if the lock failed and we should be locked.
+ if (!this.#revealed.has(element)) {
+ this.#logLockingError('Acquire', reason, element);
+ }
+ });
+ }
+
+ /**
+ * Notify the manager that |element| has been added to the list of
+ * managed elements.
+ *
+ * @param {!Element} element The element that was added.
+ */
+ #didAdd = element => {
+ // Added children should be invisible initially. We want to make them
+ // invisible at this MutationObserver timing, so that there is no
+ // frame where the browser is asked to render all of the children
+ // (which could be a lot).
+ this.#hide(element);
+ }
+
+ /**
+ * Notify the manager that |element| has been removed from the list
+ * of managed elements.
+ *
+ * @param {!Element} element The element that was removed.
+ */
+ #didRemove = element => {
+ // Removed children should be made visible again. We should stop
+ // observing them and discard any size info we have for them as it
+ // may have become incorrect.
+ //
+ // TODO(fergal): Decide whether to also unlock if
+ // displayLock.locked is true. That would only be necessary if we
+ // got out of sync between this.#revealed and the locked state. So
+ // for now, assume are not buggy.
+ if (this.#revealed.has(element)) {
+ this.#unlock(element);
+ }
+ this.#revealed.delete(element);
+ this.#elementIntersectionObserver.unobserve(element);
+ this.#elementResizeObserver.unobserve(element);
+ this.#sizeManager.remove(element);
+ }
+
+ /**
+ * Ensures that @see #sync() will be called at the next animation frame.
+ */
+ scheduleSync() {
+ if (this.#syncRAFToken !== undefined) {
+ return;
+ }
+
+ this.#syncRAFToken = window.requestAnimationFrame(() => {
+ this.#syncRAFToken = undefined;
+ this.#sync();
+ });
+ }
+
+ /**
+ * Applys |records| generated by a mutation event to the manager.
+ * This computes the elements that were newly added/removed and
+ * notifies the managers for each.
+ *
+ * @param {!Object} records The mutations records.
+ */
+ applyMutationObserverRecords(records) {
+ // It's unclear if we can support children which are not
+ // elements. We cannot control their visibility using display
+ // locking but we can just leave them alone.
+ //
+ // Relevant mutations are any additions or removals, including
+ // non-elements and also elements that are removed and then
+ // re-added as this may impact element bounds.
+ let relevantMutation = false;
+ const toRemove = new Set();
+ for (const record of records) {
+ relevantMutation = relevantMutation || record.removedNodes.length > 0;
+ for (const node of record.removedNodes) {
+ if (node.nodeType === Node.ELEMENT_NODE) {
+ toRemove.add(node);
+ }
+ }
+ }
+
+ const toAdd = new Set();
+ for (const record of records) {
+ relevantMutation = relevantMutation || record.addedNodes.length > 0;
+ for (const node of record.addedNodes) {
+ if (node.nodeType === Node.ELEMENT_NODE) {
+ if (toRemove.has(node)) {
+ toRemove.delete(node);
+ } else {
+ toAdd.add(node);
+ }
+ }
+ }
+ }
+ for (const node of toRemove) {
+ this.#didRemove(node);
+ }
+ for (const node of toAdd) {
+ this.#didAdd(node);
+ }
+
+ if (relevantMutation) {
+ this.scheduleSync();
+ }
+ }
+}
+
diff --git a/chromium/third_party/blink/renderer/core/script/resources/layered_api/kv-storage/async_iterator.mjs b/chromium/third_party/blink/renderer/core/script/resources/layered_api/kv-storage/async_iterator.mjs
index 0da4854b99d..a83dba41c20 100644
--- a/chromium/third_party/blink/renderer/core/script/resources/layered_api/kv-storage/async_iterator.mjs
+++ b/chromium/third_party/blink/renderer/core/script/resources/layered_api/kv-storage/async_iterator.mjs
@@ -16,6 +16,8 @@ const AsyncIteratorPrototype = Object.getPrototypeOf(
const StorageAreaAsyncIteratorPrototype = {
__proto__: AsyncIteratorPrototype,
+ [Symbol.toStringTag]: 'StorageArea AsyncIterator',
+
next() {
const performDatabaseOperation = _performDatabaseOperation.get(this);
if (!performDatabaseOperation) {
@@ -42,6 +44,12 @@ const StorageAreaAsyncIteratorPrototype = {
},
};
+Object.defineProperty(
+ StorageAreaAsyncIteratorPrototype,
+ Symbol.toStringTag,
+ {writable: false, enumerable: false}
+);
+
function getNextIterResult(iter, performDatabaseOperation) {
return performDatabaseOperation(async (transaction, store) => {
const lastKey = _lastKey.get(iter);
diff --git a/chromium/third_party/blink/renderer/core/script/resources/layered_api/kv-storage/index.mjs b/chromium/third_party/blink/renderer/core/script/resources/layered_api/kv-storage/index.mjs
index b5272ea5d7b..88ef25e818a 100644
--- a/chromium/third_party/blink/renderer/core/script/resources/layered_api/kv-storage/index.mjs
+++ b/chromium/third_party/blink/renderer/core/script/resources/layered_api/kv-storage/index.mjs
@@ -5,16 +5,18 @@
import {createStorageAreaAsyncIterator} from './async_iterator.mjs';
import {promiseForRequest, promiseForTransaction, throwForDisallowedKey} from './idb_utils.mjs';
-// TODOs/spec-noncompliances:
+// Overall TODOs/spec-noncompliances:
// - Susceptible to tampering of built-in prototypes and globals. We want to
// work on tooling to ameliorate that.
const DEFAULT_STORAGE_AREA_NAME = 'default';
const DEFAULT_IDB_STORE_NAME = 'store';
+// TODO(crbug.com/977470): this should be handled via infrastructure that
+// avoids putting it in the module map entirely, not as a runtime check.
+// Several web platform tests fail because of this.
if (!self.isSecureContext) {
- throw new DOMException(
- 'KV Storage is only available in secure contexts', 'SecurityError');
+ throw new TypeError('KV Storage is only available in secure contexts');
}
export class StorageArea {
@@ -132,8 +134,25 @@ export class StorageArea {
}
StorageArea.prototype[Symbol.asyncIterator] = StorageArea.prototype.entries;
-
-export const storage = new StorageArea(DEFAULT_STORAGE_AREA_NAME);
+StorageArea.prototype[Symbol.toStringTag] = 'StorageArea';
+
+// Override the defaults that are implied by using class declarations and
+// assignment, to be more Web IDL-ey.
+// https://github.com/heycam/webidl/issues/738 may modify these a bit.
+Object.defineProperties(StorageArea.prototype, {
+ set: {enumerable: true},
+ get: {enumerable: true},
+ delete: {enumerable: true},
+ clear: {enumerable: true},
+ keys: {enumerable: true},
+ values: {enumerable: true},
+ entries: {enumerable: true},
+ backingStore: {enumerable: true},
+ [Symbol.asyncIterator]: {enumerable: false},
+ [Symbol.toStringTag]: {writable: false, enumerable: false}
+});
+
+export default new StorageArea(DEFAULT_STORAGE_AREA_NAME);
async function performDatabaseOperation(
promise, setPromise, name, mode, steps) {
@@ -145,7 +164,9 @@ async function performDatabaseOperation(
const transaction = database.transaction(DEFAULT_IDB_STORE_NAME, mode);
const store = transaction.objectStore(DEFAULT_IDB_STORE_NAME);
- return steps(transaction, store);
+ const result = steps(transaction, store);
+ transaction.commit();
+ return result;
}
function initializeDatabasePromise(setPromise, databaseName) {
diff --git a/chromium/third_party/blink/renderer/core/script/resources/layered_api/resources.grdp b/chromium/third_party/blink/renderer/core/script/resources/layered_api/resources.grdp
index 2a7e3b38f14..255d05543d1 100644
--- a/chromium/third_party/blink/renderer/core/script/resources/layered_api/resources.grdp
+++ b/chromium/third_party/blink/renderer/core/script/resources/layered_api/resources.grdp
@@ -7,14 +7,17 @@
third_party/blink/public/blink_resources.grd.
-->
<include name="IDR_LAYERED_API_BLANK_INDEX_MJS" file="../renderer/core/script/resources/layered_api/blank/index.mjs" type="BINDATA" skip_minify="true" compress="gzip"/>
+ <include name="IDR_LAYERED_API_ELEMENTS_INTERNAL_REFLECTION_MJS" file="../renderer/core/script/resources/layered_api/elements/internal/reflection.mjs" type="BINDATA" skip_minify="true" compress="gzip"/>
+ <include name="IDR_LAYERED_API_ELEMENTS_SWITCH_FACE_UTILS_MJS" file="../renderer/core/script/resources/layered_api/elements/switch/face_utils.mjs" type="BINDATA" skip_minify="true" compress="gzip"/>
+ <include name="IDR_LAYERED_API_ELEMENTS_SWITCH_INDEX_MJS" file="../renderer/core/script/resources/layered_api/elements/switch/index.mjs" type="BINDATA" skip_minify="true" compress="gzip"/>
+ <include name="IDR_LAYERED_API_ELEMENTS_SWITCH_STYLE_MJS" file="../renderer/core/script/resources/layered_api/elements/switch/style.mjs" type="BINDATA" skip_minify="true" compress="gzip"/>
+ <include name="IDR_LAYERED_API_ELEMENTS_SWITCH_TRACK_MJS" file="../renderer/core/script/resources/layered_api/elements/switch/track.mjs" type="BINDATA" skip_minify="true" compress="gzip"/>
+ <include name="IDR_LAYERED_API_ELEMENTS_TOAST_INDEX_MJS" file="../renderer/core/script/resources/layered_api/elements/toast/index.mjs" type="BINDATA" skip_minify="true" compress="gzip"/>
+ <include name="IDR_LAYERED_API_ELEMENTS_VIRTUAL_SCROLLER_FIND_ELEMENT_MJS" file="../renderer/core/script/resources/layered_api/elements/virtual-scroller/find-element.mjs" type="BINDATA" skip_minify="true" compress="gzip"/>
+ <include name="IDR_LAYERED_API_ELEMENTS_VIRTUAL_SCROLLER_INDEX_MJS" file="../renderer/core/script/resources/layered_api/elements/virtual-scroller/index.mjs" type="BINDATA" skip_minify="true" compress="gzip"/>
+ <include name="IDR_LAYERED_API_ELEMENTS_VIRTUAL_SCROLLER_SETS_MJS" file="../renderer/core/script/resources/layered_api/elements/virtual-scroller/sets.mjs" type="BINDATA" skip_minify="true" compress="gzip"/>
+ <include name="IDR_LAYERED_API_ELEMENTS_VIRTUAL_SCROLLER_VISIBILITY_MANAGER_MJS" file="../renderer/core/script/resources/layered_api/elements/virtual-scroller/visibility-manager.mjs" type="BINDATA" skip_minify="true" compress="gzip"/>
<include name="IDR_LAYERED_API_KV_STORAGE_ASYNC_ITERATOR_MJS" file="../renderer/core/script/resources/layered_api/kv-storage/async_iterator.mjs" type="BINDATA" skip_minify="true" compress="gzip"/>
<include name="IDR_LAYERED_API_KV_STORAGE_IDB_UTILS_MJS" file="../renderer/core/script/resources/layered_api/kv-storage/idb_utils.mjs" type="BINDATA" skip_minify="true" compress="gzip"/>
<include name="IDR_LAYERED_API_KV_STORAGE_INDEX_MJS" file="../renderer/core/script/resources/layered_api/kv-storage/index.mjs" type="BINDATA" skip_minify="true" compress="gzip"/>
- <include name="IDR_LAYERED_API_VIRTUAL_SCROLLER_INDEX_MJS" file="../renderer/core/script/resources/layered_api/virtual-scroller/index.mjs" type="BINDATA" skip_minify="true" compress="gzip"/>
- <include name="IDR_LAYERED_API_VIRTUAL_SCROLLER_ITEM_SOURCE_MJS" file="../renderer/core/script/resources/layered_api/virtual-scroller/item-source.mjs" type="BINDATA" skip_minify="true" compress="gzip"/>
- <include name="IDR_LAYERED_API_VIRTUAL_SCROLLER_VIRTUAL_REPEATER_MJS" file="../renderer/core/script/resources/layered_api/virtual-scroller/virtual-repeater.mjs" type="BINDATA" skip_minify="true" compress="gzip"/>
- <include name="IDR_LAYERED_API_VIRTUAL_SCROLLER_VIRTUAL_SCROLLER_MJS" file="../renderer/core/script/resources/layered_api/virtual-scroller/virtual-scroller.mjs" type="BINDATA" skip_minify="true" compress="gzip"/>
- <include name="IDR_LAYERED_API_VIRTUAL_SCROLLER_LAYOUTS_LAYOUT_1D_BASE_MJS" file="../renderer/core/script/resources/layered_api/virtual-scroller/layouts/layout-1d-base.mjs" type="BINDATA" skip_minify="true" compress="gzip"/>
- <include name="IDR_LAYERED_API_VIRTUAL_SCROLLER_LAYOUTS_LAYOUT_1D_GRID_MJS" file="../renderer/core/script/resources/layered_api/virtual-scroller/layouts/layout-1d-grid.mjs" type="BINDATA" skip_minify="true" compress="gzip"/>
- <include name="IDR_LAYERED_API_VIRTUAL_SCROLLER_LAYOUTS_LAYOUT_1D_MJS" file="../renderer/core/script/resources/layered_api/virtual-scroller/layouts/layout-1d.mjs" type="BINDATA" skip_minify="true" compress="gzip"/>
</grit-part>
diff --git a/chromium/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/README.chromium b/chromium/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/README.chromium
deleted file mode 100644
index e8b4d5d0007..00000000000
--- a/chromium/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/README.chromium
+++ /dev/null
@@ -1,12 +0,0 @@
-Name: virtual-scroller Layered API
-URL: https://github.com/valdrinkoshi/virtual-scroller
-Version: 58659cee10c5d9237821d5c475dac89720bd995d
-Security Critical: no
-
-Description:
-Temporarily, the files under this directory are authored by Chromium Authors
-on a github repository, and then imported to Chromium repository directly here,
-until a long-term Layered API development plan is settled.
-
-Local Modifications:
-None (except for renaming virtual-scroller-element.mjs to index.mjs)
diff --git a/chromium/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/index.mjs b/chromium/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/index.mjs
deleted file mode 100644
index 8cdad8091f7..00000000000
--- a/chromium/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/index.mjs
+++ /dev/null
@@ -1,213 +0,0 @@
-import {_item, _key, ItemSource} from './item-source.mjs';
-import {default as Layout1dGrid} from './layouts/layout-1d-grid.mjs';
-import {default as Layout1d} from './layouts/layout-1d.mjs';
-import {VirtualScroller} from './virtual-scroller.mjs';
-
-export {ItemSource};
-
-/** Properties */
-const _scroller = Symbol();
-const _createElement = Symbol();
-const _updateElement = Symbol();
-const _recycleElement = Symbol();
-const _nodePool = Symbol();
-const _rawItemSource = Symbol();
-const _itemSource = Symbol();
-const _elementSource = Symbol();
-const _firstConnected = Symbol();
-/** Functions */
-const _render = Symbol();
-
-export class VirtualScrollerElement extends HTMLElement {
- constructor() {
- super();
- this[_scroller] = null;
- // Default create/update/recycleElement.
- this[_nodePool] = [];
- let childTemplate = null;
- this[_createElement] = () => {
- if (this[_nodePool] && this[_nodePool].length) {
- return this[_nodePool].pop();
- }
- if (!childTemplate) {
- const template = this.querySelector('template');
- childTemplate = template && template.content.firstElementChild ?
- template.content.firstElementChild :
- document.createElement('div');
- }
- return childTemplate.cloneNode(true);
- };
- this[_updateElement] = (element, item) => element.textContent =
- item.toString();
- this[_recycleElement] = (element) => this[_nodePool].push(element);
-
- this[_itemSource] = this[_rawItemSource] = null;
- this[_elementSource] = {};
-
- this[_firstConnected] = false;
- }
-
- connectedCallback() {
- if (!this[_firstConnected]) {
- this.attachShadow({mode: 'open'}).innerHTML = `
-<style>
- :host {
- display: block;
- position: relative;
- contain: strict;
- height: 150px;
- overflow: auto;
- }
- :host([hidden]) {
- display: none;
- }
- ::slotted(*) {
- box-sizing: border-box;
- }
- :host([layout=vertical]) ::slotted(*) {
- width: 100%;
- }
- :host([layout=horizontal]) ::slotted(*) {
- height: 100%;
- }
-</style>
-<slot></slot>`;
- // Set default values.
- if (!this.layout) {
- this.layout = 'vertical';
- }
- // Enables rendering.
- this[_firstConnected] = true;
- }
- this[_render]();
- }
-
- static get observedAttributes() {
- return ['layout'];
- }
-
- attributeChangedCallback(name, oldVal, newVal) {
- this[_render]();
- }
-
- get layout() {
- return this.getAttribute('layout');
- }
- set layout(layout) {
- this.setAttribute('layout', layout);
- }
-
- get itemSource() {
- return this[_itemSource];
- }
- set itemSource(itemSource) {
- // No Change.
- if (this[_rawItemSource] === itemSource) {
- return;
- }
- this[_rawItemSource] = itemSource;
- this[_itemSource] = Array.isArray(itemSource) ?
- ItemSource.fromArray(itemSource) :
- itemSource;
- this[_render]();
- }
-
- get createElement() {
- return this[_createElement];
- }
- set createElement(fn) {
- // Resets default recycling.
- if (this[_nodePool]) {
- this.recycleElement = null;
- }
- this[_createElement] = fn;
- // Invalidate wrapped function.
- this[_elementSource].createElement = null;
- this[_render]();
- }
-
- get updateElement() {
- return this[_updateElement];
- }
- set updateElement(fn) {
- this[_updateElement] = fn;
- // Invalidate wrapped function.
- this[_elementSource].updateElement = null;
- this[_render]();
- }
-
- get recycleElement() {
- return this[_recycleElement];
- }
- set recycleElement(fn) {
- // Marks default recycling changed.
- this[_nodePool] = null;
- this[_recycleElement] = fn;
- // Invalidate wrapped function.
- this[_elementSource].recycleElement = null;
- this[_render]();
- }
-
- itemsChanged() {
- if (this[_scroller]) {
- // Render because length might have changed.
- this[_render]();
- // Request reset because items might have changed.
- this[_scroller].requestReset();
- }
- }
-
- scrollToIndex(index, { position = 'start' } = {}) {
- if (this[_scroller]) {
- this[_scroller].layout.scrollToIndex(index, position);
- }
- }
-
- [_render]() {
- // Wait first connected as scroller needs to measure
- // sizes of container and children.
- if (!this[_firstConnected] || !this.createElement) {
- return;
- }
- if (!this[_scroller]) {
- this[_scroller] =
- new VirtualScroller({container: this, scrollTarget: this});
- }
- const scroller = this[_scroller];
-
- const layoutAttr = this.layout;
- const Layout = layoutAttr.endsWith('-grid') ? Layout1dGrid : Layout1d;
- const direction =
- layoutAttr.startsWith('horizontal') ? 'horizontal' : 'vertical';
- const layout = scroller.layout instanceof Layout &&
- scroller.layout.direction === direction ?
- scroller.layout :
- new Layout({direction});
-
- let {createElement, updateElement, recycleElement} = this[_elementSource];
- if (!createElement) {
- createElement = this[_elementSource].createElement = (index) =>
- this.createElement(this.itemSource[_item](index), index);
- }
- if (this.updateElement && !updateElement) {
- updateElement = this[_elementSource].updateElement = (element, index) =>
- this.updateElement(element, this.itemSource[_item](index), index);
- }
- if (this.recycleElement && !recycleElement) {
- recycleElement = this[_elementSource].recycleElement = (element, index) =>
- this.recycleElement(element, this.itemSource[_item](index), index);
- }
-
- const elementKey = this.itemSource ? this.itemSource[_key] : null;
- const totalItems = this.itemSource ? this.itemSource.length : 0;
- Object.assign(scroller, {
- layout,
- createElement,
- updateElement,
- recycleElement,
- elementKey,
- totalItems
- });
- }
-}
-customElements.define('virtual-scroller', VirtualScrollerElement);
diff --git a/chromium/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/item-source.mjs b/chromium/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/item-source.mjs
deleted file mode 100644
index 255e97b245c..00000000000
--- a/chromium/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/item-source.mjs
+++ /dev/null
@@ -1,47 +0,0 @@
-export const _getLength = Symbol();
-export const _item = Symbol();
-export const _key = Symbol();
-
-export class ItemSource {
- constructor({getLength, item, key}) {
- if (typeof getLength !== 'function') {
- throw new TypeError('getLength option must be a function');
- }
- if (typeof item !== 'function') {
- throw new TypeError('item option must be a function');
- }
- if (typeof key !== 'function') {
- throw new TypeError('key option must be a function');
- }
-
- this[_getLength] = getLength;
- this[_item] = item;
- this[_key] = key;
- }
-
- static fromArray(array, key) {
- if (!Array.isArray(array)) {
- throw new TypeError('First argument to fromArray() must be an array');
- }
- if (typeof key !== 'function' && key !== undefined) {
- throw new TypeError(
- 'Second argument to fromArray() must be a function or undefined');
- }
-
- return new this({
- getLength() {
- return array.length;
- },
- item(index) {
- return array[index];
- },
- key(index) {
- return key ? key(array[index], index) : array[index];
- }
- });
- }
-
- get length() {
- return this[_getLength]();
- }
-}
diff --git a/chromium/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/layouts/layout-1d-base.mjs b/chromium/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/layouts/layout-1d-base.mjs
deleted file mode 100644
index 89a9a9e8106..00000000000
--- a/chromium/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/layouts/layout-1d-base.mjs
+++ /dev/null
@@ -1,320 +0,0 @@
-export default class Layout extends EventTarget {
- constructor(config) {
- super();
-
- this._physicalMin = 0;
- this._physicalMax = 0;
-
- this._first = -1;
- this._last = -1;
-
- this._latestCoords = {left: 0, top: 0};
-
- this._itemSize = {width: 100, height: 100};
- this._spacing = 0;
-
- this._sizeDim = 'height';
- this._secondarySizeDim = 'width';
- this._positionDim = 'top';
- this._secondaryPositionDim = 'left';
- this._direction = 'vertical';
-
- this._scrollPosition = 0;
- this._scrollError = 0;
- this._viewportSize = {width: 0, height: 0};
- this._totalItems = 0;
-
- this._scrollSize = 1;
-
- this._overhang = 150;
-
- this._pendingReflow = false;
-
- this._scrollToIndex = -1;
- this._scrollToAnchor = 0;
-
- Object.assign(this, config);
- }
-
- // public properties
-
- get totalItems() {
- return this._totalItems;
- }
- set totalItems(num) {
- if (num !== this._totalItems) {
- this._totalItems = num;
- this._maxIdx = num - 1;
- this._scheduleReflow();
- }
- }
-
- get direction() {
- return this._direction;
- }
- set direction(dir) {
- // Force it to be either horizontal or vertical.
- dir = (dir === 'horizontal') ? dir : 'vertical';
- if (dir !== this._direction) {
- this._direction = dir;
- this._sizeDim = (dir === 'horizontal') ? 'width' : 'height';
- this._secondarySizeDim = (dir === 'horizontal') ? 'height' : 'width';
- this._positionDim = (dir === 'horizontal') ? 'left' : 'top';
- this._secondaryPositionDim = (dir === 'horizontal') ? 'top' : 'left';
- this._scheduleReflow();
- }
- }
-
- get itemSize() {
- return this._itemSize;
- }
- set itemSize(dims) {
- const {_itemDim1, _itemDim2} = this;
- Object.assign(this._itemSize, dims);
- if (_itemDim1 !== this._itemDim1 || _itemDim2 !== this._itemDim2) {
- if (_itemDim2 !== this._itemDim2) {
- this._itemDim2Changed();
- } else {
- this._scheduleReflow();
- }
- }
- }
-
- get spacing() {
- return this._spacing;
- }
- set spacing(px) {
- if (px !== this._spacing) {
- this._spacing = px;
- this._scheduleReflow();
- }
- }
-
- get viewportSize() {
- return this._viewportSize;
- }
- set viewportSize(dims) {
- const {_viewDim1, _viewDim2} = this;
- Object.assign(this._viewportSize, dims);
- if (_viewDim2 !== this._viewDim2) {
- this._viewDim2Changed();
- } else if (_viewDim1 !== this._viewDim1) {
- this._checkThresholds();
- }
- }
-
- get viewportScroll() {
- return this._latestCoords;
- }
- set viewportScroll(coords) {
- Object.assign(this._latestCoords, coords);
- const oldPos = this._scrollPosition;
- this._scrollPosition = this._latestCoords[this._positionDim];
- if (oldPos !== this._scrollPosition) {
- this._scrollPositionChanged(oldPos, this._scrollPosition);
- }
- this._checkThresholds();
- }
-
- // private properties
-
- get _delta() {
- return this._itemDim1 + this._spacing;
- }
-
- get _itemDim1() {
- return this._itemSize[this._sizeDim];
- }
-
- get _itemDim2() {
- return this._itemSize[this._secondarySizeDim];
- }
-
- get _viewDim1() {
- return this._viewportSize[this._sizeDim];
- }
-
- get _viewDim2() {
- return this._viewportSize[this._secondarySizeDim];
- }
-
- get _num() {
- if (this._first === -1 || this._last === -1) {
- return 0;
- }
- return this._last - this._first + 1;
- }
-
- // public methods
-
- reflowIfNeeded() {
- if (this._pendingReflow) {
- this._pendingReflow = false;
- this._reflow();
- }
- }
-
- scrollToIndex(index, position = 'start') {
- if (!Number.isFinite(index))
- return;
- index = Math.min(this.totalItems, Math.max(0, index));
- this._scrollToIndex = index;
- if (position === 'nearest') {
- position = index > this._first + this._num / 2 ? 'end' : 'start';
- }
- switch (position) {
- case 'start':
- this._scrollToAnchor = 0;
- break;
- case 'center':
- this._scrollToAnchor = 0.5;
- break;
- case 'end':
- this._scrollToAnchor = 1;
- break;
- default:
- throw new TypeError(
- 'position must be one of: start, center, end, nearest');
- }
- this._scheduleReflow();
- this.reflowIfNeeded();
- }
-
- ///
-
- _scheduleReflow() {
- this._pendingReflow = true;
- }
-
- _reflow() {
- const {_first, _last, _scrollSize} = this;
-
- this._updateScrollSize();
- this._getActiveItems();
- this._scrollIfNeeded();
-
- if (this._scrollSize !== _scrollSize) {
- this._emitScrollSize();
- }
-
- if (this._first === -1 && this._last === -1) {
- this._emitRange();
- } else if (
- this._first !== _first || this._last !== _last ||
- this._spacingChanged) {
- this._emitRange();
- this._emitChildPositions();
- }
- this._emitScrollError();
- }
-
- _updateScrollSize() {
- // Ensure we have at least 1px - this allows getting at least 1 item to be
- // rendered.
- this._scrollSize = Math.max(1, this._totalItems * this._delta);
- }
-
- _checkThresholds() {
- if (this._viewDim1 === 0 && this._num > 0) {
- this._scheduleReflow();
- } else {
- const min = Math.max(0, this._scrollPosition - this._overhang);
- const max = Math.min(
- this._scrollSize,
- this._scrollPosition + this._viewDim1 + this._overhang);
- if (this._physicalMin > min || this._physicalMax < max) {
- this._scheduleReflow();
- }
- }
- }
-
- _scrollIfNeeded() {
- if (this._scrollToIndex === -1) {
- return;
- }
- const index = this._scrollToIndex;
- const anchor = this._scrollToAnchor;
- const pos = this._getItemPosition(index)[this._positionDim];
- const size = this._getItemSize(index)[this._sizeDim];
-
- const curAnchorPos = this._scrollPosition + this._viewDim1 * anchor;
- const newAnchorPos = pos + size * anchor;
- // Ensure scroll position is an integer within scroll bounds.
- const scrollPosition = Math.floor(Math.min(
- this._scrollSize - this._viewDim1,
- Math.max(0, this._scrollPosition - curAnchorPos + newAnchorPos)));
- this._scrollError += this._scrollPosition - scrollPosition;
- this._scrollPosition = scrollPosition;
- }
-
- _emitRange(inProps) {
- const detail = Object.assign(
- {
- first: this._first,
- last: this._last,
- num: this._num,
- stable: true,
- },
- inProps);
- this.dispatchEvent(new CustomEvent('rangechange', {detail}));
- }
-
- _emitScrollSize() {
- const detail = {
- [this._sizeDim]: this._scrollSize,
- };
- this.dispatchEvent(new CustomEvent('scrollsizechange', {detail}));
- }
-
- _emitScrollError() {
- if (this._scrollError) {
- const detail = {
- [this._positionDim]: this._scrollError,
- [this._secondaryPositionDim]: 0,
- };
- this.dispatchEvent(new CustomEvent('scrollerrorchange', {detail}));
- this._scrollError = 0;
- }
- }
-
- _emitChildPositions() {
- const detail = {};
- for (let idx = this._first; idx <= this._last; idx++) {
- detail[idx] = this._getItemPosition(idx);
- }
- this.dispatchEvent(new CustomEvent('itempositionchange', {detail}));
- }
-
- _itemDim2Changed() {
- // Override
- }
-
- _viewDim2Changed() {
- // Override
- }
-
- _scrollPositionChanged(oldPos, newPos) {
- // When both values are bigger than the max scroll position, keep the
- // current _scrollToIndexx, otherwise invalidate it.
- const maxPos = this._scrollSize - this._viewDim1;
- if (oldPos < maxPos || newPos < maxPos) {
- this._scrollToIndex = -1;
- }
- }
-
- _getActiveItems() {
- // Override
- }
-
- _getItemPosition(idx) {
- // Override.
- }
-
- _getItemSize(idx) {
- // Override.
- return {
- [this._sizeDim]: this._itemDim1,
- [this._secondarySizeDim]: this._itemDim2,
- };
- }
-} \ No newline at end of file
diff --git a/chromium/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/layouts/layout-1d-grid.mjs b/chromium/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/layouts/layout-1d-grid.mjs
deleted file mode 100644
index c9c00d021da..00000000000
--- a/chromium/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/layouts/layout-1d-grid.mjs
+++ /dev/null
@@ -1,64 +0,0 @@
-import Layout1dBase from './layout-1d-base.mjs';
-
-export default class Layout extends Layout1dBase {
- constructor(config) {
- super(config);
- this._rolumns = 1;
- }
-
- updateItemSizes(sizes) {
- // Assume all items have the same size.
- const size = Object.values(sizes)[0];
- if (size) {
- this.itemSize = size;
- }
- }
-
- _viewDim2Changed() {
- this._defineGrid();
- }
-
- _itemDim2Changed() {
- this._defineGrid();
- }
-
- _getActiveItems() {
- const min = Math.max(0, this._scrollPosition - this._overhang);
- const max = Math.min(
- this._scrollSize,
- this._scrollPosition + this._viewDim1 + this._overhang);
- const firstCow = Math.floor(min / this._delta);
- const lastCow = Math.ceil(max / this._delta) - 1;
-
- this._first = firstCow * this._rolumns;
- this._last =
- Math.min(((lastCow + 1) * this._rolumns) - 1, this._totalItems);
- this._physicalMin = this._delta * firstCow;
- this._physicalMax = this._delta * (lastCow + 1);
- }
-
- _getItemPosition(idx) {
- return {
- [this._positionDim]: Math.floor(idx / this._rolumns) * this._delta,
- [this._secondaryPositionDim]: this._spacing +
- ((idx % this._rolumns) * (this._spacing + this._itemDim2))
- }
- }
-
-
- _defineGrid() {
- const {_spacing} = this;
- this._rolumns = Math.max(1, Math.floor(this._viewDim2 / this._itemDim2));
- if (this._rolumns > 1) {
- this._spacing = (this._viewDim2 % (this._rolumns * this._itemDim2)) /
- (this._rolumns + 1);
- }
- this._spacingChanged = !(_spacing === this._spacing);
- this._scheduleReflow();
- }
-
- _updateScrollSize() {
- this._scrollSize =
- Math.max(1, Math.ceil(this._totalItems / this._rolumns) * this._delta);
- }
-} \ No newline at end of file
diff --git a/chromium/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/layouts/layout-1d.mjs b/chromium/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/layouts/layout-1d.mjs
deleted file mode 100644
index 6f5d181cb0e..00000000000
--- a/chromium/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/layouts/layout-1d.mjs
+++ /dev/null
@@ -1,349 +0,0 @@
-import Layout1dBase from './layout-1d-base.mjs';
-
-export default class Layout extends Layout1dBase {
- constructor(config) {
- super(config);
- this._physicalItems = new Map();
- this._newPhysicalItems = new Map();
-
- this._metrics = new Map();
-
- this._anchorIdx = null;
- this._anchorPos = null;
- this._stable = true;
-
- this._needsRemeasure = false;
-
- this._nMeasured = 0;
- this._tMeasured = 0;
-
- this._estimate = true;
- }
-
- updateItemSizes(sizes) {
- Object.keys(sizes).forEach((key) => {
- const metrics = sizes[key], mi = this._getMetrics(key),
- prevSize = mi[this._sizeDim];
-
- // TODO(valdrin) Handle margin collapsing.
- // https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing
- mi.width = metrics.width + (metrics.marginLeft || 0) +
- (metrics.marginRight || 0);
- mi.height = metrics.height + (metrics.marginTop || 0) +
- (metrics.marginBottom || 0);
-
- const size = mi[this._sizeDim];
- const item = this._getPhysicalItem(Number(key));
- if (item) {
- let delta;
-
- if (size !== undefined) {
- item.size = size;
- if (prevSize === undefined) {
- delta = size;
- this._nMeasured++;
- } else {
- delta = size - prevSize;
- }
- }
- this._tMeasured = this._tMeasured + delta;
- } else {
- // console.debug(`Could not find physical item for key ${key}`);
- }
- });
- if (!this._nMeasured) {
- console.warn(`No items measured yet.`);
- } else {
- this._updateItemSize();
- this._scheduleReflow();
- }
- }
-
- _updateItemSize() {
- // Keep integer values.
- this._itemSize[this._sizeDim] =
- Math.round(this._tMeasured / this._nMeasured);
- }
-
- //
-
- _getMetrics(idx) {
- return (this._metrics[idx] = this._metrics[idx] || {});
- }
-
- _getPhysicalItem(idx) {
- return this._newPhysicalItems.get(idx) || this._physicalItems.get(idx);
- }
-
- _getSize(idx) {
- const item = this._getPhysicalItem(idx);
- return item && item.size;
- }
-
- _getPosition(idx) {
- const item = this._physicalItems.get(idx);
- return item ? item.pos : (idx * (this._delta)) + this._spacing;
- }
-
- _calculateAnchor(lower, upper) {
- if (lower === 0) {
- return 0;
- }
- if (upper > this._scrollSize - this._viewDim1) {
- return this._maxIdx;
- }
- return Math.max(
- 0,
- Math.min(
- this._maxIdx, Math.floor(((lower + upper) / 2) / this._delta)));
- }
-
- _getAnchor(lower, upper) {
- if (this._physicalItems.size === 0) {
- return this._calculateAnchor(lower, upper);
- }
- if (this._first < 0) {
- console.error('_getAnchor: negative _first');
- return this._calculateAnchor(lower, upper);
- }
- if (this._last < 0) {
- console.error('_getAnchor: negative _last');
- return this._calculateAnchor(lower, upper);
- }
-
- const firstItem = this._getPhysicalItem(this._first),
- lastItem = this._getPhysicalItem(this._last),
- firstMin = firstItem.pos, firstMax = firstMin + firstItem.size,
- lastMin = lastItem.pos, lastMax = lastMin + lastItem.size;
-
- if (lastMax < lower) {
- // Window is entirely past physical items, calculate new anchor
- return this._calculateAnchor(lower, upper);
- }
- if (firstMin > upper) {
- // Window is entirely before physical items, calculate new anchor
- return this._calculateAnchor(lower, upper);
- }
- if (firstMin >= lower || firstMax >= lower) {
- // First physical item overlaps window, choose it
- return this._first;
- }
- if (lastMax <= upper || lastMin <= upper) {
- // Last physical overlaps window, choose it
- return this._last;
- }
- // Window contains a physical item, but not the first or last
- let maxIdx = this._last, minIdx = this._first;
-
- while (true) {
- let candidateIdx = Math.round((maxIdx + minIdx) / 2),
- candidate = this._physicalItems.get(candidateIdx),
- cMin = candidate.pos, cMax = cMin + candidate.size;
-
- if ((cMin >= lower && cMin <= upper) ||
- (cMax >= lower && cMax <= upper)) {
- return candidateIdx;
- } else if (cMax < lower) {
- minIdx = candidateIdx + 1;
- } else if (cMin > upper) {
- maxIdx = candidateIdx - 1;
- }
- }
- }
-
- _getActiveItems() {
- if (this._viewDim1 === 0 || this._totalItems === 0) {
- this._clearItems();
- } else {
- const upper = Math.min(
- this._scrollSize,
- this._scrollPosition + this._viewDim1 + this._overhang),
- lower = Math.max(0, upper - this._viewDim1 - (2 * this._overhang));
-
- this._getItems(lower, upper);
- }
- }
-
- _clearItems() {
- this._first = -1;
- this._last = -1;
- this._physicalMin = 0;
- this._physicalMax = 0;
- const items = this._newPhysicalItems;
- this._newPhysicalItems = this._physicalItems;
- this._newPhysicalItems.clear();
- this._physicalItems = items;
- this._stable = true;
- }
-
- _getItems(lower, upper) {
- const items = this._newPhysicalItems;
-
- // The anchorIdx is the anchor around which we reflow.
- // It is designed to allow jumping to any point of the scroll size.
- // We choose it once and stick with it until stable. first and last are
- // deduced around it.
- if (this._anchorIdx === null || this._anchorPos === null) {
- this._anchorIdx = this._getAnchor(lower, upper);
- this._anchorPos = this._getPosition(this._anchorIdx);
- }
-
- let anchorSize = this._getSize(this._anchorIdx);
- if (anchorSize === undefined) {
- anchorSize = this._itemDim1;
- }
-
- // Anchor might be outside bounds, so prefer correcting the error and keep
- // that anchorIdx.
- let anchorErr = 0;
-
- if (this._anchorPos + anchorSize + this._spacing < lower) {
- anchorErr = lower - (this._anchorPos + anchorSize + this._spacing);
- }
-
- if (this._anchorPos > upper) {
- anchorErr = upper - this._anchorPos;
- }
-
- if (anchorErr) {
- this._scrollPosition -= anchorErr;
- lower -= anchorErr;
- upper -= anchorErr;
- this._scrollError += anchorErr;
- }
-
- items.set(this._anchorIdx, {pos: this._anchorPos, size: anchorSize});
-
- this._first = (this._last = this._anchorIdx);
- this._physicalMin = (this._physicalMax = this._anchorPos);
-
- this._stable = true;
-
- while (this._physicalMin > lower && this._first > 0) {
- let size = this._getSize(--this._first);
- if (size === undefined) {
- this._stable = false;
- size = this._itemDim1;
- }
- const pos = (this._physicalMin -= size + this._spacing);
- items.set(this._first, {pos, size});
- if (this._stable === false && this._estimate === false) {
- break;
- }
- }
-
- while (this._physicalMax < upper && this._last < this._totalItems) {
- let size = this._getSize(this._last);
- if (size === undefined) {
- this._stable = false;
- size = this._itemDim1;
- }
- items.set(this._last++, {pos: this._physicalMax, size});
- if (this._stable === false && this._estimate === false) {
- break;
- } else {
- this._physicalMax += size + this._spacing;
- }
- }
-
- this._last--;
-
- // This handles the cases where we were relying on estimated sizes.
- const extentErr = this._calculateError();
- if (extentErr) {
- this._physicalMin -= extentErr;
- this._physicalMax -= extentErr;
- this._anchorPos -= extentErr;
- this._scrollPosition -= extentErr;
- items.forEach(item => item.pos -= extentErr);
- this._scrollError += extentErr;
- }
-
- if (this._stable) {
- this._newPhysicalItems = this._physicalItems;
- this._newPhysicalItems.clear();
- this._physicalItems = items;
- }
- }
-
- _calculateError() {
- if (this._first === 0) {
- return this._physicalMin;
- } else if (this._physicalMin <= 0) {
- return this._physicalMin - (this._first * this._delta);
- } else if (this._last === this._maxIdx) {
- return this._physicalMax - this._scrollSize;
- } else if (this._physicalMax >= this._scrollSize) {
- return (
- (this._physicalMax - this._scrollSize) +
- ((this._maxIdx - this._last) * this._delta));
- }
- return 0;
- }
-
- _updateScrollSize() {
- // Reuse previously calculated physical max, as it might be
- // higher than the estimated size.
- super._updateScrollSize();
- this._scrollSize = Math.max(this._physicalMax, this._scrollSize);
- }
-
- // TODO: Can this be made to inherit from base, with proper hooks?
- _reflow() {
- const {_first, _last, _scrollSize} = this;
-
- this._updateScrollSize();
- this._getActiveItems();
- this._scrollIfNeeded();
-
- if (this._scrollSize !== _scrollSize) {
- this._emitScrollSize();
- }
-
- this._emitRange();
- if (this._first === -1 && this._last === -1) {
- this._resetReflowState();
- } else if (
- this._first !== _first || this._last !== _last ||
- this._needsRemeasure) {
- this._emitChildPositions();
- this._emitScrollError();
- } else {
- this._emitChildPositions();
- this._emitScrollError();
- this._resetReflowState();
- }
- }
-
- _resetReflowState() {
- this._anchorIdx = null;
- this._anchorPos = null;
- this._stable = true;
- }
-
- _getItemPosition(idx) {
- return {
- [this._positionDim]: this._getPosition(idx),
- [this._secondaryPositionDim]: 0
- }
- }
-
- _getItemSize(idx) {
- return {
- [this._sizeDim]: this._getSize(idx) || this._itemDim1,
- [this._secondarySizeDim]: this._itemDim2,
- };
- }
-
- _viewDim2Changed() {
- this._needsRemeasure = true;
- this._scheduleReflow();
- }
-
- _emitRange() {
- const remeasure = this._needsRemeasure;
- const stable = this._stable;
- this._needsRemeasure = false;
- super._emitRange({remeasure, stable});
- }
-}
diff --git a/chromium/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/virtual-repeater.mjs b/chromium/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/virtual-repeater.mjs
deleted file mode 100644
index 3d3cb6aa7c1..00000000000
--- a/chromium/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/virtual-repeater.mjs
+++ /dev/null
@@ -1,531 +0,0 @@
-export const Repeats = Superclass => class extends Superclass {
- constructor(config) {
- super();
-
- this._createElementFn = null;
- this._updateElementFn = null;
- this._recycleElementFn = null;
- this._elementKeyFn = null;
-
- this._measureCallback = null;
-
- this._totalItems = 0;
- // Consider renaming this. firstVisibleIndex?
- this._first = 0;
- // Consider renaming this. count? visibleElements?
- this._num = Infinity;
-
- this.__incremental = false;
-
- // used only internally..
- // legacy from 1st approach to preact integration
- this._manageDom = true;
- // used to check if it is more perf if you don't care of dom order?
- this._maintainDomOrder = true;
-
- this._last = 0;
- this._prevFirst = 0;
- this._prevLast = 0;
-
- this._needsReset = false;
- this._needsRemeasure = false;
- this._pendingRender = null;
-
- // Contains child nodes in the rendered order.
- this._ordered = [];
- // this._pool = [];
- this._active = new Map();
- this._prevActive = new Map();
- // Both used for recycling purposes.
- this._keyToChild = new Map();
- this._childToKey = new WeakMap();
- // Used to keep track of measures by index.
- this._indexToMeasure = {};
- // Used to debounce _measureChildren calls.
- this._measuringId = -1;
-
- if (config) {
- Object.assign(this, config);
- }
- }
-
- // API
-
- get container() {
- return this._container;
- }
- set container(container) {
- if (container === this._container) {
- return;
- }
- if (this._container) {
- // Remove children from old container.
- this._ordered.forEach((child) => this._removeChild(child));
- }
-
- this._container = container;
-
- if (container) {
- // Insert children in new container.
- this._ordered.forEach((child) => this._insertBefore(child, null));
- } else {
- this._ordered.length = 0;
- this._active.clear();
- this._prevActive.clear();
- }
- this.requestReset();
- }
-
- get createElement() {
- return this._createElementFn;
- }
- set createElement(fn) {
- if (fn !== this._createElementFn) {
- this._createElementFn = fn;
- this._keyToChild.clear();
- this.requestReset();
- }
- }
-
- get updateElement() {
- return this._updateElementFn;
- }
- set updateElement(fn) {
- if (fn !== this._updateElementFn) {
- this._updateElementFn = fn;
- this.requestReset();
- }
- }
-
- get recycleElement() {
- return this._recycleElementFn;
- }
- set recycleElement(fn) {
- if (fn !== this._recycleElementFn) {
- this._recycleElementFn = fn;
- this.requestReset();
- }
- }
-
- get elementKey() {
- return this._elementKeyFn;
- }
- set elementKey(fn) {
- if (fn !== this._elementKeyFn) {
- this._elementKeyFn = fn;
- this._keyToChild.clear();
- this.requestReset();
- }
- }
-
- get first() {
- return this._first;
- }
-
- set first(idx) {
- if (typeof idx === 'number') {
- const newFirst = Math.max(0, Math.min(idx, this._totalItems - this._num));
- if (newFirst !== this._first) {
- this._first = newFirst;
- this._scheduleRender();
- }
- }
- }
-
- get num() {
- return this._num;
- }
-
- set num(n) {
- if (typeof n === 'number') {
- if (n !== this._num) {
- this._num = n;
- this.first = this._first;
- this._scheduleRender();
- }
- }
- }
-
- get totalItems() {
- return this._totalItems;
- }
-
- set totalItems(num) {
- // TODO(valdrin) should we check if it is a finite number?
- // Technically, Infinity would break Layout, not VirtualRepeater.
- if (typeof num === 'number' && num !== this._totalItems) {
- this._totalItems = num;
- this.first = this._first;
- this.requestReset();
- }
- }
-
- get _incremental() {
- return this.__incremental;
- }
-
- set _incremental(inc) {
- if (inc !== this.__incremental) {
- this.__incremental = inc;
- this._scheduleRender();
- }
- }
-
- requestReset() {
- this._needsReset = true;
- this._scheduleRender();
- }
-
- requestRemeasure() {
- this._needsRemeasure = true;
- this._scheduleRender();
- }
-
- // Core functionality
-
- /**
- * @protected
- */
- _shouldRender() {
- return Boolean(this.container && this.createElement);
- }
-
- /**
- * @private
- */
- _scheduleRender() {
- if (!this._pendingRender) {
- this._pendingRender = requestAnimationFrame(() => {
- this._pendingRender = null;
- if (this._shouldRender()) {
- this._render();
- }
- });
- }
- }
-
- /**
- * Returns those children that are about to be displayed and that
- * require to be positioned. If reset or remeasure has been triggered,
- * all children are returned.
- * @return {{indices:Array<number>,children:Array<Element>}}
- * @private
- */
- get _toMeasure() {
- return this._ordered.reduce((toMeasure, c, i) => {
- const idx = this._first + i;
- if (this._needsReset || this._needsRemeasure || idx < this._prevFirst ||
- idx > this._prevLast) {
- toMeasure.indices.push(idx);
- toMeasure.children.push(c);
- }
- return toMeasure;
- }, {indices: [], children: []});
- }
-
- /**
- * Measures each child bounds and builds a map of index/bounds to be passed to
- * the `_measureCallback`
- * @private
- */
- _measureChildren({indices, children}) {
- let pm = children.map(
- (c, i) => this._indexToMeasure[indices[i]] || this._measureChild(c));
- const mm = /** @type {{ number: { width: number, height: number } }} */
- (pm.reduce((out, cur, i) => {
- out[indices[i]] = this._indexToMeasure[indices[i]] = cur;
- return out;
- }, {}));
- this._measureCallback(mm);
- }
-
- /**
- * @protected
- */
- _render() {
- const rangeChanged =
- this._first !== this._prevFirst || this._num !== this._prevNum;
- // Create/update/recycle DOM.
- if (rangeChanged || this._needsReset) {
- this._last =
- this._first + Math.min(this._num, this._totalItems - this._first) - 1;
- if (this._num || this._prevNum) {
- if (this._needsReset) {
- this._reset(this._first, this._last);
- } else {
- this._discardHead();
- this._discardTail();
- this._addHead();
- this._addTail();
- }
- }
- }
- if (this._needsRemeasure || this._needsReset) {
- this._indexToMeasure = {};
- }
- // Retrieve DOM to be measured.
- // Do it right before cleanup and reset of properties.
- const shouldMeasure = this._num > 0 && this._measureCallback &&
- (rangeChanged || this._needsRemeasure || this._needsReset);
- const toMeasure = shouldMeasure ? this._toMeasure : null;
-
- // Cleanup.
- if (!this._incremental) {
- this._prevActive.forEach((idx, child) => this._unassignChild(child, idx));
- this._prevActive.clear();
- }
- // Reset internal properties.
- this._prevFirst = this._first;
- this._prevLast = this._last;
- this._prevNum = this._num;
- this._needsReset = false;
- this._needsRemeasure = false;
-
- // Notify render completed.
- this._didRender();
- // Measure DOM.
- if (toMeasure) {
- this._measureChildren(toMeasure);
- }
- }
-
- /**
- * Invoked after DOM is updated, and before it gets measured.
- * @protected
- */
- _didRender() {
- }
-
- /**
- * @private
- */
- _discardHead() {
- const o = this._ordered;
- for (let idx = this._prevFirst; o.length && idx < this._first; idx++) {
- this._unassignChild(o.shift(), idx);
- }
- }
-
- /**
- * @private
- */
- _discardTail() {
- const o = this._ordered;
- for (let idx = this._prevLast; o.length && idx > this._last; idx--) {
- this._unassignChild(o.pop(), idx);
- }
- }
-
- /**
- * @private
- */
- _addHead() {
- const start = this._first;
- const end = Math.min(this._last, this._prevFirst - 1);
- for (let idx = end; idx >= start; idx--) {
- const child = this._assignChild(idx);
- if (this._manageDom) {
- if (this._maintainDomOrder || !this._childIsAttached(child)) {
- this._insertBefore(child, this._firstChild);
- }
- }
- if (this.updateElement) {
- this.updateElement(child, idx);
- }
- this._ordered.unshift(child);
- }
- }
-
- /**
- * @private
- */
- _addTail() {
- const start = Math.max(this._first, this._prevLast + 1);
- const end = this._last;
- for (let idx = start; idx <= end; idx++) {
- const child = this._assignChild(idx);
- if (this._manageDom) {
- if (this._maintainDomOrder || !this._childIsAttached(child)) {
- this._insertBefore(child, null);
- }
- }
- if (this.updateElement) {
- this.updateElement(child, idx);
- }
- this._ordered.push(child);
- }
- }
-
- /**
- * @param {number} first
- * @param {number} last
- * @private
- */
- _reset(first, last) {
- const len = last - first + 1;
- // Explain why swap prevActive with active - affects _assignChild.
- const prevActive = this._active;
- this._active = this._prevActive;
- this._prevActive = prevActive;
- let currentMarker = this._manageDom && this._firstChild;
- this._ordered.length = 0;
- for (let n = 0; n < len; n++) {
- const idx = first + n;
- const child = this._assignChild(idx);
- this._ordered.push(child);
- if (this._manageDom) {
- if (currentMarker && this._maintainDomOrder) {
- if (currentMarker === this._node(child)) {
- currentMarker = this._nextSibling(child);
- } else {
- this._insertBefore(child, currentMarker);
- }
- } else if (!this._childIsAttached(child)) {
- this._insertBefore(child, null);
- }
- }
- if (this.updateElement) {
- this.updateElement(child, idx);
- }
- }
- }
-
- /**
- * @param {number} idx
- * @private
- */
- _assignChild(idx) {
- const key = this.elementKey ? this.elementKey(idx) : idx;
- let child;
- if (child = this._keyToChild.get(key)) {
- this._prevActive.delete(child);
- } else {
- child = this.createElement(idx);
- this._keyToChild.set(key, child);
- this._childToKey.set(child, key);
- }
- this._showChild(child);
- this._active.set(child, idx);
- return child;
- }
-
- /**
- * @param {*} child
- * @param {number} idx
- * @private
- */
- _unassignChild(child, idx) {
- this._hideChild(child);
- if (this._incremental) {
- this._active.delete(child);
- this._prevActive.set(child, idx);
- } else {
- const key = this._childToKey.get(child);
- this._childToKey.delete(child);
- this._keyToChild.delete(key);
- this._active.delete(child);
- if (this.recycleElement) {
- this.recycleElement(child, idx);
- } else if (this._node(child).parentNode) {
- this._removeChild(child);
- }
- }
- }
-
- // TODO: Is this the right name?
- /**
- * @private
- */
- get _firstChild() {
- return this._ordered.length && this._childIsAttached(this._ordered[0]) ?
- this._node(this._ordered[0]) :
- null;
- }
-
- // Overridable abstractions for child manipulation
- /**
- * @protected
- */
- _node(child) {
- return child;
- }
- /**
- * @protected
- */
- _nextSibling(child) {
- return child.nextSibling;
- }
- /**
- * @protected
- */
- _insertBefore(child, referenceNode) {
- this._container.insertBefore(child, referenceNode);
- }
- /**
- * @protected
- */
- _childIsAttached(child) {
- const node = this._node(child);
- return node && node.parentNode === this._container;
- }
- /**
- * @protected
- */
- _hideChild(child) {
- if (child.style) {
- child.style.display = 'none';
- }
- }
- /**
- * @protected
- */
- _showChild(child) {
- if (child.style) {
- child.style.display = null;
- }
- }
-
- /**
- *
- * @param {!Element} child
- * @return {{width: number, height: number, marginTop: number, marginBottom: number, marginLeft: number, marginRight: number}} childMeasures
- * @protected
- */
- _measureChild(child) {
- // offsetWidth doesn't take transforms in consideration,
- // so we use getBoundingClientRect which does.
- const {width, height} = child.getBoundingClientRect();
- // console.debug(`_measureChild #${this._container.id} > #${
- // child.id}: height: ${height}px`);
- return Object.assign({width, height}, getMargins(child));
- }
-
- /**
- * Remove child.
- * Override to control child removal.
- *
- * @param {*} child
- * @protected
- */
- _removeChild(child) {
- child.parentNode.removeChild(child);
- }
-}
-
-function getMargins(el) {
- const style = window.getComputedStyle(el);
- // console.log(el.id, style.position);
- return {
- marginLeft: getMarginValue(style.marginLeft),
- marginRight: getMarginValue(style.marginRight),
- marginTop: getMarginValue(style.marginTop),
- marginBottom: getMarginValue(style.marginBottom),
- };
-}
-
-function getMarginValue(value) {
- value = value ? parseFloat(value) : NaN;
- return value !== value ? 0 : value;
-}
-
-export const VirtualRepeater = Repeats(class {}); \ No newline at end of file
diff --git a/chromium/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/virtual-scroller.mjs b/chromium/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/virtual-scroller.mjs
deleted file mode 100644
index 049501e6ec9..00000000000
--- a/chromium/third_party/blink/renderer/core/script/resources/layered_api/virtual-scroller/virtual-scroller.mjs
+++ /dev/null
@@ -1,444 +0,0 @@
-import {Repeats} from './virtual-repeater.mjs';
-
-export class RangeChangeEvent extends Event {
- constructor(type, init) {
- super(type, init);
- this._first = Math.floor(init.first || 0);
- this._last = Math.floor(init.last || 0);
- }
- get first() {
- return this._first;
- }
- get last() {
- return this._last;
- }
-}
-
-export const RepeatsAndScrolls = Superclass => class extends Repeats
-(Superclass) {
- constructor(config) {
- super();
- this._num = 0;
- this._first = -1;
- this._last = -1;
- this._prevFirst = -1;
- this._prevLast = -1;
-
- this._needsUpdateView = false;
- this._containerElement = null;
- this._layout = null;
- this._scrollTarget = null;
- // Keep track of original inline style of the container,
- // so it can be restored when container is changed.
- this._containerInlineStyle = null;
- // A sentinel element that sizes the container when
- // it is a scrolling element.
- this._sizer = null;
- // Layout provides these values, we set them on _render().
- this._scrollSize = null;
- this._scrollErr = null;
- this._childrenPos = null;
-
- this._containerSize = null;
- this._containerRO = new ResizeObserver(
- (entries) => this._containerSizeChanged(entries[0].contentRect));
-
- this._skipNextChildrenSizeChanged = false;
- this._childrenRO =
- new ResizeObserver((entries) => this._childrenSizeChanged(entries));
-
- if (config) {
- Object.assign(this, config);
- }
- }
-
- get container() {
- return this._container;
- }
- set container(container) {
- super.container = container;
-
- const oldEl = this._containerElement;
- // Consider document fragments as shadowRoots.
- const newEl =
- (container && container.nodeType === Node.DOCUMENT_FRAGMENT_NODE) ?
- container.host :
- container;
- if (oldEl === newEl) {
- return;
- }
-
- this._containerRO.disconnect();
- this._containerSize = null;
-
- if (oldEl) {
- if (this._containerInlineStyle) {
- oldEl.setAttribute('style', this._containerInlineStyle);
- } else {
- oldEl.removeAttribute('style');
- }
- this._containerInlineStyle = null;
- if (oldEl === this._scrollTarget) {
- oldEl.removeEventListener('scroll', this, {passive: true});
- this._sizer && this._sizer.remove();
- }
- } else {
- // First time container was setup, add listeners only now.
- addEventListener('scroll', this, {passive: true});
- }
-
- this._containerElement = newEl;
-
- if (newEl) {
- this._containerInlineStyle = newEl.getAttribute('style') || null;
- if (newEl === this._scrollTarget) {
- this._sizer = this._sizer || this._createContainerSizer();
- this._container.prepend(this._sizer);
- }
- this._scheduleUpdateView();
- this._containerRO.observe(newEl);
- }
- }
-
- get layout() {
- return this._layout;
- }
- set layout(layout) {
- if (layout === this._layout) {
- return;
- }
-
- if (this._layout) {
- this._measureCallback = null;
- this._layout.removeEventListener('scrollsizechange', this);
- this._layout.removeEventListener('scrollerrorchange', this);
- this._layout.removeEventListener('itempositionchange', this);
- this._layout.removeEventListener('rangechange', this);
- // Reset container size so layout can get correct viewport size.
- if (this._containerElement) {
- this._sizeContainer();
- }
- }
-
- this._layout = layout;
-
- if (this._layout) {
- if (typeof this._layout.updateItemSizes === 'function') {
- this._measureCallback = this._layout.updateItemSizes.bind(this._layout);
- this.requestRemeasure();
- }
- this._layout.addEventListener('scrollsizechange', this);
- this._layout.addEventListener('scrollerrorchange', this);
- this._layout.addEventListener('itempositionchange', this);
- this._layout.addEventListener('rangechange', this);
- this._scheduleUpdateView();
- }
- }
-
- /**
- * The element that generates scroll events and defines the container
- * viewport. The value `null` (default) corresponds to `window` as scroll
- * target.
- * @type {Element|null}
- */
- get scrollTarget() {
- return this._scrollTarget;
- }
- /**
- * @param {Element|null} target
- */
- set scrollTarget(target) {
- // Consider window as null.
- if (target === window) {
- target = null;
- }
- if (this._scrollTarget === target) {
- return;
- }
- if (this._scrollTarget) {
- this._scrollTarget.removeEventListener('scroll', this, {passive: true});
- if (this._sizer && this._scrollTarget === this._containerElement) {
- this._sizer.remove();
- }
- }
-
- this._scrollTarget = target;
-
- if (target) {
- target.addEventListener('scroll', this, {passive: true});
- if (target === this._containerElement) {
- this._sizer = this._sizer || this._createContainerSizer();
- this._container.prepend(this._sizer);
- }
- }
- }
-
- /**
- * @protected
- */
- _render() {
- // console.time(`render ${this._containerElement.localName}#${
- // this._containerElement.id}`);
-
- this._childrenRO.disconnect();
-
- // Update layout properties before rendering to have correct
- // first, num, scroll size, children positions.
- this._layout.totalItems = this.totalItems;
- if (this._needsUpdateView) {
- this._needsUpdateView = false;
- this._updateView();
- }
- this._layout.reflowIfNeeded();
- // Keep rendering until there is no more scheduled renders.
- while (true) {
- if (this._pendingRender) {
- cancelAnimationFrame(this._pendingRender);
- this._pendingRender = null;
- }
- // Update scroll size and correct scroll error before rendering.
- this._sizeContainer(this._scrollSize);
- if (this._scrollErr) {
- // This triggers a 'scroll' event (async) which triggers another
- // _updateView().
- this._correctScrollError(this._scrollErr);
- this._scrollErr = null;
- }
- // Position children (_didRender()), and provide their measures to layout.
- super._render();
- this._layout.reflowIfNeeded();
- // If layout reflow did not provoke another render, we're done.
- if (!this._pendingRender) {
- break;
- }
- }
- // We want to skip the first ResizeObserver callback call as we already
- // measured the children.
- this._skipNextChildrenSizeChanged = true;
- this._kids.forEach(child => this._childrenRO.observe(child));
-
- // console.timeEnd(`render ${this._containerElement.localName}#${
- // this._containerElement.id}`);
- }
-
- /**
- * Position children before they get measured.
- * Measuring will force relayout, so by positioning
- * them first, we reduce computations.
- * @protected
- */
- _didRender() {
- if (this._childrenPos) {
- this._positionChildren(this._childrenPos);
- this._childrenPos = null;
- }
- }
-
- /**
- * @param {!Event} event
- * @private
- */
- handleEvent(event) {
- switch (event.type) {
- case 'scroll':
- if (!this._scrollTarget || event.target === this._scrollTarget) {
- this._scheduleUpdateView();
- }
- break;
- case 'scrollsizechange':
- this._scrollSize = event.detail;
- this._scheduleRender();
- break;
- case 'scrollerrorchange':
- this._scrollErr = event.detail;
- this._scheduleRender();
- break;
- case 'itempositionchange':
- this._childrenPos = event.detail;
- this._scheduleRender();
- break;
- case 'rangechange':
- this._adjustRange(event.detail);
- break;
- default:
- console.warn('event not handled', event);
- }
- }
- /**
- * @return {!Element}
- * @private
- */
- _createContainerSizer() {
- const sizer = document.createElement('div');
- // When the scrollHeight is large, the height
- // of this element might be ignored.
- // Setting content and font-size ensures the element
- // has a size.
- Object.assign(sizer.style, {
- position: 'absolute',
- margin: '-2px 0 0 0',
- padding: 0,
- visibility: 'hidden',
- fontSize: '2px',
- });
- sizer.innerHTML = '&nbsp;';
- return sizer;
- }
-
- // Rename _ordered to _kids?
- /**
- * @protected
- */
- get _kids() {
- return this._ordered;
- }
- /**
- * @private
- */
- _scheduleUpdateView() {
- this._needsUpdateView = true;
- this._scheduleRender();
- }
- /**
- * @private
- */
- _updateView() {
- let width, height, top, left;
- if (this._scrollTarget === this._containerElement) {
- width = this._containerSize.width;
- height = this._containerSize.height;
- left = this._containerElement.scrollLeft;
- top = this._containerElement.scrollTop;
- } else {
- const containerBounds = this._containerElement.getBoundingClientRect();
- const scrollBounds = this._scrollTarget ?
- this._scrollTarget.getBoundingClientRect() :
- {top: 0, left: 0, width: innerWidth, height: innerHeight};
- const scrollerWidth = scrollBounds.width;
- const scrollerHeight = scrollBounds.height;
- const xMin = Math.max(
- 0, Math.min(scrollerWidth, containerBounds.left - scrollBounds.left));
- const yMin = Math.max(
- 0, Math.min(scrollerHeight, containerBounds.top - scrollBounds.top));
- const xMax = this._layout.direction === 'vertical' ?
- Math.max(
- 0,
- Math.min(
- scrollerWidth, containerBounds.right - scrollBounds.left)) :
- scrollerWidth;
- const yMax = this._layout.direction === 'vertical' ?
- scrollerHeight :
- Math.max(
- 0,
- Math.min(
- scrollerHeight, containerBounds.bottom - scrollBounds.top));
- width = xMax - xMin;
- height = yMax - yMin;
- left = Math.max(0, -(containerBounds.x - scrollBounds.left));
- top = Math.max(0, -(containerBounds.y - scrollBounds.top));
- }
- this._layout.viewportSize = {width, height};
- this._layout.viewportScroll = {top, left};
- }
- /**
- * @private
- */
- _sizeContainer(size) {
- if (this._scrollTarget === this._containerElement) {
- const left = size && size.width ? size.width - 1 : 0;
- const top = size && size.height ? size.height - 1 : 0;
- this._sizer.style.transform = `translate(${left}px, ${top}px)`;
- } else {
- const style = this._containerElement.style;
- style.minWidth = size && size.width ? size.width + 'px' : null;
- style.minHeight = size && size.height ? size.height + 'px' : null;
- }
- }
- /**
- * @private
- */
- _positionChildren(pos) {
- const kids = this._kids;
- Object.keys(pos).forEach(key => {
- const idx = key - this._first;
- const child = kids[idx];
- if (child) {
- const {top, left} = pos[key];
- // console.debug(`_positionChild #${this._container.id} >
- // #${child.id}: top ${top}`);
- child.style.position = 'absolute';
- child.style.transform = `translate(${left}px, ${top}px)`;
- }
- });
- }
- /**
- * @private
- */
- _adjustRange(range) {
- this.num = range.num;
- this.first = range.first;
- this._incremental = !(range.stable);
- if (range.remeasure) {
- this.requestRemeasure();
- } else if (range.stable) {
- this._notifyStable();
- }
- }
- /**
- * @protected
- */
- _shouldRender() {
- if (!super._shouldRender() || !this._layout) {
- return false;
- }
- // NOTE: we're about to render, but the ResizeObserver didn't execute yet.
- // Since we want to keep rAF timing, we compute _containerSize now.
- // Would be nice to have a way to flush ResizeObservers
- if (this._containerSize === null) {
- const {width, height} = this._containerElement.getBoundingClientRect();
- this._containerSize = {width, height};
- }
- return this._containerSize.width > 0 || this._containerSize.height > 0;
- }
- /**
- * @private
- */
- _correctScrollError(err) {
- if (this._scrollTarget) {
- this._scrollTarget.scrollTop -= err.top;
- this._scrollTarget.scrollLeft -= err.left;
- } else {
- window.scroll(window.scrollX - err.left, window.scrollY - err.top);
- }
- }
- /**
- * @protected
- */
- _notifyStable() {
- const {first, num} = this;
- const last = first + num - 1;
- this._container.dispatchEvent(
- new RangeChangeEvent('rangechange', {first, last}));
- }
- /**
- * @private
- */
- _containerSizeChanged(size) {
- const {width, height} = size;
- this._containerSize = {width, height};
- // console.debug('container changed size', this._containerSize);
- this._scheduleUpdateView();
- }
- /**
- * @private
- */
- _childrenSizeChanged() {
- if (this._skipNextChildrenSizeChanged) {
- this._skipNextChildrenSizeChanged = false;
- } else {
- this.requestRemeasure();
- }
- }
-};
-
-export const VirtualScroller = RepeatsAndScrolls(class {});
diff --git a/chromium/third_party/blink/renderer/core/script/script.h b/chromium/third_party/blink/renderer/core/script/script.h
index 2e99f96cb9c..d7951dc1f0a 100644
--- a/chromium/third_party/blink/renderer/core/script/script.h
+++ b/chromium/third_party/blink/renderer/core/script/script.h
@@ -21,7 +21,7 @@ class WorkerGlobalScope;
// https://html.spec.whatwg.org/C/#concept-script
class CORE_EXPORT Script : public GarbageCollectedFinalized<Script> {
public:
- virtual void Trace(blink::Visitor* visitor) {}
+ virtual void Trace(Visitor* visitor) {}
virtual ~Script() {}
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 41d5609b5f2..4666d857aed 100644
--- a/chromium/third_party/blink/renderer/core/script/script_loader.cc
+++ b/chromium/third_party/blink/renderer/core/script/script_loader.cc
@@ -33,7 +33,6 @@
#include "third_party/blink/renderer/core/dom/text.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.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/html/imports/html_import.h"
#include "third_party/blink/renderer/core/html/parser/html_parser_idioms.h"
#include "third_party/blink/renderer/core/html_names.h"
@@ -52,7 +51,8 @@
#include "third_party/blink/renderer/core/script/script_runner.h"
#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/instrumentation/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.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"
@@ -71,7 +71,8 @@ ScriptLoader::ScriptLoader(ScriptElementBase* element,
bool already_started)
: element_(element),
will_be_parser_executed_(false),
- will_execute_when_document_finished_parsing_(false) {
+ will_execute_when_document_finished_parsing_(false),
+ force_deferred_(false) {
// <spec href="https://html.spec.whatwg.org/C/#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>
@@ -97,7 +98,7 @@ ScriptLoader::ScriptLoader(ScriptElementBase* element,
ScriptLoader::~ScriptLoader() {}
-void ScriptLoader::Trace(blink::Visitor* visitor) {
+void ScriptLoader::Trace(Visitor* visitor) {
visitor->Trace(element_);
visitor->Trace(pending_script_);
visitor->Trace(prepared_pending_script_);
@@ -279,17 +280,17 @@ bool ScriptLoader::BlockForNoModule(mojom::ScriptType script_type,
// https://html.spec.whatwg.org/C/#prepare-a-script
// - Step 6 of obtaining a preloaded module script
// https://html.spec.whatwg.org/C/#link-type-modulepreload.
-network::mojom::FetchCredentialsMode ScriptLoader::ModuleScriptCredentialsMode(
+network::mojom::CredentialsMode ScriptLoader::ModuleScriptCredentialsMode(
CrossOriginAttributeValue cross_origin) {
switch (cross_origin) {
case kCrossOriginAttributeNotSet:
case kCrossOriginAttributeAnonymous:
- return network::mojom::FetchCredentialsMode::kSameOrigin;
+ return network::mojom::CredentialsMode::kSameOrigin;
case kCrossOriginAttributeUseCredentials:
- return network::mojom::FetchCredentialsMode::kInclude;
+ return network::mojom::CredentialsMode::kInclude;
}
NOTREACHED();
- return network::mojom::FetchCredentialsMode::kOmit;
+ return network::mojom::CredentialsMode::kOmit;
}
// https://github.com/WICG/feature-policy/issues/135
@@ -449,7 +450,7 @@ bool ScriptLoader::PrepareScript(const TextPosition& script_start_position,
// <spec step="17">Let module script credentials mode be the module script
// credentials mode for the element's crossorigin content attribute.</spec>
- network::mojom::FetchCredentialsMode credentials_mode =
+ network::mojom::CredentialsMode credentials_mode =
ModuleScriptCredentialsMode(cross_origin);
// <spec step="18">Let cryptographic nonce be the element's
@@ -583,7 +584,7 @@ bool ScriptLoader::PrepareScript(const TextPosition& script_start_position,
// <spec step="24.6.B">"module"
//
- // Fetch a module script graph given url, settings object, "script", and
+ // Fetch an external module script graph given url, settings object, and
// options.</spec>
Modulator* modulator = Modulator::From(
ToScriptStateForMainWorld(context_document->GetFrame()));
@@ -623,7 +624,7 @@ bool ScriptLoader::PrepareScript(const TextPosition& script_start_position,
// <spec step="25.2">Switch on the script's type:</spec>
switch (GetScriptType()) {
- // <spec step="25.2.A">"classic"</spec>
+ // <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
@@ -650,28 +651,38 @@ bool ScriptLoader::PrepareScript(const TextPosition& script_start_position,
break;
}
- // <spec step="25.2.B">"module"</spec>
+ // <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>
+ // <spec step="25.2.B.1">Fetch an inline module script graph, given
+ // source text, base URL, settings object, and options. When this
+ // asynchronously completes, set the script's script to the result. At
+ // that time, the script is ready.</spec>
+ //
+ // <specdef label="fetch-an-inline-module-script-graph"
+ // href="https://html.spec.whatwg.org/C/#fetch-an-inline-module-script-graph">
const KURL& source_url = element_document.Url();
Modulator* modulator = Modulator::From(
ToScriptStateForMainWorld(context_document->GetFrame()));
+
+ // <spec label="fetch-an-inline-module-script-graph" step="1">Let script
+ // be the result of creating a JavaScript module script using source
+ // text, settings object, base URL, and options.</spec>
ModuleScript* module_script = JSModuleScript::Create(
ParkableString(element_->TextFromChildren().Impl()), nullptr,
ScriptSourceLocationType::kInline, modulator, 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>
+ // <spec label="fetch-an-inline-module-script-graph" step="2">If script
+ // is null, asynchronously complete this algorithm with null, and abort
+ // these steps.</spec>
if (!module_script)
return false;
- // <spec step="25.2.B.3">Fetch the descendants of and instantiate
- // 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>
+ // <spec label="fetch-an-inline-module-script-graph" step="4">Fetch the
+ // descendants of and instantiate script, given settings object, the
+ // destination "script", and visited set. When this asynchronously
+ // completes with final result, asynchronously complete this algorithm
+ // with final result.</spec>
auto* module_tree_client =
MakeGarbageCollected<ModulePendingScriptTreeClient>();
modulator->FetchDescendantsForInlineScript(
@@ -718,6 +729,25 @@ bool ScriptLoader::PrepareScript(const TextPosition& script_start_position,
return true;
}
+ // Check for external script that should be force deferred.
+ if (GetScriptType() == mojom::ScriptType::kClassic &&
+ element_->HasSourceAttribute() &&
+ context_document->GetFrame()->ShouldForceDeferScript() &&
+ context_document->IsHTMLDocument() && parser_inserted_ &&
+ !element_->AsyncAttributeValue()) {
+ // In terms of ScriptLoader flags, force deferred scripts behave like
+ // parser-blocking scripts, except that |force_deferred_| is set.
+ // The caller of PrepareScript()
+ // - Force-defers such scripts if the caller supports force-defer
+ // (i.e., HTMLParserScriptRunner); or
+ // - Ignores the |force_deferred_| flag and handles such scripts as
+ // parser-blocking scripts (e.g., XMLParserScriptRunner).
+ force_deferred_ = true;
+ will_be_parser_executed_ = true;
+
+ return true;
+ }
+
// <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>
@@ -793,6 +823,14 @@ bool ScriptLoader::PrepareScript(const TextPosition& script_start_position,
DCHECK_EQ(GetScriptType(), mojom::ScriptType::kClassic);
DCHECK(!is_external_script_);
+ // Check for inline script that should be force deferred.
+ if (context_document->GetFrame()->ShouldForceDeferScript() &&
+ context_document->IsHTMLDocument() && parser_inserted_) {
+ force_deferred_ = true;
+ will_be_parser_executed_ = true;
+ return true;
+ }
+
// <spec step="26.E">If the element does not have a src attribute, and the
// element has been flagged as "parser-inserted", and either the parser that
// created the script is an XML parser or it's an HTML parser whose script
@@ -861,7 +899,7 @@ void ScriptLoader::FetchModuleScriptTree(
const ScriptFetchOptions& options) {
// <spec step="24.6.B">"module"
//
- // Fetch a module script graph given url, settings object, "script", and
+ // Fetch an external module script graph given url, settings object, and
// options.</spec>
auto* module_tree_client =
MakeGarbageCollected<ModulePendingScriptTreeClient>();
@@ -880,23 +918,6 @@ PendingScript* ScriptLoader::TakePendingScript(
EnumerationHistogram, scheduling_type_histogram,
("Blink.Script.SchedulingType", kLastScriptSchedulingType + 1));
scheduling_type_histogram.Count(static_cast<int>(scheduling_type));
-
- switch (scheduling_type) {
- case ScriptSchedulingType::kAsync:
- case ScriptSchedulingType::kInOrder:
- // As ClassicPendingScript keeps a reference to ScriptResource,
- // the ScriptResource is anyway kept alive until evaluation,
- // and can be garbage-collected after that (together with
- // ClassicPendingScript).
- resource_keep_alive_ = nullptr;
- break;
-
- default:
- // ScriptResource is kept alive by resource_keep_alive_
- // until ScriptLoader is garbage collected.
- break;
- }
-
PendingScript* pending_script = prepared_pending_script_;
prepared_pending_script_ = nullptr;
pending_script->SetSchedulingType(scheduling_type);
@@ -908,6 +929,19 @@ void ScriptLoader::PendingScriptFinished(PendingScript* pending_script) {
DCHECK_EQ(pending_script_, pending_script);
DCHECK_EQ(pending_script_->GetScriptType(), GetScriptType());
DCHECK(pending_script->IsControlledByScriptRunner());
+ DCHECK(pending_script_->GetSchedulingType() == ScriptSchedulingType::kAsync ||
+ pending_script_->GetSchedulingType() ==
+ ScriptSchedulingType::kInOrder);
+ // Historically we clear |resource_keep_alive_| when the scheduling type is
+ // kAsync or kInOrder (crbug.com/778799). But if the script resource was
+ // served via signed exchange, the script may not be in the HTTPCache,
+ // therefore will need to be refetched over network if it's evicted from the
+ // memory cache not be in the HTTPCache. So we keep |resource_keep_alive_| to
+ // keep the resource in the memory cache.
+ if (resource_keep_alive_ &&
+ !resource_keep_alive_->GetResponse().IsSignedExchangeInnerResponse()) {
+ resource_keep_alive_ = nullptr;
+ }
Document* context_document = element_->GetDocument().ContextDocument();
if (!context_document) {
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 ae9e7b85a7a..0ac49da3bc0 100644
--- a/chromium/third_party/blink/renderer/core/script/script_loader.h
+++ b/chromium/third_party/blink/renderer/core/script/script_loader.h
@@ -56,7 +56,7 @@ class CORE_EXPORT ScriptLoader final
public:
ScriptLoader(ScriptElementBase*, bool created_by_parser, bool is_evaluated);
~ScriptLoader() override;
- void Trace(blink::Visitor*) override;
+ void Trace(Visitor*) override;
const char* NameInHeapSnapshot() const override { return "ScriptLoader"; }
enum LegacyTypeSupport {
@@ -78,7 +78,7 @@ class CORE_EXPORT ScriptLoader final
static bool BlockForNoModule(mojom::ScriptType, bool nomodule);
- static network::mojom::FetchCredentialsMode ModuleScriptCredentialsMode(
+ static network::mojom::CredentialsMode ModuleScriptCredentialsMode(
CrossOriginAttributeValue);
// https://html.spec.whatwg.org/C/#prepare-a-script
@@ -96,6 +96,7 @@ class CORE_EXPORT ScriptLoader final
bool WillExecuteWhenDocumentFinishedParsing() const {
return will_execute_when_document_finished_parsing_;
}
+ bool IsForceDeferred() const { return force_deferred_; }
bool IsParserInserted() const { return parser_inserted_; }
bool AlreadyStarted() const { return already_started_; }
bool IsNonBlocking() const { return non_blocking_; }
@@ -145,33 +146,27 @@ class CORE_EXPORT ScriptLoader final
// https://html.spec.whatwg.org/C/#script-processing-model
// "A script element has several associated pieces of state.":
- // <spec
- // href="https://html.spec.whatwg.org/C/#already-started">
- // ... Initially, script elements must have this flag unset ...</spec>
+ // <spec href="https://html.spec.whatwg.org/C/#already-started">... Initially,
+ // script elements must have this flag unset ...</spec>
bool already_started_ = false;
- // <spec
- // href="https://html.spec.whatwg.org/C/#parser-inserted">
- // ... Initially, script elements must have this flag unset. ...</spec>
+ // <spec href="https://html.spec.whatwg.org/C/#parser-inserted">... Initially,
+ // script elements must have this flag unset. ...</spec>
bool parser_inserted_ = false;
- // <spec
- // href="https://html.spec.whatwg.org/C/#non-blocking">
- // ... Initially, script elements must have this flag set. ...</spec>
+ // <spec href="https://html.spec.whatwg.org/C/#non-blocking">... Initially,
+ // script elements must have this flag set. ...</spec>
bool non_blocking_ = true;
- // <spec
- // href="https://html.spec.whatwg.org/C/#ready-to-be-parser-executed">
+ // <spec href="https://html.spec.whatwg.org/C/#ready-to-be-parser-executed">
// ... Initially, script elements must have this flag unset ...</spec>
bool ready_to_be_parser_executed_ = false;
- // <spec
- // href="https://html.spec.whatwg.org/C/#concept-script-type">
- // ... It is determined when the script is prepared, ...</spec>
+ // <spec href="https://html.spec.whatwg.org/C/#concept-script-type">... It is
+ // determined when the script is prepared, ...</spec>
mojom::ScriptType script_type_ = mojom::ScriptType::kClassic;
- // <spec
- // href="https://html.spec.whatwg.org/C/#concept-script-external">
+ // <spec href="https://html.spec.whatwg.org/C/#concept-script-external">
// ... It is determined when the script is prepared, ...</spec>
bool is_external_script_ = false;
@@ -180,6 +175,9 @@ class CORE_EXPORT ScriptLoader final
bool will_execute_when_document_finished_parsing_;
+ // The script will be force deferred (https://crbug.com/976061).
+ bool force_deferred_;
+
// A PendingScript is first created in PrepareScript() and stored in
// |prepared_pending_script_|.
// Later, TakePendingScript() is called, and its caller holds a reference
diff --git a/chromium/third_party/blink/renderer/core/script/script_runner.cc b/chromium/third_party/blink/renderer/core/script/script_runner.cc
index 6e76a6417ec..c3e12f4ab8f 100644
--- a/chromium/third_party/blink/renderer/core/script/script_runner.cc
+++ b/chromium/third_party/blink/renderer/core/script/script_runner.cc
@@ -256,7 +256,7 @@ void ScriptRunner::ExecuteTask() {
#endif
}
-void ScriptRunner::Trace(blink::Visitor* visitor) {
+void ScriptRunner::Trace(Visitor* visitor) {
visitor->Trace(document_);
visitor->Trace(pending_in_order_scripts_);
visitor->Trace(pending_async_scripts_);
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 54ad3d801f9..75b69989ca9 100644
--- a/chromium/third_party/blink/renderer/core/script/script_runner.h
+++ b/chromium/third_party/blink/renderer/core/script/script_runner.h
@@ -58,7 +58,7 @@ class CORE_EXPORT ScriptRunner final
static void MovePendingScript(Document&, Document&, ScriptLoader*);
- void Trace(blink::Visitor*);
+ void Trace(Visitor*);
const char* NameInHeapSnapshot() const override { return "ScriptRunner"; }
private:
diff --git a/chromium/third_party/blink/renderer/core/script/script_scheduling_type.h b/chromium/third_party/blink/renderer/core/script/script_scheduling_type.h
index 928143ec895..744f0af5e93 100644
--- a/chromium/third_party/blink/renderer/core/script/script_scheduling_type.h
+++ b/chromium/third_party/blink/renderer/core/script/script_scheduling_type.h
@@ -62,7 +62,14 @@ enum class ScriptSchedulingType {
kAsync,
// Inline <script> executed immediately within prepare-a-script.
- kImmediate
+ kImmediate,
+
+ // Force deferred scripts controlled by HTMLParserScriptRunner.
+ // These are otherwise parser-blocking scripts that are being forced to
+ // execute after parsing completes (due to a ForceDeferScriptIntervention).
+ //
+ // Spec: not yet spec'ed. https://crbug.com/976061
+ kForceDefer
};
static const int kLastScriptSchedulingType =
diff --git a/chromium/third_party/blink/renderer/core/script/value_wrapper_synthetic_module_script.cc b/chromium/third_party/blink/renderer/core/script/value_wrapper_synthetic_module_script.cc
new file mode 100644
index 00000000000..8ee3c96acf6
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/script/value_wrapper_synthetic_module_script.cc
@@ -0,0 +1,153 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/script/value_wrapper_synthetic_module_script.h"
+
+#include "third_party/blink/public/platform/web_vector.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
+#include "third_party/blink/renderer/core/loader/modulescript/module_script_creation_params.h"
+#include "third_party/blink/renderer/core/script/modulator.h"
+#include "third_party/blink/renderer/core/script/module_record_resolver.h"
+#include "third_party/blink/renderer/platform/weborigin/kurl.h"
+#include "third_party/blink/renderer/platform/wtf/text/text_position.h"
+#include "v8/include/v8.h"
+
+namespace blink {
+
+ValueWrapperSyntheticModuleScript*
+ValueWrapperSyntheticModuleScript::CreateJSONWrapperSyntheticModuleScript(
+ const base::Optional<ModuleScriptCreationParams>& params,
+ Modulator* settings_object,
+ const ScriptFetchOptions options_) {
+ DCHECK(settings_object->HasValidContext());
+ ScriptState::Scope scope(settings_object->GetScriptState());
+ v8::Local<v8::Context> context =
+ settings_object->GetScriptState()->GetContext();
+ v8::Isolate* isolate = context->GetIsolate();
+ v8::TryCatch try_catch(isolate);
+ v8::Local<v8::String> original_json =
+ V8String(isolate, params->GetSourceText().ToString());
+ v8::Local<v8::Value> parsed_json;
+ ExceptionState exception_state(isolate, ExceptionState::kExecutionContext,
+ "ModuleScriptLoader",
+ "CreateJSONWrapperSyntheticModuleScript");
+ // Step 1. "Let script be a new module script that this algorithm will
+ // subsequently initialize."
+ // [spec text]
+ // Step 2. "Set script's settings object to settings."
+ // [spec text]
+ // Step 3. "Set script's base URL and fetch options to null."
+ // [spec text]
+ // Step 4. "Set script's parse error and error to rethrow to null."
+ // [spec text]
+ // Step 5. "Let json be ? Call(%JSONParse%, undefined, « source »).
+ // If this throws an exception, set script's parse error to that exception,
+ // and return script."
+ // [spec text]
+ if (!v8::JSON::Parse(context, original_json).ToLocal(&parsed_json)) {
+ DCHECK(try_catch.HasCaught());
+ exception_state.RethrowV8Exception(try_catch.Exception());
+ v8::Local<v8::Value> error = exception_state.GetException();
+ exception_state.ClearException();
+ return ValueWrapperSyntheticModuleScript::CreateWithError(
+ parsed_json, settings_object, params->GetResponseUrl(),
+ params->GetResponseUrl(), options_, error);
+ } else {
+ return ValueWrapperSyntheticModuleScript::CreateWithDefaultExport(
+ parsed_json, settings_object, params->GetResponseUrl(),
+ params->GetResponseUrl(), options_);
+ }
+}
+
+ValueWrapperSyntheticModuleScript*
+ValueWrapperSyntheticModuleScript::CreateWithDefaultExport(
+ v8::Local<v8::Value> value,
+ Modulator* settings_object,
+ const KURL& source_url,
+ const KURL& base_url,
+ const ScriptFetchOptions& fetch_options,
+ const TextPosition& start_position) {
+ v8::Isolate* isolate = settings_object->GetScriptState()->GetIsolate();
+ std::vector<v8::Local<v8::String>> export_names{V8String(isolate, "default")};
+ v8::Local<v8::Module> v8_synthetic_module = v8::Module::CreateSyntheticModule(
+ isolate, V8String(isolate, source_url.GetString()), export_names,
+ ValueWrapperSyntheticModuleScript::EvaluationSteps);
+ // Step 6. "Set script's record to the result of creating a synthetic module
+ // record with a default export of json with settings."
+ // [spec text]
+ ModuleRecord record = ModuleRecord(isolate, v8_synthetic_module, source_url);
+
+ ValueWrapperSyntheticModuleScript* value_wrapper_module_script =
+ MakeGarbageCollected<ValueWrapperSyntheticModuleScript>(
+ settings_object, record, source_url, base_url, fetch_options, value,
+ start_position);
+ settings_object->GetModuleRecordResolver()->RegisterModuleScript(
+ value_wrapper_module_script);
+ // Step 7. "Return script."
+ // [spec text]
+ return value_wrapper_module_script;
+}
+
+ValueWrapperSyntheticModuleScript*
+ValueWrapperSyntheticModuleScript::CreateWithError(
+ v8::Local<v8::Value> value,
+ Modulator* settings_object,
+ const KURL& source_url,
+ const KURL& base_url,
+ const ScriptFetchOptions& fetch_options,
+ v8::Local<v8::Value> error,
+ const TextPosition& start_position) {
+ ValueWrapperSyntheticModuleScript* value_wrapper_module_script =
+ MakeGarbageCollected<ValueWrapperSyntheticModuleScript>(
+ settings_object, ModuleRecord(), source_url, base_url, fetch_options,
+ value, start_position);
+ settings_object->GetModuleRecordResolver()->RegisterModuleScript(
+ value_wrapper_module_script);
+ value_wrapper_module_script->SetParseErrorAndClearRecord(
+ ScriptValue(settings_object->GetScriptState(), error));
+ // Step 7. "Return script."
+ // [spec text]
+ return value_wrapper_module_script;
+}
+
+ValueWrapperSyntheticModuleScript::ValueWrapperSyntheticModuleScript(
+ Modulator* settings_object,
+ ModuleRecord record,
+ const KURL& source_url,
+ const KURL& base_url,
+ const ScriptFetchOptions& fetch_options,
+ v8::Local<v8::Value> value,
+ const TextPosition& start_position)
+ : ModuleScript(settings_object,
+ record,
+ source_url,
+ base_url,
+ fetch_options),
+ export_value_(v8::Isolate::GetCurrent(), value) {}
+
+// TODO(sasebree) Implement this method
+v8::MaybeLocal<v8::Value> ValueWrapperSyntheticModuleScript::EvaluationSteps(
+ v8::Local<v8::Context> context,
+ v8::Local<v8::Module> module) {
+ NOTREACHED();
+ return v8::MaybeLocal<v8::Value>();
+}
+
+String ValueWrapperSyntheticModuleScript::InlineSourceTextForCSP() const {
+ // We don't construct a ValueWrapperSyntheticModuleScript with the original
+ // source, but instead construct it from the originally parsed
+ // text. If a need arises for the original module source to be used later,
+ // ValueWrapperSyntheticModuleScript will need to be modified such that its
+ // constructor takes this source text as an additional parameter and stashes
+ // it on the ValueWrapperSyntheticModuleScript.
+ NOTREACHED();
+ return "";
+}
+
+void ValueWrapperSyntheticModuleScript::Trace(Visitor* visitor) {
+ visitor->Trace(export_value_);
+ ModuleScript::Trace(visitor);
+}
+
+} // namespace blink \ No newline at end of file
diff --git a/chromium/third_party/blink/renderer/core/script/value_wrapper_synthetic_module_script.h b/chromium/third_party/blink/renderer/core/script/value_wrapper_synthetic_module_script.h
new file mode 100644
index 00000000000..ae19c095cd9
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/script/value_wrapper_synthetic_module_script.h
@@ -0,0 +1,78 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_SCRIPT_VALUE_WRAPPER_SYNTHETIC_MODULE_SCRIPT_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_SCRIPT_VALUE_WRAPPER_SYNTHETIC_MODULE_SCRIPT_H_
+
+#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/script/module_script.h"
+
+namespace WTF {
+class TextPosition;
+} // namespace WTF
+
+namespace blink {
+
+class KURL;
+class Modulator;
+class ModuleScriptCreationParams;
+
+// ValueWrapperSyntheticModuleScript is a module script
+// (https://html.spec.whatwg.org/C/#module-script) that default-exports a single
+// v8::Value, for example JSON Module Script:
+// https://html.spec.whatwg.org/multipage/webappapis.html#json-module-script
+class CORE_EXPORT ValueWrapperSyntheticModuleScript final
+ : public ModuleScript {
+ public:
+ static ValueWrapperSyntheticModuleScript*
+ CreateJSONWrapperSyntheticModuleScript(
+ const base::Optional<ModuleScriptCreationParams>& params,
+ Modulator* settings_object,
+ const ScriptFetchOptions options_);
+
+ static ValueWrapperSyntheticModuleScript* CreateWithDefaultExport(
+ v8::Local<v8::Value> value,
+ Modulator* settings_object,
+ const KURL& source_url,
+ const KURL& base_url,
+ const ScriptFetchOptions& fetch_options,
+ const TextPosition& start_position = TextPosition::MinimumPosition());
+
+ static ValueWrapperSyntheticModuleScript* CreateWithError(
+ v8::Local<v8::Value> value,
+ Modulator* settings_object,
+ const KURL& source_url,
+ const KURL& base_url,
+ const ScriptFetchOptions& fetch_options,
+ v8::Local<v8::Value> error,
+ const TextPosition& start_position = TextPosition::MinimumPosition());
+
+ ValueWrapperSyntheticModuleScript(Modulator* settings_object,
+ ModuleRecord record,
+ const KURL& source_url,
+ const KURL& base_url,
+ const ScriptFetchOptions& fetch_options,
+ v8::Local<v8::Value> value,
+ const TextPosition& start_position);
+
+ // <specdef
+ // href="https://heycam.github.io/webidl/#synthetic-module-record">
+ // An abstract operation that will be performed upon evaluation of the module,
+ // taking the Synthetic Module Record as its sole argument. These will usually
+ // set up the exported values, by using SetSyntheticModuleExport. They must
+ // not modify [[ExportNames]]. They may return an abrupt completion.
+ static v8::MaybeLocal<v8::Value> EvaluationSteps(
+ v8::Local<v8::Context> context,
+ v8::Local<v8::Module> module);
+
+ String InlineSourceTextForCSP() const override;
+ void Trace(blink::Visitor* visitor) override;
+
+ private:
+ TraceWrapperV8Reference<v8::Value> export_value_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_SCRIPT_VALUE_WRAPPER_SYNTHETIC_MODULE_SCRIPT_H_ \ No newline at end of file
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 0e0142ad9a7..e9f8feb54da 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
@@ -9,7 +9,7 @@
#include "third_party/blink/renderer/core/scroll/scroll_animator_compositor_coordinator.h"
#include "third_party/blink/renderer/core/scroll/scrollable_area.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/scroll/scroll_alignment.cc b/chromium/third_party/blink/renderer/core/scroll/scroll_alignment.cc
index cc195a28051..504efa93d0c 100644
--- a/chromium/third_party/blink/renderer/core/scroll/scroll_alignment.cc
+++ b/chromium/third_party/blink/renderer/core/scroll/scroll_alignment.cc
@@ -43,7 +43,7 @@
#include "third_party/blink/renderer/core/scroll/scroll_alignment.h"
-#include "third_party/blink/renderer/platform/geometry/layout_rect.h"
+#include "third_party/blink/renderer/core/layout/geometry/physical_rect.h"
namespace blink {
@@ -67,13 +67,13 @@ const ScrollAlignment ScrollAlignment::kAlignRightAlways = {
#define MIN_INTERSECT_FOR_REVEAL 32
ScrollOffset ScrollAlignment::GetScrollOffsetToExpose(
- const LayoutRect& scroll_snapport_rect,
- const LayoutRect& expose_rect,
+ const PhysicalRect& scroll_snapport_rect,
+ const PhysicalRect& expose_rect,
const ScrollAlignment& align_x,
const ScrollAlignment& align_y,
const ScrollOffset& current_scroll_offset) {
// Prevent degenerate cases by giving the visible rect a minimum non-0 size.
- LayoutRect non_zero_visible_rect(scroll_snapport_rect);
+ PhysicalRect non_zero_visible_rect = scroll_snapport_rect;
LayoutUnit minimum_layout_unit;
minimum_layout_unit.SetRawValue(1);
if (non_zero_visible_rect.Width() == LayoutUnit())
@@ -83,8 +83,9 @@ ScrollOffset ScrollAlignment::GetScrollOffsetToExpose(
// Determine the appropriate X behavior.
ScrollAlignmentBehavior scroll_x;
- LayoutRect expose_rect_x(expose_rect.X(), non_zero_visible_rect.Y(),
- expose_rect.Width(), non_zero_visible_rect.Height());
+ PhysicalRect expose_rect_x(expose_rect.X(), non_zero_visible_rect.Y(),
+ expose_rect.Width(),
+ non_zero_visible_rect.Height());
LayoutUnit intersect_width =
Intersection(non_zero_visible_rect, expose_rect_x).Width();
if (intersect_width == expose_rect.Width() ||
@@ -111,9 +112,9 @@ ScrollOffset ScrollAlignment::GetScrollOffsetToExpose(
// Closest edge is the right in two cases:
// (1) exposeRect to the right of and smaller than nonZeroVisibleRect
// (2) exposeRect to the left of and larger than nonZeroVisibleRect
- if ((expose_rect.MaxX() > non_zero_visible_rect.MaxX() &&
+ if ((expose_rect.Right() > non_zero_visible_rect.Right() &&
expose_rect.Width() < non_zero_visible_rect.Width()) ||
- (expose_rect.MaxX() < non_zero_visible_rect.MaxX() &&
+ (expose_rect.Right() < non_zero_visible_rect.Right() &&
expose_rect.Width() > non_zero_visible_rect.Width())) {
scroll_x = kScrollAlignmentRight;
}
@@ -121,8 +122,9 @@ ScrollOffset ScrollAlignment::GetScrollOffsetToExpose(
// Determine the appropriate Y behavior.
ScrollAlignmentBehavior scroll_y;
- LayoutRect expose_rect_y(non_zero_visible_rect.X(), expose_rect.Y(),
- non_zero_visible_rect.Width(), expose_rect.Height());
+ PhysicalRect expose_rect_y(non_zero_visible_rect.X(), expose_rect.Y(),
+ non_zero_visible_rect.Width(),
+ expose_rect.Height());
LayoutUnit intersect_height =
Intersection(non_zero_visible_rect, expose_rect_y).Height();
if (intersect_height == expose_rect.Height()) {
@@ -145,9 +147,9 @@ ScrollOffset ScrollAlignment::GetScrollOffsetToExpose(
// Closest edge is the bottom in two cases:
// (1) exposeRect below and smaller than nonZeroVisibleRect
// (2) exposeRect above and larger than nonZeroVisibleRect
- if ((expose_rect.MaxY() > non_zero_visible_rect.MaxY() &&
+ if ((expose_rect.Bottom() > non_zero_visible_rect.Bottom() &&
expose_rect.Height() < non_zero_visible_rect.Height()) ||
- (expose_rect.MaxY() < non_zero_visible_rect.MaxY() &&
+ (expose_rect.Bottom() < non_zero_visible_rect.Bottom() &&
expose_rect.Height() > non_zero_visible_rect.Height())) {
scroll_y = kScrollAlignmentBottom;
}
@@ -155,17 +157,18 @@ ScrollOffset ScrollAlignment::GetScrollOffsetToExpose(
// We would like calculate the ScrollPosition to move |expose_rect| inside
// the scroll_snapport, which is based on the scroll_origin of the scroller.
- non_zero_visible_rect.Move(LayoutSize(-current_scroll_offset));
+ non_zero_visible_rect.Move(
+ -PhysicalOffset::FromFloatSizeRound(current_scroll_offset));
// Given the X behavior, compute the X coordinate.
float x;
if (scroll_x == kScrollAlignmentNoScroll) {
x = current_scroll_offset.Width();
} else if (scroll_x == kScrollAlignmentRight) {
- x = (expose_rect.MaxX() - non_zero_visible_rect.MaxX()).ToFloat();
+ x = (expose_rect.Right() - non_zero_visible_rect.Right()).ToFloat();
} else if (scroll_x == kScrollAlignmentCenter) {
- x = ((expose_rect.X() + expose_rect.MaxX() -
- (non_zero_visible_rect.X() + non_zero_visible_rect.MaxX())) /
+ x = ((expose_rect.X() + expose_rect.Right() -
+ (non_zero_visible_rect.X() + non_zero_visible_rect.Right())) /
2)
.ToFloat();
} else {
@@ -177,10 +180,10 @@ ScrollOffset ScrollAlignment::GetScrollOffsetToExpose(
if (scroll_y == kScrollAlignmentNoScroll) {
y = current_scroll_offset.Height();
} else if (scroll_y == kScrollAlignmentBottom) {
- y = (expose_rect.MaxY() - non_zero_visible_rect.MaxY()).ToFloat();
+ y = (expose_rect.Bottom() - non_zero_visible_rect.Bottom()).ToFloat();
} else if (scroll_y == kScrollAlignmentCenter) {
- y = ((expose_rect.Y() + expose_rect.MaxY() -
- (non_zero_visible_rect.Y() + non_zero_visible_rect.MaxY())) /
+ y = ((expose_rect.Y() + expose_rect.Bottom() -
+ (non_zero_visible_rect.Y() + non_zero_visible_rect.Bottom())) /
2)
.ToFloat();
} else {
diff --git a/chromium/third_party/blink/renderer/core/scroll/scroll_alignment.h b/chromium/third_party/blink/renderer/core/scroll/scroll_alignment.h
index cd9196a1be6..1e9ab6f42ce 100644
--- a/chromium/third_party/blink/renderer/core/scroll/scroll_alignment.h
+++ b/chromium/third_party/blink/renderer/core/scroll/scroll_alignment.h
@@ -46,7 +46,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/scroll/scroll_types.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -60,7 +60,7 @@ enum ScrollAlignmentBehavior {
kScrollAlignmentClosestEdge
};
-class LayoutRect;
+struct PhysicalRect;
struct CORE_EXPORT ScrollAlignment {
STACK_ALLOCATED();
@@ -86,8 +86,8 @@ struct CORE_EXPORT ScrollAlignment {
// visible rect contracted by its scroll-padding.
// FIXME: This function should probably go somewhere else but where?
static ScrollOffset GetScrollOffsetToExpose(
- const LayoutRect& visible_scroll_snapport_rect,
- const LayoutRect& expose_rect,
+ const PhysicalRect& visible_scroll_snapport_rect,
+ const PhysicalRect& expose_rect,
const ScrollAlignment& align_x,
const ScrollAlignment& align_y,
const ScrollOffset& current_scroll_offset);
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 0d0770965e8..4f3344e236d 100644
--- a/chromium/third_party/blink/renderer/core/scroll/scroll_animator.cc
+++ b/chromium/third_party/blink/renderer/core/scroll/scroll_animator.cc
@@ -61,12 +61,15 @@ ScrollAnimatorBase* ScrollAnimatorBase::Create(
}
ScrollAnimator::ScrollAnimator(ScrollableArea* scrollable_area,
- WTF::TimeFunction time_function)
+ const base::TickClock* tick_clock)
: ScrollAnimatorBase(scrollable_area),
- time_function_(time_function),
+ tick_clock_(tick_clock),
last_granularity_(ScrollGranularity::kScrollByPixel) {}
-ScrollAnimator::~ScrollAnimator() = default;
+ScrollAnimator::~ScrollAnimator() {
+ if (on_finish_)
+ std::move(on_finish_).Run();
+}
ScrollOffset ScrollAnimator::DesiredTargetOffset() const {
if (run_state_ == RunState::kWaitingToCancelOnCompositor)
@@ -94,23 +97,33 @@ void ScrollAnimator::ResetAnimationState() {
ScrollAnimatorCompositorCoordinator::ResetAnimationState();
if (animation_curve_)
animation_curve_.reset();
- start_time_ = 0.0;
+ start_time_ = base::TimeTicks();
+ if (on_finish_)
+ std::move(on_finish_).Run();
}
-ScrollResult ScrollAnimator::UserScroll(ScrollGranularity granularity,
- const ScrollOffset& delta) {
- if (!scrollable_area_->ScrollAnimatorEnabled())
- return ScrollAnimatorBase::UserScroll(granularity, delta);
+ScrollResult ScrollAnimator::UserScroll(
+ ScrollGranularity granularity,
+ const ScrollOffset& delta,
+ ScrollableArea::ScrollCallback on_finish) {
+ // We only store on_finish_ when running an animation, and it should be
+ // invoked as soon as the animation is finished. If we don't animate the
+ // scroll, the callback is invoked immediately without being stored.
+ DCHECK(HasRunningAnimation() || on_finish_.is_null());
- TRACE_EVENT0("blink", "ScrollAnimator::scroll");
+ base::ScopedClosureRunner run_on_return(std::move(on_finish));
- if (granularity == ScrollGranularity::kScrollByPrecisePixel) {
+ if (!scrollable_area_->ScrollAnimatorEnabled() ||
+ granularity == ScrollGranularity::kScrollByPrecisePixel) {
// Cancel scroll animation because asked to instant scroll.
if (HasRunningAnimation())
CancelAnimation();
- return ScrollAnimatorBase::UserScroll(granularity, delta);
+ return ScrollAnimatorBase::UserScroll(granularity, delta,
+ run_on_return.Release());
}
+ TRACE_EVENT0("blink", "ScrollAnimator::scroll");
+
bool needs_post_animation_cleanup =
run_state_ == RunState::kPostAnimationCleanup;
if (run_state_ == RunState::kPostAnimationCleanup)
@@ -122,6 +135,9 @@ ScrollResult ScrollAnimator::UserScroll(ScrollGranularity granularity,
if (WillAnimateToOffset(target_offset)) {
last_granularity_ = granularity;
+ if (on_finish_)
+ std::move(on_finish_).Run();
+ on_finish_ = run_on_return.Release();
// Report unused delta only if there is no animation running. See
// comment below regarding scroll latching.
// TODO(bokan): Need to standardize how ScrollAnimators report
@@ -138,6 +154,8 @@ ScrollResult ScrollAnimator::UserScroll(ScrollGranularity granularity,
// Report unused delta only if there is no animation and we are not
// starting one. This ensures we latch for the duration of the
// animation rather than animating multiple scrollers at the same time.
+ if (on_finish_)
+ std::move(on_finish_).Run();
return ScrollResult(false, false, delta.Width(), delta.Height());
}
@@ -169,7 +187,7 @@ bool ScrollAnimator::WillAnimateToOffset(const ScrollOffset& target_offset) {
// of sending to the compositor.
if (run_state_ == RunState::kRunningOnMainThread) {
animation_curve_->UpdateTarget(
- TimeDelta::FromSecondsD(time_function_() - start_time_),
+ tick_clock_->NowTicks() - start_time_,
CompositorOffsetFromBlinkOffset(target_offset));
// Schedule an animation for this scrollable area even though we are
@@ -193,7 +211,7 @@ bool ScrollAnimator::WillAnimateToOffset(const ScrollOffset& target_offset) {
return false;
target_offset_ = target_offset;
- start_time_ = time_function_();
+ start_time_ = tick_clock_->NowTicks();
if (RegisterAndScheduleAnimation())
run_state_ = RunState::kWaitingToSendToCompositor;
@@ -234,7 +252,8 @@ void ScrollAnimator::TickAnimation(double monotonic_time) {
return;
TRACE_EVENT0("blink", "ScrollAnimator::tickAnimation");
- double elapsed_time = monotonic_time - start_time_;
+ double elapsed_time =
+ monotonic_time - start_time_.since_origin().InSecondsF();
bool is_finished = (elapsed_time > animation_curve_->Duration());
ScrollOffset offset = BlinkOffsetFromCompositorOffset(
@@ -245,10 +264,13 @@ void ScrollAnimator::TickAnimation(double monotonic_time) {
current_offset_ = offset;
- if (is_finished)
+ if (is_finished) {
run_state_ = RunState::kPostAnimationCleanup;
- else
+ if (on_finish_)
+ std::move(on_finish_).Run();
+ } else {
GetScrollableArea()->ScheduleAnimation();
+ }
TRACE_EVENT0("blink", "ScrollAnimator::notifyOffsetChanged");
NotifyOffsetChanged();
@@ -338,7 +360,7 @@ void ScrollAnimator::UpdateCompositorAnimations() {
// ::adjustScrollOffsetAnimation should have made the necessary
// adjustment to the curve.
animation_curve_->UpdateTarget(
- TimeDelta::FromSecondsD(time_function_() - start_time_),
+ tick_clock_->NowTicks() - start_time_,
CompositorOffsetFromBlinkOffset(target_offset_));
}
@@ -399,34 +421,20 @@ void ScrollAnimator::NotifyCompositorAnimationAborted(int group_id) {
// An animation aborted by the compositor is treated as a finished
// animation.
ScrollAnimatorCompositorCoordinator::CompositorAnimationFinished(group_id);
+ if (on_finish_)
+ std::move(on_finish_).Run();
}
void ScrollAnimator::NotifyCompositorAnimationFinished(int group_id) {
ScrollAnimatorCompositorCoordinator::CompositorAnimationFinished(group_id);
-}
-
-void ScrollAnimator::NotifyAnimationTakeover(
- double monotonic_time,
- double animation_start_time,
- std::unique_ptr<cc::AnimationCurve> curve) {
- // If there is already an animation running and the compositor asks to take
- // over an animation, do nothing to avoid judder.
- if (HasRunningAnimation())
- return;
-
- cc::ScrollOffsetAnimationCurve* scroll_offset_animation_curve =
- curve->ToScrollOffsetAnimationCurve();
- ScrollOffset target_value(scroll_offset_animation_curve->target_value().x(),
- scroll_offset_animation_curve->target_value().y());
- if (WillAnimateToOffset(target_value)) {
- animation_curve_ = std::make_unique<CompositorScrollOffsetAnimationCurve>(
- scroll_offset_animation_curve);
- start_time_ = animation_start_time;
- }
+ if (on_finish_)
+ std::move(on_finish_).Run();
}
void ScrollAnimator::CancelAnimation() {
ScrollAnimatorCompositorCoordinator::CancelAnimation();
+ if (on_finish_)
+ std::move(on_finish_).Run();
}
void ScrollAnimator::TakeOverCompositorAnimation() {
diff --git a/chromium/third_party/blink/renderer/core/scroll/scroll_animator.h b/chromium/third_party/blink/renderer/core/scroll/scroll_animator.h
index 9d57d96f402..110333f0b9b 100644
--- a/chromium/third_party/blink/renderer/core/scroll/scroll_animator.h
+++ b/chromium/third_party/blink/renderer/core/scroll/scroll_animator.h
@@ -32,6 +32,8 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_SCROLL_SCROLL_ANIMATOR_H_
#include <memory>
+#include "base/time/default_tick_clock.h"
+
#include "third_party/blink/renderer/core/scroll/scroll_animator_base.h"
#include "third_party/blink/renderer/platform/animation/compositor_animation_client.h"
#include "third_party/blink/renderer/platform/animation/compositor_animation_delegate.h"
@@ -100,14 +102,19 @@ class CompositorAnimationTimeline;
class CORE_EXPORT ScrollAnimator : public ScrollAnimatorBase {
public:
explicit ScrollAnimator(ScrollableArea*,
- WTF::TimeFunction = WTF::CurrentTimeTicksInSeconds);
+ const base::TickClock* tick_clock =
+ base::DefaultTickClock::GetInstance());
~ScrollAnimator() override;
bool HasRunningAnimation() const override;
ScrollOffset ComputeDeltaToConsume(const ScrollOffset& delta) const override;
+ // The callback will be run if the animation is updated by another
+ // UserScroll, otherwise it is called when the animation is finished,
+ // cancelled or reset.
ScrollResult UserScroll(ScrollGranularity,
- const ScrollOffset& delta) override;
+ const ScrollOffset& delta,
+ ScrollableArea::ScrollCallback on_finish) override;
void ScrollToOffsetWithoutAnimation(const ScrollOffset&) override;
ScrollOffset DesiredTargetOffset() const override;
@@ -130,14 +137,6 @@ class CORE_EXPORT ScrollAnimator : public ScrollAnimatorBase {
// Returns whether or not the animation was sent to the compositor.
virtual bool SendAnimationToCompositor();
- void NotifyAnimationTakeover(double monotonic_time,
- double animation_start_time,
- std::unique_ptr<cc::AnimationCurve>) override;
-
- std::unique_ptr<CompositorScrollOffsetAnimationCurve> animation_curve_;
- double start_time_;
- WTF::TimeFunction time_function_;
-
private:
// Returns true if the animation was scheduled successfully. If animation
// could not be scheduled (e.g. because the frame is detached), scrolls
@@ -155,8 +154,16 @@ class CORE_EXPORT ScrollAnimator : public ScrollAnimatorBase {
// because we are already at targetPos.
bool WillAnimateToOffset(const ScrollOffset& target_pos);
+ std::unique_ptr<CompositorScrollOffsetAnimationCurve> animation_curve_;
+ const base::TickClock* const tick_clock_;
+ base::TimeTicks start_time_;
+
ScrollOffset target_offset_;
ScrollGranularity last_granularity_;
+
+ // on_finish_ is a callback to call on animation finished, cancelled, or
+ // otherwise interrupted in any way.
+ ScrollableArea::ScrollCallback on_finish_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/scroll/scroll_animator_base.cc b/chromium/third_party/blink/renderer/core/scroll/scroll_animator_base.cc
index f14d68871f5..9705984b08a 100644
--- a/chromium/third_party/blink/renderer/core/scroll/scroll_animator_base.cc
+++ b/chromium/third_party/blink/renderer/core/scroll/scroll_animator_base.cc
@@ -30,6 +30,7 @@
#include "third_party/blink/renderer/core/scroll/scroll_animator_base.h"
+#include "base/callback_helpers.h"
#include "third_party/blink/renderer/core/scroll/scrollable_area.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
@@ -47,8 +48,13 @@ ScrollOffset ScrollAnimatorBase::ComputeDeltaToConsume(
return new_pos - current_offset_;
}
-ScrollResult ScrollAnimatorBase::UserScroll(ScrollGranularity,
- const ScrollOffset& delta) {
+ScrollResult ScrollAnimatorBase::UserScroll(
+ ScrollGranularity,
+ const ScrollOffset& delta,
+ ScrollableArea::ScrollCallback on_finish) {
+ // Run the callback for non-animation user scroll.
+ base::ScopedClosureRunner run_on_return(std::move(on_finish));
+
ScrollOffset consumed_delta = ComputeDeltaToConsume(delta);
ScrollOffset new_pos = current_offset_ + consumed_delta;
if (current_offset_ == new_pos)
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 34f2471baf1..6a8ca92c245 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
@@ -34,6 +34,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/scroll/scroll_animator_compositor_coordinator.h"
#include "third_party/blink/renderer/core/scroll/scroll_types.h"
+#include "third_party/blink/renderer/core/scroll/scrollable_area.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
@@ -66,7 +67,9 @@ class CORE_EXPORT ScrollAnimatorBase
// no unusedDelta and didScroll=true, i.e. fully consuming the scroll request.
// This makes animations latch to a single scroller. Note, the semantics are
// currently somewhat different on Mac - see ScrollAnimatorMac.mm.
- virtual ScrollResult UserScroll(ScrollGranularity, const ScrollOffset& delta);
+ virtual ScrollResult UserScroll(ScrollGranularity,
+ const ScrollOffset& delta,
+ ScrollableArea::ScrollCallback on_finish);
virtual void ScrollToOffsetWithoutAnimation(const ScrollOffset&);
diff --git a/chromium/third_party/blink/renderer/core/scroll/scroll_animator_compositor_coordinator.h b/chromium/third_party/blink/renderer/core/scroll/scroll_animator_compositor_coordinator.h
index d72234ce3d1..814d08251be 100644
--- a/chromium/third_party/blink/renderer/core/scroll/scroll_animator_compositor_coordinator.h
+++ b/chromium/third_party/blink/renderer/core/scroll/scroll_animator_compositor_coordinator.h
@@ -15,7 +15,7 @@
#include "third_party/blink/renderer/platform/animation/compositor_animation_delegate.h"
#include "third_party/blink/renderer/platform/graphics/compositor_element_id.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -166,6 +166,10 @@ class CORE_EXPORT ScrollAnimatorCompositorCoordinator
FRIEND_TEST_ALL_PREFIXES(ScrollAnimatorTest, CancellingAnimationResetsState);
FRIEND_TEST_ALL_PREFIXES(ScrollAnimatorTest, CancellingCompositorAnimation);
FRIEND_TEST_ALL_PREFIXES(ScrollAnimatorTest, ImplOnlyAnimationUpdatesCleared);
+ FRIEND_TEST_ALL_PREFIXES(ScrollAnimatorTest,
+ UserScrollCallBackAtAnimationFinishOnMainThread);
+ FRIEND_TEST_ALL_PREFIXES(ScrollAnimatorTest,
+ UserScrollCallBackAtAnimationFinishOnCompositor);
std::unique_ptr<CompositorAnimation> compositor_animation_;
// The element id to which the compositor animation is attached when
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 f9e6bf3d2c0..be3c1b940f4 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
@@ -141,7 +141,8 @@ class CORE_EXPORT ScrollAnimatorMac : public ScrollAnimatorBase {
ScrollOffset content_area_scrolled_timer_scroll_delta_;
ScrollResult UserScroll(ScrollGranularity,
- const ScrollOffset& delta) override;
+ const ScrollOffset& delta,
+ ScrollableArea::ScrollCallback on_finish) override;
void ScrollToOffsetWithoutAnimation(const ScrollOffset&) override;
void CancelAnimation() override;
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 9b2df12c941..783dec8eaa8 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
@@ -312,10 +312,10 @@ class BlinkScrollbarPartAnimationTimer {
~BlinkScrollbarPartAnimationTimer() {}
void Start() {
- start_time_ = WTF::CurrentTime();
+ start_time_ = base::Time::Now().ToDoubleT();
// Set the framerate of the animation. NSAnimation uses a default
// framerate of 60 Hz, so use that here.
- timer_.StartRepeating(TimeDelta::FromSecondsD(1.0 / 60.0), FROM_HERE);
+ timer_.StartRepeating(base::TimeDelta::FromSecondsD(1.0 / 60.0), FROM_HERE);
}
void Stop() { timer_.Stop(); }
@@ -324,7 +324,7 @@ class BlinkScrollbarPartAnimationTimer {
private:
void TimerFired(TimerBase*) {
- double current_time = WTF::CurrentTime();
+ double current_time = base::Time::Now().ToDoubleT();
double delta = current_time - start_time_;
if (delta >= duration_)
@@ -332,7 +332,7 @@ class BlinkScrollbarPartAnimationTimer {
double fraction = delta / duration_;
fraction = clampTo(fraction, 0.0, 1.0);
- double progress = timing_function_->Evaluate(fraction, 0.001);
+ double progress = timing_function_->Evaluate(fraction);
[animation_ setCurrentProgress:progress];
}
@@ -740,16 +740,23 @@ void ScrollAnimatorMac::Dispose() {
send_content_area_scrolled_task_handle_.Cancel();
}
-ScrollResult ScrollAnimatorMac::UserScroll(ScrollGranularity granularity,
- const ScrollOffset& delta) {
+ScrollResult ScrollAnimatorMac::UserScroll(
+ ScrollGranularity granularity,
+ const ScrollOffset& delta,
+ ScrollableArea::ScrollCallback on_finish) {
have_scrolled_since_page_load_ = true;
- if (!scrollable_area_->ScrollAnimatorEnabled())
- return ScrollAnimatorBase::UserScroll(granularity, delta);
+ if (!scrollable_area_->ScrollAnimatorEnabled() ||
+ granularity == ScrollGranularity::kScrollByPixel ||
+ granularity == ScrollGranularity::kScrollByPrecisePixel) {
+ return ScrollAnimatorBase::UserScroll(granularity, delta,
+ std::move(on_finish));
+ }
- if (granularity == ScrollGranularity::kScrollByPixel ||
- granularity == ScrollGranularity::kScrollByPrecisePixel)
- return ScrollAnimatorBase::UserScroll(granularity, delta);
+ // TODO(lanwei): we should find when the animation finishes and run the
+ // callback after the animation finishes, see https://crbug.com/967842.
+ if (on_finish)
+ std::move(on_finish).Run();
ScrollOffset consumed_delta = ComputeDeltaToConsume(delta);
ScrollOffset new_offset = current_offset_ + consumed_delta;
@@ -1051,7 +1058,7 @@ void ScrollAnimatorMac::StartScrollbarPaintTimer() {
*task_runner_, FROM_HERE,
WTF::Bind(&ScrollAnimatorMac::InitialScrollbarPaintTask,
WrapWeakPersistent(this)),
- TimeDelta::FromMilliseconds(1));
+ base::TimeDelta::FromMilliseconds(1));
}
bool ScrollAnimatorMac::ScrollbarPaintTimerIsActive() const {
diff --git a/chromium/third_party/blink/renderer/core/scroll/scroll_animator_test.cc b/chromium/third_party/blink/renderer/core/scroll/scroll_animator_test.cc
index 9840eeadbf7..5e6c867606b 100644
--- a/chromium/third_party/blink/renderer/core/scroll/scroll_animator_test.cc
+++ b/chromium/third_party/blink/renderer/core/scroll/scroll_animator_test.cc
@@ -28,6 +28,7 @@
#include "third_party/blink/renderer/core/scroll/scroll_animator.h"
#include "base/single_thread_task_runner.h"
+#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/public/platform/platform.h"
@@ -46,14 +47,12 @@ using testing::AtLeast;
using testing::Return;
using testing::_;
-static double g_mocked_time = 0.0;
+namespace {
-static double GetMockedTime() {
- return g_mocked_time;
+double NowTicksInSeconds(const base::TestMockTimeTaskRunner* task_runner) {
+ return task_runner->NowTicks().since_origin().InSecondsF();
}
-namespace {
-
class MockScrollableAreaForAnimatorTest
: public GarbageCollectedFinalized<MockScrollableAreaForAnimatorTest>,
public ScrollableArea {
@@ -139,6 +138,8 @@ class MockScrollableAreaForAnimatorTest
ScrollableArea::Trace(visitor);
}
+ void DisposeImpl() override { timer_task_runner_.reset(); }
+
private:
bool scroll_animator_enabled_;
ScrollOffset min_offset_;
@@ -150,8 +151,8 @@ class MockScrollableAreaForAnimatorTest
class TestScrollAnimator : public ScrollAnimator {
public:
TestScrollAnimator(ScrollableArea* scrollable_area,
- WTF::TimeFunction timing_function)
- : ScrollAnimator(scrollable_area, timing_function) {}
+ const base::TickClock* tick_clock)
+ : ScrollAnimator(scrollable_area, tick_clock) {}
~TestScrollAnimator() override = default;
void SetShouldSendToCompositor(bool send) {
@@ -187,8 +188,10 @@ TEST(ScrollAnimatorTest, MainThreadStates) {
auto* scrollable_area =
MakeGarbageCollected<MockScrollableAreaForAnimatorTest>(
true, ScrollOffset(), ScrollOffset(1000, 1000));
- ScrollAnimator* scroll_animator =
- MakeGarbageCollected<ScrollAnimator>(scrollable_area, GetMockedTime);
+ scoped_refptr<base::TestMockTimeTaskRunner> task_runner =
+ base::MakeRefCounted<base::TestMockTimeTaskRunner>();
+ ScrollAnimator* scroll_animator = MakeGarbageCollected<ScrollAnimator>(
+ scrollable_area, task_runner->GetMockTickClock());
EXPECT_CALL(*scrollable_area, UpdateScrollOffset(_, _)).Times(2);
// Once from userScroll, once from updateCompositorAnimations.
@@ -204,18 +207,19 @@ TEST(ScrollAnimatorTest, MainThreadStates) {
// WaitingToSendToCompositor
scroll_animator->UserScroll(ScrollGranularity::kScrollByLine,
- FloatSize(10, 0));
+ FloatSize(10, 0),
+ ScrollableArea::ScrollCallback());
EXPECT_EQ(scroll_animator->run_state_,
ScrollAnimatorCompositorCoordinator::RunState::
kWaitingToSendToCompositor);
// RunningOnMainThread
- g_mocked_time += 0.05;
+ task_runner->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
scroll_animator->UpdateCompositorAnimations();
EXPECT_EQ(
scroll_animator->run_state_,
ScrollAnimatorCompositorCoordinator::RunState::kRunningOnMainThread);
- scroll_animator->TickAnimation(GetMockedTime());
+ scroll_animator->TickAnimation(NowTicksInSeconds(task_runner.get()));
EXPECT_EQ(
scroll_animator->run_state_,
ScrollAnimatorCompositorCoordinator::RunState::kRunningOnMainThread);
@@ -228,7 +232,7 @@ TEST(ScrollAnimatorTest, MainThreadStates) {
// Idle
scroll_animator->UpdateCompositorAnimations();
- scroll_animator->TickAnimation(GetMockedTime());
+ scroll_animator->TickAnimation(NowTicksInSeconds(task_runner.get()));
EXPECT_EQ(scroll_animator->run_state_,
ScrollAnimatorCompositorCoordinator::RunState::kIdle);
@@ -242,8 +246,10 @@ TEST(ScrollAnimatorTest, MainThreadEnabled) {
auto* scrollable_area =
MakeGarbageCollected<MockScrollableAreaForAnimatorTest>(
true, ScrollOffset(), ScrollOffset(1000, 1000));
- ScrollAnimator* scroll_animator =
- MakeGarbageCollected<ScrollAnimator>(scrollable_area, GetMockedTime);
+ scoped_refptr<base::TestMockTimeTaskRunner> task_runner =
+ base::MakeRefCounted<base::TestMockTimeTaskRunner>();
+ ScrollAnimator* scroll_animator = MakeGarbageCollected<ScrollAnimator>(
+ scrollable_area, task_runner->GetMockTickClock());
EXPECT_CALL(*scrollable_area, UpdateScrollOffset(_, _)).Times(9);
EXPECT_CALL(*scrollable_area, RegisterForAnimation()).Times(6);
@@ -254,20 +260,22 @@ TEST(ScrollAnimatorTest, MainThreadEnabled) {
EXPECT_FALSE(scroll_animator->HasAnimationThatRequiresService());
ScrollResult result = scroll_animator->UserScroll(
- ScrollGranularity::kScrollByLine, FloatSize(-100, 0));
+ ScrollGranularity::kScrollByLine, FloatSize(-100, 0),
+ ScrollableArea::ScrollCallback());
EXPECT_FALSE(scroll_animator->HasAnimationThatRequiresService());
EXPECT_FALSE(result.did_scroll_x);
EXPECT_FLOAT_EQ(-100.0f, result.unused_scroll_delta_x);
result = scroll_animator->UserScroll(ScrollGranularity::kScrollByLine,
- FloatSize(100, 0));
+ FloatSize(100, 0),
+ ScrollableArea::ScrollCallback());
EXPECT_TRUE(scroll_animator->HasAnimationThatRequiresService());
EXPECT_TRUE(result.did_scroll_x);
EXPECT_FLOAT_EQ(0.0, result.unused_scroll_delta_x);
- g_mocked_time += 0.05;
+ task_runner->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
scroll_animator->UpdateCompositorAnimations();
- scroll_animator->TickAnimation(GetMockedTime());
+ scroll_animator->TickAnimation(NowTicksInSeconds(task_runner.get()));
EXPECT_NE(100, scroll_animator->CurrentOffset().Width());
EXPECT_NE(0, scroll_animator->CurrentOffset().Width());
@@ -275,12 +283,13 @@ TEST(ScrollAnimatorTest, MainThreadEnabled) {
Reset(*scroll_animator);
scroll_animator->UserScroll(ScrollGranularity::kScrollByPage,
- FloatSize(100, 0));
+ FloatSize(100, 0),
+ ScrollableArea::ScrollCallback());
EXPECT_TRUE(scroll_animator->HasAnimationThatRequiresService());
- g_mocked_time += 0.05;
+ task_runner->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
scroll_animator->UpdateCompositorAnimations();
- scroll_animator->TickAnimation(GetMockedTime());
+ scroll_animator->TickAnimation(NowTicksInSeconds(task_runner.get()));
EXPECT_NE(100, scroll_animator->CurrentOffset().Width());
EXPECT_NE(0, scroll_animator->CurrentOffset().Width());
@@ -288,22 +297,23 @@ TEST(ScrollAnimatorTest, MainThreadEnabled) {
Reset(*scroll_animator);
scroll_animator->UserScroll(ScrollGranularity::kScrollByPixel,
- FloatSize(100, 0));
+ FloatSize(100, 0),
+ ScrollableArea::ScrollCallback());
EXPECT_TRUE(scroll_animator->HasAnimationThatRequiresService());
- g_mocked_time += 0.05;
+ task_runner->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
scroll_animator->UpdateCompositorAnimations();
- scroll_animator->TickAnimation(GetMockedTime());
+ scroll_animator->TickAnimation(NowTicksInSeconds(task_runner.get()));
EXPECT_NE(100, scroll_animator->CurrentOffset().Width());
EXPECT_NE(0, scroll_animator->CurrentOffset().Width());
EXPECT_EQ(0, scroll_animator->CurrentOffset().Height());
- g_mocked_time += 1.0;
+ task_runner->FastForwardBy(base::TimeDelta::FromSeconds(1.0));
scroll_animator->UpdateCompositorAnimations();
- scroll_animator->TickAnimation(GetMockedTime());
+ scroll_animator->TickAnimation(NowTicksInSeconds(task_runner.get()));
- g_mocked_time += 0.05;
+ task_runner->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
scroll_animator->UpdateCompositorAnimations();
EXPECT_FALSE(scroll_animator->HasAnimationThatRequiresService());
EXPECT_EQ(100, scroll_animator->CurrentOffset().Width());
@@ -311,7 +321,8 @@ TEST(ScrollAnimatorTest, MainThreadEnabled) {
Reset(*scroll_animator);
scroll_animator->UserScroll(ScrollGranularity::kScrollByPrecisePixel,
- FloatSize(100, 0));
+ FloatSize(100, 0),
+ ScrollableArea::ScrollCallback());
EXPECT_FALSE(scroll_animator->HasAnimationThatRequiresService());
EXPECT_EQ(100, scroll_animator->CurrentOffset().Width());
@@ -326,8 +337,10 @@ TEST(ScrollAnimatorTest, AnimatedScrollAborted) {
auto* scrollable_area =
MakeGarbageCollected<MockScrollableAreaForAnimatorTest>(
true, ScrollOffset(), ScrollOffset(1000, 1000));
- ScrollAnimator* scroll_animator =
- MakeGarbageCollected<ScrollAnimator>(scrollable_area, GetMockedTime);
+ scoped_refptr<base::TestMockTimeTaskRunner> task_runner =
+ base::MakeRefCounted<base::TestMockTimeTaskRunner>();
+ ScrollAnimator* scroll_animator = MakeGarbageCollected<ScrollAnimator>(
+ scrollable_area, task_runner->GetMockTickClock());
EXPECT_CALL(*scrollable_area, UpdateScrollOffset(_, _)).Times(3);
EXPECT_CALL(*scrollable_area, RegisterForAnimation()).Times(2);
@@ -339,15 +352,16 @@ TEST(ScrollAnimatorTest, AnimatedScrollAborted) {
// Smooth scroll.
ScrollResult result = scroll_animator->UserScroll(
- ScrollGranularity::kScrollByLine, FloatSize(100, 0));
+ ScrollGranularity::kScrollByLine, FloatSize(100, 0),
+ ScrollableArea::ScrollCallback());
EXPECT_TRUE(scroll_animator->HasAnimationThatRequiresService());
EXPECT_TRUE(result.did_scroll_x);
EXPECT_FLOAT_EQ(0.0, result.unused_scroll_delta_x);
EXPECT_TRUE(scroll_animator->HasRunningAnimation());
- g_mocked_time += 0.05;
+ task_runner->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
scroll_animator->UpdateCompositorAnimations();
- scroll_animator->TickAnimation(GetMockedTime());
+ scroll_animator->TickAnimation(NowTicksInSeconds(task_runner.get()));
EXPECT_NE(100, scroll_animator->CurrentOffset().Width());
EXPECT_NE(0, scroll_animator->CurrentOffset().Width());
@@ -357,9 +371,10 @@ TEST(ScrollAnimatorTest, AnimatedScrollAborted) {
// Instant scroll.
result = scroll_animator->UserScroll(ScrollGranularity::kScrollByPrecisePixel,
- FloatSize(100, 0));
+ FloatSize(100, 0),
+ ScrollableArea::ScrollCallback());
EXPECT_TRUE(result.did_scroll_x);
- g_mocked_time += 0.05;
+ task_runner->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
scroll_animator->UpdateCompositorAnimations();
EXPECT_FALSE(scroll_animator->HasRunningAnimation());
EXPECT_EQ(x + 100, scroll_animator->CurrentOffset().Width());
@@ -374,8 +389,11 @@ TEST(ScrollAnimatorTest, AnimatedScrollTakeover) {
auto* scrollable_area =
MakeGarbageCollected<MockScrollableAreaForAnimatorTest>(
true, ScrollOffset(), ScrollOffset(1000, 1000));
+ scoped_refptr<base::TestMockTimeTaskRunner> task_runner =
+ base::MakeRefCounted<base::TestMockTimeTaskRunner>();
TestScrollAnimator* scroll_animator =
- MakeGarbageCollected<TestScrollAnimator>(scrollable_area, GetMockedTime);
+ MakeGarbageCollected<TestScrollAnimator>(scrollable_area,
+ task_runner->GetMockTickClock());
EXPECT_CALL(*scrollable_area, UpdateScrollOffset(_, _)).Times(2);
// Called from userScroll, updateCompositorAnimations, then
@@ -389,14 +407,15 @@ TEST(ScrollAnimatorTest, AnimatedScrollTakeover) {
// Smooth scroll.
ScrollResult result = scroll_animator->UserScroll(
- ScrollGranularity::kScrollByLine, FloatSize(100, 0));
+ ScrollGranularity::kScrollByLine, FloatSize(100, 0),
+ ScrollableArea::ScrollCallback());
EXPECT_TRUE(scroll_animator->HasAnimationThatRequiresService());
EXPECT_TRUE(result.did_scroll_x);
EXPECT_FLOAT_EQ(0.0, result.unused_scroll_delta_x);
EXPECT_TRUE(scroll_animator->HasRunningAnimation());
// Update compositor animation.
- g_mocked_time += 0.05;
+ task_runner->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
scroll_animator->SetShouldSendToCompositor(true);
scroll_animator->UpdateCompositorAnimations();
EXPECT_EQ(
@@ -415,7 +434,7 @@ TEST(ScrollAnimatorTest, AnimatedScrollTakeover) {
EXPECT_EQ(
scroll_animator->run_state_,
ScrollAnimatorCompositorCoordinator::RunState::kRunningOnMainThread);
- scroll_animator->TickAnimation(GetMockedTime());
+ scroll_animator->TickAnimation(NowTicksInSeconds(task_runner.get()));
EXPECT_NE(100, scroll_animator->CurrentOffset().Width());
EXPECT_NE(0, scroll_animator->CurrentOffset().Width());
EXPECT_EQ(0, scroll_animator->CurrentOffset().Height());
@@ -426,32 +445,38 @@ TEST(ScrollAnimatorTest, Disabled) {
auto* scrollable_area =
MakeGarbageCollected<MockScrollableAreaForAnimatorTest>(
false, ScrollOffset(), ScrollOffset(1000, 1000));
- ScrollAnimator* scroll_animator =
- MakeGarbageCollected<ScrollAnimator>(scrollable_area, GetMockedTime);
+ scoped_refptr<base::TestMockTimeTaskRunner> task_runner =
+ base::MakeRefCounted<base::TestMockTimeTaskRunner>();
+ ScrollAnimator* scroll_animator = MakeGarbageCollected<ScrollAnimator>(
+ scrollable_area, task_runner->GetMockTickClock());
EXPECT_CALL(*scrollable_area, UpdateScrollOffset(_, _)).Times(8);
EXPECT_CALL(*scrollable_area, RegisterForAnimation()).Times(0);
scroll_animator->UserScroll(ScrollGranularity::kScrollByLine,
- FloatSize(100, 0));
+ FloatSize(100, 0),
+ ScrollableArea::ScrollCallback());
EXPECT_EQ(100, scroll_animator->CurrentOffset().Width());
EXPECT_EQ(0, scroll_animator->CurrentOffset().Height());
Reset(*scroll_animator);
scroll_animator->UserScroll(ScrollGranularity::kScrollByPage,
- FloatSize(100, 0));
+ FloatSize(100, 0),
+ ScrollableArea::ScrollCallback());
EXPECT_EQ(100, scroll_animator->CurrentOffset().Width());
EXPECT_EQ(0, scroll_animator->CurrentOffset().Height());
Reset(*scroll_animator);
scroll_animator->UserScroll(ScrollGranularity::kScrollByDocument,
- FloatSize(100, 0));
+ FloatSize(100, 0),
+ ScrollableArea::ScrollCallback());
EXPECT_EQ(100, scroll_animator->CurrentOffset().Width());
EXPECT_EQ(0, scroll_animator->CurrentOffset().Height());
Reset(*scroll_animator);
scroll_animator->UserScroll(ScrollGranularity::kScrollByPixel,
- FloatSize(100, 0));
+ FloatSize(100, 0),
+ ScrollableArea::ScrollCallback());
EXPECT_EQ(100, scroll_animator->CurrentOffset().Width());
EXPECT_EQ(0, scroll_animator->CurrentOffset().Height());
Reset(*scroll_animator);
@@ -463,8 +488,10 @@ TEST(ScrollAnimatorTest, CancellingAnimationResetsState) {
auto* scrollable_area =
MakeGarbageCollected<MockScrollableAreaForAnimatorTest>(
true, ScrollOffset(), ScrollOffset(1000, 1000));
- ScrollAnimator* scroll_animator =
- MakeGarbageCollected<ScrollAnimator>(scrollable_area, GetMockedTime);
+ scoped_refptr<base::TestMockTimeTaskRunner> task_runner =
+ base::MakeRefCounted<base::TestMockTimeTaskRunner>();
+ ScrollAnimator* scroll_animator = MakeGarbageCollected<ScrollAnimator>(
+ scrollable_area, task_runner->GetMockTickClock());
// Called from first userScroll, setCurrentOffset, and second userScroll.
EXPECT_CALL(*scrollable_area, UpdateScrollOffset(_, _)).Times(3);
@@ -479,18 +506,19 @@ TEST(ScrollAnimatorTest, CancellingAnimationResetsState) {
// WaitingToSendToCompositor
scroll_animator->UserScroll(ScrollGranularity::kScrollByLine,
- FloatSize(10, 0));
+ FloatSize(10, 0),
+ ScrollableArea::ScrollCallback());
EXPECT_EQ(scroll_animator->run_state_,
ScrollAnimatorCompositorCoordinator::RunState::
kWaitingToSendToCompositor);
// RunningOnMainThread
- g_mocked_time += 0.05;
+ task_runner->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
scroll_animator->UpdateCompositorAnimations();
EXPECT_EQ(
scroll_animator->run_state_,
ScrollAnimatorCompositorCoordinator::RunState::kRunningOnMainThread);
- scroll_animator->TickAnimation(GetMockedTime());
+ scroll_animator->TickAnimation(NowTicksInSeconds(task_runner.get()));
EXPECT_EQ(
scroll_animator->run_state_,
ScrollAnimatorCompositorCoordinator::RunState::kRunningOnMainThread);
@@ -507,15 +535,16 @@ TEST(ScrollAnimatorTest, CancellingAnimationResetsState) {
// Another userScroll after modified scroll offset.
scroll_animator->SetCurrentOffset(ScrollOffset(offset_x + 15, 0));
scroll_animator->UserScroll(ScrollGranularity::kScrollByLine,
- FloatSize(10, 0));
+ FloatSize(10, 0),
+ ScrollableArea::ScrollCallback());
EXPECT_EQ(scroll_animator->run_state_,
ScrollAnimatorCompositorCoordinator::RunState::
kWaitingToSendToCompositor);
// Finish scroll animation.
- g_mocked_time += 1.0;
+ task_runner->FastForwardBy(base::TimeDelta::FromSeconds(1));
scroll_animator->UpdateCompositorAnimations();
- scroll_animator->TickAnimation(GetMockedTime());
+ scroll_animator->TickAnimation(NowTicksInSeconds(task_runner.get()));
EXPECT_EQ(
scroll_animator->run_state_,
ScrollAnimatorCompositorCoordinator::RunState::kPostAnimationCleanup);
@@ -525,14 +554,145 @@ TEST(ScrollAnimatorTest, CancellingAnimationResetsState) {
Reset(*scroll_animator);
}
+// Test that the callback passed to UserScroll function will be run when the
+// animation is canceled or finished when the scroll is sent to main thread.
+TEST(ScrollAnimatorTest, UserScrollCallBackAtAnimationFinishOnMainThread) {
+ auto* scrollable_area =
+ MakeGarbageCollected<MockScrollableAreaForAnimatorTest>(
+ true, ScrollOffset(), ScrollOffset(1000, 1000));
+ scoped_refptr<base::TestMockTimeTaskRunner> task_runner =
+ base::MakeRefCounted<base::TestMockTimeTaskRunner>();
+ ScrollAnimator* scroll_animator = MakeGarbageCollected<ScrollAnimator>(
+ scrollable_area, task_runner->GetMockTickClock());
+
+ // Called from first userScroll, setCurrentOffset, and second userScroll.
+ EXPECT_CALL(*scrollable_area, UpdateScrollOffset(_, _)).Times(3);
+ // Called from userScroll, updateCompositorAnimations.
+ EXPECT_CALL(*scrollable_area, RegisterForAnimation()).Times(4);
+ EXPECT_CALL(*scrollable_area, ScheduleAnimation())
+ .Times(AtLeast(1))
+ .WillRepeatedly(Return(true));
+
+ EXPECT_EQ(0, scroll_animator->CurrentOffset().Width());
+ EXPECT_EQ(0, scroll_animator->CurrentOffset().Height());
+
+ // WaitingToSendToCompositor
+ bool finished = false;
+ scroll_animator->UserScroll(
+ ScrollGranularity::kScrollByLine, FloatSize(10, 0),
+ ScrollableArea::ScrollCallback(
+ base::BindOnce([](bool* finished) { *finished = true; }, &finished)));
+ EXPECT_FALSE(finished);
+ EXPECT_EQ(scroll_animator->run_state_,
+ ScrollAnimatorCompositorCoordinator::RunState::
+ kWaitingToSendToCompositor);
+
+ // RunningOnMainThread
+ task_runner->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
+ scroll_animator->UpdateCompositorAnimations();
+ EXPECT_FALSE(finished);
+ EXPECT_EQ(
+ scroll_animator->run_state_,
+ ScrollAnimatorCompositorCoordinator::RunState::kRunningOnMainThread);
+ scroll_animator->TickAnimation(NowTicksInSeconds(task_runner.get()));
+
+ // Amount scrolled so far.
+ float offset_x = scroll_animator->CurrentOffset().Width();
+
+ // Interrupt user scroll.
+ scroll_animator->CancelAnimation();
+ EXPECT_TRUE(finished);
+ EXPECT_EQ(
+ scroll_animator->run_state_,
+ ScrollAnimatorCompositorCoordinator::RunState::kPostAnimationCleanup);
+
+ // Another userScroll after modified scroll offset.
+ scroll_animator->SetCurrentOffset(ScrollOffset(offset_x + 15, 0));
+ scroll_animator->UserScroll(ScrollGranularity::kScrollByLine,
+ FloatSize(10, 0),
+ ScrollableArea::ScrollCallback());
+ EXPECT_EQ(scroll_animator->run_state_,
+ ScrollAnimatorCompositorCoordinator::RunState::
+ kWaitingToSendToCompositor);
+
+ // Finish scroll animation.
+ task_runner->FastForwardBy(base::TimeDelta::FromSeconds(1.0));
+ scroll_animator->UpdateCompositorAnimations();
+ scroll_animator->TickAnimation(NowTicksInSeconds(task_runner.get()));
+ EXPECT_TRUE(finished);
+ EXPECT_EQ(
+ scroll_animator->run_state_,
+ ScrollAnimatorCompositorCoordinator::RunState::kPostAnimationCleanup);
+ EXPECT_EQ(offset_x + 15 + 10, scroll_animator->CurrentOffset().Width());
+ EXPECT_EQ(0, scroll_animator->CurrentOffset().Height());
+ Reset(*scroll_animator);
+
+ // Forced GC in order to finalize objects depending on the mock object.
+ ThreadState::Current()->CollectAllGarbageForTesting();
+}
+
+// Test that the callback passed to UserScroll function will be run when the
+// animation is canceled or finished when the scroll is sent to compositor.
+TEST(ScrollAnimatorTest, UserScrollCallBackAtAnimationFinishOnCompositor) {
+ auto* scrollable_area =
+ MakeGarbageCollected<MockScrollableAreaForAnimatorTest>(
+ true, ScrollOffset(), ScrollOffset(1000, 1000));
+ scoped_refptr<base::TestMockTimeTaskRunner> task_runner =
+ base::MakeRefCounted<base::TestMockTimeTaskRunner>();
+ TestScrollAnimator* scroll_animator =
+ MakeGarbageCollected<TestScrollAnimator>(scrollable_area,
+ task_runner->GetMockTickClock());
+
+ // Called from userScroll, and first update.
+ EXPECT_CALL(*scrollable_area, ScheduleAnimation())
+ .Times(AtLeast(1))
+ .WillRepeatedly(Return(true));
+
+ // First user scroll.
+ bool finished = false;
+ scroll_animator->UserScroll(
+ ScrollGranularity::kScrollByLine, FloatSize(100, 0),
+ ScrollableArea::ScrollCallback(
+ base::BindOnce([](bool* finished) { *finished = true; }, &finished)));
+ EXPECT_FALSE(finished);
+ EXPECT_TRUE(scroll_animator->HasRunningAnimation());
+ EXPECT_EQ(100, scroll_animator->DesiredTargetOffset().Width());
+ EXPECT_EQ(0, scroll_animator->DesiredTargetOffset().Height());
+ EXPECT_EQ(scroll_animator->run_state_,
+ ScrollAnimatorCompositorCoordinator::RunState::
+ kWaitingToSendToCompositor);
+
+ // Update compositor animation.
+ task_runner->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
+ scroll_animator->SetShouldSendToCompositor(true);
+ scroll_animator->UpdateCompositorAnimations();
+ EXPECT_FALSE(finished);
+ EXPECT_EQ(
+ scroll_animator->run_state_,
+ ScrollAnimatorCompositorCoordinator::RunState::kRunningOnCompositor);
+
+ // Cancel
+ scroll_animator->CancelAnimation();
+ EXPECT_TRUE(finished);
+ EXPECT_EQ(scroll_animator->run_state_,
+ ScrollAnimatorCompositorCoordinator::RunState::
+ kWaitingToCancelOnCompositor);
+
+ // Forced GC in order to finalize objects depending on the mock object.
+ ThreadState::Current()->CollectAllGarbageForTesting();
+}
+
// Test the behavior when in WaitingToCancelOnCompositor and a new user scroll
// happens.
TEST(ScrollAnimatorTest, CancellingCompositorAnimation) {
auto* scrollable_area =
MakeGarbageCollected<MockScrollableAreaForAnimatorTest>(
true, ScrollOffset(), ScrollOffset(1000, 1000));
+ scoped_refptr<base::TestMockTimeTaskRunner> task_runner =
+ base::MakeRefCounted<base::TestMockTimeTaskRunner>();
TestScrollAnimator* scroll_animator =
- MakeGarbageCollected<TestScrollAnimator>(scrollable_area, GetMockedTime);
+ MakeGarbageCollected<TestScrollAnimator>(scrollable_area,
+ task_runner->GetMockTickClock());
// Called when reset, not setting anywhere else.
EXPECT_CALL(*scrollable_area, UpdateScrollOffset(_, _)).Times(1);
@@ -546,7 +706,8 @@ TEST(ScrollAnimatorTest, CancellingCompositorAnimation) {
// First user scroll.
ScrollResult result = scroll_animator->UserScroll(
- ScrollGranularity::kScrollByLine, FloatSize(100, 0));
+ ScrollGranularity::kScrollByLine, FloatSize(100, 0),
+ ScrollableArea::ScrollCallback());
EXPECT_TRUE(scroll_animator->HasAnimationThatRequiresService());
EXPECT_TRUE(result.did_scroll_x);
EXPECT_FLOAT_EQ(0.0, result.unused_scroll_delta_x);
@@ -555,7 +716,7 @@ TEST(ScrollAnimatorTest, CancellingCompositorAnimation) {
EXPECT_EQ(0, scroll_animator->DesiredTargetOffset().Height());
// Update compositor animation.
- g_mocked_time += 0.05;
+ task_runner->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
scroll_animator->SetShouldSendToCompositor(true);
scroll_animator->UpdateCompositorAnimations();
EXPECT_EQ(
@@ -573,7 +734,8 @@ TEST(ScrollAnimatorTest, CancellingCompositorAnimation) {
// Desired target offset should be that of the second scroll.
result = scroll_animator->UserScroll(ScrollGranularity::kScrollByLine,
- FloatSize(100, 0));
+ FloatSize(100, 0),
+ ScrollableArea::ScrollCallback());
EXPECT_TRUE(scroll_animator->HasAnimationThatRequiresService());
EXPECT_TRUE(result.did_scroll_x);
EXPECT_FLOAT_EQ(0.0, result.unused_scroll_delta_x);
@@ -584,7 +746,7 @@ TEST(ScrollAnimatorTest, CancellingCompositorAnimation) {
EXPECT_EQ(0, scroll_animator->DesiredTargetOffset().Height());
// Update compositor animation.
- g_mocked_time += 0.05;
+ task_runner->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
scroll_animator->UpdateCompositorAnimations();
EXPECT_EQ(
scroll_animator->run_state_,
@@ -592,7 +754,8 @@ TEST(ScrollAnimatorTest, CancellingCompositorAnimation) {
// Third user scroll after compositor update updates the target.
result = scroll_animator->UserScroll(ScrollGranularity::kScrollByLine,
- FloatSize(100, 0));
+ FloatSize(100, 0),
+ ScrollableArea::ScrollCallback());
EXPECT_TRUE(scroll_animator->HasAnimationThatRequiresService());
EXPECT_TRUE(result.did_scroll_x);
EXPECT_FLOAT_EQ(0.0, result.unused_scroll_delta_x);
@@ -613,8 +776,10 @@ TEST(ScrollAnimatorTest, ImplOnlyAnimationUpdatesCleared) {
auto* scrollable_area =
MakeGarbageCollected<MockScrollableAreaForAnimatorTest>(
true, ScrollOffset(), ScrollOffset(1000, 1000));
- TestScrollAnimator* animator =
- MakeGarbageCollected<TestScrollAnimator>(scrollable_area, GetMockedTime);
+ scoped_refptr<base::TestMockTimeTaskRunner> task_runner =
+ base::MakeRefCounted<base::TestMockTimeTaskRunner>();
+ TestScrollAnimator* animator = MakeGarbageCollected<TestScrollAnimator>(
+ scrollable_area, task_runner->GetMockTickClock());
// From calls to adjust/takeoverImplOnlyScrollOffsetAnimation.
EXPECT_CALL(*scrollable_area, RegisterForAnimation()).Times(3);
@@ -651,8 +816,10 @@ TEST(ScrollAnimatorTest, MainThreadAnimationTargetAdjustment) {
auto* scrollable_area =
MakeGarbageCollected<MockScrollableAreaForAnimatorTest>(
true, ScrollOffset(-100, -100), ScrollOffset(1000, 1000));
- ScrollAnimator* animator =
- MakeGarbageCollected<ScrollAnimator>(scrollable_area, GetMockedTime);
+ scoped_refptr<base::TestMockTimeTaskRunner> task_runner =
+ base::MakeRefCounted<base::TestMockTimeTaskRunner>();
+ ScrollAnimator* animator = MakeGarbageCollected<ScrollAnimator>(
+ scrollable_area, task_runner->GetMockTickClock());
scrollable_area->SetScrollAnimator(animator);
// Twice from tickAnimation, once from reset, and twice from
@@ -669,13 +836,13 @@ TEST(ScrollAnimatorTest, MainThreadAnimationTargetAdjustment) {
EXPECT_EQ(ScrollOffset(), animator->CurrentOffset());
// WaitingToSendToCompositor
- animator->UserScroll(ScrollGranularity::kScrollByLine,
- ScrollOffset(100, 100));
+ animator->UserScroll(ScrollGranularity::kScrollByLine, ScrollOffset(100, 100),
+ ScrollableArea::ScrollCallback());
// RunningOnMainThread
- g_mocked_time += 0.05;
+ task_runner->FastForwardBy(base::TimeDelta::FromMilliseconds(50));
animator->UpdateCompositorAnimations();
- animator->TickAnimation(GetMockedTime());
+ animator->TickAnimation(NowTicksInSeconds(task_runner.get()));
ScrollOffset offset = animator->CurrentOffset();
EXPECT_EQ(ScrollOffset(100, 100), animator->DesiredTargetOffset());
EXPECT_GT(offset.Width(), 0);
@@ -687,9 +854,9 @@ TEST(ScrollAnimatorTest, MainThreadAnimationTargetAdjustment) {
EXPECT_EQ(ScrollOffset(110, 90), animator->DesiredTargetOffset());
// Adjusting after finished animation should do nothing.
- g_mocked_time += 1.0;
+ task_runner->FastForwardBy(base::TimeDelta::FromSeconds(1));
animator->UpdateCompositorAnimations();
- animator->TickAnimation(GetMockedTime());
+ animator->TickAnimation(NowTicksInSeconds(task_runner.get()));
EXPECT_EQ(
animator->RunStateForTesting(),
ScrollAnimatorCompositorCoordinator::RunState::kPostAnimationCleanup);
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 995b55d7240..a8769571f67 100644
--- a/chromium/third_party/blink/renderer/core/scroll/scrollable_area.cc
+++ b/chromium/third_party/blink/renderer/core/scroll/scrollable_area.cc
@@ -31,7 +31,6 @@
#include "third_party/blink/renderer/core/scroll/scrollable_area.h"
-#include "base/bind.h"
#include "build/build_config.h"
#include "cc/input/main_thread_scrolling_reason.h"
#include "cc/input/scrollbar.h"
@@ -40,8 +39,8 @@
#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/input/event_handler.h"
-#include "third_party/blink/renderer/core/layout/jank_tracker.h"
#include "third_party/blink/renderer/core/layout/layout_box.h"
+#include "third_party/blink/renderer/core/layout/layout_shift_tracker.h"
#include "third_party/blink/renderer/core/page/chrome_client.h"
#include "third_party/blink/renderer/core/paint/paint_timing_detector.h"
#include "third_party/blink/renderer/core/scroll/programmatic_scroll_animator.h"
@@ -91,11 +90,20 @@ ScrollableArea::ScrollableArea()
scrollbars_hidden_if_overlay_(true),
scrollbar_captured_(false),
mouse_over_scrollbar_(false),
+ has_been_disposed_(false),
needs_show_scrollbar_layers_(false),
uses_composited_scrolling_(false) {}
ScrollableArea::~ScrollableArea() = default;
+void ScrollableArea::Dispose() {
+ if (HasBeenDisposed())
+ return;
+ DisposeImpl();
+ fade_overlay_scrollbars_timer_.reset();
+ has_been_disposed_ = true;
+}
+
void ScrollableArea::ClearScrollableArea() {
#if defined(OS_MACOSX)
if (scroll_animator_)
@@ -156,10 +164,17 @@ float ScrollableArea::ScrollStep(ScrollGranularity granularity,
}
ScrollResult ScrollableArea::UserScroll(ScrollGranularity granularity,
- const ScrollOffset& delta) {
+ const ScrollOffset& delta,
+ ScrollCallback on_finish) {
TRACE_EVENT2("input", "ScrollableArea::UserScroll", "x", delta.Width(), "y",
delta.Height());
+ if (on_finish)
+ RegisterScrollCompleteCallback(std::move(on_finish));
+
+ base::ScopedClosureRunner run_on_return(WTF::Bind(
+ &ScrollableArea::RunScrollCompleteCallbacks, WrapWeakPersistent(this)));
+
float step_x = ScrollStep(granularity, kHorizontalScrollbar);
float step_y = ScrollStep(granularity, kVerticalScrollbar);
@@ -179,8 +194,8 @@ ScrollResult ScrollableArea::UserScroll(ScrollGranularity granularity,
if (SmoothScrollSequencer* sequencer = GetSmoothScrollSequencer())
sequencer->AbortAnimations();
- ScrollResult result =
- GetScrollAnimator().UserScroll(granularity, scrollable_axis_delta);
+ ScrollResult result = GetScrollAnimator().UserScroll(
+ granularity, scrollable_axis_delta, run_on_return.Release());
// Delta that wasn't scrolled because the axis is !userInputScrollable
// should count as unusedScrollDelta.
@@ -195,21 +210,30 @@ void ScrollableArea::SetScrollOffset(const ScrollOffset& offset,
ScrollType scroll_type,
ScrollBehavior behavior,
ScrollCallback on_finish) {
+ if (on_finish)
+ RegisterScrollCompleteCallback(std::move(on_finish));
+
+ base::ScopedClosureRunner run_on_return(WTF::Bind(
+ &ScrollableArea::RunScrollCompleteCallbacks, WrapWeakPersistent(this)));
+
if (SmoothScrollSequencer* sequencer = GetSmoothScrollSequencer()) {
if (sequencer->FilterNewScrollOrAbortCurrent(scroll_type)) {
- if (on_finish)
- std::move(on_finish).Run();
return;
}
}
ScrollOffset clamped_offset = ClampScrollOffset(offset);
if (clamped_offset == GetScrollOffset()) {
- if (on_finish)
- std::move(on_finish).Run();
return;
}
+ TRACE_EVENT2("blink", "ScrollableArea::SetScrollOffset", "x", offset.Width(),
+ "y", offset.Height());
+ TRACE_EVENT_INSTANT1("blink", "Type", TRACE_EVENT_SCOPE_THREAD, "type",
+ scroll_type);
+ TRACE_EVENT_INSTANT1("blink", "Behavior", TRACE_EVENT_SCOPE_THREAD,
+ "behavior", behavior);
+
if (behavior == kScrollBehaviorAuto)
behavior = ScrollBehaviorStyle();
@@ -224,11 +248,11 @@ void ScrollableArea::SetScrollOffset(const ScrollOffset& offset,
break;
case kProgrammaticScroll:
ProgrammaticScrollHelper(clamped_offset, behavior, false,
- std::move(on_finish));
+ run_on_return.Release());
break;
case kSequencedScroll:
ProgrammaticScrollHelper(clamped_offset, behavior, true,
- std::move(on_finish));
+ run_on_return.Release());
break;
case kUserScroll:
UserScrollHelper(clamped_offset, behavior);
@@ -236,8 +260,6 @@ void ScrollableArea::SetScrollOffset(const ScrollOffset& offset,
default:
NOTREACHED();
}
- if (on_finish)
- std::move(on_finish).Run();
}
void ScrollableArea::SetScrollOffset(const ScrollOffset& offset,
@@ -278,8 +300,8 @@ void ScrollableArea::ProgrammaticScrollHelper(const ScrollOffset& offset,
CancelScrollAnimation();
ScrollCallback callback = std::move(on_finish);
- if (RuntimeEnabledFeatures::UpdateHoverFromScrollAtBeginFrameEnabled()) {
- callback = ScrollCallback(base::BindOnce(
+ if (RuntimeEnabledFeatures::UpdateHoverAtBeginFrameEnabled()) {
+ callback = ScrollCallback(WTF::Bind(
[](ScrollCallback original_callback,
WeakPersistent<ScrollableArea> area) {
if (area)
@@ -323,13 +345,13 @@ void ScrollableArea::UserScrollHelper(const ScrollOffset& offset,
GetScrollAnimator().ScrollToOffsetWithoutAnimation(ScrollOffset(x, y));
}
-LayoutRect ScrollableArea::ScrollIntoView(
- const LayoutRect& rect_in_absolute,
+PhysicalRect ScrollableArea::ScrollIntoView(
+ const PhysicalRect& rect_in_absolute,
const WebScrollIntoViewParams& params) {
// TODO(bokan): This should really be implemented here but ScrollAlignment is
// in Core which is a dependency violation.
NOTREACHED();
- return LayoutRect();
+ return PhysicalRect();
}
void ScrollableArea::ScrollOffsetChanged(const ScrollOffset& offset,
@@ -358,7 +380,11 @@ void ScrollableArea::ScrollOffsetChanged(const ScrollOffset& offset,
if (Scrollbar* vertical_scrollbar = this->VerticalScrollbar())
vertical_scrollbar->OffsetDidChange();
- if (GetScrollOffset() != old_offset) {
+ ScrollOffset delta = GetScrollOffset() - old_offset;
+ // TODO(skobes): Should we exit sooner when the offset has not changed?
+ bool offset_changed = !delta.IsZero();
+
+ if (offset_changed) {
GetScrollAnimator().NotifyContentAreaScrolled(
GetScrollOffset() - old_offset, scroll_type);
}
@@ -367,7 +393,7 @@ void ScrollableArea::ScrollOffsetChanged(const ScrollOffset& offset,
(RuntimeEnabledFeatures::FirstContentfulPaintPlusPlusEnabled() ||
RuntimeEnabledFeatures::ElementTimingEnabled(
&GetLayoutBox()->GetDocument()))) {
- if (GetScrollOffset() != old_offset && GetLayoutBox()->GetFrameView() &&
+ if (offset_changed && GetLayoutBox()->GetFrameView() &&
GetLayoutBox()
->GetFrameView()
->GetPaintTimingDetector()
@@ -377,9 +403,9 @@ void ScrollableArea::ScrollOffsetChanged(const ScrollOffset& offset,
}
}
- if (GetScrollOffset() != old_offset && GetLayoutBox() &&
- GetLayoutBox()->GetFrameView()) {
- GetLayoutBox()->GetFrameView()->GetJankTracker().NotifyScroll(scroll_type);
+ if (offset_changed && GetLayoutBox() && GetLayoutBox()->GetFrameView()) {
+ GetLayoutBox()->GetFrameView()->GetLayoutShiftTracker().NotifyScroll(
+ scroll_type, delta);
}
GetScrollAnimator().SetCurrentOffset(offset);
@@ -404,6 +430,18 @@ void ScrollableArea::UpdateScrollOffsetFromInternals(const IntSize& offset) {
ScrollOffsetChanged(ScrollOffset(offset), kProgrammaticScroll);
}
+void ScrollableArea::RegisterScrollCompleteCallback(ScrollCallback callback) {
+ DCHECK(!HasBeenDisposed());
+ pending_scroll_complete_callbacks_.push_back(std::move(callback));
+}
+
+void ScrollableArea::RunScrollCompleteCallbacks() {
+ Vector<ScrollCallback> callbacks(
+ std::move(pending_scroll_complete_callbacks_));
+ for (auto& callback : callbacks)
+ std::move(callback).Run();
+}
+
void ScrollableArea::ContentAreaWillPaint() const {
if (ScrollAnimatorBase* scroll_animator = ExistingScrollAnimator())
scroll_animator->ContentAreaWillPaint();
@@ -670,7 +708,7 @@ void ScrollableArea::ShowOverlayScrollbars() {
SetScrollbarsHiddenIfOverlay(false);
needs_show_scrollbar_layers_ = true;
- const TimeDelta time_until_disable =
+ const base::TimeDelta time_until_disable =
GetPageScrollbarTheme().OverlayScrollbarFadeOutDelay() +
GetPageScrollbarTheme().OverlayScrollbarFadeOutDuration();
@@ -780,7 +818,13 @@ CompositorElementId ScrollableArea::GetScrollbarElementId(
}
void ScrollableArea::MarkHoverStateDirty() {
- GetLayoutBox()->GetFrame()->GetEventHandler().MarkHoverStateDirty();
+ if (GetLayoutBox()) {
+ GetLayoutBox()
+ ->GetFrame()
+ ->LocalFrameRoot()
+ .GetEventHandler()
+ .MarkHoverStateDirty();
+ }
}
void ScrollableArea::Trace(blink::Visitor* visitor) {
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 458ce72fe7c..0ea68777057 100644
--- a/chromium/third_party/blink/renderer/core/scroll/scrollable_area.h
+++ b/chromium/third_party/blink/renderer/core/scroll/scrollable_area.h
@@ -27,9 +27,9 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_SCROLL_SCROLLABLE_AREA_H_
#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/layout/geometry/physical_rect.h"
#include "third_party/blink/renderer/core/scroll/scrollbar.h"
#include "third_party/blink/renderer/platform/geometry/float_quad.h"
-#include "third_party/blink/renderer/platform/geometry/layout_rect.h"
#include "third_party/blink/renderer/platform/graphics/color.h"
#include "third_party/blink/renderer/platform/graphics/compositor_element_id.h"
#include "third_party/blink/renderer/platform/graphics/scroll_types.h"
@@ -47,18 +47,17 @@ class AnimationHost;
}
namespace blink {
+class ChromeClient;
class CompositorAnimationTimeline;
class GraphicsLayer;
class LayoutBox;
class LayoutObject;
class PaintLayer;
-class ChromeClient;
class ProgrammaticScrollAnimator;
class ScrollAnchor;
class ScrollAnimatorBase;
struct SerializedAnchor;
class SmoothScrollSequencer;
-class CompositorAnimationTimeline;
struct WebScrollIntoViewParams;
enum IncludeScrollbarsInRect {
@@ -68,8 +67,11 @@ enum IncludeScrollbarsInRect {
class CORE_EXPORT ScrollableArea : public GarbageCollectedMixin {
DISALLOW_COPY_AND_ASSIGN(ScrollableArea);
+ USING_PRE_FINALIZER(ScrollableArea, Dispose);
public:
+ using ScrollCallback = base::OnceClosure;
+
static int PixelsPerLineStep(ChromeClient*);
static float MinFractionToStepWhenPaging();
int MaxOverlapBetweenPages() const;
@@ -86,9 +88,10 @@ class CORE_EXPORT ScrollableArea : public GarbageCollectedMixin {
return nullptr;
}
- virtual ScrollResult UserScroll(ScrollGranularity, const ScrollOffset&);
+ virtual ScrollResult UserScroll(ScrollGranularity,
+ const ScrollOffset&,
+ ScrollCallback on_finish);
- using ScrollCallback = base::OnceClosure;
virtual void SetScrollOffset(const ScrollOffset&,
ScrollType,
ScrollBehavior,
@@ -107,11 +110,16 @@ class CORE_EXPORT ScrollableArea : public GarbageCollectedMixin {
// Scrolls the area so that the given rect, given in absolute coordinates,
// such that it's visible in the area. Returns the new location of the input
// rect in absolute coordinates.
- virtual LayoutRect ScrollIntoView(const LayoutRect&,
- const WebScrollIntoViewParams&);
+ virtual PhysicalRect ScrollIntoView(const PhysicalRect&,
+ const WebScrollIntoViewParams&);
static bool ScrollBehaviorFromString(const String&, ScrollBehavior&);
+ // Register a callback that will be invoked when the next scroll completes -
+ // this includes the scroll animation time.
+ void RegisterScrollCompleteCallback(ScrollCallback callback);
+ void RunScrollCompleteCallbacks();
+
void ContentAreaWillPaint() const;
void MouseEnteredContentArea() const;
void MouseExitedContentArea() const;
@@ -261,9 +269,9 @@ class CORE_EXPORT ScrollableArea : public GarbageCollectedMixin {
// container for the scroll snap areas when calculating snap positions. It's
// the box's scrollport contracted by its scroll-padding.
// https://drafts.csswg.org/css-scroll-snap-1/#scroll-padding
- virtual LayoutRect VisibleScrollSnapportRect(
+ virtual PhysicalRect VisibleScrollSnapportRect(
IncludeScrollbarsInRect scrollbar_inclusion = kExcludeScrollbars) const {
- return LayoutRect(VisibleContentRect(scrollbar_inclusion));
+ return PhysicalRect(VisibleContentRect(scrollbar_inclusion));
}
virtual IntPoint LastKnownMousePosition() const { return IntPoint(); }
@@ -342,6 +350,9 @@ class CORE_EXPORT ScrollableArea : public GarbageCollectedMixin {
virtual ~ScrollableArea();
+ void Dispose();
+ virtual void DisposeImpl() {}
+
// Called when any of horizontal scrollbar, vertical scrollbar and scroll
// corner is setNeedsPaintInvalidation.
virtual void ScrollControlWasSetNeedsPaintInvalidation() = 0;
@@ -382,8 +393,6 @@ class CORE_EXPORT ScrollableArea : public GarbageCollectedMixin {
// for layout movements (bit.ly/scroll-anchoring).
virtual bool ShouldPerformScrollAnchoring() const { return false; }
- // Need to promptly let go of owned animator objects.
- EAGERLY_FINALIZE();
void Trace(blink::Visitor*) override;
virtual void ClearScrollableArea();
@@ -456,7 +465,7 @@ class CORE_EXPORT ScrollableArea : public GarbageCollectedMixin {
// then reset to alpha, causing spurrious "visibilityChanged" calls.
virtual void ScrollbarVisibilityChanged() {}
- virtual bool HasBeenDisposed() const { return false; }
+ bool HasBeenDisposed() const { return has_been_disposed_; }
private:
FRIEND_TEST_ALL_PREFIXES(ScrollableAreaTest,
@@ -485,6 +494,8 @@ class CORE_EXPORT ScrollableArea : public GarbageCollectedMixin {
std::unique_ptr<TaskRunnerTimer<ScrollableArea>>
fade_overlay_scrollbars_timer_;
+ Vector<ScrollCallback> pending_scroll_complete_callbacks_;
+
unsigned scrollbar_overlay_color_theme_ : 2;
unsigned horizontal_scrollbar_needs_paint_invalidation_ : 1;
@@ -493,6 +504,7 @@ class CORE_EXPORT ScrollableArea : public GarbageCollectedMixin {
unsigned scrollbars_hidden_if_overlay_ : 1;
unsigned scrollbar_captured_ : 1;
unsigned mouse_over_scrollbar_ : 1;
+ unsigned has_been_disposed_ : 1;
// Indicates that the next compositing update needs to call
// cc::Layer::ShowScrollbars() on our scroll layer. Ignored if not composited.
diff --git a/chromium/third_party/blink/renderer/core/scroll/scrollable_area_test.cc b/chromium/third_party/blink/renderer/core/scroll/scrollable_area_test.cc
index 60a16bdf7d2..40ce515ac7c 100644
--- a/chromium/third_party/blink/renderer/core/scroll/scrollable_area_test.cc
+++ b/chromium/third_party/blink/renderer/core/scroll/scrollable_area_test.cc
@@ -285,7 +285,7 @@ TEST_F(ScrollableAreaTest, PopupOverlayScrollbarShouldNotFadeOut) {
ScrollbarThemeOverlayMock& theme =
(ScrollbarThemeOverlayMock&)scrollable_area->GetPageScrollbarTheme();
- theme.SetOverlayScrollbarFadeOutDelay(TimeDelta::FromSeconds(1));
+ theme.SetOverlayScrollbarFadeOutDelay(base::TimeDelta::FromSeconds(1));
Scrollbar* scrollbar = Scrollbar::CreateForTesting(
scrollable_area, kHorizontalScrollbar, kRegularScrollbar, &theme);
diff --git a/chromium/third_party/blink/renderer/core/scroll/scrollbar.cc b/chromium/third_party/blink/renderer/core/scroll/scrollbar.cc
index 95448c7e7f4..b8273ca361b 100644
--- a/chromium/third_party/blink/renderer/core/scroll/scrollbar.cc
+++ b/chromium/third_party/blink/renderer/core/scroll/scrollbar.cc
@@ -83,7 +83,9 @@ Scrollbar::Scrollbar(ScrollableArea* scrollable_area,
current_pos_ = ScrollableAreaCurrentPos();
}
-Scrollbar::~Scrollbar() {
+Scrollbar::~Scrollbar() =default;
+
+void Scrollbar::Dispose() {
theme_.UnregisterScrollbar(*this);
}
@@ -182,7 +184,7 @@ bool Scrollbar::ThumbWillBeUnderMouse() const {
return PressedPos() >= thumb_pos && PressedPos() < thumb_pos + thumb_length;
}
-void Scrollbar::AutoscrollPressedPart(TimeDelta delay) {
+void Scrollbar::AutoscrollPressedPart(base::TimeDelta delay) {
if (!scrollable_area_)
return;
@@ -203,7 +205,8 @@ void Scrollbar::AutoscrollPressedPart(TimeDelta delay) {
} else {
scrollable_area_->UserScroll(
PressedPartScrollGranularity(),
- ToScrollDelta(PressedPartScrollDirectionPhysical(), 1));
+ ToScrollDelta(PressedPartScrollDirectionPhysical(), 1),
+ ScrollableArea::ScrollCallback());
}
// Always start timer when user press on button since scrollable area maybe
@@ -218,7 +221,7 @@ void Scrollbar::AutoscrollPressedPart(TimeDelta delay) {
}
}
-void Scrollbar::StartTimerIfNeeded(TimeDelta delay) {
+void Scrollbar::StartTimerIfNeeded(base::TimeDelta delay) {
// Don't do anything for the thumb.
if (pressed_part_ == kThumbPart)
return;
@@ -435,22 +438,14 @@ bool Scrollbar::HandleTapGesture() {
// Taps perform a single scroll begin/update/end sequence of gesture
// events. There's no autoscroll timer since long press is not treated
// the same as holding a mouse down.
- // TODO(dlibby): Injecting GSE immediately after GSU causes scroll snap
- // to be applied immediately when the GSE is handled, which makes it
- // look like an instant scroll to the snap position (and if this is the
- // button part, most likely doesn't give the user any visual indication
- // as button scrolls are small enough that they don't exceed thresholds
- // needed to advance to the next snap point).
- // The GSE should probably be queued up as a delayed task
- // (proportional to the tap gesture timeout?). At that point we should
- // also clear state related to pressed_part_, etc.
InjectScrollGestureForPressedPart(WebInputEvent::kGestureScrollBegin);
InjectScrollGestureForPressedPart(WebInputEvent::kGestureScrollUpdate);
InjectScrollGestureForPressedPart(WebInputEvent::kGestureScrollEnd);
} else {
scrollable_area_->UserScroll(
PressedPartScrollGranularity(),
- ToScrollDelta(PressedPartScrollDirectionPhysical(), 1));
+ ToScrollDelta(PressedPartScrollDirectionPhysical(), 1),
+ ScrollableArea::ScrollCallback());
}
return true;
}
diff --git a/chromium/third_party/blink/renderer/core/scroll/scrollbar.h b/chromium/third_party/blink/renderer/core/scroll/scrollbar.h
index cc716334ca8..486f604d1f8 100644
--- a/chromium/third_party/blink/renderer/core/scroll/scrollbar.h
+++ b/chromium/third_party/blink/renderer/core/scroll/scrollbar.h
@@ -47,6 +47,7 @@ class WebMouseEvent;
class CORE_EXPORT Scrollbar : public GarbageCollectedFinalized<Scrollbar>,
public DisplayItemClient {
+ USING_PRE_FINALIZER(Scrollbar, Dispose);
public:
// Theme object ownership remains with the caller and it must outlive the
// scrollbar.
@@ -191,14 +192,14 @@ class CORE_EXPORT Scrollbar : public GarbageCollectedFinalized<Scrollbar>,
// Promptly unregister from the theme manager + run finalizers of derived
// Scrollbars.
- EAGERLY_FINALIZE();
+ void Dispose();
virtual void Trace(blink::Visitor*);
protected:
void AutoscrollTimerFired(TimerBase*);
- void StartTimerIfNeeded(TimeDelta delay);
+ void StartTimerIfNeeded(base::TimeDelta delay);
void StopTimerIfNeeded();
- void AutoscrollPressedPart(TimeDelta delay);
+ void AutoscrollPressedPart(base::TimeDelta delay);
bool HandleTapGesture();
bool IsScrollGestureInjectionEnabled() const;
void InjectScrollGestureForPressedPart(WebInputEvent::Type gesture_type);
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 008b4bfdda5..715077449e0 100644
--- a/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme.cc
+++ b/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme.cc
@@ -27,6 +27,7 @@
#include "base/optional.h"
#include "build/build_config.h"
+#include "cc/input/scrollbar.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_mouse_event.h"
#include "third_party/blink/public/platform/web_point.h"
@@ -252,14 +253,14 @@ void ScrollbarTheme::PaintTickmarks(GraphicsContext& context,
#endif
}
-TimeDelta ScrollbarTheme::OverlayScrollbarFadeOutDelay() const {
+base::TimeDelta ScrollbarTheme::OverlayScrollbarFadeOutDelay() const {
// On Mac, fading is controlled by the painting code in ScrollAnimatorMac.
- return TimeDelta();
+ return base::TimeDelta();
}
-TimeDelta ScrollbarTheme::OverlayScrollbarFadeOutDuration() const {
+base::TimeDelta ScrollbarTheme::OverlayScrollbarFadeOutDuration() const {
// On Mac, fading is controlled by the painting code in ScrollAnimatorMac.
- return TimeDelta();
+ return base::TimeDelta();
}
int ScrollbarTheme::ThumbPosition(const Scrollbar& scrollbar,
@@ -362,12 +363,12 @@ void ScrollbarTheme::SplitTrack(const Scrollbar& scrollbar,
}
}
-TimeDelta ScrollbarTheme::InitialAutoscrollTimerDelay() {
- return TimeDelta::FromMilliseconds(250);
+base::TimeDelta ScrollbarTheme::InitialAutoscrollTimerDelay() {
+ return kInitialAutoscrollTimerDelay;
}
-TimeDelta ScrollbarTheme::AutoscrollTimerDelay() {
- return TimeDelta::FromMilliseconds(50);
+base::TimeDelta ScrollbarTheme::AutoscrollTimerDelay() {
+ return base::TimeDelta::FromSecondsD(1.f / kAutoscrollMultiplier);
}
ScrollbarTheme& ScrollbarTheme::DeprecatedStaticGetTheme() {
diff --git a/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme.h b/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme.h
index f78733d81d3..9aaa655aa52 100644
--- a/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme.h
+++ b/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme.h
@@ -117,8 +117,8 @@ class CORE_EXPORT ScrollbarTheme {
int ThumbPosition(const Scrollbar& scrollbar) {
return ThumbPosition(scrollbar, scrollbar.CurrentPos());
}
- virtual TimeDelta OverlayScrollbarFadeOutDelay() const;
- virtual TimeDelta OverlayScrollbarFadeOutDuration() const;
+ virtual base::TimeDelta OverlayScrollbarFadeOutDelay() const;
+ virtual base::TimeDelta OverlayScrollbarFadeOutDuration() const;
// The position the thumb would have, relative to the track, at the specified
// scroll position.
virtual int ThumbPosition(const Scrollbar&, float scroll_position);
@@ -181,8 +181,8 @@ class CORE_EXPORT ScrollbarTheme {
return std::numeric_limits<int>::max();
}
- virtual TimeDelta InitialAutoscrollTimerDelay();
- virtual TimeDelta AutoscrollTimerDelay();
+ virtual base::TimeDelta InitialAutoscrollTimerDelay();
+ virtual base::TimeDelta AutoscrollTimerDelay();
virtual IntRect ConstrainTrackRectToTrackPieces(const Scrollbar&,
const IntRect& rect) {
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 16ff4a8c287..7ddc6472464 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
@@ -53,8 +53,8 @@ class PLATFORM_EXPORT ScrollbarThemeMac : public ScrollbarTheme {
// Mac queues up scrollbar paint timers.
bool ShouldDisableInvisibleScrollbars() const override { return false; }
- TimeDelta InitialAutoscrollTimerDelay() override;
- TimeDelta AutoscrollTimerDelay() override;
+ base::TimeDelta InitialAutoscrollTimerDelay() override;
+ base::TimeDelta AutoscrollTimerDelay() override;
void PaintTickmarks(GraphicsContext&,
const Scrollbar&,
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 be8b87dfcd6..d74831d250f 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
@@ -168,12 +168,12 @@ bool ScrollbarThemeMac::ShouldCenterOnThumb(const Scrollbar& scrollbar,
ScrollbarThemeMac::~ScrollbarThemeMac() {
}
-TimeDelta ScrollbarThemeMac::InitialAutoscrollTimerDelay() {
- return TimeDelta::FromSecondsD(s_initial_button_delay);
+base::TimeDelta ScrollbarThemeMac::InitialAutoscrollTimerDelay() {
+ return base::TimeDelta::FromSecondsD(s_initial_button_delay);
}
-TimeDelta ScrollbarThemeMac::AutoscrollTimerDelay() {
- return TimeDelta::FromSecondsD(s_autoscroll_button_delay);
+base::TimeDelta ScrollbarThemeMac::AutoscrollTimerDelay() {
+ return base::TimeDelta::FromSecondsD(s_autoscroll_button_delay);
}
bool ScrollbarThemeMac::ShouldDragDocumentInsteadOfThumb(
diff --git a/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme_overlay.cc b/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme_overlay.cc
index 7258f03adbb..2fdf0676158 100644
--- a/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme_overlay.cc
+++ b/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme_overlay.cc
@@ -82,22 +82,22 @@ bool ScrollbarThemeOverlay::UsesOverlayScrollbars() const {
return true;
}
-TimeDelta ScrollbarThemeOverlay::OverlayScrollbarFadeOutDelay() const {
+base::TimeDelta ScrollbarThemeOverlay::OverlayScrollbarFadeOutDelay() const {
// TODO(bokan): Unit tests run without a theme engine. This is normally fine
// because they expect to use ScrollbarThemeMock which doesn't use a theme
// engine. If overlays are turned on though, this class is used even if mock
// scrollbars are on. We should either provide mock out a web theme engine for
// unit tests or provide a mock version of this class.
if (!Platform::Current()->ThemeEngine())
- return TimeDelta();
+ return base::TimeDelta();
WebThemeEngine::ScrollbarStyle style;
Platform::Current()->ThemeEngine()->GetOverlayScrollbarStyle(&style);
return style.fade_out_delay;
}
-TimeDelta ScrollbarThemeOverlay::OverlayScrollbarFadeOutDuration() const {
+base::TimeDelta ScrollbarThemeOverlay::OverlayScrollbarFadeOutDuration() const {
if (!Platform::Current()->ThemeEngine())
- return TimeDelta();
+ return base::TimeDelta();
WebThemeEngine::ScrollbarStyle style;
Platform::Current()->ThemeEngine()->GetOverlayScrollbarStyle(&style);
return style.fade_out_duration;
diff --git a/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme_overlay.h b/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme_overlay.h
index 2fecb975014..7ab2f4ad606 100644
--- a/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme_overlay.h
+++ b/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme_overlay.h
@@ -56,8 +56,8 @@ class CORE_EXPORT ScrollbarThemeOverlay : public ScrollbarTheme {
int ScrollbarThickness(ScrollbarControlSize) override;
int ScrollbarMargin() const override;
bool UsesOverlayScrollbars() const override;
- TimeDelta OverlayScrollbarFadeOutDelay() const override;
- TimeDelta OverlayScrollbarFadeOutDuration() const override;
+ base::TimeDelta OverlayScrollbarFadeOutDelay() const override;
+ base::TimeDelta OverlayScrollbarFadeOutDuration() const override;
int ThumbLength(const Scrollbar&) override;
diff --git a/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme_overlay_mock.h b/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme_overlay_mock.h
index 342bae0200f..ef3b6f2ee28 100644
--- a/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme_overlay_mock.h
+++ b/chromium/third_party/blink/renderer/core/scroll/scrollbar_theme_overlay_mock.h
@@ -40,12 +40,16 @@ class CORE_EXPORT ScrollbarThemeOverlayMock : public ScrollbarThemeOverlay {
ScrollbarThemeOverlayMock()
: ScrollbarThemeOverlay(3, 4, kDisallowHitTest, Color(128, 128, 128)) {}
- TimeDelta OverlayScrollbarFadeOutDelay() const override { return delay_; }
- TimeDelta OverlayScrollbarFadeOutDuration() const override {
- return TimeDelta();
+ base::TimeDelta OverlayScrollbarFadeOutDelay() const override {
+ return delay_;
+ }
+ base::TimeDelta OverlayScrollbarFadeOutDuration() const override {
+ return base::TimeDelta();
}
- void SetOverlayScrollbarFadeOutDelay(TimeDelta delay) { delay_ = delay; }
+ void SetOverlayScrollbarFadeOutDelay(base::TimeDelta delay) {
+ delay_ = delay;
+ }
void PaintThumb(GraphicsContext& gc,
const Scrollbar& scrollbar,
@@ -63,7 +67,7 @@ class CORE_EXPORT ScrollbarThemeOverlayMock : public ScrollbarThemeOverlay {
int MinimumThumbLength(const Scrollbar&) override { return 7; }
private:
- TimeDelta delay_;
+ base::TimeDelta delay_;
bool IsMockTheme() const final { return true; }
};
diff --git a/chromium/third_party/blink/renderer/core/scroll/scrolling_test.cc b/chromium/third_party/blink/renderer/core/scroll/scrolling_test.cc
new file mode 100644
index 00000000000..45e18070ca3
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/scroll/scrolling_test.cc
@@ -0,0 +1,323 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/scroll/scroll_animator.h"
+
+#include "base/test/bind_test_util.h"
+#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/frame/local_frame.h"
+#include "third_party/blink/renderer/core/frame/local_frame_view.h"
+#include "third_party/blink/renderer/core/frame/root_frame_viewport.h"
+#include "third_party/blink/renderer/core/frame/visual_viewport.h"
+#include "third_party/blink/renderer/core/geometry/dom_rect.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/scroll/scroll_animator_base.h"
+#include "third_party/blink/renderer/core/scroll/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/unit_test_helpers.h"
+
+namespace blink {
+
+class FractionalScrollSimTest : public SimTest {
+ public:
+ FractionalScrollSimTest() : fractional_scroll_offsets_for_test_(true) {}
+
+ private:
+ ScopedFractionalScrollOffsetsForTest fractional_scroll_offsets_for_test_;
+};
+
+TEST_F(FractionalScrollSimTest, GetBoundingClientRectAtFractional) {
+ WebView().MainFrameWidget()->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>
+ body, html {
+ margin: 0;
+ height: 2000px;
+ width: 2000px;
+ }
+ div {
+ position: absolute;
+ left: 800px;
+ top: 600px;
+ width: 100px;
+ height: 100px;
+ }
+ </style>
+ <body>
+ <div id="target"></div>
+ </body>
+ )HTML");
+ Compositor().BeginFrame();
+
+ // Scroll on the layout viewport.
+ GetDocument().View()->GetScrollableArea()->SetScrollOffset(
+ FloatSize(700.5f, 500.6f), kProgrammaticScroll, kScrollBehaviorInstant);
+
+ Compositor().BeginFrame();
+
+ Element* target = GetDocument().getElementById("target");
+ DOMRect* rect = target->getBoundingClientRect();
+ const float kOneLayoutUnit = 1.f / kFixedPointDenominator;
+ EXPECT_NEAR(LayoutUnit(800.f - 700.5f), rect->left(), kOneLayoutUnit);
+ EXPECT_NEAR(LayoutUnit(600.f - 500.6f), rect->top(), kOneLayoutUnit);
+}
+
+class ScrollAnimatorSimTest : public SimTest {};
+
+// Test that the callback of user scroll will be executed when the animation
+// finishes at ScrollAnimator::TickAnimation for root frame user scroll at the
+// layout viewport.
+TEST_F(ScrollAnimatorSimTest, TestRootFrameLayoutViewportUserScrollCallBack) {
+ GetDocument().GetFrame()->GetSettings()->SetScrollAnimatorEnabled(true);
+ WebView().MainFrameWidget()->Resize(WebSize(800, 500));
+ SimRequest request("https://example.com/test.html", "text/html");
+ LoadURL("https://example.com/test.html");
+ request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ body, html {
+ margin: 0;
+ height: 500vh;
+ }
+ </style>
+ <body>
+ </body>
+ )HTML");
+ Compositor().BeginFrame();
+
+ WebView().MainFrameWidget()->SetFocus(true);
+ WebView().SetIsActive(true);
+
+ // Scroll on the layout viewport.
+ bool finished = false;
+ GetDocument().View()->GetScrollableArea()->UserScroll(
+ ScrollGranularity::kScrollByLine, FloatSize(100, 300),
+ ScrollableArea::ScrollCallback(
+ base::BindLambdaForTesting([&]() { finished = true; })));
+
+ Compositor().BeginFrame();
+ ASSERT_FALSE(finished);
+
+ // The callback is executed when the animation finishes at
+ // ScrollAnimator::TickAnimation.
+ Compositor().BeginFrame();
+ Compositor().BeginFrame(0.3);
+ ASSERT_TRUE(finished);
+}
+
+// Test that the callback of user scroll will be executed when the animation
+// finishes at ScrollAnimator::TickAnimation for root frame user scroll at the
+// visual viewport.
+TEST_F(ScrollAnimatorSimTest, TestRootFrameVisualViewporUserScrollCallBack) {
+ GetDocument().GetFrame()->GetSettings()->SetScrollAnimatorEnabled(true);
+ WebView().MainFrameWidget()->Resize(WebSize(800, 500));
+ SimRequest request("https://example.com/test.html", "text/html");
+ LoadURL("https://example.com/test.html");
+ request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ body, html {
+ margin: 0;
+ height: 500vh;
+ }
+ </style>
+ <body>
+ </body>
+ )HTML");
+ Compositor().BeginFrame();
+
+ WebView().MainFrameWidget()->SetFocus(true);
+ WebView().SetIsActive(true);
+ WebView().SetPageScaleFactor(2);
+
+ // Scroll on the visual viewport.
+ bool finished = false;
+ GetDocument().View()->GetScrollableArea()->UserScroll(
+ ScrollGranularity::kScrollByLine, FloatSize(100, 300),
+ ScrollableArea::ScrollCallback(
+ base::BindLambdaForTesting([&]() { finished = true; })));
+
+ Compositor().BeginFrame();
+ ASSERT_FALSE(finished);
+
+ // The callback is executed when the animation finishes at
+ // ScrollAnimator::TickAnimation.
+ Compositor().BeginFrame();
+ Compositor().BeginFrame(0.3);
+ ASSERT_TRUE(finished);
+}
+
+// Test that the callback of user scroll will be executed when the animation
+// finishes at ScrollAnimator::TickAnimation for root frame user scroll at both
+// the layout and visual viewport.
+TEST_F(ScrollAnimatorSimTest, TestRootFrameBothViewporsUserScrollCallBack) {
+ GetDocument().GetFrame()->GetSettings()->SetScrollAnimatorEnabled(true);
+ WebView().MainFrameWidget()->Resize(WebSize(800, 500));
+ SimRequest request("https://example.com/test.html", "text/html");
+ LoadURL("https://example.com/test.html");
+ request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ body, html {
+ margin: 0;
+ height: 500vh;
+ }
+ </style>
+ <body>
+ </body>
+ )HTML");
+ Compositor().BeginFrame();
+
+ WebView().MainFrameWidget()->SetFocus(true);
+ WebView().SetIsActive(true);
+ WebView().SetPageScaleFactor(2);
+
+ // Scroll on both the layout and visual viewports.
+ bool finished = false;
+ GetDocument().View()->GetScrollableArea()->UserScroll(
+ ScrollGranularity::kScrollByLine, FloatSize(0, 1000),
+ ScrollableArea::ScrollCallback(
+ base::BindLambdaForTesting([&]() { finished = true; })));
+
+ Compositor().BeginFrame();
+ ASSERT_FALSE(finished);
+
+ // The callback is executed when the animation finishes at
+ // ScrollAnimator::TickAnimation.
+ Compositor().BeginFrame();
+ Compositor().BeginFrame(0.3);
+ ASSERT_TRUE(finished);
+}
+
+// Test that the callback of user scroll will be executed when the animation
+// finishes at ScrollAnimator::TickAnimation for div user scroll.
+TEST_F(ScrollAnimatorSimTest, TestDivUserScrollCallBack) {
+ GetDocument().GetSettings()->SetScrollAnimatorEnabled(true);
+ WebView().MainFrameWidget()->Resize(WebSize(800, 500));
+ SimRequest request("https://example.com/test.html", "text/html");
+ LoadURL("https://example.com/test.html");
+ request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ #scroller {
+ width: 100px;
+ height: 100px;
+ overflow: auto;
+ }
+ #overflow {
+ height: 500px;
+ width: 500px;
+ }
+ </style>
+ <div id="scroller">
+ <div id="overflow"></div>
+ </div>
+ )HTML");
+ Compositor().BeginFrame();
+
+ WebView().MainFrameWidget()->SetFocus(true);
+ WebView().SetIsActive(true);
+
+ Element* scroller = GetDocument().getElementById("scroller");
+
+ bool finished = false;
+ PaintLayerScrollableArea* scrollable_area =
+ ToLayoutBox(scroller->GetLayoutObject())->GetScrollableArea();
+ scrollable_area->UserScroll(
+ ScrollGranularity::kScrollByLine, FloatSize(0, 100),
+ ScrollableArea::ScrollCallback(
+ base::BindLambdaForTesting([&]() { finished = true; })));
+
+ Compositor().BeginFrame();
+ ASSERT_FALSE(finished);
+
+ // The callback is executed when the animation finishes at
+ // ScrollAnimator::TickAnimation.
+ Compositor().BeginFrame(0.3);
+ ASSERT_TRUE(finished);
+}
+
+// Test that the callback of user scroll will be executed in
+// ScrollAnimatorBase::UserScroll when animation is disabled.
+TEST_F(ScrollAnimatorSimTest, TestUserScrollCallBackAnimatorDisabled) {
+ GetDocument().GetFrame()->GetSettings()->SetScrollAnimatorEnabled(false);
+ WebView().MainFrameWidget()->Resize(WebSize(800, 500));
+ SimRequest request("https://example.com/test.html", "text/html");
+ LoadURL("https://example.com/test.html");
+ request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ body, html {
+ margin: 0;
+ height: 500vh;
+ }
+ </style>
+ <body>
+ </body>
+ )HTML");
+ Compositor().BeginFrame();
+
+ WebView().MainFrameWidget()->SetFocus(true);
+ WebView().SetIsActive(true);
+
+ bool finished = false;
+ GetDocument().View()->GetScrollableArea()->UserScroll(
+ ScrollGranularity::kScrollByLine, FloatSize(0, 300),
+ ScrollableArea::ScrollCallback(
+ base::BindLambdaForTesting([&]() { finished = true; })));
+ Compositor().BeginFrame();
+ ASSERT_TRUE(finished);
+}
+
+// Test that the callback of user scroll will be executed when the animation is
+// canceled because performing a programmatic scroll in the middle of a user
+// scroll will cancel the animation.
+TEST_F(ScrollAnimatorSimTest, TestRootFrameUserScrollCallBackCancelAnimation) {
+ GetDocument().GetFrame()->GetSettings()->SetScrollAnimatorEnabled(true);
+ WebView().MainFrameWidget()->Resize(WebSize(800, 500));
+ SimRequest request("https://example.com/test.html", "text/html");
+ LoadURL("https://example.com/test.html");
+ request.Complete(R"HTML(
+ <!DOCTYPE html>
+ <style>
+ body, html {
+ margin: 0;
+ height: 500vh;
+ }
+ </style>
+ <body>
+ </body>
+ )HTML");
+ Compositor().BeginFrame();
+
+ WebView().MainFrameWidget()->SetFocus(true);
+ WebView().SetIsActive(true);
+
+ // Scroll on the layout viewport.
+ bool finished = false;
+ GetDocument().View()->GetScrollableArea()->UserScroll(
+ ScrollGranularity::kScrollByLine, FloatSize(100, 300),
+ ScrollableArea::ScrollCallback(
+ base::BindLambdaForTesting([&]() { finished = true; })));
+
+ Compositor().BeginFrame();
+ ASSERT_FALSE(finished);
+
+ // Programmatic scroll will cancel the current user scroll animation and the
+ // callback will be executed.
+ GetDocument().View()->GetScrollableArea()->SetScrollOffset(
+ ScrollOffset(0, 300), kProgrammaticScroll, kScrollBehaviorSmooth,
+ ScrollableArea::ScrollCallback());
+ Compositor().BeginFrame();
+ ASSERT_TRUE(finished);
+}
+
+} // 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 24a5a0577bc..e747d5e73ac 100644
--- a/chromium/third_party/blink/renderer/core/streams/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/streams/BUILD.gn
@@ -6,12 +6,18 @@ import("//third_party/blink/renderer/core/core.gni")
blink_core_sources("streams") {
sources = [
+ "byte_length_queuing_strategy.cc",
+ "byte_length_queuing_strategy.h",
+ "count_queuing_strategy.cc",
+ "count_queuing_strategy.h",
"miscellaneous_operations.cc",
"miscellaneous_operations.h",
"promise_handler.cc",
"promise_handler.h",
"queue_with_sizes.cc",
"queue_with_sizes.h",
+ "queuing_strategy_common.cc",
+ "queuing_strategy_common.h",
"readable_stream.cc",
"readable_stream.h",
"readable_stream_default_controller.cc",
@@ -30,6 +36,8 @@ blink_core_sources("streams") {
"stream_algorithms.h",
"stream_promise_resolver.cc",
"stream_promise_resolver.h",
+ "transferable_streams.cc",
+ "transferable_streams.h",
"transform_stream.cc",
"transform_stream.h",
"transform_stream_default_controller.cc",
diff --git a/chromium/third_party/blink/renderer/core/streams/README.md b/chromium/third_party/blink/renderer/core/streams/README.md
index 68569248bdf..1b845c20ec1 100644
--- a/chromium/third_party/blink/renderer/core/streams/README.md
+++ b/chromium/third_party/blink/renderer/core/streams/README.md
@@ -26,6 +26,8 @@ feature. The following files are part of the new implementation:
writable_stream_default_writer.idl
writable_stream_native.cc
writable_stream_native.h
+ transferable_streams.cc
+ transferable_streams.h
transform_stream_default_controller.cc
transform_stream_default_controller.h
transform_stream_native.cc
diff --git a/chromium/third_party/blink/renderer/core/streams/ReadableStream.js b/chromium/third_party/blink/renderer/core/streams/ReadableStream.js
index 797fe38d9b5..b34ad33e09d 100644
--- a/chromium/third_party/blink/renderer/core/streams/ReadableStream.js
+++ b/chromium/third_party/blink/renderer/core/streams/ReadableStream.js
@@ -38,7 +38,6 @@
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(
'[[strategySizeAlgorithm]]');
const _pullAlgorithm = v8.createPrivateSymbol('[[pullAlgorithm]]');
@@ -47,9 +46,6 @@
const CLOSE_REQUESTED = 0b10;
const PULLING = 0b100;
const PULL_AGAIN = 0b1000;
- // TODO(ricea): Remove this once blink::UnderlyingSourceBase no longer needs
- // it.
- const BLINK_LOCK_NOTIFICATIONS = 0b10000;
const ObjectCreate = global.Object.create;
@@ -127,10 +123,10 @@
// CreateReadableStream.
constructor(underlyingSource = {}, strategy = {},
internalArgument = undefined) {
- const enableBlinkLockNotifications =
+ const createdByUA =
internalArgument === createWithExternalControllerSentinel;
- if (!useCounted && !enableBlinkLockNotifications) {
+ if (!useCounted && !createdByUA) {
binding.countUse('ReadableStreamConstructor');
useCounted = true;
}
@@ -157,8 +153,7 @@
highWaterMark = ValidateAndNormalizeHighWaterMark(highWaterMark);
SetUpReadableStreamDefaultControllerFromUnderlyingSource(
- this, underlyingSource, highWaterMark, sizeAlgorithm,
- enableBlinkLockNotifications);
+ this, underlyingSource, highWaterMark, sizeAlgorithm);
}
}
@@ -381,11 +376,8 @@
return new ReadableStreamDefaultReader(stream);
}
- // The non-standard boolean |enableBlinkLockNotifications| argument indicates
- // whether the stream is being created from C++.
function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm,
- highWaterMark, sizeAlgorithm,
- enableBlinkLockNotifications) {
+ highWaterMark, sizeAlgorithm) {
if (highWaterMark === undefined) {
highWaterMark = 1;
}
@@ -399,7 +391,7 @@
const controller = ObjectCreate(ReadableStreamDefaultController_prototype);
SetUpReadableStreamDefaultController(
stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm,
- highWaterMark, sizeAlgorithm, enableBlinkLockNotifications);
+ highWaterMark, sizeAlgorithm);
return stream;
}
@@ -490,11 +482,9 @@
const startAlgorithm = () => undefined;
const branch1Stream = CreateReadableStream(
- startAlgorithm, pullAlgorithm, cancel1Algorithm, undefined, undefined,
- false);
+ startAlgorithm, pullAlgorithm, cancel1Algorithm);
const branch2Stream = CreateReadableStream(
- startAlgorithm, pullAlgorithm, cancel2Algorithm, undefined, undefined,
- false);
+ startAlgorithm, pullAlgorithm, cancel2Algorithm);
const branch1controller = branch1Stream[_controller];
const branch2controller = branch2Stream[_controller];
@@ -695,17 +685,6 @@
}
function ReadableStreamReaderGenericInitialize(reader, stream) {
- // TODO(yhirano): Remove this when we don't need hasPendingActivity in
- // blink::UnderlyingSourceBase.
- const controller = stream[_controller];
- if (controller[_readableStreamDefaultControllerBits] &
- BLINK_LOCK_NOTIFICATIONS) {
- // The stream is created with an external controller (i.e. made in
- // Blink).
- const lockNotifyTarget = controller[_lockNotifyTarget];
- callFunction(lockNotifyTarget.notifyLockAcquired, lockNotifyTarget);
- }
-
reader[_ownerReadableStream] = stream;
stream[_reader] = reader;
@@ -724,17 +703,6 @@
}
function ReadableStreamReaderGenericRelease(reader) {
- // TODO(yhirano): Remove this when we don't need hasPendingActivity in
- // blink::UnderlyingSourceBase.
- const controller = reader[_ownerReadableStream][_controller];
- if (controller[_readableStreamDefaultControllerBits] &
- BLINK_LOCK_NOTIFICATIONS) {
- // The stream is created with an external controller (i.e. made in
- // Blink).
- const lockNotifyTarget = controller[_lockNotifyTarget];
- callFunction(lockNotifyTarget.notifyLockReleased, lockNotifyTarget);
- }
-
if (ReadableStreamGetState(reader[_ownerReadableStream]) ===
STATE_READABLE) {
rejectPromise(
@@ -1000,12 +968,10 @@
function SetUpReadableStreamDefaultController(
stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm,
- highWaterMark, sizeAlgorithm, enableBlinkLockNotifications) {
+ highWaterMark, sizeAlgorithm) {
controller[_controlledReadableStream] = stream;
controller[_queue] = new binding.SimpleQueue();
controller[_queueTotalSize] = 0;
- controller[_readableStreamDefaultControllerBits] =
- enableBlinkLockNotifications ? BLINK_LOCK_NOTIFICATIONS : 0b0;
controller[_strategySizeAlgorithm] = sizeAlgorithm;
controller[_strategyHWM] = highWaterMark;
controller[_pullAlgorithm] = pullAlgorithm;
@@ -1019,8 +985,7 @@
}
function SetUpReadableStreamDefaultControllerFromUnderlyingSource(
- stream, underlyingSource, highWaterMark, sizeAlgorithm,
- enableBlinkLockNotifications) {
+ stream, underlyingSource, highWaterMark, sizeAlgorithm) {
const controller = ObjectCreate(ReadableStreamDefaultController_prototype);
const startAlgorithm =
() => CallOrNoop1(underlyingSource, 'start', controller,
@@ -1029,13 +994,9 @@
underlyingSource, 'pull', 0, controller, 'underlyingSource.pull');
const cancelAlgorithm = CreateAlgorithmFromUnderlyingMethod(
underlyingSource, 'cancel', 1, 'underlyingSource.cancel');
- // TODO(ricea): Remove this once C++ API has been updated.
- if (enableBlinkLockNotifications) {
- controller[_lockNotifyTarget] = underlyingSource;
- }
SetUpReadableStreamDefaultController(
stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm,
- highWaterMark, sizeAlgorithm, enableBlinkLockNotifications);
+ highWaterMark, sizeAlgorithm);
}
//
diff --git a/chromium/third_party/blink/renderer/core/streams/TransformStream.js b/chromium/third_party/blink/renderer/core/streams/TransformStream.js
index 4b7449584a9..639be9b30f1 100644
--- a/chromium/third_party/blink/renderer/core/streams/TransformStream.js
+++ b/chromium/third_party/blink/renderer/core/streams/TransformStream.js
@@ -193,7 +193,7 @@
};
stream[_readable] = binding.CreateReadableStream(
startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,
- readableSizeAlgorithm, false);
+ readableSizeAlgorithm);
stream[_backpressure] = undefined;
stream[_backpressureChangePromise] = undefined;
TransformStreamSetBackpressure(stream, true);
diff --git a/chromium/third_party/blink/renderer/core/streams/byte_length_queuing_strategy.cc b/chromium/third_party/blink/renderer/core/streams/byte_length_queuing_strategy.cc
new file mode 100644
index 00000000000..aae8fb8bc29
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/streams/byte_length_queuing_strategy.cc
@@ -0,0 +1,101 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/streams/byte_length_queuing_strategy.h"
+
+#include "third_party/blink/renderer/bindings/core/v8/script_function.h"
+#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
+#include "third_party/blink/renderer/core/streams/queuing_strategy_common.h"
+#include "third_party/blink/renderer/core/streams/queuing_strategy_init.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/visitor.h"
+
+namespace blink {
+
+namespace {
+
+class ByteLengthQueuingStrategySizeFunction final : public ScriptFunction {
+ public:
+ static v8::Local<v8::Function> CreateFunction(ScriptState* script_state) {
+ ByteLengthQueuingStrategySizeFunction* self =
+ MakeGarbageCollected<ByteLengthQueuingStrategySizeFunction>(
+ script_state);
+ return self->BindToV8Function();
+ }
+
+ explicit ByteLengthQueuingStrategySizeFunction(ScriptState* script_state)
+ : ScriptFunction(script_state) {}
+
+ private:
+ void CallRaw(const v8::FunctionCallbackInfo<v8::Value>& args) override {
+ auto* isolate = args.GetIsolate();
+ DCHECK_EQ(isolate, GetScriptState()->GetIsolate());
+ auto context = GetScriptState()->GetContext();
+ v8::Local<v8::Value> chunk;
+ if (args.Length() < 1) {
+ chunk = v8::Undefined(isolate);
+ } else {
+ chunk = args[0];
+ }
+
+ // https://streams.spec.whatwg.org/#blqs-size
+ // 1. Return ? GetV(chunk, "byteLength").
+
+ // https://tc39.es/ecma262/#sec-getv
+ // 1. Assert: IsPropertyKey(P) is true.
+ // 2. Let O be ? ToObject(V).
+ v8::Local<v8::Object> chunk_as_object;
+ if (!chunk->ToObject(context).ToLocal(&chunk_as_object)) {
+ // Should have thrown an exception, which will be caught further up the
+ // stack.
+ return;
+ }
+ // 3. Return ? O.[[Get]](P, V).
+ v8::Local<v8::Value> byte_length;
+ if (!chunk_as_object->Get(context, V8AtomicString(isolate, "byteLength"))
+ .ToLocal(&byte_length)) {
+ // Should have thrown an exception.
+ return;
+ }
+ args.GetReturnValue().Set(byte_length);
+ }
+};
+
+} // namespace
+
+ByteLengthQueuingStrategy* ByteLengthQueuingStrategy::Create(
+ ScriptState* script_state,
+ const QueuingStrategyInit* init) {
+ return MakeGarbageCollected<ByteLengthQueuingStrategy>(script_state, init);
+}
+
+ByteLengthQueuingStrategy::ByteLengthQueuingStrategy(
+ ScriptState* script_state,
+ const QueuingStrategyInit* init)
+ : high_water_mark_(script_state->GetIsolate(),
+ HighWaterMarkOrUndefined(script_state, init)) {}
+
+ByteLengthQueuingStrategy::~ByteLengthQueuingStrategy() = default;
+
+ScriptValue ByteLengthQueuingStrategy::highWaterMark(
+ ScriptState* script_state) const {
+ return ScriptValue(script_state,
+ high_water_mark_.NewLocal(script_state->GetIsolate()));
+}
+
+ScriptValue ByteLengthQueuingStrategy::size(ScriptState* script_state) const {
+ // We don't cache the result because normally this method will only be called
+ // once anyway.
+ return ScriptValue(
+ script_state,
+ ByteLengthQueuingStrategySizeFunction::CreateFunction(script_state));
+}
+
+void ByteLengthQueuingStrategy::Trace(Visitor* visitor) {
+ visitor->Trace(high_water_mark_);
+ ScriptWrappable::Trace(visitor);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/streams/byte_length_queuing_strategy.h b/chromium/third_party/blink/renderer/core/streams/byte_length_queuing_strategy.h
new file mode 100644
index 00000000000..c1544212c8a
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/streams/byte_length_queuing_strategy.h
@@ -0,0 +1,41 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_BYTE_LENGTH_QUEUING_STRATEGY_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_BYTE_LENGTH_QUEUING_STRATEGY_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 QueuingStrategyInit;
+class ScriptState;
+class ScriptValue;
+class Visitor;
+
+// https://streams.spec.whatwg.org/#blqs-class
+class ByteLengthQueuingStrategy final : public ScriptWrappable {
+ DEFINE_WRAPPERTYPEINFO();
+
+ public:
+ static ByteLengthQueuingStrategy* Create(ScriptState*,
+ const QueuingStrategyInit*);
+
+ ByteLengthQueuingStrategy(ScriptState*, const QueuingStrategyInit*);
+ ~ByteLengthQueuingStrategy() override;
+
+ ScriptValue highWaterMark(ScriptState*) const;
+ ScriptValue size(ScriptState*) const;
+
+ void Trace(Visitor*) override;
+
+ private:
+ const TraceWrapperV8Reference<v8::Value> high_water_mark_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_BYTE_LENGTH_QUEUING_STRATEGY_H_
diff --git a/chromium/third_party/blink/renderer/core/streams/byte_length_queuing_strategy.idl b/chromium/third_party/blink/renderer/core/streams/byte_length_queuing_strategy.idl
new file mode 100644
index 00000000000..af68396eb0e
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/streams/byte_length_queuing_strategy.idl
@@ -0,0 +1,17 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// https://streams.spec.whatwg.org/#blqs-class
+
+[
+ Exposed=(Window,Worker,Worklet),
+ RuntimeEnabled=StreamsNative,
+ ConstructorCallWith=ScriptState,
+ Constructor([PermissiveDictionaryConversion] QueuingStrategyInit init)
+] interface ByteLengthQueuingStrategy {
+ [CallWith=ScriptState] readonly attribute any highWaterMark;
+
+ // size is an accessor that returns a function.
+ [CallWith=ScriptState] readonly attribute any size;
+};
diff --git a/chromium/third_party/blink/renderer/core/streams/count_queuing_strategy.cc b/chromium/third_party/blink/renderer/core/streams/count_queuing_strategy.cc
new file mode 100644
index 00000000000..2b1aa3b9c24
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/streams/count_queuing_strategy.cc
@@ -0,0 +1,72 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/streams/count_queuing_strategy.h"
+
+#include "third_party/blink/renderer/bindings/core/v8/script_function.h"
+#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
+#include "third_party/blink/renderer/core/streams/queuing_strategy_common.h"
+#include "third_party/blink/renderer/core/streams/queuing_strategy_init.h"
+#include "third_party/blink/renderer/platform/bindings/script_state.h"
+#include "third_party/blink/renderer/platform/heap/visitor.h"
+
+namespace blink {
+
+namespace {
+
+class CountQueuingStrategySizeFunction final : public ScriptFunction {
+ public:
+ static v8::Local<v8::Function> CreateFunction(ScriptState* script_state) {
+ CountQueuingStrategySizeFunction* self =
+ MakeGarbageCollected<CountQueuingStrategySizeFunction>(script_state);
+ return self->BindToV8Function();
+ }
+
+ explicit CountQueuingStrategySizeFunction(ScriptState* script_state)
+ : ScriptFunction(script_state) {}
+
+ private:
+ void CallRaw(const v8::FunctionCallbackInfo<v8::Value>& args) override {
+ // https://streams.spec.whatwg.org/#cqs-size
+ // 1. Return 1.
+ args.GetReturnValue().Set(
+ v8::Integer::New(GetScriptState()->GetIsolate(), 1));
+ }
+};
+
+} // namespace
+
+CountQueuingStrategy* CountQueuingStrategy::Create(
+ ScriptState* script_state,
+ const QueuingStrategyInit* init) {
+ return MakeGarbageCollected<CountQueuingStrategy>(script_state, init);
+}
+
+CountQueuingStrategy::CountQueuingStrategy(ScriptState* script_state,
+ const QueuingStrategyInit* init)
+ : high_water_mark_(script_state->GetIsolate(),
+ HighWaterMarkOrUndefined(script_state, init)) {}
+
+CountQueuingStrategy::~CountQueuingStrategy() = default;
+
+ScriptValue CountQueuingStrategy::highWaterMark(
+ ScriptState* script_state) const {
+ return ScriptValue(script_state,
+ high_water_mark_.NewLocal(script_state->GetIsolate()));
+}
+
+ScriptValue CountQueuingStrategy::size(ScriptState* script_state) const {
+ // We don't cache the result because normally this method will only be called
+ // once anyway.
+ return ScriptValue(
+ script_state,
+ CountQueuingStrategySizeFunction::CreateFunction(script_state));
+}
+
+void CountQueuingStrategy::Trace(Visitor* visitor) {
+ visitor->Trace(high_water_mark_);
+ ScriptWrappable::Trace(visitor);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/streams/count_queuing_strategy.h b/chromium/third_party/blink/renderer/core/streams/count_queuing_strategy.h
new file mode 100644
index 00000000000..246c4599d14
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/streams/count_queuing_strategy.h
@@ -0,0 +1,40 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_COUNT_QUEUING_STRATEGY_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_COUNT_QUEUING_STRATEGY_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 QueuingStrategyInit;
+class ScriptState;
+class ScriptValue;
+class Visitor;
+
+// https://streams.spec.whatwg.org/#blqs-class
+class CountQueuingStrategy final : public ScriptWrappable {
+ DEFINE_WRAPPERTYPEINFO();
+
+ public:
+ static CountQueuingStrategy* Create(ScriptState*, const QueuingStrategyInit*);
+
+ CountQueuingStrategy(ScriptState*, const QueuingStrategyInit*);
+ ~CountQueuingStrategy() override;
+
+ ScriptValue highWaterMark(ScriptState*) const;
+ ScriptValue size(ScriptState*) const;
+
+ void Trace(Visitor*) override;
+
+ private:
+ const TraceWrapperV8Reference<v8::Value> high_water_mark_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_COUNT_QUEUING_STRATEGY_H_
diff --git a/chromium/third_party/blink/renderer/core/streams/count_queuing_strategy.idl b/chromium/third_party/blink/renderer/core/streams/count_queuing_strategy.idl
new file mode 100644
index 00000000000..02cfe7a9715
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/streams/count_queuing_strategy.idl
@@ -0,0 +1,17 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// https://streams.spec.whatwg.org/#cqs-class
+
+[
+ Exposed=(Window,Worker,Worklet),
+ RuntimeEnabled=StreamsNative,
+ ConstructorCallWith=ScriptState,
+ Constructor([PermissiveDictionaryConversion] QueuingStrategyInit init)
+] interface CountQueuingStrategy {
+ [CallWith=ScriptState] readonly attribute any highWaterMark;
+
+ // size is an accessor that returns a function.
+ [CallWith=ScriptState] readonly attribute any size;
+};
diff --git a/chromium/third_party/blink/renderer/core/streams/miscellaneous_operations.h b/chromium/third_party/blink/renderer/core/streams/miscellaneous_operations.h
index f490157e2e2..8d715102122 100644
--- a/chromium/third_party/blink/renderer/core/streams/miscellaneous_operations.h
+++ b/chromium/third_party/blink/renderer/core/streams/miscellaneous_operations.h
@@ -7,7 +7,7 @@
#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/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "v8/include/v8.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/streams/miscellaneous_operations_test.cc b/chromium/third_party/blink/renderer/core/streams/miscellaneous_operations_test.cc
index c21a934ed4a..9a8e28b4895 100644
--- a/chromium/third_party/blink/renderer/core/streams/miscellaneous_operations_test.cc
+++ b/chromium/third_party/blink/renderer/core/streams/miscellaneous_operations_test.cc
@@ -97,7 +97,8 @@ v8::Local<v8::Value> CreateFromFunctionAndGetResult(
int argc = 0,
v8::Local<v8::Value> argv[] = nullptr) {
String js = String("({start: ") + function_definition + "})" + '\0';
- ScriptValue underlying_value = EvalWithPrintingError(scope, js.Utf8().data());
+ ScriptValue underlying_value =
+ EvalWithPrintingError(scope, js.Utf8().c_str());
auto underlying_object = underlying_value.V8Value().As<v8::Object>();
auto* algo = CreateAlgorithmFromUnderlyingMethod(
scope->GetScriptState(), underlying_object, "start",
diff --git a/chromium/third_party/blink/renderer/core/streams/queuing_strategy_common.cc b/chromium/third_party/blink/renderer/core/streams/queuing_strategy_common.cc
new file mode 100644
index 00000000000..4441a896a38
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/streams/queuing_strategy_common.cc
@@ -0,0 +1,23 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/streams/queuing_strategy_common.h"
+
+#include "third_party/blink/renderer/core/streams/queuing_strategy_init.h"
+#include "third_party/blink/renderer/platform/bindings/script_state.h"
+
+namespace blink {
+
+v8::Local<v8::Value> HighWaterMarkOrUndefined(ScriptState* script_state,
+ const QueuingStrategyInit* init) {
+ v8::Local<v8::Value> high_water_mark;
+ if (init->hasHighWaterMark()) {
+ high_water_mark = init->highWaterMark().V8Value();
+ } else {
+ high_water_mark = v8::Undefined(script_state->GetIsolate());
+ }
+ return high_water_mark;
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/streams/queuing_strategy_common.h b/chromium/third_party/blink/renderer/core/streams/queuing_strategy_common.h
new file mode 100644
index 00000000000..d62e6a866f1
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/streams/queuing_strategy_common.h
@@ -0,0 +1,20 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_QUEUING_STRATEGY_COMMON_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_QUEUING_STRATEGY_COMMON_H_
+
+#include "v8/include/v8.h"
+
+namespace blink {
+
+class ScriptState;
+class QueuingStrategyInit;
+
+v8::Local<v8::Value> HighWaterMarkOrUndefined(ScriptState* script_state,
+ const QueuingStrategyInit* init);
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_QUEUING_STRATEGY_COMMON_H_
diff --git a/chromium/third_party/blink/renderer/core/streams/queuing_strategy_init.idl b/chromium/third_party/blink/renderer/core/streams/queuing_strategy_init.idl
new file mode 100644
index 00000000000..7d5bd0c511e
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/streams/queuing_strategy_init.idl
@@ -0,0 +1,10 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// https://streams.spec.whatwg.org/#cqs-class
+
+[PermissiveDictionaryConversion]
+dictionary QueuingStrategyInit {
+ any highWaterMark;
+};
diff --git a/chromium/third_party/blink/renderer/core/streams/readable_stream.cc b/chromium/third_party/blink/renderer/core/streams/readable_stream.cc
index 8b787d62af1..e1088481c4a 100644
--- a/chromium/third_party/blink/renderer/core/streams/readable_stream.cc
+++ b/chromium/third_party/blink/renderer/core/streams/readable_stream.cc
@@ -60,11 +60,9 @@ ReadableStream* ReadableStream::CreateWithCountQueueingStrategy(
ReadableStream* ReadableStream::Deserialize(ScriptState* script_state,
MessagePort* port,
ExceptionState& exception_state) {
- // TODO(ricea): Implementation serialization for the native implementation.
if (RuntimeEnabledFeatures::StreamsNativeEnabled()) {
- exception_state.ThrowTypeError(
- "serialization disabled because StreamsNative feature is enabled");
- return nullptr;
+ return ReadableStreamNative::Deserialize(script_state, port,
+ exception_state);
}
return ReadableStreamWrapper::Deserialize(script_state, port,
diff --git a/chromium/third_party/blink/renderer/core/streams/readable_stream_default_controller.cc b/chromium/third_party/blink/renderer/core/streams/readable_stream_default_controller.cc
index b5fca428366..653cab070a3 100644
--- a/chromium/third_party/blink/renderer/core/streams/readable_stream_default_controller.cc
+++ b/chromium/third_party/blink/renderer/core/streams/readable_stream_default_controller.cc
@@ -271,7 +271,6 @@ void ReadableStreamDefaultController::Trace(Visitor* visitor) {
visitor->Trace(pull_algorithm_);
visitor->Trace(queue_);
visitor->Trace(strategy_size_algorithm_);
- visitor->Trace(lock_notify_target_);
ScriptWrappable::Trace(visitor);
}
@@ -494,7 +493,6 @@ void ReadableStreamDefaultController::SetUp(
StreamAlgorithm* cancel_algorithm,
double high_water_mark,
StrategySizeAlgorithm* size_algorithm,
- bool enable_blink_lock_notifications,
ExceptionState& exception_state) {
// https://streams.spec.whatwg.org/#set-up-readable-stream-default-controller
// 1. Assert: stream.[[readableStreamController]] is undefined.
@@ -510,10 +508,6 @@ void ReadableStreamDefaultController::SetUp(
DCHECK(controller->queue_->IsEmpty());
DCHECK_EQ(controller->queue_->TotalSize(), 0);
- // Not part of the standard.
- controller->enable_blink_lock_notifications_ =
- enable_blink_lock_notifications;
-
// 5. Set controller.[[strategySizeAlgorithm]] to sizeAlgorithm and
// controller.[[strategyHWM]] to highWaterMark.
controller->strategy_size_algorithm_ = size_algorithm;
@@ -610,7 +604,6 @@ void ReadableStreamDefaultController::SetUpFromUnderlyingSource(
v8::Local<v8::Object> underlying_source,
double high_water_mark,
StrategySizeAlgorithm* size_algorithm,
- bool enable_blink_lock_notifications,
ExceptionState& exception_state) {
// https://streams.spec.whatwg.org/#set-up-readable-stream-default-controller-from-underlying-source
// 2. Let controller be ObjectCreate(the original value of
@@ -646,18 +639,11 @@ void ReadableStreamDefaultController::SetUpFromUnderlyingSource(
return;
}
- // TODO(ricea): Remove this once C++ API has been updated.
- if (enable_blink_lock_notifications) {
- controller->lock_notify_target_.Set(script_state->GetIsolate(),
- underlying_source);
- }
-
// 6. Perform ? SetUpReadableStreamDefaultController(stream, controller,
// startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark,
// sizeAlgorithm).
SetUp(script_state, stream, controller, start_algorithm, pull_algorithm,
- cancel_algorithm, high_water_mark, size_algorithm,
- enable_blink_lock_notifications, exception_state);
+ cancel_algorithm, high_water_mark, size_algorithm, exception_state);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/streams/readable_stream_default_controller.h b/chromium/third_party/blink/renderer/core/streams/readable_stream_default_controller.h
index 14e8becff8f..0a14d943b82 100644
--- a/chromium/third_party/blink/renderer/core/streams/readable_stream_default_controller.h
+++ b/chromium/third_party/blink/renderer/core/streams/readable_stream_default_controller.h
@@ -100,7 +100,6 @@ class ReadableStreamDefaultController : public ScriptWrappable {
StreamAlgorithm* cancel_algorithm,
double high_water_mark,
StrategySizeAlgorithm* size_algorithm,
- bool enable_blink_lock_notifications,
ExceptionState&);
// https://streams.spec.whatwg.org/#set-up-readable-stream-default-controller-from-underlying-source
@@ -109,7 +108,6 @@ class ReadableStreamDefaultController : public ScriptWrappable {
v8::Local<v8::Object> underlying_source,
double high_water_mark,
StrategySizeAlgorithm* size_algorithm,
- bool enable_blink_lock_notifications,
ExceptionState&);
// Boolean flags are grouped together to reduce object size. Verbs have been
@@ -118,14 +116,12 @@ class ReadableStreamDefaultController : public ScriptWrappable {
bool will_pull_again_ = false;
bool is_pulling_ = false;
bool is_started_ = false;
- bool enable_blink_lock_notifications_ = false;
Member<StreamAlgorithm> cancel_algorithm_;
Member<ReadableStreamNative> controlled_readable_stream_;
Member<StreamAlgorithm> pull_algorithm_;
Member<QueueWithSizes> queue_;
double strategy_high_water_mark_ = 0.0;
Member<StrategySizeAlgorithm> strategy_size_algorithm_;
- TraceWrapperV8Reference<v8::Object> lock_notify_target_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/streams/readable_stream_default_controller_interface.cc b/chromium/third_party/blink/renderer/core/streams/readable_stream_default_controller_interface.cc
index 6abdedafe86..91fe704295a 100644
--- a/chromium/third_party/blink/renderer/core/streams/readable_stream_default_controller_interface.cc
+++ b/chromium/third_party/blink/renderer/core/streams/readable_stream_default_controller_interface.cc
@@ -31,8 +31,6 @@ class ReadableStreamDefaultControllerWrapper final
// (close/desiredSize/enqueue/error will become no-ops afterward.)
void NoteHasBeenCanceled() override { js_controller_.Clear(); }
- bool IsActive() const override { return !js_controller_.IsEmpty(); }
-
void Close() override {
ScriptState* script_state = script_state_;
// This will assert that the context is valid; do not call this method when
@@ -129,8 +127,6 @@ class ReadableStreamDefaultControllerNative final
void NoteHasBeenCanceled() override { controller_ = nullptr; }
- bool IsActive() const override { return controller_; }
-
void Close() override {
if (!controller_)
return;
@@ -138,6 +134,7 @@ class ReadableStreamDefaultControllerNative final
ScriptState::Scope scope(script_state_);
ReadableStreamDefaultController::Close(script_state_, controller_);
+ controller_ = nullptr;
}
double DesiredSize() const override {
@@ -173,6 +170,7 @@ class ReadableStreamDefaultControllerNative final
ReadableStreamDefaultController::Error(script_state_, controller_,
js_error);
+ controller_ = nullptr;
}
void Trace(Visitor* visitor) override {
diff --git a/chromium/third_party/blink/renderer/core/streams/readable_stream_default_controller_interface.h b/chromium/third_party/blink/renderer/core/streams/readable_stream_default_controller_interface.h
index bfdb80447cb..7d859463d8c 100644
--- a/chromium/third_party/blink/renderer/core/streams/readable_stream_default_controller_interface.h
+++ b/chromium/third_party/blink/renderer/core/streams/readable_stream_default_controller_interface.h
@@ -33,7 +33,6 @@ class CORE_EXPORT ReadableStreamDefaultControllerInterface
// (Close/DesiredSize/Enqueue/Error will become no-ops afterward.)
virtual void NoteHasBeenCanceled() = 0;
- virtual bool IsActive() const = 0;
virtual void Close() = 0;
virtual double DesiredSize() const = 0;
virtual void Enqueue(v8::Local<v8::Value> js_chunk) const = 0;
diff --git a/chromium/third_party/blink/renderer/core/streams/readable_stream_native.cc b/chromium/third_party/blink/renderer/core/streams/readable_stream_native.cc
index 4567ec4b712..632ea367d68 100644
--- a/chromium/third_party/blink/renderer/core/streams/readable_stream_native.cc
+++ b/chromium/third_party/blink/renderer/core/streams/readable_stream_native.cc
@@ -8,7 +8,6 @@
#include "third_party/blink/renderer/bindings/core/v8/script_function.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_iterator_result_value.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/frame/web_feature.h"
#include "third_party/blink/renderer/core/streams/miscellaneous_operations.h"
#include "third_party/blink/renderer/core/streams/promise_handler.h"
@@ -16,6 +15,7 @@
#include "third_party/blink/renderer/core/streams/readable_stream_reader.h"
#include "third_party/blink/renderer/core/streams/stream_algorithms.h"
#include "third_party/blink/renderer/core/streams/stream_promise_resolver.h"
+#include "third_party/blink/renderer/core/streams/transferable_streams.h"
#include "third_party/blink/renderer/core/streams/underlying_source_base.h"
#include "third_party/blink/renderer/core/streams/writable_stream_default_controller.h"
#include "third_party/blink/renderer/core/streams/writable_stream_default_writer.h"
@@ -25,18 +25,12 @@
#include "third_party/blink/renderer/platform/bindings/v8_binding.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
#include "third_party/blink/renderer/platform/heap/visitor.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
#include "third_party/blink/renderer/platform/wtf/deque.h"
namespace blink {
-struct ReadableStreamNative::PipeOptions {
- PipeOptions() = default;
- bool prevent_close = false;
- bool prevent_abort = false;
- bool prevent_cancel = false;
-};
-
// PipeToEngine implements PipeTo(). All standard steps in this class come from
// https://streams.spec.whatwg.org/#readable-stream-pipe-to
//
@@ -1053,8 +1047,7 @@ ReadableStreamNative* ReadableStreamNative::Create(
// sizeAlgorithm).
ReadableStreamDefaultController::SetUp(
script_state, stream, controller, start_algorithm, pull_algorithm,
- cancel_algorithm, high_water_mark, size_algorithm, false,
- exception_state);
+ cancel_algorithm, high_water_mark, size_algorithm, exception_state);
if (exception_state.HadException()) {
return nullptr;
}
@@ -1065,14 +1058,12 @@ ReadableStreamNative* ReadableStreamNative::Create(
ReadableStreamNative::ReadableStreamNative() = default;
-// TODO(ricea): Remove |enable_blink_lock_notifications| once
-// blink::ReadableStreamOperations has been updated to use CreateReadableStream.
ReadableStreamNative::ReadableStreamNative(ScriptState* script_state,
ScriptValue raw_underlying_source,
ScriptValue raw_strategy,
- bool enable_blink_lock_notifications,
+ bool created_by_ua,
ExceptionState& exception_state) {
- if (!enable_blink_lock_notifications) {
+ if (!created_by_ua) {
// TODO(ricea): Move this to IDL once blink::ReadableStreamOperations is
// no longer using the public constructor.
UseCounter::Count(ExecutionContext::From(script_state),
@@ -1157,7 +1148,7 @@ ReadableStreamNative::ReadableStreamNative(ScriptState* script_state,
// (this, underlyingSource, highWaterMark, sizeAlgorithm).
ReadableStreamDefaultController::SetUpFromUnderlyingSource(
script_state, this, underlying_source, high_water_mark, size_algorithm,
- enable_blink_lock_notifications, exception_state);
+ exception_state);
}
ReadableStreamNative::~ReadableStreamNative() = default;
@@ -1394,7 +1385,43 @@ void ReadableStreamNative::LockAndDisturb(ScriptState* script_state,
void ReadableStreamNative::Serialize(ScriptState* script_state,
MessagePort* port,
ExceptionState& exception_state) {
- // TODO(ricea): Implement this.
+ if (IsLocked(this)) {
+ exception_state.ThrowTypeError("Cannot transfer a locked stream");
+ return;
+ }
+
+ auto* writable =
+ CreateCrossRealmTransformWritable(script_state, port, exception_state);
+ if (exception_state.HadException()) {
+ return;
+ }
+
+ auto promise = PipeTo(script_state, this, writable, PipeOptions());
+ promise.MarkAsHandled();
+}
+
+ReadableStreamNative* ReadableStreamNative::Deserialize(
+ ScriptState* script_state,
+ MessagePort* port,
+ ExceptionState& exception_state) {
+ // We need to execute JavaScript to call "Then" on v8::Promises. We will not
+ // run author code.
+ v8::Isolate::AllowJavascriptExecutionScope allow_js(
+ script_state->GetIsolate());
+ auto* readable =
+ CreateCrossRealmTransformReadable(script_state, port, exception_state);
+ if (exception_state.HadException()) {
+ return nullptr;
+ }
+ return readable;
+}
+
+ScriptPromise ReadableStreamNative::PipeTo(ScriptState* script_state,
+ ReadableStreamNative* readable,
+ WritableStreamNative* destination,
+ PipeOptions pipe_options) {
+ auto* engine = MakeGarbageCollected<PipeToEngine>(script_state, pipe_options);
+ return engine->Start(readable, destination);
}
v8::Local<v8::Value> ReadableStreamNative::GetStoredError(
@@ -1409,14 +1436,6 @@ void ReadableStreamNative::Trace(Visitor* visitor) {
ReadableStream::Trace(visitor);
}
-ScriptPromise ReadableStreamNative::PipeTo(ScriptState* script_state,
- ReadableStreamNative* readable,
- WritableStreamNative* destination,
- PipeOptions pipe_options) {
- auto* engine = MakeGarbageCollected<PipeToEngine>(script_state, pipe_options);
- return engine->Start(readable, destination);
-}
-
//
// Abstract Operations Used By Controllers
//
diff --git a/chromium/third_party/blink/renderer/core/streams/readable_stream_native.h b/chromium/third_party/blink/renderer/core/streams/readable_stream_native.h
index b2af17d437e..ee1b87d9d9b 100644
--- a/chromium/third_party/blink/renderer/core/streams/readable_stream_native.h
+++ b/chromium/third_party/blink/renderer/core/streams/readable_stream_native.h
@@ -30,6 +30,13 @@ class WritableStreamNative;
// See https://streams.spec.whatwg.org/#rs-model for background.
class ReadableStreamNative : public ReadableStream {
public:
+ struct PipeOptions {
+ PipeOptions() = default;
+ bool prevent_close = false;
+ bool prevent_abort = false;
+ bool prevent_cancel = false;
+ };
+
enum State : uint8_t { kReadable, kClosed, kErrored };
// Implements ReadableStream::Create() when this implementation is enabled.
@@ -60,14 +67,11 @@ class ReadableStreamNative : public ReadableStream {
ReadableStreamNative();
- // TODO(ricea): Remove |enable_blink_lock_notifications| once
- // blink::ReadableStreamOperations has been updated to use
- // CreateReadableStream.
// https://streams.spec.whatwg.org/#rs-constructor
ReadableStreamNative(ScriptState*,
ScriptValue raw_underlying_source,
ScriptValue raw_strategy,
- bool enable_blink_lock_notifications,
+ bool created_by_ua,
ExceptionState&);
~ReadableStreamNative() override;
@@ -146,6 +150,10 @@ class ReadableStreamNative : public ReadableStream {
void Serialize(ScriptState*, MessagePort* port, ExceptionState&) override;
+ static ReadableStreamNative* Deserialize(ScriptState*,
+ MessagePort* port,
+ ExceptionState&);
+
bool IsBroken() const override { return false; }
//
@@ -162,6 +170,12 @@ class ReadableStreamNative : public ReadableStream {
return stream->reader_;
}
+ // https://streams.spec.whatwg.org/#readable-stream-pipe-to
+ static ScriptPromise PipeTo(ScriptState*,
+ ReadableStreamNative*,
+ WritableStreamNative*,
+ PipeOptions);
+
//
// Functions exported for use by TransformStream. Not part of the standard.
//
@@ -190,7 +204,6 @@ class ReadableStreamNative : public ReadableStream {
friend class ReadableStreamDefaultController;
friend class ReadableStreamReader;
- struct PipeOptions;
class PipeToEngine;
class ReadHandleImpl;
class TeeEngine;
@@ -204,12 +217,6 @@ class ReadableStreamNative : public ReadableStream {
bool for_author_code,
ExceptionState&);
- // https://streams.spec.whatwg.org/#readable-stream-pipe-to
- static ScriptPromise PipeTo(ScriptState*,
- ReadableStreamNative*,
- WritableStreamNative*,
- PipeOptions);
-
// https://streams.spec.whatwg.org/#readable-stream-add-read-request
static StreamPromiseResolver* AddReadRequest(ScriptState*,
ReadableStreamNative*);
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 605a1b46c80..8f77a2bfc43 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
@@ -24,6 +24,7 @@
#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/runtime_enabled_features_test_helpers.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
#include "v8/include/v8.h"
@@ -131,6 +132,8 @@ ScriptValue CheckedGetInternalStream(ScriptState* script_state,
}
TEST(ReadableStreamOperationsTest, IsReadableStream) {
+ ScopedStreamsNativeForTest enabled(false);
+
V8TestingScope scope;
TryCatchScope try_catch_scope(scope.GetIsolate());
EXPECT_FALSE(ReadableStreamOperations::IsReadableStream(
@@ -167,6 +170,8 @@ TEST(ReadableStreamOperationsTest, IsReadableStream) {
}
TEST(ReadableStreamOperationsTest, IsReadableStreamDefaultReaderInvalid) {
+ ScopedStreamsNativeForTest enabled(false);
+
V8TestingScope scope;
TryCatchScope try_catch_scope(scope.GetIsolate());
EXPECT_FALSE(ReadableStreamOperations::IsReadableStreamDefaultReader(
@@ -195,6 +200,8 @@ TEST(ReadableStreamOperationsTest, IsReadableStreamDefaultReaderInvalid) {
}
TEST(ReadableStreamOperationsTest, GetReader) {
+ ScopedStreamsNativeForTest enabled(false);
+
V8TestingScope scope;
TryCatchScope try_catch_scope(scope.GetIsolate());
auto* stream =
@@ -232,6 +239,8 @@ TEST(ReadableStreamOperationsTest, GetReader) {
}
TEST(ReadableStreamOperationsTest, IsDisturbed) {
+ ScopedStreamsNativeForTest enabled(false);
+
V8TestingScope scope;
TryCatchScope try_catch_scope(scope.GetIsolate());
auto* stream =
@@ -252,6 +261,8 @@ TEST(ReadableStreamOperationsTest, IsDisturbed) {
}
TEST(ReadableStreamOperationsTest, Read) {
+ ScopedStreamsNativeForTest enabled(false);
+
V8TestingScope scope;
TryCatchScope try_catch_scope(scope.GetIsolate());
ScriptValue reader =
@@ -301,6 +312,8 @@ TEST(ReadableStreamOperationsTest, Read) {
TEST(ReadableStreamOperationsTest,
CreateReadableStreamWithCustomUnderlyingSourceAndStrategy) {
+ ScopedStreamsNativeForTest enabled(false);
+
V8TestingScope scope;
TryCatchScope try_catch_scope(scope.GetIsolate());
auto* underlying_source =
@@ -367,47 +380,9 @@ TEST(ReadableStreamOperationsTest,
EXPECT_TRUE(it3->IsDone());
}
-TEST(ReadableStreamOperationsTest,
- UnderlyingSourceShouldHavePendingActivityWhenLockedAndControllerIsActive) {
- V8TestingScope scope;
- TryCatchScope try_catch_scope(scope.GetIsolate());
- auto* underlying_source =
- MakeGarbageCollected<TestUnderlyingSource>(scope.GetScriptState());
-
- ScriptValue strategy = ReadableStreamOperations::CreateCountQueuingStrategy(
- scope.GetScriptState(), 10);
- ASSERT_FALSE(strategy.IsEmpty());
-
- ScriptValue internal_stream = ReadableStreamOperations::CreateReadableStream(
- scope.GetScriptState(), underlying_source, strategy);
- ASSERT_FALSE(internal_stream.IsEmpty());
-
- CHECK(!RuntimeEnabledFeatures::StreamsNativeEnabled());
- auto* stream = ReadableStreamWrapper::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"),
- ToV8(stream, scope.GetScriptState()))
- .IsJust());
-
- EXPECT_FALSE(underlying_source->HasPendingActivity());
- EvalWithPrintingError(&scope, "let reader = stream.getReader();");
- EXPECT_TRUE(underlying_source->HasPendingActivity());
- EvalWithPrintingError(&scope, "reader.releaseLock();");
- EXPECT_FALSE(underlying_source->HasPendingActivity());
- EvalWithPrintingError(&scope, "reader = stream.getReader();");
- EXPECT_TRUE(underlying_source->HasPendingActivity());
- underlying_source->Enqueue(
- ScriptValue(scope.GetScriptState(), v8::Undefined(scope.GetIsolate())));
- underlying_source->Close();
- EXPECT_FALSE(underlying_source->HasPendingActivity());
-}
-
TEST(ReadableStreamOperationsTest, IsReadable) {
+ ScopedStreamsNativeForTest enabled(false);
+
V8TestingScope scope;
TryCatchScope try_catch_scope(scope.GetIsolate());
@@ -448,6 +423,8 @@ TEST(ReadableStreamOperationsTest, IsReadable) {
}
TEST(ReadableStreamOperationsTest, IsClosed) {
+ ScopedStreamsNativeForTest enabled(false);
+
V8TestingScope scope;
TryCatchScope try_catch_scope(scope.GetIsolate());
@@ -488,6 +465,8 @@ TEST(ReadableStreamOperationsTest, IsClosed) {
}
TEST(ReadableStreamOperationsTest, IsErrored) {
+ ScopedStreamsNativeForTest enabled(false);
+
V8TestingScope scope;
TryCatchScope try_catch_scope(scope.GetIsolate());
@@ -528,6 +507,8 @@ TEST(ReadableStreamOperationsTest, IsErrored) {
}
TEST(ReadableStreamOperationsTest, Tee) {
+ ScopedStreamsNativeForTest enabled(false);
+
V8TestingScope scope;
TryCatchScope try_catch_scope(scope.GetIsolate());
v8::Local<v8::Context> context = scope.GetScriptState()->GetContext();
@@ -599,7 +580,8 @@ TEST(ReadableStreamOperationsTest, Tee) {
}
TEST(ReadableStreamOperationsTest, Serialize) {
- RuntimeEnabledFeatures::SetTransferableStreamsEnabled(true);
+ ScopedStreamsNativeForTest streams_native_enabled(false);
+ ScopedTransferableStreamsForTest transferable_streams_enabled(true);
V8TestingScope scope;
TryCatchScope try_catch_scope(scope.GetIsolate());
diff --git a/chromium/third_party/blink/renderer/core/streams/readable_stream_reader.cc b/chromium/third_party/blink/renderer/core/streams/readable_stream_reader.cc
index 7396853b466..66b5a1a999b 100644
--- a/chromium/third_party/blink/renderer/core/streams/readable_stream_reader.cc
+++ b/chromium/third_party/blink/renderer/core/streams/readable_stream_reader.cc
@@ -170,16 +170,6 @@ void ReadableStreamReader::GenericRelease(ScriptState* script_state,
DCHECK_EQ(reader->owner_readable_stream_->reader_, reader);
auto* isolate = script_state->GetIsolate();
- // TODO(yhirano): Remove this when we don"t need hasPendingActivity in
- // blink::UnderlyingSourceBase.
- ReadableStreamDefaultController* controller =
- reader->owner_readable_stream_->readable_stream_controller_;
- if (controller->enable_blink_lock_notifications_) {
- // The stream is created with an external controller (i.e. made in
- // Blink).
- auto lock_notify_target = controller->lock_notify_target_.NewLocal(isolate);
- CallNullaryMethod(script_state, lock_notify_target, "notifyLockReleased");
- }
// 3. If reader.[[ownerReadableStream]].[[state]] is "readable", reject
// reader.[[closedPromise]] with a TypeError exception.
@@ -237,17 +227,6 @@ void ReadableStreamReader::GenericInitialize(ScriptState* script_state,
ReadableStreamReader* reader,
ReadableStreamNative* stream) {
auto* isolate = script_state->GetIsolate();
- // TODO(yhirano): Remove this when we don't need hasPendingActivity in
- // blink::UnderlyingSourceBase.
- ReadableStreamDefaultController* controller =
- stream->readable_stream_controller_;
- if (controller->enable_blink_lock_notifications_) {
- // The stream is created with an external controller (i.e. made in
- // Blink).
- v8::Local<v8::Object> lock_notify_target =
- controller->lock_notify_target_.NewLocal(isolate);
- CallNullaryMethod(script_state, lock_notify_target, "notifyLockAcquired");
- }
// https://streams.spec.whatwg.org/#readable-stream-reader-generic-initialize
// 1. Set reader.[[forAuthorCode]] to true.
@@ -290,32 +269,4 @@ void ReadableStreamReader::GenericInitialize(ScriptState* script_state,
}
}
-void ReadableStreamReader::CallNullaryMethod(ScriptState* script_state,
- v8::Local<v8::Object> object,
- const char* method_name) {
- auto* isolate = script_state->GetIsolate();
- auto context = script_state->GetContext();
- v8::TryCatch try_catch(isolate);
- v8::Local<v8::Value> method;
- if (!object->Get(context, V8AtomicString(isolate, method_name))
- .ToLocal(&method)) {
- DLOG(WARNING) << "Ignored failed lookup of '" << method_name
- << "' in CallNullaryMethod";
- return;
- }
-
- if (!method->IsFunction()) {
- DLOG(WARNING) << "Didn't call '" << method_name
- << "' in CallNullaryMethod because it was the wrong type";
- return;
- }
-
- v8::MaybeLocal<v8::Value> result =
- method.As<v8::Function>()->Call(context, object, 0, nullptr);
- if (result.IsEmpty()) {
- DLOG(WARNING) << "Ignored failure of '" << method_name
- << "' in CallNullaryMethod";
- }
-}
-
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/streams/readable_stream_reader.h b/chromium/third_party/blink/renderer/core/streams/readable_stream_reader.h
index 3d5f8d3e7c5..ba10befa61e 100644
--- a/chromium/third_party/blink/renderer/core/streams/readable_stream_reader.h
+++ b/chromium/third_party/blink/renderer/core/streams/readable_stream_reader.h
@@ -6,6 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_READABLE_STREAM_READER_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 "v8/include/v8.h"
@@ -25,7 +26,7 @@ class Visitor;
// with the standard, ReadableStreamDefaultReader is implemented by the
// ReadableStreamReader class.
// TODO(ricea): Refactor this when implementing ReadableStreamBYOBReader.
-class ReadableStreamReader : public ScriptWrappable {
+class CORE_EXPORT ReadableStreamReader : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
@@ -81,12 +82,6 @@ class ReadableStreamReader : public ScriptWrappable {
ReadableStreamReader*,
ReadableStreamNative*);
- // Calls method |method_name| on |object|, passing no arguments, and ignoring
- // errors. Used for Blink lock notifications.
- static void CallNullaryMethod(ScriptState*,
- v8::Local<v8::Object> object,
- const char* method_name);
-
Member<StreamPromiseResolver> closed_promise_;
bool for_author_code_ = true;
Member<ReadableStreamNative> owner_readable_stream_;
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
index 8347364aea2..2217f829919 100644
--- a/chromium/third_party/blink/renderer/core/streams/readable_stream_test.cc
+++ b/chromium/third_party/blink/renderer/core/streams/readable_stream_test.cc
@@ -410,13 +410,7 @@ TEST_P(ReadableStreamTest, LockAndDisturb) {
}
TEST_P(ReadableStreamTest, Serialize) {
- if (GetParam()) {
- // Serialize() is not yet supported in the C++ implementation.
- return;
- }
-
ScopedTransferableStreamsForTest enabled(true);
- RuntimeEnabledFeatures::SetTransferableStreamsEnabled(true);
V8TestingScope scope;
auto* script_state = scope.GetScriptState();
diff --git a/chromium/third_party/blink/renderer/core/streams/transferable_streams.cc b/chromium/third_party/blink/renderer/core/streams/transferable_streams.cc
new file mode 100644
index 00000000000..82efecbc340
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/streams/transferable_streams.cc
@@ -0,0 +1,878 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// Functions for transferable streams. See design doc
+// https://docs.google.com/document/d/1_KuZzg5c3pncLJPFa8SuVm23AP4tft6mzPCL5at3I9M/edit
+
+#include "third_party/blink/renderer/core/streams/transferable_streams.h"
+
+#include "base/stl_util.h"
+#include "third_party/blink/renderer/bindings/core/v8/to_v8_for_core.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_dom_exception.h"
+#include "third_party/blink/renderer/core/dom/dom_exception.h"
+#include "third_party/blink/renderer/core/dom/events/native_event_listener.h"
+#include "third_party/blink/renderer/core/events/message_event.h"
+#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/core/streams/miscellaneous_operations.h"
+#include "third_party/blink/renderer/core/streams/promise_handler.h"
+#include "third_party/blink/renderer/core/streams/readable_stream_default_controller.h"
+#include "third_party/blink/renderer/core/streams/readable_stream_native.h"
+#include "third_party/blink/renderer/core/streams/stream_algorithms.h"
+#include "third_party/blink/renderer/core/streams/stream_promise_resolver.h"
+#include "third_party/blink/renderer/core/streams/writable_stream_default_controller.h"
+#include "third_party/blink/renderer/core/streams/writable_stream_native.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/heap.h"
+#include "third_party/blink/renderer/platform/heap/visitor.h"
+#include "third_party/blink/renderer/platform/wtf/assertions.h"
+#include "v8/include/v8.h"
+
+// See the design doc at
+// https://docs.google.com/document/d/1_KuZzg5c3pncLJPFa8SuVm23AP4tft6mzPCL5at3I9M/edit
+// for explanation of how transferable streams are constructed from the "cross
+// realm identity transform" implemented in this file.
+
+// The peer (the other end of the MessagePort) is untrusted as it may be
+// compromised. This means we have to be very careful in unpacking the messages
+// from the peer. LOG(WARNING) is used for cases where a message from the peer
+// appears to be invalid. If this appears during ordinary testing it indicates a
+// bug.
+//
+// The -vmodule=transferable_streams=3 command-line argument can be used for
+// debugging of the protocol.
+
+namespace blink {
+
+namespace {
+
+// These are the types of messages that are sent between peers.
+enum class MessageType { kPull, kCancel, kChunk, kClose, kAbort, kError };
+
+// These are the different ways an error reason can be encoded.
+enum class ErrorType { kTypeError, kJson, kDomException, kUndefined };
+
+bool IsATypeError(ScriptState* script_state, v8::Local<v8::Object> object) {
+ // There isn't a 100% reliable way to identify a TypeError.
+ return object->IsNativeError() &&
+ object->GetConstructorName()
+ ->Equals(script_state->GetContext(),
+ V8AtomicString(script_state->GetIsolate(), "TypeError"))
+ .ToChecked();
+}
+
+bool IsADOMException(v8::Isolate* isolate, v8::Local<v8::Object> object) {
+ return V8DOMException::HasInstance(object, isolate);
+}
+
+// Creates a JavaScript object with a null prototype structured like {key1:
+// value2, key2: value2}. This is used to create objects to be serialized by
+// postMessage.
+v8::Local<v8::Object> CreateKeyValueObject(v8::Isolate* isolate,
+ const char* key1,
+ v8::Local<v8::Value> value1,
+ const char* key2,
+ v8::Local<v8::Value> value2) {
+ v8::Local<v8::Name> names[] = {V8AtomicString(isolate, key1),
+ V8AtomicString(isolate, key2)};
+ v8::Local<v8::Value> values[] = {value1, value2};
+ static_assert(base::size(names) == base::size(values),
+ "names and values arrays must be the same size");
+ return v8::Object::New(isolate, v8::Null(isolate), names, values,
+ base::size(names));
+}
+
+// Unpacks an object created by CreateKeyValueObject(). |value1| and |value2|
+// are out parameters. Returns false on failure.
+bool UnpackKeyValueObject(ScriptState* script_state,
+ v8::Local<v8::Object> object,
+ const char* key1,
+ v8::Local<v8::Value>* value1,
+ const char* key2,
+ v8::Local<v8::Value>* value2) {
+ auto* isolate = script_state->GetIsolate();
+ v8::TryCatch try_catch(isolate);
+ auto context = script_state->GetContext();
+ if (!object->Get(context, V8AtomicString(isolate, key1)).ToLocal(value1)) {
+ DLOG(WARNING) << "Error reading key: '" << key1 << "'";
+ return false;
+ }
+ if (!object->Get(context, V8AtomicString(isolate, key2)).ToLocal(value2)) {
+ DLOG(WARNING) << "Error reading key: '" << key2 << "'";
+ return false;
+ }
+ return true;
+}
+
+// Send a message with type |type| and contents |value| over |port|. The type
+// will be packed as a number with key "t", and the value will be packed with
+// key "v".
+void PackAndPostMessage(ScriptState* script_state,
+ MessagePort* port,
+ MessageType type,
+ v8::Local<v8::Value> value,
+ ExceptionState& exception_state) {
+ DVLOG(3) << "PackAndPostMessage sending message type "
+ << static_cast<int>(type);
+ auto* isolate = script_state->GetIsolate();
+ v8::Local<v8::Object> packed = CreateKeyValueObject(
+ isolate, "t", v8::Number::New(isolate, static_cast<int>(type)), "v",
+ value);
+ port->postMessage(script_state, ScriptValue(script_state, packed),
+ PostMessageOptions::Create(), exception_state);
+}
+
+// Packs an error into an {e: number, s: string} object for transmission by
+// postMessage. Serializing the resulting object should never fail.
+v8::Local<v8::Object> PackErrorType(v8::Isolate* isolate,
+ ErrorType type,
+ v8::Local<v8::String> string) {
+ auto error_as_number = v8::Number::New(isolate, static_cast<int>(type));
+ return CreateKeyValueObject(isolate, "e", error_as_number, "s", string);
+}
+
+// Overload for the common case where |string| is a compile-time constant.
+v8::Local<v8::Object> PackErrorType(v8::Isolate* isolate,
+ ErrorType type,
+ const char* string) {
+ return PackErrorType(isolate, type, V8String(isolate, string));
+}
+
+// We'd like to able to transfer TypeError exceptions, but we can't, so we hack
+// around it. PackReason() is guaranteed to succeed and the object produced is
+// guaranteed to be serializable by postMessage(), however data may be lost. It
+// is not very efficient, and has fairly arbitrary semantics.
+// TODO(ricea): Replace once Errors are serializable.
+v8::Local<v8::Value> PackReason(ScriptState* script_state,
+ v8::Local<v8::Value> reason) {
+ auto* isolate = script_state->GetIsolate();
+ auto context = script_state->GetContext();
+ if (reason->IsString() || reason->IsNumber() || reason->IsBoolean()) {
+ v8::TryCatch try_catch(isolate);
+ v8::Local<v8::String> stringified;
+ if (!v8::JSON::Stringify(context, reason).ToLocal(&stringified)) {
+ return PackErrorType(isolate, ErrorType::kTypeError,
+ "Cannot transfer message");
+ }
+
+ return PackErrorType(isolate, ErrorType::kJson, stringified);
+ }
+
+ if (reason->IsNull()) {
+ return PackErrorType(isolate, ErrorType::kJson, "null");
+ }
+
+ if (reason->IsFunction() || reason->IsSymbol() || !reason->IsObject()) {
+ // Squash to undefined
+ return PackErrorType(isolate, ErrorType::kUndefined, "");
+ }
+
+ if (IsATypeError(script_state, reason.As<v8::Object>())) {
+ v8::TryCatch try_catch(isolate);
+ // "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.
+ v8::Local<v8::Value> descriptor;
+ if (!reason.As<v8::Object>()
+ ->GetOwnPropertyDescriptor(context,
+ V8AtomicString(isolate, "message"))
+ .ToLocal(&descriptor)) {
+ return PackErrorType(isolate, ErrorType::kTypeError,
+ "Cannot transfer message");
+ }
+ if (descriptor->IsUndefined()) {
+ return PackErrorType(isolate, ErrorType::kTypeError, "");
+ }
+ v8::Local<v8::Value> message;
+ CHECK(descriptor->IsObject());
+ if (!descriptor.As<v8::Object>()
+ ->Get(context, V8AtomicString(isolate, "value"))
+ .ToLocal(&message)) {
+ message = V8String(isolate, "Cannot transfer message");
+ } else if (!message->IsString()) {
+ message = V8String(isolate, "");
+ }
+ return PackErrorType(isolate, ErrorType::kTypeError,
+ message.As<v8::String>());
+ }
+
+ if (IsADOMException(isolate, reason.As<v8::Object>())) {
+ DOMException* dom_exception =
+ V8DOMException::ToImpl(reason.As<v8::Object>());
+ String message = dom_exception->message();
+ String name = dom_exception->name();
+ v8::Local<v8::Value> packed = CreateKeyValueObject(
+ isolate, "m", V8String(isolate, message), "n", V8String(isolate, name));
+ // It should be impossible for this to fail, except for out-of-memory.
+ v8::Local<v8::String> packed_string =
+ v8::JSON::Stringify(context, packed).ToLocalChecked();
+ return PackErrorType(isolate, ErrorType::kDomException, packed_string);
+ }
+
+ v8::TryCatch try_catch(isolate);
+ v8::Local<v8::Value> json;
+ if (!v8::JSON::Stringify(context, reason).ToLocal(&json)) {
+ return PackErrorType(isolate, ErrorType::kTypeError,
+ "Cannot transfer message");
+ }
+
+ return PackErrorType(isolate, ErrorType::kJson, json.As<v8::String>());
+}
+
+// Converts an object created by PackReason() back into a clone of the original
+// object, minus any data that was discarded by PackReason().
+bool UnpackReason(ScriptState* script_state,
+ v8::Local<v8::Value> packed_reason,
+ v8::Local<v8::Value>* reason) {
+ // We need to be robust against malformed input because it could come from a
+ // compromised renderer.
+ if (!packed_reason->IsObject()) {
+ DLOG(WARNING) << "packed_reason is not an object";
+ return false;
+ }
+
+ v8::Local<v8::Value> encoder_value;
+ v8::Local<v8::Value> string_value;
+ if (!UnpackKeyValueObject(script_state, packed_reason.As<v8::Object>(), "e",
+ &encoder_value, "s", &string_value)) {
+ return false;
+ }
+
+ if (!encoder_value->IsNumber()) {
+ DLOG(WARNING) << "encoder_value is not a number";
+ return false;
+ }
+
+ int encoder = encoder_value.As<v8::Number>()->Value();
+ if (!string_value->IsString()) {
+ DLOG(WARNING) << "string_value is not a string";
+ return false;
+ }
+
+ v8::Local<v8::String> string = string_value.As<v8::String>();
+ auto* isolate = script_state->GetIsolate();
+ auto context = script_state->GetContext();
+ switch (static_cast<ErrorType>(encoder)) {
+ case ErrorType::kJson: {
+ v8::TryCatch try_catch(isolate);
+ if (!v8::JSON::Parse(context, string).ToLocal(reason)) {
+ DLOG(WARNING) << "JSON Parse failed. Content: " << ToCoreString(string);
+ return false;
+ }
+ return true;
+ }
+
+ case ErrorType::kTypeError:
+ *reason = v8::Exception::TypeError(string);
+ return true;
+
+ case ErrorType::kDomException: {
+ v8::TryCatch try_catch(isolate);
+ v8::Local<v8::Value> packed_exception;
+ if (!v8::JSON::Parse(context, string).ToLocal(&packed_exception)) {
+ DLOG(WARNING) << "Packed DOMException JSON parse failed";
+ return false;
+ }
+
+ if (!packed_exception->IsObject()) {
+ DLOG(WARNING) << "Packed DOMException is not an object";
+ return false;
+ }
+
+ v8::Local<v8::Value> message;
+ v8::Local<v8::Value> name;
+ if (!UnpackKeyValueObject(script_state, packed_exception.As<v8::Object>(),
+ "m", &message, "n", &name)) {
+ DLOG(WARNING) << "Failed unpacking packed DOMException";
+ return false;
+ }
+
+ if (!message->IsString()) {
+ DLOG(WARNING) << "DOMException message is not a string";
+ return false;
+ }
+
+ if (!name->IsString()) {
+ DLOG(WARNING) << "DOMException name is not a string";
+ return false;
+ }
+
+ auto ToBlink = [](v8::Local<v8::Value> value) {
+ return ToBlinkString<String>(value.As<v8::String>(), kDoNotExternalize);
+ };
+ *reason = ToV8(DOMException::Create(ToBlink(message), ToBlink(name)),
+ script_state);
+ return true;
+ }
+
+ case ErrorType::kUndefined:
+ *reason = v8::Undefined(isolate);
+ return true;
+
+ default:
+ DLOG(WARNING) << "Invalid ErrorType: " << encoder;
+ return false;
+ }
+}
+
+// Base class for CrossRealmTransformWritable and CrossRealmTransformReadable.
+// Contains common methods that are used when handling MessagePort events.
+class CrossRealmTransformStream
+ : public GarbageCollected<CrossRealmTransformStream> {
+ public:
+ // Neither of the subclasses require finalization, so no destructor.
+
+ virtual ScriptState* GetScriptState() const = 0;
+ virtual MessagePort* GetMessagePort() const = 0;
+
+ // HandleMessage() is called by CrossRealmTransformMessageListener to handle
+ // an incoming message from the MessagePort.
+ virtual void HandleMessage(MessageType type, v8::Local<v8::Value> value) = 0;
+
+ // HandleError() is called by CrossRealmTransformErrorListener when an error
+ // event is fired on the message port. It should error the stream.
+ virtual void HandleError(v8::Local<v8::Value> error) = 0;
+
+ virtual void Trace(Visitor*) {}
+};
+
+// Handles MessageEvents from the MessagePort.
+class CrossRealmTransformMessageListener final : public NativeEventListener {
+ public:
+ explicit CrossRealmTransformMessageListener(CrossRealmTransformStream* target)
+ : target_(target) {}
+
+ void Invoke(ExecutionContext*, Event* event) override {
+ // TODO(ricea): Find a way to guarantee this cast is safe.
+ MessageEvent* message = static_cast<MessageEvent*>(event);
+ ScriptState* script_state = target_->GetScriptState();
+ // The deserializer code called by message->data() looks up the ScriptState
+ // from the current context, so we need to make sure it is set.
+ ScriptState::Scope scope(script_state);
+ v8::Local<v8::Value> data = message->data(script_state).V8Value();
+ if (!data->IsObject()) {
+ DLOG(WARNING) << "Invalid message from peer ignored (not object)";
+ return;
+ }
+
+ v8::Local<v8::Value> type;
+ v8::Local<v8::Value> value;
+ if (!UnpackKeyValueObject(script_state, data.As<v8::Object>(), "t", &type,
+ "v", &value)) {
+ DLOG(WARNING) << "Invalid message from peer ignored";
+ return;
+ }
+
+ if (!type->IsNumber()) {
+ DLOG(WARNING) << "Invalid message from peer ignored (type is not number)";
+ return;
+ }
+
+ int type_value = type.As<v8::Number>()->Value();
+ DVLOG(3) << "MessageListener saw message type " << type_value;
+ target_->HandleMessage(static_cast<MessageType>(type_value), value);
+ }
+
+ void Trace(Visitor* visitor) override {
+ visitor->Trace(target_);
+ NativeEventListener::Trace(visitor);
+ }
+
+ private:
+ const Member<CrossRealmTransformStream> target_;
+};
+
+// Handles "error" events from the MessagePort.
+class CrossRealmTransformErrorListener final : public NativeEventListener {
+ public:
+ explicit CrossRealmTransformErrorListener(CrossRealmTransformStream* target)
+ : target_(target) {}
+
+ void Invoke(ExecutionContext*, Event*) override {
+ ScriptState* script_state = target_->GetScriptState();
+ const auto* error =
+ DOMException::Create("chunk could not be cloned", "DataCloneError");
+ auto* message_port = target_->GetMessagePort();
+ v8::Local<v8::Value> error_value = ToV8(error, script_state);
+ ExceptionState exception_state(script_state->GetIsolate(),
+ ExceptionState::kUnknownContext, "", "");
+
+ PackAndPostMessage(script_state, message_port, MessageType::kError,
+ PackReason(script_state, error_value), exception_state);
+ if (exception_state.HadException()) {
+ DLOG(WARNING) << "Ignoring postMessage failure in error listener";
+ exception_state.ClearException();
+ }
+
+ message_port->close();
+ target_->HandleError(error_value);
+ }
+
+ void Trace(Visitor* visitor) override {
+ visitor->Trace(target_);
+ NativeEventListener::Trace(visitor);
+ }
+
+ private:
+ const Member<CrossRealmTransformStream> target_;
+};
+
+// Class for data associated with the writable side of the cross realm transform
+// stream.
+class CrossRealmTransformWritable final : public CrossRealmTransformStream {
+ public:
+ CrossRealmTransformWritable(ScriptState* script_state, MessagePort* port)
+ : script_state_(script_state),
+ message_port_(port),
+ backpressure_promise_(
+ MakeGarbageCollected<StreamPromiseResolver>(script_state)) {}
+
+ WritableStreamNative* CreateWritableStream(ExceptionState&);
+
+ ScriptState* GetScriptState() const override { return script_state_; }
+ MessagePort* GetMessagePort() const override { return message_port_; }
+ void HandleMessage(MessageType type, v8::Local<v8::Value> value) override;
+ void HandleError(v8::Local<v8::Value> error) override;
+
+ void Trace(Visitor* visitor) override {
+ visitor->Trace(script_state_);
+ visitor->Trace(message_port_);
+ visitor->Trace(backpressure_promise_);
+ visitor->Trace(controller_);
+ CrossRealmTransformStream::Trace(visitor);
+ }
+
+ private:
+ class WriteAlgorithm;
+ class CloseAlgorithm;
+ class AbortAlgorithm;
+
+ const Member<ScriptState> script_state_;
+ const Member<MessagePort> message_port_;
+ Member<StreamPromiseResolver> backpressure_promise_;
+ Member<WritableStreamDefaultController> controller_;
+};
+
+class CrossRealmTransformWritable::WriteAlgorithm final
+ : public StreamAlgorithm {
+ public:
+ explicit WriteAlgorithm(CrossRealmTransformWritable* writable)
+ : writable_(writable) {}
+
+ // Sends the chunk to the readable side, possibly after waiting for
+ // backpressure.
+ v8::Local<v8::Promise> Run(ScriptState* script_state,
+ int argc,
+ v8::Local<v8::Value> argv[]) override {
+ DCHECK_EQ(argc, 1);
+ auto chunk = argv[0];
+
+ if (!writable_->backpressure_promise_) {
+ return DoWrite(script_state, chunk);
+ }
+
+ auto* isolate = script_state->GetIsolate();
+ return StreamThenPromise(
+ script_state->GetContext(),
+ writable_->backpressure_promise_->V8Promise(isolate),
+ MakeGarbageCollected<DoWriteOnResolve>(script_state, chunk, this));
+ }
+
+ void Trace(Visitor* visitor) override {
+ visitor->Trace(writable_);
+ StreamAlgorithm::Trace(visitor);
+ }
+
+ private:
+ // A promise handler which calls DoWrite() when the promise resolves.
+ class DoWriteOnResolve final : public PromiseHandlerWithValue {
+ public:
+ DoWriteOnResolve(ScriptState* script_state,
+ v8::Local<v8::Value> chunk,
+ WriteAlgorithm* target)
+ : PromiseHandlerWithValue(script_state),
+ chunk_(script_state->GetIsolate(), chunk),
+ target_(target) {}
+
+ v8::Local<v8::Value> CallWithLocal(v8::Local<v8::Value>) override {
+ ScriptState* script_state = GetScriptState();
+ return target_->DoWrite(script_state,
+ chunk_.NewLocal(script_state->GetIsolate()));
+ }
+
+ void Trace(Visitor* visitor) override {
+ visitor->Trace(chunk_);
+ visitor->Trace(target_);
+ PromiseHandlerWithValue::Trace(visitor);
+ }
+
+ private:
+ const TraceWrapperV8Reference<v8::Value> chunk_;
+ const Member<WriteAlgorithm> target_;
+ };
+
+ // Sends a chunk over the message port to the readable side.
+ v8::Local<v8::Promise> DoWrite(ScriptState* script_state,
+ v8::Local<v8::Value> chunk) {
+ writable_->backpressure_promise_ =
+ MakeGarbageCollected<StreamPromiseResolver>(script_state);
+ ExceptionState exception_state(script_state->GetIsolate(),
+ ExceptionState::kUnknownContext, "", "");
+ PackAndPostMessage(script_state, writable_->message_port_,
+ MessageType::kChunk, chunk, exception_state);
+ if (exception_state.HadException()) {
+ auto exception = exception_state.GetException();
+ exception_state.ClearException();
+
+ PackAndPostMessage(
+ script_state, writable_->message_port_, MessageType::kError,
+ PackReason(writable_->script_state_, exception), exception_state);
+ if (exception_state.HadException()) {
+ DLOG(WARNING) << "Disregarding exception while sending error";
+ exception_state.ClearException();
+ }
+
+ writable_->message_port_->close();
+ return PromiseReject(script_state, exception);
+ }
+
+ return PromiseResolveWithUndefined(script_state);
+ }
+
+ const Member<CrossRealmTransformWritable> writable_;
+};
+
+class CrossRealmTransformWritable::CloseAlgorithm final
+ : public StreamAlgorithm {
+ public:
+ explicit CloseAlgorithm(CrossRealmTransformWritable* writable)
+ : writable_(writable) {}
+
+ // Sends a close message to the readable side and closes the message port.
+ v8::Local<v8::Promise> Run(ScriptState* script_state,
+ int argc,
+ v8::Local<v8::Value> argv[]) override {
+ DCHECK_EQ(argc, 0);
+ ExceptionState exception_state(script_state->GetIsolate(),
+ ExceptionState::kUnknownContext, "", "");
+ PackAndPostMessage(
+ script_state, writable_->message_port_, MessageType::kClose,
+ v8::Undefined(script_state->GetIsolate()), exception_state);
+ if (exception_state.HadException()) {
+ DLOG(WARNING) << "Ignoring exception from PackAndPostMessage kClose";
+ exception_state.ClearException();
+ }
+
+ writable_->message_port_->close();
+ return PromiseResolveWithUndefined(script_state);
+ }
+
+ void Trace(Visitor* visitor) override {
+ visitor->Trace(writable_);
+ StreamAlgorithm::Trace(visitor);
+ }
+
+ private:
+ const Member<CrossRealmTransformWritable> writable_;
+};
+
+class CrossRealmTransformWritable::AbortAlgorithm final
+ : public StreamAlgorithm {
+ public:
+ explicit AbortAlgorithm(CrossRealmTransformWritable* writable)
+ : writable_(writable) {}
+
+ // Sends an abort message to the readable side and closes the message port.
+ v8::Local<v8::Promise> Run(ScriptState* script_state,
+ int argc,
+ v8::Local<v8::Value> argv[]) override {
+ DCHECK_EQ(argc, 1);
+ auto reason = argv[0];
+ ExceptionState exception_state(script_state->GetIsolate(),
+ ExceptionState::kUnknownContext, "", "");
+ PackAndPostMessage(
+ script_state, writable_->message_port_, MessageType::kAbort,
+ PackReason(writable_->script_state_, reason), exception_state);
+ if (exception_state.HadException()) {
+ DLOG(WARNING) << "Ignoring exception from PackAndPostMessage kAbort";
+ exception_state.ClearException();
+ }
+ writable_->message_port_->close();
+ return PromiseResolveWithUndefined(script_state);
+ }
+
+ void Trace(Visitor* visitor) override {
+ visitor->Trace(writable_);
+ StreamAlgorithm::Trace(visitor);
+ }
+
+ private:
+ const Member<CrossRealmTransformWritable> writable_;
+};
+
+WritableStreamNative* CrossRealmTransformWritable::CreateWritableStream(
+ ExceptionState& exception_state) {
+ DCHECK(!controller_) << "CreateWritableStream() can only be called once";
+
+ message_port_->setOnmessage(
+ MakeGarbageCollected<CrossRealmTransformMessageListener>(this));
+ message_port_->setOnmessageerror(
+ MakeGarbageCollected<CrossRealmTransformErrorListener>(this));
+
+ auto* stream = WritableStreamNative::Create(
+ script_state_, CreateTrivialStartAlgorithm(),
+ MakeGarbageCollected<WriteAlgorithm>(this),
+ MakeGarbageCollected<CloseAlgorithm>(this),
+ MakeGarbageCollected<AbortAlgorithm>(this), 1,
+ CreateDefaultSizeAlgorithm(), exception_state);
+
+ if (exception_state.HadException()) {
+ return nullptr;
+ }
+
+ controller_ = stream->Controller();
+ return stream;
+}
+
+void CrossRealmTransformWritable::HandleMessage(MessageType type,
+ v8::Local<v8::Value> value) {
+ switch (type) {
+ case MessageType::kPull:
+ DCHECK(backpressure_promise_);
+ backpressure_promise_->ResolveWithUndefined(script_state_);
+ backpressure_promise_ = nullptr;
+ return;
+
+ case MessageType::kCancel:
+ case MessageType::kError: {
+ v8::Local<v8::Value> reason;
+ if (!UnpackReason(script_state_, value, &reason)) {
+ DLOG(WARNING)
+ << "Invalid message from peer ignored (unable to unpack value)";
+ return;
+ }
+ WritableStreamDefaultController::ErrorIfNeeded(script_state_, controller_,
+ reason);
+ if (backpressure_promise_) {
+ backpressure_promise_->ResolveWithUndefined(script_state_);
+ backpressure_promise_ = nullptr;
+ }
+ return;
+ }
+
+ default:
+ DLOG(WARNING) << "Invalid message from peer ignored (invalid type): "
+ << static_cast<int>(type);
+ return;
+ }
+}
+
+void CrossRealmTransformWritable::HandleError(v8::Local<v8::Value> error) {
+ WritableStreamDefaultController::ErrorIfNeeded(script_state_, controller_,
+ error);
+}
+
+// Class for data associated with the readable side of the cross realm transform
+// stream.
+class CrossRealmTransformReadable final : public CrossRealmTransformStream {
+ public:
+ CrossRealmTransformReadable(ScriptState* script_state, MessagePort* port)
+ : script_state_(script_state),
+ message_port_(port),
+ backpressure_promise_(
+ MakeGarbageCollected<StreamPromiseResolver>(script_state)) {}
+
+ ReadableStreamNative* CreateReadableStream(ExceptionState&);
+
+ ScriptState* GetScriptState() const override { return script_state_; }
+ MessagePort* GetMessagePort() const override { return message_port_; }
+ void HandleMessage(MessageType type, v8::Local<v8::Value> value) override;
+ void HandleError(v8::Local<v8::Value> error) override;
+
+ void Trace(Visitor* visitor) override {
+ visitor->Trace(script_state_);
+ visitor->Trace(message_port_);
+ visitor->Trace(backpressure_promise_);
+ visitor->Trace(controller_);
+ CrossRealmTransformStream::Trace(visitor);
+ }
+
+ private:
+ class PullAlgorithm;
+ class CancelAlgorithm;
+
+ const Member<ScriptState> script_state_;
+ const Member<MessagePort> message_port_;
+ Member<StreamPromiseResolver> backpressure_promise_;
+ Member<ReadableStreamDefaultController> controller_;
+ bool finished_ = false;
+};
+
+class CrossRealmTransformReadable::PullAlgorithm final
+ : public StreamAlgorithm {
+ public:
+ explicit PullAlgorithm(CrossRealmTransformReadable* readable)
+ : readable_(readable) {}
+
+ // Sends a pull message to the writable side and then waits for backpressure
+ // to clear.
+ v8::Local<v8::Promise> Run(ScriptState* script_state,
+ int argc,
+ v8::Local<v8::Value> argv[]) override {
+ DCHECK_EQ(argc, 0);
+ auto* isolate = script_state->GetIsolate();
+ ExceptionState exception_state(isolate, ExceptionState::kUnknownContext, "",
+ "");
+
+ PackAndPostMessage(
+ script_state, readable_->message_port_, MessageType::kPull,
+ v8::Undefined(script_state->GetIsolate()), exception_state);
+ if (exception_state.HadException()) {
+ DLOG(WARNING) << "Ignoring exception from PackAndPostMessage kClose";
+ exception_state.ClearException();
+ }
+
+ return readable_->backpressure_promise_->V8Promise(isolate);
+ }
+
+ void Trace(Visitor* visitor) override {
+ visitor->Trace(readable_);
+ StreamAlgorithm::Trace(visitor);
+ }
+
+ private:
+ const Member<CrossRealmTransformReadable> readable_;
+};
+
+class CrossRealmTransformReadable::CancelAlgorithm final
+ : public StreamAlgorithm {
+ public:
+ explicit CancelAlgorithm(CrossRealmTransformReadable* readable)
+ : readable_(readable) {}
+
+ // Sends a cancel message to the writable side and closes the message port.
+ v8::Local<v8::Promise> Run(ScriptState* script_state,
+ int argc,
+ v8::Local<v8::Value> argv[]) override {
+ DCHECK_EQ(argc, 1);
+ auto reason = argv[0];
+ readable_->finished_ = true;
+ ExceptionState exception_state(script_state->GetIsolate(),
+ ExceptionState::kUnknownContext, "", "");
+
+ PackAndPostMessage(script_state, readable_->message_port_,
+ MessageType::kCancel, PackReason(script_state, reason),
+ exception_state);
+ if (exception_state.HadException()) {
+ DLOG(WARNING) << "Ignoring exception from PackAndPostMessage kClose";
+ exception_state.ClearException();
+ }
+
+ readable_->message_port_->close();
+ return PromiseResolveWithUndefined(script_state);
+ }
+
+ void Trace(Visitor* visitor) override {
+ visitor->Trace(readable_);
+ StreamAlgorithm::Trace(visitor);
+ }
+
+ private:
+ const Member<CrossRealmTransformReadable> readable_;
+};
+
+ReadableStreamNative* CrossRealmTransformReadable::CreateReadableStream(
+ ExceptionState& exception_state) {
+ DCHECK(!controller_) << "CreateReadableStream can only be called once";
+
+ message_port_->setOnmessage(
+ MakeGarbageCollected<CrossRealmTransformMessageListener>(this));
+ message_port_->setOnmessageerror(
+ MakeGarbageCollected<CrossRealmTransformErrorListener>(this));
+
+ auto* stream = ReadableStreamNative::Create(
+ script_state_, CreateTrivialStartAlgorithm(),
+ MakeGarbageCollected<PullAlgorithm>(this),
+ MakeGarbageCollected<CancelAlgorithm>(this),
+ /* highWaterMark = */ 0, CreateDefaultSizeAlgorithm(), exception_state);
+
+ if (exception_state.HadException()) {
+ return nullptr;
+ }
+
+ controller_ = stream->GetController();
+ return stream;
+}
+
+void CrossRealmTransformReadable::HandleMessage(MessageType type,
+ v8::Local<v8::Value> value) {
+ switch (type) {
+ case MessageType::kChunk: {
+ // This can't throw because we always use the default strategy size
+ // algorithm, which doesn't throw, and always returns a valid value of
+ // 1.0.
+ ReadableStreamDefaultController::Enqueue(script_state_, controller_,
+ value, ASSERT_NO_EXCEPTION);
+
+ backpressure_promise_->ResolveWithUndefined(script_state_);
+ backpressure_promise_ =
+ MakeGarbageCollected<StreamPromiseResolver>(script_state_);
+ return;
+ }
+
+ case MessageType::kClose:
+ finished_ = true;
+ ReadableStreamDefaultController::Close(script_state_, controller_);
+ message_port_->close();
+ return;
+
+ case MessageType::kAbort:
+ case MessageType::kError: {
+ finished_ = true;
+ v8::Local<v8::Value> reason;
+ if (!UnpackReason(script_state_, value, &reason)) {
+ DLOG(WARNING)
+ << "Invalid message from peer ignored (unable to unpack value)";
+ return;
+ }
+
+ ReadableStreamDefaultController::Error(script_state_, controller_,
+ reason);
+ message_port_->close();
+ return;
+ }
+
+ default:
+ DLOG(WARNING) << "Invalid message from peer ignored (invalid type): "
+ << static_cast<int>(type);
+ return;
+ }
+}
+
+void CrossRealmTransformReadable::HandleError(v8::Local<v8::Value> error) {
+ ReadableStreamDefaultController::Error(script_state_, controller_, error);
+}
+
+} // namespace
+
+CORE_EXPORT WritableStreamNative* CreateCrossRealmTransformWritable(
+ ScriptState* script_state,
+ MessagePort* port,
+ ExceptionState& exception_state) {
+ return MakeGarbageCollected<CrossRealmTransformWritable>(script_state, port)
+ ->CreateWritableStream(exception_state);
+}
+
+CORE_EXPORT ReadableStreamNative* CreateCrossRealmTransformReadable(
+ ScriptState* script_state,
+ MessagePort* port,
+ ExceptionState& exception_state) {
+ return MakeGarbageCollected<CrossRealmTransformReadable>(script_state, port)
+ ->CreateReadableStream(exception_state);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/streams/transferable_streams.h b/chromium/third_party/blink/renderer/core/streams/transferable_streams.h
new file mode 100644
index 00000000000..62883f1d69c
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/streams/transferable_streams.h
@@ -0,0 +1,37 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// Functions used to build transferable streams.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_TRANSFERABLE_STREAMS_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_TRANSFERABLE_STREAMS_H_
+
+#include "third_party/blink/renderer/core/core_export.h"
+
+namespace blink {
+
+class ExceptionState;
+class MessagePort;
+class ReadableStreamNative;
+class ScriptState;
+class WritableStreamNative;
+
+// Creates the writable side of a cross-realm identity transform stream, using
+// |port| for communication. |port| must be entangled with another MessagePort
+// which is passed to CreateCrossRealmTransformReadable().
+CORE_EXPORT WritableStreamNative* CreateCrossRealmTransformWritable(
+ ScriptState*,
+ MessagePort* port,
+ ExceptionState&);
+
+// Creates the readable side of a cross-realm identity transform stream. |port|
+// is used symmetrically with CreateCrossRealmTransformWritable().
+CORE_EXPORT ReadableStreamNative* CreateCrossRealmTransformReadable(
+ ScriptState*,
+ MessagePort* port,
+ ExceptionState&);
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_TRANSFERABLE_STREAMS_H_
diff --git a/chromium/third_party/blink/renderer/core/streams/transferable_streams_test.cc b/chromium/third_party/blink/renderer/core/streams/transferable_streams_test.cc
new file mode 100644
index 00000000000..3811b0541e5
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/streams/transferable_streams_test.cc
@@ -0,0 +1,129 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/streams/transferable_streams.h"
+
+#include "testing/gtest/include/gtest/gtest.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_value.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.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_default_reader.h"
+#include "third_party/blink/renderer/bindings/core/v8/v8_writable_stream_default_writer.h"
+#include "third_party/blink/renderer/core/messaging/message_channel.h"
+#include "third_party/blink/renderer/core/streams/readable_stream_default_reader.h"
+#include "third_party/blink/renderer/core/streams/readable_stream_native.h"
+#include "third_party/blink/renderer/core/streams/writable_stream_default_writer.h"
+#include "third_party/blink/renderer/core/streams/writable_stream_native.h"
+#include "third_party/blink/renderer/platform/bindings/exception_state.h"
+#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
+
+namespace blink {
+
+namespace {
+
+// We only do minimal testing here. The functionality of transferable streams is
+// tested in the layout tests.
+TEST(TransferableStreamsTest, SmokeTest) {
+ V8TestingScope scope;
+
+ auto* channel =
+ MakeGarbageCollected<MessageChannel>(scope.GetExecutionContext());
+ auto* script_state = scope.GetScriptState();
+ auto* writable = CreateCrossRealmTransformWritable(
+ script_state, channel->port1(), ASSERT_NO_EXCEPTION);
+ ASSERT_TRUE(writable);
+ auto* readable = CreateCrossRealmTransformReadable(
+ script_state, channel->port2(), ASSERT_NO_EXCEPTION);
+ ASSERT_TRUE(readable);
+
+ auto* writer = V8WritableStreamDefaultWriter::ToImpl(
+ writable->getWriter(script_state, ASSERT_NO_EXCEPTION)
+ .V8Value()
+ .As<v8::Object>());
+ auto* reader = V8ReadableStreamDefaultReader::ToImpl(
+ readable->getReader(script_state, ASSERT_NO_EXCEPTION)
+ .V8Value()
+ .As<v8::Object>());
+
+ writer->write(script_state, ScriptValue::CreateNull(script_state));
+
+ class ExpectNullResponse : public ScriptFunction {
+ public:
+ static v8::Local<v8::Function> Create(ScriptState* script_state,
+ bool* got_response) {
+ auto* self =
+ MakeGarbageCollected<ExpectNullResponse>(script_state, got_response);
+ return self->BindToV8Function();
+ }
+
+ ExpectNullResponse(ScriptState* script_state, bool* got_response)
+ : ScriptFunction(script_state), got_response_(got_response) {}
+
+ private:
+ ScriptValue Call(ScriptValue value) override {
+ *got_response_ = true;
+ if (!value.IsObject()) {
+ ADD_FAILURE() << "iterator must be an object";
+ return ScriptValue();
+ }
+ bool done = false;
+ auto* script_state = GetScriptState();
+ auto chunk_maybe =
+ V8UnpackIteratorResult(script_state,
+ value.V8Value()
+ ->ToObject(script_state->GetContext())
+ .ToLocalChecked(),
+ &done);
+ EXPECT_FALSE(done);
+ v8::Local<v8::Value> chunk;
+ if (!chunk_maybe.ToLocal(&chunk)) {
+ ADD_FAILURE() << "V8UnpackIteratorResult failed";
+ return ScriptValue();
+ }
+ EXPECT_TRUE(chunk->IsNull());
+ return ScriptValue();
+ }
+
+ bool* got_response_;
+ };
+
+ // TODO(ricea): This is copy-and-pasted from transform_stream_test.cc. Put it
+ // in a shared location.
+ class ExpectNotReached : public ScriptFunction {
+ public:
+ static v8::Local<v8::Function> Create(ScriptState* script_state) {
+ auto* self = MakeGarbageCollected<ExpectNotReached>(script_state);
+ return self->BindToV8Function();
+ }
+
+ explicit ExpectNotReached(ScriptState* script_state)
+ : ScriptFunction(script_state) {}
+
+ private:
+ ScriptValue Call(ScriptValue) override {
+ ADD_FAILURE() << "ExpectNotReached was reached";
+ return ScriptValue();
+ }
+ };
+
+ bool got_response = false;
+ reader->read(script_state)
+ .Then(ExpectNullResponse::Create(script_state, &got_response),
+ ExpectNotReached::Create(script_state));
+
+ // Need to run the event loop to pass messages through the MessagePort.
+ test::RunPendingTasks();
+
+ // Resolve promises.
+ v8::MicrotasksScope::PerformCheckpoint(scope.GetIsolate());
+
+ EXPECT_TRUE(got_response);
+}
+
+} // namespace
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/streams/transform_stream_default_controller_interface.h b/chromium/third_party/blink/renderer/core/streams/transform_stream_default_controller_interface.h
index 3ce613810ae..d87de7fea31 100644
--- a/chromium/third_party/blink/renderer/core/streams/transform_stream_default_controller_interface.h
+++ b/chromium/third_party/blink/renderer/core/streams/transform_stream_default_controller_interface.h
@@ -7,7 +7,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "v8/include/v8.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/streams/transform_stream_native.cc b/chromium/third_party/blink/renderer/core/streams/transform_stream_native.cc
index 79040dae29f..825cece3098 100644
--- a/chromium/third_party/blink/renderer/core/streams/transform_stream_native.cc
+++ b/chromium/third_party/blink/renderer/core/streams/transform_stream_native.cc
@@ -5,7 +5,6 @@
#include "third_party/blink/renderer/core/streams/transform_stream_native.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/streams/miscellaneous_operations.h"
#include "third_party/blink/renderer/core/streams/promise_handler.h"
#include "third_party/blink/renderer/core/streams/readable_stream_default_controller.h"
@@ -22,7 +21,8 @@
#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/heap/visitor.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/streams/transform_stream_wrapper.h b/chromium/third_party/blink/renderer/core/streams/transform_stream_wrapper.h
index 022a175c8be..f0668dffaad 100644
--- a/chromium/third_party/blink/renderer/core/streams/transform_stream_wrapper.h
+++ b/chromium/third_party/blink/renderer/core/streams/transform_stream_wrapper.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
#include "third_party/blink/renderer/platform/heap/member.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "v8/include/v8.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/streams/underlying_sink_base.h b/chromium/third_party/blink/renderer/core/streams/underlying_sink_base.h
index 515b64cd552..9dd9e0bf5ee 100644
--- a/chromium/third_party/blink/renderer/core/streams/underlying_sink_base.h
+++ b/chromium/third_party/blink/renderer/core/streams/underlying_sink_base.h
@@ -5,6 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_UNDERLYING_SINK_BASE_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_UNDERLYING_SINK_BASE_H_
+#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/streams/writable_stream_default_controller_interface.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
@@ -12,7 +13,6 @@
namespace blink {
-class ScriptPromise;
class ScriptValue;
class ScriptState;
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 6e4ccc9f619..9efc0fe8ad5 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
@@ -47,22 +47,6 @@ ScriptValue UnderlyingSourceBase::type(ScriptState* script_state) const {
return ScriptValue(script_state, v8::Undefined(script_state->GetIsolate()));
}
-void UnderlyingSourceBase::notifyLockAcquired() {
- is_stream_locked_ = true;
-}
-
-void UnderlyingSourceBase::notifyLockReleased() {
- is_stream_locked_ = false;
-}
-
-bool UnderlyingSourceBase::HasPendingActivity() const {
- // This will return false within a finite time period _assuming_ that
- // consumers use the controller to close or error the stream.
- // Browser-created readable streams should always close or error within a
- // finite time period, due to timeouts etc.
- return controller_ && controller_->IsActive() && is_stream_locked_;
-}
-
void UnderlyingSourceBase::ContextDestroyed(ExecutionContext*) {
if (controller_) {
controller_->NoteHasBeenCanceled();
diff --git a/chromium/third_party/blink/renderer/core/streams/underlying_source_base.h b/chromium/third_party/blink/renderer/core/streams/underlying_source_base.h
index 55abd8e3dfb..664f30e87d5 100644
--- a/chromium/third_party/blink/renderer/core/streams/underlying_source_base.h
+++ b/chromium/third_party/blink/renderer/core/streams/underlying_source_base.h
@@ -22,7 +22,6 @@ class ReadableStreamDefaultControllerInterface;
class CORE_EXPORT UnderlyingSourceBase
: public ScriptWrappable,
- public ActiveScriptWrappable<UnderlyingSourceBase>,
public ContextLifecycleObserver {
DEFINE_WRAPPERTYPEINFO();
USING_GARBAGE_COLLECTED_MIXIN(UnderlyingSourceBase);
@@ -41,13 +40,8 @@ class CORE_EXPORT UnderlyingSourceBase
ScriptValue type(ScriptState*) const;
- void notifyLockAcquired();
- void notifyLockReleased();
-
- // ScriptWrappable
- bool HasPendingActivity() const override;
-
// ContextLifecycleObserver
+ // TODO(ricea): Is this still useful?
void ContextDestroyed(ExecutionContext*) override;
protected:
@@ -60,7 +54,6 @@ class CORE_EXPORT UnderlyingSourceBase
private:
Member<ReadableStreamDefaultControllerInterface> controller_;
- bool is_stream_locked_ = false;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/streams/underlying_source_base.idl b/chromium/third_party/blink/renderer/core/streams/underlying_source_base.idl
index d943658bcc2..bdf11311634 100644
--- a/chromium/third_party/blink/renderer/core/streams/underlying_source_base.idl
+++ b/chromium/third_party/blink/renderer/core/streams/underlying_source_base.idl
@@ -8,7 +8,6 @@
// automatically for use in initializing a ReadableStream.
[
- ActiveScriptWrappable,
NoInterfaceObject
]
interface UnderlyingSourceBase {
@@ -18,7 +17,4 @@ interface UnderlyingSourceBase {
// This only exists to prevent Object.prototype.type being accessed.
[CallWith=ScriptState] readonly attribute any type;
-
- void notifyLockAcquired();
- void notifyLockReleased();
};
diff --git a/chromium/third_party/blink/renderer/core/streams/writable_stream.cc b/chromium/third_party/blink/renderer/core/streams/writable_stream.cc
index da3db6e90c5..f0817bf8400 100644
--- a/chromium/third_party/blink/renderer/core/streams/writable_stream.cc
+++ b/chromium/third_party/blink/renderer/core/streams/writable_stream.cc
@@ -53,11 +53,27 @@ WritableStream* WritableStream::Create(ScriptState* script_state,
return stream;
}
+WritableStream* WritableStream::CreateWithCountQueueingStrategy(
+ ScriptState* script_state,
+ UnderlyingSinkBase* underlying_sink,
+ size_t high_water_mark) {
+ if (RuntimeEnabledFeatures::StreamsNativeEnabled()) {
+ return WritableStreamNative::CreateWithCountQueueingStrategy(
+ script_state, underlying_sink, high_water_mark);
+ }
+
+ return WritableStreamWrapper::CreateWithCountQueueingStrategy(
+ script_state, underlying_sink, high_water_mark);
+}
+
// static
WritableStream* WritableStream::Deserialize(ScriptState* script_state,
MessagePort* port,
ExceptionState& exception_state) {
- // TODO(ricea): Switch on Blink feature.
+ if (RuntimeEnabledFeatures::StreamsNativeEnabled()) {
+ return WritableStreamNative::Deserialize(script_state, port,
+ exception_state);
+ }
return WritableStreamWrapper::Deserialize(script_state, port,
exception_state);
}
diff --git a/chromium/third_party/blink/renderer/core/streams/writable_stream.h b/chromium/third_party/blink/renderer/core/streams/writable_stream.h
index 2d57e2195b9..cbc4f61654b 100644
--- a/chromium/third_party/blink/renderer/core/streams/writable_stream.h
+++ b/chromium/third_party/blink/renderer/core/streams/writable_stream.h
@@ -15,6 +15,7 @@
namespace blink {
class MessagePort;
+class UnderlyingSinkBase;
// This is an implementation of the corresponding IDL interface.
class CORE_EXPORT WritableStream : public ScriptWrappable {
@@ -31,6 +32,10 @@ class CORE_EXPORT WritableStream : public ScriptWrappable {
ScriptValue underlying_sink,
ScriptValue strategy,
ExceptionState&);
+ static WritableStream* CreateWithCountQueueingStrategy(
+ ScriptState*,
+ UnderlyingSinkBase*,
+ size_t high_water_mark);
// IDL defined functions
virtual bool locked(ScriptState*, ExceptionState&) const = 0;
diff --git a/chromium/third_party/blink/renderer/core/streams/writable_stream_default_writer.h b/chromium/third_party/blink/renderer/core/streams/writable_stream_default_writer.h
index 1bb5bea8112..fbe239eac20 100644
--- a/chromium/third_party/blink/renderer/core/streams/writable_stream_default_writer.h
+++ b/chromium/third_party/blink/renderer/core/streams/writable_stream_default_writer.h
@@ -6,6 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_STREAMS_WRITABLE_STREAM_DEFAULT_WRITER_H_
#include "base/optional.h"
+#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "v8/include/v8.h"
@@ -21,7 +22,7 @@ class WritableStream;
class WritableStreamNative;
// https://streams.spec.whatwg.org/#default-writer-class
-class WritableStreamDefaultWriter final : public ScriptWrappable {
+class CORE_EXPORT WritableStreamDefaultWriter final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
diff --git a/chromium/third_party/blink/renderer/core/streams/writable_stream_native.cc b/chromium/third_party/blink/renderer/core/streams/writable_stream_native.cc
index 262a9833c1b..4c8477811ac 100644
--- a/chromium/third_party/blink/renderer/core/streams/writable_stream_native.cc
+++ b/chromium/third_party/blink/renderer/core/streams/writable_stream_native.cc
@@ -7,7 +7,11 @@
#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
#include "third_party/blink/renderer/core/streams/miscellaneous_operations.h"
#include "third_party/blink/renderer/core/streams/promise_handler.h"
+#include "third_party/blink/renderer/core/streams/readable_stream_native.h"
+#include "third_party/blink/renderer/core/streams/readable_stream_operations.h"
#include "third_party/blink/renderer/core/streams/stream_promise_resolver.h"
+#include "third_party/blink/renderer/core/streams/transferable_streams.h"
+#include "third_party/blink/renderer/core/streams/underlying_sink_base.h"
#include "third_party/blink/renderer/core/streams/writable_stream_default_controller.h"
#include "third_party/blink/renderer/core/streams/writable_stream_default_writer.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
@@ -215,6 +219,67 @@ WritableStreamNative* WritableStreamNative::Create(
return stream;
}
+// static
+WritableStreamNative* WritableStreamNative::CreateWithCountQueueingStrategy(
+ ScriptState* script_state,
+ UnderlyingSinkBase* underlying_sink,
+ size_t high_water_mark) {
+ // TODO(crbug.com/902633): This method of constructing a WritableStream
+ // introduces unnecessary trips through the V8. Perhaps we should implement
+ // algorithms based on an UnderlyingSinkBase, or C++ stream implementations
+ // should provide the algorithms directly.
+ ScriptValue strategy = ReadableStreamOperations::CreateCountQueuingStrategy(
+ script_state, high_water_mark);
+ if (strategy.IsEmpty())
+ return nullptr;
+
+ auto underlying_sink_value = ScriptValue::From(script_state, underlying_sink);
+
+ ExceptionState exception_state(script_state->GetIsolate(),
+ ExceptionState::kConstructionContext,
+ "WritableStream");
+ auto* stream = MakeGarbageCollected<WritableStreamNative>(
+ script_state, underlying_sink_value, strategy, exception_state);
+ if (exception_state.HadException())
+ return nullptr;
+ return stream;
+}
+
+void WritableStreamNative::Serialize(ScriptState* script_state,
+ MessagePort* port,
+ ExceptionState& exception_state) {
+ if (IsLocked(this)) {
+ exception_state.ThrowTypeError("Cannot transfer a locked stream");
+ return;
+ }
+
+ auto* readable =
+ CreateCrossRealmTransformReadable(script_state, port, exception_state);
+ if (exception_state.HadException()) {
+ return;
+ }
+
+ auto promise = ReadableStreamNative::PipeTo(
+ script_state, readable, this, ReadableStreamNative::PipeOptions());
+ promise.MarkAsHandled();
+}
+
+WritableStreamNative* WritableStreamNative::Deserialize(
+ ScriptState* script_state,
+ MessagePort* port,
+ ExceptionState& exception_state) {
+ // We need to execute JavaScript to call "Then" on v8::Promises. We will not
+ // run author code.
+ v8::Isolate::AllowJavascriptExecutionScope allow_js(
+ script_state->GetIsolate());
+ auto* writable =
+ CreateCrossRealmTransformWritable(script_state, port, exception_state);
+ if (exception_state.HadException()) {
+ return nullptr;
+ }
+ return writable;
+}
+
WritableStreamDefaultWriter* WritableStreamNative::AcquireDefaultWriter(
ScriptState* script_state,
WritableStreamNative* stream,
diff --git a/chromium/third_party/blink/renderer/core/streams/writable_stream_native.h b/chromium/third_party/blink/renderer/core/streams/writable_stream_native.h
index 64f80fc2fdd..e37cac9a68c 100644
--- a/chromium/third_party/blink/renderer/core/streams/writable_stream_native.h
+++ b/chromium/third_party/blink/renderer/core/streams/writable_stream_native.h
@@ -20,6 +20,7 @@ class StrategySizeAlgorithm;
class StreamAlgorithm;
class StreamPromiseResolver;
class StreamStartAlgorithm;
+class UnderlyingSinkBase;
class WritableStreamDefaultController;
class WritableStreamDefaultWriter;
@@ -44,6 +45,11 @@ class CORE_EXPORT WritableStreamNative : public WritableStream {
StrategySizeAlgorithm* size_algorithm,
ExceptionState&);
+ static WritableStreamNative* CreateWithCountQueueingStrategy(
+ ScriptState*,
+ UnderlyingSinkBase*,
+ size_t high_water_mark);
+
// Used by Create().
WritableStreamNative();
@@ -83,9 +89,11 @@ class CORE_EXPORT WritableStreamNative : public WritableStream {
return stream->writer_;
}
- void Serialize(ScriptState*, MessagePort*, ExceptionState&) override {
- // TODO(ricea): Implement this.
- }
+ void Serialize(ScriptState*, MessagePort*, ExceptionState&) override;
+
+ static WritableStreamNative* Deserialize(ScriptState*,
+ MessagePort*,
+ ExceptionState&);
//
// Methods used by ReadableStreamNative::PipeTo
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
index 5401cc714fc..e87946d1063 100644
--- a/chromium/third_party/blink/renderer/core/streams/writable_stream_test.cc
+++ b/chromium/third_party/blink/renderer/core/streams/writable_stream_test.cc
@@ -60,12 +60,6 @@ TEST_P(WritableStreamTest, GetWriter) {
}
TEST_P(WritableStreamTest, Serialize) {
- // Disable the test when StreamsNative is enabled as WritableStreamNative
- // doesn't support serialization yet.
- // TODO(ricea): Re-enable this test when serialization is supported.
- if (GetParam())
- return;
-
ScopedTransferableStreamsForTest enable_transferable_streams(true);
V8TestingScope scope;
diff --git a/chromium/third_party/blink/renderer/core/streams/writable_stream_wrapper.cc b/chromium/third_party/blink/renderer/core/streams/writable_stream_wrapper.cc
index 277aa68d67a..6e6ffcd7ab3 100644
--- a/chromium/third_party/blink/renderer/core/streams/writable_stream_wrapper.cc
+++ b/chromium/third_party/blink/renderer/core/streams/writable_stream_wrapper.cc
@@ -7,6 +7,8 @@
#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/readable_stream_operations.h"
+#include "third_party/blink/renderer/core/streams/underlying_sink_base.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"
@@ -46,6 +48,27 @@ WritableStreamWrapper* WritableStreamWrapper::CreateFromInternalStream(
return stream;
}
+WritableStreamWrapper* WritableStreamWrapper::CreateWithCountQueueingStrategy(
+ ScriptState* script_state,
+ UnderlyingSinkBase* underlying_sink,
+ size_t high_water_mark) {
+ ScriptValue strategy = ReadableStreamOperations::CreateCountQueuingStrategy(
+ script_state, high_water_mark);
+ if (strategy.IsEmpty())
+ return nullptr;
+
+ auto underlying_sink_value = ScriptValue::From(script_state, underlying_sink);
+ auto* stream = MakeGarbageCollected<WritableStreamWrapper>();
+
+ ExceptionState exception_state(script_state->GetIsolate(),
+ ExceptionState::kConstructionContext,
+ "WritableStream");
+ stream->Init(script_state, underlying_sink_value, strategy, exception_state);
+ if (exception_state.HadException())
+ return nullptr;
+ return stream;
+}
+
bool WritableStreamWrapper::InitInternal(
ScriptState* script_state,
v8::Local<v8::Object> internal_stream) {
diff --git a/chromium/third_party/blink/renderer/core/streams/writable_stream_wrapper.h b/chromium/third_party/blink/renderer/core/streams/writable_stream_wrapper.h
index 4a24ad85ae6..658c6d10225 100644
--- a/chromium/third_party/blink/renderer/core/streams/writable_stream_wrapper.h
+++ b/chromium/third_party/blink/renderer/core/streams/writable_stream_wrapper.h
@@ -16,6 +16,7 @@
namespace blink {
class MessagePort;
+class WritableStreamWrapper;
// This is an implementation of the WritableStream interface that delegates to
// the V8 Extras implementation.
@@ -46,6 +47,11 @@ class CORE_EXPORT WritableStreamWrapper final : public WritableStream {
v8::Local<v8::Object> internal_stream,
ExceptionState&);
+ static WritableStreamWrapper* CreateWithCountQueueingStrategy(
+ ScriptState*,
+ UnderlyingSinkBase*,
+ size_t high_water_mark);
+
void Trace(Visitor* visitor) override;
// IDL defined functions
diff --git a/chromium/third_party/blink/renderer/core/style/applied_text_decoration.h b/chromium/third_party/blink/renderer/core/style/applied_text_decoration.h
index be8772e3c4e..5d8855aa661 100644
--- a/chromium/third_party/blink/renderer/core/style/applied_text_decoration.h
+++ b/chromium/third_party/blink/renderer/core/style/applied_text_decoration.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/style/computed_style_constants.h"
#include "third_party/blink/renderer/platform/graphics/color.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.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 9c852ff3863..d73aa6ef36f 100644
--- a/chromium/third_party/blink/renderer/core/style/basic_shapes.h
+++ b/chromium/third_party/blink/renderer/core/style/basic_shapes.h
@@ -35,7 +35,7 @@
#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/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/casting.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_edge.h b/chromium/third_party/blink/renderer/core/style/border_edge.h
index 623b9626492..86fcbc74214 100644
--- a/chromium/third_party/blink/renderer/core/style/border_edge.h
+++ b/chromium/third_party/blink/renderer/core/style/border_edge.h
@@ -7,7 +7,7 @@
#include "third_party/blink/renderer/core/style/computed_style_constants.h"
#include "third_party/blink/renderer/platform/graphics/color.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 12ec360a327..fba0e1a0bf2 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
@@ -32,7 +32,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_BORDER_IMAGE_LENGTH_H_
#include "third_party/blink/renderer/platform/geometry/length.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/style/border_image_length_box.h b/chromium/third_party/blink/renderer/core/style/border_image_length_box.h
index 6c75b2e0131..c6187a43faf 100644
--- a/chromium/third_party/blink/renderer/core/style/border_image_length_box.h
+++ b/chromium/third_party/blink/renderer/core/style/border_image_length_box.h
@@ -32,7 +32,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_BORDER_IMAGE_LENGTH_BOX_H_
#include "third_party/blink/renderer/core/style/border_image_length.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/style/border_style.h b/chromium/third_party/blink/renderer/core/style/border_style.h
index 0702b117871..53c279f5be5 100644
--- a/chromium/third_party/blink/renderer/core/style/border_style.h
+++ b/chromium/third_party/blink/renderer/core/style/border_style.h
@@ -28,7 +28,7 @@
#include "third_party/blink/renderer/core/css/style_color.h"
#include "third_party/blink/renderer/core/style/computed_style_constants.h"
#include "third_party/blink/renderer/platform/graphics/color.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/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 46ff11342c1..af4aa75c443 100644
--- a/chromium/third_party/blink/renderer/core/style/border_value.h
+++ b/chromium/third_party/blink/renderer/core/style/border_value.h
@@ -28,7 +28,7 @@
#include "third_party/blink/renderer/core/css/style_color.h"
#include "third_party/blink/renderer/core/style/computed_style_constants.h"
#include "third_party/blink/renderer/platform/graphics/color.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 4a8a479b045..9bd97ccbcf6 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
@@ -32,7 +32,7 @@
#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/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/style/clip_path_operation.h b/chromium/third_party/blink/renderer/core/style/clip_path_operation.h
index e09bd0bd900..289ab950143 100644
--- a/chromium/third_party/blink/renderer/core/style/clip_path_operation.h
+++ b/chromium/third_party/blink/renderer/core/style/clip_path_operation.h
@@ -30,7 +30,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_CLIP_PATH_OPERATION_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_CLIP_PATH_OPERATION_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
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 1da88d7b5fb..71a3c95f95d 100644
--- a/chromium/third_party/blink/renderer/core/style/computed_style.cc
+++ b/chromium/third_party/blink/renderer/core/style/computed_style.cc
@@ -72,6 +72,7 @@
#include "third_party/blink/renderer/platform/wtf/assertions.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
#include "third_party/blink/renderer/platform/wtf/size_assertions.h"
+#include "third_party/blink/renderer/platform/wtf/text/case_map.h"
namespace blink {
@@ -152,8 +153,6 @@ scoped_refptr<ComputedStyle>
ComputedStyle::CreateInheritedDisplayContentsStyleIfNeeded(
const ComputedStyle& parent_style,
const ComputedStyle& layout_parent_style) {
- if (&parent_style == &layout_parent_style)
- return nullptr;
if (parent_style.InheritedEqual(layout_parent_style))
return nullptr;
return ComputedStyle::CreateAnonymousStyleWithDisplay(parent_style,
@@ -237,32 +236,54 @@ ComputedStyle::Difference ComputedStyle::ComputeDifference(
return Difference::kEqual;
if (!old_style || !new_style)
return Difference::kInherited;
- if (old_style->Display() != new_style->Display() &&
- (old_style->IsDisplayFlexibleOrGridBox() ||
- old_style->IsDisplayLayoutCustomBox() ||
- new_style->IsDisplayFlexibleOrGridBox() ||
- old_style->IsDisplayLayoutCustomBox())) {
+
+ // For inline elements, the new computed first line style will be |new_style|
+ // inheriting from the parent's first line style. If |new_style| is different
+ // from |old_style|'s cached inherited first line style, the new computed
+ // first line style may be different from the old even if |new_style| and
+ // |old_style| equal. Especially if the difference is on inherited properties,
+ // we need to propagate the difference to descendants.
+ // See external/wpt/css/css-pseudo/first-line-change-inline-color*.html.
+ auto inherited_first_line_style_diff = Difference::kEqual;
+ if (const ComputedStyle* cached_inherited_first_line_style =
+ old_style->GetCachedPseudoStyle(kPseudoIdFirstLineInherited)) {
+ DCHECK(!new_style->GetCachedPseudoStyle(kPseudoIdFirstLineInherited));
+ inherited_first_line_style_diff =
+ ComputeDifferenceIgnoringInheritedFirstLineStyle(
+ *cached_inherited_first_line_style, *new_style);
+ }
+ return std::max(
+ inherited_first_line_style_diff,
+ ComputeDifferenceIgnoringInheritedFirstLineStyle(*old_style, *new_style));
+}
+
+ComputedStyle::Difference
+ComputedStyle::ComputeDifferenceIgnoringInheritedFirstLineStyle(
+ const ComputedStyle& old_style,
+ const ComputedStyle& new_style) {
+ DCHECK_NE(&old_style, &new_style);
+ if (old_style.Display() != new_style.Display() &&
+ old_style.BlockifiesChildren() != new_style.BlockifiesChildren())
return Difference::kDisplayAffectingDescendantStyles;
- }
- if (!old_style->NonIndependentInheritedEqual(*new_style))
+ if (!old_style.NonIndependentInheritedEqual(new_style))
return Difference::kInherited;
- if (!old_style->LoadingCustomFontsEqual(*new_style) ||
- old_style->JustifyItems() != new_style->JustifyItems())
+ if (!old_style.LoadingCustomFontsEqual(new_style) ||
+ old_style.JustifyItems() != new_style.JustifyItems())
return Difference::kInherited;
- bool non_inherited_equal = old_style->NonInheritedEqual(*new_style);
- if (!non_inherited_equal && old_style->HasExplicitlyInheritedProperties()) {
+ bool non_inherited_equal = old_style.NonInheritedEqual(new_style);
+ if (!non_inherited_equal && old_style.HasExplicitlyInheritedProperties()) {
return Difference::kInherited;
}
- if (!old_style->IndependentInheritedEqual(*new_style))
+ if (!old_style.IndependentInheritedEqual(new_style))
return Difference::kIndependentInherited;
if (non_inherited_equal) {
- DCHECK(*old_style == *new_style);
- if (PseudoStylesEqual(*old_style, *new_style))
+ DCHECK(old_style == new_style);
+ if (PseudoStylesEqual(old_style, new_style))
return Difference::kEqual;
return Difference::kPseudoStyle;
}
- if (new_style->HasAnyPublicPseudoStyles() ||
- old_style->HasAnyPublicPseudoStyles())
+ if (new_style.HasAnyPublicPseudoStyles() ||
+ old_style.HasAnyPublicPseudoStyles())
return Difference::kPseudoStyle;
return Difference::kNonInherited;
}
@@ -459,7 +480,7 @@ const ComputedStyle* ComputedStyle::GetCachedPseudoStyle(PseudoId pid) const {
}
const ComputedStyle* ComputedStyle::AddCachedPseudoStyle(
- scoped_refptr<ComputedStyle> pseudo) {
+ scoped_refptr<const ComputedStyle> pseudo) const {
DCHECK(pseudo);
DCHECK_GT(pseudo->StyleType(), kPseudoIdNone);
@@ -1510,12 +1531,18 @@ void ComputedStyle::ApplyTextTransform(String* text,
case ETextTransform::kCapitalize:
*text = Capitalize(*text, previous_character);
return;
- case ETextTransform::kUppercase:
- *text = DisableNewGeorgianCapitalLetters(text->UpperUnicode(Locale()));
+ case ETextTransform::kUppercase: {
+ const LayoutLocale* locale = GetFontDescription().Locale();
+ CaseMap case_map(locale ? locale->CaseMapLocale() : CaseMap::Locale());
+ *text = DisableNewGeorgianCapitalLetters(case_map.ToUpper(*text));
return;
- case ETextTransform::kLowercase:
- *text = text->LowerUnicode(Locale());
+ }
+ case ETextTransform::kLowercase: {
+ const LayoutLocale* locale = GetFontDescription().Locale();
+ CaseMap case_map(locale ? locale->CaseMapLocale() : CaseMap::Locale());
+ *text = case_map.ToLower(*text);
return;
+ }
}
NOTREACHED();
}
@@ -2015,8 +2042,8 @@ void ComputedStyle::ClearMultiCol() {
ComputedStyleInitialValues::InitialColumnRuleColor());
SetColumnRuleColorIsCurrentColor(
ComputedStyleInitialValues::InitialColumnRuleColorIsCurrentColor());
- SetVisitedLinkColumnRuleColorInternal(
- ComputedStyleInitialValues::InitialVisitedLinkColumnRuleColor());
+ SetInternalVisitedColumnRuleColorInternal(
+ ComputedStyleInitialValues::InitialInternalVisitedColumnRuleColor());
SetColumnCountInternal(ComputedStyleInitialValues::InitialColumnCount());
SetHasAutoColumnCountInternal(
ComputedStyleInitialValues::InitialHasAutoColumnCount());
@@ -2028,8 +2055,8 @@ void ComputedStyle::ClearMultiCol() {
StyleColor ComputedStyle::DecorationColorIncludingFallback(
bool visited_link) const {
- StyleColor style_color =
- visited_link ? VisitedLinkTextDecorationColor() : TextDecorationColor();
+ StyleColor style_color = visited_link ? InternalVisitedTextDecorationColor()
+ : TextDecorationColor();
if (!style_color.IsCurrentColor())
return style_color;
@@ -2037,24 +2064,35 @@ StyleColor ComputedStyle::DecorationColorIncludingFallback(
if (TextStrokeWidth()) {
// Prefer stroke color if possible, but not if it's fully transparent.
StyleColor text_stroke_style_color =
- visited_link ? VisitedLinkTextStrokeColor() : TextStrokeColor();
+ visited_link ? InternalVisitedTextStrokeColor() : TextStrokeColor();
if (!text_stroke_style_color.IsCurrentColor() &&
text_stroke_style_color.GetColor().Alpha())
return text_stroke_style_color;
}
- return visited_link ? VisitedLinkTextFillColor() : TextFillColor();
+ return visited_link ? InternalVisitedTextFillColor() : TextFillColor();
}
Color ComputedStyle::VisitedDependentColor(
const CSSProperty& color_property) const {
+ DCHECK(!color_property.IsVisited());
+
Color unvisited_color =
To<Longhand>(color_property).ColorIncludingFallback(false, *this);
if (InsideLink() != EInsideLink::kInsideVisitedLink)
return unvisited_color;
+ // Properties that provide a GetVisitedProperty() must use the
+ // ColorIncludingFallback function on that property.
+ //
+ // TODO(andruud): Simplify this when all properties support
+ // GetVisitedProperty.
+ const CSSProperty* visited_property = &color_property;
+ if (const CSSProperty* visited = color_property.GetVisitedProperty())
+ visited_property = visited;
+
Color visited_color =
- To<Longhand>(color_property).ColorIncludingFallback(true, *this);
+ To<Longhand>(*visited_property).ColorIncludingFallback(true, *this);
// Take the alpha from the unvisited color, but get the RGB values from the
// visited color.
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 e72e62c7187..6185cf135c1 100644
--- a/chromium/third_party/blink/renderer/core/style/computed_style.h
+++ b/chromium/third_party/blink/renderer/core/style/computed_style.h
@@ -87,7 +87,7 @@ class StyleResolver;
class StyleSelfAlignmentData;
class TransformationMatrix;
-typedef Vector<scoped_refptr<ComputedStyle>, 4> PseudoStyleCache;
+typedef Vector<scoped_refptr<const ComputedStyle>, 4> PseudoStyleCache;
namespace css_longhand {
@@ -99,8 +99,21 @@ class BorderTopColor;
class CaretColor;
class Color;
class ColumnRuleColor;
-class FloodColor;
class Fill;
+class FloodColor;
+class InternalVisitedBackgroundColor;
+class InternalVisitedBorderBottomColor;
+class InternalVisitedBorderLeftColor;
+class InternalVisitedBorderRightColor;
+class InternalVisitedBorderTopColor;
+class InternalVisitedCaretColor;
+class InternalVisitedColor;
+class InternalVisitedColumnRuleColor;
+class InternalVisitedOutlineColor;
+class InternalVisitedTextDecorationColor;
+class InternalVisitedTextEmphasisColor;
+class InternalVisitedTextFillColor;
+class InternalVisitedTextStrokeColor;
class LightingColor;
class OutlineColor;
class StopColor;
@@ -187,8 +200,21 @@ class ComputedStyle : public ComputedStyleBase,
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::FloodColor;
+ friend class css_longhand::InternalVisitedBackgroundColor;
+ friend class css_longhand::InternalVisitedBorderBottomColor;
+ friend class css_longhand::InternalVisitedBorderLeftColor;
+ friend class css_longhand::InternalVisitedBorderRightColor;
+ friend class css_longhand::InternalVisitedBorderTopColor;
+ friend class css_longhand::InternalVisitedCaretColor;
+ friend class css_longhand::InternalVisitedColor;
+ friend class css_longhand::InternalVisitedColumnRuleColor;
+ friend class css_longhand::InternalVisitedOutlineColor;
+ friend class css_longhand::InternalVisitedTextDecorationColor;
+ friend class css_longhand::InternalVisitedTextEmphasisColor;
+ friend class css_longhand::InternalVisitedTextFillColor;
+ friend class css_longhand::InternalVisitedTextStrokeColor;
friend class css_longhand::LightingColor;
friend class css_longhand::OutlineColor;
friend class css_longhand::StopColor;
@@ -222,8 +248,25 @@ class ComputedStyle : public ComputedStyleBase,
friend class StyleResolver;
protected:
- // list of associated pseudo styles
- std::unique_ptr<PseudoStyleCache> cached_pseudo_styles_;
+ // This cache stores ComputedStyles for pseudo elements originating from this
+ // ComputedStyle's element. Pseudo elements which are represented by
+ // PseudoElement in DOM store the ComputedStyle on those elements, so this
+ // cache is for:
+ //
+ // 1. Pseudo elements which do not generate a PseudoElement internally like
+ // ::first-line and ::selection.
+ //
+ // 2. Pseudo element style requested from getComputedStyle() where the element
+ // currently doesn't generate a PseudoElement. E.g.:
+ //
+ // <style>
+ // #div::before { color: green /* no content property! */}
+ // </style>
+ // <div id=div></div>
+ // <script>
+ // getComputedStyle(div, "::before").color // still green.
+ // </script>
+ mutable std::unique_ptr<PseudoStyleCache> cached_pseudo_styles_;
DataRef<SVGComputedStyle> svg_style_;
@@ -321,11 +364,18 @@ class ComputedStyle : public ComputedStyleBase,
IsAtShadowBoundary = kNotAtShadowBoundary);
void CopyNonInheritedFromCached(const ComputedStyle&);
- PseudoId StyleType() const { return static_cast<PseudoId>(StyleTypeInternal()); }
+ PseudoId StyleType() const {
+ return static_cast<PseudoId>(StyleTypeInternal());
+ }
void SetStyleType(PseudoId style_type) { SetStyleTypeInternal(style_type); }
const ComputedStyle* GetCachedPseudoStyle(PseudoId) const;
- const ComputedStyle* AddCachedPseudoStyle(scoped_refptr<ComputedStyle>);
+ const ComputedStyle* AddCachedPseudoStyle(
+ scoped_refptr<const ComputedStyle>) const;
+ void ClearCachedPseudoStyles() const {
+ if (cached_pseudo_styles_)
+ cached_pseudo_styles_->clear();
+ }
/**
* ComputedStyle properties
@@ -828,6 +878,7 @@ class ComputedStyle : public ComputedStyleBase,
}
bool SetEffectiveZoom(float);
+ float EffectiveZoom() const;
// -webkit-clip-path
bool ClipPathDataEquivalent(const ComputedStyle& other) const {
@@ -991,9 +1042,9 @@ class ComputedStyle : public ComputedStyleBase,
void SetTabSize(const TabSize& t) {
if (t.GetPixelSize(1) < 0) {
if (t.IsSpaces())
- SetTabSizeInternal(0);
+ SetTabSizeInternal(TabSize(0, TabSizeValueType::kSpace));
else
- SetTabSizeInternal(0.0f);
+ SetTabSizeInternal(TabSize(0, TabSizeValueType::kLength));
} else {
SetTabSizeInternal(t);
}
@@ -1894,6 +1945,12 @@ class ComputedStyle : public ComputedStyleBase,
// Offset utility functions.
// Accessors for positioned object edges that take into account writing mode.
+ const Length& LogicalInlineStart() const {
+ return PhysicalBoundsToLogical().InlineStart();
+ }
+ const Length& LogicalInlineEnd() const {
+ return PhysicalBoundsToLogical().InlineEnd();
+ }
const Length& LogicalLeft() const {
return PhysicalBoundsToLogical().LineLeft();
}
@@ -1958,6 +2015,11 @@ class ComputedStyle : public ComputedStyleBase,
bool IsDisplayTableType() const { return IsDisplayTableType(Display()); }
+ bool BlockifiesChildren() const {
+ return IsDisplayFlexibleOrGridBox() || IsDisplayLayoutCustomBox() ||
+ (Display() == EDisplay::kContents && IsInBlockifyingDisplay());
+ }
+
// Isolation utility functions.
bool HasIsolation() const { return Isolation() != EIsolation::kAuto; }
@@ -2278,7 +2340,7 @@ class ComputedStyle : public ComputedStyleBase,
}
bool HasBackgroundRelatedColorReferencingCurrentColor() const {
if (BackgroundColor().IsCurrentColor() ||
- VisitedLinkBackgroundColor().IsCurrentColor())
+ InternalVisitedBackgroundColor().IsCurrentColor())
return true;
if (!BoxShadow())
return false;
@@ -2325,47 +2387,52 @@ class ComputedStyle : public ComputedStyleBase,
}
private:
- void SetVisitedLinkBackgroundColor(const StyleColor& v) {
- SetVisitedLinkBackgroundColorInternal(v);
+ void SetInternalVisitedColor(const Color& v) {
+ SetInternalVisitedColorInternal(v);
}
- void SetVisitedLinkBorderLeftColor(const StyleColor& v) {
- SetVisitedLinkBorderLeftColorInternal(v);
+ void SetInternalVisitedBackgroundColor(const StyleColor& v) {
+ SetInternalVisitedBackgroundColorInternal(v);
}
- void SetVisitedLinkBorderRightColor(const StyleColor& v) {
- SetVisitedLinkBorderRightColorInternal(v);
+ void SetInternalVisitedBorderLeftColor(const StyleColor& v) {
+ SetInternalVisitedBorderLeftColorInternal(v);
}
- void SetVisitedLinkBorderBottomColor(const StyleColor& v) {
- SetVisitedLinkBorderBottomColorInternal(v);
+ void SetInternalVisitedBorderRightColor(const StyleColor& v) {
+ SetInternalVisitedBorderRightColorInternal(v);
}
- void SetVisitedLinkBorderTopColor(const StyleColor& v) {
- SetVisitedLinkBorderTopColorInternal(v);
+ void SetInternalVisitedBorderBottomColor(const StyleColor& v) {
+ SetInternalVisitedBorderBottomColorInternal(v);
}
- void SetVisitedLinkOutlineColor(const StyleColor& v) {
- SetVisitedLinkOutlineColorInternal(v);
+ void SetInternalVisitedBorderTopColor(const StyleColor& v) {
+ SetInternalVisitedBorderTopColorInternal(v);
}
- void SetVisitedLinkColumnRuleColor(const StyleColor& v) {
- SetVisitedLinkColumnRuleColorInternal(v);
+ void SetInternalVisitedOutlineColor(const StyleColor& v) {
+ SetInternalVisitedOutlineColorInternal(v);
}
- void SetVisitedLinkTextDecorationColor(const StyleColor& v) {
- SetVisitedLinkTextDecorationColorInternal(v);
+ void SetInternalVisitedColumnRuleColor(const StyleColor& v) {
+ SetInternalVisitedColumnRuleColorInternal(v);
}
- void SetVisitedLinkTextEmphasisColor(const StyleColor& color) {
- SetVisitedLinkTextEmphasisColorInternal(color.Resolve(Color()));
- SetVisitedLinkTextEmphasisColorIsCurrentColorInternal(
+ void SetInternalVisitedTextDecorationColor(const StyleColor& v) {
+ SetInternalVisitedTextDecorationColorInternal(v);
+ }
+ void SetInternalVisitedTextEmphasisColor(const StyleColor& color) {
+ SetInternalVisitedTextEmphasisColorInternal(color.Resolve(Color()));
+ SetInternalVisitedTextEmphasisColorIsCurrentColorInternal(
color.IsCurrentColor());
}
- void SetVisitedLinkTextFillColor(const StyleColor& color) {
- SetVisitedLinkTextFillColorInternal(color.Resolve(Color()));
- SetVisitedLinkTextFillColorIsCurrentColorInternal(color.IsCurrentColor());
+ void SetInternalVisitedTextFillColor(const StyleColor& color) {
+ SetInternalVisitedTextFillColorInternal(color.Resolve(Color()));
+ SetInternalVisitedTextFillColorIsCurrentColorInternal(
+ color.IsCurrentColor());
}
- void SetVisitedLinkTextStrokeColor(const StyleColor& color) {
- SetVisitedLinkTextStrokeColorInternal(color.Resolve(Color()));
- SetVisitedLinkTextStrokeColorIsCurrentColorInternal(color.IsCurrentColor());
+ void SetInternalVisitedTextStrokeColor(const StyleColor& color) {
+ SetInternalVisitedTextStrokeColorInternal(color.Resolve(Color()));
+ SetInternalVisitedTextStrokeColorIsCurrentColorInternal(
+ color.IsCurrentColor());
}
- void SetVisitedLinkCaretColor(const StyleAutoColor& color) {
- SetVisitedLinkCaretColorInternal(color.Resolve(Color()));
- SetVisitedLinkCaretColorIsCurrentColorInternal(color.IsCurrentColor());
- SetVisitedLinkCaretColorIsAutoInternal(color.IsAutoColor());
+ void SetInternalVisitedCaretColor(const StyleAutoColor& color) {
+ SetInternalVisitedCaretColorInternal(color.Resolve(Color()));
+ SetInternalVisitedCaretColorIsCurrentColorInternal(color.IsCurrentColor());
+ SetInternalVisitedCaretColorIsAutoInternal(color.IsAutoColor());
}
static bool IsDisplayBlockContainer(EDisplay display) {
@@ -2469,78 +2536,82 @@ class ComputedStyle : public ComputedStyleBase,
? StyleColor::CurrentColor()
: StyleColor(TextStrokeColorInternal());
}
- StyleAutoColor VisitedLinkCaretColor() const {
- if (VisitedLinkCaretColorIsCurrentColorInternal())
+ Color InternalVisitedColor() const { return InternalVisitedColorInternal(); }
+ StyleAutoColor InternalVisitedCaretColor() const {
+ if (InternalVisitedCaretColorIsCurrentColorInternal())
return StyleAutoColor::CurrentColor();
- if (VisitedLinkCaretColorIsAutoInternal())
+ if (InternalVisitedCaretColorIsAutoInternal())
return StyleAutoColor::AutoColor();
- return StyleAutoColor(VisitedLinkCaretColorInternal());
+ return StyleAutoColor(InternalVisitedCaretColorInternal());
}
- StyleColor VisitedLinkBackgroundColor() const {
- return VisitedLinkBackgroundColorInternal();
+ StyleColor InternalVisitedBackgroundColor() const {
+ return InternalVisitedBackgroundColorInternal();
}
- StyleColor VisitedLinkBorderLeftColor() const {
- return VisitedLinkBorderLeftColorInternal();
+ StyleColor InternalVisitedBorderLeftColor() const {
+ return InternalVisitedBorderLeftColorInternal();
}
- bool VisitedLinkBorderLeftColorHasNotChanged(
+ bool InternalVisitedBorderLeftColorHasNotChanged(
const ComputedStyle& other) const {
- return (VisitedLinkBorderLeftColor() ==
- other.VisitedLinkBorderLeftColor() ||
+ return (InternalVisitedBorderLeftColor() ==
+ other.InternalVisitedBorderLeftColor() ||
!BorderLeftWidth());
}
- StyleColor VisitedLinkBorderRightColor() const {
- return VisitedLinkBorderRightColorInternal();
+ StyleColor InternalVisitedBorderRightColor() const {
+ return InternalVisitedBorderRightColorInternal();
}
- bool VisitedLinkBorderRightColorHasNotChanged(
+ bool InternalVisitedBorderRightColorHasNotChanged(
const ComputedStyle& other) const {
- return (VisitedLinkBorderRightColor() ==
- other.VisitedLinkBorderRightColor() ||
+ return (InternalVisitedBorderRightColor() ==
+ other.InternalVisitedBorderRightColor() ||
!BorderRightWidth());
}
- StyleColor VisitedLinkBorderBottomColor() const {
- return VisitedLinkBorderBottomColorInternal();
+ StyleColor InternalVisitedBorderBottomColor() const {
+ return InternalVisitedBorderBottomColorInternal();
}
- bool VisitedLinkBorderBottomColorHasNotChanged(
+ bool InternalVisitedBorderBottomColorHasNotChanged(
const ComputedStyle& other) const {
- return (VisitedLinkBorderBottomColor() ==
- other.VisitedLinkBorderBottomColor() ||
+ return (InternalVisitedBorderBottomColor() ==
+ other.InternalVisitedBorderBottomColor() ||
!BorderBottomWidth());
}
- StyleColor VisitedLinkBorderTopColor() const {
- return VisitedLinkBorderTopColorInternal();
+ StyleColor InternalVisitedBorderTopColor() const {
+ return InternalVisitedBorderTopColorInternal();
}
- bool VisitedLinkBorderTopColorHasNotChanged(
+ bool InternalVisitedBorderTopColorHasNotChanged(
const ComputedStyle& other) const {
- return (VisitedLinkBorderTopColor() == other.VisitedLinkBorderTopColor() ||
+ return (InternalVisitedBorderTopColor() ==
+ other.InternalVisitedBorderTopColor() ||
!BorderTopWidth());
}
- StyleColor VisitedLinkOutlineColor() const {
- return VisitedLinkOutlineColorInternal();
+ StyleColor InternalVisitedOutlineColor() const {
+ return InternalVisitedOutlineColorInternal();
}
- bool VisitedLinkOutlineColorHasNotChanged(const ComputedStyle& other) const {
- return (VisitedLinkOutlineColor() == other.VisitedLinkOutlineColor() ||
+ bool InternalVisitedOutlineColorHasNotChanged(
+ const ComputedStyle& other) const {
+ return (InternalVisitedOutlineColor() ==
+ other.InternalVisitedOutlineColor() ||
!OutlineWidth());
}
- StyleColor VisitedLinkColumnRuleColor() const {
- return VisitedLinkColumnRuleColorInternal();
+ StyleColor InternalVisitedColumnRuleColor() const {
+ return InternalVisitedColumnRuleColorInternal();
}
- StyleColor VisitedLinkTextDecorationColor() const {
- return VisitedLinkTextDecorationColorInternal();
+ StyleColor InternalVisitedTextDecorationColor() const {
+ return InternalVisitedTextDecorationColorInternal();
}
- StyleColor VisitedLinkTextEmphasisColor() const {
- return VisitedLinkTextEmphasisColorIsCurrentColorInternal()
+ StyleColor InternalVisitedTextEmphasisColor() const {
+ return InternalVisitedTextEmphasisColorIsCurrentColorInternal()
? StyleColor::CurrentColor()
- : StyleColor(VisitedLinkTextEmphasisColorInternal());
+ : StyleColor(InternalVisitedTextEmphasisColorInternal());
}
- StyleColor VisitedLinkTextFillColor() const {
- return VisitedLinkTextFillColorIsCurrentColorInternal()
+ StyleColor InternalVisitedTextFillColor() const {
+ return InternalVisitedTextFillColorIsCurrentColorInternal()
? StyleColor::CurrentColor()
- : StyleColor(VisitedLinkTextFillColorInternal());
+ : StyleColor(InternalVisitedTextFillColorInternal());
}
- StyleColor VisitedLinkTextStrokeColor() const {
- return VisitedLinkTextStrokeColorIsCurrentColorInternal()
+ StyleColor InternalVisitedTextStrokeColor() const {
+ return InternalVisitedTextStrokeColorIsCurrentColorInternal()
? StyleColor::CurrentColor()
- : StyleColor(VisitedLinkTextStrokeColorInternal());
+ : StyleColor(InternalVisitedTextStrokeColorInternal());
}
StyleColor DecorationColorIncludingFallback(bool visited_link) const;
@@ -2625,6 +2696,10 @@ class ComputedStyle : public ComputedStyleBase,
Top(), Right(), Bottom(), Left());
}
+ static Difference ComputeDifferenceIgnoringInheritedFirstLineStyle(
+ const ComputedStyle& old_style,
+ const ComputedStyle& new_style);
+
FRIEND_TEST_ALL_PREFIXES(
ComputedStyleTest,
UpdatePropertySpecificDifferencesRespectsTransformAnimation);
@@ -2670,10 +2745,14 @@ inline bool ComputedStyle::SetEffectiveZoom(float f) {
float clamped_effective_zoom = clampTo<float>(f, 1e-6, 1e6);
if (EffectiveZoom() == clamped_effective_zoom)
return false;
- SetEffectiveZoomInternal(clamped_effective_zoom);
+ SetInternalEffectiveZoom(clamped_effective_zoom);
return true;
}
+inline float ComputedStyle::EffectiveZoom() const {
+ return InternalEffectiveZoom();
+}
+
inline bool ComputedStyle::HasAnyPublicPseudoStyles() const {
return PseudoBitsInternal() != kPseudoIdNone;
}
diff --git a/chromium/third_party/blink/renderer/core/style/computed_style_diff_functions.json5 b/chromium/third_party/blink/renderer/core/style/computed_style_diff_functions.json5
index 5cc6a3a4346..36e484b99f7 100644
--- a/chromium/third_party/blink/renderer/core/style/computed_style_diff_functions.json5
+++ b/chromium/third_party/blink/renderer/core/style/computed_style_diff_functions.json5
@@ -84,7 +84,7 @@
"-webkit-margin-before-collapse",
"-webkit-margin-after-collapse", "-webkit-line-clamp",
"text-overflow", "shape-margin", "order", "-webkit-highlight",
- "text-indent", "text-align-last", "TextIndentLine", "EffectiveZoom",
+ "text-indent", "text-align-last", "TextIndentLine", "-internal-effective-zoom",
"word-break", "overflow-wrap", "-webkit-line-break",
"-webkit-text-security", "hyphens", "HyphenationLimitBefore",
"HyphenationLimitAfter", "-webkit-hyphenate-character",
@@ -110,7 +110,7 @@
"-webkit-box-pack", "-webkit-box-orient",
"grid-row-start", "grid-row-end", "grid-column-start", "grid-column-end",
"column-gap", "column-width", "column-rule-style",
- "column-rule-width", "column-rule-color", "ColumnRuleColorIsCurrentColor", "VisitedLinkColumnRuleColor",
+ "column-rule-width", "column-rule-color", "ColumnRuleColorIsCurrentColor", "-internal-visited-column-rule-color",
"column-count", "HasAutoColumnCount", "HasAutoColumnWidth", "column-fill", "column-span",],
methods_to_diff: [
{
@@ -262,8 +262,8 @@
field_dependencies: ["InsideLink"]
},
{
- method: "VisitedLinkBackgroundColor()",
- field_dependencies: ["VisitedLinkBackgroundColor"]
+ method: "InternalVisitedBackgroundColor()",
+ field_dependencies: ["-internal-visited-background-color"]
},
{
method: "Resize()",
@@ -288,24 +288,24 @@
field_dependencies: ["outline-width", "outline-color", "OutlineColorIsCurrentColor", "outline-offset", "outline-style", "OutlineStyleIsAuto"]
},
{
- predicate: "a.VisitedLinkBorderLeftColorHasNotChanged(b)",
- field_dependencies: ["VisitedLinkBorderLeftColor"]
+ predicate: "a.InternalVisitedBorderLeftColorHasNotChanged(b)",
+ field_dependencies: ["-internal-visited-border-left-color"]
},
{
- predicate: "a.VisitedLinkBorderRightColorHasNotChanged(b)",
- field_dependencies: ["VisitedLinkBorderRightColor"]
+ predicate: "a.InternalVisitedBorderRightColorHasNotChanged(b)",
+ field_dependencies: ["-internal-visited-border-right-color"]
},
{
- predicate: "a.VisitedLinkBorderBottomColorHasNotChanged(b)",
- field_dependencies: ["VisitedLinkBorderBottomColor"]
+ predicate: "a.InternalVisitedBorderBottomColorHasNotChanged(b)",
+ field_dependencies: ["-internal-visited-border-bottom-color"]
},
{
- predicate: "a.VisitedLinkBorderTopColorHasNotChanged(b)",
- field_dependencies: ["VisitedLinkBorderTopColor"]
+ predicate: "a.InternalVisitedBorderTopColorHasNotChanged(b)",
+ field_dependencies: ["-internal-visited-border-top-color"]
},
{
- predicate: "a.VisitedLinkOutlineColorHasNotChanged(b)",
- field_dependencies: ["VisitedLinkOutlineColor"]
+ predicate: "a.InternalVisitedOutlineColorHasNotChanged(b)",
+ field_dependencies: ["-internal-visited-outline-color"]
},
]
},
@@ -412,9 +412,9 @@
},
{
name: "UpdatePropertySpecificDifferencesTextDecorationOrColor",
- fields_to_diff: ["color", "VisitedLinkColor", "text-decoration-line",
+ fields_to_diff: ["color", "-internal-visited-color", "text-decoration-line",
"text-decoration-style", "text-decoration-color",
- "VisitedLinkTextDecorationColor", "TextEmphasisFill",
+ "-internal-visited-text-decoration-color", "TextEmphasisFill",
"text-underline-position", "text-decoration-skip-ink", "AppliedTextDecorations"],
methods_to_diff: [
{
@@ -434,24 +434,24 @@
field_dependencies: ["-webkit-text-emphasis-color"]
},
{
- method: "VisitedLinkTextFillColor()",
- field_dependencies: ["VisitedLinkTextFillColor"]
+ method: "InternalVisitedTextFillColor()",
+ field_dependencies: ["-internal-visited-text-fill-color"]
},
{
- method: "VisitedLinkTextStrokeColor()",
- field_dependencies: ["VisitedLinkTextStrokeColor"]
+ method: "InternalVisitedTextStrokeColor()",
+ field_dependencies: ["-internal-visited-text-stroke-color"]
},
{
- method: "VisitedLinkTextEmphasisColor()",
- field_dependencies: ["VisitedLinkTextEmphasisColor"]
+ method: "InternalVisitedTextEmphasisColor()",
+ field_dependencies: ["-internal-visited-text-emphasis-color"]
},
{
method: "CaretColor()",
field_dependencies: ["caret-color"]
},
{
- method: "VisitedLinkCaretColor()",
- field_dependencies: ["VisitedLinkCaretColor"]
+ method: "InternalVisitedCaretColor()",
+ field_dependencies: ["-internal-visited-caret-color"]
},
]
},
diff --git a/chromium/third_party/blink/renderer/core/style/computed_style_extra_fields.json5 b/chromium/third_party/blink/renderer/core/style/computed_style_extra_fields.json5
index 88ffa92ee5b..b29f4d5df4c 100644
--- a/chromium/third_party/blink/renderer/core/style/computed_style_extra_fields.json5
+++ b/chromium/third_party/blink/renderer/core/style/computed_style_extra_fields.json5
@@ -113,6 +113,14 @@
keywords: ["not-inside-link", "inside-unvisited-link", "inside-visited-link"],
inherited: true,
},
+ // Whether we're inside an NG block fragmentation context.
+ {
+ name: "InsideNGFragmentationContext",
+ field_template: "primitive",
+ default_value: "false",
+ type_name: "bool",
+ inherited: true,
+ },
// Style has content property with attr() values.
{
name: "HasAttrContent",
@@ -277,13 +285,6 @@
computed_style_custom_functions: ["getter", "setter"],
},
{
- name: "VisitedLinkColor",
- inherited: true,
- field_template: "<color>",
- field_group: "inherited",
- default_value: "Color::kBlack",
- },
- {
name: "TextAutosizingMultiplier",
inherited: true,
field_template: "primitive",
@@ -293,46 +294,6 @@
computed_style_custom_functions: ["setter"],
},
{
- name: "VisitedLinkTextStrokeColor",
- inherited: true,
- field_template: "external",
- type_name: "Color",
- include_paths: ["third_party/blink/renderer/platform/graphics/color.h"],
- default_value: "Color()",
- field_group: "*",
- computed_style_custom_functions: ["getter", "setter"],
- },
- {
- name: "VisitedLinkTextFillColor",
- inherited: true,
- field_template: "external",
- type_name: "Color",
- include_paths: ["third_party/blink/renderer/platform/graphics/color.h"],
- default_value: "Color()",
- field_group: "*",
- computed_style_custom_functions: ["getter", "setter"],
- },
- {
- name: "VisitedLinkTextEmphasisColor",
- inherited: true,
- field_template: "external",
- type_name: "Color",
- include_paths: ["third_party/blink/renderer/platform/graphics/color.h"],
- default_value: "Color()",
- field_group: "*",
- computed_style_custom_functions: ["getter", "setter"],
- },
- {
- name: "VisitedLinkCaretColor",
- inherited: true,
- field_template: "external",
- type_name: "Color",
- include_paths: ["third_party/blink/renderer/platform/graphics/color.h"],
- default_value: "Color()",
- field_group: "*",
- computed_style_custom_functions: ["getter", "setter"],
- },
- {
name: "CursorData",
inherited: true,
field_template: "external",
@@ -344,15 +305,6 @@
computed_style_custom_functions: ["getter", "setter"],
},
{
- name: "EffectiveZoom",
- inherited: true,
- field_template: "primitive",
- type_name: "float",
- default_value: "1.0f",
- field_group: "*",
- computed_style_custom_functions: ["setter"],
- },
- {
name: "TextStrokeColorIsCurrentColor",
inherited: true,
field_template: "primitive",
@@ -398,7 +350,7 @@
computed_style_custom_functions: ["getter", "setter"],
},
{
- name: "VisitedLinkTextStrokeColorIsCurrentColor",
+ name: "InternalVisitedTextStrokeColorIsCurrentColor",
inherited: true,
field_template: "primitive",
type_name: "bool",
@@ -407,7 +359,7 @@
computed_style_custom_functions: ["getter", "setter"],
},
{
- name: "VisitedLinkTextFillColorIsCurrentColor",
+ name: "InternalVisitedTextFillColorIsCurrentColor",
inherited: true,
field_template: "primitive",
type_name: "bool",
@@ -416,7 +368,7 @@
computed_style_custom_functions: ["getter", "setter"],
},
{
- name: "VisitedLinkTextEmphasisColorIsCurrentColor",
+ name: "InternalVisitedTextEmphasisColorIsCurrentColor",
inherited: true,
field_template: "primitive",
type_name: "bool",
@@ -425,7 +377,7 @@
computed_style_custom_functions: ["getter", "setter"],
},
{
- name: "VisitedLinkCaretColorIsCurrentColor",
+ name: "InternalVisitedCaretColorIsCurrentColor",
inherited: true,
field_template: "primitive",
type_name: "bool",
@@ -434,7 +386,7 @@
computed_style_custom_functions: ["getter", "setter"],
},
{
- name: "VisitedLinkCaretColorIsAuto",
+ name: "InternalVisitedCaretColorIsAuto",
inherited: true,
field_template: "primitive",
type_name: "bool",
@@ -657,62 +609,6 @@
field_group: "*",
},
{
- name: "VisitedLinkTextDecorationColor",
- field_template: "external",
- type_name: "StyleColor",
- field_group: "*",
- default_value: "StyleColor::CurrentColor()",
- computed_style_custom_functions: ["getter", "setter"],
- },
- {
- name: "VisitedLinkBackgroundColor",
- field_template: "external",
- type_name: "StyleColor",
- field_group: "*",
- default_value: "StyleColor(Color::kTransparent)",
- computed_style_custom_functions: ["getter", "setter"],
- },
- {
- name: "VisitedLinkOutlineColor",
- field_template: "external",
- type_name: "StyleColor",
- field_group: "*",
- default_value: "StyleColor::CurrentColor()",
- computed_style_custom_functions: ["getter", "setter"],
- },
- {
- name: "VisitedLinkBorderLeftColor",
- field_template: "external",
- type_name: "StyleColor",
- field_group: "*",
- default_value: "StyleColor::CurrentColor()",
- computed_style_custom_functions: ["getter", "setter"],
- },
- {
- name: "VisitedLinkBorderRightColor",
- field_template: "external",
- type_name: "StyleColor",
- field_group: "*",
- default_value: "StyleColor::CurrentColor()",
- computed_style_custom_functions: ["getter", "setter"],
- },
- {
- name: "VisitedLinkBorderTopColor",
- field_template: "external",
- type_name: "StyleColor",
- field_group: "*",
- default_value: "StyleColor::CurrentColor()",
- computed_style_custom_functions: ["getter", "setter"],
- },
- {
- name: "VisitedLinkBorderBottomColor",
- field_template: "external",
- type_name: "StyleColor",
- field_group: "*",
- default_value: "StyleColor::CurrentColor()",
- computed_style_custom_functions: ["getter", "setter"],
- },
- {
name: "CallbackSelectors",
field_template: "external",
type_name: "Vector<String>",
@@ -887,15 +783,6 @@
field_group: "*->multi-col",
},
{
- name: "VisitedLinkColumnRuleColor",
- field_template: "external",
- type_name: "StyleColor",
- field_group: "*->multi-col",
- default_value: "StyleColor::CurrentColor()",
- include_paths: ["third_party/blink/renderer/core/css/style_color.h"],
- computed_style_custom_functions: ["getter", "setter"],
- },
- {
name: "HasAutoColumnWidth",
field_template: "primitive",
type_name: "bool",
@@ -1082,5 +969,11 @@
field_group: "inherited",
default_value: "false",
},
+ {
+ name: "IsInBlockifyingDisplay",
+ field_template: "monotonic_flag",
+ default_value: "false",
+ custom_compare: true,
+ },
],
}
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 8ad43131905..6bc972c7c58 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
@@ -9,6 +9,7 @@
#include "third_party/blink/renderer/core/css/css_font_selector.h"
#include "third_party/blink/renderer/core/css/css_gradient_value.h"
#include "third_party/blink/renderer/core/css/css_identifier_value.h"
+#include "third_party/blink/renderer/core/css/css_numeric_literal_value.h"
#include "third_party/blink/renderer/core/css/css_test_helpers.h"
#include "third_party/blink/renderer/core/css/css_value_list.h"
#include "third_party/blink/renderer/core/css/properties/css_property_ref.h"
@@ -69,13 +70,22 @@ TEST(ComputedStyleTest, ClipPathEqual) {
TEST(ComputedStyleTest, FocusRingWidth) {
scoped_refptr<ComputedStyle> style = ComputedStyle::Create();
style->SetEffectiveZoom(3.5);
-#if defined(OS_MACOSX)
style->SetOutlineStyle(EBorderStyle::kSolid);
+#if defined(OS_MACOSX)
EXPECT_EQ(3, style->GetOutlineStrokeWidthForFocusRing());
#else
- EXPECT_EQ(3.5, style->GetOutlineStrokeWidthForFocusRing());
+ style->SetOutlineStyleIsAuto(static_cast<bool>(OutlineIsAuto::kOn));
+ static uint16_t outline_width = 4;
+ style->SetOutlineWidth(outline_width);
+
+ double expected_width =
+ LayoutTheme::GetTheme().IsFocusRingOutset() ? outline_width : 3.5;
+ EXPECT_EQ(expected_width, style->GetOutlineStrokeWidthForFocusRing());
+
+ expected_width =
+ LayoutTheme::GetTheme().IsFocusRingOutset() ? outline_width : 1.0;
style->SetEffectiveZoom(0.5);
- EXPECT_EQ(1, style->GetOutlineStrokeWidthForFocusRing());
+ EXPECT_EQ(expected_width, style->GetOutlineStrokeWidthForFocusRing());
#endif
}
@@ -447,9 +457,9 @@ TEST(ComputedStyleTest, CustomPropertiesEqual_Values) {
using UnitType = CSSPrimitiveValue::UnitType;
- const auto* value1 = CSSPrimitiveValue::Create(1.0, UnitType::kPixels);
- const auto* value2 = CSSPrimitiveValue::Create(2.0, UnitType::kPixels);
- const auto* value3 = CSSPrimitiveValue::Create(1.0, UnitType::kPixels);
+ const auto* value1 = CSSNumericLiteralValue::Create(1.0, UnitType::kPixels);
+ const auto* value2 = CSSNumericLiteralValue::Create(2.0, UnitType::kPixels);
+ const auto* value3 = CSSNumericLiteralValue::Create(1.0, UnitType::kPixels);
Vector<AtomicString> properties;
properties.push_back("--x");
@@ -504,8 +514,8 @@ TEST(ComputedStyleTest, ApplyColorSchemeLightOnDark) {
dummy_page_holder_->GetDocument().GetSettings()->SetPreferredColorScheme(
PreferredColorScheme::kDark);
StyleResolverState state(dummy_page_holder_->GetDocument(),
- nullptr /* element */, nullptr /* pseudo_element */,
- initial, initial);
+ *dummy_page_holder_->GetDocument().documentElement(),
+ nullptr /* pseudo_element */, initial, initial);
scoped_refptr<ComputedStyle> style = ComputedStyle::Create();
state.SetStyle(style);
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 fcdc93b8f12..fd4dc064548 100644
--- a/chromium/third_party/blink/renderer/core/style/content_data.cc
+++ b/chromium/third_party/blink/renderer/core/style/content_data.cc
@@ -72,9 +72,10 @@ void ContentData::Trace(blink::Visitor* visitor) {
visitor->Trace(next_);
}
-LayoutObject* ImageContentData::CreateLayoutObject(PseudoElement& pseudo,
- ComputedStyle& pseudo_style,
- LegacyLayout) const {
+LayoutObject* ImageContentData::CreateLayoutObject(
+ PseudoElement& pseudo,
+ const ComputedStyle& pseudo_style,
+ LegacyLayout) const {
LayoutImage* image = LayoutImage::CreateAnonymous(pseudo);
image->SetPseudoStyle(&pseudo_style);
if (image_) {
@@ -91,9 +92,10 @@ void ImageContentData::Trace(blink::Visitor* visitor) {
ContentData::Trace(visitor);
}
-LayoutObject* TextContentData::CreateLayoutObject(PseudoElement& pseudo,
- ComputedStyle& pseudo_style,
- LegacyLayout legacy) const {
+LayoutObject* TextContentData::CreateLayoutObject(
+ PseudoElement& pseudo,
+ const ComputedStyle& pseudo_style,
+ LegacyLayout legacy) const {
LayoutObject* layout_object =
LayoutTextFragment::CreateAnonymous(pseudo, text_.Impl(), legacy);
layout_object->SetPseudoStyle(&pseudo_style);
@@ -102,7 +104,7 @@ LayoutObject* TextContentData::CreateLayoutObject(PseudoElement& pseudo,
LayoutObject* AltTextContentData::CreateLayoutObject(
PseudoElement& pseudo,
- ComputedStyle& pseudo_style,
+ const ComputedStyle& pseudo_style,
LegacyLayout) const {
// Does not require a layout object. Calling site should first check
// IsAltContentData() before calling this method.
@@ -112,16 +114,17 @@ LayoutObject* AltTextContentData::CreateLayoutObject(
LayoutObject* CounterContentData::CreateLayoutObject(
PseudoElement& pseudo,
- ComputedStyle& pseudo_style,
+ const ComputedStyle& pseudo_style,
LegacyLayout) const {
LayoutObject* layout_object = new LayoutCounter(pseudo, *counter_);
layout_object->SetPseudoStyle(&pseudo_style);
return layout_object;
}
-LayoutObject* QuoteContentData::CreateLayoutObject(PseudoElement& pseudo,
- ComputedStyle& pseudo_style,
- LegacyLayout) const {
+LayoutObject* QuoteContentData::CreateLayoutObject(
+ PseudoElement& pseudo,
+ const ComputedStyle& pseudo_style,
+ LegacyLayout) const {
LayoutObject* layout_object = new LayoutQuote(pseudo, quote_);
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 f8f287f4390..6ec82543c40 100644
--- a/chromium/third_party/blink/renderer/core/style/content_data.h
+++ b/chromium/third_party/blink/renderer/core/style/content_data.h
@@ -57,7 +57,7 @@ class ContentData : public GarbageCollectedFinalized<ContentData> {
virtual bool IsAltText() const { return false; }
virtual LayoutObject* CreateLayoutObject(PseudoElement&,
- ComputedStyle&,
+ const ComputedStyle&,
LegacyLayout) const = 0;
virtual ContentData* Clone() const;
@@ -90,7 +90,7 @@ class ImageContentData final : public ContentData {
bool IsImage() const override { return true; }
LayoutObject* CreateLayoutObject(PseudoElement&,
- ComputedStyle&,
+ const ComputedStyle&,
LegacyLayout) const override;
bool Equals(const ContentData& data) const override {
@@ -129,7 +129,7 @@ class TextContentData final : public ContentData {
bool IsText() const override { return true; }
LayoutObject* CreateLayoutObject(PseudoElement&,
- ComputedStyle&,
+ const ComputedStyle&,
LegacyLayout) const override;
bool Equals(const ContentData& data) const override {
@@ -160,7 +160,7 @@ class AltTextContentData final : public ContentData {
bool IsAltText() const override { return true; }
LayoutObject* CreateLayoutObject(PseudoElement&,
- ComputedStyle&,
+ const ComputedStyle&,
LegacyLayout) const override;
bool Equals(const ContentData& data) const override {
@@ -195,7 +195,7 @@ class CounterContentData final : public ContentData {
bool IsCounter() const override { return true; }
LayoutObject* CreateLayoutObject(PseudoElement&,
- ComputedStyle&,
+ const ComputedStyle&,
LegacyLayout) const override;
private:
@@ -233,7 +233,7 @@ class QuoteContentData final : public ContentData {
bool IsQuote() const override { return true; }
LayoutObject* CreateLayoutObject(PseudoElement&,
- ComputedStyle&,
+ const ComputedStyle&,
LegacyLayout) const override;
bool Equals(const ContentData& data) const override {
diff --git a/chromium/third_party/blink/renderer/core/style/counter_directives.h b/chromium/third_party/blink/renderer/core/style/counter_directives.h
index bf316c44a3f..cc096ba5e58 100644
--- a/chromium/third_party/blink/renderer/core/style/counter_directives.h
+++ b/chromium/third_party/blink/renderer/core/style/counter_directives.h
@@ -30,7 +30,7 @@
#include "base/memory/ptr_util.h"
#include "base/memory/scoped_refptr.h"
#include "base/numerics/checked_math.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
diff --git a/chromium/third_party/blink/renderer/core/style/data_ref.h b/chromium/third_party/blink/renderer/core/style/data_ref.h
index 59e7f829255..6186788a1c6 100644
--- a/chromium/third_party/blink/renderer/core/style/data_ref.h
+++ b/chromium/third_party/blink/renderer/core/style/data_ref.h
@@ -25,7 +25,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_DATA_REF_H_
#include "base/memory/scoped_refptr.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 9502f6eb788..b4d9f183c5e 100644
--- a/chromium/third_party/blink/renderer/core/style/fill_layer.h
+++ b/chromium/third_party/blink/renderer/core/style/fill_layer.h
@@ -33,7 +33,7 @@
#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/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 a70a32243dc..d0a356f1a6a 100644
--- a/chromium/third_party/blink/renderer/core/style/gap_length.h
+++ b/chromium/third_party/blink/renderer/core/style/gap_length.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_GAP_LENGTH_H_
#include "third_party/blink/renderer/platform/geometry/length.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/style/grid_area.h b/chromium/third_party/blink/renderer/core/style/grid_area.h
index a7be249009d..87fc702e9a1 100644
--- a/chromium/third_party/blink/renderer/core/style/grid_area.h
+++ b/chromium/third_party/blink/renderer/core/style/grid_area.h
@@ -32,7 +32,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_GRID_AREA_H_
#include "third_party/blink/renderer/core/style/grid_positions_resolver.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
#include "third_party/blink/renderer/platform/wtf/text/string_hash.h"
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 0e6d874f324..12f0d134db6 100644
--- a/chromium/third_party/blink/renderer/core/style/grid_length.h
+++ b/chromium/third_party/blink/renderer/core/style/grid_length.h
@@ -32,7 +32,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_GRID_LENGTH_H_
#include "third_party/blink/renderer/platform/geometry/length.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/style/grid_position.h b/chromium/third_party/blink/renderer/core/style/grid_position.h
index a26b712fb67..5e1d16de898 100644
--- a/chromium/third_party/blink/renderer/core/style/grid_position.h
+++ b/chromium/third_party/blink/renderer/core/style/grid_position.h
@@ -31,7 +31,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_GRID_POSITION_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_GRID_POSITION_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/style/grid_positions_resolver.h b/chromium/third_party/blink/renderer/core/style/grid_positions_resolver.h
index 08ab54dab34..475819da7a5 100644
--- a/chromium/third_party/blink/renderer/core/style/grid_positions_resolver.h
+++ b/chromium/third_party/blink/renderer/core/style/grid_positions_resolver.h
@@ -7,7 +7,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/style/grid_position.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/style/grid_track_size.h b/chromium/third_party/blink/renderer/core/style/grid_track_size.h
index 76298bf7f05..89e38c25fee 100644
--- a/chromium/third_party/blink/renderer/core/style/grid_track_size.h
+++ b/chromium/third_party/blink/renderer/core/style/grid_track_size.h
@@ -32,7 +32,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_GRID_TRACK_SIZE_H_
#include "third_party/blink/renderer/core/style/grid_length.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/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 d2a26d3c6c4..e50133b6581 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
@@ -32,7 +32,7 @@
#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/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/style/quotes_data.h b/chromium/third_party/blink/renderer/core/style/quotes_data.h
index 33e0a6dc82c..ad734a3acf9 100644
--- a/chromium/third_party/blink/renderer/core/style/quotes_data.h
+++ b/chromium/third_party/blink/renderer/core/style/quotes_data.h
@@ -23,7 +23,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_QUOTES_DATA_H_
#include "base/memory/scoped_refptr.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
diff --git a/chromium/third_party/blink/renderer/core/style/shadow_list.h b/chromium/third_party/blink/renderer/core/style/shadow_list.h
index 2b55f2a0ee7..ea239ab0f65 100644
--- a/chromium/third_party/blink/renderer/core/style/shadow_list.h
+++ b/chromium/third_party/blink/renderer/core/style/shadow_list.h
@@ -35,7 +35,7 @@
#include "third_party/blink/renderer/core/style/shadow_data.h"
#include "third_party/blink/renderer/platform/geometry/float_rect_outsets.h"
#include "third_party/blink/renderer/platform/graphics/draw_looper_builder.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/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/style_content_alignment_data.h b/chromium/third_party/blink/renderer/core/style/style_content_alignment_data.h
index 81cb89735d9..13d1a9f6065 100644
--- a/chromium/third_party/blink/renderer/core/style/style_content_alignment_data.h
+++ b/chromium/third_party/blink/renderer/core/style/style_content_alignment_data.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_STYLE_CONTENT_ALIGNMENT_DATA_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/allocator/allocator.h"
namespace blink {
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 a005d4c3a05..91292961f1f 100644
--- a/chromium/third_party/blink/renderer/core/style/style_difference.h
+++ b/chromium/third_party/blink/renderer/core/style/style_difference.h
@@ -7,7 +7,7 @@
#include <iosfwd>
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
namespace blink {
@@ -44,6 +44,20 @@ class StyleDifference {
scroll_anchor_disabling_property_changed_(false),
compositing_reasons_changed_(false) {}
+ void Merge(StyleDifference other) {
+ paint_invalidation_type_ =
+ std::max(paint_invalidation_type_, other.paint_invalidation_type_);
+ layout_type_ = std::max(layout_type_, other.layout_type_);
+ needs_collect_inlines_ |= other.needs_collect_inlines_;
+ needs_reshape_ |= other.needs_reshape_;
+ recompute_overflow_ |= other.recompute_overflow_;
+ visual_rect_update_ |= other.visual_rect_update_;
+ property_specific_differences_ |= other.property_specific_differences_;
+ scroll_anchor_disabling_property_changed_ |=
+ other.scroll_anchor_disabling_property_changed_;
+ compositing_reasons_changed_ |= other.compositing_reasons_changed_;
+ }
+
bool HasDifference() const {
return paint_invalidation_type_ || layout_type_ || needs_collect_inlines_ ||
needs_reshape_ || property_specific_differences_ ||
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 f6586b48641..3cdbb76f2e6 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
@@ -30,18 +30,22 @@
#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/loader/resource/image_resource_content.h"
+#include "third_party/blink/renderer/core/paint/image_element_timing.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
#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"
+#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
namespace blink {
StyleFetchedImage::StyleFetchedImage(const Document& document,
FetchParameters& params,
bool is_lazyload_possibly_deferred)
- : document_(&document), url_(params.Url()) {
+ : document_(&document),
+ url_(params.Url()),
+ origin_clean_(!params.IsFromOriginDirtyStyleSheet()) {
is_image_resource_ = true;
is_lazyload_possibly_deferred_ = is_lazyload_possibly_deferred;
@@ -77,7 +81,9 @@ ImageResourceContent* StyleFetchedImage::CachedImage() const {
}
CSSValue* StyleFetchedImage::CssValue() const {
- return CSSImageValue::Create(url_, const_cast<StyleFetchedImage*>(this));
+ return CSSImageValue::Create(
+ url_, origin_clean_ ? OriginClean::kTrue : OriginClean::kFalse,
+ const_cast<StyleFetchedImage*>(this));
}
CSSValue* StyleFetchedImage::ComputedCSSValue() const {
@@ -136,6 +142,12 @@ void StyleFetchedImage::ImageNotifyFinished(ImageResourceContent*) {
image_->UpdateImageAnimationPolicy();
}
+ if (document_ && RuntimeEnabledFeatures::ElementTimingEnabled(document_)) {
+ if (LocalDOMWindow* window = document_->domWindow()) {
+ ImageElementTiming::From(*window).NotifyBackgroundImageFinished(this);
+ }
+ }
+
// Oilpan: do not prolong the Document's lifetime.
document_.Clear();
}
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 637128280c7..c163ad2d3f3 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
@@ -83,6 +83,7 @@ class StyleFetchedImage final : public StyleImage,
Member<ImageResourceContent> image_;
Member<const Document> document_;
const KURL url_;
+ const bool origin_clean_;
};
template <>
diff --git a/chromium/third_party/blink/renderer/core/style/style_non_inherited_variables.h b/chromium/third_party/blink/renderer/core/style/style_non_inherited_variables.h
index e68c9982895..e8e36c2ba51 100644
--- a/chromium/third_party/blink/renderer/core/style/style_non_inherited_variables.h
+++ b/chromium/third_party/blink/renderer/core/style/style_non_inherited_variables.h
@@ -13,7 +13,7 @@
#include "third_party/blink/renderer/core/css/css_variable_data.h"
#include "third_party/blink/renderer/core/style/style_variables.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/allocator/allocator.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"
diff --git a/chromium/third_party/blink/renderer/core/style/style_path.cc b/chromium/third_party/blink/renderer/core/style/style_path.cc
index e9f66197b10..41ccc527456 100644
--- a/chromium/third_party/blink/renderer/core/style/style_path.cc
+++ b/chromium/third_party/blink/renderer/core/style/style_path.cc
@@ -29,7 +29,7 @@ scoped_refptr<StylePath> StylePath::Create(
return base::AdoptRef(new StylePath(std::move(path_byte_stream)));
}
-StylePath* StylePath::EmptyPath() {
+const StylePath* StylePath::EmptyPath() {
DEFINE_STATIC_REF(StylePath, empty_path,
StylePath::Create(std::make_unique<SVGPathByteStream>()));
return empty_path;
diff --git a/chromium/third_party/blink/renderer/core/style/style_path.h b/chromium/third_party/blink/renderer/core/style/style_path.h
index 5876df0499e..b25f3081e99 100644
--- a/chromium/third_party/blink/renderer/core/style/style_path.h
+++ b/chromium/third_party/blink/renderer/core/style/style_path.h
@@ -21,7 +21,7 @@ class StylePath final : public BasicShape {
static scoped_refptr<StylePath> Create(std::unique_ptr<SVGPathByteStream>);
~StylePath() override;
- static StylePath* EmptyPath();
+ static const StylePath* EmptyPath();
const Path& GetPath() const;
float length() const;
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 672305d7b89..d6fc71c3b93 100644
--- a/chromium/third_party/blink/renderer/core/style/style_reflection.h
+++ b/chromium/third_party/blink/renderer/core/style/style_reflection.h
@@ -28,7 +28,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/geometry/length.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/style/style_self_alignment_data.h b/chromium/third_party/blink/renderer/core/style/style_self_alignment_data.h
index 3fd513db021..18816e7ffd3 100644
--- a/chromium/third_party/blink/renderer/core/style/style_self_alignment_data.h
+++ b/chromium/third_party/blink/renderer/core/style/style_self_alignment_data.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_STYLE_SELF_ALIGNMENT_DATA_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/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/style/style_svg_resource.h b/chromium/third_party/blink/renderer/core/style/style_svg_resource.h
index 97573a02437..646b28eabd2 100644
--- a/chromium/third_party/blink/renderer/core/style/style_svg_resource.h
+++ b/chromium/third_party/blink/renderer/core/style/style_svg_resource.h
@@ -9,7 +9,7 @@
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/core/svg/svg_resource.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/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/atomic_string.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 443dd6255cd..f5d3a27411a 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
@@ -30,7 +30,7 @@
#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/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
@@ -190,7 +190,7 @@ class SVGComputedStyle : public RefCounted<SVGComputedStyle> {
fill.Access()->paint = paint;
}
- void SetVisitedLinkFillPaint(const SVGPaint& paint) {
+ void SetInternalVisitedFillPaint(const SVGPaint& paint) {
if (!(fill->visited_link_paint == paint))
fill.Access()->visited_link_paint = paint;
}
@@ -205,7 +205,7 @@ class SVGComputedStyle : public RefCounted<SVGComputedStyle> {
stroke.Access()->paint = paint;
}
- void SetVisitedLinkStrokePaint(const SVGPaint& paint) {
+ void SetInternalVisitedStrokePaint(const SVGPaint& paint) {
if (!(stroke->visited_link_paint == paint))
stroke.Access()->visited_link_paint = paint;
}
@@ -363,21 +363,21 @@ class SVGComputedStyle : public RefCounted<SVGComputedStyle> {
}
EPaintOrderType PaintOrderType(unsigned index) const;
- const SVGPaint& VisitedLinkFillPaint() const {
+ const SVGPaint& InternalVisitedFillPaint() const {
return fill->visited_link_paint;
}
- const SVGPaint& VisitedLinkStrokePaint() const {
+ const SVGPaint& InternalVisitedStrokePaint() const {
return stroke->visited_link_paint;
}
bool IsFillColorCurrentColor() const {
return FillPaint().HasCurrentColor() ||
- VisitedLinkFillPaint().HasCurrentColor();
+ InternalVisitedFillPaint().HasCurrentColor();
}
bool IsStrokeColorCurrentColor() const {
return StrokePaint().HasCurrentColor() ||
- VisitedLinkStrokePaint().HasCurrentColor();
+ InternalVisitedStrokePaint().HasCurrentColor();
}
// convenience
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 e0c4c483492..33f2bcf35ef 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
@@ -34,7 +34,7 @@
#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/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
diff --git a/chromium/third_party/blink/renderer/core/style/svg_computed_style_test.cc b/chromium/third_party/blink/renderer/core/style/svg_computed_style_test.cc
index e7ec9a4fcd9..2559a45b921 100644
--- a/chromium/third_party/blink/renderer/core/style/svg_computed_style_test.cc
+++ b/chromium/third_party/blink/renderer/core/style/svg_computed_style_test.cc
@@ -45,8 +45,8 @@ TEST(SVGComputedStyleTest, StrokeStyleShouldCompareValue) {
{
scoped_refptr<SVGComputedStyle> svg1 = SVGComputedStyle::Create();
scoped_refptr<SVGComputedStyle> svg2 = SVGComputedStyle::Create();
- svg1->SetVisitedLinkStrokePaint(SVGComputedStyle::InitialStrokePaint());
- svg2->SetVisitedLinkStrokePaint(SVGComputedStyle::InitialStrokePaint());
+ svg1->SetInternalVisitedStrokePaint(SVGComputedStyle::InitialStrokePaint());
+ svg2->SetInternalVisitedStrokePaint(SVGComputedStyle::InitialStrokePaint());
EXPECT_FALSE(svg1->Diff(*svg2).HasDifference());
}
}
diff --git a/chromium/third_party/blink/renderer/core/style/text_size_adjust.h b/chromium/third_party/blink/renderer/core/style/text_size_adjust.h
index a0a58cb1030..2f5e6af0578 100644
--- a/chromium/third_party/blink/renderer/core/style/text_size_adjust.h
+++ b/chromium/third_party/blink/renderer/core/style/text_size_adjust.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_TEXT_SIZE_ADJUST_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_TEXT_SIZE_ADJUST_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 db1ac806cfc..7fa384dacab 100644
--- a/chromium/third_party/blink/renderer/core/style/transform_origin.h
+++ b/chromium/third_party/blink/renderer/core/style/transform_origin.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_TRANSFORM_ORIGIN_H_
#include "third_party/blink/renderer/platform/geometry/length.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/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 58c6861e677..0878e91c919 100644
--- a/chromium/third_party/blink/renderer/core/svg/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/svg/BUILD.gn
@@ -14,6 +14,8 @@ blink_core_sources("svg") {
}
sources = [
+ "animation/smil_animation_sandwich.cc",
+ "animation/smil_animation_sandwich.h",
"animation/smil_time.cc",
"animation/smil_time.h",
"animation/smil_time_container.cc",
diff --git a/chromium/third_party/blink/renderer/core/svg/animation/smil_animation_sandwich.cc b/chromium/third_party/blink/renderer/core/svg/animation/smil_animation_sandwich.cc
new file mode 100644
index 00000000000..503581cf8b8
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/svg/animation/smil_animation_sandwich.cc
@@ -0,0 +1,153 @@
+/*
+ * 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 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 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/renderer/core/svg/animation/smil_animation_sandwich.h"
+
+#include <algorithm>
+
+#include "third_party/blink/renderer/core/svg/animation/svg_smil_element.h"
+
+namespace blink {
+
+SMILAnimationSandwich::SMILAnimationSandwich() {}
+
+void SMILAnimationSandwich::Schedule(SVGSMILElement* animation) {
+ DCHECK(!sandwich_.Contains(animation));
+ sandwich_.push_back(animation);
+}
+
+void SMILAnimationSandwich::Unschedule(SVGSMILElement* animation) {
+ auto* position = std::find(sandwich_.begin(), sandwich_.end(), animation);
+ DCHECK(sandwich_.end() != position);
+ sandwich_.erase(position);
+}
+
+void SMILAnimationSandwich::Reset() {
+ for (SVGSMILElement* animation : sandwich_) {
+ animation->Reset();
+ }
+}
+
+void SMILAnimationSandwich::UpdateTiming(double elapsed, bool seek_to_time) {
+ if (!std::is_sorted(sandwich_.begin(), sandwich_.end(),
+ PriorityCompare(elapsed))) {
+ std::sort(sandwich_.begin(), sandwich_.end(), PriorityCompare(elapsed));
+ }
+
+ active_.ReserveCapacity(sandwich_.size());
+ for (const auto& it_animation : sandwich_) {
+ SVGSMILElement* animation = it_animation.Get();
+ DCHECK(animation->HasValidTarget());
+
+ if (animation->NeedsToProgress(elapsed)) {
+ animation->Progress(elapsed, seek_to_time);
+ active_.push_back(animation);
+ } else if (animation->IsContributing(elapsed)) {
+ active_.push_back(animation);
+ } else {
+ animation->ClearAnimatedType();
+ }
+ }
+}
+
+SMILTime SMILAnimationSandwich::GetNextFireTime() {
+ SMILTime earliest_fire_time = SMILTime::Unresolved();
+ for (const auto& it_animation : sandwich_) {
+ SVGSMILElement* animation = it_animation.Get();
+
+ SMILTime next_fire_time = animation->NextProgressTime();
+ if (next_fire_time.IsFinite())
+ earliest_fire_time = std::min(next_fire_time, earliest_fire_time);
+ }
+ return earliest_fire_time;
+}
+
+void SMILAnimationSandwich::SendEvents(double elapsed, bool seek_to_time) {
+ if (seek_to_time) {
+ for (auto& animation : active_) {
+ animation->TriggerPendingEvents(elapsed);
+ }
+ }
+
+ for (auto& animation : active_) {
+ animation->UpdateSyncbases();
+ }
+
+ for (auto& animation : active_) {
+ animation->UpdateNextProgressTime(elapsed);
+ }
+
+ auto* it = active_.begin();
+ while (it != active_.end()) {
+ auto* scheduled = it->Get();
+ if (scheduled->IsContributing(elapsed)) {
+ it++;
+ continue;
+ }
+ scheduled->ClearAnimatedType();
+ it = active_.erase(it);
+ }
+}
+
+SVGSMILElement* SMILAnimationSandwich::ApplyAnimationValues() {
+ if (active_.IsEmpty())
+ return nullptr;
+ // Results are accumulated to the first animation that animates and
+ // contributes to a particular element/attribute pair.
+ // Only reset the animated type to the base value once for
+ // the lowest priority animation that animates and
+ // contributes to a particular element/attribute pair.
+ SVGSMILElement* result_element = active_.front();
+ result_element->ResetAnimatedType();
+
+ // Animations have to be applied lowest to highest prio.
+ //
+ // Only calculate the relevant animations. If we actually set the
+ // animation value, we don't need to calculate what is beneath it
+ // in the sandwich.
+ auto* sandwich_start = active_.end();
+ while (sandwich_start != active_.begin()) {
+ --sandwich_start;
+ if ((*sandwich_start)->OverwritesUnderlyingAnimationValue())
+ break;
+ }
+
+ for (auto* sandwich_it = sandwich_start; sandwich_it != active_.end();
+ sandwich_it++) {
+ (*sandwich_it)->UpdateAnimatedValue(result_element);
+ }
+ active_.Shrink(0);
+
+ result_element->ApplyResultsToTarget();
+
+ return result_element;
+}
+
+void SMILAnimationSandwich::Trace(blink::Visitor* visitor) {
+ visitor->Trace(sandwich_);
+ visitor->Trace(active_);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/animation/smil_animation_sandwich.h b/chromium/third_party/blink/renderer/core/svg/animation/smil_animation_sandwich.h
new file mode 100644
index 00000000000..f783f3d352d
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/svg/animation/smil_animation_sandwich.h
@@ -0,0 +1,83 @@
+/*
+ * 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 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 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.
+ */
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_SVG_ANIMATION_SMIL_ANIMATION_SANDWICH_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_SVG_ANIMATION_SMIL_ANIMATION_SANDWICH_H_
+
+#include "third_party/blink/renderer/core/svg/animation/smil_time.h"
+#include "third_party/blink/renderer/core/svg/animation/svg_smil_element.h"
+#include "third_party/blink/renderer/platform/heap/handle.h"
+#include "third_party/blink/renderer/platform/wtf/vector.h"
+
+namespace blink {
+
+struct PriorityCompare {
+ PriorityCompare(double elapsed) : elapsed_(elapsed) {}
+ bool operator()(const Member<SVGSMILElement>& a,
+ const Member<SVGSMILElement>& b) {
+ // FIXME: This should also consider possible timing relations between the
+ // elements.
+ SMILTime a_begin = a->IntervalBegin();
+ SMILTime b_begin = b->IntervalBegin();
+ // Frozen elements need to be prioritized based on their previous interval.
+ a_begin = a->IsFrozen() && elapsed_ < a_begin ? a->PreviousIntervalBegin()
+ : a_begin;
+ b_begin = b->IsFrozen() && elapsed_ < b_begin ? b->PreviousIntervalBegin()
+ : b_begin;
+ if (a_begin == b_begin)
+ return a->DocumentOrderIndex() < b->DocumentOrderIndex();
+ return a_begin < b_begin;
+ }
+ double elapsed_;
+};
+
+class SMILAnimationSandwich : public GarbageCollected<SMILAnimationSandwich> {
+ public:
+ using ScheduledVector = HeapVector<Member<SVGSMILElement>>;
+ explicit SMILAnimationSandwich();
+
+ void Schedule(SVGSMILElement* animation);
+ void Unschedule(SVGSMILElement* animation);
+ void Reset();
+
+ void UpdateTiming(double elapsed, bool seek_to_time);
+ void SendEvents(double elapsed, bool seek_to_time);
+ SVGSMILElement* ApplyAnimationValues();
+
+ SMILTime GetNextFireTime();
+
+ bool IsEmpty() { return sandwich_.IsEmpty(); }
+
+ void Trace(blink::Visitor*);
+
+ private:
+ // The list stored here is always sorted.
+ ScheduledVector sandwich_;
+ ScheduledVector active_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_SVG_ANIMATION_SMIL_ANIMATION_SANDWICH_H_
diff --git a/chromium/third_party/blink/renderer/core/svg/animation/smil_time.h b/chromium/third_party/blink/renderer/core/svg/animation/smil_time.h
index 378ab8b5ad4..bea1545c331 100644
--- a/chromium/third_party/blink/renderer/core/svg/animation/smil_time.h
+++ b/chromium/third_party/blink/renderer/core/svg/animation/smil_time.h
@@ -26,7 +26,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_SVG_ANIMATION_SMIL_TIME_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_SVG_ANIMATION_SMIL_TIME_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
#include "third_party/blink/renderer/platform/wtf/hash_traits.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
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 e9d898324ed..8b392035b7c 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
@@ -32,15 +32,15 @@
#include "third_party/blink/renderer/core/dom/element_traversal.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/svg/animation/smil_time.h"
#include "third_party/blink/renderer/core/svg/animation/svg_smil_element.h"
#include "third_party/blink/renderer/core/svg/svg_svg_element.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
-static constexpr TimeDelta kAnimationPolicyOnceDuration =
- TimeDelta::FromSeconds(3);
+static constexpr base::TimeDelta kAnimationPolicyOnceDuration =
+ base::TimeDelta::FromSeconds(3);
SMILTimeContainer::SMILTimeContainer(SVGSVGElement& owner)
: presentation_time_(0),
@@ -79,15 +79,19 @@ void SMILTimeContainer::Schedule(SVGSMILElement* animation,
DCHECK(!prevent_scheduled_animations_changes_);
#endif
- AttributeAnimationsMap& attribute_map =
- scheduled_animations_.insert(target, AttributeAnimationsMap())
- .stored_value->value;
- Member<AnimationsLinkedHashSet>& scheduled =
- attribute_map.insert(attribute_name, nullptr).stored_value->value;
- if (!scheduled)
- scheduled = MakeGarbageCollected<AnimationsLinkedHashSet>();
- DCHECK(!scheduled->Contains(animation));
- scheduled->insert(animation);
+ // Separate out Discard and AnimateMotion
+ QualifiedName name = (animation->HasTagName(svg_names::kAnimateMotionTag) ||
+ animation->HasTagName(svg_names::kDiscardTag))
+ ? animation->TagQName()
+ : attribute_name;
+
+ auto key = std::make_pair(target, name);
+ auto& sandwich =
+ scheduled_animations_.insert(key, nullptr).stored_value->value;
+ if (!sandwich)
+ sandwich = MakeGarbageCollected<SMILAnimationSandwich>();
+
+ sandwich->Schedule(animation);
SMILTime next_fire_time = animation->NextProgressTime();
if (next_fire_time.IsFinite())
@@ -103,20 +107,20 @@ void SMILTimeContainer::Unschedule(SVGSMILElement* animation,
DCHECK(!prevent_scheduled_animations_changes_);
#endif
- GroupedAnimationsMap::iterator it = scheduled_animations_.find(target);
+ // Separate out Discard and AnimateMotion
+ QualifiedName name = (animation->HasTagName(svg_names::kAnimateMotionTag) ||
+ animation->HasTagName(svg_names::kDiscardTag))
+ ? animation->TagQName()
+ : attribute_name;
+
+ auto key = std::make_pair(target, name);
+ AnimationsMap::iterator it = scheduled_animations_.find(key);
CHECK(it != scheduled_animations_.end());
- AttributeAnimationsMap& attribute_map = it->value;
- AttributeAnimationsMap::iterator attribute_map_it =
- attribute_map.find(attribute_name);
- DCHECK(attribute_map_it != attribute_map.end());
- AnimationsLinkedHashSet* scheduled = attribute_map_it->value;
- AnimationsLinkedHashSet::iterator it_animation = scheduled->find(animation);
- DCHECK(it_animation != scheduled->end());
- scheduled->erase(it_animation);
-
- if (scheduled->IsEmpty())
- attribute_map.erase(attribute_map_it);
- if (attribute_map.IsEmpty())
+
+ auto& sandwich = *(it->value);
+ sandwich.Unschedule(animation);
+
+ if (sandwich.IsEmpty())
scheduled_animations_.erase(it);
}
@@ -235,13 +239,8 @@ void SMILTimeContainer::SetElapsed(double elapsed) {
#if DCHECK_IS_ON()
prevent_scheduled_animations_changes_ = true;
#endif
- for (const auto& attribute_entry : scheduled_animations_) {
- for (const auto& entry : attribute_entry.value) {
- const AnimationsLinkedHashSet* scheduled = entry.value;
- for (SVGSMILElement* element : *scheduled) {
- element->Reset();
- }
- }
+ for (const auto& sandwich : scheduled_animations_) {
+ sandwich.value->Reset();
}
#if DCHECK_IS_ON()
prevent_scheduled_animations_changes_ = false;
@@ -273,7 +272,8 @@ void SMILTimeContainer::ScheduleWakeUp(
FrameSchedulingState frame_scheduling_state) {
DCHECK(frame_scheduling_state == kSynchronizeAnimations ||
frame_scheduling_state == kFutureAnimationFrame);
- wakeup_timer_.StartOneShot(TimeDelta::FromSecondsD(delay_time), FROM_HERE);
+ wakeup_timer_.StartOneShot(base::TimeDelta::FromSecondsD(delay_time),
+ FROM_HERE);
frame_scheduling_state_ = frame_scheduling_state;
}
@@ -352,26 +352,6 @@ void SMILTimeContainer::UpdateDocumentOrderIndexes() {
document_order_indexes_dirty_ = false;
}
-struct PriorityCompare {
- PriorityCompare(double elapsed) : elapsed_(elapsed) {}
- bool operator()(const Member<SVGSMILElement>& a,
- const Member<SVGSMILElement>& b) {
- // FIXME: This should also consider possible timing relations between the
- // elements.
- SMILTime a_begin = a->IntervalBegin();
- SMILTime b_begin = b->IntervalBegin();
- // Frozen elements need to be prioritized based on their previous interval.
- a_begin = a->IsFrozen() && elapsed_ < a_begin ? a->PreviousIntervalBegin()
- : a_begin;
- b_begin = b->IsFrozen() && elapsed_ < b_begin ? b->PreviousIntervalBegin()
- : b_begin;
- if (a_begin == b_begin)
- return a->DocumentOrderIndex() < b->DocumentOrderIndex();
- return a_begin < b_begin;
- }
- double elapsed_;
-};
-
SVGSVGElement& SMILTimeContainer::OwnerSVGElement() const {
return *owner_svg_element_;
}
@@ -411,106 +391,87 @@ void SMILTimeContainer::UpdateAnimationsAndScheduleFrameIfNeeded(
if (!GetDocument().IsActive())
return;
- SMILTime earliest_fire_time = UpdateAnimations(elapsed, seek_to_time);
+ UpdateAnimationTimings(elapsed, seek_to_time);
+ ApplyAnimationValues(elapsed);
+
+ SMILTime earliest_fire_time = SMILTime::Unresolved();
+ for (auto& sandwich : scheduled_animations_) {
+ SMILTime next_fire_time = sandwich.value->GetNextFireTime();
+ if (next_fire_time.IsFinite())
+ earliest_fire_time = std::min(next_fire_time, earliest_fire_time);
+ }
+
if (!CanScheduleFrame(earliest_fire_time))
return;
double delay_time = earliest_fire_time.Value() - elapsed;
ScheduleAnimationFrame(delay_time);
}
-SMILTime SMILTimeContainer::UpdateAnimations(double elapsed,
- bool seek_to_time) {
+void SMILTimeContainer::UpdateAnimationTimings(double elapsed,
+ bool seek_to_time) {
DCHECK(GetDocument().IsActive());
- SMILTime earliest_fire_time = SMILTime::Unresolved();
#if DCHECK_IS_ON()
// This boolean will catch any attempts to schedule/unschedule
- // scheduledAnimations during this critical section. Similarly, any elements
+ // scheduledAnimations during this critical section. Similarly, any elements
// removed will unschedule themselves, so this will catch modification of
// animationsToApply.
- prevent_scheduled_animations_changes_ = true;
+ base::AutoReset<bool> no_scheduled_animations_change_scope(
+ &prevent_scheduled_animations_changes_, true);
#endif
if (document_order_indexes_dirty_)
UpdateDocumentOrderIndexes();
- using AnimationsVector = HeapVector<Member<SVGSMILElement>>;
- AnimationsVector animations_to_apply;
- AnimationsVector scheduled_animations_in_same_group;
- for (auto& attribute_entry : scheduled_animations_) {
- AttributeAnimationsMap& attribute_map = attribute_entry.value;
- Vector<QualifiedName> invalid_keys;
- for (const auto& entry : attribute_map) {
- DCHECK(entry.value);
+ {
+ Vector<AnimationId> invalid_keys;
+ for (auto& entry : scheduled_animations_) {
if (entry.value->IsEmpty()) {
invalid_keys.push_back(entry.key);
- continue;
}
+ }
+ scheduled_animations_.RemoveAll(invalid_keys);
+ }
- // Sort according to priority. Elements with later begin time have higher
- // priority. In case of a tie, document order decides.
- // FIXME: This should also consider timing relationships between the
- // elements. Dependents have higher priority.
- CopyToVector(*entry.value, scheduled_animations_in_same_group);
- std::sort(scheduled_animations_in_same_group.begin(),
- scheduled_animations_in_same_group.end(),
- PriorityCompare(elapsed));
-
- AnimationsVector sandwich;
- for (const auto& it_animation : scheduled_animations_in_same_group) {
- SVGSMILElement* animation = it_animation.Get();
- DCHECK_EQ(animation->TimeContainer(), this);
- DCHECK(animation->HasValidTarget());
-
- // This will calculate the contribution from the animation and update
- // timing.
- if (animation->Progress(elapsed, seek_to_time)) {
- sandwich.push_back(animation);
- } else {
- animation->ClearAnimatedType();
- }
-
- SMILTime next_fire_time = animation->NextProgressTime();
- if (next_fire_time.IsFinite())
- earliest_fire_time = std::min(next_fire_time, earliest_fire_time);
- }
+ active_sandwiches_.ReserveCapacity(scheduled_animations_.size());
+ for (auto& entry : scheduled_animations_) {
+ auto* sandwich = entry.value.Get();
+ sandwich->UpdateTiming(elapsed, seek_to_time);
- if (!sandwich.IsEmpty()) {
- // Results are accumulated to the first animation that animates and
- // contributes to a particular element/attribute pair.
- // Only reset the animated type to the base value once for
- // the lowest priority animation that animates and
- // contributes to a particular element/attribute pair.
- SVGSMILElement* result_element = sandwich.front();
- result_element->ResetAnimatedType();
-
- // Go through the sandwich from lowest prio to highest and generate
- // the animated value (if any.)
- for (const auto& animation : sandwich)
- animation->UpdateAnimatedValue(result_element);
-
- animations_to_apply.push_back(result_element);
- }
+ if (!sandwich->IsEmpty()) {
+ active_sandwiches_.push_back(sandwich);
}
- attribute_map.RemoveAll(invalid_keys);
}
+ for (auto& sandwich : active_sandwiches_) {
+ sandwich->SendEvents(elapsed, seek_to_time);
+ }
+}
+
+void SMILTimeContainer::ApplyAnimationValues(double elapsed) {
+#if DCHECK_IS_ON()
+ prevent_scheduled_animations_changes_ = true;
+#endif
+ HeapVector<Member<SVGSMILElement>> animations_to_apply;
+ for (auto& sandwich : active_sandwiches_) {
+ if (SVGSMILElement* animation = sandwich->ApplyAnimationValues())
+ animations_to_apply.push_back(animation);
+ }
+ active_sandwiches_.Shrink(0);
+
if (animations_to_apply.IsEmpty()) {
#if DCHECK_IS_ON()
prevent_scheduled_animations_changes_ = false;
#endif
- return earliest_fire_time;
+ return;
}
+ // Everything bellow handles "discard" elements.
UseCounter::Count(&GetDocument(), WebFeature::kSVGSMILAnimationAppliedEffect);
std::sort(animations_to_apply.begin(), animations_to_apply.end(),
PriorityCompare(elapsed));
- // Apply results to target elements.
- for (const auto& timed_element : animations_to_apply)
- timed_element->ApplyResultsToTarget();
-
#if DCHECK_IS_ON()
prevent_scheduled_animations_changes_ = false;
#endif
@@ -519,6 +480,8 @@ SMILTime SMILTimeContainer::UpdateAnimations(double elapsed,
if (timed_element->isConnected() && timed_element->IsSVGDiscardElement()) {
SVGElement* target_element = timed_element->targetElement();
if (target_element && target_element->isConnected()) {
+ UseCounter::Count(&GetDocument(),
+ WebFeature::kSVGSMILDiscardElementTriggered);
target_element->remove(IGNORE_EXCEPTION_FOR_TESTING);
DCHECK(!target_element->isConnected());
}
@@ -529,7 +492,7 @@ SMILTime SMILTimeContainer::UpdateAnimations(double elapsed,
}
}
}
- return earliest_fire_time;
+ return;
}
void SMILTimeContainer::AdvanceFrameForTesting() {
@@ -540,6 +503,7 @@ void SMILTimeContainer::AdvanceFrameForTesting() {
void SMILTimeContainer::Trace(blink::Visitor* visitor) {
visitor->Trace(scheduled_animations_);
visitor->Trace(owner_svg_element_);
+ visitor->Trace(active_sandwiches_);
}
} // namespace blink
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 ad3e1addaa1..ce762bfa188 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
@@ -27,6 +27,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_SVG_ANIMATION_SMIL_TIME_CONTAINER_H_
#include "third_party/blink/renderer/core/dom/qualified_name.h"
+#include "third_party/blink/renderer/core/svg/animation/smil_animation_sandwich.h"
#include "third_party/blink/renderer/platform/graphics/image_animation_policy.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/timer.h"
@@ -40,11 +41,14 @@ namespace blink {
class Document;
class SMILTime;
class SVGElement;
-class SVGSMILElement;
class SVGSVGElement;
class SMILTimeContainer : public GarbageCollectedFinalized<SMILTimeContainer> {
public:
+ // Sorted list
+ using AnimationId = std::pair<WeakMember<SVGElement>, QualifiedName>;
+ using AnimationsMap = HeapHashMap<AnimationId, Member<SMILAnimationSandwich>>;
+
explicit SMILTimeContainer(SVGSVGElement& owner);
~SMILTimeContainer();
@@ -106,7 +110,8 @@ class SMILTimeContainer : public GarbageCollectedFinalized<SMILTimeContainer> {
bool CanScheduleFrame(SMILTime earliest_fire_time) const;
void UpdateAnimationsAndScheduleFrameIfNeeded(double elapsed,
bool seek_to_time = false);
- SMILTime UpdateAnimations(double elapsed, bool seek_to_time);
+ void UpdateAnimationTimings(double elapsed, bool seek_to_time);
+ void ApplyAnimationValues(double elapsed);
void ServiceOnNextFrame();
void ScheduleWakeUp(double delay_time, FrameSchedulingState);
bool HasPendingSynchronization() const;
@@ -131,12 +136,8 @@ class SMILTimeContainer : public GarbageCollectedFinalized<SMILTimeContainer> {
TaskRunnerTimer<SMILTimeContainer> wakeup_timer_;
TaskRunnerTimer<SMILTimeContainer> animation_policy_once_timer_;
- using AnimationsLinkedHashSet = HeapLinkedHashSet<WeakMember<SVGSMILElement>>;
- using AttributeAnimationsMap =
- HeapHashMap<QualifiedName, Member<AnimationsLinkedHashSet>>;
- using GroupedAnimationsMap =
- HeapHashMap<WeakMember<SVGElement>, AttributeAnimationsMap>;
- GroupedAnimationsMap scheduled_animations_;
+ AnimationsMap scheduled_animations_;
+ HeapVector<Member<SMILAnimationSandwich>> active_sandwiches_;
Member<SVGSVGElement> owner_svg_element_;
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 fe85da6a37f..ffad3ed7358 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
@@ -33,13 +33,13 @@
#include "third_party/blink/renderer/core/dom/events/event.h"
#include "third_party/blink/renderer/core/dom/events/native_event_listener.h"
#include "third_party/blink/renderer/core/dom/id_target_observer.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/svg/animation/smil_time_container.h"
#include "third_party/blink/renderer/core/svg/svg_svg_element.h"
#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/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.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"
@@ -153,12 +153,13 @@ void SVGSMILElement::Condition::ConnectSyncBase(SVGSMILElement& timed_element) {
DCHECK(!base_id_.IsEmpty());
DCHECK_EQ(type_, kSyncbase);
Element* element = timed_element.GetTreeScope().getElementById(base_id_);
- if (!element || !IsSVGSMILElement(*element)) {
+ auto* svg_smil_element = DynamicTo<SVGSMILElement>(element);
+ if (!svg_smil_element) {
base_element_ = nullptr;
return;
}
- base_element_ = ToSVGSMILElement(element);
- ToSVGSMILElement(*element).AddSyncBaseDependent(timed_element);
+ base_element_ = svg_smil_element;
+ svg_smil_element->AddSyncBaseDependent(timed_element);
}
void SVGSMILElement::Condition::DisconnectSyncBase(
@@ -166,7 +167,7 @@ void SVGSMILElement::Condition::DisconnectSyncBase(
DCHECK_EQ(type_, kSyncbase);
if (!base_element_)
return;
- ToSVGSMILElement(*base_element_).RemoveSyncBaseDependent(timed_element);
+ To<SVGSMILElement>(*base_element_).RemoveSyncBaseDependent(timed_element);
base_element_ = nullptr;
}
@@ -228,7 +229,8 @@ SVGSMILElement::SVGSMILElement(const QualifiedName& tag_name, Document& doc)
cached_repeat_dur_(kInvalidCachedTime),
cached_repeat_count_(kInvalidCachedTime),
cached_min_(kInvalidCachedTime),
- cached_max_(kInvalidCachedTime) {
+ cached_max_(kInvalidCachedTime),
+ interval_has_changed_(false) {
ResolveFirstInterval();
}
@@ -710,7 +712,7 @@ static void InsertSorted(Vector<SMILTimeWithOrigin>& list,
void SVGSMILElement::AddInstanceTime(BeginOrEnd begin_or_end,
SMILTime time,
SMILTimeWithOrigin::Origin origin) {
- SMILTime elapsed = this->Elapsed();
+ SMILTime elapsed = Elapsed();
if (elapsed.IsUnresolved())
return;
SMILTimeWithOrigin time_with_origin(time, origin);
@@ -761,9 +763,9 @@ SMILTime SVGSMILElement::FindInstanceTime(BeginOrEnd begin_or_end,
SMILTime SVGSMILElement::RepeatingDuration() const {
// Computing the active duration
// http://www.w3.org/TR/SMIL2/smil-timing.html#Timing-ComputingActiveDur
- SMILTime repeat_count = this->RepeatCount();
- SMILTime repeat_dur = this->RepeatDur();
- SMILTime simple_duration = this->SimpleDuration();
+ SMILTime repeat_count = RepeatCount();
+ SMILTime repeat_dur = RepeatDur();
+ SMILTime simple_duration = SimpleDuration();
if (!simple_duration ||
(repeat_dur.IsUnresolved() && repeat_count.IsUnresolved()))
return simple_duration;
@@ -788,8 +790,8 @@ SMILTime SVGSMILElement::ResolveActiveEnd(SMILTime resolved_begin,
preliminary_active_duration =
std::min(RepeatingDuration(), resolved_end - resolved_begin);
- SMILTime min_value = this->MinValue();
- SMILTime max_value = this->MaxValue();
+ SMILTime min_value = MinValue();
+ SMILTime max_value = MaxValue();
if (min_value > max_value) {
// Ignore both.
// http://www.w3.org/TR/2001/REC-smil-animation-20010904/#MinMax
@@ -804,9 +806,9 @@ SMILInterval SVGSMILElement::ResolveInterval(
IntervalSelector interval_selector) const {
bool first = interval_selector == kFirstInterval;
// See the pseudocode in http://www.w3.org/TR/SMIL3/smil-timing.html#q90.
- SMILTime begin_after =
- first ? -std::numeric_limits<double>::infinity() : interval_.end;
- SMILTime last_interval_temp_end = std::numeric_limits<double>::infinity();
+ auto constexpr infinity = std::numeric_limits<double>::infinity();
+ SMILTime begin_after = first ? -infinity : interval_.end;
+ SMILTime last_interval_temp_end = infinity;
while (true) {
bool equals_minimum_ok = !first || interval_.end > interval_.begin;
SMILTime temp_begin =
@@ -843,7 +845,7 @@ void SVGSMILElement::ResolveFirstInterval() {
if (!first_interval.begin.IsUnresolved() && first_interval != interval_) {
interval_ = first_interval;
- NotifyDependentsIntervalChanged();
+ NotifyDependentsIntervalChanged(interval_);
next_progress_time_ = next_progress_time_.IsUnresolved()
? interval_.begin
: std::min(next_progress_time_, interval_.begin);
@@ -853,21 +855,16 @@ void SVGSMILElement::ResolveFirstInterval() {
}
}
-bool SVGSMILElement::ResolveNextInterval() {
+base::Optional<SMILInterval> SVGSMILElement::ResolveNextInterval() {
SMILInterval next_interval = ResolveInterval(kNextInterval);
DCHECK(!next_interval.begin.IsIndefinite());
if (!next_interval.begin.IsUnresolved() &&
next_interval.begin != interval_.begin) {
- interval_ = next_interval;
- NotifyDependentsIntervalChanged();
- next_progress_time_ = next_progress_time_.IsUnresolved()
- ? interval_.begin
- : std::min(next_progress_time_, interval_.begin);
- return true;
+ return next_interval;
}
- return false;
+ return base::nullopt;
}
SMILTime SVGSMILElement::NextProgressTime() const {
@@ -892,7 +889,7 @@ void SVGSMILElement::BeginListChanged(SMILTime event_time) {
if (GetActiveState() != kActive)
EndedActiveInterval();
}
- NotifyDependentsIntervalChanged();
+ NotifyDependentsIntervalChanged(interval_);
}
}
}
@@ -903,7 +900,7 @@ void SVGSMILElement::BeginListChanged(SMILTime event_time) {
}
void SVGSMILElement::EndListChanged(SMILTime) {
- SMILTime elapsed = this->Elapsed();
+ SMILTime elapsed = Elapsed();
if (is_waiting_for_first_interval_) {
ResolveFirstInterval();
} else if (elapsed < interval_.end && interval_.begin.IsFinite()) {
@@ -912,7 +909,7 @@ void SVGSMILElement::EndListChanged(SMILTime) {
new_end = ResolveActiveEnd(interval_.begin, new_end);
if (new_end != interval_.end) {
interval_.end = new_end;
- NotifyDependentsIntervalChanged();
+ NotifyDependentsIntervalChanged(interval_);
}
}
}
@@ -922,35 +919,35 @@ void SVGSMILElement::EndListChanged(SMILTime) {
time_container_->NotifyIntervalsChanged();
}
-SVGSMILElement::RestartedInterval SVGSMILElement::MaybeRestartInterval(
+base::Optional<SMILInterval> SVGSMILElement::CheckForNewRestartInterval(
double elapsed) {
DCHECK(!is_waiting_for_first_interval_);
DCHECK(elapsed >= interval_.begin);
Restart restart = GetRestart();
if (restart == kRestartNever)
- return kDidNotRestartInterval;
+ return base::nullopt;
- if (elapsed < interval_.end) {
- if (restart != kRestartAlways)
- return kDidNotRestartInterval;
+ base::Optional<SMILInterval> modified;
+ if (elapsed < interval_.end && restart == kRestartAlways) {
SMILTime next_begin = FindInstanceTime(kBegin, interval_.begin, false);
if (next_begin < interval_.end) {
- interval_.end = next_begin;
- NotifyDependentsIntervalChanged();
+ modified = interval_;
+ modified->end = next_begin;
}
}
- if (elapsed >= interval_.end) {
- if (ResolveNextInterval() && elapsed >= interval_.begin)
- return kDidRestartInterval;
+ if ((modified && elapsed >= modified->end) ||
+ (!modified && elapsed >= interval_.end)) {
+ modified = ResolveNextInterval();
}
- return kDidNotRestartInterval;
+
+ return modified;
}
void SVGSMILElement::SeekToIntervalCorrespondingToTime(double elapsed) {
DCHECK(!is_waiting_for_first_interval_);
- DCHECK(elapsed >= interval_.begin);
+ DCHECK(interval_.begin.IsFinite());
// Manually seek from interval to interval, just as if the animation would run
// regulary.
@@ -971,16 +968,33 @@ void SVGSMILElement::SeekToIntervalCorrespondingToTime(double elapsed) {
// End current interval, and start a new interval from the 'nextBegin'
// time.
interval_.end = next_begin;
- if (!ResolveNextInterval())
+
+ base::Optional<SMILInterval> next_interval = ResolveNextInterval();
+ if (!next_interval)
break;
+
+ interval_ = *next_interval;
+ NotifyDependentsIntervalChanged(interval_);
+ next_progress_time_ =
+ next_progress_time_.IsUnresolved()
+ ? interval_.begin
+ : std::min(next_progress_time_, interval_.begin);
continue;
}
// If the desired 'elapsed' time is past the current interval, advance to
// the next.
if (elapsed >= interval_.end) {
- if (!ResolveNextInterval())
+ base::Optional<SMILInterval> next_interval = ResolveNextInterval();
+ if (!next_interval)
break;
+
+ interval_ = *next_interval;
+ NotifyDependentsIntervalChanged(interval_);
+ next_progress_time_ =
+ next_progress_time_.IsUnresolved()
+ ? interval_.begin
+ : std::min(next_progress_time_, interval_.begin);
continue;
}
@@ -988,45 +1002,57 @@ void SVGSMILElement::SeekToIntervalCorrespondingToTime(double elapsed) {
}
}
-float SVGSMILElement::CalculateAnimationPercentAndRepeat(
- double elapsed,
- unsigned& repeat) const {
- SMILTime simple_duration = this->SimpleDuration();
- repeat = 0;
+unsigned SVGSMILElement::CalculateAnimationRepeat(double elapsed) const {
+ const SMILTime simple_duration = SimpleDuration();
+ if (simple_duration.IsIndefinite() || !simple_duration)
+ return 0;
+ DCHECK(simple_duration.IsFinite());
+ DCHECK(interval_.begin.IsFinite());
+
+ double active_time = std::max(elapsed - interval_.begin.Value(), 0.0);
+ SMILTime repeating_duration = RepeatingDuration();
+ if (elapsed >= interval_.end || active_time > repeating_duration) {
+ unsigned repeat = static_cast<unsigned>(repeating_duration.Value() /
+ simple_duration.Value());
+ if (!fmod(repeating_duration.Value(), simple_duration.Value()))
+ return repeat - 1;
+ return repeat;
+ }
+ unsigned repeat =
+ static_cast<unsigned>(active_time / simple_duration.Value());
+ return repeat;
+}
+
+float SVGSMILElement::CalculateAnimationPercent(double elapsed) const {
+ SMILTime simple_duration = SimpleDuration();
if (simple_duration.IsIndefinite()) {
- repeat = 0;
return 0.f;
}
if (!simple_duration) {
- repeat = 0;
return 1.f;
}
- DCHECK(interval_.begin.IsFinite());
DCHECK(simple_duration.IsFinite());
+ DCHECK(interval_.begin.IsFinite());
+
+ SMILTime repeating_duration = RepeatingDuration();
double active_time = elapsed - interval_.begin.Value();
- SMILTime repeating_duration = this->RepeatingDuration();
if (elapsed >= interval_.end || active_time > repeating_duration) {
- repeat = static_cast<unsigned>(repeating_duration.Value() /
- simple_duration.Value());
- if (!fmod(repeating_duration.Value(), simple_duration.Value()))
- repeat--;
-
// Use the interval to compute the interval position if we've passed the
// interval end, otherwise use the "repeating duration". This prevents a
// stale interval (with for instance an 'indefinite' end) from yielding an
// invalid interval position.
- double last_active_duration =
- elapsed >= interval_.end
- ? interval_.end.Value() - interval_.begin.Value()
- : repeating_duration.Value();
+ double last_active_duration;
+ if (elapsed >= interval_.end)
+ last_active_duration = interval_.end.Value() - interval_.begin.Value();
+ else
+ last_active_duration = repeating_duration.Value();
double percent = last_active_duration / simple_duration.Value();
percent = percent - floor(percent);
- if (percent < std::numeric_limits<float>::epsilon() ||
- 1 - percent < std::numeric_limits<float>::epsilon())
+ float epsilon = std::numeric_limits<float>::epsilon();
+ if (percent < epsilon || 1 - percent < epsilon)
return 1.0f;
return clampTo<float>(percent);
}
- repeat = static_cast<unsigned>(active_time / simple_duration.Value());
double simple_time = fmod(active_time, simple_duration.Value());
return clampTo<float>(simple_time / simple_duration.Value());
}
@@ -1035,7 +1061,7 @@ SMILTime SVGSMILElement::CalculateNextProgressTime(double elapsed) const {
if (GetActiveState() == kActive) {
// If duration is indefinite the value does not actually change over time.
// Same is true for <set>.
- SMILTime simple_duration = this->SimpleDuration();
+ SMILTime simple_duration = SimpleDuration();
if (simple_duration.IsIndefinite() || IsSVGSetElement(*this)) {
SMILTime repeating_duration_end = interval_.begin + RepeatingDuration();
// We are supposed to do freeze semantics when repeating ends, even if the
@@ -1069,13 +1095,19 @@ bool SVGSMILElement::IsContributing(double elapsed) const {
GetActiveState() == kFrozen;
}
-bool SVGSMILElement::Progress(double elapsed, bool seek_to_time) {
+// The first part of the processing of the animation,
+// this checks if there are any further calculations needed
+// to continue and makes sure the intervals are correct.
+bool SVGSMILElement::NeedsToProgress(double elapsed) {
+ // Check we're connected to something.
DCHECK(time_container_);
+ // Check that we have some form of start or are prepared to find it.
DCHECK(is_waiting_for_first_interval_ || interval_.begin.IsFinite());
if (!sync_base_conditions_connected_)
ConnectSyncBaseConditions();
+ // Check if we need updating, otherwise just return.
if (!interval_.begin.IsFinite()) {
DCHECK_EQ(GetActiveState(), kInactive);
next_progress_time_ = SMILTime::Unresolved();
@@ -1085,39 +1117,92 @@ bool SVGSMILElement::Progress(double elapsed, bool seek_to_time) {
if (elapsed < interval_.begin) {
DCHECK_NE(GetActiveState(), kActive);
next_progress_time_ = interval_.begin;
- // If the animation is frozen, it's still contributing.
- return GetActiveState() == kFrozen;
+ return false;
}
- previous_interval_begin_ = interval_.begin;
if (is_waiting_for_first_interval_) {
is_waiting_for_first_interval_ = false;
ResolveFirstInterval();
}
+ return true;
+}
+void SVGSMILElement::TriggerPendingEvents(double elapsed) {
+ if (GetActiveState() == kInactive)
+ ScheduleEvent(event_type_names::kBeginEvent);
+
+ unsigned repeat = CalculateAnimationRepeat(elapsed);
+ if (repeat) {
+ for (unsigned repeat_event_count = 1; repeat_event_count < repeat;
+ repeat_event_count++)
+ ScheduleRepeatEvents(repeat_event_count);
+ if (GetActiveState() == kInactive)
+ ScheduleRepeatEvents(repeat);
+ }
+
+ if (GetActiveState() == kInactive || GetActiveState() == kFrozen)
+ ScheduleEvent(event_type_names::kEndEvent);
+}
+
+void SVGSMILElement::UpdateSyncbases() {
+ if (!interval_has_changed_)
+ return;
+ interval_has_changed_ = false;
+ NotifyDependentsIntervalChanged(interval_);
+ next_progress_time_ = next_progress_time_.IsUnresolved()
+ ? interval_.begin
+ : std::min(next_progress_time_, interval_.begin);
+}
+
+void SVGSMILElement::UpdateNextProgressTime(double elapsed) {
+ next_progress_time_ = CalculateNextProgressTime(elapsed);
+}
+
+void SVGSMILElement::Progress(double elapsed, bool seek_to_time) {
// This call may obtain a new interval -- never call
- // calculateAnimationPercentAndRepeat() before!
+ // CalculateAnimation{ Percent, Repeat }() before!
if (seek_to_time) {
SeekToIntervalCorrespondingToTime(elapsed);
if (elapsed < interval_.begin) {
// elapsed is not within an interval.
next_progress_time_ = interval_.begin;
- return false;
+ return;
}
}
- unsigned repeat = 0;
- float percent = CalculateAnimationPercentAndRepeat(elapsed, repeat);
- RestartedInterval restarted_interval = MaybeRestartInterval(elapsed);
+ float percent = CalculateAnimationPercent(elapsed);
+ unsigned repeat = CalculateAnimationRepeat(elapsed);
+
+ base::Optional<SMILInterval> new_interval =
+ CheckForNewRestartInterval(elapsed);
+
+ // This boolean is quite intricate. (Bug 379751)
+ //
+ // If we get a new interval we send all events
+ bool interval_did_start_or_end = (new_interval && *new_interval != interval_);
+
+ // This catches a tricky edge case where the interval began and ended
+ // on the same frame. So we check if the interval has passed, and
+ // that it's not the same interval as it was last time.
+ bool new_begin_time =
+ (interval_.begin != previous_interval_begin_ && interval_.end <= elapsed);
+
+ if (new_begin_time) {
+ previous_interval_begin_ = interval_.begin;
+ interval_did_start_or_end = true;
+ }
+
+ if (new_interval) {
+ interval_ = *new_interval;
+ interval_has_changed_ = true;
+ }
ActiveState old_active_state = GetActiveState();
active_state_ = DetermineActiveState(elapsed);
- bool animation_is_contributing = IsContributing(elapsed);
- if (animation_is_contributing) {
- if (old_active_state == kInactive ||
- restarted_interval == kDidRestartInterval) {
+ if (IsContributing(elapsed)) {
+ if (old_active_state == kInactive || interval_did_start_or_end) {
ScheduleEvent(event_type_names::kBeginEvent);
StartedActiveInterval();
}
@@ -1130,34 +1215,15 @@ bool SVGSMILElement::Progress(double elapsed, bool seek_to_time) {
}
if ((old_active_state == kActive && GetActiveState() != kActive) ||
- restarted_interval == kDidRestartInterval) {
+ interval_did_start_or_end) {
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(event_type_names::kBeginEvent);
-
- if (repeat) {
- for (unsigned repeat_event_count = 1; repeat_event_count < repeat;
- repeat_event_count++)
- ScheduleRepeatEvents(repeat_event_count);
- if (GetActiveState() == kInactive)
- ScheduleRepeatEvents(repeat);
- }
-
- if (GetActiveState() == kInactive || GetActiveState() == kFrozen)
- ScheduleEvent(event_type_names::kEndEvent);
- }
-
- next_progress_time_ = CalculateNextProgressTime(elapsed);
- return animation_is_contributing;
}
-void SVGSMILElement::NotifyDependentsIntervalChanged() {
- DCHECK(interval_.begin.IsFinite());
+void SVGSMILElement::NotifyDependentsIntervalChanged(
+ const SMILInterval& interval) {
+ DCHECK(interval.begin.IsFinite());
// |loopBreaker| is used to avoid infinite recursions which may be caused by:
// |notifyDependentsIntervalChanged| -> |createInstanceTimesFromSyncbase| ->
// |add{Begin,End}Time| -> |{begin,end}TimeChanged| ->
@@ -1172,13 +1238,14 @@ void SVGSMILElement::NotifyDependentsIntervalChanged() {
return;
for (SVGSMILElement* element : sync_base_dependents_)
- element->CreateInstanceTimesFromSyncbase(*this);
+ element->CreateInstanceTimesFromSyncbase(*this, interval);
loop_breaker.erase(this);
}
void SVGSMILElement::CreateInstanceTimesFromSyncbase(
- SVGSMILElement& sync_base) {
+ SVGSMILElement& sync_base,
+ const SMILInterval& interval) {
// FIXME: To be really correct, this should handle updating exising interval
// by changing the associated times instead of creating new ones.
for (Condition* condition : conditions_) {
@@ -1189,9 +1256,9 @@ void SVGSMILElement::CreateInstanceTimesFromSyncbase(
// conversions. Phew!
SMILTime time = 0;
if (condition->GetName() == "begin")
- time = sync_base.interval_.begin + condition->Offset();
+ time = interval.begin + condition->Offset();
else
- time = sync_base.interval_.end + condition->Offset();
+ time = interval.end + condition->Offset();
if (!time.IsFinite())
continue;
AddInstanceTime(condition->GetBeginOrEnd(), time);
@@ -1202,7 +1269,7 @@ void SVGSMILElement::CreateInstanceTimesFromSyncbase(
void SVGSMILElement::AddSyncBaseDependent(SVGSMILElement& animation) {
sync_base_dependents_.insert(&animation);
if (interval_.begin.IsFinite())
- animation.CreateInstanceTimesFromSyncbase(*this);
+ animation.CreateInstanceTimesFromSyncbase(*this, interval_);
}
void SVGSMILElement::RemoveSyncBaseDependent(SVGSMILElement& animation) {
@@ -1267,6 +1334,10 @@ void SVGSMILElement::DidChangeAnimationTarget() {
is_scheduled_ = true;
}
+const AttrNameToTrustedType& SVGSMILElement::GetCheckedAttributeTypes() const {
+ return SVGURIReference::GetCheckedAttributeTypes();
+}
+
void SVGSMILElement::Trace(blink::Visitor* visitor) {
visitor->Trace(target_element_);
visitor->Trace(target_id_observer_);
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 5ff56d78fa8..5e801946596 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
@@ -85,7 +85,13 @@ class CORE_EXPORT SVGSMILElement : public SVGElement, public SVGTests {
SMILTime SimpleDuration() const;
void SeekToIntervalCorrespondingToTime(double elapsed);
- bool Progress(double elapsed, bool seek_to_time);
+
+ bool NeedsToProgress(double elapsed);
+ void Progress(double elapsed, bool seek_to_time);
+ void TriggerPendingEvents(double elapsed);
+ void UpdateSyncbases();
+ void UpdateNextProgressTime(double elapsed);
+
SMILTime NextProgressTime() const;
void UpdateAnimatedValue(SVGSMILElement* result_element) {
UpdateAnimation(last_percent_, last_repeat_, result_element);
@@ -106,6 +112,11 @@ class CORE_EXPORT SVGSMILElement : public SVGElement, public SVGTests {
virtual void ClearAnimatedType() = 0;
virtual void ApplyResultsToTarget() = 0;
+ // Returns true if this animation "sets" the
+ // value of the animation. Thus all previous
+ // animations are rendered useless.
+ virtual bool OverwritesUnderlyingAnimationValue() = 0;
+
bool AnimatedTypeIsLocked() const { return animated_property_locked_; }
void LockAnimatedType() {
DCHECK(!animated_property_locked_);
@@ -125,6 +136,8 @@ class CORE_EXPORT SVGSMILElement : public SVGElement, public SVGTests {
virtual bool IsSVGDiscardElement() const { return false; }
+ const AttrNameToTrustedType& GetCheckedAttributeTypes() const override;
+
void Trace(blink::Visitor*) override;
protected:
@@ -168,14 +181,12 @@ class CORE_EXPORT SVGSMILElement : public SVGElement, public SVGTests {
SMILInterval ResolveInterval(IntervalSelector) const;
void ResolveFirstInterval();
- bool ResolveNextInterval();
+ base::Optional<SMILInterval> ResolveNextInterval();
SMILTime ResolveActiveEnd(SMILTime resolved_begin,
SMILTime resolved_end) const;
SMILTime RepeatingDuration() const;
- enum RestartedInterval { kDidNotRestartInterval, kDidRestartInterval };
-
- RestartedInterval MaybeRestartInterval(double elapsed);
+ base::Optional<SMILInterval> CheckForNewRestartInterval(double elapsed);
void BeginListChanged(SMILTime event_time);
void EndListChanged(SMILTime event_time);
@@ -227,8 +238,9 @@ class CORE_EXPORT SVGSMILElement : public SVGElement, public SVGTests {
void DisconnectSyncBaseConditions();
void DisconnectEventBaseConditions();
- void NotifyDependentsIntervalChanged();
- void CreateInstanceTimesFromSyncbase(SVGSMILElement& syncbase);
+ void NotifyDependentsIntervalChanged(const SMILInterval& interval);
+ void CreateInstanceTimesFromSyncbase(SVGSMILElement& syncbase,
+ const SMILInterval& interval);
void AddSyncBaseDependent(SVGSMILElement&);
void RemoveSyncBaseDependent(SVGSMILElement&);
@@ -238,8 +250,8 @@ class CORE_EXPORT SVGSMILElement : public SVGElement, public SVGTests {
return static_cast<ActiveState>(active_state_);
}
ActiveState DetermineActiveState(SMILTime elapsed) const;
- float CalculateAnimationPercentAndRepeat(double elapsed,
- unsigned& repeat) const;
+ float CalculateAnimationPercent(double elapsed) const;
+ unsigned CalculateAnimationRepeat(double elapsed) const;
SMILTime CalculateNextProgressTime(double elapsed) const;
Member<SVGElement> target_element_;
@@ -284,6 +296,7 @@ class CORE_EXPORT SVGSMILElement : public SVGElement, public SVGTests {
mutable SMILTime cached_max_;
bool animated_property_locked_;
+ bool interval_has_changed_;
friend class ConditionEventListener;
};
@@ -296,8 +309,15 @@ inline bool IsSVGSMILElement(const SVGElement& element) {
element.HasTagName((svg_names::kDiscardTag));
}
-DEFINE_SVGELEMENT_TYPE_CASTS_WITH_FUNCTION(SVGSMILElement);
+template <>
+struct DowncastTraits<SVGSMILElement> {
+ static bool AllowFrom(const Node& node) {
+ auto* svg_element = DynamicTo<SVGElement>(node);
+ return svg_element && IsSVGSMILElement(*svg_element);
+ }
+};
+DEFINE_SVGELEMENT_TYPE_CASTS_WITH_FUNCTION(SVGSMILElement);
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_SVG_ANIMATION_SVG_SMIL_ELEMENT_H_
diff --git a/chromium/third_party/blink/renderer/core/svg/color_distance.h b/chromium/third_party/blink/renderer/core/svg/color_distance.h
index f69c1c1748c..cef574f78e4 100644
--- a/chromium/third_party/blink/renderer/core/svg/color_distance.h
+++ b/chromium/third_party/blink/renderer/core/svg/color_distance.h
@@ -20,7 +20,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_SVG_COLOR_DISTANCE_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_SVG_COLOR_DISTANCE_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/svg/gradient_attributes.h b/chromium/third_party/blink/renderer/core/svg/gradient_attributes.h
index a6eb3872330..18eadcfd26c 100644
--- a/chromium/third_party/blink/renderer/core/svg/gradient_attributes.h
+++ b/chromium/third_party/blink/renderer/core/svg/gradient_attributes.h
@@ -22,7 +22,7 @@
#include "third_party/blink/renderer/core/svg/svg_gradient_element.h"
#include "third_party/blink/renderer/core/svg/svg_unit_types.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/svg/graphics/dark_mode_svg_image_classifier.cc b/chromium/third_party/blink/renderer/core/svg/graphics/dark_mode_svg_image_classifier.cc
index da38d471619..5947150aac5 100644
--- a/chromium/third_party/blink/renderer/core/svg/graphics/dark_mode_svg_image_classifier.cc
+++ b/chromium/third_party/blink/renderer/core/svg/graphics/dark_mode_svg_image_classifier.cc
@@ -11,7 +11,7 @@ DarkModeSVGImageClassifier::DarkModeSVGImageClassifier() {}
DarkModeClassification DarkModeSVGImageClassifier::Classify(
SVGImage* image,
const FloatRect& src_rect) {
- return DarkModeClassification::kApplyDarkModeFilter;
+ return DarkModeClassification::kApplyFilter;
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/graphics/dark_mode_svg_image_classifier.h b/chromium/third_party/blink/renderer/core/svg/graphics/dark_mode_svg_image_classifier.h
index 62bdaf9feb0..98fa960a33d 100644
--- a/chromium/third_party/blink/renderer/core/svg/graphics/dark_mode_svg_image_classifier.h
+++ b/chromium/third_party/blink/renderer/core/svg/graphics/dark_mode_svg_image_classifier.h
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/svg/graphics/svg_image.h"
#include "third_party/blink/renderer/platform/geometry/float_rect.h"
#include "third_party/blink/renderer/platform/graphics/graphics_types.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/svg/graphics/filters/svg_filter_builder.cc b/chromium/third_party/blink/renderer/core/svg/graphics/filters/svg_filter_builder.cc
index f7049447a40..751dc6ba66e 100644
--- a/chromium/third_party/blink/renderer/core/svg/graphics/filters/svg_filter_builder.cc
+++ b/chromium/third_party/blink/renderer/core/svg/graphics/filters/svg_filter_builder.cc
@@ -96,7 +96,7 @@ void SVGFilterGraphNodeMap::InvalidateDependentEffects(FilterEffect* effect) {
effect->DisposeImageFilters();
- FilterEffectSet& effect_references = this->EffectReferences(effect);
+ FilterEffectSet& effect_references = EffectReferences(effect);
for (FilterEffect* effect_reference : effect_references)
InvalidateDependentEffects(effect_reference);
}
@@ -179,8 +179,7 @@ void SVGFilterBuilder::BuildGraph(Filter* filter,
if (!element->IsFilterEffect())
continue;
- SVGFilterPrimitiveStandardAttributes& effect_element =
- ToSVGFilterPrimitiveStandardAttributes(*element);
+ auto& effect_element = To<SVGFilterPrimitiveStandardAttributes>(*element);
FilterEffect* effect = effect_element.Build(this, filter);
if (!effect)
continue;
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 943099a29d8..1801d0f37cc 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
@@ -34,6 +34,7 @@
#include "third_party/blink/renderer/core/dom/events/event_dispatch_forbidden_scope.h"
#include "third_party/blink/renderer/core/dom/flat_tree_traversal.h"
#include "third_party/blink/renderer/core/dom/node_traversal.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/local_frame_view.h"
@@ -673,13 +674,18 @@ void SVGImage::AdvanceAnimationForTesting() {
root_element->TimeContainer()->AdvanceFrameForTesting();
// The following triggers animation updates which can issue a new draw
- // but will not permanently change the animation timeline.
- // TODO(pdr): Actually advance the document timeline so CSS animations
- // can be properly tested.
+ // and temporarily change the animation timeline. It's necessary to call
+ // reset before changing to a time value as animation clock does not
+ // expect to go backwards.
+ base::TimeTicks current_animation_time =
+ page_->Animator().Clock().CurrentTime();
+ page_->Animator().Clock().ResetTimeForTesting();
page_->Animator().ServiceScriptedAnimations(
- base::TimeTicks() +
+ root_element->GetDocument().Timeline().ZeroTime() +
base::TimeDelta::FromSecondsD(root_element->getCurrentTime()));
GetImageObserver()->Changed(this);
+ page_->Animator().Clock().ResetTimeForTesting();
+ page_->Animator().Clock().UpdateTime(current_animation_time);
}
}
@@ -789,7 +795,8 @@ Image::SizeAvailability SVGImage::DataChanged(bool all_data_received) {
TRACE_EVENT0("blink", "SVGImage::dataChanged::createFrame");
DCHECK(!frame_client_);
frame_client_ = MakeGarbageCollected<SVGImageLocalFrameClient>(this);
- frame = MakeGarbageCollected<LocalFrame>(frame_client_, *page, nullptr);
+ frame = MakeGarbageCollected<LocalFrame>(frame_client_, *page, nullptr,
+ nullptr, nullptr);
frame->SetView(MakeGarbageCollected<LocalFrameView>(*frame));
frame->Init();
}
@@ -838,6 +845,10 @@ Image::SizeAvailability SVGImage::DataChanged(bool all_data_received) {
return kSizeAvailable;
}
+bool SVGImage::IsSizeAvailable() {
+ return SvgRootElement(page_.Get());
+}
+
String SVGImage::FilenameExtension() const {
return "svg";
}
diff --git a/chromium/third_party/blink/renderer/core/svg/graphics/svg_image.h b/chromium/third_party/blink/renderer/core/svg/graphics/svg_image.h
index c501563971b..29fe1bf74c6 100644
--- a/chromium/third_party/blink/renderer/core/svg/graphics/svg_image.h
+++ b/chromium/third_party/blink/renderer/core/svg/graphics/svg_image.h
@@ -33,7 +33,7 @@
#include "third_party/blink/renderer/platform/graphics/paint/paint_record.h"
#include "third_party/blink/renderer/platform/heap/handle.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/allocator/allocator.h"
#include "third_party/skia/include/core/SkRefCnt.h"
namespace blink {
@@ -126,7 +126,7 @@ class CORE_EXPORT SVGImage final : public Image {
protected:
// Whether or not size is available yet.
- bool IsSizeAvailable() override { return !!page_; }
+ bool IsSizeAvailable() override;
private:
// Accesses m_page.
@@ -245,8 +245,9 @@ class CORE_EXPORT SVGImage final : public Image {
FRIEND_TEST_ALL_PREFIXES(ElementFragmentAnchorTest,
SVGDocumentDoesntCreateFragment);
FRIEND_TEST_ALL_PREFIXES(SVGImageTest, SupportsSubsequenceCaching);
- FRIEND_TEST_ALL_PREFIXES(SVGImageTest, JankTrackerDisabled);
+ FRIEND_TEST_ALL_PREFIXES(SVGImageTest, LayoutShiftTrackerDisabled);
FRIEND_TEST_ALL_PREFIXES(SVGImageTest, SetSizeOnVisualViewport);
+ FRIEND_TEST_ALL_PREFIXES(SVGImageTest, IsSizeAvailable);
};
DEFINE_IMAGE_TYPE_CASTS(SVGImage);
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 058982369b9..141c30d0d25 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
@@ -38,8 +38,8 @@
namespace blink {
-static constexpr TimeDelta kAnimationFrameDelay =
- TimeDelta::FromSecondsD(1.0 / 60);
+static constexpr base::TimeDelta kAnimationFrameDelay =
+ base::TimeDelta::FromSecondsD(1.0 / 60);
SVGImageChromeClient::SVGImageChromeClient(SVGImage* image)
: image_(image),
@@ -104,7 +104,7 @@ void SVGImageChromeClient::ScheduleAnimation(const LocalFrameView*) {
// animations, but prefer a fixed, jittery, frame-delay if there're any
// animations. Checking for pending/active animations could be more
// stringent.
- TimeDelta fire_time;
+ base::TimeDelta fire_time;
if (image_->MaybeAnimated()) {
if (IsSuspended())
return;
@@ -131,7 +131,7 @@ void SVGImageChromeClient::AnimationTimerFired(TimerBase*) {
if (!image_->GetImageObserver())
return;
- image_->ServiceAnimations(CurrentTimeTicks());
+ image_->ServiceAnimations(base::TimeTicks::Now());
}
} // namespace blink
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 f6adc8da886..078ece67a1f 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
@@ -12,7 +12,7 @@
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/frame/visual_viewport.h"
#include "third_party/blink/renderer/core/html/html_image_element.h"
-#include "third_party/blink/renderer/core/layout/jank_tracker.h"
+#include "third_party/blink/renderer/core/layout/layout_shift_tracker.h"
#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/svg/graphics/svg_image_chrome_client.h"
@@ -114,7 +114,7 @@ TEST_F(SVGImageTest, TimelineSuspendAndResume) {
// Fire the timer/trigger a frame update. Since the observer always returns
// true for shouldPauseAnimation, this will result in the timeline being
// suspended.
- test::RunDelayedTasks(TimeDelta::FromMilliseconds(1) +
+ test::RunDelayedTasks(base::TimeDelta::FromMilliseconds(1) +
timer->NextFireInterval());
EXPECT_TRUE(chrome_client.IsSuspended());
EXPECT_FALSE(timer->IsActive());
@@ -148,7 +148,7 @@ TEST_F(SVGImageTest, ResetAnimation) {
// Fire the timer/trigger a frame update. The timeline will remain
// suspended and no frame will be scheduled.
- test::RunDelayedTasks(TimeDelta::FromMillisecondsD(1) +
+ test::RunDelayedTasks(base::TimeDelta::FromMillisecondsD(1) +
timer->NextFireInterval());
EXPECT_TRUE(chrome_client.IsSuspended());
EXPECT_FALSE(timer->IsActive());
@@ -172,14 +172,14 @@ TEST_F(SVGImageTest, SupportsSubsequenceCaching) {
ToLayoutBoxModelObject(svg_root)->Layer()->SupportsSubsequenceCaching());
}
-TEST_F(SVGImageTest, JankTrackerDisabled) {
+TEST_F(SVGImageTest, LayoutShiftTrackerDisabled) {
const bool kDontPause = false;
Load("<svg xmlns='http://www.w3.org/2000/svg'></svg>", kDontPause);
LocalFrame* local_frame =
To<LocalFrame>(GetImage().GetPageForTesting()->MainFrame());
EXPECT_TRUE(local_frame->GetDocument()->IsSVGDocument());
- auto& jank_tracker = local_frame->View()->GetJankTracker();
- EXPECT_FALSE(jank_tracker.IsActive());
+ auto& layout_shift_tracker = local_frame->View()->GetLayoutShiftTracker();
+ EXPECT_FALSE(layout_shift_tracker.IsActive());
}
TEST_F(SVGImageTest, SetSizeOnVisualViewport) {
@@ -197,6 +197,18 @@ TEST_F(SVGImageTest, SetSizeOnVisualViewport) {
GetImage().GetPageForTesting()->GetVisualViewport().Size());
}
+TEST_F(SVGImageTest, IsSizeAvailable) {
+ const bool kShouldPause = false;
+ Load("<svg xmlns='http://www.w3.org/2000/svg'></svg>", kShouldPause);
+ EXPECT_TRUE(GetImage().IsSizeAvailable());
+
+ Load("<notsvg></notsvg>", kShouldPause);
+ EXPECT_FALSE(GetImage().IsSizeAvailable());
+
+ Load("<notsvg xmlns='http://www.w3.org/2000/svg'></notsvg>", kShouldPause);
+ EXPECT_FALSE(GetImage().IsSizeAvailable());
+}
+
class SVGImageSimTest : public SimTest {};
TEST_F(SVGImageSimTest, PageVisibilityHiddenToVisible) {
@@ -226,7 +238,7 @@ TEST_F(SVGImageSimTest, PageVisibilityHiddenToVisible) {
// Wait for the next animation frame to be triggered, and then trigger a new
// frame. The image animation timeline should be running.
- test::RunDelayedTasks(TimeDelta::FromMilliseconds(1) +
+ test::RunDelayedTasks(base::TimeDelta::FromMilliseconds(1) +
timer->NextFireInterval());
Compositor().BeginFrame();
@@ -236,7 +248,7 @@ TEST_F(SVGImageSimTest, PageVisibilityHiddenToVisible) {
// fire. This should suspend the image animation. (Suspend the image's
// animation timeline.)
WebView().SetIsHidden(/*is_hidden=*/true, /*initial_state=*/false);
- test::RunDelayedTasks(TimeDelta::FromMilliseconds(1) +
+ test::RunDelayedTasks(base::TimeDelta::FromMilliseconds(1) +
timer->NextFireInterval());
EXPECT_TRUE(svg_image_chrome_client.IsSuspended());
@@ -244,7 +256,7 @@ TEST_F(SVGImageSimTest, PageVisibilityHiddenToVisible) {
// Set page visibility to 'visible' - this should schedule a new animation
// frame and resume the image animation.
WebView().SetIsHidden(/*is_hidden=*/false, /*initial_state=*/false);
- test::RunDelayedTasks(TimeDelta::FromMilliseconds(1) +
+ test::RunDelayedTasks(base::TimeDelta::FromMilliseconds(1) +
timer->NextFireInterval());
Compositor().BeginFrame();
diff --git a/chromium/third_party/blink/renderer/core/svg/properties/svg_animated_property.cc b/chromium/third_party/blink/renderer/core/svg/properties/svg_animated_property.cc
index 00baabda75f..31b4b832dd5 100644
--- a/chromium/third_party/blink/renderer/core/svg/properties/svg_animated_property.cc
+++ b/chromium/third_party/blink/renderer/core/svg/properties/svg_animated_property.cc
@@ -51,8 +51,8 @@ SVGAnimatedPropertyBase::SVGAnimatedPropertyBase(
attribute_name_(attribute_name) {
DCHECK(context_element_);
DCHECK(attribute_name_ != QualifiedName::Null());
- DCHECK_EQ(this->GetType(), type);
- DCHECK_EQ(this->CssPropertyId(), css_property_id);
+ DCHECK_EQ(GetType(), type);
+ DCHECK_EQ(CssPropertyId(), css_property_id);
DCHECK_EQ(initial_value_storage_, initial_value);
}
diff --git a/chromium/third_party/blink/renderer/core/svg/properties/svg_list_property_helper.h b/chromium/third_party/blink/renderer/core/svg/properties/svg_list_property_helper.h
index 866817217a3..7596e65f652 100644
--- a/chromium/third_party/blink/renderer/core/svg/properties/svg_list_property_helper.h
+++ b/chromium/third_party/blink/renderer/core/svg/properties/svg_list_property_helper.h
@@ -36,7 +36,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/heap/heap.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
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 0a7bb9f24ca..f44723cbf89 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
@@ -120,8 +120,9 @@ void SVGAElement::DefaultEventHandler(Event& event) {
if (url[0] == '#') {
Element* target_element =
GetTreeScope().getElementById(AtomicString(url.Substring(1)));
- if (target_element && IsSVGSMILElement(*target_element)) {
- ToSVGSMILElement(target_element)->BeginByLinkActivation();
+ if (auto* svg_smil_element =
+ DynamicTo<SVGSMILElement>(target_element)) {
+ svg_smil_element->BeginByLinkActivation();
event.SetDefaultHandled();
return;
}
@@ -132,14 +133,18 @@ void SVGAElement::DefaultEventHandler(Event& event) {
target = AtomicString("_blank");
event.SetDefaultHandled();
+ if (!GetDocument().GetFrame())
+ return;
+
FrameLoadRequest frame_request(
&GetDocument(), ResourceRequest(GetDocument().CompleteURL(url)));
frame_request.SetNavigationPolicy(NavigationPolicyFromEvent(&event));
frame_request.SetTriggeringEventInfo(
event.isTrusted() ? WebTriggeringEventInfo::kFromTrustedEvent
: WebTriggeringEventInfo::kFromUntrustedEvent);
- if (!GetDocument().GetFrame())
- return;
+ frame_request.GetResourceRequest().SetHasUserGesture(
+ LocalFrame::HasTransientUserActivation(GetDocument().GetFrame()));
+
Frame* frame = GetDocument()
.GetFrame()
->Tree()
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_a_element.h b/chromium/third_party/blink/renderer/core/svg/svg_a_element.h
index 0302bcae462..19cfd753e5a 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_a_element.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_a_element.h
@@ -38,6 +38,10 @@ class CORE_EXPORT SVGAElement final : public SVGGraphicsElement,
explicit SVGAElement(Document&);
+ const AttrNameToTrustedType& GetCheckedAttributeTypes() const override {
+ return SVGURIReference::GetCheckedAttributeTypes();
+ }
+
void Trace(blink::Visitor*) override;
private:
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_a_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_a_element.idl
index 29e46a3f5ef..cdc459e6628 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_a_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_a_element.idl
@@ -25,6 +25,7 @@
// https://svgwg.org/svg2-draft/linking.html#InterfaceSVGAElement
+[Exposed=Window]
interface SVGAElement : SVGGraphicsElement {
[ImplementedAs=svgTarget, Measure] readonly attribute SVGAnimatedString target;
};
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_angle.idl b/chromium/third_party/blink/renderer/core/svg/svg_angle.idl
index e684b5582cb..84a5f2907c0 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_angle.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_angle.idl
@@ -23,6 +23,7 @@
// https://svgwg.org/svg2-draft/types.html#InterfaceSVGAngle
[
+ Exposed=Window,
ImplementedAs=SVGAngleTearOff
] interface SVGAngle {
// Angle Unit Types
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 7cb6975172d..8096b369441 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
@@ -339,8 +339,7 @@ void SVGAnimateElement::CalculateAnimatedValue(float percentage,
DCHECK_EQ(from_property_->GetType(), GetAnimatedPropertyType());
DCHECK(to_property_);
- SVGAnimateElement* result_animation_element =
- ToSVGAnimateElement(result_element);
+ auto* result_animation_element = To<SVGAnimateElement>(result_element);
DCHECK(result_animation_element->animated_value_);
DCHECK_EQ(result_animation_element->GetAnimatedPropertyType(),
GetAnimatedPropertyType());
@@ -352,7 +351,7 @@ void SVGAnimateElement::CalculateAnimatedValue(float percentage,
percentage = percentage < 0.5 ? 0 : 1;
// Target element might have changed.
- SVGElement* target_element = this->targetElement();
+ SVGElement* target_element = targetElement();
// Values-animation accumulates using the last values entry corresponding to
// the end of duration time.
@@ -419,8 +418,8 @@ bool SVGAnimateElement::CalculateFromAndByValues(const String& from_string,
void SVGAnimateElement::ResetAnimatedType() {
ResolveTargetProperty();
- SVGElement* target_element = this->targetElement();
- const QualifiedName& attribute_name = this->AttributeName();
+ SVGElement* target_element = targetElement();
+ const QualifiedName& attribute_name = AttributeName();
if (!ShouldApplyAnimation(*target_element, attribute_name))
return;
@@ -451,7 +450,7 @@ void SVGAnimateElement::ClearAnimatedType() {
// the lock is held. See crbug.com/581546.
DCHECK(!AnimatedTypeIsLocked());
- SVGElement* target_element = this->targetElement();
+ SVGElement* target_element = targetElement();
if (!target_element) {
animated_value_.Clear();
return;
@@ -489,7 +488,8 @@ void SVGAnimateElement::ApplyResultsToTarget() {
if (!animated_value_)
return;
- if (!ShouldApplyAnimation(*targetElement(), AttributeName()))
+ SVGElement* target_element = targetElement();
+ if (!ShouldApplyAnimation(*target_element, AttributeName()))
return;
// We do update the style and the animation property independent of each
@@ -497,15 +497,17 @@ void SVGAnimateElement::ApplyResultsToTarget() {
if (IsAnimatingCSSProperty()) {
// CSS properties animation code-path.
// Convert the result of the animation to a String and apply it as CSS
- // property on the target.
- MutableCSSPropertyValueSet* property_set =
- targetElement()->EnsureAnimatedSMILStyleProperties();
- if (property_set
- ->SetProperty(
- css_property_id_, animated_value_->ValueAsString(), false,
- targetElement()->GetDocument().GetSecureContextMode(), nullptr)
- .did_change) {
- targetElement()->SetNeedsStyleRecalc(
+ // property on the target_element.
+ MutableCSSPropertyValueSet* properties =
+ target_element->EnsureAnimatedSMILStyleProperties();
+ auto animated_value_string = animated_value_->ValueAsString();
+ auto secure_context_mode =
+ target_element->GetDocument().GetSecureContextMode();
+ auto set_result =
+ properties->SetProperty(css_property_id_, animated_value_string, false,
+ secure_context_mode, nullptr);
+ if (set_result.did_change) {
+ target_element->SetNeedsStyleRecalc(
kLocalStyleChange,
StyleChangeReasonForTracing::Create(style_change_reason::kAnimation));
}
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 04d066604d1..094435aef5d 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
@@ -137,7 +137,13 @@ inline bool IsSVGAnimateElement(const SVGElement& element) {
element.HasTagName(svg_names::kSetTag);
}
-DEFINE_SVGELEMENT_TYPE_CASTS_WITH_FUNCTION(SVGAnimateElement);
+template <>
+struct DowncastTraits<SVGAnimateElement> {
+ static bool AllowFrom(const Node& node) {
+ auto* element = DynamicTo<SVGElement>(node);
+ return element && IsSVGAnimateElement(*element);
+ }
+};
} // namespace blink
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 fa8c8d5fc7e..c0c87d99464 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
@@ -143,7 +143,7 @@ static bool ParsePoint(const String& string, FloatPoint& point) {
}
void SVGAnimateMotionElement::ResetAnimatedType() {
- SVGElement* target_element = this->targetElement();
+ SVGElement* target_element = targetElement();
if (!target_element || !TargetCanHaveMotionTransform(*target_element))
return;
if (AffineTransform* transform = target_element->AnimateMotionTransform())
@@ -151,7 +151,7 @@ void SVGAnimateMotionElement::ResetAnimatedType() {
}
void SVGAnimateMotionElement::ClearAnimatedType() {
- SVGElement* target_element = this->targetElement();
+ SVGElement* target_element = targetElement();
if (!target_element)
return;
@@ -198,7 +198,7 @@ bool SVGAnimateMotionElement::CalculateFromAndByValues(
void SVGAnimateMotionElement::CalculateAnimatedValue(float percentage,
unsigned repeat_count,
SVGSMILElement*) {
- SVGElement* target_element = this->targetElement();
+ SVGElement* target_element = targetElement();
DCHECK(target_element);
AffineTransform* transform = target_element->AnimateMotionTransform();
if (!transform)
@@ -245,7 +245,7 @@ void SVGAnimateMotionElement::CalculateAnimatedValue(float percentage,
}
transform->Translate(position.X(), position.Y());
- RotateMode rotate_mode = this->GetRotateMode();
+ RotateMode rotate_mode = GetRotateMode();
if (rotate_mode != kRotateAuto && rotate_mode != kRotateAutoReverse)
return;
if (rotate_mode == kRotateAutoReverse)
@@ -256,23 +256,23 @@ void SVGAnimateMotionElement::CalculateAnimatedValue(float percentage,
void SVGAnimateMotionElement::ApplyResultsToTarget() {
// We accumulate to the target element transform list so there is not much to
// do here.
- SVGElement* target_element = this->targetElement();
+ SVGElement* target_element = targetElement();
if (!target_element)
return;
- AffineTransform* t = target_element->AnimateMotionTransform();
- if (!t)
+ AffineTransform* target_transform = target_element->AnimateMotionTransform();
+ if (!target_transform)
return;
// ...except in case where we have additional instances in <use> trees.
- const HeapHashSet<WeakMember<SVGElement>>& instances =
- target_element->InstancesForElement();
+ const auto& instances = target_element->InstancesForElement();
for (SVGElement* shadow_tree_element : instances) {
DCHECK(shadow_tree_element);
- AffineTransform* transform = shadow_tree_element->AnimateMotionTransform();
- if (!transform)
+ AffineTransform* shadow_transform =
+ shadow_tree_element->AnimateMotionTransform();
+ if (!shadow_transform)
continue;
- transform->SetMatrix(t->A(), t->B(), t->C(), t->D(), t->E(), t->F());
+ shadow_transform->SetTransform(*target_transform);
if (LayoutObject* layout_object = shadow_tree_element->GetLayoutObject())
InvalidateForAnimateMotionTransformChange(*layout_object);
}
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_angle.idl b/chromium/third_party/blink/renderer/core/svg/svg_animated_angle.idl
index 73997a2c16f..2c6575dee30 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_angle.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_angle.idl
@@ -25,6 +25,7 @@
// https://svgwg.org/svg2-draft/types.html#InterfaceSVGAnimatedAngle
+[Exposed=Window]
interface SVGAnimatedAngle {
readonly attribute SVGAngle baseVal;
readonly attribute SVGAngle animVal;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_boolean.idl b/chromium/third_party/blink/renderer/core/svg/svg_animated_boolean.idl
index c8492ea9e4d..d5c4168b7ea 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_boolean.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_boolean.idl
@@ -25,6 +25,7 @@
// https://svgwg.org/svg2-draft/types.html#InterfaceSVGAnimatedBoolean
+[Exposed=Window]
interface SVGAnimatedBoolean {
[RaisesException=Setter] attribute boolean baseVal;
readonly attribute boolean animVal;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_enumeration.idl b/chromium/third_party/blink/renderer/core/svg/svg_animated_enumeration.idl
index b6e66228bae..05beaa0410e 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_enumeration.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_enumeration.idl
@@ -26,6 +26,7 @@
// https://svgwg.org/svg2-draft/types.html#InterfaceSVGAnimatedEnumeration
[
+ Exposed=Window,
ImplementedAs=SVGAnimatedEnumerationBase
] interface SVGAnimatedEnumeration {
[RaisesException=Setter] attribute unsigned short baseVal;
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 c9144106b28..bbf6c93202c 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
@@ -4,11 +4,11 @@
#include "third_party/blink/renderer/core/svg/svg_animated_href.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/svg/svg_element.h"
#include "third_party/blink/renderer/core/svg_names.h"
#include "third_party/blink/renderer/core/xlink_names.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_integer.idl b/chromium/third_party/blink/renderer/core/svg/svg_animated_integer.idl
index 794195b8449..21fde77c89d 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_integer.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_integer.idl
@@ -25,6 +25,7 @@
// https://svgwg.org/svg2-draft/types.html#InterfaceSVGAnimatedInteger
+[Exposed=Window]
interface SVGAnimatedInteger {
[RaisesException=Setter] attribute long baseVal;
readonly attribute long animVal;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_length.cc b/chromium/third_party/blink/renderer/core/svg/svg_animated_length.cc
index 6179957867c..72f7c264bda 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_length.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_length.cc
@@ -39,9 +39,13 @@ SVGParsingError SVGAnimatedLength::AttributeChanged(const String& value) {
SVGAnimatedProperty<SVGLength>::AttributeChanged(value);
if (SVGLength::NegativeValuesForbiddenForAnimatedLengthAttribute(
- AttributeName()) &&
- BaseValue()->ValueInSpecifiedUnits() < 0)
- parse_status = SVGParseStatus::kNegativeValue;
+ AttributeName())) {
+ // TODO(crbug.com/982425): Pass |kValueRangeNonNegative| to property parser
+ // to handle range checking on math functions correctly, and also to avoid
+ // this ad hoc range checking.
+ if (BaseValue()->IsNegativeNumericLiteral())
+ parse_status = SVGParseStatus::kNegativeValue;
+ }
return parse_status;
}
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_length.idl b/chromium/third_party/blink/renderer/core/svg/svg_animated_length.idl
index 4d32d50d4e5..bf4abe2037f 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_length.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_length.idl
@@ -25,6 +25,7 @@
// https://svgwg.org/svg2-draft/types.html#InterfaceSVGAnimatedLength
+[Exposed=Window]
interface SVGAnimatedLength {
readonly attribute SVGLength baseVal;
readonly attribute SVGLength animVal;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_length_list.idl b/chromium/third_party/blink/renderer/core/svg/svg_animated_length_list.idl
index 1abc3dffebf..55e73f81c7c 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_length_list.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_length_list.idl
@@ -25,6 +25,7 @@
// https://svgwg.org/svg2-draft/types.html#InterfaceSVGAnimatedLengthList
+[Exposed=Window]
interface SVGAnimatedLengthList {
readonly attribute SVGLengthList baseVal;
readonly attribute SVGLengthList animVal;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_number.idl b/chromium/third_party/blink/renderer/core/svg/svg_animated_number.idl
index 5bae7e0b196..61f0a1fd8fb 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_number.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_number.idl
@@ -26,6 +26,7 @@
// https://svgwg.org/svg2-draft/types.html#InterfaceSVGAnimatedNumber
+[Exposed=Window]
interface SVGAnimatedNumber {
[RaisesException=Setter] attribute float baseVal;
readonly attribute float animVal;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_number_list.idl b/chromium/third_party/blink/renderer/core/svg/svg_animated_number_list.idl
index 4f35f957f2d..b828e0a1b6e 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_number_list.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_number_list.idl
@@ -25,6 +25,7 @@
// https://svgwg.org/svg2-draft/types.html#InterfaceSVGAnimatedNumberList
+[Exposed=Window]
interface SVGAnimatedNumberList {
readonly attribute SVGNumberList baseVal;
readonly attribute SVGNumberList animVal;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_preserve_aspect_ratio.idl b/chromium/third_party/blink/renderer/core/svg/svg_animated_preserve_aspect_ratio.idl
index 505752ba57b..0b5fbfe1d3c 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_preserve_aspect_ratio.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_preserve_aspect_ratio.idl
@@ -25,6 +25,7 @@
// https://svgwg.org/svg2-draft/coords.html#InterfaceSVGAnimatedPreserveAspectRatio
+[Exposed=Window]
interface SVGAnimatedPreserveAspectRatio {
readonly attribute SVGPreserveAspectRatio baseVal;
readonly attribute SVGPreserveAspectRatio animVal;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_rect.idl b/chromium/third_party/blink/renderer/core/svg/svg_animated_rect.idl
index ebbdc18c520..d464cd00a74 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_rect.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_rect.idl
@@ -25,6 +25,7 @@
// https://svgwg.org/svg2-draft/types.html#InterfaceSVGAnimatedRect
+[Exposed=Window]
interface SVGAnimatedRect {
// TODO(foolip): SVGRect should be DOMRectReadOnly.
readonly attribute SVGRect baseVal;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_string.idl b/chromium/third_party/blink/renderer/core/svg/svg_animated_string.idl
index 5081ecba54a..2b1b8e971de 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_string.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_string.idl
@@ -25,6 +25,7 @@
// https://svgwg.org/svg2-draft/types.html#InterfaceSVGAnimatedString
+[Exposed=Window]
interface SVGAnimatedString {
[RaisesException=Setter] attribute DOMString baseVal;
readonly attribute DOMString animVal;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_animated_transform_list.idl b/chromium/third_party/blink/renderer/core/svg/svg_animated_transform_list.idl
index bd0c2950f27..fa01fa45fb8 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_animated_transform_list.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_animated_transform_list.idl
@@ -25,6 +25,7 @@
// https://svgwg.org/svg2-draft/coords.html#InterfaceSVGAnimatedTransformList
+[Exposed=Window]
interface SVGAnimatedTransformList {
[MeasureAs=SVGAnimatedTransformListBaseVal] readonly attribute SVGTransformList baseVal;
readonly attribute SVGTransformList animVal;
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 6c4c0b34cd7..8b28853e571 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
@@ -25,11 +25,11 @@
#include "third_party/blink/renderer/core/svg/svg_animation_element.h"
#include "third_party/blink/renderer/core/dom/document.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/svg/svg_animate_element.h"
#include "third_party/blink/renderer/core/svg/svg_parser_utilities.h"
#include "third_party/blink/renderer/core/svg_names.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
namespace blink {
@@ -469,10 +469,9 @@ void SVGAnimationElement::CurrentValuesForValuesAnimation(
return;
}
- CalcMode calc_mode = this->GetCalcMode();
- if (IsSVGAnimateElement(*this)) {
- SVGAnimateElement& animate_element = ToSVGAnimateElement(*this);
- if (!animate_element.AnimatedPropertyTypeSupportsAddition())
+ CalcMode calc_mode = GetCalcMode();
+ if (auto* animate_element = DynamicTo<SVGAnimateElement>(this)) {
+ if (!animate_element->AnimatedPropertyTypeSupportsAddition())
calc_mode = kCalcModeDiscrete;
}
if (!key_points_.IsEmpty() && calc_mode != kCalcModePaced)
@@ -527,8 +526,8 @@ void SVGAnimationElement::StartedActiveInterval() {
key_points_.size() != key_times_.size())
return;
- AnimationMode animation_mode = this->GetAnimationMode();
- CalcMode calc_mode = this->GetCalcMode();
+ AnimationMode animation_mode = GetAnimationMode();
+ CalcMode calc_mode = GetCalcMode();
if (calc_mode == kCalcModeSpline) {
unsigned splines_count = key_splines_.size();
if (!splines_count ||
@@ -601,8 +600,8 @@ void SVGAnimationElement::UpdateAnimation(float percent,
return;
float effective_percent;
- CalcMode calc_mode = this->GetCalcMode();
- AnimationMode animation_mode = this->GetAnimationMode();
+ CalcMode calc_mode = GetCalcMode();
+ AnimationMode animation_mode = GetAnimationMode();
if (animation_mode == kValuesAnimation) {
String from;
String to;
@@ -629,4 +628,11 @@ void SVGAnimationElement::UpdateAnimation(float percent,
CalculateAnimatedValue(effective_percent, repeat_count, result_element);
}
+bool SVGAnimationElement::OverwritesUnderlyingAnimationValue() {
+ return !IsAdditive() && !IsAccumulated() &&
+ GetAnimationMode() != kToAnimation &&
+ GetAnimationMode() != kByAnimation &&
+ GetAnimationMode() != kNoAnimation;
+}
+
} // namespace blink
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 3b546c0d8d8..fcfb1791be8 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
@@ -74,6 +74,8 @@ class CORE_EXPORT SVGAnimationElement : public SVGSMILElement {
AnimationMode GetAnimationMode() const { return animation_mode_; }
CalcMode GetCalcMode() const { return calc_mode_; }
+ bool OverwritesUnderlyingAnimationValue() override;
+
template <typename AnimatedType>
void AnimateDiscreteType(float percentage,
const AnimatedType& from_type,
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_circle_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_circle_element.idl
index 76f2a42a6b6..64cfbad9f99 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_circle_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_circle_element.idl
@@ -26,6 +26,7 @@
// https://svgwg.org/svg2-draft/shapes.html#InterfaceSVGCircleElement
+[Exposed=Window]
interface SVGCircleElement : SVGGeometryElement {
[MeasureAs=SVG1DOMShape] readonly attribute SVGAnimatedLength cx;
[MeasureAs=SVG1DOMShape] readonly attribute SVGAnimatedLength cy;
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 9767ed1f9f1..676b342ead2 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
@@ -46,7 +46,7 @@ void SVGClipPathElement::SvgAttributeChanged(const QualifiedName& attr_name) {
SVGElement::InvalidationGuard invalidation_guard(this);
LayoutSVGResourceContainer* layout_object =
- ToLayoutSVGResourceContainer(this->GetLayoutObject());
+ ToLayoutSVGResourceContainer(GetLayoutObject());
if (layout_object)
layout_object->InvalidateCacheAndMarkForLayout();
return;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_defs_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_defs_element.idl
index ba525a6356c..a463b202a00 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_defs_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_defs_element.idl
@@ -25,5 +25,6 @@
// https://svgwg.org/svg2-draft/struct.html#InterfaceSVGDefsElement
+[Exposed=Window]
interface SVGDefsElement : SVGGraphicsElement {
};
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_desc_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_desc_element.idl
index 68ed11d7fad..d11274b5777 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_desc_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_desc_element.idl
@@ -25,5 +25,6 @@
// https://svgwg.org/svg2-draft/struct.html#InterfaceSVGDescElement
+[Exposed=Window]
interface SVGDescElement : SVGElement {
};
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 d5f6cc98b59..a9b70737e19 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,6 +35,8 @@
namespace blink {
SVGDiscardElement::SVGDiscardElement(Document& document)
- : SVGSMILElement(svg_names::kDiscardTag, document) {}
+ : SVGSMILElement(svg_names::kDiscardTag, document) {
+ UseCounter::Count(&GetDocument(), WebFeature::kSVGSMILDiscardElementParsed);
+}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_discard_element.h b/chromium/third_party/blink/renderer/core/svg/svg_discard_element.h
index 7b9d4140bde..8b7b026349b 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_discard_element.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_discard_element.h
@@ -49,6 +49,8 @@ class SVGDiscardElement final : public SVGSMILElement {
void ApplyResultsToTarget() override {}
void AnimationAttributeChanged() override {}
+ bool OverwritesUnderlyingAnimationValue() override { return false; }
+
void StartedActiveInterval() override {}
void UpdateAnimation(float percent,
unsigned repeat,
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 506e181d42c..20546983471 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_element.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_element.cc
@@ -44,7 +44,6 @@
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#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/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/html_element.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
@@ -60,6 +59,7 @@
#include "third_party/blink/renderer/core/svg_names.h"
#include "third_party/blink/renderer/core/xml_names.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/wtf/threading.h"
namespace blink {
@@ -83,8 +83,8 @@ SVGElement::~SVGElement() {
DCHECK(isConnected() || !HasRelativeLengths());
}
-void SVGElement::DetachLayoutTree(const AttachContext& context) {
- Element::DetachLayoutTree(context);
+void SVGElement::DetachLayoutTree(bool performing_reattach) {
+ Element::DetachLayoutTree(performing_reattach);
if (SVGElement* element = CorrespondingElement())
element->RemoveInstanceMapping(this);
// To avoid a noncollectable Blink GC reference cycle, we must clear the
@@ -583,7 +583,7 @@ void SVGElement::InvalidateRelativeLengthClients(
&in_relative_length_clients_invalidation_, true);
#endif
- if (LayoutObject* layout_object = this->GetLayoutObject()) {
+ if (LayoutObject* layout_object = GetLayoutObject()) {
if (HasRelativeLengths() && layout_object->IsSVGResourceContainer()) {
ToLayoutSVGResourceContainer(layout_object)
->InvalidateCacheAndMarkForLayout(
@@ -1328,4 +1328,9 @@ void SVGElement::Trace(blink::Visitor* visitor) {
Element::Trace(visitor);
}
+void SVGElement::AccessKeyAction(bool send_mouse_events) {
+ DispatchSimulatedClick(
+ nullptr, send_mouse_events ? kSendMouseUpDownEvents : kSendNoEvents);
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_element.h b/chromium/third_party/blink/renderer/core/svg/svg_element.h
index 3c5fb74591f..60ed0c4bc73 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_element.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_element.h
@@ -29,7 +29,7 @@
#include "third_party/blink/renderer/core/svg/svg_parsing_error.h"
#include "third_party/blink/renderer/core/svg_names.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/casting.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
@@ -55,7 +55,7 @@ class CORE_EXPORT SVGElement : public Element {
public:
~SVGElement() override;
void AttachLayoutTree(AttachContext&) override;
- void DetachLayoutTree(const AttachContext&) override;
+ void DetachLayoutTree(bool performing_reattach) override;
int tabIndex() const override;
bool SupportsFocus() const override { return false; }
@@ -264,6 +264,8 @@ class CORE_EXPORT SVGElement : public Element {
void RemovedEventListener(const AtomicString& event_type,
const RegisteredEventListener&) final;
+ void AccessKeyAction(bool send_mouse_events) override;
+
private:
bool IsSVGElement() const =
delete; // This will catch anyone doing an unnecessary check.
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_element.idl
index 57a07d3e1a8..9fee3804823 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_element.idl
@@ -22,6 +22,7 @@
// https://svgwg.org/svg2-draft/types.html#InterfaceSVGElement
+[Exposed=Window]
interface SVGElement : Element {
[MeasureAs=SVGClassName] readonly attribute SVGAnimatedString className;
[SameObject, PerWorldBindings] readonly attribute DOMStringMap dataset;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_ellipse_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_ellipse_element.idl
index 546f53292f7..206bf047695 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_ellipse_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_ellipse_element.idl
@@ -25,6 +25,7 @@
// https://svgwg.org/svg2-draft/shapes.html#InterfaceSVGEllipseElement
+[Exposed=Window]
interface SVGEllipseElement : SVGGeometryElement {
[MeasureAs=SVG1DOMShape] readonly attribute SVGAnimatedLength cx;
[MeasureAs=SVG1DOMShape] readonly attribute SVGAnimatedLength cy;
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 1256a0e23fc..9069c8b1ede 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
@@ -45,7 +45,9 @@ SVGFEImageElement::SVGFEImageElement(Document& document)
AddToPropertyMap(preserve_aspect_ratio_);
}
-SVGFEImageElement::~SVGFEImageElement() {
+SVGFEImageElement::~SVGFEImageElement() = default;
+
+void SVGFEImageElement::Dispose() {
ClearImageResource();
}
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 af5dcd70c64..a29911334a1 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
@@ -36,6 +36,8 @@ class SVGFEImageElement final : public SVGFilterPrimitiveStandardAttributes,
public ImageResourceObserver {
DEFINE_WRAPPERTYPEINFO();
USING_GARBAGE_COLLECTED_MIXIN(SVGFEImageElement);
+ // Pre-finalize to promptly remove as a ImageResource client.
+ USING_PRE_FINALIZER(SVGFEImageElement, Dispose);
public:
bool CurrentFrameHasSingleSecurityOrigin() const;
@@ -46,8 +48,12 @@ class SVGFEImageElement final : public SVGFilterPrimitiveStandardAttributes,
return preserve_aspect_ratio_.Get();
}
- // Promptly remove as a ImageResource client.
- EAGERLY_FINALIZE();
+ const AttrNameToTrustedType& GetCheckedAttributeTypes() const override {
+ return SVGURIReference::GetCheckedAttributeTypes();
+ }
+
+ void Dispose();
+
void Trace(blink::Visitor*) override;
private:
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_filter_element.h b/chromium/third_party/blink/renderer/core/svg/svg_filter_element.h
index 02c1c251f3d..46c123b0970 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_filter_element.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_filter_element.h
@@ -68,6 +68,10 @@ class CORE_EXPORT SVGFilterElement final : public SVGElement,
// Get the associated SVGResource object, if any.
LocalSVGResource* AssociatedResource() const;
+ const AttrNameToTrustedType& GetCheckedAttributeTypes() const override {
+ return SVGURIReference::GetCheckedAttributeTypes();
+ }
+
private:
void SvgAttributeChanged(const QualifiedName&) override;
void ChildrenChanged(const ChildrenChange&) override;
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 a0c122aa35a..9edbeaa78f2 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
@@ -190,12 +190,11 @@ void SVGFilterPrimitiveStandardAttributes::PrimitiveAttributeChanged(
}
void InvalidateFilterPrimitiveParent(SVGElement& element) {
- auto* svg_parent = DynamicTo<SVGElement>(element.parentElement());
+ auto* svg_parent =
+ DynamicTo<SVGFilterPrimitiveStandardAttributes>(element.parentElement());
if (!svg_parent)
return;
- if (!IsSVGFilterPrimitiveStandardAttributes(*svg_parent))
- return;
- ToSVGFilterPrimitiveStandardAttributes(*svg_parent).Invalidate();
+ svg_parent->Invalidate();
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_filter_primitive_standard_attributes.h b/chromium/third_party/blink/renderer/core/svg/svg_filter_primitive_standard_attributes.h
index 2aed48ffdc3..b0271c5fe3b 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_filter_primitive_standard_attributes.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_filter_primitive_standard_attributes.h
@@ -85,8 +85,13 @@ inline bool IsSVGFilterPrimitiveStandardAttributes(const SVGElement& element) {
return element.IsFilterEffect();
}
-DEFINE_SVGELEMENT_TYPE_CASTS_WITH_FUNCTION(
- SVGFilterPrimitiveStandardAttributes);
+template <>
+struct DowncastTraits<SVGFilterPrimitiveStandardAttributes> {
+ static bool AllowFrom(const Node& node) {
+ auto* element = DynamicTo<SVGElement>(node);
+ return element && IsSVGFilterPrimitiveStandardAttributes(*element);
+ }
+};
} // 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 a440a448328..a912b47f3d6 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
@@ -21,10 +21,10 @@
#include "third_party/blink/renderer/core/svg/svg_foreign_object_element.h"
#include "third_party/blink/renderer/core/css/style_change_reason.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/layout/svg/layout_svg_foreign_object.h"
#include "third_party/blink/renderer/core/svg/svg_length.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_foreign_object_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_foreign_object_element.idl
index 03f3aff6801..1d2fa831adc 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_foreign_object_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_foreign_object_element.idl
@@ -25,6 +25,7 @@
// https://svgwg.org/svg2-draft/embedded.html#InterfaceSVGForeignObjectElement
+[Exposed=Window]
interface SVGForeignObjectElement : SVGGraphicsElement {
[MeasureAs=SVG1DOMForeignObjectElement] readonly attribute SVGAnimatedLength x;
[MeasureAs=SVG1DOMForeignObjectElement] readonly attribute SVGAnimatedLength y;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_g_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_g_element.idl
index cf7d964b5e1..6cec8b55b07 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_g_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_g_element.idl
@@ -25,5 +25,6 @@
// https://svgwg.org/svg2-draft/struct.html#InterfaceSVGGElement
+[Exposed=Window]
interface SVGGElement : SVGGraphicsElement {
};
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_geometry_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_geometry_element.idl
index 8145d5c79fa..f447ef3b81f 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_geometry_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_geometry_element.idl
@@ -30,6 +30,7 @@
// https://svgwg.org/svg2-draft/types.html#InterfaceSVGGeometryElement
+[Exposed=Window]
interface SVGGeometryElement : SVGGraphicsElement {
[SameObject] readonly attribute SVGAnimatedNumber pathLength;
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 3b684b46ec8..c05a4394725 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
@@ -81,7 +81,7 @@ void SVGGradientElement::BuildPendingResource() {
if (!isConnected())
return;
Element* target = ObserveTarget(target_id_observer_, *this);
- if (auto* gradient = ToSVGGradientElementOrNull(target))
+ if (auto* gradient = DynamicTo<SVGGradientElement>(target))
AddReferenceTo(gradient);
InvalidateGradient(layout_invalidation_reason::kSvgResourceInvalidated);
@@ -160,7 +160,7 @@ void SVGGradientElement::InvalidateGradient(
void SVGGradientElement::InvalidateDependentGradients() {
NotifyIncomingReferences([](SVGElement& element) {
- if (auto* gradient = ToSVGGradientElementOrNull(element)) {
+ if (auto* gradient = DynamicTo<SVGGradientElement>(element)) {
gradient->InvalidateGradient(
layout_invalidation_reason::kSvgResourceInvalidated);
}
@@ -190,7 +190,7 @@ void SVGGradientElement::CollectCommonAttributes(
const SVGGradientElement* SVGGradientElement::ReferencedElement() const {
// Respect xlink:href, take attributes from referenced element.
- return ToSVGGradientElementOrNull(
+ return DynamicTo<SVGGradientElement>(
TargetElementFromIRIString(HrefString(), GetTreeScope()));
}
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 0376e5dfd46..ba5f6eea191 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
@@ -64,6 +64,10 @@ class SVGGradientElement : public SVGElement, public SVGURIReference {
const SVGGradientElement* ReferencedElement() const;
void CollectCommonAttributes(GradientAttributes&) const;
+ const AttrNameToTrustedType& GetCheckedAttributeTypes() const override {
+ return SVGURIReference::GetCheckedAttributeTypes();
+ }
+
void Trace(blink::Visitor*) override;
protected:
@@ -99,7 +103,13 @@ inline bool IsSVGGradientElement(const SVGElement& element) {
element.HasTagName(svg_names::kLinearGradientTag);
}
-DEFINE_SVGELEMENT_TYPE_CASTS_WITH_FUNCTION(SVGGradientElement);
+template <>
+struct DowncastTraits<SVGGradientElement> {
+ static bool AllowFrom(const Node& node) {
+ auto* svg_element = DynamicTo<SVGElement>(node);
+ return svg_element && IsSVGGradientElement(*svg_element);
+ }
+};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_gradient_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_gradient_element.idl
index 5fb065d6a11..e8fe8dad1f2 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_gradient_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_gradient_element.idl
@@ -26,6 +26,7 @@
// https://svgwg.org/svg2-draft/pservers.html#InterfaceSVGGradientElement
[
+ Exposed=Window,
DoNotCheckConstants
] interface SVGGradientElement : SVGElement {
// Spread Method Types
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_graphics_element.h b/chromium/third_party/blink/renderer/core/svg/svg_graphics_element.h
index fd03167ee26..2b602085711 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_graphics_element.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_graphics_element.h
@@ -91,6 +91,14 @@ inline bool IsSVGGraphicsElement(const SVGElement& element) {
return element.IsSVGGraphicsElement();
}
+template <>
+struct DowncastTraits<SVGGraphicsElement> {
+ static bool AllowFrom(const Node& node) {
+ auto* svg_element = DynamicTo<SVGElement>(node);
+ return svg_element && IsSVGGraphicsElement(*svg_element);
+ }
+};
+
DEFINE_SVGELEMENT_TYPE_CASTS_WITH_FUNCTION(SVGGraphicsElement);
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_graphics_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_graphics_element.idl
index 5f9b1d6e6e4..da35d78a36d 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_graphics_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_graphics_element.idl
@@ -30,6 +30,7 @@
// https://svgwg.org/svg2-draft/types.html#InterfaceSVGGraphicsElement
+[Exposed=Window]
interface SVGGraphicsElement : SVGElement {
[Measure] readonly attribute SVGAnimatedTransformList transform;
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 da3cb08045e..008ea04bb38 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
@@ -24,7 +24,6 @@
#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/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"
#include "third_party/blink/renderer/core/layout/layout_image_resource.h"
@@ -32,6 +31,7 @@
#include "third_party/blink/renderer/core/layout/svg/layout_svg_image.h"
#include "third_party/blink/renderer/core/svg_names.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
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 7c7c3ee084d..b5e3a360b4a 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
@@ -78,6 +78,10 @@ class CORE_EXPORT SVGImageElement final
GetImageLoader().SetImageForTest(content);
}
+ const AttrNameToTrustedType& GetCheckedAttributeTypes() const override {
+ return SVGURIReference::GetCheckedAttributeTypes();
+ }
+
private:
bool IsStructurallyExternal() const override {
return !HrefString().IsNull();
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 6271a18c695..a7e66c3baf5 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_length.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_length.cc
@@ -21,6 +21,8 @@
#include "third_party/blink/renderer/core/svg/svg_length.h"
+#include "third_party/blink/renderer/core/css/css_math_function_value.h"
+#include "third_party/blink/renderer/core/css/css_numeric_literal_value.h"
#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.h"
@@ -63,17 +65,17 @@ const CSSPrimitiveValue& CreateInitialCSSValue(
size_t initial_value_index = static_cast<size_t>(initial_value);
DCHECK_LT(initial_value_index, base::size(g_initial_lengths_table));
const auto& entry = g_initial_lengths_table[initial_value_index];
- return *CSSPrimitiveValue::Create(
+ return *CSSNumericLiteralValue::Create(
entry.value, static_cast<CSSPrimitiveValue::UnitType>(entry.unit));
}
} // namespace
SVGLength::SVGLength(SVGLengthMode mode)
- : SVGLength(
- *CSSPrimitiveValue::Create(0,
- CSSPrimitiveValue::UnitType::kUserUnits),
- mode) {}
+ : SVGLength(*CSSNumericLiteralValue::Create(
+ 0,
+ CSSPrimitiveValue::UnitType::kUserUnits),
+ mode) {}
SVGLength::SVGLength(Initial initial, SVGLengthMode mode)
: SVGLength(CreateInitialCSSValue(initial), mode) {}
@@ -99,9 +101,10 @@ SVGPropertyBase* SVGLength::CloneForAnimation(const String& value) const {
auto* length = MakeGarbageCollected<SVGLength>();
length->unit_mode_ = unit_mode_;
- if (length->SetValueAsString(value) != SVGParseStatus::kNoError)
- length->value_ =
- CSSPrimitiveValue::Create(0, CSSPrimitiveValue::UnitType::kUserUnits);
+ if (length->SetValueAsString(value) != SVGParseStatus::kNoError) {
+ length->value_ = CSSNumericLiteralValue::Create(
+ 0, CSSPrimitiveValue::UnitType::kUserUnits);
+ }
return length;
}
@@ -115,38 +118,66 @@ float SVGLength::Value(const SVGLengthContext& context) const {
return context.ResolveValue(AsCSSPrimitiveValue(), UnitMode());
return context.ConvertValueToUserUnits(value_->GetFloatValue(), UnitMode(),
- value_->TypeWithCalcResolved());
+ NumericLiteralType());
}
void SVGLength::SetValueAsNumber(float value) {
- value_ =
- CSSPrimitiveValue::Create(value, CSSPrimitiveValue::UnitType::kUserUnits);
+ value_ = CSSNumericLiteralValue::Create(
+ value, CSSPrimitiveValue::UnitType::kUserUnits);
}
void SVGLength::SetValue(float value, const SVGLengthContext& context) {
- value_ = CSSPrimitiveValue::Create(
+ // |value| is in user units.
+ if (IsCalculated()) {
+ value_ = CSSNumericLiteralValue::Create(
+ value, CSSPrimitiveValue::UnitType::kUserUnits);
+ return;
+ }
+ value_ = CSSNumericLiteralValue::Create(
context.ConvertValueFromUserUnits(value, UnitMode(),
- value_->TypeWithCalcResolved()),
- value_->TypeWithCalcResolved());
+ NumericLiteralType()),
+ NumericLiteralType());
+}
+
+void SVGLength::SetValueInSpecifiedUnits(float value) {
+ DCHECK(!IsCalculated());
+ value_ = CSSNumericLiteralValue::Create(value, NumericLiteralType());
}
-static bool IsCalcCSSUnitType(CSSPrimitiveValue::UnitType type) {
- return type >= CSSPrimitiveValue::UnitType::kCalc &&
- type <=
- CSSPrimitiveValue::UnitType::kCalcPercentageWithLengthAndNumber;
+bool SVGLength::IsRelative() const {
+ if (IsPercentage())
+ return true;
+ // TODO(crbug.com/979895): This is the result of a refactoring, which might
+ // have revealed an existing bug with relative units in math functions.
+ return !IsCalculated() &&
+ CSSPrimitiveValue::IsRelativeUnit(NumericLiteralType());
}
static bool IsSupportedCSSUnitType(CSSPrimitiveValue::UnitType type) {
return (CSSPrimitiveValue::IsLength(type) ||
type == CSSPrimitiveValue::UnitType::kNumber ||
- type == CSSPrimitiveValue::UnitType::kPercentage ||
- IsCalcCSSUnitType(type)) &&
+ type == CSSPrimitiveValue::UnitType::kPercentage) &&
type != CSSPrimitiveValue::UnitType::kQuirkyEms;
}
+static bool IsSupportedCalculationCategory(CalculationCategory category) {
+ switch (category) {
+ case kCalcLength:
+ case kCalcNumber:
+ case kCalcPercent:
+ case kCalcPercentNumber:
+ case kCalcPercentLength:
+ case kCalcLengthNumber:
+ case kCalcPercentLengthNumber:
+ return true;
+ default:
+ return false;
+ }
+}
+
void SVGLength::SetUnitType(CSSPrimitiveValue::UnitType type) {
DCHECK(IsSupportedCSSUnitType(type));
- value_ = CSSPrimitiveValue::Create(value_->GetFloatValue(), type);
+ value_ = CSSNumericLiteralValue::Create(value_->GetFloatValue(), type);
}
float SVGLength::ValueAsPercentage() const {
@@ -179,29 +210,45 @@ float SVGLength::ScaleByPercentage(float input) const {
return result;
}
+namespace {
+
+const CSSParserContext* GetSVGAttributeParserContext() {
+ // NOTE(ikilpatrick): We will always parse SVG lengths in the insecure
+ // context mode. If a function/unit/etc will require a secure context check
+ // in the future, plumbing will need to be added.
+ DEFINE_STATIC_LOCAL(
+ const Persistent<CSSParserContext>, svg_parser_context,
+ (MakeGarbageCollected<CSSParserContext>(
+ kSVGAttributeMode, SecureContextMode::kInsecureContext)));
+ return svg_parser_context;
+}
+
+} // namespace
+
SVGParsingError SVGLength::SetValueAsString(const String& string) {
// TODO(fs): Preferably we wouldn't need to special-case the null
// string (which we'll get for example for removeAttribute.)
// Hopefully work on crbug.com/225807 can help here.
if (string.IsNull()) {
- value_ =
- CSSPrimitiveValue::Create(0, CSSPrimitiveValue::UnitType::kUserUnits);
+ value_ = CSSNumericLiteralValue::Create(
+ 0, CSSPrimitiveValue::UnitType::kUserUnits);
return SVGParseStatus::kNoError;
}
- // NOTE(ikilpatrick): We will always parse svg lengths in the insecure
- // context mode. If a function/unit/etc will require a secure context check
- // in the future, plumbing will need to be added.
- auto* svg_parser_context = MakeGarbageCollected<CSSParserContext>(
- kSVGAttributeMode, SecureContextMode::kInsecureContext);
const CSSValue* parsed = CSSParser::ParseSingleValue(
- CSSPropertyID::kX, string, svg_parser_context);
+ CSSPropertyID::kX, string, GetSVGAttributeParserContext());
const auto* new_value = DynamicTo<CSSPrimitiveValue>(parsed);
if (!new_value)
return SVGParseStatus::kExpectedLength;
- if (!IsSupportedCSSUnitType(new_value->TypeWithCalcResolved()))
- return SVGParseStatus::kExpectedLength;
+ if (const auto* math_value = DynamicTo<CSSMathFunctionValue>(new_value)) {
+ if (!IsSupportedCalculationCategory(math_value->Category()))
+ return SVGParseStatus::kExpectedLength;
+ } else {
+ const auto* numeric_literal_value = To<CSSNumericLiteralValue>(new_value);
+ if (!IsSupportedCSSUnitType(numeric_literal_value->GetType()))
+ return SVGParseStatus::kExpectedLength;
+ }
value_ = new_value;
return SVGParseStatus::kNoError;
@@ -213,7 +260,7 @@ String SVGLength::ValueAsString() const {
void SVGLength::NewValueSpecifiedUnits(CSSPrimitiveValue::UnitType type,
float value) {
- value_ = CSSPrimitiveValue::Create(value, type);
+ value_ = CSSNumericLiteralValue::Create(value, type);
}
void SVGLength::ConvertToSpecifiedUnits(CSSPrimitiveValue::UnitType type,
@@ -221,7 +268,7 @@ void SVGLength::ConvertToSpecifiedUnits(CSSPrimitiveValue::UnitType type,
DCHECK(IsSupportedCSSUnitType(type));
float value_in_user_units = Value(context);
- value_ = CSSPrimitiveValue::Create(
+ value_ = CSSNumericLiteralValue::Create(
context.ConvertValueFromUserUnits(value_in_user_units, UnitMode(), type),
type);
}
@@ -311,15 +358,17 @@ void SVGLength::CalculateAnimatedValue(
CSSPrimitiveValue::UnitType new_unit =
CSSPrimitiveValue::UnitType::kUserUnits;
if (percentage < 0.5) {
- if (!from_length->IsCalculated())
- new_unit = from_length->TypeWithCalcResolved();
+ if (!from_length->IsCalculated()) {
+ new_unit = from_length->NumericLiteralType();
+ }
} else {
- if (!to_length->IsCalculated())
- new_unit = to_length->TypeWithCalcResolved();
+ if (!to_length->IsCalculated()) {
+ new_unit = to_length->NumericLiteralType();
+ }
}
animated_number = length_context.ConvertValueFromUserUnits(
animated_number, UnitMode(), new_unit);
- value_ = CSSPrimitiveValue::Create(animated_number, new_unit);
+ value_ = CSSNumericLiteralValue::Create(animated_number, new_unit);
}
float SVGLength::CalculateDistance(SVGPropertyBase* to_value,
@@ -334,4 +383,10 @@ void SVGLength::SetInitial(unsigned initial_value) {
value_ = CreateInitialCSSValue(static_cast<Initial>(initial_value));
}
+bool SVGLength::IsNegativeNumericLiteral() const {
+ if (!value_->IsNumericLiteralValue())
+ return false;
+ return value_->GetDoubleValue() < 0;
+}
+
} // namespace blink
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 5e59803833d..b95a5fd0720 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_length.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_length.h
@@ -21,6 +21,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_SVG_SVG_LENGTH_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_SVG_SVG_LENGTH_H_
+#include "third_party/blink/renderer/core/css/css_numeric_literal_value.h"
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
#include "third_party/blink/renderer/core/svg/properties/svg_property.h"
#include "third_party/blink/renderer/core/svg/svg_length_context.h"
@@ -64,9 +65,11 @@ class SVGLength final : public SVGPropertyBase {
SVGLength* Clone() const;
SVGPropertyBase* CloneForAnimation(const String&) const override;
- CSSPrimitiveValue::UnitType TypeWithCalcResolved() const {
- return value_->TypeWithCalcResolved();
+ CSSPrimitiveValue::UnitType NumericLiteralType() const {
+ DCHECK(value_->IsNumericLiteralValue());
+ return To<CSSNumericLiteralValue>(*value_).GetType();
}
+
void SetUnitType(CSSPrimitiveValue::UnitType);
SVGLengthMode UnitMode() const {
return static_cast<SVGLengthMode>(unit_mode_);
@@ -80,9 +83,7 @@ class SVGLength final : public SVGPropertyBase {
void SetValueAsNumber(float);
float ValueInSpecifiedUnits() const { return value_->GetFloatValue(); }
- void SetValueInSpecifiedUnits(float value) {
- value_ = CSSPrimitiveValue::Create(value, value_->TypeWithCalcResolved());
- }
+ void SetValueInSpecifiedUnits(float value);
const CSSPrimitiveValue& AsCSSPrimitiveValue() const { return *value_; }
@@ -106,12 +107,12 @@ class SVGLength final : public SVGPropertyBase {
const SVGLengthContext&);
// Helper functions
- bool IsRelative() const {
- return CSSPrimitiveValue::IsRelativeUnit(value_->TypeWithCalcResolved());
- }
+ bool IsRelative() const;
bool IsFontRelative() const { return value_->IsFontRelativeLength(); }
bool IsCalculated() const { return value_->IsCalculated(); }
+ bool IsPercentage() const { return value_->IsPercentage(); }
+ bool IsNegativeNumericLiteral() const;
bool IsZero() const { return value_->GetFloatValue() == 0; }
static SVGLengthMode LengthModeForAnimatedLengthAttribute(
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_length.idl b/chromium/third_party/blink/renderer/core/svg/svg_length.idl
index 4a90ae6e2d0..62f619eb66b 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_length.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_length.idl
@@ -23,6 +23,7 @@
// https://svgwg.org/svg2-draft/types.html#InterfaceSVGLength
[
+ Exposed=Window,
ImplementedAs=SVGLengthTearOff
] interface SVGLength {
// Length Unit Types
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_length_list.cc b/chromium/third_party/blink/renderer/core/svg/svg_length_list.cc
index 2579e0fde51..9ed70d9c3a5 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_length_list.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_length_list.cc
@@ -135,12 +135,11 @@ void SVGLengthList::CalculateAnimatedValue(
for (uint32_t i = 0; i < to_length_list_size; ++i) {
// TODO(shanmuga.m): Support calc for SVGLengthList animation
float animated_number = at(i)->Value(length_context);
- CSSPrimitiveValue::UnitType unit_type =
- to_list->at(i)->TypeWithCalcResolved();
+ const SVGLength* length_for_unit_type = to_list->at(i);
float effective_from = 0;
if (from_length_list_size) {
if (percentage < 0.5)
- unit_type = from_list->at(i)->TypeWithCalcResolved();
+ length_for_unit_type = from_list->at(i);
effective_from = from_list->at(i)->Value(length_context);
}
float effective_to = to_list->at(i)->Value(length_context);
@@ -152,6 +151,11 @@ void SVGLengthList::CalculateAnimatedValue(
animation_element->AnimateAdditiveNumber(
percentage, repeat_count, effective_from, effective_to,
effective_to_at_end, animated_number);
+ // |animated_number| is in user units.
+ CSSPrimitiveValue::UnitType unit_type =
+ length_for_unit_type->IsCalculated()
+ ? CSSPrimitiveValue::UnitType::kUserUnits
+ : length_for_unit_type->NumericLiteralType();
at(i)->SetUnitType(unit_type);
at(i)->SetValue(animated_number, length_context);
}
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_length_list.idl b/chromium/third_party/blink/renderer/core/svg/svg_length_list.idl
index b71c499c38b..a235675382b 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_length_list.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_length_list.idl
@@ -27,6 +27,7 @@
// https://svgwg.org/svg2-draft/types.html#InterfaceSVGLengthList
[
+ Exposed=Window,
ImplementedAs=SVGLengthListTearOff
] interface SVGLengthList {
readonly attribute unsigned long length;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_length_tear_off.cc b/chromium/third_party/blink/renderer/core/svg/svg_length_tear_off.cc
index 749de14193f..be80a2d5b9d 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_length_tear_off.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_length_tear_off.cc
@@ -101,7 +101,7 @@ bool SVGLengthTearOff::HasExposedLengthUnit() {
if (Target()->IsCalculated())
return false;
- CSSPrimitiveValue::UnitType unit = Target()->TypeWithCalcResolved();
+ CSSPrimitiveValue::UnitType unit = Target()->NumericLiteralType();
return IsValidLengthUnit(unit) ||
unit == CSSPrimitiveValue::UnitType::kUnknown ||
unit == CSSPrimitiveValue::UnitType::kUserUnits;
@@ -109,7 +109,7 @@ bool SVGLengthTearOff::HasExposedLengthUnit() {
uint16_t SVGLengthTearOff::unitType() {
return HasExposedLengthUnit()
- ? ToInterfaceConstant(Target()->TypeWithCalcResolved())
+ ? ToInterfaceConstant(Target()->NumericLiteralType())
: kSvgLengthtypeUnknown;
}
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_line_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_line_element.idl
index 24856081f44..60927a53541 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_line_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_line_element.idl
@@ -25,6 +25,7 @@
// https://svgwg.org/svg2-draft/shapes.html#InterfaceSVGLineElement
+[Exposed=Window]
interface SVGLineElement : SVGGeometryElement {
[MeasureAs=SVG1DOMShape] readonly attribute SVGAnimatedLength x1;
[MeasureAs=SVG1DOMShape] readonly attribute SVGAnimatedLength y1;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_linear_gradient_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_linear_gradient_element.idl
index 64c8656b6da..02a6d078cda 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_linear_gradient_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_linear_gradient_element.idl
@@ -25,6 +25,7 @@
// https://svgwg.org/svg2-draft/pservers.html#InterfaceSVGLinearGradientElement
+[Exposed=Window]
interface SVGLinearGradientElement : SVGGradientElement {
[MeasureAs=SVG1DOMPaintServer] readonly attribute SVGAnimatedLength x1;
[MeasureAs=SVG1DOMPaintServer] readonly attribute SVGAnimatedLength y1;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_marker_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_marker_element.idl
index edd8c75ab28..c75fd2ffd3d 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_marker_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_marker_element.idl
@@ -25,6 +25,7 @@
// https://svgwg.org/svg2-draft/painting.html#InterfaceSVGMarkerElement
+[Exposed=Window]
interface SVGMarkerElement : SVGElement {
// Marker Unit Types
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 827e47966d9..e194b0fe21f 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
@@ -130,7 +130,7 @@ void SVGMaskElement::SvgAttributeChanged(const QualifiedName& attr_name) {
}
LayoutSVGResourceContainer* layout_object =
- ToLayoutSVGResourceContainer(this->GetLayoutObject());
+ ToLayoutSVGResourceContainer(GetLayoutObject());
if (layout_object)
layout_object->InvalidateCacheAndMarkForLayout();
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_metadata_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_metadata_element.idl
index 9c557f1fa12..e55d8a167b2 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_metadata_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_metadata_element.idl
@@ -21,5 +21,6 @@
// https://svgwg.org/svg2-draft/struct.html#InterfaceSVGMetadataElement
+[Exposed=Window]
interface SVGMetadataElement : SVGElement {
};
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_mpath_element.h b/chromium/third_party/blink/renderer/core/svg/svg_mpath_element.h
index ee6fa88384b..59e28717381 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_mpath_element.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_mpath_element.h
@@ -39,6 +39,10 @@ class SVGMPathElement final : public SVGElement, public SVGURIReference {
void TargetPathChanged();
+ const AttrNameToTrustedType& GetCheckedAttributeTypes() const override {
+ return SVGURIReference::GetCheckedAttributeTypes();
+ }
+
void Trace(blink::Visitor*) override;
private:
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_number.idl b/chromium/third_party/blink/renderer/core/svg/svg_number.idl
index b8be001920c..34fb0bde275 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_number.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_number.idl
@@ -23,6 +23,7 @@
// https://svgwg.org/svg2-draft/types.html#InterfaceSVGNumber
[
+ Exposed=Window,
ImplementedAs=SVGNumberTearOff
] interface SVGNumber {
[RaisesException=Setter] attribute float value;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_number_list.idl b/chromium/third_party/blink/renderer/core/svg/svg_number_list.idl
index 1b26f22a8a3..10c86ae8eb6 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_number_list.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_number_list.idl
@@ -27,6 +27,7 @@
// https://svgwg.org/svg2-draft/types.html#InterfaceSVGNumberList
[
+ Exposed=Window,
ImplementedAs=SVGNumberListTearOff
] interface SVGNumberList {
readonly attribute unsigned long length;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_parsing_error.h b/chromium/third_party/blink/renderer/core/svg/svg_parsing_error.h
index 03affa67a76..5ddcde59d00 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_parsing_error.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_parsing_error.h
@@ -68,7 +68,7 @@ class SVGParsingError {
SVGParsingError(SVGParseStatus status = SVGParseStatus::kNoError,
size_t locus = 0)
: status_(static_cast<unsigned>(status)), locus_(CheckLocus(locus)) {
- DCHECK_EQ(this->Status(), status);
+ DCHECK_EQ(Status(), status);
}
SVGParseStatus Status() const { return static_cast<SVGParseStatus>(status_); }
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_path_blender.cc b/chromium/third_party/blink/renderer/core/svg/svg_path_blender.cc
index 3fd84ceb6f8..feeb3608ae4 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_path_blender.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_path_blender.cc
@@ -23,7 +23,7 @@
#include "third_party/blink/renderer/core/svg/svg_path_consumer.h"
#include "third_party/blink/renderer/core/svg/svg_path_data.h"
#include "third_party/blink/renderer/platform/animation/animation_utilities.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_path_data.h b/chromium/third_party/blink/renderer/core/svg/svg_path_data.h
index 9e4f84abaaf..c58d9fd1610 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_path_data.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_path_data.h
@@ -22,7 +22,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_SVG_SVG_PATH_DATA_H_
#include "third_party/blink/renderer/platform/geometry/float_point.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 cb1383fe0fe..c4f1cdf877e 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
@@ -47,7 +47,7 @@ Path SVGPathElement::AttributePath() const {
}
const StylePath* SVGPathElement::GetStylePath() const {
- if (LayoutObject* layout_object = this->GetLayoutObject()) {
+ if (LayoutObject* layout_object = GetLayoutObject()) {
const StylePath* style_path = layout_object->StyleRef().SvgStyle().D();
if (style_path)
return style_path;
@@ -99,7 +99,7 @@ void SVGPathElement::CollectStyleForPresentationAttribute(
MutableCSSPropertyValueSet* style) {
SVGAnimatedPropertyBase* property = PropertyFromAttribute(name);
if (property == path_) {
- SVGAnimatedPath* path = this->GetPath();
+ SVGAnimatedPath* path = GetPath();
// If this is a <use> instance, return the referenced path to maximize
// geometry sharing.
if (const SVGElement* element = CorrespondingElement())
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_path_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_path_element.idl
index 748f41834c8..2a4f0f75023 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_path_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_path_element.idl
@@ -26,5 +26,6 @@
// https://svgwg.org/svg2-draft/paths.html#InterfaceSVGPathElement
+[Exposed=Window]
interface SVGPathElement : SVGGeometryElement {
};
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_path_query.h b/chromium/third_party/blink/renderer/core/svg/svg_path_query.h
index c4b57386f23..5cb68be5d57 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_path_query.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_path_query.h
@@ -21,7 +21,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_SVG_SVG_PATH_QUERY_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_SVG_SVG_PATH_QUERY_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_pattern_element.h b/chromium/third_party/blink/renderer/core/svg/svg_pattern_element.h
index 45b7af10525..1a4e2cbf138 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_pattern_element.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_pattern_element.h
@@ -80,6 +80,10 @@ class SVGPatternElement final : public SVGElement,
const SVGPatternElement* ReferencedElement() const;
+ const AttrNameToTrustedType& GetCheckedAttributeTypes() const override {
+ return SVGURIReference::GetCheckedAttributeTypes();
+ }
+
void Trace(blink::Visitor*) override;
private:
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_pattern_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_pattern_element.idl
index 121f9b0a72a..49098b490a5 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_pattern_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_pattern_element.idl
@@ -25,6 +25,7 @@
// https://svgwg.org/svg2-draft/pservers.html#InterfaceSVGPatternElement
+[Exposed=Window]
interface SVGPatternElement : SVGElement {
[MeasureAs=SVG1DOMPaintServer] readonly attribute SVGAnimatedEnumeration patternUnits;
[MeasureAs=SVG1DOMPaintServer] readonly attribute SVGAnimatedEnumeration patternContentUnits;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_point_list.idl b/chromium/third_party/blink/renderer/core/svg/svg_point_list.idl
index 060c6c08840..fd5aaa7161f 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_point_list.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_point_list.idl
@@ -26,6 +26,7 @@
// https://svgwg.org/svg2-draft/shapes.html#InterfaceSVGPointList
[
+ Exposed=Window,
ImplementedAs=SVGPointListTearOff
] interface SVGPointList {
readonly attribute unsigned long length;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_polygon_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_polygon_element.idl
index 02bf320cfc6..ab5e762f0cf 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_polygon_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_polygon_element.idl
@@ -25,6 +25,7 @@
// https://svgwg.org/svg2-draft/shapes.html#InterfaceSVGPolygonElement
+[Exposed=Window]
interface SVGPolygonElement : SVGGeometryElement {
// TODO(foolip): points and animatedPoints be on the SVGAnimatedPoints
// interface which SVGPolygonElement should implement:
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_polyline_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_polyline_element.idl
index 2bb45187bd5..8539eaddde6 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_polyline_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_polyline_element.idl
@@ -25,6 +25,7 @@
// https://svgwg.org/svg2-draft/shapes.html#InterfaceSVGPolylineElement
+[Exposed=Window]
interface SVGPolylineElement : SVGGeometryElement {
// TODO(foolip): points and animatedPoints should be on the
// SVGAnimatedPoints interface which SVGPolylineElement should implement:
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_preserve_aspect_ratio.idl b/chromium/third_party/blink/renderer/core/svg/svg_preserve_aspect_ratio.idl
index 6ff75fb2dfc..1b730f7d0d5 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_preserve_aspect_ratio.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_preserve_aspect_ratio.idl
@@ -26,6 +26,7 @@
// https://svgwg.org/svg2-draft/coords.html#InterfaceSVGPreserveAspectRatio
[
+ Exposed=Window,
ImplementedAs=SVGPreserveAspectRatioTearOff
] interface SVGPreserveAspectRatio {
// Alignment types
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_radial_gradient_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_radial_gradient_element.idl
index a128bf5851a..3330290c604 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_radial_gradient_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_radial_gradient_element.idl
@@ -25,6 +25,7 @@
// https://svgwg.org/svg2-draft/pservers.html#InterfaceSVGRadialGradientElement
+[Exposed=Window]
interface SVGRadialGradientElement : SVGGradientElement {
[MeasureAs=SVG1DOMPaintServer] readonly attribute SVGAnimatedLength cx;
[MeasureAs=SVG1DOMPaintServer] readonly attribute SVGAnimatedLength cy;
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 9f32545d709..e579b2745a9 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_rect.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_rect.h
@@ -23,7 +23,7 @@
#include "third_party/blink/renderer/core/svg/properties/svg_property_helper.h"
#include "third_party/blink/renderer/core/svg/svg_parsing_error.h"
#include "third_party/blink/renderer/platform/geometry/float_rect.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_rect_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_rect_element.idl
index bde3c4bedf9..dabf27d429a 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_rect_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_rect_element.idl
@@ -26,6 +26,7 @@
// https://svgwg.org/svg2-draft/shapes.html#InterfaceSVGRectElement
+[Exposed=Window]
interface SVGRectElement : SVGGeometryElement {
[MeasureAs=SVG1DOMShape] readonly attribute SVGAnimatedLength x;
[MeasureAs=SVG1DOMShape] readonly attribute SVGAnimatedLength y;
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 d767e45b99c..9421f732db6 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_resource.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_resource.cc
@@ -128,8 +128,8 @@ void ExternalSVGResource::Load(const Document& document) {
ResourceLoaderOptions options;
options.initiator_info.name = fetch_initiator_type_names::kCSS;
FetchParameters params(ResourceRequest(url_), options);
- params.MutableResourceRequest().SetFetchRequestMode(
- network::mojom::FetchRequestMode::kSameOrigin);
+ params.MutableResourceRequest().SetMode(
+ network::mojom::RequestMode::kSameOrigin);
resource_document_ =
DocumentResource::FetchSVGDocument(params, document.Fetcher(), this);
target_ = ResolveTarget();
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 5d3ac5435b2..0147e9dfdef 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
@@ -173,6 +173,16 @@ bool SVGScriptElement::IsAnimatableAttribute(const QualifiedName& name) const {
}
#endif
+const AttrNameToTrustedType& SVGScriptElement::GetCheckedAttributeTypes()
+ const {
+ DEFINE_STATIC_LOCAL(AttrNameToTrustedType, attribute_map,
+ ({
+ {svg_names::kHrefAttr.LocalName(),
+ SpecificTrustedType::kTrustedScriptURL},
+ }));
+ return attribute_map;
+}
+
void SVGScriptElement::Trace(blink::Visitor* visitor) {
visitor->Trace(loader_);
SVGElement::Trace(visitor);
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 c1222ee2449..cb4b1763331 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
@@ -49,6 +49,8 @@ class SVGScriptElement final : public SVGElement,
bool IsScriptElement() const override { return true; }
+ const AttrNameToTrustedType& GetCheckedAttributeTypes() const override;
+
void Trace(blink::Visitor*) override;
private:
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_script_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_script_element.idl
index 8ab0ade9b9a..59fc666d8bd 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_script_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_script_element.idl
@@ -25,6 +25,7 @@
// https://svgwg.org/svg2-draft/interact.html#InterfaceSVGScriptElement
+[Exposed=Window]
interface SVGScriptElement : SVGElement {
[Reflect] attribute DOMString type;
};
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 7d73cf86127..557ce8d9706 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
@@ -51,7 +51,7 @@ void InvalidateInstancesAndAncestorResources(SVGStopElement* stop_element) {
SVGElement::InvalidationGuard invalidation_guard(stop_element);
Element* parent = stop_element->parentElement();
- if (auto* gradient = ToSVGGradientElementOrNull(parent))
+ if (auto* gradient = DynamicTo<SVGGradientElement>(parent))
gradient->InvalidateGradient(layout_invalidation_reason::kChildChanged);
}
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_stop_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_stop_element.idl
index 642e3aa8190..36fc16ec889 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_stop_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_stop_element.idl
@@ -25,6 +25,7 @@
// https://svgwg.org/svg2-draft/pservers.html#InterfaceSVGStopElement
+[Exposed=Window]
interface SVGStopElement : SVGElement {
[MeasureAs=SVG1DOMPaintServer] readonly attribute SVGAnimatedNumber offset;
};
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_string_list.idl b/chromium/third_party/blink/renderer/core/svg/svg_string_list.idl
index 3609fcb8b2a..8f81d377b1d 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_string_list.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_string_list.idl
@@ -26,6 +26,7 @@
// https://svgwg.org/svg2-draft/types.html#InterfaceSVGStringList
[
+ Exposed=Window,
ImplementedAs=SVGStringListTearOff
] interface SVGStringList {
readonly attribute unsigned long length;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_style_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_style_element.idl
index 59fe6ac06e5..17044044289 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_style_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_style_element.idl
@@ -26,6 +26,7 @@
// https://svgwg.org/svg2-draft/styling.html#InterfaceSVGStyleElement
+[Exposed=Window]
interface SVGStyleElement : SVGElement {
attribute DOMString type;
attribute DOMString media;
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 3ca5f742ddf..fa5d203086e 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
@@ -146,7 +146,7 @@ void SVGSVGElement::UpdateUserTransform() {
}
bool SVGSVGElement::ZoomAndPanEnabled() const {
- SVGZoomAndPanType zoom_and_pan = this->zoomAndPan();
+ SVGZoomAndPanType zoom_and_pan = zoomAndPan();
if (view_spec_ && view_spec_->ZoomAndPan() != kSVGZoomAndPanUnknown)
zoom_and_pan = view_spec_->ZoomAndPan();
return zoom_and_pan == kSVGZoomAndPanMagnify;
@@ -249,7 +249,7 @@ void SVGSVGElement::SvgAttributeChanged(const QualifiedName& attr_name) {
// height attributes can affect the replaced size so we need
// to mark it for updating.
if (width_or_height_changed) {
- LayoutObject* layout_object = this->GetLayoutObject();
+ LayoutObject* layout_object = GetLayoutObject();
// If the element is not attached, we cannot be sure if it is (going to
// be) an outermost root, so always mark presentation attributes dirty in
// that case.
@@ -323,7 +323,7 @@ bool SVGSVGElement::CheckIntersectionOrEnclosure(
return false;
AffineTransform ctm =
- ToSVGGraphicsElement(element).ComputeCTM(kAncestorScope, this);
+ To<SVGGraphicsElement>(element).ComputeCTM(kAncestorScope, this);
FloatRect mapped_repaint_rect =
ctm.MapRect(layout_object->VisualRectInLocalSVGCoordinates());
@@ -451,7 +451,7 @@ AffineTransform SVGSVGElement::LocalCoordinateSpaceTransform(
transform.Translate(x_->CurrentValue()->Value(length_context),
y_->CurrentValue()->Value(length_context));
} else if (mode == kScreenScope) {
- if (LayoutObject* layout_object = this->GetLayoutObject()) {
+ if (LayoutObject* layout_object = GetLayoutObject()) {
TransformationMatrix matrix;
// Adjust for the zoom level factored into CSS coordinates (WK bug
// #96361).
@@ -629,18 +629,21 @@ FloatSize SVGSVGElement::CurrentViewportSize() const {
}
bool SVGSVGElement::HasIntrinsicWidth() const {
- return width()->CurrentValue()->TypeWithCalcResolved() !=
- CSSPrimitiveValue::UnitType::kPercentage;
+ // TODO(crbug.com/979895): This is the result of a refactoring, which might
+ // have revealed an existing bug that we are not handling math functions
+ // involving percentages correctly. Fix it if necessary.
+ return !width()->CurrentValue()->IsPercentage();
}
bool SVGSVGElement::HasIntrinsicHeight() const {
- return height()->CurrentValue()->TypeWithCalcResolved() !=
- CSSPrimitiveValue::UnitType::kPercentage;
+ // TODO(crbug.com/979895): This is the result of a refactoring, which might
+ // have revealed an existing bug that we are not handling math functions
+ // involving percentages correctly. Fix it if necessary.
+ return !height()->CurrentValue()->IsPercentage();
}
float SVGSVGElement::IntrinsicWidth() const {
- if (width()->CurrentValue()->TypeWithCalcResolved() ==
- CSSPrimitiveValue::UnitType::kPercentage)
+ if (!HasIntrinsicWidth())
return 0;
SVGLengthContext length_context(this);
@@ -648,8 +651,7 @@ float SVGSVGElement::IntrinsicWidth() const {
}
float SVGSVGElement::IntrinsicHeight() const {
- if (height()->CurrentValue()->TypeWithCalcResolved() ==
- CSSPrimitiveValue::UnitType::kPercentage)
+ if (!HasIntrinsicHeight())
return 0;
SVGLengthContext length_context(this);
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 898a11cf01e..e59537f9f2b 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
@@ -22,6 +22,7 @@
// https://svgwg.org/svg2-draft/struct.html#InterfaceSVGSVGElement
+[Exposed=Window]
interface SVGSVGElement : SVGGraphicsElement {
[MeasureAs=SVG1DOMSVGElement] readonly attribute SVGAnimatedLength x;
[MeasureAs=SVG1DOMSVGElement] readonly attribute SVGAnimatedLength y;
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 73be72c72a3..f47af0dbb74 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
@@ -20,9 +20,9 @@
#include "third_party/blink/renderer/core/svg/svg_switch_element.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/layout/svg/layout_svg_transformable_container.h"
#include "third_party/blink/renderer/core/svg_names.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_switch_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_switch_element.idl
index 3611d236aae..f90943eb9f9 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_switch_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_switch_element.idl
@@ -25,5 +25,6 @@
// https://svgwg.org/svg2-draft/struct.html#InterfaceSVGSwitchElement
+[Exposed=Window]
interface SVGSwitchElement : SVGGraphicsElement {
};
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_symbol_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_symbol_element.idl
index 7b5298a879a..939eb94ae66 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_symbol_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_symbol_element.idl
@@ -25,6 +25,7 @@
// https://svgwg.org/svg2-draft/struct.html#InterfaceSVGSymbolElement
+[Exposed=Window]
interface SVGSymbolElement : SVGElement {
};
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 07ecdaff02c..15a88aacac1 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
@@ -24,7 +24,6 @@
#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"
@@ -35,6 +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/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
@@ -60,8 +60,7 @@ class SVGAnimatedTextLength final : public SVGAnimatedLength {
SVGLength::Initial::kUnitlessZero) {}
SVGLengthTearOff* baseVal() override {
- SVGTextContentElement* text_content_element =
- ToSVGTextContentElement(ContextElement());
+ auto* text_content_element = To<SVGTextContentElement>(ContextElement());
if (!text_content_element->TextLengthIsSpecifiedByUser())
BaseValue()->NewValueSpecifiedUnits(
CSSPrimitiveValue::UnitType::kNumber,
@@ -280,10 +279,8 @@ SVGTextContentElement* SVGTextContentElement::ElementFromLineLayoutItem(
(!line_layout_item.IsSVGText() && !line_layout_item.IsSVGInline()))
return nullptr;
- auto* element = To<SVGElement>(line_layout_item.GetNode());
- DCHECK(element);
- return IsSVGTextContentElement(*element) ? ToSVGTextContentElement(element)
- : nullptr;
+ DCHECK(line_layout_item.GetNode());
+ return DynamicTo<SVGTextContentElement>(line_layout_item.GetNode());
}
} // namespace blink
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 e6b76611395..2538750acae 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
@@ -96,7 +96,13 @@ inline bool IsSVGTextContentElement(const SVGElement& element) {
return element.IsTextContent();
}
-DEFINE_SVGELEMENT_TYPE_CASTS_WITH_FUNCTION(SVGTextContentElement);
+template <>
+struct DowncastTraits<SVGTextContentElement> {
+ static bool AllowFrom(const Node& node) {
+ auto* svg_element = DynamicTo<SVGElement>(node);
+ return svg_element && IsSVGTextContentElement(*svg_element);
+ }
+};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_text_content_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_text_content_element.idl
index 6557fcf63d8..2117f0d68b5 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_text_content_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_text_content_element.idl
@@ -25,6 +25,7 @@
// https://svgwg.org/svg2-draft/text.html#InterfaceSVGTextContentElement
+[Exposed=Window]
interface SVGTextContentElement : SVGGraphicsElement {
// lengthAdjust Types
[MeasureAs=SVG1DOMText] const unsigned short LENGTHADJUST_UNKNOWN = 0;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_text_content_element_test.cc b/chromium/third_party/blink/renderer/core/svg/svg_text_content_element_test.cc
index db820703b09..24625dde3b6 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_text_content_element_test.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_text_content_element_test.cc
@@ -13,8 +13,7 @@ class SVGTextContentElementTest : public EditingTestBase {};
TEST_F(SVGTextContentElementTest, selectSubStringNotCrash) {
SetBodyContent("<svg><text style='visibility:hidden;'>Text</text></svg>");
- SVGTextContentElement* elem =
- ToSVGTextContentElement(GetDocument().QuerySelector("text"));
+ auto* elem = To<SVGTextContentElement>(GetDocument().QuerySelector("text"));
VisiblePosition start = VisiblePosition::FirstPositionInNode(
*const_cast<SVGTextContentElement*>(elem));
EXPECT_TRUE(start.IsNull());
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_text_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_text_element.idl
index d3cbdf80a51..0ab1b3353b6 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_text_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_text_element.idl
@@ -25,5 +25,6 @@
// https://svgwg.org/svg2-draft/text.html#InterfaceSVGTextElement
+[Exposed=Window]
interface SVGTextElement : SVGTextPositioningElement {
};
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 05766023ca6..17c7f3c8a26 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
@@ -66,6 +66,10 @@ class SVGTextPathElement final : public SVGTextContentElement,
return spacing_.Get();
}
+ const AttrNameToTrustedType& GetCheckedAttributeTypes() const override {
+ return SVGURIReference::GetCheckedAttributeTypes();
+ }
+
void Trace(blink::Visitor*) override;
private:
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_text_path_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_text_path_element.idl
index 2aea585ab3c..4fa851e0fc2 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_text_path_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_text_path_element.idl
@@ -25,6 +25,7 @@
// https://svgwg.org/svg2-draft/text.html#InterfaceSVGTextPathElement
+[Exposed=Window]
interface SVGTextPathElement : SVGTextContentElement {
// textPath Method Types
[MeasureAs=SVG1DOMText] const unsigned short TEXTPATH_METHODTYPE_UNKNOWN = 0;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_text_positioning_element.h b/chromium/third_party/blink/renderer/core/svg/svg_text_positioning_element.h
index ac293307305..fd26dff2e08 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_text_positioning_element.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_text_positioning_element.h
@@ -57,7 +57,13 @@ inline bool IsSVGTextPositioningElement(const SVGElement& element) {
return element.IsTextPositioning();
}
-DEFINE_SVGELEMENT_TYPE_CASTS_WITH_FUNCTION(SVGTextPositioningElement);
+template <>
+struct DowncastTraits<SVGTextPositioningElement> {
+ static bool AllowFrom(const Node& node) {
+ auto* svg_element = DynamicTo<SVGElement>(node);
+ return svg_element && IsSVGTextPositioningElement(*svg_element);
+ }
+};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_text_positioning_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_text_positioning_element.idl
index c55fe385578..3e3e90c3f17 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_text_positioning_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_text_positioning_element.idl
@@ -25,6 +25,7 @@
// https://svgwg.org/svg2-draft/text.html#InterfaceSVGTextPositioningElement
+[Exposed=Window]
interface SVGTextPositioningElement : SVGTextContentElement {
[MeasureAs=SVG1DOMText] readonly attribute SVGAnimatedLengthList x;
[MeasureAs=SVG1DOMText] readonly attribute SVGAnimatedLengthList y;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_title_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_title_element.idl
index cfb65fbba04..b40e215c0f1 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_title_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_title_element.idl
@@ -25,5 +25,6 @@
// https://svgwg.org/svg2-draft/struct.html#InterfaceSVGTitleElement
+[Exposed=Window]
interface SVGTitleElement : SVGElement {
};
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_transform.idl b/chromium/third_party/blink/renderer/core/svg/svg_transform.idl
index d0ec20edd83..1fe9ee2c5d0 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_transform.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_transform.idl
@@ -22,6 +22,7 @@
// https://svgwg.org/svg2-draft/coords.html#InterfaceSVGTransform
[
+ Exposed=Window,
ImplementedAs=SVGTransformTearOff
] interface SVGTransform {
// Transform Types
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_transform_distance.h b/chromium/third_party/blink/renderer/core/svg/svg_transform_distance.h
index 6fa9ab660d2..3f0bb934018 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_transform_distance.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_transform_distance.h
@@ -21,7 +21,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_SVG_SVG_TRANSFORM_DISTANCE_H_
#include "third_party/blink/renderer/core/svg/svg_transform.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_transform_list.cc b/chromium/third_party/blink/renderer/core/svg/svg_transform_list.cc
index c24b8c20c81..c85f8ececdf 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_transform_list.cc
+++ b/chromium/third_party/blink/renderer/core/svg/svg_transform_list.cc
@@ -26,6 +26,7 @@
#include "base/stl_util.h"
#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_numeric_literal_value.h"
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
#include "third_party/blink/renderer/core/css/css_value_list.h"
#include "third_party/blink/renderer/core/svg/svg_parser_utilities.h"
@@ -228,46 +229,46 @@ CSSValue* CreateTransformCSSValue(const SVGTransform& transform) {
MakeGarbageCollected<CSSFunctionValue>(function_id);
switch (function_id) {
case CSSValueID::kRotate: {
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.Angle(), CSSPrimitiveValue::UnitType::kDegrees));
FloatPoint rotation_origin = transform.RotationCenter();
if (!ToFloatSize(rotation_origin).IsZero()) {
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
rotation_origin.X(), CSSPrimitiveValue::UnitType::kUserUnits));
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
rotation_origin.Y(), CSSPrimitiveValue::UnitType::kUserUnits));
}
break;
}
case CSSValueID::kSkewX:
case CSSValueID::kSkewY:
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.Angle(), CSSPrimitiveValue::UnitType::kDegrees));
break;
case CSSValueID::kMatrix:
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.Matrix().A(), CSSPrimitiveValue::UnitType::kUserUnits));
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.Matrix().B(), CSSPrimitiveValue::UnitType::kUserUnits));
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.Matrix().C(), CSSPrimitiveValue::UnitType::kUserUnits));
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.Matrix().D(), CSSPrimitiveValue::UnitType::kUserUnits));
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.Matrix().E(), CSSPrimitiveValue::UnitType::kUserUnits));
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.Matrix().F(), CSSPrimitiveValue::UnitType::kUserUnits));
break;
case CSSValueID::kScale:
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.Matrix().A(), CSSPrimitiveValue::UnitType::kUserUnits));
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.Matrix().D(), CSSPrimitiveValue::UnitType::kUserUnits));
break;
case CSSValueID::kTranslate:
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.Matrix().E(), CSSPrimitiveValue::UnitType::kUserUnits));
- transform_value->Append(*CSSPrimitiveValue::Create(
+ transform_value->Append(*CSSNumericLiteralValue::Create(
transform.Matrix().F(), CSSPrimitiveValue::UnitType::kUserUnits));
break;
default:
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_transform_list.idl b/chromium/third_party/blink/renderer/core/svg/svg_transform_list.idl
index e917f280ee1..3dda559cf64 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_transform_list.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_transform_list.idl
@@ -27,6 +27,7 @@
// https://svgwg.org/svg2-draft/coords.html#InterfaceSVGTransformList
[
+ Exposed=Window,
ImplementedAs=SVGTransformListTearOff
] interface SVGTransformList {
readonly attribute unsigned long length;
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_tspan_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_tspan_element.idl
index d72fa86dba4..c28604e9265 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_tspan_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_tspan_element.idl
@@ -25,5 +25,6 @@
// https://svgwg.org/svg2-draft/text.html#InterfaceSVGTSpanElement
+[Exposed=Window]
interface SVGTSpanElement : SVGTextPositioningElement {
};
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_unit_types.idl b/chromium/third_party/blink/renderer/core/svg/svg_unit_types.idl
index 444f27d798f..77700b8b16e 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_unit_types.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_unit_types.idl
@@ -25,6 +25,7 @@
// https://svgwg.org/svg2-draft/types.html#InterfaceSVGUnitTypes
+[Exposed=Window]
interface SVGUnitTypes {
// Unit Types
const unsigned short SVG_UNIT_TYPE_UNKNOWN = 0;
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 99471e10c92..47221fbcadf 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
@@ -151,4 +151,13 @@ void SVGURIReference::UnobserveTarget(Member<IdTargetObserver>& observer) {
observer = nullptr;
}
+const AttrNameToTrustedType& SVGURIReference::GetCheckedAttributeTypes() {
+ DEFINE_STATIC_LOCAL(
+ AttrNameToTrustedType, attribute_map,
+ ({
+ {svg_names::kHrefAttr.LocalName(), SpecificTrustedType::kTrustedURL},
+ }));
+ return attribute_map;
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_uri_reference.h b/chromium/third_party/blink/renderer/core/svg/svg_uri_reference.h
index 9b0d5050fc7..8d240521c55 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_uri_reference.h
+++ b/chromium/third_party/blink/renderer/core/svg/svg_uri_reference.h
@@ -24,6 +24,7 @@
#include <memory>
#include "base/callback.h"
#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/svg/svg_animated_href.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
@@ -31,7 +32,6 @@
namespace blink {
class Document;
-class Element;
class IdTargetObserver;
class SVGElement;
class TreeScope;
@@ -81,6 +81,8 @@ class CORE_EXPORT SVGURIReference : public GarbageCollectedMixin {
// JS API
SVGAnimatedHref* href() const { return href_.Get(); }
+ static const AttrNameToTrustedType& GetCheckedAttributeTypes();
+
void Trace(blink::Visitor*) override;
protected:
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 cdfdda9d4c8..2d5a2b3a1f2 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
@@ -204,8 +204,8 @@ void SVGUseElement::UpdateTargetReference() {
ResourceLoaderOptions options;
options.initiator_info.name = localName();
FetchParameters params(ResourceRequest(element_url_), options);
- params.MutableResourceRequest().SetFetchRequestMode(
- network::mojom::FetchRequestMode::kSameOrigin);
+ params.MutableResourceRequest().SetMode(
+ network::mojom::RequestMode::kSameOrigin);
DocumentResource::FetchSVGDocument(params, GetDocument().Fetcher(), this);
}
@@ -499,23 +499,21 @@ Path SVGUseElement::ToClipPath() const {
SVGGraphicsElement* SVGUseElement::VisibleTargetGraphicsElementForClipping()
const {
- auto* element = DynamicTo<SVGElement>(UseShadowRoot().firstChild());
- if (!element)
- return nullptr;
-
- if (!element->IsSVGGraphicsElement())
+ auto* svg_graphics_element =
+ DynamicTo<SVGGraphicsElement>(UseShadowRoot().firstChild());
+ if (!svg_graphics_element)
return nullptr;
// Spec: "If a <use> element is a child of a clipPath element, it must
// directly reference <path>, <text> or basic shapes elements. Indirect
// references are an error and the clipPath element must be ignored."
// https://drafts.fxtf.org/css-masking/#the-clip-path
- if (!IsDirectReference(*element)) {
+ if (!IsDirectReference(*svg_graphics_element)) {
// Spec: Indirect references are an error (14.3.5)
return nullptr;
}
- return &ToSVGGraphicsElement(*element);
+ return svg_graphics_element;
}
void SVGUseElement::AddReferencesToFirstDegreeNestedUseElements(
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 7c40606ee2c..b1ce459c8b0 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
@@ -59,6 +59,10 @@ class SVGUseElement final : public SVGGraphicsElement,
void DispatchPendingEvent();
Path ToClipPath() const;
+ const AttrNameToTrustedType& GetCheckedAttributeTypes() const override {
+ return SVGURIReference::GetCheckedAttributeTypes();
+ }
+
void Trace(blink::Visitor*) override;
private:
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_use_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_use_element.idl
index 487f78ad324..2324986492b 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_use_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_use_element.idl
@@ -25,6 +25,7 @@
// https://svgwg.org/svg2-draft/struct.html#InterfaceSVGUseElement
+[Exposed=Window]
interface SVGUseElement : SVGGraphicsElement {
[MeasureAs=SVG1DOMUseElement] readonly attribute SVGAnimatedLength x;
[MeasureAs=SVG1DOMUseElement] readonly attribute SVGAnimatedLength y;
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 53e9262b0db..f91681d0d1a 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
@@ -20,8 +20,8 @@
#include "third_party/blink/renderer/core/svg/svg_view_element.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/svg_names.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/svg/svg_view_element.idl b/chromium/third_party/blink/renderer/core/svg/svg_view_element.idl
index 53626f22dc4..cb31f4a66ec 100644
--- a/chromium/third_party/blink/renderer/core/svg/svg_view_element.idl
+++ b/chromium/third_party/blink/renderer/core/svg/svg_view_element.idl
@@ -25,6 +25,7 @@
// https://svgwg.org/svg2-draft/linking.html#InterfaceSVGViewElement
+[Exposed=Window]
interface SVGViewElement : SVGElement {
};
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 b49eeeb7b7a..20a4843225a 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
@@ -95,11 +95,11 @@ TEST(UnsafeSVGAttributeSanitizationTest, pasteAnchor_javaScriptHrefIsStripped) {
EXPECT_TRUE(sanitized_content.Contains("</a>"))
<< "We should have pasted *something*; the document is: "
- << sanitized_content.Utf8().data();
+ << sanitized_content.Utf8();
EXPECT_FALSE(sanitized_content.Contains(":alert()"))
<< "The JavaScript URL is unsafe and should have been stripped; "
"instead: "
- << sanitized_content.Utf8().data();
+ << sanitized_content.Utf8();
}
TEST(UnsafeSVGAttributeSanitizationTest,
@@ -116,11 +116,11 @@ TEST(UnsafeSVGAttributeSanitizationTest,
EXPECT_TRUE(sanitized_content.Contains("</a>"))
<< "We should have pasted *something*; the document is: "
- << sanitized_content.Utf8().data();
+ << sanitized_content.Utf8();
EXPECT_FALSE(sanitized_content.Contains(":alert()"))
<< "The JavaScript URL is unsafe and should have been stripped; "
"instead: "
- << sanitized_content.Utf8().data();
+ << sanitized_content.Utf8();
}
TEST(UnsafeSVGAttributeSanitizationTest,
@@ -136,11 +136,11 @@ TEST(UnsafeSVGAttributeSanitizationTest,
EXPECT_TRUE(sanitized_content.Contains("</a>"))
<< "We should have pasted *something*; the document is: "
- << sanitized_content.Utf8().data();
+ << sanitized_content.Utf8();
EXPECT_FALSE(sanitized_content.Contains(":alert()"))
<< "The JavaScript URL is unsafe and should have been stripped; "
"instead: "
- << sanitized_content.Utf8().data();
+ << sanitized_content.Utf8();
}
TEST(UnsafeSVGAttributeSanitizationTest,
@@ -157,11 +157,11 @@ TEST(UnsafeSVGAttributeSanitizationTest,
EXPECT_TRUE(sanitized_content.Contains("</a>"))
<< "We should have pasted *something*; the document is: "
- << sanitized_content.Utf8().data();
+ << sanitized_content.Utf8();
EXPECT_FALSE(sanitized_content.Contains(":alert()"))
<< "The JavaScript URL is unsafe and should have been stripped; "
"instead: "
- << sanitized_content.Utf8().data();
+ << sanitized_content.Utf8();
}
TEST(UnsafeSVGAttributeSanitizationTest,
@@ -177,11 +177,11 @@ TEST(UnsafeSVGAttributeSanitizationTest,
EXPECT_TRUE(sanitized_content.Contains("</a>"))
<< "We should have pasted *something*; the document is: "
- << sanitized_content.Utf8().data();
+ << sanitized_content.Utf8();
EXPECT_FALSE(sanitized_content.Contains(":alert()"))
<< "The JavaScript URL is unsafe and should have been stripped; "
"instead: "
- << sanitized_content.Utf8().data();
+ << sanitized_content.Utf8();
}
TEST(
@@ -199,11 +199,11 @@ TEST(
EXPECT_TRUE(sanitized_content.Contains("</a>"))
<< "We should have pasted *something*; the document is: "
- << sanitized_content.Utf8().data();
+ << sanitized_content.Utf8();
EXPECT_FALSE(sanitized_content.Contains(":alert()"))
<< "The JavaScript URL is unsafe and should have been stripped; "
"instead: "
- << sanitized_content.Utf8().data();
+ << sanitized_content.Utf8();
}
// Other sanitization integration tests are web tests that use
@@ -226,11 +226,11 @@ TEST(UnsafeSVGAttributeSanitizationTest,
EXPECT_TRUE(sanitized_content.Contains("<a href=\"https://www.goo"))
<< "We should have pasted *something*; the document is: "
- << sanitized_content.Utf8().data();
+ << sanitized_content.Utf8();
EXPECT_FALSE(sanitized_content.Contains(":alert()"))
<< "The JavaScript URL is unsafe and should have been stripped; "
"instead: "
- << sanitized_content.Utf8().data();
+ << sanitized_content.Utf8();
}
TEST(
@@ -252,11 +252,11 @@ TEST(
EXPECT_TRUE(sanitized_content.Contains("<a xlink:href=\"https://www.goo"))
<< "We should have pasted *something*; the document is: "
- << sanitized_content.Utf8().data();
+ << sanitized_content.Utf8();
EXPECT_FALSE(sanitized_content.Contains(":alert()"))
<< "The JavaScript URL is unsafe and should have been stripped; "
"instead: "
- << sanitized_content.Utf8().data();
+ << sanitized_content.Utf8();
}
// Unit tests
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 fdd1ccd02ee..55a35cd652c 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
@@ -23,7 +23,8 @@ LocalFrame* SingleChildLocalFrameClient::CreateFrame(
auto* child_client =
MakeGarbageCollected<LocalFrameClientWithParent>(parent_frame);
child_ = MakeGarbageCollected<LocalFrame>(
- child_client, *parent_frame->GetPage(), owner_element);
+ child_client, *parent_frame->GetPage(), owner_element,
+ &parent_frame->window_agent_factory(), nullptr);
child_->CreateView(IntSize(500, 500), Color::kTransparent);
child_->Init();
@@ -45,7 +46,7 @@ RenderingTest::RenderingTest(LocalFrameClient* local_frame_client)
: UseMockScrollbarSettings(), local_frame_client_(local_frame_client) {}
const Node* RenderingTest::HitTest(int x, int y) {
- HitTestLocation location(LayoutPoint(x, y));
+ HitTestLocation location(PhysicalOffset(x, y));
HitTestResult result(
HitTestRequest(HitTestRequest::kReadOnly | HitTestRequest::kActive |
HitTestRequest::kAllowChildFrameContent),
@@ -54,7 +55,8 @@ const Node* RenderingTest::HitTest(int x, int y) {
return result.InnerNode();
}
-HitTestResult::NodeSet RenderingTest::RectBasedHitTest(LayoutRect rect) {
+HitTestResult::NodeSet RenderingTest::RectBasedHitTest(
+ const PhysicalRect& rect) {
HitTestLocation location(rect);
HitTestResult result(
HitTestRequest(HitTestRequest::kReadOnly | HitTestRequest::kActive |
@@ -76,6 +78,8 @@ void RenderingTest::SetUp() {
// This ensures that the minimal DOM tree gets attached
// correctly for tests that don't call setBodyInnerHTML.
+ GetDocument().View()->SetParentVisible(true);
+ GetDocument().View()->SetSelfVisible(true);
UpdateAllLifecyclePhasesForTest();
// Allow ASSERT_DEATH and EXPECT_DEATH for multiple threads.
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 7f525260548..2491f685468 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
@@ -22,7 +22,7 @@
#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/testing/layer_tree_host_embedder.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -74,6 +74,7 @@ class RenderingTestChromeClient : public EmptyChromeClient {
// Runtime flags can affect LayerTreeHost's settings so this needs to be
// recreated for each test.
layer_tree_.reset(new LayerTreeHostEmbedder());
+ device_emulation_transform_.reset();
}
bool HasLayer(const cc::Layer& layer) {
@@ -89,8 +90,17 @@ class RenderingTestChromeClient : public EmptyChromeClient {
return layer_tree_->layer_tree_host();
}
+ void SetDeviceEmulationTransform(const TransformationMatrix& t) {
+ device_emulation_transform_ = std::make_unique<TransformationMatrix>(t);
+ }
+ TransformationMatrix GetDeviceEmulationTransform() const override {
+ return device_emulation_transform_ ? *device_emulation_transform_
+ : TransformationMatrix();
+ }
+
private:
std::unique_ptr<LayerTreeHostEmbedder> layer_tree_;
+ std::unique_ptr<TransformationMatrix> device_emulation_transform_;
};
class RenderingTest : public PageTestBase, public UseMockScrollbarSettings {
@@ -105,7 +115,7 @@ class RenderingTest : public PageTestBase, public UseMockScrollbarSettings {
explicit RenderingTest(LocalFrameClient* = nullptr);
const Node* HitTest(int x, int y);
- HitTestResult::NodeSet RectBasedHitTest(LayoutRect rect);
+ HitTestResult::NodeSet RectBasedHitTest(const PhysicalRect& rect);
protected:
void SetUp() override;
@@ -122,11 +132,7 @@ class RenderingTest : public PageTestBase, public UseMockScrollbarSettings {
void SetChildFrameHTML(const String&);
- // 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);
+ void RunDocumentLifecycle() {
GetDocument().View()->SetParentVisible(true);
GetDocument().View()->SetSelfVisible(true);
UpdateAllLifecyclePhasesForTest();
diff --git a/chromium/third_party/blink/renderer/core/testing/data/frameserialization/image_in_plugin.html b/chromium/third_party/blink/renderer/core/testing/data/frameserialization/image_in_plugin.html
new file mode 100644
index 00000000000..9f9510ca989
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/testing/data/frameserialization/image_in_plugin.html
@@ -0,0 +1,10 @@
+<html>
+<head>
+<meta charset="utf8">
+<title>Test Image in Plugin Element</title>
+</head>
+<body>
+<object data="1x.png" ></object>
+<embed src="2x.png"></embed>
+</body>
+</html>
diff --git a/chromium/third_party/blink/renderer/core/testing/data/frameserialization/img_srcset.html b/chromium/third_party/blink/renderer/core/testing/data/frameserialization/img_srcset.html
index 0f3dbe688e7..cceee514caf 100644
--- a/chromium/third_party/blink/renderer/core/testing/data/frameserialization/img_srcset.html
+++ b/chromium/third_party/blink/renderer/core/testing/data/frameserialization/img_srcset.html
@@ -4,7 +4,7 @@
<title>Test Image with srcset</title>
</head>
<body>
-<img src="1x.png" id="i1" srcset="2x.png 2x">
+<img src="1x.png" id="i1" srcset="2x.png 2x" sizes="(max-width: 640px) 6px">
<img src="1x.png" id="i2" width="8" srcset="2x.png 2x">
</body>
</html>
diff --git a/chromium/third_party/blink/renderer/core/testing/data/frameserialization/picture.html b/chromium/third_party/blink/renderer/core/testing/data/frameserialization/picture.html
new file mode 100644
index 00000000000..cf54501ad7f
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/testing/data/frameserialization/picture.html
@@ -0,0 +1,13 @@
+<html>
+<head>
+<meta charset="utf8">
+<title>Test Picture Element</title>
+</head>
+<body>
+<picture>
+ <source media="(min-width: 500px)" srcset="2x.png">
+ <source media="(min-width: 200px)" srcset="1x.png">
+ <img />
+</picture>
+</body>
+</html>
diff --git a/chromium/third_party/blink/renderer/core/testing/data/frameserialization/style_element_with_dynamic_css.html b/chromium/third_party/blink/renderer/core/testing/data/frameserialization/style_element_with_dynamic_css.html
new file mode 100644
index 00000000000..1464da53fd2
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/testing/data/frameserialization/style_element_with_dynamic_css.html
@@ -0,0 +1,20 @@
+<html>
+<head>
+<meta charset="utf8">
+<title>Test style element with dynamically updated CSS</title>
+<style id="style1" type="text/css"></style>
+<style id="style2" type="text/css">h1: {color: green;}</style>
+<script>
+function Run() {
+ document.getElementById("style1").sheet.insertRule("div { color: blue; }", 0);
+ document.getElementById("style2").sheet.insertRule("p { color: red; }", 0);
+}
+</script>
+</head>
+<body onload="Run()">
+ <h1>Title</h1>
+ <div>Hello</div>
+ <p>World</p>
+</body>
+</html>
+
diff --git a/chromium/third_party/blink/renderer/core/testing/data/notifications/file.txt b/chromium/third_party/blink/renderer/core/testing/data/notifications/file.txt
new file mode 100644
index 00000000000..6f96b7b2d5d
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/testing/data/notifications/file.txt
@@ -0,0 +1 @@
+notifications \ No newline at end of file
diff --git a/chromium/third_party/blink/renderer/core/testing/document_interface_broker_test_helpers.cc b/chromium/third_party/blink/renderer/core/testing/document_interface_broker_test_helpers.cc
index 252af799c3b..9a00ab95fa8 100644
--- a/chromium/third_party/blink/renderer/core/testing/document_interface_broker_test_helpers.cc
+++ b/chromium/third_party/blink/renderer/core/testing/document_interface_broker_test_helpers.cc
@@ -9,9 +9,9 @@
namespace blink {
void FrameHostTestInterfaceImpl::BindAndFlush(
- mojom::blink::FrameHostTestInterfaceRequest request) {
- binding_.Bind(std::move(request));
- binding_.WaitForIncomingMethodCall();
+ mojo::PendingReceiver<mojom::blink::FrameHostTestInterface> receiver) {
+ receiver_.Bind(std::move(receiver));
+ receiver_.WaitForIncomingCall();
}
void FrameHostTestInterfaceImpl::GetName(GetNameCallback callback) {
@@ -19,9 +19,9 @@ void FrameHostTestInterfaceImpl::GetName(GetNameCallback callback) {
}
void FrameHostTestDocumentInterfaceBroker::GetFrameHostTestInterface(
- mojom::blink::FrameHostTestInterfaceRequest request) {
+ mojo::PendingReceiver<mojom::blink::FrameHostTestInterface> receiver) {
FrameHostTestInterfaceImpl impl;
- impl.BindAndFlush(std::move(request));
+ impl.BindAndFlush(std::move(receiver));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/testing/document_interface_broker_test_helpers.h b/chromium/third_party/blink/renderer/core/testing/document_interface_broker_test_helpers.h
index 28c0a5bd0dc..23c5266367b 100644
--- a/chromium/third_party/blink/renderer/core/testing/document_interface_broker_test_helpers.h
+++ b/chromium/third_party/blink/renderer/core/testing/document_interface_broker_test_helpers.h
@@ -7,6 +7,8 @@
#include <utility>
+#include "mojo/public/cpp/bindings/pending_receiver.h"
+#include "mojo/public/cpp/bindings/receiver.h"
#include "third_party/blink/public/mojom/frame/document_interface_broker.mojom-blink.h"
#include "third_party/blink/public/mojom/frame/frame_host_test_interface.mojom-blink.h"
#include "third_party/blink/renderer/core/testing/test_document_interface_broker.h"
@@ -21,17 +23,18 @@ constexpr char kGetNameTestResponse[] = "BlinkTestName";
// examples.
class FrameHostTestInterfaceImpl : public mojom::blink::FrameHostTestInterface {
public:
- FrameHostTestInterfaceImpl() : binding_(this) {}
+ FrameHostTestInterfaceImpl() = default;
~FrameHostTestInterfaceImpl() override {}
- void BindAndFlush(mojom::blink::FrameHostTestInterfaceRequest request);
+ void BindAndFlush(
+ mojo::PendingReceiver<mojom::blink::FrameHostTestInterface> receiver);
protected:
void Ping(const KURL& url, const WTF::String& event) override {}
void GetName(GetNameCallback callback) override;
private:
- mojo::Binding<mojom::blink::FrameHostTestInterface> binding_;
+ mojo::Receiver<mojom::blink::FrameHostTestInterface> receiver_{this};
DISALLOW_COPY_AND_ASSIGN(FrameHostTestInterfaceImpl);
};
@@ -46,7 +49,8 @@ class FrameHostTestDocumentInterfaceBroker
std::move(request)) {}
void GetFrameHostTestInterface(
- mojom::blink::FrameHostTestInterfaceRequest request) override;
+ mojo::PendingReceiver<mojom::blink::FrameHostTestInterface> receiver)
+ override;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/testing/dummy_modulator.cc b/chromium/third_party/blink/renderer/core/testing/dummy_modulator.cc
index 5a4d3f4abb9..7afbf4da34d 100644
--- a/chromium/third_party/blink/renderer/core/testing/dummy_modulator.cc
+++ b/chromium/third_party/blink/renderer/core/testing/dummy_modulator.cc
@@ -20,7 +20,8 @@ class EmptyModuleRecordResolver final : public ModuleRecordResolver {
void RegisterModuleScript(const ModuleScript*) override {}
void UnregisterModuleScript(const ModuleScript*) override {}
- const ModuleScript* GetHostDefined(const ModuleRecord&) const override {
+ const ModuleScript* GetModuleScriptFromModuleRecord(
+ const ModuleRecord&) const override {
NOTREACHED();
return nullptr;
}
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 879592b356f..7ab8fb379f3 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
@@ -63,7 +63,8 @@ DummyPageHolder::DummyPageHolder(
const IntSize& initial_view_size,
Page::PageClients* page_clients_argument,
LocalFrameClient* local_frame_client,
- FrameSettingOverrideFunction setting_overrider) {
+ base::OnceCallback<void(Settings&)> setting_overrider,
+ const base::TickClock* clock) {
Page::PageClients page_clients;
if (!page_clients_argument)
FillWithEmptyClients(page_clients);
@@ -72,14 +73,18 @@ DummyPageHolder::DummyPageHolder(
page_ = Page::CreateNonOrdinary(page_clients);
Settings& settings = page_->GetSettings();
if (setting_overrider)
- (*setting_overrider)(settings);
+ std::move(setting_overrider).Run(settings);
local_frame_client_ = local_frame_client;
if (!local_frame_client_)
local_frame_client_ = MakeGarbageCollected<DummyLocalFrameClient>();
- frame_ = MakeGarbageCollected<LocalFrame>(local_frame_client_.Get(), *page_,
- nullptr);
+ // Create new WindowAgentFactory as this page will be isolated from others.
+ frame_ =
+ MakeGarbageCollected<LocalFrame>(local_frame_client_.Get(), *page_,
+ /* FrameOwner* */ nullptr,
+ /* WindowAgentFactory* */ nullptr,
+ /* InterfaceRegistry* */ nullptr, clock);
frame_->SetView(
MakeGarbageCollected<LocalFrameView>(*frame_, initial_view_size));
frame_->View()->GetPage()->GetVisualViewport().SetSize(initial_view_size);
diff --git a/chromium/third_party/blink/renderer/core/testing/dummy_page_holder.h b/chromium/third_party/blink/renderer/core/testing/dummy_page_holder.h
index fc6ef6cf000..67e784504f4 100644
--- a/chromium/third_party/blink/renderer/core/testing/dummy_page_holder.h
+++ b/chromium/third_party/blink/renderer/core/testing/dummy_page_holder.h
@@ -32,12 +32,15 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_TESTING_DUMMY_PAGE_HOLDER_H_
#include <memory>
+
+#include "base/callback.h"
#include "base/macros.h"
+#include "base/time/default_tick_clock.h"
#include "third_party/blink/renderer/core/frame/local_frame_client.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/platform/geometry/int_size.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -47,8 +50,6 @@ class LocalFrame;
class LocalFrameView;
class Settings;
-typedef void (*FrameSettingOverrideFunction)(Settings&);
-
// Creates a dummy Page, LocalFrame, and LocalFrameView whose clients are all
// no-op.
//
@@ -66,10 +67,13 @@ class DummyPageHolder {
USING_FAST_MALLOC(DummyPageHolder);
public:
- DummyPageHolder(const IntSize& initial_view_size = IntSize(),
- Page::PageClients* = nullptr,
- LocalFrameClient* = nullptr,
- FrameSettingOverrideFunction setting_overrider = nullptr);
+ DummyPageHolder(
+ const IntSize& initial_view_size = IntSize(),
+ Page::PageClients* = nullptr,
+ LocalFrameClient* = nullptr,
+ base::OnceCallback<void(Settings&)> setting_overrider =
+ base::NullCallback(),
+ const base::TickClock* clock = base::DefaultTickClock::GetInstance());
~DummyPageHolder();
Page& GetPage() const;
diff --git a/chromium/third_party/blink/renderer/core/testing/gc_object_liveness_observer.h b/chromium/third_party/blink/renderer/core/testing/gc_object_liveness_observer.h
index e713a435446..651661b0d3f 100644
--- a/chromium/third_party/blink/renderer/core/testing/gc_object_liveness_observer.h
+++ b/chromium/third_party/blink/renderer/core/testing/gc_object_liveness_observer.h
@@ -8,7 +8,7 @@
#include <memory>
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 6b87770c107..fe1c1222b82 100644
--- a/chromium/third_party/blink/renderer/core/testing/internal_settings.h
+++ b/chromium/third_party/blink/renderer/core/testing/internal_settings.h
@@ -34,7 +34,7 @@
#include "third_party/blink/renderer/platform/geometry/int_size.h"
#include "third_party/blink/renderer/platform/graphics/image_animation_policy.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/testing/internals.cc b/chromium/third_party/blink/renderer/core/testing/internals.cc
index b251981e9aa..ad853e1babe 100644
--- a/chromium/third_party/blink/renderer/core/testing/internals.cc
+++ b/chromium/third_party/blink/renderer/core/testing/internals.cc
@@ -26,7 +26,6 @@
#include "third_party/blink/renderer/core/testing/internals.h"
-#include <deque>
#include <memory>
#include "base/macros.h"
@@ -35,6 +34,7 @@
#include "gpu/command_buffer/client/gles2_interface.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_graphics_context_3d_provider.h"
+#include "third_party/blink/public/web/web_device_emulation_params.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"
@@ -165,7 +165,7 @@
#include "third_party/blink/renderer/platform/graphics/paint/raster_invalidation_tracking.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
-#include "third_party/blink/renderer/platform/instance_counters.h"
+#include "third_party/blink/renderer/platform/instrumentation/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/loader/fetch/memory_cache.h"
@@ -173,6 +173,7 @@
#include "third_party/blink/renderer/platform/loader/fetch/resource_load_priority.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/scheduler/public/thread.h"
#include "third_party/blink/renderer/platform/testing/url_test_helpers.h"
#include "third_party/blink/renderer/platform/text/layout_locale.h"
#include "third_party/blink/renderer/platform/weborigin/scheme_registry.h"
@@ -272,8 +273,7 @@ void Internals::ResetToConsistentState(Page* page) {
// call.
page->SetDefaultPageScaleLimits(1, 4);
page->SetPageScaleFactor(1);
- page->GetChromeClient().GetWebView()->SetDeviceEmulationTransform(
- TransformationMatrix());
+ page->GetChromeClient().GetWebView()->DisableDeviceEmulation();
// Ensure timers are reset so timers such as EventHandler's |hover_timer_| do
// not cause additional lifecycle updates.
@@ -486,7 +486,7 @@ ScriptPromise Internals::getResourcePriority(ScriptState* script_state,
ScriptPromiseResolver* resolver =
MakeGarbageCollected<ScriptPromiseResolver>(script_state);
ScriptPromise promise = resolver->Promise();
- KURL resource_url = url_test_helpers::ToKURL(url.Utf8().data());
+ KURL resource_url = url_test_helpers::ToKURL(url.Utf8());
DCHECK(document);
auto callback = WTF::Bind(&Internals::ResolveResourcePriority,
@@ -513,10 +513,10 @@ String Internals::getResourceHeader(const String& url,
if (!document)
return String();
Resource* resource = document->Fetcher()->AllResources().at(
- url_test_helpers::ToKURL(url.Utf8().data()));
+ url_test_helpers::ToKURL(url.Utf8()));
if (!resource)
return String();
- return resource->GetResourceRequest().HttpHeaderField(header.Utf8().data());
+ return resource->GetResourceRequest().HttpHeaderField(AtomicString(header));
}
bool Internals::isValidContentSelect(Element* insertion_point,
@@ -885,14 +885,8 @@ DOMWindow* Internals::pagePopupWindow() const {
if (!document_)
return nullptr;
if (Page* page = document_->GetPage()) {
- LocalDOMWindow* popup =
- To<LocalDOMWindow>(page->GetChromeClient().PagePopupWindowForTesting());
- if (popup) {
- // We need to make the popup same origin so web tests can access it.
- popup->document()->UpdateSecurityOrigin(
- document_->GetMutableSecurityOrigin());
- }
- return popup;
+ return To<LocalDOMWindow>(
+ page->GetChromeClient().PagePopupWindowForTesting());
}
return nullptr;
}
@@ -1385,7 +1379,7 @@ void Internals::setAutofilledValue(Element* element,
if (auto* select = ToHTMLSelectElementOrNull(*element))
select->setValue(value, true /* send_events */);
- ToHTMLFormControlElement(element)->SetAutofillState(
+ To<HTMLFormControlElement>(element)->SetAutofillState(
blink::WebAutofillState::kAutofilled);
}
@@ -1406,19 +1400,15 @@ void Internals::setAutofilled(Element* element,
bool enabled,
ExceptionState& exception_state) {
DCHECK(element);
- if (!element->IsFormControlElement()) {
+ auto* form_control_element = DynamicTo<HTMLFormControlElement>(element);
+ if (!form_control_element) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidNodeTypeError,
"The element provided is not a form control element.");
return;
}
- if (enabled) {
- ToHTMLFormControlElement(element)->SetAutofillState(
- WebAutofillState::kAutofilled);
- } else {
- ToHTMLFormControlElement(element)->SetAutofillState(
- WebAutofillState::kNotFilled);
- }
+ form_control_element->SetAutofillState(
+ enabled ? WebAutofillState::kAutofilled : WebAutofillState::kNotFilled);
}
Range* Internals::rangeFromLocationAndLength(Element* scope,
@@ -1472,10 +1462,10 @@ void Internals::HitTestRect(HitTestLocation& location,
Document* document) {
document->UpdateStyleAndLayout();
EventHandler& event_handler = document->GetFrame()->GetEventHandler();
- LayoutPoint hit_test_point(
- document->GetFrame()->View()->ConvertFromRootFrame(LayoutPoint(x, y)));
- location = HitTestLocation(
- (LayoutRect(hit_test_point, LayoutSize((int)width, (int)height))));
+ PhysicalRect rect{LayoutUnit(x), LayoutUnit(y), LayoutUnit(width),
+ LayoutUnit(height)};
+ rect.offset = document->GetFrame()->View()->ConvertFromRootFrame(rect.offset);
+ location = HitTestLocation(rect);
result = event_handler.HitTestResultAtLocation(
location, HitTestRequest::kReadOnly | HitTestRequest::kActive |
HitTestRequest::kListBased);
@@ -1806,14 +1796,14 @@ static void AccumulateTouchActionRectList(
HitTestLayerRectList* hit_test_rects) {
const cc::TouchActionRegion& touch_action_region =
graphics_layer->CcLayer()->touch_action_region();
- if (!touch_action_region.region().IsEmpty()) {
+ if (!touch_action_region.GetAllRegions().IsEmpty()) {
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())
+ for (const gfx::Rect& hit_test_rect : touch_action_region.GetAllRegions())
layer_hit_test_rects.push_back(IntRect(hit_test_rect));
MergeRects(layer_hit_test_rects);
@@ -1851,13 +1841,13 @@ HitTestLayerRectList* Internals::touchEventTargetLayerRects(
for (const auto& layer : content_layers) {
const cc::TouchActionRegion& touch_action_region =
layer->touch_action_region();
- if (!touch_action_region.region().IsEmpty()) {
+ if (!touch_action_region.GetAllRegions().IsEmpty()) {
const auto& offset = layer->offset_to_transform_parent();
IntRect layer_rect(RoundedIntPoint(FloatPoint(offset.x(), offset.y())),
IntSize(layer->bounds()));
Vector<IntRect> layer_hit_test_rects;
- for (const gfx::Rect& hit_test_rect : touch_action_region.region())
+ for (const auto& hit_test_rect : touch_action_region.GetAllRegions())
layer_hit_test_rects.push_back(IntRect(hit_test_rect));
MergeRects(layer_hit_test_rects);
@@ -1961,7 +1951,8 @@ StaticNodeList* Internals::nodesFromRect(
HitTestRequest::kActive |
HitTestRequest::kListBased;
LocalFrame* frame = document->GetFrame();
- LayoutRect rect(x, y, width, height);
+ PhysicalRect rect{LayoutUnit(x), LayoutUnit(y), LayoutUnit(width),
+ LayoutUnit(height)};
if (ignore_clipping) {
hit_type |= HitTestRequest::kIgnoreClipping;
} else if (!IntRect(IntPoint(), frame->View()->Size())
@@ -2316,7 +2307,7 @@ String Internals::pageProperty(String property_name,
return String();
}
- return PrintContext::PageProperty(GetFrame(), property_name.Utf8().data(),
+ return PrintContext::PageProperty(GetFrame(), property_name.Utf8().c_str(),
page_number);
}
@@ -2614,96 +2605,110 @@ DOMRectList* Internals::AnnotatedRegions(Document* document,
return DOMRectList::Create(quads);
}
-static const char* CursorTypeToString(Cursor::Type cursor_type) {
+static const char* CursorTypeToString(ui::CursorType cursor_type) {
switch (cursor_type) {
- case Cursor::kPointer:
+ case ui::CursorType::kPointer:
return "Pointer";
- case Cursor::kCross:
+ case ui::CursorType::kCross:
return "Cross";
- case Cursor::kHand:
+ case ui::CursorType::kHand:
return "Hand";
- case Cursor::kIBeam:
+ case ui::CursorType::kIBeam:
return "IBeam";
- case Cursor::kWait:
+ case ui::CursorType::kWait:
return "Wait";
- case Cursor::kHelp:
+ case ui::CursorType::kHelp:
return "Help";
- case Cursor::kEastResize:
+ case ui::CursorType::kEastResize:
return "EastResize";
- case Cursor::kNorthResize:
+ case ui::CursorType::kNorthResize:
return "NorthResize";
- case Cursor::kNorthEastResize:
+ case ui::CursorType::kNorthEastResize:
return "NorthEastResize";
- case Cursor::kNorthWestResize:
+ case ui::CursorType::kNorthWestResize:
return "NorthWestResize";
- case Cursor::kSouthResize:
+ case ui::CursorType::kSouthResize:
return "SouthResize";
- case Cursor::kSouthEastResize:
+ case ui::CursorType::kSouthEastResize:
return "SouthEastResize";
- case Cursor::kSouthWestResize:
+ case ui::CursorType::kSouthWestResize:
return "SouthWestResize";
- case Cursor::kWestResize:
+ case ui::CursorType::kWestResize:
return "WestResize";
- case Cursor::kNorthSouthResize:
+ case ui::CursorType::kNorthSouthResize:
return "NorthSouthResize";
- case Cursor::kEastWestResize:
+ case ui::CursorType::kEastWestResize:
return "EastWestResize";
- case Cursor::kNorthEastSouthWestResize:
+ case ui::CursorType::kNorthEastSouthWestResize:
return "NorthEastSouthWestResize";
- case Cursor::kNorthWestSouthEastResize:
+ case ui::CursorType::kNorthWestSouthEastResize:
return "NorthWestSouthEastResize";
- case Cursor::kColumnResize:
+ case ui::CursorType::kColumnResize:
return "ColumnResize";
- case Cursor::kRowResize:
+ case ui::CursorType::kRowResize:
return "RowResize";
- case Cursor::kMiddlePanning:
+ case ui::CursorType::kMiddlePanning:
return "MiddlePanning";
- case Cursor::kEastPanning:
+ case ui::CursorType::kMiddlePanningVertical:
+ return "MiddlePanningVertical";
+ case ui::CursorType::kMiddlePanningHorizontal:
+ return "MiddlePanningHorizontal";
+ case ui::CursorType::kEastPanning:
return "EastPanning";
- case Cursor::kNorthPanning:
+ case ui::CursorType::kNorthPanning:
return "NorthPanning";
- case Cursor::kNorthEastPanning:
+ case ui::CursorType::kNorthEastPanning:
return "NorthEastPanning";
- case Cursor::kNorthWestPanning:
+ case ui::CursorType::kNorthWestPanning:
return "NorthWestPanning";
- case Cursor::kSouthPanning:
+ case ui::CursorType::kSouthPanning:
return "SouthPanning";
- case Cursor::kSouthEastPanning:
+ case ui::CursorType::kSouthEastPanning:
return "SouthEastPanning";
- case Cursor::kSouthWestPanning:
+ case ui::CursorType::kSouthWestPanning:
return "SouthWestPanning";
- case Cursor::kWestPanning:
+ case ui::CursorType::kWestPanning:
return "WestPanning";
- case Cursor::kMove:
+ case ui::CursorType::kMove:
return "Move";
- case Cursor::kVerticalText:
+ case ui::CursorType::kVerticalText:
return "VerticalText";
- case Cursor::kCell:
+ case ui::CursorType::kCell:
return "Cell";
- case Cursor::kContextMenu:
+ case ui::CursorType::kContextMenu:
return "ContextMenu";
- case Cursor::kAlias:
+ case ui::CursorType::kAlias:
return "Alias";
- case Cursor::kProgress:
+ case ui::CursorType::kProgress:
return "Progress";
- case Cursor::kNoDrop:
+ case ui::CursorType::kNoDrop:
return "NoDrop";
- case Cursor::kCopy:
+ case ui::CursorType::kCopy:
return "Copy";
- case Cursor::kNone:
+ case ui::CursorType::kNone:
return "None";
- case Cursor::kNotAllowed:
+ case ui::CursorType::kNotAllowed:
return "NotAllowed";
- case Cursor::kZoomIn:
+ case ui::CursorType::kZoomIn:
return "ZoomIn";
- case Cursor::kZoomOut:
+ case ui::CursorType::kZoomOut:
return "ZoomOut";
- case Cursor::kGrab:
+ case ui::CursorType::kGrab:
return "Grab";
- case Cursor::kGrabbing:
+ case ui::CursorType::kGrabbing:
return "Grabbing";
- case Cursor::kCustom:
+ case ui::CursorType::kCustom:
return "Custom";
+ case ui::CursorType::kNull:
+ return "Null";
+ case ui::CursorType::kDndNone:
+ return "DragAndDropNone";
+ case ui::CursorType::kDndMove:
+ return "DragAndDropMove";
+ case ui::CursorType::kDndCopy:
+ return "DragAndDropCopy";
+ case ui::CursorType::kDndLink:
+ return "DragAndDropLink";
}
NOTREACHED();
@@ -3158,7 +3163,7 @@ unsigned Internals::canvasFontCacheMaxFonts() {
void Internals::setScrollChain(ScrollState* scroll_state,
const HeapVector<Member<Element>>& elements,
ExceptionState&) {
- std::deque<DOMNodeId> scroll_chain;
+ Deque<DOMNodeId> scroll_chain;
for (wtf_size_t i = 0; i < elements.size(); ++i)
scroll_chain.push_back(DOMNodeIds::IdForNode(elements[i].Get()));
scroll_state->SetScrollChain(scroll_chain);
@@ -3292,6 +3297,17 @@ void Internals::setCapsLockState(bool enabled) {
enabled ? OverrideCapsLockState::kOn : OverrideCapsLockState::kOff);
}
+void Internals::setPseudoClassState(Element* element,
+ const String& pseudo,
+ bool matches,
+ ExceptionState& exception_state) {
+ if (!element->GetDocument().SetPseudoStateForTesting(*element, pseudo,
+ matches)) {
+ exception_state.ThrowDOMException(DOMExceptionCode::kNotSupportedError,
+ pseudo + " is not supported");
+ }
+}
+
bool Internals::setScrollbarVisibilityInScrollableArea(Node* node,
bool visible) {
if (ScrollableArea* scrollable_area = ScrollableAreaForNode(node)) {
@@ -3309,7 +3325,7 @@ double Internals::monotonicTimeToZeroBasedDocumentTime(
return document_->Loader()
->GetTiming()
.MonotonicTimeToZeroBasedDocumentTime(
- base::TimeTicks() + TimeDelta::FromSecondsD(platform_time))
+ base::TimeTicks() + base::TimeDelta::FromSecondsD(platform_time))
.InSecondsF();
}
@@ -3445,8 +3461,9 @@ void Internals::setDeviceEmulationScale(float scale,
"The document's page cannot be retrieved.");
return;
}
- page->GetChromeClient().GetWebView()->SetDeviceEmulationTransform(
- TransformationMatrix().Scale(scale));
+ WebDeviceEmulationParams params;
+ params.scale = scale;
+ page->GetChromeClient().GetWebView()->EnableDeviceEmulation(params);
}
void Internals::ResolveResourcePriority(ScriptPromiseResolver* resolver,
@@ -3454,4 +3471,17 @@ void Internals::ResolveResourcePriority(ScriptPromiseResolver* resolver,
resolver->Resolve(resource_load_priority);
}
+String Internals::getDocumentAgentId(Document* document) {
+ // Sounds like there's no notion of "process ID" in Blink, but the main
+ // thread's thread ID serves for that purpose.
+ PlatformThreadId process_id = Thread::MainThread()->ThreadId();
+
+ uintptr_t agent_address = reinterpret_cast<uintptr_t>(document->GetAgent());
+
+ // This serializes a pointer as a decimal number, which is a bit ugly, but
+ // it works. Is there any utility to dump a number in a hexadecimal form?
+ // I couldn't find one in WTF.
+ return String::Number(process_id) + ":" + String::Number(agent_address);
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/testing/internals.h b/chromium/third_party/blink/renderer/core/testing/internals.h
index a42abd87803..f49dfaf4c36 100644
--- a/chromium/third_party/blink/renderer/core/testing/internals.h
+++ b/chromium/third_party/blink/renderer/core/testing/internals.h
@@ -540,6 +540,10 @@ class Internals final : public ScriptWrappable {
String unscopableMethod();
void setCapsLockState(bool enabled);
+ void setPseudoClassState(Element* element,
+ const String& pseudo,
+ bool enabled,
+ ExceptionState& exception_state);
bool setScrollbarVisibilityInScrollableArea(Node*, bool visible);
@@ -597,6 +601,8 @@ class Internals final : public ScriptWrappable {
void setDeviceEmulationScale(float scale, ExceptionState&);
+ String getDocumentAgentId(Document*);
+
private:
Document* ContextDocument() 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 f9a7aaba97b..bb24d2277a5 100644
--- a/chromium/third_party/blink/renderer/core/testing/internals.idl
+++ b/chromium/third_party/blink/renderer/core/testing/internals.idl
@@ -370,6 +370,9 @@
void setCapsLockState(boolean enabled);
+ // pseudo: One of ":focus", ":focus-within", ":active", and ":hover".
+ [RaisesException] void setPseudoClassState(Element element, DOMString pseudo, boolean enabled);
+
// Returns whether the scrollbar was able to be shown or hidden; not all platforms
// support overlay scrollbars.
boolean setScrollbarVisibilityInScrollableArea(Node node, boolean visible);
@@ -433,4 +436,10 @@
// Sets the scale for devtools device emulation.
[RaisesException] void setDeviceEmulationScale(float scale);
+
+ // Return a string that identifies |document|'s WindowAgent. You can use it
+ // to distinguish different Agent instances (perhaps in a remote process).
+ // The returned string is composed of the process ID and the memory address
+ // of the Agent object.
+ DOMString getDocumentAgentId(Document document);
};
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 fedccd43776..50ecfd89d9f 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
@@ -14,8 +14,11 @@
namespace blink {
-NullExecutionContext::NullExecutionContext()
- : ExecutionContext(v8::Isolate::GetCurrent(), nullptr),
+NullExecutionContext::NullExecutionContext(
+ OriginTrialContext* origin_trial_context)
+ : ExecutionContext(v8::Isolate::GetCurrent(),
+ nullptr,
+ origin_trial_context),
tasks_need_pause_(false),
is_secure_context_(true),
scheduler_(scheduler::CreateDummyFrameScheduler()) {}
diff --git a/chromium/third_party/blink/renderer/core/testing/null_execution_context.h b/chromium/third_party/blink/renderer/core/testing/null_execution_context.h
index 59fc259dd46..06a6b41114f 100644
--- a/chromium/third_party/blink/renderer/core/testing/null_execution_context.h
+++ b/chromium/third_party/blink/renderer/core/testing/null_execution_context.h
@@ -23,7 +23,7 @@ class NullExecutionContext
USING_GARBAGE_COLLECTED_MIXIN(NullExecutionContext);
public:
- NullExecutionContext();
+ NullExecutionContext(OriginTrialContext* origin_trial_context = nullptr);
~NullExecutionContext() override;
void SetURL(const KURL& url) { url_ = url; }
@@ -44,7 +44,6 @@ class NullExecutionContext
bool TasksNeedPause() override { return tasks_need_pause_; }
void SetTasksNeedPause(bool flag) { tasks_need_pause_ = flag; }
- void DidUpdateSecurityOrigin() override {}
SecurityContext& GetSecurityContext() final { return *this; }
const SecurityContext& GetSecurityContext() const final { return *this; }
DOMTimerCoordinator* Timers() override { return nullptr; }
@@ -69,6 +68,8 @@ class NullExecutionContext
void CountUse(mojom::WebFeature) override {}
void CountDeprecation(mojom::WebFeature) override {}
+ void SetSandboxFlags(WebSandboxFlags flags) { sandbox_flags_ = flags; }
+
using SecurityContext::GetSecurityOrigin;
using SecurityContext::GetContentSecurityPolicy;
diff --git a/chromium/third_party/blink/renderer/core/testing/origin_trials_test_partial.h b/chromium/third_party/blink/renderer/core/testing/origin_trials_test_partial.h
index 5ebf2255aa0..ca2807862ee 100644
--- a/chromium/third_party/blink/renderer/core/testing/origin_trials_test_partial.h
+++ b/chromium/third_party/blink/renderer/core/testing/origin_trials_test_partial.h
@@ -5,7 +5,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_TESTING_ORIGIN_TRIALS_TEST_PARTIAL_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_TESTING_ORIGIN_TRIALS_TEST_PARTIAL_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
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 f4745dc8f68..55577cb8693 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
@@ -4,12 +4,15 @@
#include "third_party/blink/renderer/core/testing/page_test_base.h"
+#include "base/test/bind_test_util.h"
+#include "base/time/default_tick_clock.h"
#include "third_party/blink/renderer/bindings/core/v8/string_or_array_buffer_or_array_buffer_view.h"
#include "third_party/blink/renderer/core/css/font_face_descriptors.h"
#include "third_party/blink/renderer/core/css/font_face_set_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/frame/local_frame_view.h"
+#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/html/html_element.h"
#include "third_party/blink/renderer/platform/shared_buffer.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
@@ -20,9 +23,20 @@ PageTestBase::PageTestBase() = default;
PageTestBase::~PageTestBase() = default;
+void PageTestBase::EnableCompositing() {
+ DCHECK(!dummy_page_holder_)
+ << "EnableCompositing() must be called before set up";
+ enable_compositing_ = true;
+}
+
void PageTestBase::SetUp() {
DCHECK(!dummy_page_holder_) << "Page should be set up only once";
- dummy_page_holder_ = std::make_unique<DummyPageHolder>(IntSize(800, 600));
+ auto setter = base::BindLambdaForTesting([&](Settings& settings) {
+ if (enable_compositing_)
+ settings.SetAcceleratedCompositingEnabled(true);
+ });
+ dummy_page_holder_ = std::make_unique<DummyPageHolder>(
+ IntSize(800, 600), nullptr, nullptr, std::move(setter), GetTickClock());
// Use no-quirks (ake "strict") mode by default.
GetDocument().SetCompatibilityMode(Document::kNoQuirksMode);
@@ -33,7 +47,12 @@ void PageTestBase::SetUp() {
void PageTestBase::SetUp(IntSize size) {
DCHECK(!dummy_page_holder_) << "Page should be set up only once";
- dummy_page_holder_ = std::make_unique<DummyPageHolder>(size);
+ auto setter = base::BindLambdaForTesting([&](Settings& settings) {
+ if (enable_compositing_)
+ settings.SetAcceleratedCompositingEnabled(true);
+ });
+ dummy_page_holder_ = std::make_unique<DummyPageHolder>(
+ size, nullptr, nullptr, std::move(setter), GetTickClock());
// Use no-quirks (ake "strict") mode by default.
GetDocument().SetCompatibilityMode(Document::kNoQuirksMode);
@@ -47,8 +66,15 @@ void PageTestBase::SetupPageWithClients(
LocalFrameClient* local_frame_client,
FrameSettingOverrideFunction setting_overrider) {
DCHECK(!dummy_page_holder_) << "Page should be set up only once";
+ auto setter = base::BindLambdaForTesting([&](Settings& settings) {
+ if (setting_overrider)
+ setting_overrider(settings);
+ if (enable_compositing_)
+ settings.SetAcceleratedCompositingEnabled(true);
+ });
dummy_page_holder_ = std::make_unique<DummyPageHolder>(
- IntSize(800, 600), clients, local_frame_client, setting_overrider);
+ IntSize(800, 600), clients, local_frame_client, std::move(setter),
+ GetTickClock());
// Use no-quirks (ake "strict") mode by default.
GetDocument().SetCompatibilityMode(Document::kNoQuirksMode);
@@ -105,15 +131,35 @@ void PageTestBase::SetBodyInnerHTML(const String& body_content) {
}
void PageTestBase::SetBodyContent(const std::string& body_content) {
- SetBodyInnerHTML(String::FromUTF8(body_content.c_str()));
+ SetBodyInnerHTML(String::FromUTF8(body_content));
}
void PageTestBase::SetHtmlInnerHTML(const std::string& html_content) {
GetDocument().documentElement()->SetInnerHTMLFromString(
- String::FromUTF8(html_content.c_str()));
+ String::FromUTF8(html_content));
UpdateAllLifecyclePhasesForTest();
}
+void PageTestBase::NavigateTo(const KURL& url,
+ const String& feature_policy_header,
+ const String& csp_header) {
+ auto params =
+ WebNavigationParams::CreateWithHTMLBuffer(SharedBuffer::Create(), url);
+ if (!feature_policy_header.IsEmpty()) {
+ params->response.SetHttpHeaderField(http_names::kFeaturePolicy,
+ feature_policy_header);
+ }
+ if (!csp_header.IsEmpty()) {
+ params->response.SetHttpHeaderField(http_names::kContentSecurityPolicy,
+ csp_header);
+ }
+ GetFrame().Loader().CommitNavigation(std::move(params),
+ nullptr /* extra_data */);
+
+ blink::test::RunPendingTasks();
+ ASSERT_EQ(url.GetString(), GetDocument().Url().GetString());
+}
+
void PageTestBase::UpdateAllLifecyclePhasesForTest() {
GetDocument().View()->UpdateAllLifecyclePhases(
DocumentLifecycle::LifecycleUpdateReason::kTest);
@@ -146,4 +192,9 @@ void PageTestBase::EnablePlatform() {
ScopedTestingPlatformSupport<TestingPlatformSupportWithMockScheduler>>();
}
+const base::TickClock* PageTestBase::GetTickClock() {
+ return platform_ ? platform()->test_task_runner()->GetMockTickClock()
+ : base::DefaultTickClock::GetInstance();
+}
+
} // namespace blink
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 a88ee4874fd..b15cbd7957e 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
@@ -9,6 +9,10 @@
#include "third_party/blink/renderer/core/testing/dummy_page_holder.h"
#include "third_party/blink/renderer/platform/testing/testing_platform_support_with_mock_scheduler.h"
+namespace base {
+class TickClock;
+}
+
namespace blink {
class Document;
@@ -21,9 +25,13 @@ class PageTestBase : public testing::Test {
PageTestBase();
~PageTestBase() override;
+ void EnableCompositing();
+
void SetUp() override;
void TearDown() override;
+ using FrameSettingOverrideFunction = void (*)(Settings&);
+
void SetUp(IntSize);
void SetupPageWithClients(Page::PageClients* = nullptr,
LocalFrameClient* = nullptr,
@@ -33,6 +41,12 @@ class PageTestBase : public testing::Test {
void SetBodyInnerHTML(const String&);
void SetHtmlInnerHTML(const std::string&);
+ // Navigate to |url| providing an empty response but
+ // URL and security origin of the Document will be set to |url|.
+ void NavigateTo(const KURL& url,
+ const String& feature_policy_header = String(),
+ const String& csp_header = String());
+
Document& GetDocument() const;
Page& GetPage() const;
LocalFrame& GetFrame() const;
@@ -56,6 +70,13 @@ class PageTestBase : public testing::Test {
void LoadAhem();
void EnablePlatform();
+ // Used by subclasses to provide a different tick clock. At the moment is only
+ // used to initialize DummyPageHolder. Note that subclasses calling
+ // EnablePlatform() do not need to redefine this because the platform's mock
+ // tick clock will be automatically used (see the default implementation in
+ // the source file).
+ virtual const base::TickClock* GetTickClock();
+
ScopedTestingPlatformSupport<TestingPlatformSupportWithMockScheduler>&
platform() {
return *platform_;
@@ -68,6 +89,7 @@ class PageTestBase : public testing::Test {
ScopedTestingPlatformSupport<TestingPlatformSupportWithMockScheduler>>
platform_;
std::unique_ptr<DummyPageHolder> dummy_page_holder_;
+ bool enable_compositing_ = false;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/testing/sim/sim_canvas.h b/chromium/third_party/blink/renderer/core/testing/sim/sim_canvas.h
index 64a92cd54f0..eaf713f1552 100644
--- a/chromium/third_party/blink/renderer/core/testing/sim/sim_canvas.h
+++ b/chromium/third_party/blink/renderer/core/testing/sim/sim_canvas.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_TESTING_SIM_SIM_CANVAS_H_
#include "third_party/blink/renderer/platform/graphics/color.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
#include "third_party/skia/include/core/SkCanvas.h"
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 f797e92e592..ea86a23709f 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
@@ -23,6 +23,7 @@ namespace blink {
SimCompositor::SimCompositor() {
LocalFrameView::SetInitialTracksPaintInvalidationsForTesting(true);
+ last_frame_time_ = base::TimeTicks::Now();
}
SimCompositor::~SimCompositor() {
@@ -38,11 +39,6 @@ void SimCompositor::SetWebView(
layer_tree_view_ = &layer_tree_view;
test_web_view_client_ = &view_client;
test_web_widget_client_ = &widget_client;
-
- // 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_->DeferMainFrameUpdateForTesting();
}
SimCanvas::Commands SimCompositor::BeginFrame(double time_delta_in_seconds) {
diff --git a/chromium/third_party/blink/renderer/core/testing/sim/sim_network.cc b/chromium/third_party/blink/renderer/core/testing/sim/sim_network.cc
index 0dfea38c006..637f3e904e2 100644
--- a/chromium/third_party/blink/renderer/core/testing/sim/sim_network.cc
+++ b/chromium/third_party/blink/renderer/core/testing/sim/sim_network.cc
@@ -77,15 +77,14 @@ void SimNetwork::DidFail(WebURLLoaderClient* client,
}
void SimNetwork::DidFinishLoading(WebURLLoaderClient* client,
- TimeTicks finish_time,
+ base::TimeTicks finish_time,
int64_t total_encoded_data_length,
int64_t total_encoded_body_length,
int64_t total_decoded_body_length) {
if (!current_request_) {
client->DidFinishLoading(finish_time, total_encoded_data_length,
total_encoded_body_length,
- total_decoded_body_length, false,
- std::vector<network::cors::PreflightTimingInfo>());
+ total_decoded_body_length, false, {});
return;
}
current_request_ = nullptr;
diff --git a/chromium/third_party/blink/renderer/core/testing/sim/sim_network.h b/chromium/third_party/blink/renderer/core/testing/sim/sim_network.h
index 56f424d3c24..0257c166451 100644
--- a/chromium/third_party/blink/renderer/core/testing/sim/sim_network.h
+++ b/chromium/third_party/blink/renderer/core/testing/sim/sim_network.h
@@ -46,7 +46,7 @@ class SimNetwork final : public WebURLLoaderTestDelegate {
int64_t total_encoded_body_length,
int64_t total_decoded_body_length) override;
void DidFinishLoading(WebURLLoaderClient*,
- TimeTicks finish_time,
+ base::TimeTicks finish_time,
int64_t total_encoded_data_length,
int64_t total_encoded_body_length,
int64_t total_decoded_body_length) override;
diff --git a/chromium/third_party/blink/renderer/core/testing/sim/sim_page.h b/chromium/third_party/blink/renderer/core/testing/sim/sim_page.h
index a2c4c57f31d..efd9c0e89a5 100644
--- a/chromium/third_party/blink/renderer/core/testing/sim/sim_page.h
+++ b/chromium/third_party/blink/renderer/core/testing/sim/sim_page.h
@@ -6,17 +6,15 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_TESTING_SIM_SIM_PAGE_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/allocator/allocator.h"
namespace blink {
class Page;
class SimPage final {
- DISALLOW_NEW();
-
public:
- explicit SimPage();
+ SimPage();
~SimPage();
void SetPage(Page*);
diff --git a/chromium/third_party/blink/renderer/core/testing/sim/sim_request.cc b/chromium/third_party/blink/renderer/core/testing/sim/sim_request.cc
index 41d6bc0e96f..f078561fcae 100644
--- a/chromium/third_party/blink/renderer/core/testing/sim/sim_request.cc
+++ b/chromium/third_party/blink/renderer/core/testing/sim/sim_request.cc
@@ -4,11 +4,11 @@
#include "third_party/blink/renderer/core/testing/sim/sim_request.h"
-#include <vector>
#include "third_party/blink/public/platform/web_url_loader_client.h"
#include "third_party/blink/renderer/core/testing/sim/sim_network.h"
#include "third_party/blink/renderer/platform/loader/static_data_navigation_body_loader.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
+#include "third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h"
namespace blink {
@@ -65,18 +65,14 @@ void SimRequestBase::StartInternal() {
}
void SimRequestBase::Write(const String& data) {
- if (!started_)
- ServePending();
- DCHECK(started_);
- DCHECK(!error_);
- total_encoded_data_length_ += data.length();
- if (navigation_body_loader_)
- navigation_body_loader_->Write(data.Utf8().data(), data.length());
- else
- client_->DidReceiveData(data.Utf8().data(), data.length());
+ WriteInternal(StringUTF8Adaptor(data));
}
void SimRequestBase::Write(const Vector<char>& data) {
+ WriteInternal(data);
+}
+
+void SimRequestBase::WriteInternal(base::span<const char> data) {
if (!started_)
ServePending();
DCHECK(started_);
@@ -101,10 +97,9 @@ void SimRequestBase::Finish() {
navigation_body_loader_->Finish();
} else {
// TODO(esprehn): Is claiming a request time of 0 okay for tests?
- client_->DidFinishLoading(
- TimeTicks(), total_encoded_data_length_, total_encoded_data_length_,
- total_encoded_data_length_, false,
- std::vector<network::cors::PreflightTimingInfo>());
+ client_->DidFinishLoading(base::TimeTicks(), total_encoded_data_length_,
+ total_encoded_data_length_,
+ total_encoded_data_length_, false, {});
}
}
Reset();
diff --git a/chromium/third_party/blink/renderer/core/testing/sim/sim_request.h b/chromium/third_party/blink/renderer/core/testing/sim/sim_request.h
index f1c116c181c..cd2083569c1 100644
--- a/chromium/third_party/blink/renderer/core/testing/sim/sim_request.h
+++ b/chromium/third_party/blink/renderer/core/testing/sim/sim_request.h
@@ -67,6 +67,9 @@ class SimRequestBase {
void Reset();
+ // Internal function to write a chunk of the response body
+ void WriteInternal(base::span<const char>);
+
// Used by SimNetwork.
void DidReceiveResponse(WebURLLoaderClient*, const WebURLResponse&);
void DidFail(const WebURLError&);
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 e29d395a9b4..f0bd794a2ba 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
@@ -18,11 +18,7 @@
namespace blink {
-SimTest::SimTest()
- : // SimCompositor overrides the LayerTreeViewDelegate to respond to
- // BeginMainFrame(), which will update and paint the main frame of the
- // WebViewImpl given to SetWebView().
- web_widget_client_(&compositor_) {
+SimTest::SimTest() {
Document::SetThreadedParsingEnabledForTesting(false);
// Use the mock theme to get more predictable code paths, this also avoids
// the OS callbacks in ScrollAnimatorMac which can schedule frames
@@ -42,9 +38,6 @@ SimTest::SimTest()
}
SimTest::~SimTest() {
- // Pump the message loop to process the load event.
- test::RunPendingTasks();
-
Document::SetThreadedParsingEnabledForTesting(true);
WebTestSupport::SetMockThemeEnabledForTest(false);
ScrollbarTheme::SetMockScrollbarsEnabled(false);
@@ -55,11 +48,40 @@ SimTest::~SimTest() {
void SimTest::SetUp() {
Test::SetUp();
- web_view_helper_.Initialize(&web_frame_client_, &web_view_client_,
- &web_widget_client_);
- compositor_.SetWebView(WebView(), *web_widget_client_.layer_tree_view(),
- web_view_client_, web_widget_client_);
- page_.SetPage(WebView().GetPage());
+ // SimCompositor overrides the LayerTreeViewDelegate to respond to
+ // BeginMainFrame(), which will update and paint the main frame of the
+ // WebViewImpl given to SetWebView().
+ network_ = std::make_unique<SimNetwork>();
+ compositor_ = std::make_unique<SimCompositor>();
+ web_frame_client_ =
+ std::make_unique<frame_test_helpers::TestWebFrameClient>();
+ web_widget_client_ =
+ std::make_unique<frame_test_helpers::TestWebWidgetClient>(
+ compositor_.get());
+ web_view_client_ = std::make_unique<frame_test_helpers::TestWebViewClient>();
+ page_ = std::make_unique<SimPage>();
+ web_view_helper_ = std::make_unique<frame_test_helpers::WebViewHelper>();
+
+ web_view_helper_->Initialize(web_frame_client_.get(), web_view_client_.get(),
+ web_widget_client_.get());
+ compositor_->SetWebView(WebView(), *web_widget_client_->layer_tree_view(),
+ *web_view_client_, *web_widget_client_);
+ page_->SetPage(WebView().GetPage());
+}
+
+void SimTest::TearDown() {
+ // Pump the message loop to process the load event.
+ test::RunPendingTasks();
+
+ // Shut down this stuff before settings change to keep the world
+ // consistent, and before the subclass tears down.
+ web_view_helper_.reset();
+ page_.reset();
+ web_view_client_.reset();
+ web_widget_client_.reset();
+ web_frame_client_.reset();
+ compositor_.reset();
+ network_.reset();
}
void SimTest::LoadURL(const String& url_string) {
@@ -78,7 +100,7 @@ LocalDOMWindow& SimTest::Window() {
}
SimPage& SimTest::GetPage() {
- return page_;
+ return *page_;
}
Document& SimTest::GetDocument() {
@@ -86,7 +108,7 @@ Document& SimTest::GetDocument() {
}
WebViewImpl& SimTest::WebView() {
- return *web_view_helper_.GetWebView();
+ return *web_view_helper_->GetWebView();
}
WebLocalFrameImpl& SimTest::MainFrame() {
@@ -94,23 +116,23 @@ WebLocalFrameImpl& SimTest::MainFrame() {
}
frame_test_helpers::TestWebViewClient& SimTest::WebViewClient() {
- return web_view_client_;
+ return *web_view_client_;
}
frame_test_helpers::TestWebWidgetClient& SimTest::WebWidgetClient() {
- return web_widget_client_;
+ return *web_widget_client_;
}
frame_test_helpers::TestWebFrameClient& SimTest::WebFrameClient() {
- return web_frame_client_;
+ return *web_frame_client_;
}
SimCompositor& SimTest::Compositor() {
- return compositor_;
+ return *compositor_;
}
Vector<String>& SimTest::ConsoleMessages() {
- return web_frame_client_.ConsoleMessages();
+ return web_frame_client_->ConsoleMessages();
}
} // namespace blink
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 b2fd25e0c17..b235acbaa2f 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
@@ -25,6 +25,7 @@ class SimTest : public testing::Test {
~SimTest() override;
void SetUp() override;
+ void TearDown() override;
void LoadURL(const String& url);
@@ -44,13 +45,16 @@ class SimTest : public testing::Test {
Vector<String>& ConsoleMessages();
private:
- SimNetwork network_;
- SimCompositor compositor_;
- frame_test_helpers::TestWebFrameClient web_frame_client_;
- frame_test_helpers::TestWebWidgetClient web_widget_client_;
- frame_test_helpers::TestWebViewClient web_view_client_;
- SimPage page_;
- frame_test_helpers::WebViewHelper web_view_helper_;
+ // These are unique_ptrs in order to destroy them in TearDown. Subclasses
+ // may override Platform::Current() and these must shutdown before the
+ // subclass destructor.
+ std::unique_ptr<SimNetwork> network_;
+ std::unique_ptr<SimCompositor> compositor_;
+ std::unique_ptr<frame_test_helpers::TestWebFrameClient> web_frame_client_;
+ std::unique_ptr<frame_test_helpers::TestWebWidgetClient> web_widget_client_;
+ std::unique_ptr<frame_test_helpers::TestWebViewClient> web_view_client_;
+ std::unique_ptr<SimPage> page_;
+ std::unique_ptr<frame_test_helpers::WebViewHelper> web_view_helper_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/testing/worker_internals.cc b/chromium/third_party/blink/renderer/core/testing/worker_internals.cc
index af4e51ba453..1561b4cc8b9 100644
--- a/chromium/third_party/blink/renderer/core/testing/worker_internals.cc
+++ b/chromium/third_party/blink/renderer/core/testing/worker_internals.cc
@@ -6,10 +6,10 @@
#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/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/testing/origin_trials_test.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/instrumentation/use_counter.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/timing/BUILD.gn b/chromium/third_party/blink/renderer/core/timing/BUILD.gn
index 75005ad3b19..353c444f015 100644
--- a/chromium/third_party/blink/renderer/core/timing/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/timing/BUILD.gn
@@ -10,6 +10,8 @@ blink_core_sources("timing") {
"dom_window_performance.h",
"event_timing.cc",
"event_timing.h",
+ "largest_contentful_paint.cc",
+ "largest_contentful_paint.h",
"layout_shift.cc",
"layout_shift.h",
"memory_info.cc",
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 3110fb11531..f45a5a3c10c 100644
--- a/chromium/third_party/blink/renderer/core/timing/event_timing.cc
+++ b/chromium/third_party/blink/renderer/core/timing/event_timing.cc
@@ -12,14 +12,13 @@
#include "third_party/blink/renderer/core/timing/dom_window_performance.h"
#include "third_party/blink/renderer/core/timing/performance_event_timing.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
-#include "third_party/blink/renderer/platform/wtf/time.h"
namespace {
const base::TickClock* g_clock_for_testing = nullptr;
static base::TimeTicks Now() {
return g_clock_for_testing ? g_clock_for_testing->NowTicks()
- : CurrentTimeTicks();
+ : base::TimeTicks::Now();
}
} // namespace
@@ -49,18 +48,12 @@ bool ShouldReportForEventTiming(WindowPerformance* performance) {
performance->GetExecutionContext()))
return false;
- if (performance->HasObserverFor(PerformanceEntry::kEvent))
- return true;
- if (performance->ShouldBufferEntries() &&
- !performance->IsEventTimingBufferFull()) {
- return true;
- }
-
- return false;
+ return (!performance->IsEventTimingBufferFull() ||
+ performance->HasObserverFor(PerformanceEntry::kEvent));
}
-EventTiming::EventTiming(TimeTicks processing_start,
- TimeTicks event_timestamp,
+EventTiming::EventTiming(base::TimeTicks processing_start,
+ base::TimeTicks event_timestamp,
WindowPerformance* performance)
: processing_start_(processing_start),
event_timestamp_(event_timestamp),
@@ -79,7 +72,7 @@ std::unique_ptr<EventTiming> EventTiming::Create(LocalDOMWindow* window,
if (!should_report_for_event_timing && !should_log_event)
return nullptr;
- TimeTicks event_timestamp =
+ base::TimeTicks event_timestamp =
event.IsPointerEvent() ? ToPointerEvent(&event)->OldestPlatformTimeStamp()
: event.PlatformTimeStamp();
diff --git a/chromium/third_party/blink/renderer/core/timing/event_timing.h b/chromium/third_party/blink/renderer/core/timing/event_timing.h
index 9768e3fd176..a6d7eef4bd4 100644
--- a/chromium/third_party/blink/renderer/core/timing/event_timing.h
+++ b/chromium/third_party/blink/renderer/core/timing/event_timing.h
@@ -9,7 +9,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/timing/window_performance.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
@@ -28,8 +28,8 @@ class CORE_EXPORT EventTiming final {
// Returns an object only if the event is relevant for the EventTiming API.
static std::unique_ptr<EventTiming> Create(LocalDOMWindow*, const Event&);
- explicit EventTiming(TimeTicks processing_start,
- TimeTicks event_timestamp,
+ explicit EventTiming(base::TimeTicks processing_start,
+ base::TimeTicks event_timestamp,
WindowPerformance* performance);
// Notifies the Performance object that the event has been dispatched.
@@ -40,9 +40,9 @@ class CORE_EXPORT EventTiming final {
private:
// The time the first event handler or default action started to execute.
- TimeTicks processing_start_;
+ base::TimeTicks processing_start_;
// The event timestamp to be used in EventTiming and in histograms.
- TimeTicks event_timestamp_;
+ base::TimeTicks event_timestamp_;
Persistent<WindowPerformance> performance_;
DISALLOW_COPY_AND_ASSIGN(EventTiming);
diff --git a/chromium/third_party/blink/renderer/core/timing/largest_contentful_paint.cc b/chromium/third_party/blink/renderer/core/timing/largest_contentful_paint.cc
new file mode 100644
index 00000000000..0a4899238a3
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/timing/largest_contentful_paint.cc
@@ -0,0 +1,65 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/timing/largest_contentful_paint.h"
+
+#include "third_party/blink/renderer/bindings/core/v8/v8_object_builder.h"
+#include "third_party/blink/renderer/core/performance_entry_names.h"
+#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h"
+
+namespace blink {
+
+LargestContentfulPaint::LargestContentfulPaint(double start_time,
+ double render_time,
+ uint64_t size,
+ double load_time,
+ const AtomicString& id,
+ const String& url,
+ Element* element)
+ : PerformanceEntry(g_empty_atom, start_time, start_time),
+ size_(size),
+ render_time_(render_time),
+ load_time_(load_time),
+ id_(id),
+ url_(url),
+ element_(element) {}
+
+LargestContentfulPaint::~LargestContentfulPaint() = default;
+
+AtomicString LargestContentfulPaint::entryType() const {
+ return performance_entry_names::kLargestContentfulPaint;
+}
+
+PerformanceEntryType LargestContentfulPaint::EntryTypeEnum() const {
+ return PerformanceEntry::EntryType::kLargestContentfulPaint;
+}
+
+Element* LargestContentfulPaint::element() const {
+ if (!element_ || !element_->isConnected() || element_->IsInShadowTree())
+ return nullptr;
+
+ // Do not expose |element_| when the document is not 'fully active'.
+ const Document& document = element_->GetDocument();
+ if (!document.IsActive() || !document.GetFrame())
+ return nullptr;
+
+ return element_;
+}
+
+void LargestContentfulPaint::BuildJSONValue(V8ObjectBuilder& builder) const {
+ PerformanceEntry::BuildJSONValue(builder);
+ builder.Add("size", size_);
+ builder.Add("renderTime", render_time_);
+ builder.Add("loadTime", load_time_);
+ builder.Add("id", id_);
+ builder.Add("url", url_);
+ builder.Add("element", element());
+}
+
+void LargestContentfulPaint::Trace(blink::Visitor* visitor) {
+ visitor->Trace(element_);
+ PerformanceEntry::Trace(visitor);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/timing/largest_contentful_paint.h b/chromium/third_party/blink/renderer/core/timing/largest_contentful_paint.h
new file mode 100644
index 00000000000..ae34beaeaa8
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/timing/largest_contentful_paint.h
@@ -0,0 +1,54 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_TIMING_LARGEST_CONTENTFUL_PAINT_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_TIMING_LARGEST_CONTENTFUL_PAINT_H_
+
+#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/dom/element.h"
+#include "third_party/blink/renderer/core/timing/performance_entry.h"
+
+namespace blink {
+
+// Exposes the Largest Contenful Paint, computed as described in
+// https://github.com/WICG/LargestContentfulPaint.
+class CORE_EXPORT LargestContentfulPaint final : public PerformanceEntry {
+ DEFINE_WRAPPERTYPEINFO();
+
+ public:
+ LargestContentfulPaint(double start_time,
+ double render_time,
+ uint64_t size,
+ double load_time,
+ const AtomicString& id,
+ const String& url,
+ Element*);
+ ~LargestContentfulPaint() override;
+
+ AtomicString entryType() const override;
+ PerformanceEntryType EntryTypeEnum() const override;
+
+ uint64_t size() const { return size_; }
+ DOMHighResTimeStamp renderTime() const { return render_time_; }
+ DOMHighResTimeStamp loadTime() const { return load_time_; }
+ const AtomicString& id() const { return id_; }
+ const String& url() const { return url_; }
+ Element* element() const;
+
+ void Trace(blink::Visitor*) override;
+
+ private:
+ void BuildJSONValue(V8ObjectBuilder&) const override;
+
+ uint64_t size_;
+ DOMHighResTimeStamp render_time_;
+ DOMHighResTimeStamp load_time_;
+ AtomicString id_;
+ String url_;
+ WeakMember<Element> element_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_TIMING_LARGEST_CONTENTFUL_PAINT_H_
diff --git a/chromium/third_party/blink/renderer/core/timing/largest_contentful_paint.idl b/chromium/third_party/blink/renderer/core/timing/largest_contentful_paint.idl
new file mode 100644
index 00000000000..54cdaef5c43
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/timing/largest_contentful_paint.idl
@@ -0,0 +1,16 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// https://github.com/WICG/LargestContentfulPaint
+[Exposed=Window, RuntimeEnabled=LargestContentfulPaint]
+interface LargestContentfulPaint : PerformanceEntry {
+ readonly attribute DOMHighResTimeStamp renderTime;
+ readonly attribute DOMHighResTimeStamp loadTime;
+ readonly attribute unsigned long long size;
+ readonly attribute DOMString id;
+ readonly attribute DOMString url;
+ readonly attribute Element? element;
+
+ [CallWith=ScriptState, ImplementedAs=toJSONForBinding] object toJSON();
+};
diff --git a/chromium/third_party/blink/renderer/core/timing/layout_shift.cc b/chromium/third_party/blink/renderer/core/timing/layout_shift.cc
index a842adc2cdc..fd228888103 100644
--- a/chromium/third_party/blink/renderer/core/timing/layout_shift.cc
+++ b/chromium/third_party/blink/renderer/core/timing/layout_shift.cc
@@ -10,8 +10,14 @@
namespace blink {
-LayoutShift::LayoutShift(double start_time, double value)
- : PerformanceEntry(g_empty_atom, start_time, start_time), value_(value) {}
+LayoutShift::LayoutShift(double start_time,
+ double value,
+ bool input_detected,
+ double input_timestamp)
+ : PerformanceEntry(g_empty_atom, start_time, start_time),
+ value_(value),
+ had_recent_input_(input_detected),
+ most_recent_input_timestamp_(input_timestamp) {}
LayoutShift::~LayoutShift() = default;
@@ -20,12 +26,14 @@ AtomicString LayoutShift::entryType() const {
}
PerformanceEntryType LayoutShift::EntryTypeEnum() const {
- return PerformanceEntry::EntryType::kLayoutJank;
+ return PerformanceEntry::EntryType::kLayoutShift;
}
void LayoutShift::BuildJSONValue(V8ObjectBuilder& builder) const {
PerformanceEntry::BuildJSONValue(builder);
builder.Add("value", value_);
+ builder.Add("hadRecentInput", had_recent_input_);
+ builder.Add("lastInputTime", most_recent_input_timestamp_);
}
void LayoutShift::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/timing/layout_shift.h b/chromium/third_party/blink/renderer/core/timing/layout_shift.h
index 9652c89ee43..d9dc5a0aa9a 100644
--- a/chromium/third_party/blink/renderer/core/timing/layout_shift.h
+++ b/chromium/third_party/blink/renderer/core/timing/layout_shift.h
@@ -6,6 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_TIMING_LAYOUT_SHIFT_H_
#include "third_party/blink/renderer/core/core_export.h"
+#include "third_party/blink/renderer/core/dom/dom_high_res_time_stamp.h"
#include "third_party/blink/renderer/core/timing/performance_entry.h"
namespace blink {
@@ -16,13 +17,18 @@ class CORE_EXPORT LayoutShift final : public PerformanceEntry {
DEFINE_WRAPPERTYPEINFO();
public:
- LayoutShift(double start_time, double value);
+ LayoutShift(double start_time,
+ double value,
+ bool input_detected,
+ double input_timestamp);
~LayoutShift() override;
AtomicString entryType() const override;
PerformanceEntryType EntryTypeEnum() const override;
double value() const { return value_; }
+ bool hadRecentInput() const { return had_recent_input_; }
+ double lastInputTime() const { return most_recent_input_timestamp_; }
void Trace(blink::Visitor*) override;
@@ -30,6 +36,8 @@ class CORE_EXPORT LayoutShift final : public PerformanceEntry {
void BuildJSONValue(V8ObjectBuilder&) const override;
double value_;
+ bool had_recent_input_;
+ DOMHighResTimeStamp most_recent_input_timestamp_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/timing/layout_shift.idl b/chromium/third_party/blink/renderer/core/timing/layout_shift.idl
index 5c76e69ebaf..639c82dd5dc 100644
--- a/chromium/third_party/blink/renderer/core/timing/layout_shift.idl
+++ b/chromium/third_party/blink/renderer/core/timing/layout_shift.idl
@@ -2,10 +2,12 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// https://gist.github.com/skobes/2f296da1b0a88cc785a4bf10a42bca07
+// https://wicg.github.io/layout-instability/#sec-layout-shift
[Exposed=Window, RuntimeEnabled=LayoutInstabilityAPI]
interface LayoutShift : PerformanceEntry {
readonly attribute double value;
+ readonly attribute boolean hadRecentInput;
+ readonly attribute DOMHighResTimeStamp lastInputTime;
// TODO(peria): toJSON is not in spec. https://crbug.com/736332
[CallWith=ScriptState, ImplementedAs=toJSONForBinding] object toJSON();
diff --git a/chromium/third_party/blink/renderer/core/timing/memory_info.cc b/chromium/third_party/blink/renderer/core/timing/memory_info.cc
index 5ebb0aea989..1db6689e736 100644
--- a/chromium/third_party/blink/renderer/core/timing/memory_info.cc
+++ b/chromium/third_party/blink/renderer/core/timing/memory_info.cc
@@ -43,8 +43,10 @@
namespace blink {
-static constexpr TimeDelta kTwentyMinutes = TimeDelta::FromMinutes(20);
-static constexpr TimeDelta kFiftyMs = TimeDelta::FromMilliseconds(50);
+static constexpr base::TimeDelta kTwentyMinutes =
+ base::TimeDelta::FromMinutes(20);
+static constexpr base::TimeDelta kFiftyMs =
+ base::TimeDelta::FromMilliseconds(50);
static void GetHeapSize(HeapInfo& info) {
v8::HeapStatistics heap_statistics;
@@ -54,10 +56,6 @@ static void GetHeapSize(HeapInfo& info) {
info.total_js_heap_size =
heap_statistics.total_physical_size() + heap_statistics.external_memory();
info.js_heap_size_limit = heap_statistics.heap_size_limit();
- info.used_js_heap_size_without_external_memory =
- heap_statistics.used_heap_size();
- info.total_js_heap_size_without_external_memory =
- heap_statistics.total_physical_size();
}
class HeapSizeCache {
@@ -86,10 +84,10 @@ class HeapSizeCache {
// to make it more difficult for attackers to compare memory usage before
// and after some event. We limit to once every 50 ms in the Precise case to
// avoid exposing precise GC timings.
- TimeTicks now = clock_->NowTicks();
- TimeDelta delta_allowed = precision == MemoryInfo::Precision::Bucketized
- ? kTwentyMinutes
- : kFiftyMs;
+ base::TimeTicks now = clock_->NowTicks();
+ base::TimeDelta delta_allowed =
+ precision == MemoryInfo::Precision::Bucketized ? kTwentyMinutes
+ : kFiftyMs;
if (!last_update_time_.has_value() ||
now - last_update_time_.value() >= delta_allowed) {
Update(precision);
@@ -105,13 +103,9 @@ class HeapSizeCache {
info_.used_js_heap_size = QuantizeMemorySize(info_.used_js_heap_size);
info_.total_js_heap_size = QuantizeMemorySize(info_.total_js_heap_size);
info_.js_heap_size_limit = QuantizeMemorySize(info_.js_heap_size_limit);
- info_.used_js_heap_size_without_external_memory =
- QuantizeMemorySize(info_.used_js_heap_size_without_external_memory);
- info_.total_js_heap_size_without_external_memory =
- QuantizeMemorySize(info_.total_js_heap_size_without_external_memory);
}
- base::Optional<TimeTicks> last_update_time_;
+ base::Optional<base::TimeTicks> last_update_time_;
const base::TickClock* clock_;
HeapInfo info_;
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 b73e146c3b4..7cc0704a8f7 100644
--- a/chromium/third_party/blink/renderer/core/timing/memory_info.h
+++ b/chromium/third_party/blink/renderer/core/timing/memory_info.h
@@ -34,7 +34,7 @@
#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"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace base {
class TickClock;
@@ -48,9 +48,6 @@ struct HeapInfo {
size_t used_js_heap_size = 0;
size_t total_js_heap_size = 0;
size_t js_heap_size_limit = 0;
- // Values for origin trial: "Legacy Performance Memory Counters".
- size_t used_js_heap_size_without_external_memory = 0;
- size_t total_js_heap_size_without_external_memory = 0;
};
class CORE_EXPORT MemoryInfo final : public ScriptWrappable {
@@ -68,12 +65,6 @@ class CORE_EXPORT MemoryInfo final : public ScriptWrappable {
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; }
- size_t usedJSHeapSizeWithoutExternalMemory() const {
- return info_.used_js_heap_size_without_external_memory;
- }
- size_t totalJSHeapSizeWithoutExternalMemory() const {
- return info_.total_js_heap_size_without_external_memory;
- }
private:
FRIEND_TEST_ALL_PREFIXES(MemoryInfoTest, Bucketized);
diff --git a/chromium/third_party/blink/renderer/core/timing/memory_info.idl b/chromium/third_party/blink/renderer/core/timing/memory_info.idl
index dcac5313267..dbbf246c38d 100644
--- a/chromium/third_party/blink/renderer/core/timing/memory_info.idl
+++ b/chromium/third_party/blink/renderer/core/timing/memory_info.idl
@@ -37,6 +37,4 @@
[Measure] readonly attribute unsigned long long totalJSHeapSize;
[Measure] readonly attribute unsigned long long usedJSHeapSize;
[Measure] readonly attribute unsigned long long jsHeapSizeLimit;
- [RuntimeEnabled=LegacyPerformanceMemoryCounters] readonly attribute unsigned long long usedJSHeapSizeWithoutExternalMemory;
- [RuntimeEnabled=LegacyPerformanceMemoryCounters] readonly attribute unsigned long long totalJSHeapSizeWithoutExternalMemory;
};
diff --git a/chromium/third_party/blink/renderer/core/timing/memory_info_test.cc b/chromium/third_party/blink/renderer/core/timing/memory_info_test.cc
index b0670efce1d..73eb38030e0 100644
--- a/chromium/third_party/blink/renderer/core/timing/memory_info_test.cc
+++ b/chromium/third_party/blink/renderer/core/timing/memory_info_test.cc
@@ -127,7 +127,7 @@ TEST_F(MemoryInfoTest, Bucketized) {
// allocated alive even if GC happens. In practice, the objects only get GC'd
// after we go out of V8TestingScope. But having them in a vector makes it
// impossible for GC to clear them up unexpectedly early.
- std::vector<v8::Local<v8::ArrayBuffer>> objects;
+ Vector<v8::Local<v8::ArrayBuffer>> objects;
MemoryInfoTestScopedMockTime mock_time(MemoryInfo::Precision::Bucketized);
MemoryInfo* bucketized_memory =
@@ -172,7 +172,7 @@ TEST_F(MemoryInfoTest, Bucketized) {
TEST_F(MemoryInfoTest, Precise) {
V8TestingScope scope;
v8::Isolate* isolate = scope.GetIsolate();
- std::vector<v8::Local<v8::ArrayBuffer>> objects;
+ Vector<v8::Local<v8::ArrayBuffer>> objects;
MemoryInfoTestScopedMockTime mock_time(MemoryInfo::Precision::Precise);
MemoryInfo* precise_memory =
@@ -217,7 +217,7 @@ TEST_F(MemoryInfoTest, FlagEnabled) {
ScopedPreciseMemoryInfoForTest precise_memory_info(true);
V8TestingScope scope;
v8::Isolate* isolate = scope.GetIsolate();
- std::vector<v8::Local<v8::ArrayBuffer>> objects;
+ Vector<v8::Local<v8::ArrayBuffer>> objects;
// Using MemoryInfo::Precision::Bucketized to ensure that the runtime-enabled
// flag overrides the Precision passed onto the method.
@@ -240,14 +240,14 @@ TEST_F(MemoryInfoTest, FlagEnabled) {
}
TEST_F(MemoryInfoTest, ZeroTime) {
- // In this test, we make sure that even if the current TimeTicks() value is
- // very close to 0, we still obtain memory information from the first call to
- // MemoryInfo::Create.
+ // In this test, we make sure that even if the current base::TimeTicks() value
+ // is very close to 0, we still obtain memory information from the first call
+ // to MemoryInfo::Create.
MemoryInfoTestScopedMockTime mock_time(MemoryInfo::Precision::Precise);
mock_time.AdvanceClock(base::TimeDelta::FromMicroseconds(100));
V8TestingScope scope;
v8::Isolate* isolate = scope.GetIsolate();
- std::vector<v8::Local<v8::ArrayBuffer>> objects;
+ Vector<v8::Local<v8::ArrayBuffer>> objects;
objects.push_back(v8::ArrayBuffer::New(isolate, 100));
MemoryInfo* precise_memory =
diff --git a/chromium/third_party/blink/renderer/core/timing/performance.cc b/chromium/third_party/blink/renderer/core/timing/performance.cc
index 4196f5cbf35..d51cc94e869 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance.cc
+++ b/chromium/third_party/blink/renderer/core/timing/performance.cc
@@ -43,10 +43,10 @@
#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/core/frame/local_frame.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_load_timing.h"
#include "third_party/blink/renderer/core/loader/document_loader.h"
+#include "third_party/blink/renderer/core/timing/largest_contentful_paint.h"
#include "third_party/blink/renderer/core/timing/layout_shift.h"
#include "third_party/blink/renderer/core/timing/performance_element_timing.h"
#include "third_party/blink/renderer/core/timing/performance_event_timing.h"
@@ -62,6 +62,7 @@
#include "third_party/blink/renderer/core/timing/profiler_group.h"
#include "third_party/blink/renderer/core/timing/profiler_init_options.h"
#include "third_party/blink/renderer/core/timing/time_clamper.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_response.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_timing_info.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
@@ -78,77 +79,6 @@ const SecurityOrigin* GetSecurityOrigin(ExecutionContext* context) {
return nullptr;
}
-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 StringOrPerformanceMeasureOptions& start_or_options) {
- if (start_or_options.IsString()) {
- return StringToNavigationTimingParameterType(
- start_or_options.GetAsString());
- }
- // Since start_or_options cannot be number any more, we don't record number
- // type as MeasureParameterType in UMA any more.
- if (start_or_options.IsPerformanceMeasureOptions())
- return Performance::MeasureParameterType::kObjectObject;
- // null and undefined are undistinguishable in
- // StringOrPerformanceMeasureOptions.
- 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);
-}
-
const Performance::UnifiedClock* DefaultUnifiedClock() {
DEFINE_THREAD_SAFE_STATIC_LOCAL(Performance::UnifiedClock, unified_clock,
(base::DefaultClock::GetInstance(),
@@ -156,6 +86,10 @@ const Performance::UnifiedClock* DefaultUnifiedClock() {
return &unified_clock;
}
+bool IsMeasureOptionsEmpty(const PerformanceMeasureOptions& options) {
+ return !options.hasDetail() && !options.hasEnd() && !options.hasStart();
+}
+
} // namespace
using PerformanceObserverVector = HeapVector<Member<PerformanceObserver>>;
@@ -164,9 +98,10 @@ constexpr size_t kDefaultResourceTimingBufferSize = 250;
constexpr size_t kDefaultEventTimingBufferSize = 150;
constexpr size_t kDefaultElementTimingBufferSize = 150;
constexpr size_t kDefaultLayoutJankBufferSize = 150;
+constexpr size_t kDefaultLargestContenfulPaintSize = 150;
Performance::Performance(
- TimeTicks time_origin,
+ base::TimeTicks time_origin,
scoped_refptr<base::SingleThreadTaskRunner> task_runner)
: resource_timing_buffer_size_limit_(kDefaultResourceTimingBufferSize),
event_timing_buffer_max_size_(kDefaultEventTimingBufferSize),
@@ -212,9 +147,6 @@ PerformanceEntryVector Performance::getEntries() {
PerformanceEntryVector entries;
entries.AppendVector(resource_timing_buffer_);
- entries.AppendVector(event_timing_buffer_);
- entries.AppendVector(element_timing_buffer_);
- entries.AppendVector(layout_jank_buffer_);
if (first_input_timing_)
entries.push_back(first_input_timing_);
if (!navigation_timing_)
@@ -270,8 +202,6 @@ PerformanceEntryVector Performance::getEntriesByTypeInternal(
entries.push_back(resource);
break;
case PerformanceEntry::kElement:
- UseCounter::Count(GetExecutionContext(),
- WebFeature::kElementTimingExplicitlyRequested);
for (const auto& element : element_timing_buffer_)
entries.push_back(element);
break;
@@ -316,12 +246,13 @@ PerformanceEntryVector Performance::getEntriesByTypeInternal(
break;
case PerformanceEntry::kTaskAttribution:
break;
- case PerformanceEntry::kLayoutJank:
- UseCounter::Count(GetExecutionContext(),
- WebFeature::kLayoutJankExplicitlyRequested);
+ case PerformanceEntry::kLayoutShift:
for (const auto& layout_jank : layout_jank_buffer_)
entries.push_back(layout_jank);
break;
+ case PerformanceEntry::kLargestContentfulPaint:
+ entries.AppendVector(largest_contentful_paint_buffer_);
+ break;
case PerformanceEntry::kInvalid:
break;
}
@@ -338,8 +269,14 @@ PerformanceEntryVector Performance::getEntriesByName(
PerformanceEntry::EntryType type =
PerformanceEntry::ToEntryTypeEnum(entry_type);
- if (!entry_type.IsNull() && type == PerformanceEntry::kInvalid)
+ if (!entry_type.IsNull() &&
+ !PerformanceEntry::IsValidTimelineEntryType(type)) {
+ String message = "Deprecated API for given entry type.";
+ GetExecutionContext()->AddConsoleMessage(
+ ConsoleMessage::Create(mojom::ConsoleMessageSource::kJavaScript,
+ mojom::ConsoleMessageLevel::kWarning, message));
return entries;
+ }
if (entry_type.IsNull() || type == PerformanceEntry::kResource) {
for (const auto& resource : resource_timing_buffer_) {
@@ -348,38 +285,6 @@ PerformanceEntryVector Performance::getEntriesByName(
}
}
- if (entry_type.IsNull() || type == PerformanceEntry::kLayoutJank) {
- for (const auto& layout_jank : layout_jank_buffer_) {
- if (layout_jank->name() == name)
- entries.push_back(layout_jank);
- }
- }
- if (type == PerformanceEntry::kLayoutJank) {
- UseCounter::Count(GetExecutionContext(),
- WebFeature::kLayoutJankExplicitlyRequested);
- }
- if (entry_type.IsNull() || type == PerformanceEntry::kElement) {
- for (const auto& element : element_timing_buffer_) {
- if (element->name() == name)
- entries.push_back(element);
- }
- }
- if (type == PerformanceEntry::kElement) {
- UseCounter::Count(GetExecutionContext(),
- WebFeature::kElementTimingExplicitlyRequested);
- }
-
- if (entry_type.IsNull() || type == PerformanceEntry::kEvent) {
- for (const auto& event : event_timing_buffer_) {
- if (event->name() == name)
- entries.push_back(event);
- }
- }
- if (type == PerformanceEntry::kEvent) {
- UseCounter::Count(GetExecutionContext(),
- WebFeature::kEventTimingExplicitlyRequested);
- }
-
if (entry_type.IsNull() || type == PerformanceEntry::kFirstInput) {
if (first_input_timing_ && first_input_timing_->name() == name)
entries.push_back(first_input_timing_);
@@ -527,7 +432,7 @@ WebResourceTimingInfo Performance::GenerateResourceTiming(
result.last_redirect_end_time = last_chained_timing->ReceiveHeadersEnd();
} else {
result.allow_redirect_details = false;
- result.last_redirect_end_time = TimeTicks();
+ result.last_redirect_end_time = base::TimeTicks();
}
if (!result.allow_redirect_details) {
// TODO(https://crbug.com/817691): There was previously a DCHECK that
@@ -541,7 +446,7 @@ WebResourceTimingInfo Performance::GenerateResourceTiming(
}
} else {
result.allow_redirect_details = false;
- result.last_redirect_end_time = TimeTicks();
+ result.last_redirect_end_time = base::TimeTicks();
}
result.transfer_size = info.TransferSize();
@@ -576,7 +481,8 @@ void Performance::AddResourceTiming(const WebResourceTimingInfo& info,
}
if (!resource_timing_buffer_full_event_pending_) {
resource_timing_buffer_full_event_pending_ = true;
- resource_timing_buffer_full_timer_.StartOneShot(TimeDelta(), FROM_HERE);
+ resource_timing_buffer_full_timer_.StartOneShot(base::TimeDelta(),
+ FROM_HERE);
}
resource_timing_secondary_buffer_.push_back(entry);
}
@@ -627,18 +533,16 @@ void Performance::FireResourceTimingBufferFull(TimerBase*) {
}
void Performance::AddElementTimingBuffer(PerformanceElementTiming& entry) {
- element_timing_buffer_.push_back(&entry);
-
- if (IsElementTimingBufferFull())
- DispatchEvent(*Event::Create(event_type_names::kElementtimingbufferfull));
+ if (!IsElementTimingBufferFull()) {
+ element_timing_buffer_.push_back(&entry);
+ }
}
void Performance::AddEventTimingBuffer(PerformanceEventTiming& entry) {
DCHECK(RuntimeEnabledFeatures::EventTimingEnabled(GetExecutionContext()));
- event_timing_buffer_.push_back(&entry);
-
- if (IsEventTimingBufferFull())
- DispatchEvent(*Event::Create(event_type_names::kEventtimingbufferfull));
+ if (!IsEventTimingBufferFull()) {
+ event_timing_buffer_.push_back(&entry);
+ }
}
void Performance::AddLayoutJankBuffer(LayoutShift& entry) {
@@ -646,48 +550,24 @@ void Performance::AddLayoutJankBuffer(LayoutShift& entry) {
layout_jank_buffer_.push_back(&entry);
}
-unsigned Performance::ElementTimingBufferSize() const {
- return element_timing_buffer_.size();
-}
-
-unsigned Performance::EventTimingBufferSize() const {
- return event_timing_buffer_.size();
-}
-
-void Performance::clearElementTimings() {
- element_timing_buffer_.clear();
-}
-
-void Performance::clearEventTimings() {
- event_timing_buffer_.clear();
-}
-
-// TODO(crbug.com/72556): remove Element Timing buffering when shipping the
-// 'buffered' flag.
-void Performance::setElementTimingBufferMaxSize(unsigned size) {
- element_timing_buffer_max_size_ = size;
- if (IsElementTimingBufferFull())
- DispatchEvent(*Event::Create(event_type_names::kElementtimingbufferfull));
-}
-
-// TODO(yoav): EventTiming should follow a simpler buffering model.
-void Performance::setEventTimingBufferMaxSize(unsigned size) {
- event_timing_buffer_max_size_ = size;
- if (IsEventTimingBufferFull())
- DispatchEvent(*Event::Create(event_type_names::kEventtimingbufferfull));
+void Performance::AddLargestContentfulPaint(LargestContentfulPaint* entry) {
+ if (largest_contentful_paint_buffer_.size() <
+ kDefaultLargestContenfulPaintSize) {
+ largest_contentful_paint_buffer_.push_back(entry);
+ }
}
-void Performance::AddFirstPaintTiming(TimeTicks start_time) {
+void Performance::AddFirstPaintTiming(base::TimeTicks start_time) {
AddPaintTiming(PerformancePaintTiming::PaintType::kFirstPaint, start_time);
}
-void Performance::AddFirstContentfulPaintTiming(TimeTicks start_time) {
+void Performance::AddFirstContentfulPaintTiming(base::TimeTicks start_time) {
AddPaintTiming(PerformancePaintTiming::PaintType::kFirstContentfulPaint,
start_time);
}
void Performance::AddPaintTiming(PerformancePaintTiming::PaintType type,
- TimeTicks start_time) {
+ base::TimeTicks start_time) {
PerformanceEntry* entry = MakeGarbageCollected<PerformancePaintTiming>(
type, MonotonicTimeToDOMHighResTimeStamp(start_time));
// Always buffer First Paint & First Contentful Paint.
@@ -704,8 +584,8 @@ bool Performance::CanAddResourceTimingEntry() {
}
void Performance::AddLongTaskTiming(
- TimeTicks start_time,
- TimeTicks end_time,
+ base::TimeTicks start_time,
+ base::TimeTicks end_time,
const AtomicString& name,
const String& frame_src,
const String& frame_id,
@@ -761,11 +641,12 @@ void Performance::clearMarks(const AtomicString& mark_name) {
PerformanceMeasure* Performance::measure(ScriptState* script_state,
const AtomicString& measure_name,
ExceptionState& exception_state) {
- LogMeasureStartToUma(MeasureParameterType::kUnprovided);
- LogMeasureEndToUma(MeasureParameterType::kUnprovided);
+ // When |startOrOptions| is not provided, it's assumed to be an empty
+ // dictionary.
return MeasureInternal(
script_state, measure_name,
- NativeValueTraits<StringOrPerformanceMeasureOptions>::NullValue(),
+ StringOrPerformanceMeasureOptions::FromPerformanceMeasureOptions(
+ PerformanceMeasureOptions::Create()),
base::nullopt, exception_state);
}
@@ -774,8 +655,6 @@ PerformanceMeasure* Performance::measure(
const AtomicString& measure_name,
const StringOrPerformanceMeasureOptions& start_or_options,
ExceptionState& exception_state) {
- LogMeasureStartToUma(StartOrOptionsToParameterType(start_or_options));
- LogMeasureEndToUma(MeasureParameterType::kUnprovided);
return MeasureInternal(script_state, measure_name, start_or_options,
base::nullopt, exception_state);
}
@@ -786,8 +665,6 @@ PerformanceMeasure* Performance::measure(
const StringOrPerformanceMeasureOptions& start_or_options,
const String& end,
ExceptionState& exception_state) {
- LogMeasureStartToUma(StartOrOptionsToParameterType(start_or_options));
- LogMeasureEndToUma(StringToNavigationTimingParameterType(end));
return MeasureInternal(script_state, measure_name, start_or_options,
base::Optional<String>(end), exception_state);
}
@@ -815,12 +692,15 @@ PerformanceMeasure* Performance::MeasureInternal(
const StringOrPerformanceMeasureOptions& start_or_options,
base::Optional<String> end,
ExceptionState& exception_state) {
+ DCHECK(!start_or_options.IsNull());
if (RuntimeEnabledFeatures::CustomUserTimingEnabled()) {
- if (start_or_options.IsPerformanceMeasureOptions()) {
- // measure("name", {}, *)
+ // An empty option is treated with no difference as null, undefined.
+ if (start_or_options.IsPerformanceMeasureOptions() &&
+ !IsMeasureOptionsEmpty(
+ *start_or_options.GetAsPerformanceMeasureOptions())) {
+ // measure("name", { start, end }, *)
if (end) {
- exception_state.ThrowDOMException(
- DOMExceptionCode::kSyntaxError,
+ exception_state.ThrowTypeError(
"If a PerformanceMeasureOptions object was passed, |end| must be "
"null.");
return nullptr;
@@ -830,46 +710,38 @@ PerformanceMeasure* Performance::MeasureInternal(
return MeasureWithDetail(script_state, measure_name, options->start(),
options->end(), options->detail(),
exception_state);
- } else {
- // measure("name", "mark1", *)
- StringOrDouble converted_start;
- if (start_or_options.IsString()) {
- converted_start =
- StringOrDouble::FromString(start_or_options.GetAsString());
- } else {
- DCHECK(start_or_options.IsNull());
- converted_start = NativeValueTraits<StringOrDouble>::NullValue();
- }
- // We let |end| behave the same whether it's empty, undefined or null in
- // JS, as long as |end| is null in C++.
- return MeasureWithDetail(
- script_state, measure_name, converted_start,
- end ? StringOrDouble::FromString(*end)
- : NativeValueTraits<StringOrDouble>::NullValue(),
- ScriptValue::CreateNull(script_state), exception_state);
}
- } else {
- // For consistency with UserTimingL2: the L2 API took |start| as a string,
- // so any object passed in became a string '[object, object]', null became
- // string 'null'.
+ // measure("name", "mark1", *)
StringOrDouble converted_start;
- if (start_or_options.IsPerformanceMeasureOptions()) {
- converted_start = StringOrDouble::FromString("[object Object]");
- } else if (start_or_options.IsString()) {
+ if (start_or_options.IsString()) {
converted_start =
StringOrDouble::FromString(start_or_options.GetAsString());
- } else {
- DCHECK(start_or_options.IsNull());
- DCHECK(converted_start.IsNull());
}
-
- MeasureWithDetail(script_state, measure_name, converted_start,
- end ? StringOrDouble::FromString(*end)
- : NativeValueTraits<StringOrDouble>::NullValue(),
- ScriptValue::CreateNull(script_state), exception_state);
- // Return nullptr to distinguish from L3.
- return nullptr;
- }
+ // We let |end| behave the same whether it's empty, undefined or null in
+ // JS, as long as |end| is null in C++.
+ return MeasureWithDetail(
+ script_state, measure_name, converted_start,
+ end ? StringOrDouble::FromString(*end)
+ : NativeValueTraits<StringOrDouble>::NullValue(),
+ ScriptValue::CreateNull(script_state), exception_state);
+ }
+ // For consistency with UserTimingL2: the L2 API took |start| as a string,
+ // so any object passed in became a string '[object, object]', null became
+ // string 'null'.
+ StringOrDouble converted_start;
+ if (!start_or_options.IsPerformanceMeasureOptions()) {
+ // |start_or_options| is not nullable.
+ DCHECK(start_or_options.IsString());
+ converted_start =
+ StringOrDouble::FromString(start_or_options.GetAsString());
+ }
+
+ MeasureWithDetail(script_state, measure_name, converted_start,
+ end ? StringOrDouble::FromString(*end)
+ : NativeValueTraits<StringOrDouble>::NullValue(),
+ ScriptValue::CreateNull(script_state), exception_state);
+ // Return nullptr to distinguish from L3.
+ return nullptr;
}
PerformanceMeasure* Performance::MeasureWithDetail(
@@ -906,7 +778,7 @@ ScriptPromise Performance::profile(ScriptState* script_state,
auto* profiler = profiler_group->CreateProfiler(
script_state, *options, time_origin_, exception_state);
if (exception_state.HadException())
- return ScriptPromise::Reject(script_state, exception_state);
+ return ScriptPromise();
return ScriptPromise::Cast(script_state, ToV8(profiler, script_state));
}
@@ -959,7 +831,7 @@ bool Performance::HasObserverFor(
void Performance::ActivateObserver(PerformanceObserver& observer) {
if (active_observers_.IsEmpty())
- deliver_observations_timer_.StartOneShot(TimeDelta(), FROM_HERE);
+ deliver_observations_timer_.StartOneShot(base::TimeDelta(), FROM_HERE);
active_observers_.insert(&observer);
}
@@ -997,8 +869,8 @@ double Performance::ClampTimeResolution(double time_seconds) {
// static
DOMHighResTimeStamp Performance::MonotonicTimeToDOMHighResTimeStamp(
- TimeTicks time_origin,
- TimeTicks monotonic_time,
+ base::TimeTicks time_origin,
+ base::TimeTicks monotonic_time,
bool allow_negative_value) {
// Avoid exposing raw platform timestamps.
if (monotonic_time.is_null() || time_origin.is_null())
@@ -1013,7 +885,7 @@ DOMHighResTimeStamp Performance::MonotonicTimeToDOMHighResTimeStamp(
}
DOMHighResTimeStamp Performance::MonotonicTimeToDOMHighResTimeStamp(
- TimeTicks monotonic_time) const {
+ base::TimeTicks monotonic_time) const {
return MonotonicTimeToDOMHighResTimeStamp(time_origin_, monotonic_time,
false /* allow_negative_value */);
}
@@ -1039,6 +911,7 @@ void Performance::Trace(blink::Visitor* visitor) {
visitor->Trace(element_timing_buffer_);
visitor->Trace(event_timing_buffer_);
visitor->Trace(layout_jank_buffer_);
+ visitor->Trace(largest_contentful_paint_buffer_);
visitor->Trace(navigation_timing_);
visitor->Trace(user_timing_);
visitor->Trace(first_paint_timing_);
@@ -1063,7 +936,7 @@ DOMHighResTimeStamp Performance::UnifiedClock::GetUnixAtZeroMonotonic() const {
return unix_at_zero_monotonic_.value();
}
-TimeTicks Performance::UnifiedClock::NowTicks() const {
+base::TimeTicks Performance::UnifiedClock::NowTicks() const {
return tick_clock_->NowTicks();
}
diff --git a/chromium/third_party/blink/renderer/core/timing/performance.h b/chromium/third_party/blink/renderer/core/timing/performance.h
index 03562a19d03..b9c81dc3d95 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance.h
+++ b/chromium/third_party/blink/renderer/core/timing/performance.h
@@ -60,6 +60,7 @@ namespace blink {
class PerformanceMarkOptions;
class ExceptionState;
+class LargestContentfulPaint;
class LayoutShift;
class MemoryInfo;
class PerformanceElementTiming;
@@ -104,15 +105,15 @@ class CORE_EXPORT Performance : public EventTargetWithInlineData {
static double ClampTimeResolution(double time_seconds);
static DOMHighResTimeStamp MonotonicTimeToDOMHighResTimeStamp(
- TimeTicks time_origin,
- TimeTicks monotonic_time,
+ base::TimeTicks time_origin,
+ base::TimeTicks monotonic_time,
bool allow_negative_value);
// Translate given platform monotonic time in seconds into a high resolution
// DOMHighResTimeStamp in milliseconds. The result timestamp is relative to
// document's time origin and has a time resolution that is safe for
// exposing to web.
- DOMHighResTimeStamp MonotonicTimeToDOMHighResTimeStamp(TimeTicks) const;
+ DOMHighResTimeStamp MonotonicTimeToDOMHighResTimeStamp(base::TimeTicks) const;
DOMHighResTimeStamp now() const;
// High Resolution Time Level 3 timeOrigin.
@@ -142,8 +143,8 @@ class CORE_EXPORT Performance : public EventTargetWithInlineData {
kResourcetimingbufferfull)
void AddLongTaskTiming(
- TimeTicks start_time,
- TimeTicks end_time,
+ base::TimeTicks start_time,
+ base::TimeTicks end_time,
const AtomicString& name,
const String& culprit_frame_src,
const String& culprit_frame_id,
@@ -168,27 +169,20 @@ class CORE_EXPORT Performance : public EventTargetWithInlineData {
void NotifyNavigationTimingToObservers();
- void AddFirstPaintTiming(TimeTicks start_time);
+ void AddFirstPaintTiming(base::TimeTicks start_time);
- void AddFirstContentfulPaintTiming(TimeTicks start_time);
+ void AddFirstContentfulPaintTiming(base::TimeTicks start_time);
bool IsElementTimingBufferFull() const;
void AddElementTimingBuffer(PerformanceElementTiming&);
- unsigned ElementTimingBufferSize() const;
- void clearElementTimings();
- void setElementTimingBufferMaxSize(unsigned);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(elementtimingbufferfull,
- kElementtimingbufferfull)
bool IsEventTimingBufferFull() const;
void AddEventTimingBuffer(PerformanceEventTiming&);
- unsigned EventTimingBufferSize() const;
- void clearEventTimings();
- void setEventTimingBufferMaxSize(unsigned);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(eventtimingbufferfull, kEventtimingbufferfull)
void AddLayoutJankBuffer(LayoutShift&);
+ void AddLargestContentfulPaint(LargestContentfulPaint*);
+
PerformanceMark* mark(ScriptState*,
const AtomicString& mark_name,
ExceptionState&);
@@ -199,6 +193,7 @@ class CORE_EXPORT Performance : public EventTargetWithInlineData {
ExceptionState&);
void clearMarks(const AtomicString& mark_name);
+ void clearMarks() { return clearMarks(AtomicString()); }
// 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
@@ -256,6 +251,7 @@ class CORE_EXPORT Performance : public EventTargetWithInlineData {
ExceptionState&);
void clearMeasures(const AtomicString& measure_name);
+ void clearMeasures() { return clearMeasures(AtomicString()); }
ScriptPromise profile(ScriptState*,
const ProfilerInitOptions*,
@@ -288,7 +284,7 @@ class CORE_EXPORT Performance : public EventTargetWithInlineData {
UnifiedClock(const base::Clock* clock, const base::TickClock* tick_clock)
: clock_(clock), tick_clock_(tick_clock) {}
DOMHighResTimeStamp GetUnixAtZeroMonotonic() const;
- TimeTicks NowTicks() const;
+ base::TimeTicks NowTicks() const;
private:
const base::Clock* clock_;
@@ -301,7 +297,8 @@ class CORE_EXPORT Performance : public EventTargetWithInlineData {
void ResetTimeOriginForTesting(base::TimeTicks time_origin);
private:
- void AddPaintTiming(PerformancePaintTiming::PaintType, TimeTicks start_time);
+ void AddPaintTiming(PerformancePaintTiming::PaintType,
+ base::TimeTicks start_time);
PerformanceMeasure* MeasureInternal(
ScriptState*,
@@ -322,7 +319,7 @@ class CORE_EXPORT Performance : public EventTargetWithInlineData {
PerformanceEntry::EntryType type);
protected:
- Performance(TimeTicks time_origin,
+ Performance(base::TimeTicks time_origin,
scoped_refptr<base::SingleThreadTaskRunner>);
// Expect WindowPerformance to override this method,
@@ -354,13 +351,14 @@ class CORE_EXPORT Performance : public EventTargetWithInlineData {
PerformanceEntryVector element_timing_buffer_;
unsigned element_timing_buffer_max_size_;
PerformanceEntryVector layout_jank_buffer_;
+ PerformanceEntryVector largest_contentful_paint_buffer_;
Member<PerformanceEntry> navigation_timing_;
Member<UserTiming> user_timing_;
Member<PerformanceEntry> first_paint_timing_;
Member<PerformanceEntry> first_contentful_paint_timing_;
Member<PerformanceEventTiming> first_input_timing_;
- TimeTicks time_origin_;
+ base::TimeTicks time_origin_;
const UnifiedClock* unified_clock_;
PerformanceEntryTypeMask observer_filter_options_;
diff --git a/chromium/third_party/blink/renderer/core/timing/performance.idl b/chromium/third_party/blink/renderer/core/timing/performance.idl
index d8daffca8d2..729fe9052a9 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance.idl
+++ b/chromium/third_party/blink/renderer/core/timing/performance.idl
@@ -51,19 +51,6 @@ interface Performance : EventTarget {
void setResourceTimingBufferSize(unsigned long maxSize);
attribute EventHandler onresourcetimingbufferfull;
- // Element Timing
- // https://github.com/npm1/Element-Timing
- [MeasureAs=ElementTimingExplicitlyRequested, RuntimeEnabled=ElementTiming] void clearElementTimings();
- [MeasureAs=ElementTimingExplicitlyRequested, RuntimeEnabled=ElementTiming] void setElementTimingBufferMaxSize(unsigned long maxSize);
- [MeasureAs=ElementTimingExplicitlyRequested, RuntimeEnabled=ElementTiming] attribute EventHandler onelementtimingbufferfull;
-
-
- // Event Timing
- // https://github.com/wicg/event-timing
- [MeasureAs=PerformanceEventTimingBuffer, RuntimeEnabled=EventTiming] void clearEventTimings();
- [MeasureAs=PerformanceEventTimingBuffer, RuntimeEnabled=EventTiming] void setEventTimingBufferMaxSize(unsigned long maxSize);
- [MeasureAs=PerformanceEventTimingBuffer, RuntimeEnabled=EventTiming] attribute EventHandler oneventtimingbufferfull;
-
// Navigation Timing
// https://w3c.github.io/navigation-timing/#extensions-to-the-performance-interface
[Exposed=Window, SameObject, Measure] readonly attribute PerformanceTiming timing;
@@ -77,7 +64,7 @@ interface Performance : EventTarget {
[MeasureAs=UserTiming, CallWith=ScriptState, RaisesException] PerformanceMark? mark(DOMString markName);
// TODO(maxlg): PerformanceMarkOptions will be changed to optional after L3 is default to be enabled.
[MeasureAs=UserTiming, CallWith=ScriptState, RuntimeEnabled=CustomUserTiming, RaisesException] PerformanceMark? mark(DOMString markName, PerformanceMarkOptions markOptions);
- [MeasureAs=UserTiming] void clearMarks(optional DOMString markName = null);
+ [MeasureAs=UserTiming] void clearMarks(optional DOMString markName);
// Doing either of the following requires enabling CustomUserTiming:
// * passing PerformanceMeasureOptions to |startOrOptions|
@@ -85,10 +72,9 @@ interface Performance : EventTarget {
// We use the returned value for feature detection:
// * L2 API returns null but this is a bug: crbug.com/914441.
// * 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 PerformanceMeasureOptions)? startOrOptions, optional DOMString end);
- [MeasureAs=UserTiming] void clearMeasures(optional DOMString measureName = null);
+ // https://w3c.github.io/user-timing/#extensions-performance-interface
+ [MeasureAs=UserTiming, CallWith=ScriptState, RaisesException] PerformanceMeasure? measure(DOMString measureName, optional (DOMString or PerformanceMeasureOptions) startOrOptions, optional DOMString end);
+ [MeasureAs=UserTiming] void clearMeasures(optional DOMString measureName);
// TODO(foolip): There is no spec for the Memory Info API, see blink-dev:
// https://groups.google.com/a/chromium.org/d/msg/blink-dev/g5YRCGpC9vs/b4OJz71NmPwJ
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 770e038c45d..f0cab8151e1 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
@@ -12,9 +12,10 @@ namespace blink {
// static
PerformanceElementTiming* PerformanceElementTiming::Create(
const AtomicString& name,
+ const String& url,
const FloatRect& intersection_rect,
- DOMHighResTimeStamp start_time,
- DOMHighResTimeStamp response_end,
+ DOMHighResTimeStamp render_time,
+ DOMHighResTimeStamp load_time,
const AtomicString& identifier,
int naturalWidth,
int naturalHeight,
@@ -25,16 +26,19 @@ PerformanceElementTiming* PerformanceElementTiming::Create(
DCHECK_GE(naturalWidth, 0);
DCHECK_GE(naturalHeight, 0);
DCHECK(element);
+ double start_time = render_time != 0.0 ? render_time : load_time;
return MakeGarbageCollected<PerformanceElementTiming>(
- name, intersection_rect, start_time, response_end, identifier,
- naturalWidth, naturalHeight, id, element);
+ name, start_time, url, intersection_rect, render_time, load_time,
+ identifier, naturalWidth, naturalHeight, id, element);
}
PerformanceElementTiming::PerformanceElementTiming(
const AtomicString& name,
- const FloatRect& intersection_rect,
DOMHighResTimeStamp start_time,
- DOMHighResTimeStamp response_end,
+ const String& url,
+ const FloatRect& intersection_rect,
+ DOMHighResTimeStamp render_time,
+ DOMHighResTimeStamp load_time,
const AtomicString& identifier,
int naturalWidth,
int naturalHeight,
@@ -43,11 +47,13 @@ PerformanceElementTiming::PerformanceElementTiming(
: PerformanceEntry(name, start_time, start_time),
element_(element),
intersection_rect_(DOMRectReadOnly::FromFloatRect(intersection_rect)),
- response_end_(response_end),
+ render_time_(render_time),
+ load_time_(load_time),
identifier_(identifier),
naturalWidth_(naturalWidth),
naturalHeight_(naturalHeight),
- id_(id) {}
+ id_(id),
+ url_(url) {}
PerformanceElementTiming::~PerformanceElementTiming() = default;
@@ -63,12 +69,25 @@ Element* PerformanceElementTiming::element() const {
if (!element_ || !element_->isConnected() || element_->IsInShadowTree())
return nullptr;
+ // Do not expose |element_| when the document is not 'fully active'.
+ const Document& document = element_->GetDocument();
+ if (!document.IsActive() || !document.GetFrame())
+ return nullptr;
+
return element_;
}
void PerformanceElementTiming::BuildJSONValue(V8ObjectBuilder& builder) const {
PerformanceEntry::BuildJSONValue(builder);
+ builder.Add("renderTime", render_time_);
+ builder.Add("loadTime", load_time_);
builder.Add("intersectionRect", intersection_rect_);
+ builder.Add("identifier", identifier_);
+ builder.Add("naturalWidth", naturalWidth_);
+ builder.Add("naturalHeight", naturalHeight_);
+ builder.Add("id", id_);
+ builder.Add("element", element());
+ builder.Add("url", url_);
}
void PerformanceElementTiming::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_element_timing.h b/chromium/third_party/blink/renderer/core/timing/performance_element_timing.h
index ac920ed0cc7..ad6a994b896 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_element_timing.h
+++ b/chromium/third_party/blink/renderer/core/timing/performance_element_timing.h
@@ -22,18 +22,21 @@ class CORE_EXPORT PerformanceElementTiming final : public PerformanceEntry {
public:
static PerformanceElementTiming* Create(const AtomicString& name,
+ const String& url,
const FloatRect& intersection_rect,
- DOMHighResTimeStamp start_time,
- DOMHighResTimeStamp response_end,
+ DOMHighResTimeStamp render_time,
+ DOMHighResTimeStamp load_time,
const AtomicString& identifier,
int naturalWidth,
int naturalHeight,
const AtomicString& id,
Element*);
PerformanceElementTiming(const AtomicString& name,
- const FloatRect& intersection_rect,
DOMHighResTimeStamp start_time,
- DOMHighResTimeStamp response_end,
+ const String& url,
+ const FloatRect& intersection_rect,
+ DOMHighResTimeStamp render_time,
+ DOMHighResTimeStamp load_time,
const AtomicString& identifier,
int naturalWidth,
int naturalHeight,
@@ -46,17 +49,13 @@ class CORE_EXPORT PerformanceElementTiming final : public PerformanceEntry {
PerformanceEntryType EntryTypeEnum() const override;
DOMRectReadOnly* intersectionRect() const { return intersection_rect_; }
-
- DOMHighResTimeStamp responseEnd() const { return response_end_; }
-
+ DOMHighResTimeStamp renderTime() const { return render_time_; }
+ DOMHighResTimeStamp loadTime() const { return load_time_; }
AtomicString identifier() const { return identifier_; }
-
unsigned naturalWidth() const { return naturalWidth_; }
-
unsigned naturalHeight() const { return naturalHeight_; }
-
AtomicString id() const { return id_; }
-
+ String url() const { return url_; }
Element* element() const;
void Trace(blink::Visitor*) override;
@@ -66,11 +65,13 @@ class CORE_EXPORT PerformanceElementTiming final : public PerformanceEntry {
WeakMember<Element> element_;
Member<DOMRectReadOnly> intersection_rect_;
- DOMHighResTimeStamp response_end_;
+ DOMHighResTimeStamp render_time_;
+ DOMHighResTimeStamp load_time_;
AtomicString identifier_;
unsigned naturalWidth_;
unsigned naturalHeight_;
AtomicString id_;
+ String url_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_element_timing.idl b/chromium/third_party/blink/renderer/core/timing/performance_element_timing.idl
index 7a2c5a5fd91..e691f5678fa 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_element_timing.idl
+++ b/chromium/third_party/blink/renderer/core/timing/performance_element_timing.idl
@@ -2,16 +2,18 @@
// 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/1blFeMVdqxB0V3BAJh60ptOBFY7cJSXnf7VyW3wspbZ8
+// https://wicg.github.io/element-timing/#sec-performance-element-timing
[RuntimeEnabled=ElementTiming]
interface PerformanceElementTiming : PerformanceEntry {
+ readonly attribute DOMHighResTimeStamp renderTime;
+ readonly attribute DOMHighResTimeStamp loadTime;
readonly attribute DOMRectReadOnly intersectionRect;
- readonly attribute DOMHighResTimeStamp responseEnd;
readonly attribute DOMString identifier;
readonly attribute unsigned long naturalWidth;
readonly attribute unsigned long naturalHeight;
readonly attribute DOMString id;
readonly attribute Element? element;
+ readonly attribute DOMString url;
// TODO(peria): toJSON is not in spec. https://crbug.com/736332
[CallWith=ScriptState, ImplementedAs=toJSONForBinding] object toJSON();
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 618814d2db0..67aa23040e9 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_entry.cc
+++ b/chromium/third_party/blink/renderer/core/timing/performance_entry.cc
@@ -82,7 +82,9 @@ PerformanceEntry::EntryType PerformanceEntry::ToEntryTypeEnum(
if (entry_type == performance_entry_names::kElement)
return kElement;
if (entry_type == performance_entry_names::kLayoutShift)
- return kLayoutJank;
+ return kLayoutShift;
+ if (entry_type == performance_entry_names::kLargestContentfulPaint)
+ return kLargestContentfulPaint;
return kInvalid;
}
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_entry.h b/chromium/third_party/blink/renderer/core/timing/performance_entry.h
index a6a1420a4e1..68c90d3ccfa 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_entry.h
+++ b/chromium/third_party/blink/renderer/core/timing/performance_entry.h
@@ -65,7 +65,8 @@ class CORE_EXPORT PerformanceEntry : public ScriptWrappable {
kEvent = 1 << 7,
kFirstInput = 1 << 8,
kElement = 1 << 9,
- kLayoutJank = 1 << 10,
+ kLayoutShift = 1 << 10,
+ kLargestContentfulPaint = 1 << 11,
};
const AtomicString& name() const { return name_; }
@@ -103,10 +104,10 @@ class CORE_EXPORT PerformanceEntry : public ScriptWrappable {
if (entry_type == kInvalid) {
return true;
}
- DEFINE_THREAD_SAFE_STATIC_LOCAL(
- HashSet<PerformanceEntryType>, valid_timeline_entry_types,
- ({kNavigation, kMark, kMeasure, kResource, kTaskAttribution, kPaint,
- kEvent, kFirstInput, kElement, kLayoutJank}));
+ DEFINE_THREAD_SAFE_STATIC_LOCAL(HashSet<PerformanceEntryType>,
+ valid_timeline_entry_types,
+ ({kNavigation, kMark, kMeasure, kResource,
+ kTaskAttribution, kPaint, kFirstInput}));
return valid_timeline_entry_types.Contains(entry_type);
}
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 58805fa73f7..318edbd1be5 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
@@ -7,8 +7,9 @@
data: [
"element",
"event",
- "firstInput",
- "layoutShift",
+ "first-input",
+ "largest-contentful-paint",
+ "layout-shift",
"longtask",
"mark",
"measure",
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_event_timing.idl b/chromium/third_party/blink/renderer/core/timing/performance_event_timing.idl
index 951011e3318..466db50a432 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_event_timing.idl
+++ b/chromium/third_party/blink/renderer/core/timing/performance_event_timing.idl
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// https://github.com/wicg/event-timing
+// https://wicg.github.io/event-timing/#sec-performance-event-timing
[Exposed=Window]
interface PerformanceEventTiming : PerformanceEntry {
readonly attribute DOMHighResTimeStamp processingStart;
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 a1733a82c0a..8e52412fbb4 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_mark.cc
+++ b/chromium/third_party/blink/renderer/core/timing/performance_mark.cc
@@ -5,26 +5,45 @@
#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
#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/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/performance_entry_names.h"
#include "third_party/blink/renderer/core/timing/dom_window_performance.h"
#include "third_party/blink/renderer/core/timing/performance.h"
#include "third_party/blink/renderer/core/timing/performance_mark_options.h"
#include "third_party/blink/renderer/core/timing/performance_user_timing.h"
+#include "third_party/blink/renderer/core/timing/worker_global_scope_performance.h"
+#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
namespace blink {
-PerformanceMark::PerformanceMark(ScriptState* script_state,
- const AtomicString& name,
- double start_time,
- const ScriptValue& detail)
- : PerformanceEntry(name, start_time, start_time) {
- world_ = WrapRefCounted(&script_state->World());
- if (detail.IsEmpty() || detail.IsNull() || detail.IsUndefined()) {
- return;
+PerformanceMark::PerformanceMark(
+ ScriptState* script_state,
+ const AtomicString& name,
+ double start_time,
+ scoped_refptr<SerializedScriptValue> serialized_detail,
+ ExceptionState& exception_state)
+ : PerformanceEntry(name, start_time, start_time),
+ serialized_detail_(std::move(serialized_detail)) {}
+
+// static
+PerformanceMark* PerformanceMark::Create(ScriptState* script_state,
+ const AtomicString& name,
+ double start_time,
+ const ScriptValue& detail,
+ ExceptionState& exception_state) {
+ scoped_refptr<SerializedScriptValue> serialized_detail;
+ if (detail.IsEmpty()) {
+ serialized_detail = SerializedScriptValue::NullValue();
+ } else {
+ serialized_detail = SerializedScriptValue::Serialize(
+ script_state->GetIsolate(), detail.V8Value(),
+ SerializedScriptValue::SerializeOptions(), exception_state);
+ if (exception_state.HadException())
+ return nullptr;
}
- detail_.Set(detail.GetIsolate(), detail.V8Value());
+ return MakeGarbageCollected<PerformanceMark>(script_state, name, start_time,
+ std::move(serialized_detail),
+ exception_state);
}
// static
@@ -32,15 +51,23 @@ PerformanceMark* PerformanceMark::Create(ScriptState* script_state,
const AtomicString& mark_name,
PerformanceMarkOptions* mark_options,
ExceptionState& exception_state) {
- LocalDOMWindow* window = LocalDOMWindow::From(script_state);
- if (!window)
- return nullptr;
- Performance* performance = DOMWindowPerformance::performance(*window);
- if (!performance)
- return nullptr;
+ Performance* performance = nullptr;
+ if (LocalDOMWindow* window = LocalDOMWindow::From(script_state)) {
+ performance = DOMWindowPerformance::performance(*window);
+ DCHECK(performance);
+ } else if (auto* scope = DynamicTo<WorkerGlobalScope>(
+ ExecutionContext::From(script_state))) {
+ performance = WorkerGlobalScopePerformance::performance(*scope);
+ DCHECK(performance);
+ }
- return performance->GetUserTiming().CreatePerformanceMark(
- script_state, mark_name, mark_options, exception_state);
+ if (performance) {
+ return performance->GetUserTiming().CreatePerformanceMark(
+ script_state, mark_name, mark_options, exception_state);
+ }
+ exception_state.ThrowTypeError(
+ "PerformanceMark: no 'worker' or 'window' in current context.");
+ return nullptr;
}
AtomicString PerformanceMark::entryType() const {
@@ -51,23 +78,23 @@ PerformanceEntryType PerformanceMark::EntryTypeEnum() const {
return PerformanceEntry::EntryType::kMark;
}
-ScriptValue PerformanceMark::detail(ScriptState* script_state) const {
+ScriptValue PerformanceMark::detail(ScriptState* script_state) {
v8::Isolate* isolate = script_state->GetIsolate();
- if (detail_.IsEmpty()) {
+ if (!serialized_detail_)
return ScriptValue(script_state, v8::Null(isolate));
- }
- // Return a serialized clone when the world is different.
- if (!world_ || world_->GetWorldId() != script_state->World().GetWorldId()) {
- v8::Local<v8::Value> value = detail_.NewLocal(isolate);
- scoped_refptr<SerializedScriptValue> serialized =
- SerializedScriptValue::SerializeAndSwallowExceptions(isolate, value);
- return ScriptValue(script_state, serialized->Deserialize(isolate));
- }
- return ScriptValue(script_state, detail_.NewLocal(isolate));
+ auto result = deserialized_detail_map_.insert(
+ script_state, TraceWrapperV8Reference<v8::Value>());
+ TraceWrapperV8Reference<v8::Value>& relevant_data =
+ result.stored_value->value;
+ if (!result.is_new_entry)
+ return ScriptValue(script_state, relevant_data.NewLocal(isolate));
+ v8::Local<v8::Value> value = serialized_detail_->Deserialize(isolate);
+ relevant_data.Set(isolate, value);
+ return ScriptValue(script_state, value);
}
void PerformanceMark::Trace(blink::Visitor* visitor) {
- visitor->Trace(detail_);
+ visitor->Trace(deserialized_detail_map_);
PerformanceEntry::Trace(visitor);
}
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 da82967a0a3..397d52362ad 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_mark.h
+++ b/chromium/third_party/blink/renderer/core/timing/performance_mark.h
@@ -26,9 +26,11 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_TIMING_PERFORMANCE_MARK_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_TIMING_PERFORMANCE_MARK_H_
+#include "third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h"
#include "third_party/blink/renderer/core/timing/performance_entry.h"
-#include "third_party/blink/renderer/platform/bindings/dom_wrapper_world.h"
#include "third_party/blink/renderer/platform/bindings/trace_wrapper_v8_reference.h"
+#include "third_party/blink/renderer/platform/heap/heap_allocator.h"
+#include "third_party/blink/renderer/platform/heap/member.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
@@ -43,10 +45,8 @@ class CORE_EXPORT PerformanceMark final : public PerformanceEntry {
static PerformanceMark* Create(ScriptState* script_state,
const AtomicString& name,
double start_time,
- const ScriptValue& detail) {
- return MakeGarbageCollected<PerformanceMark>(script_state, name, start_time,
- detail);
- }
+ const ScriptValue& detail,
+ ExceptionState& exception_state);
// This method is required by the constructor defined in performance_mark.idl.
static PerformanceMark* Create(ScriptState*,
@@ -57,20 +57,24 @@ class CORE_EXPORT PerformanceMark final : public PerformanceEntry {
PerformanceMark(ScriptState*,
const AtomicString& name,
double start_time,
- const ScriptValue& detail);
+ scoped_refptr<SerializedScriptValue>,
+ ExceptionState& exception_state);
AtomicString entryType() const override;
PerformanceEntryType EntryTypeEnum() const override;
- ScriptValue detail(ScriptState*) const;
+ ScriptValue detail(ScriptState*);
void Trace(blink::Visitor*) override;
private:
~PerformanceMark() override = default;
- scoped_refptr<DOMWrapperWorld> world_;
- TraceWrapperV8Reference<v8::Value> detail_;
+ scoped_refptr<SerializedScriptValue> serialized_detail_;
+ // In order to prevent cross-world reference leak, we create a copy of the
+ // detail for each world.
+ HeapHashMap<WeakMember<ScriptState>, TraceWrapperV8Reference<v8::Value>>
+ deserialized_detail_map_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_mark_options.idl b/chromium/third_party/blink/renderer/core/timing/performance_mark_options.idl
index fc91d8e133f..d080083c383 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_mark_options.idl
+++ b/chromium/third_party/blink/renderer/core/timing/performance_mark_options.idl
@@ -2,9 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// TODO(maxlg): refer to user timing L3 spec once authored.
-// https://docs.google.com/document/d/1hltt8z9C4PaI5Qu1YMIp1wOGdbJPJPoJwBarEeCY6xQ/edit#
-
+// https://w3c.github.io/user-timing/#performancemarkoptions-dictionary
dictionary PerformanceMarkOptions {
any detail;
DOMHighResTimeStamp startTime;
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 0a6c3db671e..e3880e4c31c 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_measure.cc
+++ b/chromium/third_party/blink/renderer/core/timing/performance_measure.cc
@@ -7,27 +7,56 @@
#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
#include "third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h"
#include "third_party/blink/renderer/core/performance_entry_names.h"
+#include "third_party/blink/renderer/platform/bindings/exception_state.h"
namespace blink {
-PerformanceMeasure::PerformanceMeasure(ScriptState* script_state,
- const AtomicString& name,
- double start_time,
- double end_time,
- const ScriptValue& detail)
- : PerformanceEntry(name, start_time, end_time) {
+PerformanceMeasure::PerformanceMeasure(
+ ScriptState* script_state,
+ const AtomicString& name,
+ double start_time,
+ double end_time,
+ scoped_refptr<SerializedScriptValue> serialized_detail,
+ ExceptionState& exception_state)
+ : PerformanceEntry(name, start_time, end_time),
+ serialized_detail_(serialized_detail) {}
+
+// static
+PerformanceMeasure* PerformanceMeasure::Create(
+ ScriptState* script_state,
+ const AtomicString& name,
+ double start_time,
+ double end_time,
+ const ScriptValue& detail,
+ ExceptionState& exception_state) {
+ scoped_refptr<SerializedScriptValue> serialized_detail;
if (detail.IsEmpty()) {
- detail_ = SerializedScriptValue::NullValue();
+ serialized_detail = nullptr;
} else {
- detail_ = SerializedScriptValue::SerializeAndSwallowExceptions(
- script_state->GetIsolate(), detail.V8Value());
+ serialized_detail = SerializedScriptValue::Serialize(
+ script_state->GetIsolate(), detail.V8Value(),
+ SerializedScriptValue::SerializeOptions(), exception_state);
+ if (exception_state.HadException())
+ return nullptr;
}
+ return MakeGarbageCollected<PerformanceMeasure>(
+ script_state, name, start_time, end_time, serialized_detail,
+ exception_state);
}
-ScriptValue PerformanceMeasure::detail(ScriptState* script_state) const {
+ScriptValue PerformanceMeasure::detail(ScriptState* script_state) {
v8::Isolate* isolate = script_state->GetIsolate();
- v8::Local<v8::Value> detail = detail_->Deserialize(isolate);
- return ScriptValue(script_state, detail);
+ if (!serialized_detail_)
+ return ScriptValue(script_state, v8::Null(isolate));
+ auto result = deserialized_detail_map_.insert(
+ script_state, TraceWrapperV8Reference<v8::Value>());
+ TraceWrapperV8Reference<v8::Value>& relevant_data =
+ result.stored_value->value;
+ if (!result.is_new_entry)
+ return ScriptValue(script_state, relevant_data.NewLocal(isolate));
+ v8::Local<v8::Value> value = serialized_detail_->Deserialize(isolate);
+ relevant_data.Set(isolate, value);
+ return ScriptValue(script_state, value);
}
AtomicString PerformanceMeasure::entryType() const {
@@ -38,4 +67,9 @@ PerformanceEntryType PerformanceMeasure::EntryTypeEnum() const {
return PerformanceEntry::EntryType::kMeasure;
}
+void PerformanceMeasure::Trace(blink::Visitor* visitor) {
+ visitor->Trace(deserialized_detail_map_);
+ PerformanceEntry::Trace(visitor);
+}
+
} // namespace blink
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 bb15e1f12ef..4ac3ab0a804 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_measure.h
+++ b/chromium/third_party/blink/renderer/core/timing/performance_measure.h
@@ -27,12 +27,16 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_TIMING_PERFORMANCE_MEASURE_H_
#include "base/memory/scoped_refptr.h"
+#include "third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h"
#include "third_party/blink/renderer/core/timing/performance_entry.h"
+#include "third_party/blink/renderer/platform/bindings/trace_wrapper_v8_reference.h"
+#include "third_party/blink/renderer/platform/heap/heap_allocator.h"
+#include "third_party/blink/renderer/platform/heap/member.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
-class SerializedScriptValue;
+class ExceptionState;
class PerformanceMeasure final : public PerformanceEntry {
DEFINE_WRAPPERTYPEINFO();
@@ -42,20 +46,30 @@ class PerformanceMeasure final : public PerformanceEntry {
const AtomicString& name,
double start_time,
double end_time,
- const ScriptValue& detail);
+ scoped_refptr<SerializedScriptValue>,
+ ExceptionState&);
- ScriptValue detail(ScriptState*) const;
+ static PerformanceMeasure* Create(ScriptState*,
+ const AtomicString& name,
+ double start_time,
+ double end_time,
+ const ScriptValue& detail,
+ ExceptionState&);
+
+ ScriptValue detail(ScriptState*);
AtomicString entryType() const override;
PerformanceEntryType EntryTypeEnum() const override;
- void Trace(blink::Visitor* visitor) override {
- PerformanceEntry::Trace(visitor);
- }
+ void Trace(blink::Visitor* visitor) override;
private:
~PerformanceMeasure() override = default;
- scoped_refptr<SerializedScriptValue> detail_;
+ scoped_refptr<SerializedScriptValue> serialized_detail_;
+ // In order to prevent cross-world reference leak, we create a copy of the
+ // detail for each world.
+ HeapHashMap<WeakMember<ScriptState>, TraceWrapperV8Reference<v8::Value>>
+ deserialized_detail_map_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_measure_options.idl b/chromium/third_party/blink/renderer/core/timing/performance_measure_options.idl
index c8f84669dc0..c8f29343bcd 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_measure_options.idl
+++ b/chromium/third_party/blink/renderer/core/timing/performance_measure_options.idl
@@ -2,8 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// TODO(maxlg): refer to user timing L3 spec once authored.
-// https://docs.google.com/document/d/1hltt8z9C4PaI5Qu1YMIp1wOGdbJPJPoJwBarEeCY6xQ/edit#
+// https://w3c.github.io/user-timing/#performancemeasureoptions-dictionary
dictionary PerformanceMeasureOptions {
any detail;
(DOMString or DOMHighResTimeStamp) start;
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 909fd4100a8..d0934bef6dc 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
@@ -13,23 +13,54 @@
#include "third_party/blink/renderer/core/performance_entry_names.h"
#include "third_party/blink/renderer/core/timing/performance.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_timing_info.h"
+#include "third_party/blink/renderer/platform/weborigin/kurl.h"
namespace blink {
+namespace {
+
+bool PassesSameOriginCheck(const ResourceResponse& response,
+ const SecurityOrigin& initiator_security_origin) {
+ const KURL& response_url = response.ResponseUrl();
+ scoped_refptr<const SecurityOrigin> resource_origin =
+ SecurityOrigin::Create(response_url);
+ return resource_origin->IsSameSchemeHostPort(&initiator_security_origin);
+}
+
+bool AllowNavigationTimingRedirect(
+ const Vector<ResourceResponse>& redirect_chain,
+ const ResourceResponse& final_response,
+ const SecurityOrigin& initiator_security_origin) {
+ if (!PassesSameOriginCheck(final_response, initiator_security_origin)) {
+ return false;
+ }
+
+ for (const ResourceResponse& response : redirect_chain) {
+ if (!PassesSameOriginCheck(response, initiator_security_origin))
+ return false;
+ }
+
+ return true;
+}
+
+} // namespace
+
PerformanceNavigationTiming::PerformanceNavigationTiming(
LocalFrame* frame,
ResourceTimingInfo* info,
- TimeTicks time_origin,
+ base::TimeTicks time_origin,
const WebVector<WebServerTimingInfo>& server_timing)
: PerformanceResourceTiming(
info ? AtomicString(
info->FinalResponse().CurrentRequestUrl().GetString())
: g_empty_atom,
time_origin,
+ SecurityOrigin::IsSecure(frame->GetDocument()->Url()),
server_timing),
ContextClient(frame),
resource_timing_info_(info) {
DCHECK(frame);
+ DCHECK(frame->GetDocument());
DCHECK(info);
}
@@ -119,17 +150,18 @@ AtomicString PerformanceNavigationTiming::initiatorType() const {
}
bool PerformanceNavigationTiming::GetAllowRedirectDetails() const {
- ExecutionContext* context = GetFrame() ? GetFrame()->GetDocument() : nullptr;
- const SecurityOrigin* security_origin = nullptr;
+ blink::ExecutionContext* context =
+ GetFrame() ? GetFrame()->GetDocument() : nullptr;
+ const blink::SecurityOrigin* security_origin = nullptr;
if (context)
security_origin = context->GetSecurityOrigin();
if (!security_origin)
return false;
// TODO(sunjian): Think about how to make this flag deterministic.
// crbug/693183.
- return Performance::AllowsTimingRedirect(
- resource_timing_info_->RedirectChain(),
- resource_timing_info_->FinalResponse(), *security_origin, context);
+ return AllowNavigationTimingRedirect(resource_timing_info_->RedirectChain(),
+ resource_timing_info_->FinalResponse(),
+ *security_origin);
}
AtomicString PerformanceNavigationTiming::AlpnNegotiatedProtocol() const {
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_navigation_timing.h b/chromium/third_party/blink/renderer/core/timing/performance_navigation_timing.h
index 5889f9e1772..8a9488eacb7 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_navigation_timing.h
+++ b/chromium/third_party/blink/renderer/core/timing/performance_navigation_timing.h
@@ -33,7 +33,7 @@ class CORE_EXPORT PerformanceNavigationTiming final
public:
PerformanceNavigationTiming(LocalFrame*,
ResourceTimingInfo*,
- TimeTicks time_origin,
+ base::TimeTicks time_origin,
const WebVector<WebServerTimingInfo>&);
// Attributes inheritted from PerformanceEntry.
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 f549b50a7bd..992b20f201c 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_observer.cc
+++ b/chromium/third_party/blink/renderer/core/timing/performance_observer.cc
@@ -10,7 +10,6 @@
#include "third_party/blink/renderer/bindings/core/v8/v8_performance_observer_callback.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.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/performance_entry_names.h"
#include "third_party/blink/renderer/core/timing/dom_window_performance.h"
@@ -22,6 +21,7 @@
#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
#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/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/timer.h"
@@ -62,6 +62,10 @@ Vector<AtomicString> PerformanceObserver::supportedEntryTypes(
if (RuntimeEnabledFeatures::EventTimingEnabled(execution_context))
supportedEntryTypes.push_back(performance_entry_names::kEvent);
supportedEntryTypes.push_back(performance_entry_names::kFirstInput);
+ if (RuntimeEnabledFeatures::LargestContentfulPaintEnabled()) {
+ supportedEntryTypes.push_back(
+ performance_entry_names::kLargestContentfulPaint);
+ }
if (RuntimeEnabledFeatures::LayoutInstabilityAPIEnabled(execution_context))
supportedEntryTypes.push_back(performance_entry_names::kLayoutShift);
supportedEntryTypes.push_back(performance_entry_names::kLongtask);
@@ -101,15 +105,16 @@ void PerformanceObserver::observe(const PerformanceObserverInit* observer_init,
bool is_buffered = false;
if (observer_init->hasEntryTypes()) {
if (observer_init->hasType()) {
- exception_state.ThrowDOMException(
- DOMExceptionCode::kSyntaxError,
- "An observe() call MUST NOT include both entryTypes and type.");
+ exception_state.ThrowDOMException(DOMExceptionCode::kSyntaxError,
+ "An observe() call must not include "
+ "both entryTypes and type arguments.");
return;
}
if (type_ == PerformanceObserverType::kTypeObserver) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidModificationError,
- "This observer has performed observe({type:...}, therefore it cannot "
+ "This PerformanceObserver has performed observe({type:...}, "
+ "therefore it cannot "
"perform observe({entryTypes:...})");
return;
}
@@ -117,24 +122,25 @@ void PerformanceObserver::observe(const PerformanceObserverInit* observer_init,
PerformanceEntryTypeMask entry_types = PerformanceEntry::kInvalid;
const Vector<String>& sequence = observer_init->entryTypes();
for (const auto& entry_type_string : sequence) {
- entry_types |=
+ PerformanceEntryType entry_type =
PerformanceEntry::ToEntryTypeEnum(AtomicString(entry_type_string));
+ if (entry_type == PerformanceEntry::kInvalid) {
+ String message = "The entry type '" + entry_type_string +
+ "' does not exist or isn't supported.";
+ GetExecutionContext()->AddConsoleMessage(ConsoleMessage::Create(
+ mojom::ConsoleMessageSource::kJavaScript,
+ mojom::ConsoleMessageLevel::kWarning, message));
+ }
+ entry_types |= entry_type;
}
if (entry_types == PerformanceEntry::kInvalid) {
- String message =
- "The Performance Observer MUST have at least one valid entryType in "
- "its "
- "entryTypes attribute.";
- GetExecutionContext()->AddConsoleMessage(ConsoleMessage::Create(
- mojom::ConsoleMessageSource::kJavaScript,
- mojom::ConsoleMessageLevel::kWarning, message));
return;
}
if (RuntimeEnabledFeatures::PerformanceObserverBufferedFlagEnabled() &&
observer_init->buffered()) {
String message =
- "The Performance Observer does not support buffered flag with "
- "entryTypes. ";
+ "The PerformanceObserver does not support buffered flag with "
+ "the entryTypes argument.";
GetExecutionContext()->AddConsoleMessage(ConsoleMessage::Create(
mojom::ConsoleMessageSource::kJavaScript,
mojom::ConsoleMessageLevel::kWarning, message));
@@ -142,9 +148,9 @@ void PerformanceObserver::observe(const PerformanceObserverInit* observer_init,
filter_options_ = entry_types;
} else {
if (!observer_init->hasType()) {
- exception_state.ThrowDOMException(
- DOMExceptionCode::kSyntaxError,
- "An observe() call MUST include either entryTypes or type.");
+ exception_state.ThrowDOMException(DOMExceptionCode::kSyntaxError,
+ "An observe() call must include either "
+ "entryTypes or type arguments.");
return;
}
if (type_ == PerformanceObserverType::kEntryTypesObserver) {
@@ -158,9 +164,8 @@ void PerformanceObserver::observe(const PerformanceObserverInit* observer_init,
PerformanceEntryType entry_type =
PerformanceEntry::ToEntryTypeEnum(AtomicString(observer_init->type()));
if (entry_type == PerformanceEntry::kInvalid) {
- String message =
- "The Performance Observer MUST have a valid entryType in its "
- "type attribute.";
+ String message = "The entry type '" + observer_init->type() +
+ "' does not exist or isn't supported.";
GetExecutionContext()->AddConsoleMessage(ConsoleMessage::Create(
mojom::ConsoleMessageSource::kJavaScript,
mojom::ConsoleMessageLevel::kWarning, message));
@@ -168,8 +173,9 @@ void PerformanceObserver::observe(const PerformanceObserverInit* observer_init,
}
if (filter_options_ & entry_type) {
String message =
- "The Performance Observer has already been called with this "
- "entryType";
+ "The PerformanceObserver has already been called with the entry type "
+ "'" +
+ observer_init->type() + "'.";
GetExecutionContext()->AddConsoleMessage(ConsoleMessage::Create(
mojom::ConsoleMessageSource::kJavaScript,
mojom::ConsoleMessageLevel::kWarning, message));
@@ -179,7 +185,7 @@ void PerformanceObserver::observe(const PerformanceObserverInit* observer_init,
observer_init->buffered()) {
if (entry_type == PerformanceEntry::kLongTask) {
String message =
- "Buffered flag does not support the long task entry type ";
+ "Buffered flag does not support the 'longtask' entry type.";
GetExecutionContext()->AddConsoleMessage(ConsoleMessage::Create(
mojom::ConsoleMessageSource::kJavaScript,
mojom::ConsoleMessageLevel::kWarning, message));
@@ -196,9 +202,17 @@ void PerformanceObserver::observe(const PerformanceObserverInit* observer_init,
}
filter_options_ |= entry_type;
}
- if (filter_options_ & PerformanceEntry::kLayoutJank) {
+ if (filter_options_ & PerformanceEntry::kLayoutShift) {
+ UseCounter::Count(GetExecutionContext(),
+ WebFeature::kLayoutShiftExplicitlyRequested);
+ }
+ if (filter_options_ & PerformanceEntry::kElement) {
+ UseCounter::Count(GetExecutionContext(),
+ WebFeature::kElementTimingExplicitlyRequested);
+ }
+ if (filter_options_ & PerformanceEntry::kLargestContentfulPaint) {
UseCounter::Count(GetExecutionContext(),
- WebFeature::kLayoutJankExplicitlyRequested);
+ WebFeature::kLargestContentfulPaintExplicitlyRequested);
}
if (is_registered_)
performance_->UpdatePerformanceObserverFilterOptions();
@@ -206,6 +220,8 @@ void PerformanceObserver::observe(const PerformanceObserverInit* observer_init,
performance_->RegisterPerformanceObserver(*this);
is_registered_ = true;
if (is_buffered) {
+ UseCounter::Count(GetExecutionContext(),
+ WebFeature::kPerformanceObserverBufferedFlag);
performance_->ActivateObserver(*this);
}
}
diff --git a/chromium/third_party/blink/renderer/core/timing/performance_observer.idl b/chromium/third_party/blink/renderer/core/timing/performance_observer.idl
index c4348fb7141..8d28a314517 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_observer.idl
+++ b/chromium/third_party/blink/renderer/core/timing/performance_observer.idl
@@ -15,5 +15,5 @@ callback PerformanceObserverCallback = void (PerformanceObserverEntryList entrie
[RaisesException] void observe(optional PerformanceObserverInit options);
void disconnect();
PerformanceEntryList takeRecords();
- [CallWith=ScriptState] static readonly attribute FrozenArray<DOMString> supportedEntryTypes;
+ [SameObject, SaveSameObject, CallWith=ScriptState] static readonly attribute FrozenArray<DOMString> supportedEntryTypes;
};
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 709417f736a..58f5d1c7f9f 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
@@ -21,7 +21,7 @@ namespace blink {
class MockPerformance : public Performance {
public:
explicit MockPerformance(ScriptState* script_state)
- : Performance(TimeTicks(),
+ : Performance(base::TimeTicks(),
ExecutionContext::From(script_state)
->GetTaskRunner(TaskType::kPerformanceTimeline)) {}
~MockPerformance() override = default;
@@ -69,12 +69,12 @@ TEST_F(PerformanceObserverTest, ObserveWithBufferedFlag) {
NonThrowableExceptionState exception_state;
PerformanceObserverInit* options = PerformanceObserverInit::Create();
- options->setType("layoutShift");
+ options->setType("layout-shift");
options->setBuffered(true);
EXPECT_EQ(0, NumPerformanceEntries());
// add a layoutjank to performance so getEntries() returns it
- auto* entry = MakeGarbageCollected<LayoutShift>(0.0, 1234);
+ auto* entry = MakeGarbageCollected<LayoutShift>(0.0, 1234, true, 5678);
base_->AddLayoutJankBuffer(*entry);
// call observe with the buffered flag
@@ -86,11 +86,12 @@ TEST_F(PerformanceObserverTest, ObserveWithBufferedFlag) {
TEST_F(PerformanceObserverTest, Enqueue) {
V8TestingScope scope;
+ NonThrowableExceptionState exception_state;
Initialize(scope.GetScriptState());
ScriptValue empty_value;
- Persistent<PerformanceEntry> entry =
- PerformanceMark::Create(scope.GetScriptState(), "m", 1234, empty_value);
+ Persistent<PerformanceEntry> entry = PerformanceMark::Create(
+ scope.GetScriptState(), "m", 1234, empty_value, exception_state);
EXPECT_EQ(0, NumPerformanceEntries());
observer_->EnqueuePerformanceEntry(*entry);
@@ -99,11 +100,12 @@ TEST_F(PerformanceObserverTest, Enqueue) {
TEST_F(PerformanceObserverTest, Deliver) {
V8TestingScope scope;
+ NonThrowableExceptionState exception_state;
Initialize(scope.GetScriptState());
ScriptValue empty_value;
- Persistent<PerformanceEntry> entry =
- PerformanceMark::Create(scope.GetScriptState(), "m", 1234, empty_value);
+ Persistent<PerformanceEntry> entry = PerformanceMark::Create(
+ scope.GetScriptState(), "m", 1234, empty_value, exception_state);
EXPECT_EQ(0, NumPerformanceEntries());
observer_->EnqueuePerformanceEntry(*entry);
@@ -115,11 +117,12 @@ TEST_F(PerformanceObserverTest, Deliver) {
TEST_F(PerformanceObserverTest, Disconnect) {
V8TestingScope scope;
+ NonThrowableExceptionState exception_state;
Initialize(scope.GetScriptState());
ScriptValue empty_value;
- Persistent<PerformanceEntry> entry =
- PerformanceMark::Create(scope.GetScriptState(), "m", 1234, empty_value);
+ Persistent<PerformanceEntry> entry = PerformanceMark::Create(
+ scope.GetScriptState(), "m", 1234, empty_value, exception_state);
EXPECT_EQ(0, NumPerformanceEntries());
observer_->EnqueuePerformanceEntry(*entry);
@@ -129,4 +132,4 @@ TEST_F(PerformanceObserverTest, Disconnect) {
EXPECT_FALSE(IsRegistered());
EXPECT_EQ(0, NumPerformanceEntries());
}
-}
+} // namespace blink
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 6ab95ff9e3f..2ffba14396b 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
@@ -44,7 +44,7 @@ namespace blink {
PerformanceResourceTiming::PerformanceResourceTiming(
const WebResourceTimingInfo& info,
- TimeTicks time_origin,
+ base::TimeTicks time_origin,
const AtomicString& initiator_type)
: PerformanceEntry(info.name,
Performance::MonotonicTimeToDOMHighResTimeStamp(
@@ -80,10 +80,12 @@ PerformanceResourceTiming::PerformanceResourceTiming(
// This constructor is for PerformanceNavigationTiming.
PerformanceResourceTiming::PerformanceResourceTiming(
const AtomicString& name,
- TimeTicks time_origin,
+ base::TimeTicks time_origin,
+ bool is_secure_context,
const WebVector<WebServerTimingInfo>& server_timing)
: PerformanceEntry(name, 0.0, 0.0),
time_origin_(time_origin),
+ is_secure_context_(is_secure_context),
server_timing_(
PerformanceServerTiming::FromParsedServerTiming(server_timing)) {}
@@ -235,7 +237,7 @@ DOMHighResTimeStamp PerformanceResourceTiming::connectStart() const {
return domainLookupEnd();
// connectStart includes any DNS time, so we may need to trim that off.
- TimeTicks connect_start = timing->ConnectStart();
+ base::TimeTicks connect_start = timing->ConnectStart();
if (!timing->DnsEnd().is_null())
connect_start = timing->DnsEnd();
@@ -292,7 +294,7 @@ DOMHighResTimeStamp PerformanceResourceTiming::responseStart() const {
if (!timing)
return requestStart();
- TimeTicks response_start = timing->ReceiveHeadersStart();
+ base::TimeTicks response_start = timing->ReceiveHeadersStart();
if (response_start.is_null())
response_start = timing->ReceiveHeadersEnd();
if (response_start.is_null())
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 4b1e8497258..e235bf1a708 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
@@ -52,10 +52,11 @@ class CORE_EXPORT PerformanceResourceTiming : public PerformanceEntry {
// This constructor is for PerformanceNavigationTiming.
// Related doc: https://goo.gl/uNecAj.
PerformanceResourceTiming(const AtomicString& name,
- TimeTicks time_origin,
+ base::TimeTicks time_origin,
+ bool is_secure_context,
const WebVector<WebServerTimingInfo>&);
PerformanceResourceTiming(const WebResourceTimingInfo&,
- TimeTicks time_origin,
+ base::TimeTicks time_origin,
const AtomicString& initiator_type);
~PerformanceResourceTiming() override;
@@ -90,7 +91,7 @@ class CORE_EXPORT PerformanceResourceTiming : public PerformanceEntry {
virtual AtomicString AlpnNegotiatedProtocol() const;
virtual AtomicString ConnectionInfo() const;
- TimeTicks TimeOrigin() const { return time_origin_; }
+ base::TimeTicks TimeOrigin() const { return time_origin_; }
private:
static AtomicString GetNextHopProtocol(
@@ -109,10 +110,10 @@ class CORE_EXPORT PerformanceResourceTiming : public PerformanceEntry {
AtomicString initiator_type_;
AtomicString alpn_negotiated_protocol_;
AtomicString connection_info_;
- TimeTicks time_origin_;
+ base::TimeTicks time_origin_;
scoped_refptr<ResourceLoadTiming> timing_;
- TimeTicks last_redirect_end_time_;
- TimeTicks response_end_;
+ base::TimeTicks last_redirect_end_time_;
+ base::TimeTicks response_end_;
uint64_t transfer_size_ = 0;
uint64_t encoded_body_size_ = 0;
uint64_t decoded_body_size_ = 0;
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 39e7ebd3c47..1c726e0d81d 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_test.cc
+++ b/chromium/third_party/blink/renderer/core/timing/performance_test.cc
@@ -25,7 +25,7 @@ namespace blink {
class TestPerformance : public Performance {
public:
explicit TestPerformance(ScriptState* script_state)
- : Performance(TimeTicks(),
+ : Performance(base::TimeTicks(),
ExecutionContext::From(script_state)
->GetTaskRunner(TaskType::kPerformanceTimeline)) {}
~TestPerformance() override = default;
@@ -183,128 +183,4 @@ TEST_F(PerformanceTest, AllowsTimingRedirect) {
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",
- StringOrPerformanceMeasureOptions::FromString("string"),
- exception_state);
- histograms.ExpectBucketCount("Performance.MeasureParameter.StartMark",
- Performance::MeasureParameterType::kOther, 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",
- StringOrPerformanceMeasureOptions::FromString("string"),
- "string", exception_state);
- histograms.ExpectBucketCount("Performance.MeasureParameter.StartMark",
- Performance::MeasureParameterType::kOther, 1);
- histograms.ExpectBucketCount("Performance.MeasureParameter.EndMark",
- Performance::MeasureParameterType::kOther, 1);
-}
-
-TEST_F(PerformanceTest, MeasureParameters_ObjectType) {
- base::HistogramTester histograms;
- V8TestingScope scope;
- DummyExceptionStateForTesting exception_state;
- Initialize(scope.GetScriptState());
- base_->measure(
- scope.GetScriptState(), "name",
- StringOrPerformanceMeasureOptions::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());
- struct {
- String keyword;
- Performance::MeasureParameterType measure_type;
- } const test_cases[] = {
- {"unloadEventStart",
- Performance::MeasureParameterType::kUnloadEventStart},
- {"unloadEventEnd", Performance::MeasureParameterType::kUnloadEventEnd},
- {"domInteractive", Performance::MeasureParameterType::kDomInteractive},
- {"domContentLoadedEventStart",
- Performance::MeasureParameterType::kDomContentLoadedEventStart},
- {"domContentLoadedEventEnd",
- Performance::MeasureParameterType::kDomContentLoadedEventEnd},
- {"domComplete", Performance::MeasureParameterType::kDomComplete},
- {"loadEventStart", Performance::MeasureParameterType::kLoadEventStart},
- {"loadEventEnd", Performance::MeasureParameterType::kLoadEventEnd},
- {"navigationStart", Performance::MeasureParameterType::kNavigationStart},
- {"redirectStart", Performance::MeasureParameterType::kRedirectStart},
- {"fetchStart", Performance::MeasureParameterType::kFetchStart},
- {"domainLookupStart",
- Performance::MeasureParameterType::kDomainLookupStart},
- {"domainLookupEnd", Performance::MeasureParameterType::kDomainLookupEnd},
- {"connectStart", Performance::MeasureParameterType::kConnectStart},
- {"connectEnd", Performance::MeasureParameterType::kConnectEnd},
- {"secureConnectionStart",
- Performance::MeasureParameterType::kSecureConnectionStart},
- {"requestStart", Performance::MeasureParameterType::kRequestStart},
- {"responseStart", Performance::MeasureParameterType::kResponseStart},
- {"responseEnd", Performance::MeasureParameterType::kResponseEnd},
- {"domLoading", Performance::MeasureParameterType::kDomLoading},
- };
- int count = 0;
- for (const auto& test : test_cases) {
- base_->measure(scope.GetScriptState(), "name",
- StringOrPerformanceMeasureOptions::FromString(test.keyword),
- exception_state);
- histograms.ExpectBucketCount("Performance.MeasureParameter.StartMark",
- test.measure_type, 1);
- histograms.ExpectBucketCount("Performance.MeasureParameter.EndMark",
- Performance::MeasureParameterType::kUnprovided,
- ++count);
- }
-}
-
-TEST_F(PerformanceTest, MeasureParameters_Other) {
- base::HistogramTester histograms;
- V8TestingScope scope;
- DummyExceptionStateForTesting exception_state;
- Initialize(scope.GetScriptState());
- base_->measure(scope.GetScriptState(), "name",
- StringOrPerformanceMeasureOptions::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 7f5957416e9..8bc7afee91a 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_timing.cc
+++ b/chromium/third_party/blink/renderer/core/timing/performance_timing.cc
@@ -52,7 +52,7 @@
// Legacy support for NT1(https://www.w3.org/TR/navigation-timing/).
namespace blink {
-static uint64_t ToIntegerMilliseconds(TimeDelta duration) {
+static uint64_t ToIntegerMilliseconds(base::TimeDelta duration) {
// TODO(npm): add histograms to understand when/why |duration| is sometimes
// negative.
double clamped_seconds =
@@ -141,7 +141,7 @@ uint64_t PerformanceTiming::domainLookupStart() const {
// This will be zero when a DNS request is not performed. Rather than
// exposing a special value that indicates no DNS, we "backfill" with
// fetchStart.
- TimeTicks dns_start = timing->DnsStart();
+ base::TimeTicks dns_start = timing->DnsStart();
if (dns_start.is_null())
return fetchStart();
@@ -156,7 +156,7 @@ uint64_t PerformanceTiming::domainLookupEnd() const {
// This will be zero when a DNS request is not performed. Rather than
// exposing a special value that indicates no DNS, we "backfill" with
// domainLookupStart.
- TimeTicks dns_end = timing->DnsEnd();
+ base::TimeTicks dns_end = timing->DnsEnd();
if (dns_end.is_null())
return domainLookupStart();
@@ -175,7 +175,7 @@ uint64_t PerformanceTiming::connectStart() const {
// connectStart will be zero when a network request is not made. Rather than
// exposing a special value that indicates no new connection, we "backfill"
// with domainLookupEnd.
- TimeTicks connect_start = timing->ConnectStart();
+ base::TimeTicks connect_start = timing->ConnectStart();
if (connect_start.is_null() || loader->GetResponse().ConnectionReused())
return domainLookupEnd();
@@ -200,7 +200,7 @@ uint64_t PerformanceTiming::connectEnd() const {
// connectEnd will be zero when a network request is not made. Rather than
// exposing a special value that indicates no new connection, we "backfill"
// with connectStart.
- TimeTicks connect_end = timing->ConnectEnd();
+ base::TimeTicks connect_end = timing->ConnectEnd();
if (connect_end.is_null() || loader->GetResponse().ConnectionReused())
return connectStart();
@@ -216,7 +216,7 @@ uint64_t PerformanceTiming::secureConnectionStart() const {
if (!timing)
return 0;
- TimeTicks ssl_start = timing->SslStart();
+ base::TimeTicks ssl_start = timing->SslStart();
if (ssl_start.is_null())
return 0;
@@ -237,7 +237,7 @@ uint64_t PerformanceTiming::responseStart() const {
if (!timing)
return requestStart();
- TimeTicks response_start = timing->ReceiveHeadersStart();
+ base::TimeTicks response_start = timing->ReceiveHeadersStart();
if (response_start.is_null())
response_start = timing->ReceiveHeadersEnd();
if (response_start.is_null())
@@ -622,7 +622,7 @@ ScriptValue PerformanceTiming::toJSONForBinding(
}
uint64_t PerformanceTiming::MonotonicTimeToIntegerMilliseconds(
- TimeTicks time) const {
+ base::TimeTicks time) const {
const DocumentLoadTiming* timing = GetDocumentLoadTiming();
if (!timing)
return 0;
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 841737fa9c2..717e20a80f8 100644
--- a/chromium/third_party/blink/renderer/core/timing/performance_timing.h
+++ b/chromium/third_party/blink/renderer/core/timing/performance_timing.h
@@ -150,7 +150,7 @@ class CORE_EXPORT PerformanceTiming final : public ScriptWrappable,
void Trace(blink::Visitor*) override;
- uint64_t MonotonicTimeToIntegerMilliseconds(TimeTicks) const;
+ uint64_t MonotonicTimeToIntegerMilliseconds(base::TimeTicks) const;
std::unique_ptr<TracedValue> GetNavigationTracingData();
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 c1da450a34a..c097e1b6bd5 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
@@ -33,7 +33,7 @@
#include "third_party/blink/renderer/core/timing/performance_mark_options.h"
#include "third_party/blink/renderer/core/timing/performance_measure.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/wtf/text/string_hash.h"
@@ -110,6 +110,11 @@ PerformanceMark* UserTiming::CreatePerformanceMark(
DOMHighResTimeStamp start = 0.0;
if (mark_options && mark_options->hasStartTime()) {
start = mark_options->startTime();
+ if (start < 0.0) {
+ exception_state.ThrowTypeError("'" + mark_name +
+ "' cannot have a negative start time.");
+ return nullptr;
+ }
} else {
start = performance_->now();
}
@@ -130,16 +135,17 @@ PerformanceMark* UserTiming::CreatePerformanceMark(
return nullptr;
}
- return PerformanceMark::Create(script_state, mark_name, start, detail);
+ return PerformanceMark::Create(script_state, mark_name, start, detail,
+ exception_state);
}
void UserTiming::AddMarkToPerformanceTimeline(PerformanceMark& mark) {
if (performance_->timing()) {
- TRACE_EVENT_COPY_MARK1("blink.user_timing", mark.name().Utf8().data(),
+ TRACE_EVENT_COPY_MARK1("blink.user_timing", mark.name().Utf8().c_str(),
"data",
performance_->timing()->GetNavigationTracingData());
} else {
- TRACE_EVENT_COPY_MARK("blink.user_timing", mark.name().Utf8().data());
+ TRACE_EVENT_COPY_MARK("blink.user_timing", mark.name().Utf8().c_str());
}
InsertPerformanceEntry(marks_map_, mark);
DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram,
@@ -191,14 +197,20 @@ double UserTiming::FindExistingMarkStartTime(const AtomicString& mark_name,
return value - timing->navigationStart();
}
-double UserTiming::GetTimeOrFindMarkTime(const StringOrDouble& mark_or_time,
+double UserTiming::GetTimeOrFindMarkTime(const AtomicString& measure_name,
+ const StringOrDouble& mark_or_time,
ExceptionState& exception_state) {
if (mark_or_time.IsString()) {
return FindExistingMarkStartTime(AtomicString(mark_or_time.GetAsString()),
exception_state);
}
DCHECK(mark_or_time.IsDouble());
- return mark_or_time.GetAsDouble();
+ const double time = mark_or_time.GetAsDouble();
+ if (time < 0.0) {
+ exception_state.ThrowTypeError("'" + measure_name +
+ "' cannot have a negative time stamp.");
+ }
+ return time;
}
PerformanceMeasure* UserTiming::Measure(ScriptState* script_state,
@@ -208,12 +220,15 @@ PerformanceMeasure* UserTiming::Measure(ScriptState* script_state,
const ScriptValue& detail,
ExceptionState& exception_state) {
double start_time =
- start.IsNull() ? 0.0 : GetTimeOrFindMarkTime(start, exception_state);
+ start.IsNull()
+ ? 0.0
+ : GetTimeOrFindMarkTime(measure_name, start, exception_state);
if (exception_state.HadException())
return nullptr;
- double end_time = end.IsNull() ? performance_->now()
- : GetTimeOrFindMarkTime(end, exception_state);
+ double end_time =
+ end.IsNull() ? performance_->now()
+ : GetTimeOrFindMarkTime(measure_name, end, exception_state);
if (exception_state.HadException())
return nullptr;
@@ -228,14 +243,17 @@ PerformanceMeasure* UserTiming::Measure(ScriptState* script_state,
WTF::AddFloatToHash(hash, end_time);
TRACE_EVENT_COPY_NESTABLE_ASYNC_BEGIN_WITH_TIMESTAMP0(
- "blink.user_timing", measure_name.Utf8().data(), hash,
+ "blink.user_timing", measure_name.Utf8().c_str(), hash,
trace_event::ToTraceTimestamp(start_time_monotonic));
TRACE_EVENT_COPY_NESTABLE_ASYNC_END_WITH_TIMESTAMP0(
- "blink.user_timing", measure_name.Utf8().data(), hash,
+ "blink.user_timing", measure_name.Utf8().c_str(), hash,
trace_event::ToTraceTimestamp(end_time_monotonic));
- auto* measure = MakeGarbageCollected<PerformanceMeasure>(
- script_state, measure_name, start_time, end_time, detail);
+ PerformanceMeasure* measure =
+ PerformanceMeasure::Create(script_state, measure_name, start_time,
+ end_time, detail, exception_state);
+ if (!measure)
+ return nullptr;
InsertPerformanceEntry(measures_map_, *measure);
if (end_time >= start_time) {
DEFINE_THREAD_SAFE_STATIC_LOCAL(
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 ffb07ce0bc0..fc8df660c16 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
@@ -71,7 +71,8 @@ class UserTiming final : public GarbageCollected<UserTiming> {
private:
double FindExistingMarkStartTime(const AtomicString& mark_name,
ExceptionState&);
- double GetTimeOrFindMarkTime(const StringOrDouble& mark_or_time,
+ double GetTimeOrFindMarkTime(const AtomicString& measure_name,
+ const StringOrDouble& mark_or_time,
ExceptionState&);
Member<Performance> performance_;
diff --git a/chromium/third_party/blink/renderer/core/timing/profiler.idl b/chromium/third_party/blink/renderer/core/timing/profiler.idl
index 9d4897195fb..74760a9dca7 100644
--- a/chromium/third_party/blink/renderer/core/timing/profiler.idl
+++ b/chromium/third_party/blink/renderer/core/timing/profiler.idl
@@ -2,10 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// https://wicg.github.io/js-self-profiling/
-
-typedef any ProfilerTrace;
-
+// https://wicg.github.io/js-self-profiling/#the-profiler-interface
[Exposed=(Window,Worker), RuntimeEnabled=ExperimentalJSProfiler]
interface Profiler {
readonly attribute DOMHighResTimeStamp sampleInterval;
diff --git a/chromium/third_party/blink/renderer/core/timing/profiler_frame.idl b/chromium/third_party/blink/renderer/core/timing/profiler_frame.idl
new file mode 100644
index 00000000000..55e33323d37
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/timing/profiler_frame.idl
@@ -0,0 +1,12 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// https://wicg.github.io/js-self-profiling/#the-profilerframe-dictionary
+
+dictionary ProfilerFrame {
+ required DOMString name;
+ unsigned long long resourceId;
+ unsigned long long line;
+ unsigned long long column;
+};
diff --git a/chromium/third_party/blink/renderer/core/timing/profiler_group.cc b/chromium/third_party/blink/renderer/core/timing/profiler_group.cc
index 769418c68a0..698926c1adc 100644
--- a/chromium/third_party/blink/renderer/core/timing/profiler_group.cc
+++ b/chromium/third_party/blink/renderer/core/timing/profiler_group.cc
@@ -6,9 +6,11 @@
#include "base/time/time.h"
#include "build/build_config.h"
+#include "third_party/blink/renderer/bindings/core/v8/profiler_trace_builder.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/timing/profiler.h"
#include "third_party/blink/renderer/core/timing/profiler_init_options.h"
+#include "third_party/blink/renderer/core/timing/profiler_trace.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"
@@ -23,7 +25,8 @@ namespace {
#if defined(OS_WIN)
// On Windows, assume we have the coarsest possible timer.
-static constexpr int kBaseSampleIntervalMs = Time::kMinLowResolutionThresholdMs;
+static constexpr int kBaseSampleIntervalMs =
+ base::Time::kMinLowResolutionThresholdMs;
#else
// Default to a 10ms base sampling interval on other platforms.
// TODO(acomminos): Reevaluate based on empirical overhead.
@@ -43,18 +46,16 @@ ProfilerGroup* ProfilerGroup::From(v8::Isolate* isolate) {
return profiler_group;
}
+base::TimeDelta ProfilerGroup::GetBaseSampleInterval() {
+ return base::TimeDelta::FromMilliseconds(kBaseSampleIntervalMs);
+}
+
ProfilerGroup::ProfilerGroup(v8::Isolate* isolate)
: isolate_(isolate),
- cpu_profiler_(v8::CpuProfiler::New(isolate, v8::kStandardNaming)),
- next_profiler_id_(0) {
+ cpu_profiler_(nullptr),
+ next_profiler_id_(0),
+ num_active_profilers_(0) {
DCHECK(RuntimeEnabledFeatures::ExperimentalJSProfilerEnabled());
-#if defined(OS_WIN)
- // Avoid busy-waiting on Windows, clamping us to the system clock interrupt
- // interval in the worst case.
- cpu_profiler_->SetUsePreciseSampling(false);
-#endif // defined(OS_WIN)
- cpu_profiler_->SetSamplingInterval(kBaseSampleIntervalMs *
- Time::kMicrosecondsPerMillisecond);
}
Profiler* ProfilerGroup::CreateProfiler(ScriptState* script_state,
@@ -62,22 +63,28 @@ Profiler* ProfilerGroup::CreateProfiler(ScriptState* script_state,
base::TimeTicks time_origin,
ExceptionState& exception_state) {
DCHECK_EQ(script_state->GetIsolate(), isolate_);
- DCHECK(cpu_profiler_);
DCHECK(init_options.hasSampleInterval());
- if (init_options.sampleInterval() < 0) {
- exception_state.ThrowRangeError("Expected non-negative sample interval");
+ const base::TimeDelta sample_interval =
+ base::TimeDelta::FromMillisecondsD(init_options.sampleInterval());
+ const int64_t sample_interval_us = sample_interval.InMicroseconds();
+
+ if (sample_interval_us < 0 ||
+ sample_interval_us > std::numeric_limits<int>::max()) {
+ exception_state.ThrowRangeError("Invalid sample interval");
return nullptr;
}
- // TODO(acomminos): Requires support in V8 for subsampling intervals
- int sample_interval_ms = kBaseSampleIntervalMs;
+ if (!cpu_profiler_)
+ InitV8Profiler();
+ DCHECK(cpu_profiler_);
String profiler_id = NextProfilerId();
- v8::CpuProfilingOptions options(
- v8::kLeafNodeLineNumbers, init_options.hasMaxBufferSize()
- ? init_options.maxBufferSize()
- : v8::CpuProfilingOptions::kNoSampleLimit);
+ v8::CpuProfilingOptions options(v8::kLeafNodeLineNumbers,
+ init_options.hasMaxBufferSize()
+ ? init_options.maxBufferSize()
+ : v8::CpuProfilingOptions::kNoSampleLimit,
+ static_cast<int>(sample_interval_us));
cpu_profiler_->StartProfiling(V8String(isolate_, profiler_id), options);
@@ -87,9 +94,25 @@ Profiler* ProfilerGroup::CreateProfiler(ScriptState* script_state,
scoped_refptr<const SecurityOrigin> source_origin(
execution_context->GetSecurityOrigin());
- auto* profiler = MakeGarbageCollected<Profiler>(
- this, profiler_id, sample_interval_ms, source_origin, time_origin);
+ // The V8 CPU profiler ticks in multiples of the base sampling interval. This
+ // effectively means that we gather samples at the multiple of the base
+ // sampling interval that's greater than or equal to the requested interval.
+ int effective_sample_interval_ms =
+ static_cast<int>(sample_interval.InMilliseconds());
+ if (effective_sample_interval_ms % kBaseSampleIntervalMs != 0 ||
+ effective_sample_interval_ms == 0) {
+ effective_sample_interval_ms +=
+ (kBaseSampleIntervalMs -
+ effective_sample_interval_ms % kBaseSampleIntervalMs);
+ }
+
+ auto* profiler = MakeGarbageCollected<Profiler>(this, profiler_id,
+ effective_sample_interval_ms,
+ source_origin, time_origin);
profilers_.insert(profiler);
+
+ num_active_profilers_++;
+
return profiler;
}
@@ -105,8 +128,8 @@ void ProfilerGroup::WillBeDestroyed() {
DCHECK(profiler->stopped());
}
- cpu_profiler_->Dispose();
- cpu_profiler_ = nullptr;
+ if (cpu_profiler_)
+ TeardownV8Profiler();
}
void ProfilerGroup::Trace(blink::Visitor* visitor) {
@@ -114,6 +137,28 @@ void ProfilerGroup::Trace(blink::Visitor* visitor) {
V8PerIsolateData::GarbageCollectedData::Trace(visitor);
}
+void ProfilerGroup::InitV8Profiler() {
+ DCHECK(!cpu_profiler_);
+ DCHECK_EQ(num_active_profilers_, 0);
+
+ cpu_profiler_ = v8::CpuProfiler::New(isolate_, v8::kStandardNaming);
+#if defined(OS_WIN)
+ // Avoid busy-waiting on Windows, clamping us to the system clock interrupt
+ // interval in the worst case.
+ cpu_profiler_->SetUsePreciseSampling(false);
+#endif // defined(OS_WIN)
+ cpu_profiler_->SetSamplingInterval(kBaseSampleIntervalMs *
+ base::Time::kMicrosecondsPerMillisecond);
+}
+
+void ProfilerGroup::TeardownV8Profiler() {
+ DCHECK(cpu_profiler_);
+ DCHECK_EQ(num_active_profilers_, 0);
+
+ cpu_profiler_->Dispose();
+ cpu_profiler_ = nullptr;
+}
+
void ProfilerGroup::StopProfiler(ScriptState* script_state,
Profiler* profiler,
ScriptPromiseResolver* resolver) {
@@ -123,9 +168,14 @@ void ProfilerGroup::StopProfiler(ScriptState* script_state,
v8::Local<v8::String> profiler_id =
V8String(isolate_, profiler->ProfilerId());
auto* profile = cpu_profiler_->StopProfiling(profiler_id);
- // TODO(acomminos): Process v8::CpuProfile into JS Self-Profiling trace format
- resolver->Resolve();
+ auto* trace = ProfilerTraceBuilder::FromProfile(
+ script_state, profile, profiler->SourceOrigin(), profiler->TimeOrigin());
+ resolver->Resolve(trace);
+
profile->Delete();
+
+ if (--num_active_profilers_ == 0)
+ TeardownV8Profiler();
}
void ProfilerGroup::CancelProfiler(Profiler* profiler) {
@@ -138,6 +188,9 @@ void ProfilerGroup::CancelProfiler(Profiler* profiler) {
auto* profile = cpu_profiler_->StopProfiling(profiler_id);
profile->Delete();
+
+ if (--num_active_profilers_ == 0)
+ TeardownV8Profiler();
}
String ProfilerGroup::NextProfilerId() {
diff --git a/chromium/third_party/blink/renderer/core/timing/profiler_group.h b/chromium/third_party/blink/renderer/core/timing/profiler_group.h
index 0bb205e4634..8a74fdc75e6 100644
--- a/chromium/third_party/blink/renderer/core/timing/profiler_group.h
+++ b/chromium/third_party/blink/renderer/core/timing/profiler_group.h
@@ -30,6 +30,8 @@ class CORE_EXPORT ProfilerGroup
public:
static ProfilerGroup* From(v8::Isolate*);
+ static base::TimeDelta GetBaseSampleInterval();
+
ProfilerGroup(v8::Isolate* isolate);
~ProfilerGroup() override;
@@ -44,6 +46,9 @@ class CORE_EXPORT ProfilerGroup
private:
friend class Profiler;
+ void InitV8Profiler();
+ void TeardownV8Profiler();
+
void StopProfiler(ScriptState*, Profiler*, ScriptPromiseResolver*);
// Cancels a profiler, discarding its associated trace.
@@ -55,6 +60,7 @@ class CORE_EXPORT ProfilerGroup
v8::Isolate* const isolate_;
v8::CpuProfiler* cpu_profiler_;
int next_profiler_id_;
+ int num_active_profilers_;
HeapHashSet<WeakMember<Profiler>> profilers_;
diff --git a/chromium/third_party/blink/renderer/core/timing/profiler_group_test.cc b/chromium/third_party/blink/renderer/core/timing/profiler_group_test.cc
index 410cc91aaeb..c54cdfe288c 100644
--- a/chromium/third_party/blink/renderer/core/timing/profiler_group_test.cc
+++ b/chromium/third_party/blink/renderer/core/timing/profiler_group_test.cc
@@ -62,4 +62,86 @@ TEST(ProfilerGroupTest, StopProfilerOnGroupDeallocate) {
EXPECT_TRUE(profiler->stopped());
}
+TEST(ProfilerGroupTest, CreateProfiler) {
+ V8TestingScope scope;
+
+ ProfilerGroup* profiler_group = ProfilerGroup::From(scope.GetIsolate());
+
+ ProfilerInitOptions* init_options = ProfilerInitOptions::Create();
+ init_options->setSampleInterval(10);
+ Profiler* profiler = profiler_group->CreateProfiler(
+ scope.GetScriptState(), *init_options, base::TimeTicks(),
+ scope.GetExceptionState());
+
+ EXPECT_FALSE(profiler->stopped());
+ EXPECT_FALSE(scope.GetExceptionState().HadException());
+}
+
+TEST(ProfilerGroupTest, ClampedSamplingIntervalZero) {
+ V8TestingScope scope;
+
+ ProfilerGroup* profiler_group = ProfilerGroup::From(scope.GetIsolate());
+
+ ProfilerInitOptions* init_options = ProfilerInitOptions::Create();
+ init_options->setSampleInterval(0);
+ Profiler* profiler = profiler_group->CreateProfiler(
+ scope.GetScriptState(), *init_options, base::TimeTicks(),
+ scope.GetExceptionState());
+
+ EXPECT_FALSE(profiler->stopped());
+ EXPECT_FALSE(scope.GetExceptionState().HadException());
+ // Verify that the sample interval clamped to the next non-zero supported
+ // interval.
+ EXPECT_EQ(profiler->sampleInterval(),
+ ProfilerGroup::GetBaseSampleInterval().InMilliseconds());
+}
+
+TEST(ProfilerGroupTest, ClampedSamplingIntervalNext) {
+ V8TestingScope scope;
+
+ ProfilerGroup* profiler_group = ProfilerGroup::From(scope.GetIsolate());
+
+ ProfilerInitOptions* init_options = ProfilerInitOptions::Create();
+ init_options->setSampleInterval((ProfilerGroup::GetBaseSampleInterval() +
+ base::TimeDelta::FromMilliseconds(1))
+ .InMilliseconds());
+ Profiler* profiler = profiler_group->CreateProfiler(
+ scope.GetScriptState(), *init_options, base::TimeTicks(),
+ scope.GetExceptionState());
+
+ EXPECT_FALSE(profiler->stopped());
+ EXPECT_FALSE(scope.GetExceptionState().HadException());
+ // Verify that the sample interval clamped to the next highest supported
+ // interval.
+ EXPECT_EQ(profiler->sampleInterval(),
+ (ProfilerGroup::GetBaseSampleInterval() * 2).InMilliseconds());
+}
+
+TEST(ProfilerGroupTest, NegativeSamplingInterval) {
+ V8TestingScope scope;
+
+ ProfilerGroup* profiler_group = ProfilerGroup::From(scope.GetIsolate());
+
+ ProfilerInitOptions* init_options = ProfilerInitOptions::Create();
+ init_options->setSampleInterval(-10);
+ profiler_group->CreateProfiler(scope.GetScriptState(), *init_options,
+ base::TimeTicks(), scope.GetExceptionState());
+
+ EXPECT_TRUE(scope.GetExceptionState().HadException());
+}
+
+TEST(ProfilerGroupTest, OverflowSamplingInterval) {
+ V8TestingScope scope;
+
+ ProfilerGroup* profiler_group = ProfilerGroup::From(scope.GetIsolate());
+
+ ProfilerInitOptions* init_options = ProfilerInitOptions::Create();
+ init_options->setSampleInterval((double)std::numeric_limits<int>::max() +
+ 1.f);
+ profiler_group->CreateProfiler(scope.GetScriptState(), *init_options,
+ base::TimeTicks(), scope.GetExceptionState());
+
+ EXPECT_TRUE(scope.GetExceptionState().HadException());
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/timing/profiler_init_options.idl b/chromium/third_party/blink/renderer/core/timing/profiler_init_options.idl
index 6903c44b671..a9f2ab00498 100644
--- a/chromium/third_party/blink/renderer/core/timing/profiler_init_options.idl
+++ b/chromium/third_party/blink/renderer/core/timing/profiler_init_options.idl
@@ -2,8 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-// https://wicg.github.io/js-self-profiling/
-
+// https://wicg.github.io/js-self-profiling/#dom-profilerinitoptions
dictionary ProfilerInitOptions {
required DOMHighResTimeStamp sampleInterval;
unsigned long maxBufferSize;
diff --git a/chromium/third_party/blink/renderer/core/timing/profiler_sample.idl b/chromium/third_party/blink/renderer/core/timing/profiler_sample.idl
new file mode 100644
index 00000000000..bea7c30b233
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/timing/profiler_sample.idl
@@ -0,0 +1,10 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// https://wicg.github.io/js-self-profiling/#the-profilersample-dictionary
+
+dictionary ProfilerSample {
+ required DOMHighResTimeStamp timestamp;
+ unsigned long long stackId;
+};
diff --git a/chromium/third_party/blink/renderer/core/timing/profiler_stack.idl b/chromium/third_party/blink/renderer/core/timing/profiler_stack.idl
new file mode 100644
index 00000000000..5b53e4d4b10
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/timing/profiler_stack.idl
@@ -0,0 +1,10 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// https://wicg.github.io/js-self-profiling/#the-profilerstack-dictionary
+
+dictionary ProfilerStack {
+ unsigned long long parentId;
+ required unsigned long long frameId;
+};
diff --git a/chromium/third_party/blink/renderer/core/timing/profiler_trace.idl b/chromium/third_party/blink/renderer/core/timing/profiler_trace.idl
new file mode 100644
index 00000000000..352f4a0d59e
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/timing/profiler_trace.idl
@@ -0,0 +1,12 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// https://wicg.github.io/js-self-profiling/#the-profilertrace-dictionary
+
+dictionary ProfilerTrace {
+ required sequence<DOMString> resources;
+ required sequence<ProfilerFrame> frames;
+ required sequence<ProfilerStack> stacks;
+ required sequence<ProfilerSample> samples;
+};
diff --git a/chromium/third_party/blink/renderer/core/timing/sub_task_attribution.cc b/chromium/third_party/blink/renderer/core/timing/sub_task_attribution.cc
index e7079af56a7..caaaa0ef31d 100644
--- a/chromium/third_party/blink/renderer/core/timing/sub_task_attribution.cc
+++ b/chromium/third_party/blink/renderer/core/timing/sub_task_attribution.cc
@@ -8,8 +8,8 @@ namespace blink {
SubTaskAttribution::SubTaskAttribution(const AtomicString& sub_task_name,
const String& script_url,
- TimeTicks start_time,
- TimeDelta duration)
+ base::TimeTicks start_time,
+ base::TimeDelta duration)
: sub_task_name_(sub_task_name),
script_url_(script_url),
start_time_(start_time),
diff --git a/chromium/third_party/blink/renderer/core/timing/sub_task_attribution.h b/chromium/third_party/blink/renderer/core/timing/sub_task_attribution.h
index 781d3feec5b..af4faeb7b74 100644
--- a/chromium/third_party/blink/renderer/core/timing/sub_task_attribution.h
+++ b/chromium/third_party/blink/renderer/core/timing/sub_task_attribution.h
@@ -9,7 +9,7 @@
#include "third_party/blink/renderer/core/dom/dom_high_res_time_stamp.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
@@ -23,12 +23,12 @@ class SubTaskAttribution {
SubTaskAttribution(const AtomicString& sub_task_name,
const String& script_url,
- TimeTicks start_time,
- TimeDelta duration);
+ base::TimeTicks start_time,
+ base::TimeDelta duration);
inline AtomicString subTaskName() const { return sub_task_name_; }
inline String scriptURL() const { return script_url_; }
- inline TimeTicks startTime() const { return start_time_; }
- inline TimeDelta duration() const { return duration_; }
+ inline base::TimeTicks startTime() const { return start_time_; }
+ inline base::TimeDelta duration() const { return duration_; }
inline DOMHighResTimeStamp highResStartTime() const {
return high_res_start_time_;
@@ -46,8 +46,8 @@ class SubTaskAttribution {
private:
AtomicString sub_task_name_;
String script_url_;
- TimeTicks start_time_;
- TimeDelta duration_;
+ base::TimeTicks start_time_;
+ base::TimeDelta duration_;
DOMHighResTimeStamp high_res_start_time_;
DOMHighResTimeStamp high_res_duration_;
};
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 8f294563f06..1664bb3f692 100644
--- a/chromium/third_party/blink/renderer/core/timing/time_clamper.h
+++ b/chromium/third_party/blink/renderer/core/timing/time_clamper.h
@@ -8,7 +8,7 @@
#include "base/macros.h"
#include "build/build_config.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include <stdint.h>
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 70844162bb0..763aa258515 100644
--- a/chromium/third_party/blink/renderer/core/timing/window_performance.cc
+++ b/chromium/third_party/blink/renderer/core/timing/window_performance.cc
@@ -39,18 +39,19 @@
#include "third_party/blink/renderer/core/dom/qualified_name.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/use_counter.h"
#include "third_party/blink/renderer/core/html/html_frame_owner_element.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/timing/largest_contentful_paint.h"
#include "third_party/blink/renderer/core/timing/layout_shift.h"
#include "third_party/blink/renderer/core/timing/performance_element_timing.h"
#include "third_party/blink/renderer/core/timing/performance_event_timing.h"
#include "third_party/blink/renderer/core/timing/performance_timing.h"
-#include "third_party/blink/renderer/platform/cross_thread_functional.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_timing_info.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
static constexpr base::TimeDelta kLongTaskObserverThreshold =
base::TimeDelta::FromMilliseconds(50);
@@ -119,14 +120,14 @@ bool IsSameOrigin(const AtomicString& key) {
} // namespace
-static TimeTicks ToTimeOrigin(LocalDOMWindow* window) {
+static base::TimeTicks ToTimeOrigin(LocalDOMWindow* window) {
Document* document = window->document();
if (!document)
- return TimeTicks();
+ return base::TimeTicks();
DocumentLoader* loader = document->Loader();
if (!loader)
- return TimeTicks();
+ return base::TimeTicks();
return loader->GetTiming().ReferenceMonotonicTime();
}
@@ -321,16 +322,10 @@ void WindowPerformance::ReportLongTask(
}
}
-// We buffer Element Timing and Event Timing (long-latency events) entries until
-// onload, i.e., LoadEventStart is not reached yet.
-bool WindowPerformance::ShouldBufferEntries() {
- return !timing() || !timing()->loadEventStart();
-}
-
void WindowPerformance::RegisterEventTiming(const AtomicString& event_type,
- TimeTicks start_time,
- TimeTicks processing_start,
- TimeTicks processing_end,
+ base::TimeTicks start_time,
+ base::TimeTicks processing_start,
+ base::TimeTicks processing_end,
bool cancelable) {
// |start_time| could be null in some tests that inject input.
DCHECK(!processing_start.is_null());
@@ -357,7 +352,7 @@ void WindowPerformance::RegisterEventTiming(const AtomicString& event_type,
}
void WindowPerformance::ReportEventTimings(WebWidgetClient::SwapResult result,
- TimeTicks timestamp) {
+ base::TimeTicks timestamp) {
DOMHighResTimeStamp end_time = MonotonicTimeToDOMHighResTimeStamp(timestamp);
bool event_timing_enabled =
RuntimeEnabledFeatures::EventTimingEnabled(GetExecutionContext());
@@ -386,31 +381,29 @@ void WindowPerformance::ReportEventTimings(WebWidgetClient::SwapResult result,
NotifyObserversOfEntry(*entry);
}
- if (ShouldBufferEntries() && !IsEventTimingBufferFull())
+ if (!IsEventTimingBufferFull())
AddEventTimingBuffer(*entry);
}
event_timings_.clear();
}
void WindowPerformance::AddElementTiming(const AtomicString& name,
+ const String& url,
const FloatRect& rect,
- TimeTicks start_time,
- TimeTicks response_end,
+ base::TimeTicks start_time,
+ base::TimeTicks load_time,
const AtomicString& identifier,
const IntSize& intrinsic_size,
const AtomicString& id,
Element* element) {
DCHECK(RuntimeEnabledFeatures::ElementTimingEnabled(GetExecutionContext()));
PerformanceElementTiming* entry = PerformanceElementTiming::Create(
- name, rect, MonotonicTimeToDOMHighResTimeStamp(start_time),
- MonotonicTimeToDOMHighResTimeStamp(response_end), identifier,
+ name, url, rect, MonotonicTimeToDOMHighResTimeStamp(start_time),
+ MonotonicTimeToDOMHighResTimeStamp(load_time), identifier,
intrinsic_size.Width(), intrinsic_size.Height(), id, element);
- if (HasObserverFor(PerformanceEntry::kElement)) {
- UseCounter::Count(GetExecutionContext(),
- WebFeature::kElementTimingExplicitlyRequested);
+ if (HasObserverFor(PerformanceEntry::kElement))
NotifyObserversOfEntry(*entry);
- }
- if (ShouldBufferEntries() && !IsElementTimingBufferFull())
+ if (!IsElementTimingBufferFull())
AddElementTimingBuffer(*entry);
}
@@ -418,7 +411,7 @@ void WindowPerformance::DispatchFirstInputTiming(
PerformanceEventTiming* entry) {
if (!entry)
return;
- DCHECK_EQ("firstInput", entry->entryType());
+ DCHECK_EQ("first-input", entry->entryType());
if (HasObserverFor(PerformanceEntry::kFirstInput)) {
UseCounter::Count(GetExecutionContext(),
WebFeature::kEventTimingExplicitlyRequested);
@@ -429,14 +422,37 @@ void WindowPerformance::DispatchFirstInputTiming(
first_input_timing_ = entry;
}
-void WindowPerformance::AddLayoutJankFraction(double jank_fraction) {
+void WindowPerformance::AddLayoutJankFraction(double jank_fraction,
+ bool input_detected,
+ base::TimeTicks input_timestamp) {
DCHECK(RuntimeEnabledFeatures::LayoutInstabilityAPIEnabled(
GetExecutionContext()));
- auto* entry = MakeGarbageCollected<LayoutShift>(now(), jank_fraction);
- if (HasObserverFor(PerformanceEntry::kLayoutJank))
+ auto* entry = MakeGarbageCollected<LayoutShift>(
+ now(), jank_fraction, input_detected,
+ input_detected ? MonotonicTimeToDOMHighResTimeStamp(input_timestamp)
+ : 0.0);
+ if (HasObserverFor(PerformanceEntry::kLayoutShift))
+ NotifyObserversOfEntry(*entry);
+ AddLayoutJankBuffer(*entry);
+}
+
+void WindowPerformance::OnLargestContentfulPaintUpdated(
+ base::TimeTicks paint_time,
+ uint64_t paint_size,
+ base::TimeTicks load_time,
+ const AtomicString& id,
+ const String& url,
+ Element* element) {
+ double render_timestamp = MonotonicTimeToDOMHighResTimeStamp(paint_time);
+ double load_timestamp = MonotonicTimeToDOMHighResTimeStamp(load_time);
+ double start_timestamp =
+ render_timestamp != 0.0 ? render_timestamp : load_timestamp;
+ auto* entry = MakeGarbageCollected<LargestContentfulPaint>(
+ start_timestamp, render_timestamp, paint_size, load_timestamp, id, url,
+ element);
+ if (HasObserverFor(PerformanceEntry::kLargestContentfulPaint))
NotifyObserversOfEntry(*entry);
- if (ShouldBufferEntries())
- AddLayoutJankBuffer(*entry);
+ AddLargestContentfulPaint(entry);
}
} // namespace blink
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 25559465122..43fe1f4e534 100644
--- a/chromium/third_party/blink/renderer/core/timing/window_performance.h
+++ b/chromium/third_party/blink/renderer/core/timing/window_performance.h
@@ -63,29 +63,37 @@ class CORE_EXPORT WindowPerformance final : public Performance,
void UpdateLongTaskInstrumentation() override;
- bool ShouldBufferEntries();
-
bool FirstInputDetected() const { return !!first_input_timing_; }
// This method creates a PerformanceEventTiming and if needed creates a swap
// promise to calculate the |duration| attribute when such promise is
// resolved.
void RegisterEventTiming(const AtomicString& event_type,
- TimeTicks start_time,
- TimeTicks processing_start,
- TimeTicks processing_end,
+ base::TimeTicks start_time,
+ base::TimeTicks processing_start,
+ base::TimeTicks processing_end,
bool cancelable);
void AddElementTiming(const AtomicString& name,
+ const String& url,
const FloatRect& rect,
- TimeTicks start_time,
- TimeTicks response_end,
+ base::TimeTicks start_time,
+ base::TimeTicks load_time,
const AtomicString& identifier,
const IntSize& intrinsic_size,
const AtomicString& id,
Element*);
- void AddLayoutJankFraction(double jank_fraction);
+ void AddLayoutJankFraction(double jank_fraction,
+ bool input_detected,
+ base::TimeTicks input_timestamp);
+
+ void OnLargestContentfulPaintUpdated(base::TimeTicks paint_time,
+ uint64_t paint_size,
+ base::TimeTicks load_time,
+ const AtomicString& id,
+ const String& url,
+ Element*);
void Trace(blink::Visitor*) override;
@@ -110,7 +118,7 @@ class CORE_EXPORT WindowPerformance final : public Performance,
// Method called once swap promise is resolved. It will add all event timings
// that have not been added since the last swap promise.
void ReportEventTimings(WebWidgetClient::SwapResult result,
- TimeTicks timestamp);
+ base::TimeTicks timestamp);
void DispatchFirstInputTiming(PerformanceEventTiming* entry);
diff --git a/chromium/third_party/blink/renderer/core/timing/window_performance_test.cc b/chromium/third_party/blink/renderer/core/timing/window_performance_test.cc
index 24ea9964ceb..8fe7b9568fd 100644
--- a/chromium/third_party/blink/renderer/core/timing/window_performance_test.cc
+++ b/chromium/third_party/blink/renderer/core/timing/window_performance_test.cc
@@ -23,8 +23,8 @@ namespace blink {
namespace {
-TimeTicks GetTimeOrigin() {
- return TimeTicks() + TimeDelta::FromSeconds(500);
+base::TimeTicks GetTimeOrigin() {
+ return base::TimeTicks() + base::TimeDelta::FromSeconds(500);
}
} // namespace
@@ -63,7 +63,7 @@ class WindowPerformanceTest : public testing::Test {
base::TimeTicks(), base::TimeTicks() + base::TimeDelta::FromSeconds(1));
}
- void SimulateSwapPromise(TimeTicks timestamp) {
+ void SimulateSwapPromise(base::TimeTicks timestamp) {
performance_->ReportEventTimings(WebWidgetClient::SwapResult::kDidSwap,
timestamp);
}
@@ -173,7 +173,7 @@ TEST(PerformanceLifetimeTest, SurviveContextSwitch) {
auto* document_loader = page_holder->GetFrame().Loader().GetDocumentLoader();
ASSERT_TRUE(document_loader);
- document_loader->GetTiming().SetNavigationStart(CurrentTimeTicks());
+ document_loader->GetTiming().SetNavigationStart(base::TimeTicks::Now());
EXPECT_EQ(&page_holder->GetFrame(), perf->GetFrame());
EXPECT_EQ(&page_holder->GetFrame(), timing->GetFrame());
@@ -200,15 +200,15 @@ TEST_F(WindowPerformanceTest, EnsureEntryListOrder) {
V8TestingScope scope;
auto initial_offset =
test_task_runner_->NowTicks().since_origin().InSecondsF();
- test_task_runner_->FastForwardBy(GetTimeOrigin() - TimeTicks());
+ test_task_runner_->FastForwardBy(GetTimeOrigin() - base::TimeTicks());
DummyExceptionStateForTesting exception_state;
- test_task_runner_->FastForwardBy(TimeDelta::FromSeconds(2));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromSeconds(2));
for (int i = 0; i < 8; i++) {
performance_->mark(scope.GetScriptState(), AtomicString::Number(i),
exception_state);
}
- test_task_runner_->FastForwardBy(TimeDelta::FromSeconds(2));
+ test_task_runner_->FastForwardBy(base::TimeDelta::FromSeconds(2));
for (int i = 8; i < 17; i++) {
performance_->mark(scope.GetScriptState(), AtomicString::Number(i),
exception_state);
@@ -225,19 +225,22 @@ TEST_F(WindowPerformanceTest, EnsureEntryListOrder) {
}
}
-TEST_F(WindowPerformanceTest, EventTimingBeforeOnLoad) {
+TEST_F(WindowPerformanceTest, EventTimingEntryBuffering) {
ScopedEventTimingForTest event_timing(true);
EXPECT_TRUE(page_holder_->GetFrame().Loader().GetDocumentLoader());
- TimeTicks start_time = GetTimeOrigin() + TimeDelta::FromSecondsD(1.1);
- TimeTicks processing_start = GetTimeOrigin() + TimeDelta::FromSecondsD(3.3);
- TimeTicks processing_end = GetTimeOrigin() + TimeDelta::FromSecondsD(3.8);
+ base::TimeTicks start_time =
+ GetTimeOrigin() + base::TimeDelta::FromSecondsD(1.1);
+ base::TimeTicks processing_start =
+ GetTimeOrigin() + base::TimeDelta::FromSecondsD(3.3);
+ base::TimeTicks processing_end =
+ GetTimeOrigin() + base::TimeDelta::FromSecondsD(3.8);
performance_->RegisterEventTiming("click", start_time, processing_start,
processing_end, false);
- TimeTicks swap_time = GetTimeOrigin() + TimeDelta::FromSecondsD(6.0);
+ base::TimeTicks swap_time =
+ GetTimeOrigin() + base::TimeDelta::FromSecondsD(6.0);
SimulateSwapPromise(swap_time);
- EXPECT_EQ(1u, performance_->getEntriesByName("click", "event").size());
- performance_->clearEventTimings();
+ EXPECT_EQ(1u, performance_->getBufferedEntriesByType("event").size());
page_holder_->GetFrame()
.Loader()
@@ -247,62 +250,66 @@ TEST_F(WindowPerformanceTest, EventTimingBeforeOnLoad) {
performance_->RegisterEventTiming("click", start_time, processing_start,
processing_end, true);
SimulateSwapPromise(swap_time);
- EXPECT_EQ(0u, performance_->getEntriesByName("click", "event").size());
- performance_->clearEventTimings();
+ EXPECT_EQ(2u, performance_->getBufferedEntriesByType("event").size());
EXPECT_TRUE(page_holder_->GetFrame().Loader().GetDocumentLoader());
- GetFrame()->PrepareForCommit();
+ GetFrame()->DetachDocument();
EXPECT_FALSE(page_holder_->GetFrame().Loader().GetDocumentLoader());
performance_->RegisterEventTiming("click", start_time, processing_start,
processing_end, false);
SimulateSwapPromise(swap_time);
- EXPECT_EQ(1u, performance_->getEntriesByName("click", "event").size());
- performance_->clearEventTimings();
+ EXPECT_EQ(3u, performance_->getBufferedEntriesByType("event").size());
}
TEST_F(WindowPerformanceTest, Expose100MsEvents) {
ScopedEventTimingForTest event_timing(true);
- TimeTicks start_time = GetTimeOrigin() + TimeDelta::FromSeconds(1);
- TimeTicks processing_start = start_time + TimeDelta::FromMilliseconds(10);
- TimeTicks processing_end = processing_start + TimeDelta::FromMilliseconds(10);
+ base::TimeTicks start_time =
+ GetTimeOrigin() + base::TimeDelta::FromSeconds(1);
+ base::TimeTicks processing_start =
+ start_time + base::TimeDelta::FromMilliseconds(10);
+ base::TimeTicks processing_end =
+ processing_start + base::TimeDelta::FromMilliseconds(10);
performance_->RegisterEventTiming("mousedown", start_time, processing_start,
processing_end, false);
- TimeTicks start_time2 = start_time + TimeDelta::FromMicroseconds(200);
+ base::TimeTicks start_time2 =
+ start_time + base::TimeDelta::FromMicroseconds(200);
performance_->RegisterEventTiming("click", start_time2, processing_start,
processing_end, false);
// The swap time is 100.1 ms after |start_time| but only 99.9 ms after
// |start_time2|.
- TimeTicks swap_time = start_time + TimeDelta::FromMicroseconds(100100);
+ base::TimeTicks swap_time =
+ start_time + base::TimeDelta::FromMicroseconds(100100);
SimulateSwapPromise(swap_time);
// Only the longer event should have been reported.
- EXPECT_EQ(1u, performance_->getEntriesByType("event").size());
- EXPECT_EQ(1u, performance_->getEntriesByName("mousedown", "event").size());
- EXPECT_EQ(0u, performance_->getEntriesByName("click", "event").size());
+ const auto& entries = performance_->getBufferedEntriesByType("event");
+ EXPECT_EQ(1u, entries.size());
+ EXPECT_EQ("mousedown", entries.at(0)->name());
}
TEST_F(WindowPerformanceTest, EventTimingDuration) {
ScopedEventTimingForTest event_timing(true);
- TimeTicks start_time = GetTimeOrigin() + TimeDelta::FromMilliseconds(1000);
- TimeTicks processing_start =
- GetTimeOrigin() + TimeDelta::FromMilliseconds(1001);
- TimeTicks processing_end =
- GetTimeOrigin() + TimeDelta::FromMilliseconds(1002);
+ base::TimeTicks start_time =
+ GetTimeOrigin() + base::TimeDelta::FromMilliseconds(1000);
+ base::TimeTicks processing_start =
+ GetTimeOrigin() + base::TimeDelta::FromMilliseconds(1001);
+ base::TimeTicks processing_end =
+ GetTimeOrigin() + base::TimeDelta::FromMilliseconds(1002);
performance_->RegisterEventTiming("click", start_time, processing_start,
processing_end, false);
- TimeTicks short_swap_time =
- GetTimeOrigin() + TimeDelta::FromMilliseconds(1003);
+ base::TimeTicks short_swap_time =
+ GetTimeOrigin() + base::TimeDelta::FromMilliseconds(1003);
SimulateSwapPromise(short_swap_time);
- EXPECT_EQ(0u, performance_->getEntriesByName("click", "event").size());
+ EXPECT_EQ(0u, performance_->getBufferedEntriesByType("event").size());
performance_->RegisterEventTiming("click", start_time, processing_start,
processing_end, true);
- TimeTicks long_swap_time =
- GetTimeOrigin() + TimeDelta::FromMilliseconds(2000);
+ base::TimeTicks long_swap_time =
+ GetTimeOrigin() + base::TimeDelta::FromMilliseconds(2000);
SimulateSwapPromise(long_swap_time);
- EXPECT_EQ(1u, performance_->getEntriesByName("click", "event").size());
+ EXPECT_EQ(1u, performance_->getBufferedEntriesByType("event").size());
performance_->RegisterEventTiming("click", start_time, processing_start,
processing_end, true);
@@ -310,7 +317,7 @@ TEST_F(WindowPerformanceTest, EventTimingDuration) {
performance_->RegisterEventTiming("click", start_time, processing_start,
processing_end, false);
SimulateSwapPromise(long_swap_time);
- EXPECT_EQ(2u, performance_->getEntriesByName("click", "event").size());
+ EXPECT_EQ(2u, performance_->getBufferedEntriesByType("event").size());
}
TEST_F(WindowPerformanceTest, MultipleEventsSameSwap) {
@@ -318,20 +325,23 @@ TEST_F(WindowPerformanceTest, MultipleEventsSameSwap) {
size_t num_events = 10;
for (size_t i = 0; i < num_events; ++i) {
- TimeTicks start_time = GetTimeOrigin() + TimeDelta::FromSeconds(i);
- TimeTicks processing_start = start_time + TimeDelta::FromMilliseconds(100);
- TimeTicks processing_end = start_time + TimeDelta::FromMilliseconds(200);
+ base::TimeTicks start_time =
+ GetTimeOrigin() + base::TimeDelta::FromSeconds(i);
+ base::TimeTicks processing_start =
+ start_time + base::TimeDelta::FromMilliseconds(100);
+ base::TimeTicks processing_end =
+ start_time + base::TimeDelta::FromMilliseconds(200);
performance_->RegisterEventTiming("click", start_time, processing_start,
processing_end, false);
- EXPECT_EQ(0u, performance_->getEntriesByName("click", "event").size());
+ EXPECT_EQ(0u, performance_->getBufferedEntriesByType("event").size());
}
- TimeTicks swap_time = GetTimeOrigin() + TimeDelta::FromSeconds(num_events);
+ base::TimeTicks swap_time =
+ GetTimeOrigin() + base::TimeDelta::FromSeconds(num_events);
SimulateSwapPromise(swap_time);
- EXPECT_EQ(num_events,
- performance_->getEntriesByName("click", "event").size());
+ EXPECT_EQ(num_events, performance_->getBufferedEntriesByType("event").size());
}
-// Test for existence of 'firstInput' given different types of first events.
+// Test for existence of 'first-input' given different types of first events.
TEST_F(WindowPerformanceTest, FirstInput) {
struct {
AtomicString event_type;
@@ -341,14 +351,14 @@ TEST_F(WindowPerformanceTest, FirstInput) {
{"mousedown", true}, {"mousemove", false},
{"mouseover", false}};
for (const auto& input : inputs) {
- // firstInput does not have a |duration| threshold so use close values.
+ // first-input does not have a |duration| threshold so use close values.
performance_->RegisterEventTiming(
input.event_type, GetTimeOrigin(),
- GetTimeOrigin() + TimeDelta::FromMilliseconds(1),
- GetTimeOrigin() + TimeDelta::FromMilliseconds(2), false);
- SimulateSwapPromise(GetTimeOrigin() + TimeDelta::FromMilliseconds(3));
+ GetTimeOrigin() + base::TimeDelta::FromMilliseconds(1),
+ GetTimeOrigin() + base::TimeDelta::FromMilliseconds(2), false);
+ SimulateSwapPromise(GetTimeOrigin() + base::TimeDelta::FromMilliseconds(3));
PerformanceEntryVector firstInputs =
- performance_->getEntriesByType("firstInput");
+ performance_->getEntriesByType("first-input");
EXPECT_GE(1u, firstInputs.size());
EXPECT_EQ(input.should_report, firstInputs.size() == 1u);
ResetPerformance();
@@ -362,32 +372,35 @@ TEST_F(WindowPerformanceTest, FirstInputAfterIgnored) {
for (const auto& event : several_events) {
performance_->RegisterEventTiming(
event, GetTimeOrigin(),
- GetTimeOrigin() + TimeDelta::FromMilliseconds(1),
- GetTimeOrigin() + TimeDelta::FromMilliseconds(2), false);
+ GetTimeOrigin() + base::TimeDelta::FromMilliseconds(1),
+ GetTimeOrigin() + base::TimeDelta::FromMilliseconds(2), false);
}
- SimulateSwapPromise(GetTimeOrigin() + TimeDelta::FromMilliseconds(3));
- ASSERT_EQ(1u, performance_->getEntriesByType("firstInput").size());
+ SimulateSwapPromise(GetTimeOrigin() + base::TimeDelta::FromMilliseconds(3));
+ ASSERT_EQ(1u, performance_->getEntriesByType("first-input").size());
EXPECT_EQ("mousedown",
- performance_->getEntriesByType("firstInput")[0]->name());
+ performance_->getEntriesByType("first-input")[0]->name());
}
// Test that pointerdown followed by pointerup works as a 'firstInput'.
TEST_F(WindowPerformanceTest, FirstPointerUp) {
- TimeTicks start_time = GetTimeOrigin();
- TimeTicks processing_start = GetTimeOrigin() + TimeDelta::FromMilliseconds(1);
- TimeTicks processing_end = GetTimeOrigin() + TimeDelta::FromMilliseconds(2);
- TimeTicks swap_time = GetTimeOrigin() + TimeDelta::FromMilliseconds(3);
+ base::TimeTicks start_time = GetTimeOrigin();
+ base::TimeTicks processing_start =
+ GetTimeOrigin() + base::TimeDelta::FromMilliseconds(1);
+ base::TimeTicks processing_end =
+ GetTimeOrigin() + base::TimeDelta::FromMilliseconds(2);
+ base::TimeTicks swap_time =
+ GetTimeOrigin() + base::TimeDelta::FromMilliseconds(3);
performance_->RegisterEventTiming("pointerdown", start_time, processing_start,
processing_end, false);
SimulateSwapPromise(swap_time);
- EXPECT_EQ(0u, performance_->getEntriesByType("firstInput").size());
+ EXPECT_EQ(0u, performance_->getEntriesByType("first-input").size());
performance_->RegisterEventTiming("pointerup", start_time, processing_start,
processing_end, false);
SimulateSwapPromise(swap_time);
- EXPECT_EQ(1u, performance_->getEntriesByType("firstInput").size());
+ EXPECT_EQ(1u, performance_->getEntriesByType("first-input").size());
// The name of the entry should be "pointerdown".
- EXPECT_EQ(1u,
- performance_->getEntriesByName("pointerdown", "firstInput").size());
+ EXPECT_EQ(
+ 1u, performance_->getEntriesByName("pointerdown", "first-input").size());
}
} // namespace blink
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 e4dbf180502..25746832c1e 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
@@ -4,7 +4,7 @@
#include "third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.h"
-#include "third_party/blink/public/mojom/web_feature/web_feature.mojom-shared.h"
+#include "third_party/blink/public/mojom/web_feature/web_feature.mojom-blink.h"
#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_trusted_html.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_trusted_script.h"
@@ -13,9 +13,9 @@
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.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/trustedtypes/trusted_type_policy.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/wtf/text/string_hash.h"
namespace blink {
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 3cc03c1ff13..a27005b567f 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
@@ -6,7 +6,7 @@
[
Exposed=(Window, Worker),
- OriginTrialEnabled=TrustedDOMTypes
+ RuntimeEnabled=TrustedDOMTypes
] interface TrustedTypePolicyFactory {
[RaisesException, Unforgeable] TrustedTypePolicy createPolicy(DOMString policyName, TrustedTypePolicyOptions policyOptions, optional boolean exposed = false);
[Unforgeable] TrustedTypePolicy getExposedPolicy(DOMString policyName);
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 6607d2ecb33..15f369b3fd0 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
@@ -14,6 +14,8 @@
#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/dom/node.h"
+#include "third_party/blink/renderer/core/dom/text.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
#include "third_party/blink/renderer/core/trustedtypes/trusted_html.h"
#include "third_party/blink/renderer/core/trustedtypes/trusted_script.h"
@@ -22,11 +24,16 @@
#include "third_party/blink/renderer/core/trustedtypes/trusted_type_policy_factory.h"
#include "third_party/blink/renderer/core/trustedtypes/trusted_url.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
+#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
namespace blink {
namespace {
+// This value is derived from the Trusted Types spec (draft), and determines the
+// maximum length of the sample value in the violation reports.
+const unsigned kReportedValueMaximumLength = 40;
+
enum TrustedTypeViolationKind {
kAnyTrustedTypeAssignment,
kTrustedHTMLAssignment,
@@ -37,6 +44,8 @@ enum TrustedTypeViolationKind {
kTrustedScriptAssignmentAndDefaultPolicyFailed,
kTrustedURLAssignmentAndDefaultPolicyFailed,
kTrustedScriptURLAssignmentAndDefaultPolicyFailed,
+ kTextNodeScriptAssignment,
+ kTextNodeScriptAssignmentAndDefaultPolicyFailed,
};
const char* GetMessage(TrustedTypeViolationKind kind) {
@@ -63,11 +72,45 @@ const char* GetMessage(TrustedTypeViolationKind kind) {
case kTrustedScriptURLAssignmentAndDefaultPolicyFailed:
return "This document requires 'TrustedScriptURL' assignment and the "
"'default' policy failed to execute.";
+ case kTextNodeScriptAssignment:
+ return "This document requires 'TrustedScript' assignment, "
+ "and inserting a text node into a script element is equivalent to "
+ "a 'TrustedScript' assignment.";
+ case kTextNodeScriptAssignmentAndDefaultPolicyFailed:
+ return "This document requires 'TrustedScript' assignment. "
+ "Inserting a text node into a script element is equivalent to "
+ "a 'TrustedScript' assignment and the default policy failed to "
+ "execute.";
}
NOTREACHED();
return "";
}
+std::pair<String, String> GetMessageAndSample(
+ TrustedTypeViolationKind kind,
+ const ExceptionState& exception_state,
+ const String& value) {
+ const char* interface_name = exception_state.InterfaceName();
+ const char* property_name = exception_state.PropertyName();
+
+ // We have two sample formats, one for eval and one for assignment.
+ // If we don't have the required values being passed in, just leave the
+ // sample empty.
+ StringBuilder sample;
+ if (interface_name && strcmp("eval", interface_name) == 0) {
+ sample.Append("eval");
+ } else if (interface_name && property_name) {
+ sample.Append(interface_name);
+ sample.Append(".");
+ sample.Append(property_name);
+ }
+ if (!sample.IsEmpty()) {
+ sample.Append(" ");
+ sample.Append(value.Left(kReportedValueMaximumLength));
+ }
+ return std::make_pair<String, String>(GetMessage(kind), sample.ToString());
+}
+
// Handle failure of a Trusted Type assignment.
//
// If trusted type assignment fails, we need to
@@ -78,7 +121,8 @@ const char* GetMessage(TrustedTypeViolationKind kind) {
// Returns whether the failure should be enforced.
bool TrustedTypeFail(TrustedTypeViolationKind kind,
const ExecutionContext* execution_context,
- ExceptionState& exception_state) {
+ ExceptionState& exception_state,
+ const String& value) {
if (!execution_context)
return true;
@@ -87,26 +131,29 @@ bool TrustedTypeFail(TrustedTypeViolationKind kind,
if (execution_context->GetTrustedTypes())
execution_context->GetTrustedTypes()->CountTrustedTypeAssignmentError();
- const char* message = GetMessage(kind);
+ String message;
+ String sample;
+ std::tie(message, sample) = GetMessageAndSample(kind, exception_state, value);
bool allow = execution_context->GetSecurityContext()
.GetContentSecurityPolicy()
- ->AllowTrustedTypeAssignmentFailure(message);
+ ->AllowTrustedTypeAssignmentFailure(message, sample);
if (!allow) {
exception_state.ThrowTypeError(message);
}
return !allow;
}
-bool RequireTrustedTypes(const ExecutionContext* execution_context) {
- return execution_context && execution_context->RequireTrustedTypes();
-}
-
TrustedTypePolicy* GetDefaultPolicy(const ExecutionContext* execution_context) {
return execution_context->GetTrustedTypes()->getExposedPolicy("default");
}
} // namespace
+bool RequireTrustedTypesCheck(const ExecutionContext* execution_context) {
+ return execution_context && execution_context->RequireTrustedTypes() &&
+ !ContentSecurityPolicy::ShouldBypassMainWorld(execution_context);
+}
+
String GetStringFromTrustedType(
const StringOrTrustedHTMLOrTrustedScriptOrTrustedScriptURLOrTrustedURL&
string_or_trusted_type,
@@ -115,9 +162,10 @@ String GetStringFromTrustedType(
DCHECK(!string_or_trusted_type.IsNull());
if (string_or_trusted_type.IsString() &&
- RequireTrustedTypes(execution_context)) {
- TrustedTypeFail(kAnyTrustedTypeAssignment, execution_context,
- exception_state);
+ RequireTrustedTypesCheck(execution_context)) {
+ TrustedTypeFail(
+ kAnyTrustedTypeAssignment, execution_context, exception_state,
+ GetStringFromTrustedTypeWithoutCheck(string_or_trusted_type));
return g_empty_string;
}
@@ -157,6 +205,8 @@ String GetStringFromSpecificTrustedType(
const ExecutionContext* execution_context,
ExceptionState& exception_state) {
switch (specific_trusted_type) {
+ case SpecificTrustedType::kNone:
+ return GetStringFromTrustedTypeWithoutCheck(string_or_trusted_type);
case SpecificTrustedType::kTrustedHTML: {
StringOrTrustedHTML string_or_trusted_html =
string_or_trusted_type.IsTrustedHTML()
@@ -220,7 +270,7 @@ String GetStringFromTrustedHTML(StringOrTrustedHTML string_or_trusted_html,
String GetStringFromTrustedHTML(const String& string,
const ExecutionContext* execution_context,
ExceptionState& exception_state) {
- bool require_trusted_type = RequireTrustedTypes(execution_context);
+ bool require_trusted_type = RequireTrustedTypesCheck(execution_context);
if (!require_trusted_type) {
return string;
}
@@ -228,7 +278,7 @@ String GetStringFromTrustedHTML(const String& string,
TrustedTypePolicy* default_policy = GetDefaultPolicy(execution_context);
if (!default_policy) {
if (TrustedTypeFail(kTrustedHTMLAssignment, execution_context,
- exception_state)) {
+ exception_state, string)) {
return g_empty_string;
}
return string;
@@ -239,7 +289,7 @@ String GetStringFromTrustedHTML(const String& string,
if (exception_state.HadException()) {
exception_state.ClearException();
TrustedTypeFail(kTrustedHTMLAssignmentAndDefaultPolicyFailed,
- execution_context, exception_state);
+ execution_context, exception_state, string);
return g_empty_string;
}
@@ -256,46 +306,43 @@ String GetStringFromTrustedScript(
// string_or_trusted_script.IsNull(), unlike the various similar methods in
// this file.
- bool require_trusted_type = RequireTrustedTypes(execution_context);
- 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());
+ if (string_or_trusted_script.IsNull()) {
+ string_or_trusted_script =
+ StringOrTrustedScript::FromString(g_empty_string);
+ }
+ return GetStringFromTrustedScript(string_or_trusted_script.GetAsString(),
+ execution_context, exception_state);
+}
+
+String GetStringFromTrustedScript(const String& potential_script,
+ const ExecutionContext* execution_context,
+ ExceptionState& exception_state) {
+ bool require_trusted_type = RequireTrustedTypesCheck(execution_context);
+ if (!require_trusted_type) {
+ return potential_script;
+ }
TrustedTypePolicy* default_policy = GetDefaultPolicy(execution_context);
if (!default_policy) {
if (TrustedTypeFail(kTrustedScriptAssignment, execution_context,
- exception_state)) {
+ exception_state, potential_script)) {
return g_empty_string;
}
- if (string_or_trusted_script.IsNull())
- return g_empty_string;
- return string_or_trusted_script.GetAsString();
+ return potential_script;
}
- const String& string_value_or_empty =
- string_or_trusted_script.IsNull()
- ? g_empty_string
- : string_or_trusted_script.GetAsString();
TrustedScript* result = default_policy->CreateScript(
- execution_context->GetIsolate(), string_value_or_empty, exception_state);
+ execution_context->GetIsolate(), potential_script, exception_state);
DCHECK_EQ(!result, exception_state.HadException());
if (exception_state.HadException()) {
exception_state.ClearException();
TrustedTypeFail(kTrustedScriptAssignmentAndDefaultPolicyFailed,
- execution_context, exception_state);
+ execution_context, exception_state, potential_script);
return g_empty_string;
}
@@ -307,35 +354,36 @@ String GetStringFromTrustedScriptURL(
const ExecutionContext* execution_context,
ExceptionState& exception_state) {
DCHECK(!string_or_trusted_script_url.IsNull());
+ if (string_or_trusted_script_url.IsTrustedScriptURL()) {
+ return string_or_trusted_script_url.GetAsTrustedScriptURL()->toString();
+ }
+
+ DCHECK(string_or_trusted_script_url.IsString());
+ String string = string_or_trusted_script_url.GetAsString();
bool require_trusted_type =
- RequireTrustedTypes(execution_context) &&
+ RequireTrustedTypesCheck(execution_context) &&
RuntimeEnabledFeatures::TrustedDOMTypesEnabled(execution_context);
- 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();
+ if (!require_trusted_type) {
+ return string;
}
TrustedTypePolicy* default_policy = GetDefaultPolicy(execution_context);
if (!default_policy) {
if (TrustedTypeFail(kTrustedScriptURLAssignment, execution_context,
- exception_state)) {
+ exception_state, string)) {
return g_empty_string;
}
- return string_or_trusted_script_url.GetAsString();
+ return string;
}
TrustedScriptURL* result = default_policy->CreateScriptURL(
- execution_context->GetIsolate(),
- string_or_trusted_script_url.GetAsString(), exception_state);
+ execution_context->GetIsolate(), string, exception_state);
if (exception_state.HadException()) {
exception_state.ClearException();
TrustedTypeFail(kTrustedScriptURLAssignmentAndDefaultPolicyFailed,
- execution_context, exception_state);
+ execution_context, exception_state, string);
return g_empty_string;
}
@@ -346,36 +394,65 @@ String GetStringFromTrustedURL(USVStringOrTrustedURL string_or_trusted_url,
const ExecutionContext* execution_context,
ExceptionState& exception_state) {
DCHECK(!string_or_trusted_url.IsNull());
-
- bool require_trusted_type = RequireTrustedTypes(execution_context);
- 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();
}
+ DCHECK(string_or_trusted_url.IsUSVString());
+ String string = string_or_trusted_url.GetAsUSVString();
+
+ bool require_trusted_type = RequireTrustedTypesCheck(execution_context);
+ if (!require_trusted_type) {
+ return string;
+ }
+
TrustedTypePolicy* default_policy = GetDefaultPolicy(execution_context);
if (!default_policy) {
if (TrustedTypeFail(kTrustedURLAssignment, execution_context,
- exception_state)) {
+ exception_state, string)) {
return g_empty_string;
}
- return string_or_trusted_url.GetAsUSVString();
+ return string;
}
TrustedURL* result = default_policy->CreateURL(
- execution_context->GetIsolate(), string_or_trusted_url.GetAsUSVString(),
- exception_state);
+ execution_context->GetIsolate(), string, exception_state);
if (exception_state.HadException()) {
exception_state.ClearException();
TrustedTypeFail(kTrustedURLAssignmentAndDefaultPolicyFailed,
- execution_context, exception_state);
+ execution_context, exception_state, string);
return g_empty_string;
}
return result->toString();
}
+Node* TrustedTypesCheckForHTMLScriptElement(Node* child,
+ Document* doc,
+ ExceptionState& exception_state) {
+ bool require_trusted_type = RequireTrustedTypesCheck(doc);
+ if (!require_trusted_type)
+ return child;
+
+ TrustedTypePolicy* default_policy = GetDefaultPolicy(doc);
+ if (!default_policy) {
+ return TrustedTypeFail(kTextNodeScriptAssignment, doc, exception_state,
+ child->textContent())
+ ? nullptr
+ : child;
+ }
+
+ TrustedScript* result = default_policy->CreateScript(
+ doc->GetIsolate(), child->textContent(), exception_state);
+ if (exception_state.HadException()) {
+ exception_state.ClearException();
+ return TrustedTypeFail(kTextNodeScriptAssignmentAndDefaultPolicyFailed, doc,
+ exception_state, child->textContent())
+ ? nullptr
+ : child;
+ }
+
+ return Text::Create(*doc, result->toString());
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/trustedtypes/trusted_types_util.h b/chromium/third_party/blink/renderer/core/trustedtypes/trusted_types_util.h
index 65c1181678c..fc84a0b4421 100644
--- a/chromium/third_party/blink/renderer/core/trustedtypes/trusted_types_util.h
+++ b/chromium/third_party/blink/renderer/core/trustedtypes/trusted_types_util.h
@@ -10,8 +10,10 @@
namespace blink {
+class Document;
class ExecutionContext;
class ExceptionState;
+class Node;
class StringOrTrustedHTML;
class StringOrTrustedHTMLOrTrustedScriptOrTrustedScriptURLOrTrustedURL;
class StringOrTrustedScript;
@@ -19,6 +21,7 @@ class StringOrTrustedScriptURL;
class USVStringOrTrustedURL;
enum class SpecificTrustedType {
+ kNone,
kTrustedHTML,
kTrustedScript,
kTrustedScriptURL,
@@ -51,6 +54,10 @@ String CORE_EXPORT GetStringFromTrustedScript(StringOrTrustedScript,
const ExecutionContext*,
ExceptionState&);
+String GetStringFromTrustedScript(const String&,
+ const ExecutionContext*,
+ ExceptionState&);
+
String CORE_EXPORT GetStringFromTrustedScriptURL(StringOrTrustedScriptURL,
const ExecutionContext*,
ExceptionState&);
@@ -58,6 +65,26 @@ String CORE_EXPORT GetStringFromTrustedScriptURL(StringOrTrustedScriptURL,
String CORE_EXPORT GetStringFromTrustedURL(USVStringOrTrustedURL,
const ExecutionContext*,
ExceptionState&);
+
+// For <script> elements, we need to treat insertion of DOM text nodes
+// as equivalent to string assignment. This checks the child-node to be
+// inserted and runs all of the Trusted Types checks if it's a text node.
+//
+// Returns nullptr if the check failed, or the node to use (possibly child)
+// if they succeeded.
+Node* TrustedTypesCheckForHTMLScriptElement(Node* child,
+ Document*,
+ ExceptionState&);
+
+// Determine whether a Trusted Types check is needed in this execution context.
+//
+// Note: All methods above handle this internally and will return success if a
+// check is not required. However, in cases where not-required doesn't
+// immediately imply "okay" this method can be used.
+// Example: To determine whether 'eval' may pass, one needs to also take CSP
+// into account.
+bool CORE_EXPORT RequireTrustedTypesCheck(const ExecutionContext*);
+
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_TRUSTEDTYPES_TRUSTED_TYPES_UTIL_H_
diff --git a/chromium/third_party/blink/renderer/core/typed_arrays/dom_array_buffer.cc b/chromium/third_party/blink/renderer/core/typed_arrays/dom_array_buffer.cc
index 769b4271921..dd38aeddc62 100644
--- a/chromium/third_party/blink/renderer/core/typed_arrays/dom_array_buffer.cc
+++ b/chromium/third_party/blink/renderer/core/typed_arrays/dom_array_buffer.cc
@@ -102,4 +102,25 @@ DOMArrayBuffer* DOMArrayBuffer::Create(
return Create(ArrayBuffer::Create(contents));
}
+DOMArrayBuffer* DOMArrayBuffer::Create(
+ const Vector<base::span<const char>>& data) {
+ size_t size = 0;
+ for (const auto& span : data) {
+ size += span.size();
+ }
+ WTF::ArrayBufferContents contents(size, 1,
+ WTF::ArrayBufferContents::kNotShared,
+ WTF::ArrayBufferContents::kDontInitialize);
+ uint8_t* ptr = static_cast<uint8_t*>(contents.Data());
+ if (UNLIKELY(!ptr))
+ OOM_CRASH();
+
+ for (const auto& span : data) {
+ memcpy(ptr, span.data(), span.size());
+ ptr += span.size();
+ }
+
+ return Create(ArrayBuffer::Create(contents));
+}
+
} // namespace blink
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 975463ec98f..6d579076a0e 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
@@ -5,9 +5,11 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_TYPED_ARRAYS_DOM_ARRAY_BUFFER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_TYPED_ARRAYS_DOM_ARRAY_BUFFER_H_
+#include "base/containers/span.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/typed_arrays/dom_array_buffer_base.h"
#include "third_party/blink/renderer/platform/wtf/typed_arrays/array_buffer.h"
+#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
@@ -31,6 +33,7 @@ class CORE_EXPORT DOMArrayBuffer final : public DOMArrayBufferBase {
return Create(WTF::ArrayBuffer::Create(contents));
}
static DOMArrayBuffer* Create(scoped_refptr<SharedBuffer>);
+ static DOMArrayBuffer* Create(const Vector<base::span<const char>>&);
// Only for use by XMLHttpRequest::responseArrayBuffer and
// Internals::serializeObject.
diff --git a/chromium/third_party/blink/renderer/core/url/dom_url_utils.cc b/chromium/third_party/blink/renderer/core/url/dom_url_utils.cc
index 6e05c1b6ee7..50dcb710aab 100644
--- a/chromium/third_party/blink/renderer/core/url/dom_url_utils.cc
+++ b/chromium/third_party/blink/renderer/core/url/dom_url_utils.cc
@@ -97,8 +97,10 @@ void DOMURLUtils::setPort(const String& value) {
KURL kurl = Url();
if (!kurl.CanSetHostOrPort())
return;
-
- kurl.SetPort(value);
+ if (!value.IsEmpty())
+ kurl.SetPort(value);
+ else
+ kurl.RemovePort();
SetURL(kurl);
}
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 fd43bb89e4d..65db947ce84 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
@@ -48,7 +48,7 @@ class URLSearchParamsIterationSource final
bool CompareParams(const std::pair<String, String>& a,
const std::pair<String, String>& b) {
- return WTF::CodePointCompareLessThan(a.first, b.first);
+ return WTF::CodeUnitCompareLessThan(a.first, b.first);
}
} // namespace
@@ -133,8 +133,10 @@ void URLSearchParams::RunUpdateSteps() {
}
static String DecodeString(String input) {
+ // |DecodeURLMode::kUTF8| is used because "UTF-8 decode without BOM" should
+ // be performed (see https://url.spec.whatwg.org/#concept-urlencoded-parser).
return DecodeURLEscapeSequences(input.Replace('+', ' '),
- DecodeURLMode::kUTF8OrIsomorphic);
+ DecodeURLMode::kUTF8);
}
void URLSearchParams::SetInputWithoutUpdate(const String& query_string) {
diff --git a/chromium/third_party/blink/renderer/core/workers/BUILD.gn b/chromium/third_party/blink/renderer/core/workers/BUILD.gn
index 28acb5029e5..c3ca5e597c2 100644
--- a/chromium/third_party/blink/renderer/core/workers/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/workers/BUILD.gn
@@ -18,19 +18,6 @@ blink_core_sources("workers") {
"dedicated_worker_object_proxy.h",
"dedicated_worker_thread.cc",
"dedicated_worker_thread.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",
"global_scope_creation_params.h",
"installed_scripts_manager.cc",
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 9c221ad625e..d1202690a5b 100644
--- a/chromium/third_party/blink/renderer/core/workers/dedicated_worker.cc
+++ b/chromium/third_party/blink/renderer/core/workers/dedicated_worker.cc
@@ -20,10 +20,10 @@
#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/execution_context/execution_context.h"
+#include "third_party/blink/renderer/core/fetch/request.h"
#include "third_party/blink/renderer/core/fileapi/public_url_manager.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/main_thread_debugger.h"
#include "third_party/blink/renderer/core/loader/appcache/application_cache_host.h"
#include "third_party/blink/renderer/core/loader/document_loader.h"
@@ -41,8 +41,8 @@
#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/bindings/script_state.h"
-#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/instrumentation/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher_properties.h"
#include "third_party/blink/renderer/platform/weborigin/security_policy.h"
@@ -149,11 +149,24 @@ DedicatedWorker::DedicatedWorker(ExecutionContext* context,
DCHECK(context->IsContextThread());
DCHECK(script_request_url_.IsValid());
DCHECK(context_proxy_);
+
+ // For nested workers, ensure the inside ResourceFetcher because it may not
+ // have been used yet.
+ // For documents, the ResourceFetcher is always already valid.
+ if (auto* scope = DynamicTo<WorkerGlobalScope>(*context))
+ scope->EnsureFetcher();
+
+ outside_fetch_client_settings_object_ =
+ MakeGarbageCollected<FetchClientSettingsObjectSnapshot>(
+ context->Fetcher()->GetProperties().GetFetchClientSettingsObject());
}
-DedicatedWorker::~DedicatedWorker() {
+DedicatedWorker::~DedicatedWorker() = default;
+
+void DedicatedWorker::Dispose() {
DCHECK(!GetExecutionContext() || GetExecutionContext()->IsContextThread());
context_proxy_->ParentObjectDestroyed();
+ factory_client_.reset();
}
void DedicatedWorker::postMessage(ScriptState* script_state,
@@ -208,9 +221,19 @@ void DedicatedWorker::Start() {
// calling into the debugger can cause a breakpoint.
v8_stack_trace_id_ = ThreadDebugger::From(GetExecutionContext()->GetIsolate())
->StoreCurrentStackTrace("Worker Created");
- if (auto* scope = DynamicTo<WorkerGlobalScope>(*GetExecutionContext()))
- scope->EnsureFetcher();
if (blink::features::IsPlzDedicatedWorkerEnabled()) {
+ // For classic script, always use "same-origin" credentials mode.
+ // https://html.spec.whatwg.org/C/#fetch-a-classic-worker-script
+ // For module script, respect the credentials mode specified by
+ // WorkerOptions.
+ // https://html.spec.whatwg.org/C/#workeroptions
+ auto credentials_mode = network::mojom::CredentialsMode::kSameOrigin;
+ if (options_->type() == "module") {
+ bool result = Request::ParseCredentialsMode(options_->credentials(),
+ &credentials_mode);
+ DCHECK(result);
+ }
+
mojom::blink::BlobURLTokenPtr blob_url_token;
if (script_request_url_.ProtocolIs("blob") &&
BlobUtils::MojoBlobURLsEnabled()) {
@@ -221,6 +244,11 @@ void DedicatedWorker::Start() {
factory_client_->CreateWorkerHost(
script_request_url_,
WebSecurityOrigin(GetExecutionContext()->GetSecurityOrigin()),
+ credentials_mode,
+ WebSecurityOrigin(
+ outside_fetch_client_settings_object_->GetSecurityOrigin()),
+ outside_fetch_client_settings_object_->GetReferrerPolicy(),
+ KURL(outside_fetch_client_settings_object_->GetOutgoingReferrer()),
blob_url_token.PassInterface().PassHandle());
// Continue in OnScriptLoadStarted() or OnScriptLoadStartFailed().
return;
@@ -248,8 +276,8 @@ void DedicatedWorker::Start() {
classic_script_loader_->LoadTopLevelScriptAsynchronously(
*GetExecutionContext(), GetExecutionContext()->Fetcher(),
script_request_url_, mojom::RequestContextType::WORKER,
- network::mojom::FetchRequestMode::kSameOrigin,
- network::mojom::FetchCredentialsMode::kSameOrigin,
+ network::mojom::RequestMode::kSameOrigin,
+ network::mojom::CredentialsMode::kSameOrigin,
WTF::Bind(&DedicatedWorker::OnResponse, WrapPersistent(this)),
WTF::Bind(&DedicatedWorker::OnFinished, WrapPersistent(this)));
return;
@@ -397,17 +425,11 @@ void DedicatedWorker::ContinueStart(
network::mojom::ReferrerPolicy referrer_policy,
base::Optional<mojom::IPAddressSpace> response_address_space,
const String& source_code) {
- auto* outside_settings_object =
- MakeGarbageCollected<FetchClientSettingsObjectSnapshot>(
- GetExecutionContext()
- ->Fetcher()
- ->GetProperties()
- .GetFetchClientSettingsObject());
context_proxy_->StartWorkerGlobalScope(
CreateGlobalScopeCreationParams(script_url, off_main_thread_fetch_option,
referrer_policy, response_address_space),
- options_, script_url, *outside_settings_object, v8_stack_trace_id_,
- source_code);
+ options_, script_url, *outside_fetch_client_settings_object_,
+ v8_stack_trace_id_, source_code);
}
std::unique_ptr<GlobalScopeCreationParams>
@@ -475,12 +497,11 @@ DedicatedWorker::CreateWebWorkerFetchContext() {
// This worker is being created by an existing worker (i.e., nested workers).
// Clone the worker fetch context from the parent's one.
- // TODO(nhiroki): Create WebWorkerFetchContext using |factory_client_| when
- // PlzDedicatedWorker is enabled (https://crbug.com/906991).
auto* scope = To<WorkerGlobalScope>(GetExecutionContext());
- return static_cast<WorkerFetchContext&>(scope->Fetcher()->Context())
- .GetWebWorkerFetchContext()
- ->CloneForNestedWorker(scope->GetTaskRunner(TaskType::kNetworking));
+ return factory_client_->CloneWorkerFetchContext(
+ static_cast<WorkerFetchContext&>(scope->Fetcher()->Context())
+ .GetWebWorkerFetchContext(),
+ scope->GetTaskRunner(TaskType::kNetworking));
}
const AtomicString& DedicatedWorker::InterfaceName() const {
@@ -513,8 +534,9 @@ void DedicatedWorker::ContextLifecycleStateChanged(
}
void DedicatedWorker::Trace(blink::Visitor* visitor) {
- visitor->Trace(context_proxy_);
visitor->Trace(options_);
+ visitor->Trace(outside_fetch_client_settings_object_);
+ visitor->Trace(context_proxy_);
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 a305ae06e31..ec220869fd3 100644
--- a/chromium/third_party/blink/renderer/core/workers/dedicated_worker.h
+++ b/chromium/third_party/blink/renderer/core/workers/dedicated_worker.h
@@ -18,6 +18,7 @@
#include "third_party/blink/renderer/core/workers/global_scope_creation_params.h"
#include "third_party/blink/renderer/core/workers/worker_options.h"
#include "third_party/blink/renderer/platform/graphics/begin_frame_provider.h"
+#include "third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object_snapshot.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "v8/include/v8-inspector.h"
@@ -69,9 +70,9 @@ class CORE_EXPORT DedicatedWorker final
public WebDedicatedWorker {
DEFINE_WRAPPERTYPEINFO();
USING_GARBAGE_COLLECTED_MIXIN(DedicatedWorker);
- // Eager finalization is needed to notify the parent object destruction of the
+ // Pre-finalization is needed to notify the parent object destruction of the
// GC-managed messaging proxy and to initiate worker termination.
- EAGERLY_FINALIZE();
+ USING_PRE_FINALIZER(DedicatedWorker, Dispose);
public:
static DedicatedWorker* Create(ExecutionContext*,
@@ -84,6 +85,8 @@ class CORE_EXPORT DedicatedWorker final
const WorkerOptions*);
~DedicatedWorker() override;
+ void Dispose();
+
void postMessage(ScriptState*,
const ScriptValue& message,
Vector<ScriptValue>& transfer,
@@ -142,6 +145,8 @@ class CORE_EXPORT DedicatedWorker final
const KURL script_request_url_;
Member<const WorkerOptions> options_;
+ Member<const FetchClientSettingsObjectSnapshot>
+ outside_fetch_client_settings_object_;
const Member<DedicatedWorkerMessagingProxy> context_proxy_;
Member<WorkerClassicScriptLoader> classic_script_loader_;
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 faa4b0438fc..1325215587c 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
@@ -99,7 +99,7 @@ DedicatedWorkerGlobalScope::DedicatedWorkerGlobalScope(
std::unique_ptr<Vector<String>> outside_origin_trial_tokens)
: WorkerGlobalScope(std::move(creation_params), thread, time_origin) {
// Dedicated workers don't need to pause after script fetch.
- ReadyToRunClassicScript();
+ ReadyToRunWorkerScript();
// Inherit the outside's origin trial tokens.
OriginTrialContext::AddTokens(this, outside_origin_trial_tokens.get());
}
@@ -172,8 +172,8 @@ void DedicatedWorkerGlobalScope::FetchAndRunClassicScript(
*this,
CreateOutsideSettingsFetcher(outside_settings_object,
outside_resource_timing_notifier),
- script_url, destination, network::mojom::FetchRequestMode::kSameOrigin,
- network::mojom::FetchCredentialsMode::kSameOrigin,
+ script_url, destination, network::mojom::RequestMode::kSameOrigin,
+ network::mojom::CredentialsMode::kSameOrigin,
WTF::Bind(&DedicatedWorkerGlobalScope::DidReceiveResponseForClassicScript,
WrapWeakPersistent(this),
WrapPersistent(classic_script_loader)),
@@ -187,7 +187,7 @@ void DedicatedWorkerGlobalScope::FetchAndRunModuleScript(
const KURL& module_url_record,
const FetchClientSettingsObjectSnapshot& outside_settings_object,
WorkerResourceTimingNotifier& outside_resource_timing_notifier,
- network::mojom::FetchCredentialsMode credentials_mode) {
+ network::mojom::CredentialsMode credentials_mode) {
// Step 12: "Let destination be "sharedworker" if is shared is true, and
// "worker" otherwise."
mojom::RequestContextType destination = mojom::RequestContextType::WORKER;
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 36bcb564074..a2942ee57f2 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
@@ -90,7 +90,7 @@ class CORE_EXPORT DedicatedWorkerGlobalScope final : public WorkerGlobalScope {
const KURL& module_url_record,
const FetchClientSettingsObjectSnapshot& outside_settings_object,
WorkerResourceTimingNotifier& outside_resource_timing_notifier,
- network::mojom::FetchCredentialsMode) override;
+ network::mojom::CredentialsMode) override;
// Called by the bindings (dedicated_worker_global_scope.idl).
const String name() const;
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 151458af87b..03063be69b8 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
@@ -5,7 +5,7 @@
#include "third_party/blink/renderer/core/workers/dedicated_worker_messaging_proxy.h"
#include <memory>
-#include "services/network/public/mojom/fetch_api.mojom-shared.h"
+#include "services/network/public/mojom/fetch_api.mojom-blink.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"
@@ -21,8 +21,8 @@
#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_options.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/wtf/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/wtf/wtf.h"
namespace blink {
@@ -86,7 +86,7 @@ void DedicatedWorkerMessagingProxy::StartWorkerGlobalScope(
// "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;
+ network::mojom::CredentialsMode credentials_mode;
bool result = Request::ParseCredentialsMode(options->credentials(),
&credentials_mode);
DCHECK(result);
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 4e963e8766e..0347fe0d0c6 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,7 +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 "services/network/public/mojom/referrer_policy.mojom-blink.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"
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 ae7793cb0a0..7f30a4732f4 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
@@ -47,8 +47,8 @@
#include "third_party/blink/renderer/core/workers/parent_execution_context_task_runners.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/scheduler/public/post_cross_thread_task.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
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 53a84e372ef..9b4ced8e9cd 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
@@ -23,9 +23,9 @@
#include "third_party/blink/renderer/core/workers/worker_backing_thread_startup_data.h"
#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/testing/unit_test_helpers.h"
#include "third_party/blink/renderer/platform/weborigin/security_policy.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
namespace blink {
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 8d982a44f93..351add9b194 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
@@ -41,7 +41,6 @@
#include "third_party/blink/renderer/core/workers/dedicated_worker_object_proxy.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/platform/web_thread_supporting_gc.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/OWNERS b/chromium/third_party/blink/renderer/core/workers/experimental/OWNERS
deleted file mode 100644
index 193f2830a14..00000000000
--- a/chromium/third_party/blink/renderer/core/workers/experimental/OWNERS
+++ /dev/null
@@ -1,4 +0,0 @@
-japhet@chromium.org
-
-# TEAM: worker-dev@chromium.org
-# COMPONENT: Blink>Workers
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/README.md b/chromium/third_party/blink/renderer/core/workers/experimental/README.md
deleted file mode 100644
index fbc340eb14b..00000000000
--- a/chromium/third_party/blink/renderer/core/workers/experimental/README.md
+++ /dev/null
@@ -1,17 +0,0 @@
-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
deleted file mode 100644
index 4b380e1fcc5..00000000000
--- a/chromium/third_party/blink/renderer/core/workers/experimental/task.cc
+++ /dev/null
@@ -1,507 +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/experimental/task.h"
-
-#include <utility>
-
-#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 {
-
-// worker_thread_ only.
-class TaskBase::AsyncFunctionCompleted : public ScriptFunction {
- public:
- static v8::Local<v8::Function> CreateFunction(ScriptState* script_state,
- TaskBase* task,
- State state) {
- return (MakeGarbageCollected<AsyncFunctionCompleted>(script_state, task,
- state))
- ->BindToV8Function();
- }
-
- AsyncFunctionCompleted(ScriptState* script_state, TaskBase* task, State state)
- : ScriptFunction(script_state), task_(task), state_(state) {}
-
- ScriptValue Call(ScriptValue v) override {
- task_->TaskCompletedOnWorkerThread(v.V8Value(), state_);
- return ScriptValue();
- }
-
- private:
- CrossThreadPersistent<TaskBase> task_;
- const State state_;
-};
-
-TaskBase::TaskBase(v8::Isolate* isolate,
- TaskType task_type,
- V8Function* function,
- const String& function_name,
- ExceptionState& exception_state)
- : task_type_(task_type),
- self_keep_alive_(this),
- function_name_(function_name.IsolatedCopy()) {
- DCHECK(IsMainThread());
- DCHECK(task_type_ == TaskType::kUserInteraction ||
- task_type_ == TaskType::kIdleTask);
-
- if (!function)
- return; // Nothing to do.
-
- v8::Local<v8::String> function_string;
- {
- v8::TryCatch try_catch(isolate);
- if (!function->CallbackObject()
- ->ToString(isolate->GetCurrentContext())
- .ToLocal(&function_string)) {
- exception_state.RethrowV8Exception(try_catch.Exception());
- return;
- }
- }
-
- scoped_refptr<SerializedScriptValue> serialized =
- SerializedScriptValue::Serialize(
- isolate, function_string, SerializedScriptValue::SerializeOptions(),
- exception_state);
- if (exception_state.HadException())
- return;
-
- function_ = std::move(serialized);
-}
-
-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)) {
- arguments_[i].serialized_value =
- SerializedScriptValue::SerializeAndSwallowExceptions(
- isolate, arguments[i].V8Value());
- continue;
- }
- TaskBase* prerequisite =
- ToScriptWrappable(arguments[i].V8Value().As<v8::Object>())
- ->ToImpl<Task>();
- prerequisites.push_back(prerequisite);
- prerequisites_indices.push_back(i);
- }
-
- worker_thread_ = SelectThread(prerequisites, thread_provider);
- worker_thread_->IncrementTasksInProgressCount();
-
- if (prerequisites.IsEmpty()) {
- MutexLocker lock(mutex_);
- MaybeStartTask();
- return;
- }
-
- // 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.
- RegisterDependencies(prerequisites, prerequisites_indices);
-}
-
-// static
-ThreadPoolThread* TaskBase::SelectThread(
- const HeapVector<Member<TaskBase>>& prerequisites,
- ThreadPoolThreadProvider* thread_provider) {
- DCHECK(IsMainThread());
- HashCountedSet<ThreadPoolThread*> prerequisite_location_counts;
- size_t max_prerequisite_location_count = 0;
- ThreadPoolThread* max_prerequisite_thread = nullptr;
- 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_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 TaskBase::RegisterDependencies(
- const HeapVector<Member<TaskBase>>& prerequisites,
- const Vector<size_t>& prerequisites_indices) {
- DCHECK(IsMainThread());
- {
- MutexLocker lock(mutex_);
- prerequisites_remaining_ = prerequisites.size();
- }
-
- for (size_t i = 0; i < prerequisites.size(); i++) {
- TaskBase* prerequisite = prerequisites[i];
- size_t prerequisite_index = prerequisites_indices[i];
-
- {
- MutexLocker lock(prerequisite->mutex_);
- if (!prerequisite->HasFinished()) {
- prerequisite->dependents_.emplace_back(
- MakeGarbageCollected<Dependent>(this, prerequisite_index));
- continue;
- }
- }
-
- PostCrossThreadTask(
- *prerequisite->worker_thread_->GetTaskRunner(task_type_), FROM_HERE,
- CrossThreadBindOnce(&TaskBase::PassResultToDependentOnWorkerThread,
- WrapCrossThreadPersistent(prerequisite),
- prerequisite_index,
- WrapCrossThreadPersistent(this)));
- }
-}
-
-TaskBase::~TaskBase() {
- DCHECK(IsMainThread());
- DCHECK(HasFinished());
- DCHECK(!function_);
- DCHECK(arguments_.IsEmpty());
- DCHECK(!prerequisites_remaining_);
- DCHECK(dependents_.IsEmpty());
-}
-
-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 = worker_thread_->GlobalScope()->GetIsolate();
- 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_GT(prerequisites_remaining_, 0u);
- prerequisites_remaining_--;
- if (failed)
- AdvanceState(State::kCancelPending);
- arguments_[index].v8_value = v8_result;
- arguments_[index].serialized_value = serialized_result;
- MaybeStartTask();
-}
-
-void TaskBase::MaybeStartTask() {
- if (prerequisites_remaining_)
- return;
- DCHECK(state_ == State::kPending || state_ == State::kCancelPending);
- PostCrossThreadTask(*worker_thread_->GetTaskRunner(task_type_), FROM_HERE,
- CrossThreadBindOnce(&TaskBase::StartTaskOnWorkerThread,
- WrapCrossThreadPersistent(this)));
-}
-
-bool TaskBase::WillStartTaskOnWorkerThread() {
- DCHECK(worker_thread_->IsCurrentThread());
- {
- MutexLocker lock(mutex_);
- DCHECK(!prerequisites_remaining_);
- switch (state_) {
- case State::kPending:
- AdvanceState(State::kStarted);
- break;
- case State::kCancelPending:
- return false;
- case State::kStarted:
- case State::kCompleted:
- case State::kFailed:
- NOTREACHED();
- break;
- }
- }
- return true;
-}
-
-void TaskBase::TaskCompletedOnWorkerThread(v8::Local<v8::Value> v8_result,
- State state) {
- DCHECK(worker_thread_->IsCurrentThread());
- v8_result_ = MakeGarbageCollected<V8ResultHolder>(
- worker_thread_->GlobalScope()->GetIsolate(), v8_result);
- function_ = nullptr;
- arguments_.clear();
-
- Vector<CrossThreadPersistent<Dependent>> dependents_to_notify;
- {
- MutexLocker lock(mutex_);
- AdvanceState(state);
- dependents_to_notify.swap(dependents_);
- }
-
- for (auto& dependent : dependents_to_notify)
- PassResultToDependentOnWorkerThread(dependent->index, dependent->task);
-
- PostCrossThreadTask(
- *worker_thread_->GetParentExecutionContextTaskRunners()->Get(
- TaskType::kInternalDefault),
- FROM_HERE,
- CrossThreadBindOnce(&TaskBase::TaskCompleted,
- WrapCrossThreadPersistent(this),
- state == State::kCompleted));
-}
-
-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 = global_scope->GetIsolate();
- v8::Local<v8::Context> context = isolate->GetCurrentContext();
-
- 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++) {
- DCHECK(!arguments_[i].serialized_value || !arguments_[i].v8_value);
- if (arguments_[i].serialized_value)
- params[i] = arguments_[i].serialized_value->Deserialize(isolate);
- else
- params[i] = arguments_[i].v8_value->GetResult(isolate);
- }
-
- v8::TryCatch block(isolate);
- v8::MaybeLocal<v8::Value> ret =
- script_function->Call(context, receiver, params.size(), params.data());
- if (block.HasCaught()) {
- // ToString can fail in some cases. For example, if the executed javascript
- // creates an exception that overrides toString and the toString method
- // throws an exception. We currently don't handle such cases here.
- TaskCompletedOnWorkerThread(block.Exception()
- ->ToString(isolate->GetCurrentContext())
- .ToLocalChecked(),
- State::kFailed);
- return;
- }
-
- 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();
- }
- TaskCompletedOnWorkerThread(return_value, State::kCompleted);
-}
-
-void TaskBase::TaskCompleted(bool was_successful) {
- DCHECK(IsMainThread());
- worker_thread_->DecrementTasksInProgressCount();
- self_keep_alive_.Clear();
-}
-
-void TaskBase::AdvanceState(State new_state) {
- switch (new_state) {
- case State::kPending:
- NOTREACHED() << "kPending should only be set via initialization";
- break;
- 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;
- case State::kFailed:
- DCHECK(state_ == State::kStarted || state_ == State::kCancelPending);
- break;
- }
- 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,
- ExceptionState& exception_state) {
- DCHECK(IsMainThread());
- if (!resolve_task_) {
- ResolveTask* resolve_task = MakeGarbageCollected<ResolveTask>(
- script_state, task_type_, this, exception_state);
- if (exception_state.HadException())
- return ScriptPromise();
- resolve_task_ = resolve_task;
- }
- 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 = global_scope->GetIsolate();
- 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,
- ExceptionState& exception_state)
- : TaskBase(script_state->GetIsolate(),
- task_type,
- nullptr,
- String(),
- exception_state),
- resolver_(MakeGarbageCollected<ScriptPromiseResolver>(script_state)) {
- DCHECK(IsMainThread());
- if (exception_state.HadException())
- return;
-
- // 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
deleted file mode 100644
index 9b9e66e40be..00000000000
--- a/chromium/third_party/blink/renderer/core/workers/experimental/task.h
+++ /dev/null
@@ -1,230 +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_EXPERIMENTAL_TASK_H_
-#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_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 V8Function;
-
-// 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.
-// TaskBase keeps itself alive via a SelfKeepAlive until the
-// the task completes and reports itself done on the main thread via
-// TaskCompleted().
-class TaskBase : public GarbageCollectedMixin {
- public:
- virtual ~TaskBase();
-
- protected:
- virtual void StartTaskOnWorkerThread() LOCKS_EXCLUDED(mutex_) = 0;
- virtual bool IsTargetThreadForArguments() = 0;
-
- enum class State { kPending, kStarted, kCancelPending, kCompleted, kFailed };
-
- TaskBase(v8::Isolate*,
- TaskType,
- V8Function* function,
- const String& function_name,
- ExceptionState&);
-
- 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 index,
- V8ResultHolder*,
- scoped_refptr<SerializedScriptValue>,
- 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 HeapVector<Member<TaskBase>>& prerequisites,
- ThreadPoolThreadProvider*);
- void RegisterDependencies(const HeapVector<Member<TaskBase>>& prerequisites,
- const Vector<size_t>& prerequisite_indices)
- LOCKS_EXCLUDED(mutex_);
- 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
- 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_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;
- 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;
-
- // Initialized in constructor on main thread, each completed prerequisite
- // decrements from the prerequisite's thread or main thread.
- 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.
- struct Dependent final : public GarbageCollected<Dependent> {
- public:
- 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;
- };
- Vector<CrossThreadPersistent<Dependent>> dependents_ GUARDED_BY(mutex_);
-
- Mutex mutex_;
-};
-
-// The variant of TaskBase that is exposed to JS.
-class Task final : public ScriptWrappable, public TaskBase {
- DEFINE_WRAPPERTYPEINFO();
- USING_GARBAGE_COLLECTED_MIXIN(Task);
-
- public:
- // Called on main thread
- Task(ScriptState* script_state,
- ThreadPoolThreadProvider* thread_provider,
- V8Function* function,
- const Vector<ScriptValue>& arguments,
- TaskType task_type,
- ExceptionState& exception_state)
- : TaskBase(script_state->GetIsolate(),
- task_type,
- function,
- String(),
- exception_state) {
- if (exception_state.HadException())
- return;
- InitializeArgumentsOnMainThread(thread_provider, script_state, arguments);
- }
- Task(ScriptState* script_state,
- ThreadPoolThreadProvider* thread_provider,
- const String& function_name,
- const Vector<ScriptValue>& arguments,
- TaskType task_type,
- ExceptionState& exception_state)
- : TaskBase(script_state->GetIsolate(),
- task_type,
- nullptr,
- function_name,
- exception_state) {
- if (exception_state.HadException())
- return;
- InitializeArgumentsOnMainThread(thread_provider, script_state, arguments);
- }
-
- // Returns a promise that will be resolved with the result when it completes.
- ScriptPromise result(ScriptState*, ExceptionState&);
- void cancel() LOCKS_EXCLUDED(mutex_);
-
- void StartTaskOnWorkerThread() override LOCKS_EXCLUDED(mutex_);
- bool IsTargetThreadForArguments() override {
- return worker_thread_->IsCurrentThread();
- }
- 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);
-
- public:
- ResolveTask(ScriptState*, TaskType, Task* prerequisite, ExceptionState&);
- 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:
- Member<ScriptPromiseResolver> resolver_;
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_TASK_H_
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/task.idl b/chromium/third_party/blink/renderer/core/workers/experimental/task.idl
deleted file mode 100644
index f57bc98f0d1..00000000000
--- a/chromium/third_party/blink/renderer/core/workers/experimental/task.idl
+++ /dev/null
@@ -1,11 +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.
-
-[
- Exposed=Window,
- RuntimeEnabled=WorkerTaskQueue
-] interface Task {
- [CallWith=ScriptState, RaisesException] 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
deleted file mode 100644
index 6d070dbd01e..00000000000
--- a/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet.cc
+++ /dev/null
@@ -1,143 +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/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:
- explicit 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 = MakeGarbageCollected<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,
- V8Function* function,
- const Vector<ScriptValue>& arguments,
- ExceptionState& exception_state) {
- if (!GetExecutionContext() || GetExecutionContext()->IsContextDestroyed()) {
- exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
- "This frame is already detached");
- return nullptr;
- }
-
- // 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.
- Task* task =
- MakeGarbageCollected<Task>(script_state, this, function, arguments,
- TaskType::kIdleTask, exception_state);
- if (exception_state.HadException())
- return nullptr;
- return task;
-}
-
-Task* TaskWorklet::postTask(ScriptState* script_state,
- const String& function_name,
- const Vector<ScriptValue>& arguments,
- ExceptionState& exception_state) {
- if (!GetExecutionContext() || GetExecutionContext()->IsContextDestroyed()) {
- exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
- "This frame is already detached");
- return nullptr;
- }
-
- Task* task =
- MakeGarbageCollected<Task>(script_state, this, function_name, arguments,
- TaskType::kIdleTask, exception_state);
- if (exception_state.HadException())
- return nullptr;
- return task;
-}
-
-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 =
- MakeGarbageCollected<TaskWorkletMessagingProxy>(GetExecutionContext());
- proxy->Initialize(MakeGarbageCollected<WorkerClients>(), 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
deleted file mode 100644
index 3515e6b99bc..00000000000
--- a/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet.h
+++ /dev/null
@@ -1,54 +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_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 V8Function;
-
-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*,
- V8Function* task,
- const Vector<ScriptValue>& arguments,
- ExceptionState&);
-
- Task* postTask(ScriptState*,
- const String& function_name,
- const Vector<ScriptValue>& arguments,
- ExceptionState&);
-
- ThreadPoolThread* GetLeastBusyThread() override;
-
- explicit TaskWorklet(Document*);
-
- void Trace(blink::Visitor*) override;
-
- private:
- ~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
deleted file mode 100644
index aaafe67cf92..00000000000
--- a/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet.idl
+++ /dev/null
@@ -1,11 +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.
-
-[
- RuntimeEnabled=WorkerTaskQueue,
- SecureContext
-] interface TaskWorklet : Worklet {
- [CallWith=ScriptState, RaisesException] Task postTask(Function task, any... arguments);
- [CallWith=ScriptState, RaisesException] 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
deleted file mode 100644
index 90f2dd00d73..00000000000
--- a/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.cc
+++ /dev/null
@@ -1,110 +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/experimental/task_worklet_global_scope.h"
-
-#include "third_party/blink/renderer/bindings/core/v8/v8_no_argument_constructor.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/platform/bindings/callback_method_retriever.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_);
- visitor->Trace(process_);
- }
-
- 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,
- V8NoArgumentConstructor* constructor,
- 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;
- }
-
- CallbackMethodRetriever retriever(constructor);
-
- retriever.GetPrototypeObject(exception_state);
- if (exception_state.HadException())
- return;
-
- v8::Local<v8::Function> process =
- retriever.GetMethodOrThrow("process", exception_state);
- if (exception_state.HadException())
- return;
-
- ScriptValue instance;
- {
- v8::TryCatch try_catch(constructor->GetIsolate());
- if (!constructor->Construct().To(&instance)) {
- exception_state.RethrowV8Exception(try_catch.Exception());
- return;
- }
- }
-
- TaskDefinition* definition = MakeGarbageCollected<TaskDefinition>(
- constructor->GetIsolate(), instance.V8Value(), 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
deleted file mode 100644
index 221b897216d..00000000000
--- a/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.h
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef 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 V8NoArgumentConstructor;
-
-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,
- V8NoArgumentConstructor*,
- ExceptionState&);
- v8::Local<v8::Value> GetInstanceForName(const String&, v8::Isolate*);
- v8::Local<v8::Function> GetProcessFunctionForName(const String&,
- v8::Isolate*);
-
- private:
- HeapHashMap<String, Member<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
deleted file mode 100644
index 3ae6d5d85dd..00000000000
--- a/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.idl
+++ /dev/null
@@ -1,10 +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.
-
-[
- RuntimeEnabled=WorkerTaskQueue,
- Global=(Worklet,TaskWorklet)
-] interface TaskWorkletGlobalScope : WorkletGlobalScope {
- [RaisesException] void registerTask(DOMString name, NoArgumentConstructor 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
deleted file mode 100644
index 4cf38760cd1..00000000000
--- a/chromium/third_party/blink/renderer/core/workers/experimental/thread_pool.cc
+++ /dev/null
@@ -1,167 +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/experimental/thread_pool.h"
-
-#include "services/service_manager/public/cpp/interface_provider.h"
-#include "third_party/blink/public/mojom/worker/dedicated_worker_host_factory.mojom-blink.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/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"
-
-namespace blink {
-
-class ThreadPoolObjectProxy final : public ThreadedObjectProxyBase {
- public:
- ThreadPoolObjectProxy(ThreadPoolMessagingProxy* messaging_proxy,
- ParentExecutionContextTaskRunners* task_runners)
- : ThreadedObjectProxyBase(task_runners),
- messaging_proxy_(messaging_proxy) {}
- ~ThreadPoolObjectProxy() override = default;
-
- CrossThreadWeakPersistent<ThreadedMessagingProxyBase> MessagingProxyWeakPtr()
- override {
- return messaging_proxy_;
- }
-
- private:
- CrossThreadWeakPersistent<ThreadPoolMessagingProxy> messaging_proxy_;
-};
-
-class ThreadPoolMessagingProxy final : public ThreadedMessagingProxyBase {
- public:
- explicit ThreadPoolMessagingProxy(ExecutionContext* context)
- : ThreadedMessagingProxyBase(context) {
- object_proxy_ = std::make_unique<ThreadPoolObjectProxy>(
- this, GetParentExecutionContextTaskRunners());
- }
- ~ThreadPoolMessagingProxy() override = default;
-
- void StartWorker(std::unique_ptr<GlobalScopeCreationParams> creation_params) {
- InitializeWorkerThread(std::move(creation_params),
- WorkerBackingThreadStartupData::CreateDefault());
- }
- std::unique_ptr<WorkerThread> CreateWorkerThread() override {
- return std::make_unique<ThreadPoolThread>(
- GetExecutionContext(), *object_proxy_.get(), ThreadPoolThread::kWorker);
- }
-
- ThreadPoolThread* GetWorkerThread() const {
- return static_cast<ThreadPoolThread*>(
- ThreadedMessagingProxyBase::GetWorkerThread());
- }
-
- private:
- std::unique_ptr<ThreadPoolObjectProxy> object_proxy_;
-};
-
-service_manager::mojom::blink::InterfaceProviderPtrInfo
-ConnectToWorkerInterfaceProviderForThreadPool(
- ExecutionContext* execution_context,
- scoped_refptr<const SecurityOrigin> script_origin) {
- // TODO(japhet): Implement a proper factory.
- mojom::blink::DedicatedWorkerHostFactoryPtr worker_host_factory;
- execution_context->GetInterfaceProvider()->GetInterface(&worker_host_factory);
- service_manager::mojom::blink::InterfaceProviderPtrInfo
- interface_provider_ptr;
- worker_host_factory->CreateWorkerHost(
- script_origin, mojo::MakeRequest(&interface_provider_ptr));
- return interface_provider_ptr;
-}
-
-const char ThreadPool::kSupplementName[] = "ThreadPool";
-
-ThreadPool* ThreadPool::From(Document& document) {
- ThreadPool* thread_pool = Supplement<Document>::From<ThreadPool>(document);
- if (!thread_pool) {
- thread_pool = MakeGarbageCollected<ThreadPool>(document);
- Supplement<Document>::ProvideTo(document, thread_pool);
- }
- return thread_pool;
-}
-
-static const size_t kMaxThreadCount = 4;
-
-ThreadPool::ThreadPool(Document& document)
- : Supplement<Document>(document), ContextLifecycleObserver(&document) {}
-
-ThreadPool::~ThreadPool() {
- DCHECK(IsMainThread());
- for (auto proxy : thread_proxies_) {
- proxy->ParentObjectDestroyed();
- }
-}
-
-ThreadPoolThread* ThreadPool::CreateNewThread() {
- DCHECK(IsMainThread());
- DCHECK_LT(thread_proxies_.size(), kMaxThreadCount);
- base::UnguessableToken devtools_worker_token =
- GetFrame() ? GetFrame()->GetDevToolsFrameToken()
- : base::UnguessableToken::Create();
- ExecutionContext* context = GetExecutionContext();
-
- ThreadPoolMessagingProxy* proxy =
- MakeGarbageCollected<ThreadPoolMessagingProxy>(context);
- 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(), mojom::ScriptType::kClassic,
- OffMainThreadWorkerScriptFetchOption::kDisabled, "ThreadPool",
- context->UserAgent(), nullptr /* web_worker_fetch_context */,
- context->GetContentSecurityPolicy()->Headers(),
- network::mojom::ReferrerPolicy::kDefault, context->GetSecurityOrigin(),
- context->IsSecureContext(), context->GetHttpsState(),
- MakeGarbageCollected<WorkerClients>(),
- context->GetSecurityContext().AddressSpace(),
- OriginTrialContext::GetTokens(context).get(), devtools_worker_token,
- std::move(settings), kV8CacheOptionsDefault,
- nullptr /* worklet_module_responses_map */,
- ConnectToWorkerInterfaceProviderForThreadPool(
- context, context->GetSecurityOrigin())));
- thread_proxies_.insert(proxy);
- return proxy->GetWorkerThread();
-}
-
-ThreadPoolThread* ThreadPool::GetLeastBusyThread() {
- DCHECK(IsMainThread());
- ThreadPoolThread* least_busy_thread = nullptr;
- size_t lowest_task_count = std::numeric_limits<std::size_t>::max();
- for (auto proxy : thread_proxies_) {
- ThreadPoolThread* current_thread = proxy->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 (thread_proxies_.size() == kMaxThreadCount)
- return least_busy_thread;
- return CreateNewThread();
-}
-
-void ThreadPool::ContextDestroyed(ExecutionContext*) {
- DCHECK(IsMainThread());
- DCHECK(GetExecutionContext()->IsContextThread());
- for (auto proxy : thread_proxies_) {
- proxy->TerminateGlobalScope();
- }
-}
-
-void ThreadPool::Trace(blink::Visitor* visitor) {
- Supplement<Document>::Trace(visitor);
- ContextLifecycleObserver::Trace(visitor);
- visitor->Trace(thread_proxies_);
-}
-
-} // namespace blink
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
deleted file mode 100644
index 9e4b4e55549..00000000000
--- a/chromium/third_party/blink/renderer/core/workers/experimental/thread_pool.h
+++ /dev/null
@@ -1,41 +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_EXPERIMENTAL_THREAD_POOL_H_
-#define 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/supplementable.h"
-
-namespace blink {
-class Document;
-class ThreadPoolMessagingProxy;
-
-class ThreadPool final : public GarbageCollectedFinalized<ThreadPool>,
- public Supplement<Document>,
- public ContextLifecycleObserver,
- public ThreadPoolThreadProvider {
- USING_GARBAGE_COLLECTED_MIXIN(ThreadPool);
- EAGERLY_FINALIZE();
-
- public:
- static const char kSupplementName[];
- static ThreadPool* From(Document&);
-
- ThreadPool(Document&);
- ~ThreadPool();
-
- ThreadPoolThread* GetLeastBusyThread() override;
- void ContextDestroyed(ExecutionContext*) final;
- void Trace(blink::Visitor*) final;
-
- private:
- ThreadPoolThread* CreateNewThread();
-
- HeapHashSet<Member<ThreadPoolMessagingProxy>> thread_proxies_;
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_THREAD_POOL_H_
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
deleted file mode 100644
index 826f5adf1bb..00000000000
--- a/chromium/third_party/blink/renderer/core/workers/experimental/thread_pool_thread.cc
+++ /dev/null
@@ -1,104 +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/experimental/thread_pool_thread.h"
-
-#include "third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.h"
-#include "third_party/blink/renderer/core/execution_context/execution_context.h"
-#include "third_party/blink/renderer/core/origin_trials/origin_trial_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()) {
- ReadyToRunClassicScript();
- }
-
- ~ThreadPoolWorkerGlobalScope() override = default;
-
- // EventTarget
- const AtomicString& InterfaceName() const override {
- // TODO(japhet): Replaces this with
- // EventTargetNames::ThreadPoolWorkerGlobalScope.
- return event_target_names::kDedicatedWorkerGlobalScope;
- }
-
- // WorkerGlobalScope
- void Initialize(const KURL& response_url,
- network::mojom::ReferrerPolicy response_referrer_policy,
- mojom::IPAddressSpace response_address_space,
- const Vector<CSPHeaderAndType>& response_csp_headers,
- const Vector<String>* response_origin_trial_tokens) override {
- InitializeURL(response_url);
- SetReferrerPolicy(response_referrer_policy);
- SetAddressSpace(response_address_space);
-
- // These should be called after SetAddressSpace() to correctly override the
- // address space by the "treat-as-public-address" CSP directive.
- InitContentSecurityPolicyFromVector(response_csp_headers);
- BindContentSecurityPolicyToExecutionContext();
-
- OriginTrialContext::AddTokens(this, response_origin_trial_tokens);
-
- // This should be called after OriginTrialContext::AddTokens() to install
- // origin trial features in JavaScript's global object.
- ScriptController()->PrepareForEvaluation();
- }
- void FetchAndRunClassicScript(
- const KURL& script_url,
- const FetchClientSettingsObjectSnapshot& outside_settings_object,
- WorkerResourceTimingNotifier& outside_resource_timing_notifier,
- const v8_inspector::V8StackTraceId& stack_id) override {
- NOTREACHED();
- }
- void FetchAndRunModuleScript(
- const KURL& module_url_record,
- const FetchClientSettingsObjectSnapshot& outside_settings_object,
- WorkerResourceTimingNotifier& outside_resource_timing_notifier,
- 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_ = std::make_unique<WorkerBackingThread>(
- ThreadCreationParams(GetThreadType())
- .SetFrameOrWorkerScheduler(parent_execution_context->GetScheduler()));
-}
-
-WorkerOrWorkletGlobalScope* ThreadPoolThread::CreateWorkerGlobalScope(
- std::unique_ptr<GlobalScopeCreationParams> creation_params) {
- if (backing_policy_ == kWorker) {
- return MakeGarbageCollected<ThreadPoolWorkerGlobalScope>(
- std::move(creation_params), this);
- }
- return MakeGarbageCollected<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
deleted file mode 100644
index 6c8871a0487..00000000000
--- a/chromium/third_party/blink/renderer/core/workers/experimental/thread_pool_thread.h
+++ /dev/null
@@ -1,65 +0,0 @@
-// Copyright 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#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
deleted file mode 100644
index f4446c8c898..00000000000
--- a/chromium/third_party/blink/renderer/core/workers/experimental/window_task_worklet.h
+++ /dev/null
@@ -1,23 +0,0 @@
-// Copyright 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#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
deleted file mode 100644
index 626225faa7b..00000000000
--- a/chromium/third_party/blink/renderer/core/workers/experimental/window_task_worklet.idl
+++ /dev/null
@@ -1,11 +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.
-
-[
- 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
deleted file mode 100644
index 3c499bcd6ad..00000000000
--- a/chromium/third_party/blink/renderer/core/workers/experimental/worker_task_queue.cc
+++ /dev/null
@@ -1,92 +0,0 @@
-// Copyright 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "third_party/blink/renderer/core/workers/experimental/worker_task_queue.h"
-
-#include "third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h"
-#include "third_party/blink/renderer/core/dom/abort_signal.h"
-#include "third_party/blink/renderer/core/dom/document.h"
-#include "third_party/blink/renderer/core/workers/experimental/task.h"
-#include "third_party/blink/renderer/core/workers/experimental/thread_pool.h"
-
-namespace blink {
-
-WorkerTaskQueue* WorkerTaskQueue::Create(ExecutionContext* context,
- const String& type,
- ExceptionState& exception_state) {
- DCHECK(context->IsContextThread());
-
- if (context->IsContextDestroyed()) {
- exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
- "This frame is already detached.");
- return nullptr;
- }
-
- auto* document = DynamicTo<Document>(context);
- if (!document) {
- exception_state.ThrowDOMException(
- DOMExceptionCode::kInvalidAccessError,
- "WorkerTaskQueue can only be constructed from a document.");
- return nullptr;
- }
- DCHECK(type == "user-interaction" || type == "background");
- TaskType task_type = type == "user-interaction" ? TaskType::kUserInteraction
- : TaskType::kIdleTask;
- return MakeGarbageCollected<WorkerTaskQueue>(document, task_type);
-}
-
-WorkerTaskQueue::WorkerTaskQueue(Document* document, TaskType task_type)
- : document_(document), task_type_(task_type) {}
-
-ScriptPromise WorkerTaskQueue::postFunction(
- ScriptState* script_state,
- V8Function* function,
- AbortSignal* signal,
- const Vector<ScriptValue>& arguments,
- ExceptionState& exception_state) {
- DCHECK(document_->IsContextThread());
-
- if (document_->IsContextDestroyed()) {
- exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
- "This frame is already detached");
- return ScriptPromise();
- }
-
- Task* task = MakeGarbageCollected<Task>(
- script_state, ThreadPool::From(*document_), function, arguments,
- task_type_, exception_state);
- if (exception_state.HadException())
- return ScriptPromise();
-
- if (signal)
- signal->AddAlgorithm(WTF::Bind(&Task::cancel, WrapWeakPersistent(task)));
- return task->result(script_state, exception_state);
-}
-
-Task* WorkerTaskQueue::postTask(ScriptState* script_state,
- V8Function* function,
- const Vector<ScriptValue>& arguments,
- ExceptionState& exception_state) {
- DCHECK(document_->IsContextThread());
-
- if (document_->IsContextDestroyed()) {
- exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
- "This frame is already detached");
- return nullptr;
- }
-
- Task* task = MakeGarbageCollected<Task>(
- script_state, ThreadPool::From(*document_), function, arguments,
- task_type_, exception_state);
- if (exception_state.HadException())
- return nullptr;
- return task;
-}
-
-void WorkerTaskQueue::Trace(blink::Visitor* visitor) {
- ScriptWrappable::Trace(visitor);
- visitor->Trace(document_);
-}
-
-} // namespace blink
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
deleted file mode 100644
index 364cf4556d6..00000000000
--- a/chromium/third_party/blink/renderer/core/workers/experimental/worker_task_queue.h
+++ /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.
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_WORKER_TASK_QUEUE_H_
-#define THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_WORKER_TASK_QUEUE_H_
-
-#include "third_party/blink/public/platform/task_type.h"
-#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
-#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
-
-namespace blink {
-
-class AbortSignal;
-class Document;
-class ExceptionState;
-class ExecutionContext;
-class ScriptState;
-class ScriptValue;
-class Task;
-class V8Function;
-
-class CORE_EXPORT WorkerTaskQueue : public ScriptWrappable {
- DEFINE_WRAPPERTYPEINFO();
-
- public:
- static WorkerTaskQueue* Create(ExecutionContext*,
- const String&,
- ExceptionState&);
-
- WorkerTaskQueue(Document*, TaskType);
- ~WorkerTaskQueue() override = default;
-
- ScriptPromise postFunction(ScriptState*,
- V8Function* function,
- AbortSignal*,
- const Vector<ScriptValue>& arguments,
- ExceptionState&);
-
- Task* postTask(ScriptState*,
- V8Function* function,
- const Vector<ScriptValue>& arguments,
- ExceptionState&);
-
- void Trace(blink::Visitor*) override;
-
- private:
- Member<Document> document_;
- const TaskType task_type_;
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_WORKER_TASK_QUEUE_H_
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/worker_task_queue.idl b/chromium/third_party/blink/renderer/core/workers/experimental/worker_task_queue.idl
deleted file mode 100644
index 90a4e289ef6..00000000000
--- a/chromium/third_party/blink/renderer/core/workers/experimental/worker_task_queue.idl
+++ /dev/null
@@ -1,17 +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.
-
-enum TaskQueueType { "user-interaction", "background" };
-
-[
- Constructor(TaskQueueType queue_type),
- ConstructorCallWith=ExecutionContext,
- Exposed=Window,
- RaisesException=Constructor,
- RuntimeEnabled=WorkerTaskQueue,
- SecureContext
-] interface WorkerTaskQueue {
- [CallWith=ScriptState, RaisesException] Promise<any> postFunction(Function task, optional AbortSignal signal = null, any... arguments);
- [CallWith=ScriptState, RaisesException] Task postTask(Function task, any... arguments);
-};
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 0a1aad3fc6f..1e844d51bf1 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,7 +9,7 @@
#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/network/public/mojom/referrer_policy.mojom-blink.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"
diff --git a/chromium/third_party/blink/renderer/core/workers/installed_scripts_manager.h b/chromium/third_party/blink/renderer/core/workers/installed_scripts_manager.h
index 51f80981617..62317bf6171 100644
--- a/chromium/third_party/blink/renderer/core/workers/installed_scripts_manager.h
+++ b/chromium/third_party/blink/renderer/core/workers/installed_scripts_manager.h
@@ -11,7 +11,7 @@
#include "third_party/blink/renderer/platform/network/content_security_policy_response_headers.h"
#include "third_party/blink/renderer/platform/network/http_header_map.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/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/workers/main_thread_worklet_reporting_proxy.cc b/chromium/third_party/blink/renderer/core/workers/main_thread_worklet_reporting_proxy.cc
index be3b4f9bcc2..07030d36f0a 100644
--- a/chromium/third_party/blink/renderer/core/workers/main_thread_worklet_reporting_proxy.cc
+++ b/chromium/third_party/blink/renderer/core/workers/main_thread_worklet_reporting_proxy.cc
@@ -6,7 +6,7 @@
#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/use_counter.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
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 1aca5cd35f5..6ba6b522c17 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
@@ -7,7 +7,6 @@
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
-#include "third_party/blink/renderer/core/frame/use_counter.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"
@@ -15,6 +14,7 @@
#include "third_party/blink/renderer/core/workers/main_thread_worklet_reporting_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/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
namespace blink {
@@ -51,9 +51,8 @@ class MainThreadWorkletTest : public PageTestBase {
}
void SetUpScope(const String& csp_header) {
PageTestBase::SetUp(IntSize());
+ NavigateTo(KURL("https://example.com/"));
Document* document = &GetDocument();
- document->SetURL(KURL("https://example.com/"));
- document->UpdateSecurityOrigin(SecurityOrigin::Create(document->Url()));
// Set up the CSP for Document before starting MainThreadWorklet because
// MainThreadWorklet inherits the owner Document's CSP.
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 950e40b156c..84734915fc3 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
@@ -13,7 +13,7 @@
#include "third_party/blink/renderer/core/dom/task_type_traits.h"
#include "third_party/blink/renderer/core/execution_context/context_lifecycle_observer.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 7cceae2ea86..46a36fbfdfe 100644
--- a/chromium/third_party/blink/renderer/core/workers/shared_worker.cc
+++ b/chromium/third_party/blink/renderer/core/workers/shared_worker.cc
@@ -34,12 +34,12 @@
#include "third_party/blink/public/common/blob/blob_utils.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/fileapi/public_url_manager.h"
-#include "third_party/blink/renderer/core/frame/use_counter.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/probe/core_probes.h"
#include "third_party/blink/renderer/core/workers/shared_worker_client_holder.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
diff --git a/chromium/third_party/blink/renderer/core/workers/shared_worker_client.cc b/chromium/third_party/blink/renderer/core/workers/shared_worker_client.cc
index 75655884d0e..5ee80a7a11a 100644
--- a/chromium/third_party/blink/renderer/core/workers/shared_worker_client.cc
+++ b/chromium/third_party/blink/renderer/core/workers/shared_worker_client.cc
@@ -7,8 +7,8 @@
#include "base/logging.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/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/workers/shared_worker.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/workers/shared_worker_client_holder.cc b/chromium/third_party/blink/renderer/core/workers/shared_worker_client_holder.cc
index 08633f82e35..6f72eb4608d 100644
--- a/chromium/third_party/blink/renderer/core/workers/shared_worker_client_holder.cc
+++ b/chromium/third_party/blink/renderer/core/workers/shared_worker_client_holder.cc
@@ -35,6 +35,7 @@
#include "base/logging.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "third_party/blink/public/common/messaging/message_port_channel.h"
+#include "third_party/blink/public/mojom/loader/fetch_client_settings_object.mojom-blink.h"
#include "third_party/blink/public/mojom/worker/shared_worker_info.mojom-blink.h"
#include "third_party/blink/public/platform/web_content_security_policy.h"
#include "third_party/blink/public/platform/web_string.h"
@@ -45,6 +46,9 @@
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
#include "third_party/blink/renderer/core/workers/shared_worker.h"
#include "third_party/blink/renderer/core/workers/shared_worker_client.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/loader/fetch/resource_fetcher_properties.h"
namespace blink {
@@ -102,8 +106,19 @@ void SharedWorkerClientHolder::Connect(
mojo::MakeRequest(&client_ptr, task_runner_),
task_runner_);
+ auto* outside_fetch_client_settings_object =
+ MakeGarbageCollected<FetchClientSettingsObjectSnapshot>(
+ worker->GetExecutionContext()
+ ->Fetcher()
+ ->GetProperties()
+ .GetFetchClientSettingsObject());
+
connector_->Connect(
- std::move(info), std::move(client_ptr),
+ std::move(info),
+ mojom::blink::FetchClientSettingsObject::New(
+ outside_fetch_client_settings_object->GetReferrerPolicy(),
+ KURL(outside_fetch_client_settings_object->GetOutgoingReferrer())),
+ std::move(client_ptr),
worker->GetExecutionContext()->IsSecureContext()
? mojom::SharedWorkerCreationContextType::kSecure
: mojom::SharedWorkerCreationContextType::kNonsecure,
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 ef0dd363f5c..16e973b0399 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
@@ -91,10 +91,10 @@ SharedWorkerGlobalScope::SharedWorkerGlobalScope(
SharedWorkerThread* thread,
base::TimeTicks time_origin)
: WorkerGlobalScope(std::move(creation_params), thread, time_origin) {
- // When off-the-main-thread script fetch is enabled, ReadyToRunClassicScript()
+ // When off-the-main-thread script fetch is enabled, ReadyToRunWorkerScript()
// will be called after an app cache is selected.
if (!features::IsOffMainThreadSharedWorkerScriptFetchEnabled())
- ReadyToRunClassicScript();
+ ReadyToRunWorkerScript();
}
SharedWorkerGlobalScope::~SharedWorkerGlobalScope() = default;
@@ -162,8 +162,8 @@ void SharedWorkerGlobalScope::FetchAndRunClassicScript(
*this,
CreateOutsideSettingsFetcher(outside_settings_object,
outside_resource_timing_notifier),
- script_url, destination, network::mojom::FetchRequestMode::kSameOrigin,
- network::mojom::FetchCredentialsMode::kSameOrigin,
+ script_url, destination, network::mojom::RequestMode::kSameOrigin,
+ network::mojom::CredentialsMode::kSameOrigin,
WTF::Bind(&SharedWorkerGlobalScope::DidReceiveResponseForClassicScript,
WrapWeakPersistent(this),
WrapPersistent(classic_script_loader)),
@@ -177,7 +177,7 @@ void SharedWorkerGlobalScope::FetchAndRunModuleScript(
const KURL& module_url_record,
const FetchClientSettingsObjectSnapshot& outside_settings_object,
WorkerResourceTimingNotifier& outside_resource_timing_notifier,
- network::mojom::FetchCredentialsMode credentials_mode) {
+ network::mojom::CredentialsMode credentials_mode) {
// Step 12: "Let destination be "sharedworker" if is shared is true, and
// "worker" otherwise."
@@ -208,7 +208,7 @@ void SharedWorkerGlobalScope::Connect(MessagePortChannel channel) {
void SharedWorkerGlobalScope::OnAppCacheSelected() {
DCHECK(IsContextThread());
DCHECK(features::IsOffMainThreadSharedWorkerScriptFetchEnabled());
- ReadyToRunClassicScript();
+ ReadyToRunWorkerScript();
}
void SharedWorkerGlobalScope::DidReceiveResponseForClassicScript(
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 fbb2dcbfef0..7e6f70fbbe9 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
@@ -82,7 +82,7 @@ class CORE_EXPORT SharedWorkerGlobalScope final : public WorkerGlobalScope {
const KURL& module_url_record,
const FetchClientSettingsObjectSnapshot& outside_settings_object,
WorkerResourceTimingNotifier& outside_resource_timing_notifier,
- network::mojom::FetchCredentialsMode) override;
+ network::mojom::CredentialsMode) override;
// shared_worker_global_scope.idl
const String name() const;
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 38a3ba54b57..96e754dfb2e 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
@@ -7,7 +7,7 @@
#include "base/location.h"
#include "third_party/blink/renderer/bindings/core/v8/source_location.h"
#include "third_party/blink/renderer/core/exported/web_shared_worker_impl.h"
-#include "third_party/blink/renderer/platform/cross_thread_functional.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/wtf/wtf.h"
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 69d5ac244ab..65ba66c4e30 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
@@ -39,7 +39,7 @@ ThreadedMessagingProxyBase::ThreadedMessagingProxyBase(
execution_context->GetScheduler()->RegisterFeature(
SchedulingPolicy::Feature::kDedicatedWorkerOrWorklet,
{SchedulingPolicy::RecordMetricsForBackForwardCache()})),
- keep_alive_(this) {
+ keep_alive_(PERSISTENT_FROM_HERE, this) {
DCHECK(IsParentContextThread());
g_live_messaging_proxy_count++;
}
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 a1a7417016f..b5c0674a8db 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
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_THREADED_MESSAGING_PROXY_BASE_H_
#include "base/optional.h"
-#include "third_party/blink/public/mojom/devtools/console_message.mojom-shared.h"
+#include "third_party/blink/public/mojom/devtools/console_message.mojom-blink.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/frame/web_feature_forward.h"
#include "third_party/blink/renderer/core/workers/parent_execution_context_task_runners.h"
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 512cf5a468e..d122709aa8d 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
@@ -9,8 +9,8 @@
#include "third_party/blink/renderer/core/inspector/console_message.h"
#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/scheduler/public/post_cross_thread_task.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
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 42a319010a4..dc29d2aa47e 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
@@ -23,10 +23,10 @@
#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/loader/fetch/worker_resource_timing_notifier.h"
#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
namespace blink {
@@ -88,7 +88,7 @@ void ThreadedWorkletMessagingProxy::Trace(blink::Visitor* visitor) {
void ThreadedWorkletMessagingProxy::FetchAndInvokeScript(
const KURL& module_url_record,
- network::mojom::FetchCredentialsMode credentials_mode,
+ network::mojom::CredentialsMode credentials_mode,
const FetchClientSettingsObjectSnapshot& outside_settings_object,
WorkerResourceTimingNotifier& outside_resource_timing_notifier,
scoped_refptr<base::SingleThreadTaskRunner> outside_settings_task_runner,
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 1ca2d5a08ab..6fb7f94b37d 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
@@ -25,7 +25,7 @@ class CORE_EXPORT ThreadedWorkletMessagingProxy
// WorkletGlobalScopeProxy implementation.
void FetchAndInvokeScript(
const KURL& module_url_record,
- network::mojom::FetchCredentialsMode,
+ network::mojom::CredentialsMode,
const FetchClientSettingsObjectSnapshot& outside_settings_object,
WorkerResourceTimingNotifier& outside_resource_timing_notifier,
scoped_refptr<base::SingleThreadTaskRunner> outside_settings_task_runner,
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 6cea20dd76d..74dad39a706 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
@@ -27,7 +27,7 @@ ThreadedWorkletObjectProxy::~ThreadedWorkletObjectProxy() = default;
void ThreadedWorkletObjectProxy::FetchAndInvokeScript(
const KURL& module_url_record,
- network::mojom::FetchCredentialsMode credentials_mode,
+ network::mojom::CredentialsMode credentials_mode,
std::unique_ptr<CrossThreadFetchClientSettingsObjectData>
outside_settings_object,
WorkerResourceTimingNotifier* outside_resource_timing_notifier,
diff --git a/chromium/third_party/blink/renderer/core/workers/threaded_worklet_object_proxy.h b/chromium/third_party/blink/renderer/core/workers/threaded_worklet_object_proxy.h
index e5b6091a109..ee717bdec49 100644
--- a/chromium/third_party/blink/renderer/core/workers/threaded_worklet_object_proxy.h
+++ b/chromium/third_party/blink/renderer/core/workers/threaded_worklet_object_proxy.h
@@ -37,7 +37,7 @@ class CORE_EXPORT ThreadedWorkletObjectProxy : public ThreadedObjectProxyBase {
void FetchAndInvokeScript(
const KURL& module_url_record,
- network::mojom::FetchCredentialsMode,
+ network::mojom::CredentialsMode,
std::unique_ptr<CrossThreadFetchClientSettingsObjectData>
outside_settings_object,
WorkerResourceTimingNotifier* outside_resource_timing_notifier,
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 96582d2b41a..e03a79e4fb6 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
@@ -20,9 +20,9 @@
#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_thread_holder.h"
-#include "third_party/blink/renderer/platform/cross_thread_functional.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/cross_thread_functional.h"
namespace blink {
@@ -230,9 +230,13 @@ class ThreadedWorkletTest : public testing::Test {
public:
void SetUp() override {
page_ = std::make_unique<DummyPageHolder>();
- Document* document = page_->GetFrame().GetDocument();
- document->SetURL(KURL("https://example.com/"));
- document->UpdateSecurityOrigin(SecurityOrigin::Create(document->Url()));
+ KURL url("https://example.com/");
+ page_->GetFrame().Loader().CommitNavigation(
+ WebNavigationParams::CreateWithHTMLBuffer(SharedBuffer::Create(), url),
+ nullptr /* extra_data */);
+ blink::test::RunPendingTasks();
+ ASSERT_EQ(url.GetString(), GetDocument().Url().GetString());
+
messaging_proxy_ =
MakeGarbageCollected<ThreadedWorkletMessagingProxyForTest>(
&page_->GetDocument());
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_animation_frame_provider.cc b/chromium/third_party/blink/renderer/core/workers/worker_animation_frame_provider.cc
index c9058280833..094fe6c4780 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_animation_frame_provider.cc
+++ b/chromium/third_party/blink/renderer/core/workers/worker_animation_frame_provider.cc
@@ -6,7 +6,7 @@
#include "third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.h"
#include "third_party/blink/renderer/core/timing/worker_global_scope_performance.h"
-#include "third_party/blink/renderer/platform/cross_thread_functional.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
namespace blink {
@@ -18,8 +18,7 @@ WorkerAnimationFrameProvider::WorkerAnimationFrameProvider(
std::make_unique<BeginFrameProvider>(begin_frame_provider_params,
this)),
callback_collection_(context),
- context_(context),
- weak_factory_(this) {}
+ context_(context) {}
int WorkerAnimationFrameProvider::RegisterCallback(
FrameRequestCallbackCollection::FrameCallback* callback) {
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 20628c320dc..b075b804f84 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
@@ -59,7 +59,7 @@ class CORE_EXPORT WorkerAnimationFrameProvider
Member<ExecutionContext> context_;
- base::WeakPtrFactory<WorkerAnimationFrameProvider> weak_factory_;
+ base::WeakPtrFactory<WorkerAnimationFrameProvider> weak_factory_{this};
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_backing_thread.cc b/chromium/third_party/blink/renderer/core/workers/worker_backing_thread.cc
index e7366e7a226..d18082b586f 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_backing_thread.cc
+++ b/chromium/third_party/blink/renderer/core/workers/worker_backing_thread.cc
@@ -17,9 +17,8 @@
#include "third_party/blink/renderer/core/inspector/worker_thread_debugger.h"
#include "third_party/blink/renderer/core/workers/worker_backing_thread_startup_data.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/runtime_enabled_features.h"
-#include "third_party/blink/renderer/platform/web_thread_supporting_gc.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
namespace blink {
@@ -57,17 +56,17 @@ void MemoryPressureNotificationToWorkerThreadIsolates(
}
WorkerBackingThread::WorkerBackingThread(const ThreadCreationParams& params)
- : backing_thread_(std::make_unique<WebThreadSupportingGC>(params)) {}
+ : backing_thread_(blink::Thread::CreateThread(
+ ThreadCreationParams(params).SetSupportsGC(true))) {}
WorkerBackingThread::~WorkerBackingThread() = default;
void WorkerBackingThread::InitializeOnBackingThread(
const WorkerBackingThreadStartupData& startup_data) {
DCHECK(backing_thread_->IsCurrentThread());
- backing_thread_->InitializeOnThread();
DCHECK(!isolate_);
- ThreadScheduler* scheduler = BackingThread().PlatformThread().Scheduler();
+ ThreadScheduler* scheduler = BackingThread().Scheduler();
isolate_ = V8PerIsolateData::Initialize(
scheduler->V8TaskRunner(),
V8PerIsolateData::V8ContextSnapshotMode::kDontUseSnapshot);
@@ -98,7 +97,7 @@ void WorkerBackingThread::InitializeOnBackingThread(
void WorkerBackingThread::ShutdownOnBackingThread() {
DCHECK(backing_thread_->IsCurrentThread());
- BackingThread().PlatformThread().Scheduler()->SetV8Isolate(nullptr);
+ BackingThread().Scheduler()->SetV8Isolate(nullptr);
Platform::Current()->WillStopWorkerThread();
V8PerIsolateData::WillBeDestroyed(isolate_);
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_backing_thread.h b/chromium/third_party/blink/renderer/core/workers/worker_backing_thread.h
index 58de18ea59d..6391d5126c6 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_backing_thread.h
+++ b/chromium/third_party/blink/renderer/core/workers/worker_backing_thread.h
@@ -11,14 +11,13 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/heap/thread_state.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "third_party/blink/renderer/platform/wtf/threading_primitives.h"
#include "v8/include/v8.h"
namespace blink {
-class WebThreadSupportingGC;
struct WorkerBackingThreadStartupData;
// WorkerBackingThread represents a WebThread with Oilpan and V8. A client of
@@ -39,7 +38,7 @@ class CORE_EXPORT WorkerBackingThread final {
void InitializeOnBackingThread(const WorkerBackingThreadStartupData&);
void ShutdownOnBackingThread();
- WebThreadSupportingGC& BackingThread() {
+ blink::Thread& BackingThread() {
DCHECK(backing_thread_);
return *backing_thread_;
}
@@ -50,7 +49,7 @@ class CORE_EXPORT WorkerBackingThread final {
v8::MemoryPressureLevel);
private:
- std::unique_ptr<WebThreadSupportingGC> backing_thread_;
+ std::unique_ptr<blink::Thread> backing_thread_;
v8::Isolate* isolate_ = nullptr;
};
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_backing_thread_startup_data.h b/chromium/third_party/blink/renderer/core/workers/worker_backing_thread_startup_data.h
index 09c9c49c106..a203e6a3ef5 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_backing_thread_startup_data.h
+++ b/chromium/third_party/blink/renderer/core/workers/worker_backing_thread_startup_data.h
@@ -6,7 +6,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_WORKER_BACKING_THREAD_STARTUP_DATA_H_
#include "base/optional.h"
-#include "third_party/blink/renderer/platform/cross_thread_copier.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_copier.h"
namespace blink {
@@ -31,13 +31,17 @@ struct WorkerBackingThreadStartupData {
AtomicsWaitMode atomics_wait_mode;
};
+} // namespace blink
+
+namespace WTF {
+
// This allows to pass base::Optional<WorkerBackingThreadStartupData> across
// threads by PostTask().
template <>
-struct CrossThreadCopier<base::Optional<WorkerBackingThreadStartupData>>
+struct CrossThreadCopier<base::Optional<blink::WorkerBackingThreadStartupData>>
: public CrossThreadCopierPassThrough<
- base::Optional<WorkerBackingThreadStartupData>> {};
+ base::Optional<blink::WorkerBackingThreadStartupData>> {};
-} // namespace blink
+} // namespace WTF
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_WORKER_BACKING_THREAD_STARTUP_DATA_H_
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 eeeaa47777d..873bf34f0f6 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
@@ -37,6 +37,7 @@
#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"
+#include "third_party/blink/renderer/platform/loader/fetch/detachable_use_counter.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher_properties.h"
@@ -133,8 +134,8 @@ void WorkerClassicScriptLoader::LoadTopLevelScriptAsynchronously(
ResourceFetcher* fetch_client_settings_object_fetcher,
const KURL& url,
mojom::RequestContextType request_context,
- network::mojom::FetchRequestMode fetch_request_mode,
- network::mojom::FetchCredentialsMode fetch_credentials_mode,
+ network::mojom::RequestMode request_mode,
+ network::mojom::CredentialsMode credentials_mode,
base::OnceClosure response_callback,
base::OnceClosure finished_callback) {
DCHECK(fetch_client_settings_object_fetcher);
@@ -152,8 +153,8 @@ void WorkerClassicScriptLoader::LoadTopLevelScriptAsynchronously(
.GetFetchClientSettingsObject()
.GetAddressSpace());
request.SetRequestContext(request_context);
- request.SetFetchRequestMode(fetch_request_mode);
- request.SetFetchCredentialsMode(fetch_credentials_mode);
+ request.SetMode(request_mode);
+ request.SetCredentialsMode(credentials_mode);
need_to_cancel_ = true;
threadable_loader_ = MakeGarbageCollected<ThreadableLoader>(
@@ -177,7 +178,7 @@ void WorkerClassicScriptLoader::DidReceiveResponse(
return;
}
if (!AllowedByNosniff::MimeTypeAsScript(
- fetch_client_settings_object_fetcher_->Context(),
+ fetch_client_settings_object_fetcher_->GetUseCounter(),
&fetch_client_settings_object_fetcher_->GetConsoleLogger(), response,
fetch_client_settings_object_fetcher_->GetProperties()
.GetFetchClientSettingsObject()
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 255334b687a..ed7040f34a3 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
@@ -39,7 +39,7 @@
#include "third_party/blink/renderer/platform/loader/allowed_by_nosniff.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/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.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/text/string_builder.h"
@@ -76,8 +76,8 @@ class CORE_EXPORT WorkerClassicScriptLoader final
ResourceFetcher* fetch_client_settings_object_fetcher,
const KURL&,
mojom::RequestContextType,
- network::mojom::FetchRequestMode,
- network::mojom::FetchCredentialsMode,
+ network::mojom::RequestMode,
+ network::mojom::CredentialsMode,
base::OnceClosure response_callback,
base::OnceClosure finished_callback);
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 36c2d65f01a..a50179a346b 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
@@ -63,8 +63,7 @@
#include "third_party/blink/renderer/core/workers/worker_thread.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/microtask.h"
-#include "third_party/blink/renderer/platform/cross_thread_functional.h"
-#include "third_party/blink/renderer/platform/instance_counters.h"
+#include "third_party/blink/renderer/platform/instrumentation/instance_counters.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object_snapshot.h"
#include "third_party/blink/renderer/platform/loader/fetch/memory_cache.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
@@ -76,6 +75,7 @@
#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"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
namespace blink {
namespace {
@@ -84,6 +84,17 @@ void RemoveURLFromMemoryCacheInternal(const KURL& url) {
GetMemoryCache()->RemoveURLFromCache(url);
}
+scoped_refptr<SecurityOrigin> CreateSecurityOrigin(
+ GlobalScopeCreationParams* creation_params) {
+ scoped_refptr<SecurityOrigin> security_origin =
+ SecurityOrigin::Create(creation_params->script_url);
+ if (creation_params->starter_origin) {
+ security_origin->TransferPrivilegesFrom(
+ creation_params->starter_origin->CreatePrivilegeData());
+ }
+ return security_origin;
+}
+
} // namespace
FontFaceSet* WorkerGlobalScope::fonts() {
@@ -390,7 +401,7 @@ void WorkerGlobalScope::WorkerScriptFetchFinished(
RunWorkerScript();
}
-void WorkerGlobalScope::ReadyToRunClassicScript() {
+void WorkerGlobalScope::ReadyToRunWorkerScript() {
DCHECK(IsContextThread());
DCHECK_EQ(ScriptEvalState::kPauseAfterFetch, script_eval_state_);
@@ -454,6 +465,7 @@ WorkerGlobalScope::WorkerGlobalScope(
base::TimeTicks time_origin)
: WorkerOrWorkletGlobalScope(
thread->GetIsolate(),
+ CreateSecurityOrigin(creation_params.get()),
Agent::CreateForWorkerOrWorklet(thread->GetIsolate()),
creation_params->off_main_thread_fetch_option,
creation_params->global_scope_name,
@@ -478,13 +490,6 @@ WorkerGlobalScope::WorkerGlobalScope(
script_eval_state_(ScriptEvalState::kPauseAfterFetch) {
InstanceCounters::IncrementCounter(
InstanceCounters::kWorkerGlobalScopeCounter);
- scoped_refptr<SecurityOrigin> security_origin =
- SecurityOrigin::Create(creation_params->script_url);
- if (creation_params->starter_origin) {
- security_origin->TransferPrivilegesFrom(
- creation_params->starter_origin->CreatePrivilegeData());
- }
- SetSecurityOrigin(std::move(security_origin));
// https://html.spec.whatwg.org/C/#run-a-worker
// 4. Set worker global scope's HTTPS state to response's HTTPS state. [spec
@@ -538,9 +543,9 @@ NOINLINE void WorkerGlobalScope::InitializeURL(const KURL& url) {
}
void WorkerGlobalScope::queueMicrotask(V8VoidFunction* callback) {
- GetAgent()->event_loop()->EnqueueMicrotask(WTF::Bind(
- &V8PersistentCallbackFunction<V8VoidFunction>::InvokeAndReportException,
- WrapPersistent(ToV8PersistentCallbackFunction(callback)), nullptr));
+ GetAgent()->event_loop()->EnqueueMicrotask(
+ WTF::Bind(&V8VoidFunction::InvokeAndReportException,
+ WrapPersistent(callback), nullptr));
}
int WorkerGlobalScope::requestAnimationFrame(V8FrameRequestCallback* callback,
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 15717a82ec2..6d29396e815 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
@@ -28,7 +28,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_WORKER_GLOBAL_SCOPE_H_
#include <memory>
-#include "services/network/public/mojom/fetch_api.mojom-shared.h"
+#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/net/ip_address_space.mojom-blink.h"
@@ -183,7 +183,7 @@ class CORE_EXPORT WorkerGlobalScope
const KURL& module_url_record,
const FetchClientSettingsObjectSnapshot& outside_settings_object,
WorkerResourceTimingNotifier& outside_resource_timing_notifier,
- network::mojom::FetchCredentialsMode) = 0;
+ network::mojom::CredentialsMode) = 0;
void ReceiveMessage(BlinkTransferableMessage);
base::TimeTicks TimeOrigin() const { return time_origin_; }
@@ -219,10 +219,10 @@ class CORE_EXPORT WorkerGlobalScope
void ExceptionThrown(ErrorEvent*) override;
void RemoveURLFromMemoryCache(const KURL&) final;
- // Notifies that the top-level classic script is ready to evaluate.
+ // Notifies that the top-level worker script is ready to evaluate.
// Worker top-level script is evaluated after it is fetched and
- // ReadyToRunClassicScript() is called.
- void ReadyToRunClassicScript();
+ // ReadyToRunWorkerScript() is called.
+ void ReadyToRunWorkerScript();
void InitializeURL(const KURL& url);
@@ -274,12 +274,12 @@ class CORE_EXPORT WorkerGlobalScope
// State transition about worker-toplevel script evaluation.
enum class ScriptEvalState {
- // Initial state: ReadyToRunClassicScript() is not yet called.
+ // Initial state: ReadyToRunWorkerScript() is not yet called.
// Worker top-level script fetch might or might not completed, and even when
// the fetch completes in this state, script evaluation will be deferred to
- // when ReadyToRunClassicScript() is called later.
+ // when ReadyToRunWorkerScript() is called later.
kPauseAfterFetch,
- // ReadyToRunClassicScript() is already called.
+ // ReadyToRunWorkerScript() is already called.
kReadyToEvaluate,
// The worker top-level script is evaluated.
kEvaluated,
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 8c27b9af043..452357275f4 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,7 @@
readonly attribute FontFaceSet fonts;
// TrustedTypes API: http://github.com/wicg/trusted-types
- [OriginTrialEnabled=TrustedDOMTypes, Unforgeable] readonly attribute TrustedTypePolicyFactory TrustedTypesWorkers;
+ [RuntimeEnabled=TrustedDOMTypes, Unforgeable] readonly attribute TrustedTypePolicyFactory TrustedTypesWorkers;
};
WorkerGlobalScope includes WindowOrWorkerGlobalScope;
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 7df314bdc59..cdd93b5076d 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
@@ -18,16 +18,18 @@
#include "third_party/blink/renderer/core/loader/worker_fetch_context.h"
#include "third_party/blink/renderer/core/loader/worker_resource_fetcher_properties.h"
#include "third_party/blink/renderer/core/loader/worker_resource_timing_notifier_impl.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/script/fetch_client_settings_object_impl.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/cross_thread_functional.h"
+#include "third_party/blink/renderer/platform/loader/fetch/detachable_use_counter.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object_snapshot.h"
#include "third_party/blink/renderer/platform/loader/fetch/null_resource_fetcher_properties.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_load_observer.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
@@ -166,6 +168,7 @@ class OutsideSettingsCSPDelegate final
WorkerOrWorkletGlobalScope::WorkerOrWorkletGlobalScope(
v8::Isolate* isolate,
+ scoped_refptr<SecurityOrigin> origin,
Agent* agent,
OffMainThreadWorkerScriptFetchOption off_main_thread_fetch_option,
const String& name,
@@ -174,7 +177,10 @@ WorkerOrWorkletGlobalScope::WorkerOrWorkletGlobalScope(
WorkerClients* worker_clients,
scoped_refptr<WebWorkerFetchContext> web_worker_fetch_context,
WorkerReportingProxy& reporting_proxy)
- : ExecutionContext(isolate, agent),
+ : ExecutionContext(isolate,
+ agent,
+ MakeGarbageCollected<OriginTrialContext>()),
+ SecurityContext(std::move(origin), WebSandboxFlags::kNone, nullptr),
off_main_thread_fetch_option_(off_main_thread_fetch_option),
name_(name),
parent_devtools_token_(parent_devtools_token),
@@ -306,8 +312,8 @@ ResourceFetcher* WorkerOrWorkletGlobalScope::CreateFetcherInternal(
GetTaskRunner(TaskType::kNetworking),
MakeGarbageCollected<LoaderFactoryForWorker>(
*this, web_worker_fetch_context_));
- auto* console_logger = MakeGarbageCollected<DetachableConsoleLogger>(this);
- init.console_logger = console_logger;
+ init.use_counter = MakeGarbageCollected<DetachableUseCounter>(this);
+ init.console_logger = MakeGarbageCollected<DetachableConsoleLogger>(this);
fetcher = MakeGarbageCollected<ResourceFetcher>(init);
fetcher->SetResourceLoadObserver(
MakeGarbageCollected<ResourceLoadObserverForWorker>(
@@ -393,6 +399,14 @@ WorkerOrWorkletGlobalScope::GetTaskRunner(TaskType type) {
return GetThread()->GetTaskRunner(type);
}
+void WorkerOrWorkletGlobalScope::ApplySandboxFlags(SandboxFlags mask) {
+ sandbox_flags_ |= mask;
+ if (IsSandboxed(WebSandboxFlags::kOrigin) &&
+ !GetSecurityOrigin()->IsOpaque()) {
+ SetSecurityOrigin(GetSecurityOrigin()->DeriveNewOpaqueOrigin());
+ }
+}
+
void WorkerOrWorkletGlobalScope::SetOutsideContentSecurityPolicyHeaders(
const Vector<CSPHeaderAndType>& headers) {
outside_content_security_policy_headers_ = headers;
@@ -425,7 +439,7 @@ void WorkerOrWorkletGlobalScope::FetchModuleScript(
const FetchClientSettingsObjectSnapshot& fetch_client_settings_object,
WorkerResourceTimingNotifier& resource_timing_notifier,
mojom::RequestContextType destination,
- network::mojom::FetchCredentialsMode credentials_mode,
+ network::mojom::CredentialsMode credentials_mode,
ModuleScriptCustomFetchType custom_fetch_type,
ModuleTreeClient* client) {
// Step 2: "Let options be a script fetch options whose cryptographic nonce is
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 a78227ef380..c1dbaf8ed4a 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
@@ -7,7 +7,7 @@
#include <bitset>
#include "base/single_thread_task_runner.h"
-#include "services/network/public/mojom/fetch_api.mojom-shared.h"
+#include "services/network/public/mojom/fetch_api.mojom-blink.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"
@@ -46,6 +46,7 @@ class CORE_EXPORT WorkerOrWorkletGlobalScope : public EventTargetWithInlineData,
WorkerOrWorkletGlobalScope(
v8::Isolate*,
+ scoped_refptr<SecurityOrigin> origin,
Agent* agent,
OffMainThreadWorkerScriptFetchOption,
const String& name,
@@ -74,9 +75,6 @@ class CORE_EXPORT WorkerOrWorkletGlobalScope : public EventTargetWithInlineData,
void DisableEval(const String& error_message) final;
bool CanExecuteScripts(ReasonForCallingCanExecuteScripts) final;
- // SecurityContext
- void DidUpdateSecurityOrigin() final {}
-
// Returns true when the WorkerOrWorkletGlobalScope is closing (e.g. via
// WorkerGlobalScope#close() method). If this returns true, the worker is
// going to be shutdown after the current task execution. Globals that
@@ -143,6 +141,8 @@ class CORE_EXPORT WorkerOrWorkletGlobalScope : public EventTargetWithInlineData,
return off_main_thread_fetch_option_;
}
+ void ApplySandboxFlags(SandboxFlags mask);
+
protected:
// Sets outside's CSP used for off-main-thread top-level worker script
// fetch.
@@ -156,7 +156,7 @@ class CORE_EXPORT WorkerOrWorkletGlobalScope : public EventTargetWithInlineData,
const FetchClientSettingsObjectSnapshot&,
WorkerResourceTimingNotifier&,
mojom::RequestContextType destination,
- network::mojom::FetchCredentialsMode,
+ network::mojom::CredentialsMode,
ModuleScriptCustomFetchType,
ModuleTreeClient*);
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 6c4a462fcce..d1ecd27719f 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
@@ -32,7 +32,7 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_WORKER_REPORTING_PROXY_H_
#include <memory>
-#include "third_party/blink/public/mojom/devtools/console_message.mojom-shared.h"
+#include "third_party/blink/public/mojom/devtools/console_message.mojom-blink.h"
#include "third_party/blink/renderer/bindings/core/v8/source_location.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/frame/web_feature_forward.h"
@@ -128,6 +128,11 @@ class CORE_EXPORT WorkerReportingProxy {
// Invoked when the thread is stopped and WorkerGlobalScope is being
// destructed. This is the last method that is called on this interface.
virtual void DidTerminateWorkerThread() {}
+
+ // This is a quick fix for service worker onion-soup. Don't add a similar
+ // function like IsDedicatedWorkerGlobalScopeProxy().
+ // TODO(leonhsl): Remove this after this becomes unnecessary.
+ virtual bool IsServiceWorkerGlobalScopeProxy() const { return false; }
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_settings.h b/chromium/third_party/blink/renderer/core/workers/worker_settings.h
index ccf9549c7c3..bb454652eb3 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_settings.h
+++ b/chromium/third_party/blink/renderer/core/workers/worker_settings.h
@@ -8,7 +8,7 @@
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/platform/fonts/generic_font_family_settings.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 6c71516b190..440dbcee21a 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_thread.cc
+++ b/chromium/third_party/blink/renderer/core/workers/worker_thread.cc
@@ -47,9 +47,8 @@
#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/platform/bindings/microtask.h"
-#include "third_party/blink/renderer/platform/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/heap/thread_state.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object_snapshot.h"
#include "third_party/blink/renderer/platform/loader/fetch/worker_resource_timing_notifier.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
@@ -57,8 +56,8 @@
#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/web_thread_supporting_gc.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/threading.h"
@@ -70,7 +69,8 @@ using ExitCode = WorkerThread::ExitCode;
namespace {
// TODO(nhiroki): Adjust the delay based on UMA.
-constexpr TimeDelta kForcibleTerminationDelay = TimeDelta::FromSeconds(2);
+constexpr base::TimeDelta kForcibleTerminationDelay =
+ base::TimeDelta::FromSeconds(2);
} // namespace
@@ -213,7 +213,7 @@ void WorkerThread::FetchAndRunModuleScript(
const KURL& script_url,
const FetchClientSettingsObjectSnapshot& outside_settings_object,
WorkerResourceTimingNotifier& outside_resource_timing_notifier,
- network::mojom::FetchCredentialsMode credentials_mode) {
+ network::mojom::CredentialsMode credentials_mode) {
DCHECK_CALLED_ON_VALID_THREAD(parent_thread_checker_);
PostCrossThreadTask(
*GetTaskRunner(TaskType::kDOMManipulation), FROM_HERE,
@@ -313,8 +313,9 @@ void WorkerThread::DidProcessTask(const base::PendingTask& pending_task) {
// metrics for microtasks are counted as a part of the preceding task.
// TODO(nhiroki): Replace this null check with DCHECK(agent) after making
// WorkletGlobalScope take a proper Agent.
- if (Agent* agent = GlobalScope()->GetAgent())
+ if (Agent* agent = GlobalScope()->GetAgent()) {
agent->event_loop()->PerformMicrotaskCheckpoint();
+ }
// Microtask::PerformCheckpoint() runs microtasks and its completion hooks for
// the default microtask queue. The default queue may contain the microtasks
@@ -378,7 +379,7 @@ HashSet<WorkerThread*>& WorkerThread::WorkerThreads() {
}
PlatformThreadId WorkerThread::GetPlatformThreadId() {
- return GetWorkerBackingThread().BackingThread().PlatformThread().ThreadId();
+ return GetWorkerBackingThread().BackingThread().ThreadId();
}
bool WorkerThread::IsForciblyTerminated() {
@@ -432,7 +433,7 @@ void WorkerThread::ChildThreadTerminatedOnWorkerThread(WorkerThread* child) {
}
WorkerThread::WorkerThread(WorkerReportingProxy& worker_reporting_proxy)
- : time_origin_(CurrentTimeTicks()),
+ : time_origin_(base::TimeTicks::Now()),
worker_thread_id_(GetNextWorkerThreadId()),
forcible_termination_delay_(kForcibleTerminationDelay),
worker_reporting_proxy_(worker_reporting_proxy),
@@ -500,9 +501,8 @@ void WorkerThread::InitializeSchedulerOnWorkerThread(
base::WaitableEvent* waitable_event) {
DCHECK(IsCurrentThread());
DCHECK(!worker_scheduler_);
- scheduler::WorkerThread& worker_thread =
- static_cast<scheduler::WorkerThread&>(
- GetWorkerBackingThread().BackingThread().PlatformThread());
+ auto& worker_thread = static_cast<scheduler::WorkerThread&>(
+ GetWorkerBackingThread().BackingThread());
worker_scheduler_ = std::make_unique<scheduler::WorkerScheduler>(
static_cast<scheduler::WorkerThreadScheduler*>(
worker_thread.GetNonMainThreadScheduler()),
@@ -612,7 +612,7 @@ void WorkerThread::FetchAndRunModuleScriptOnWorkerThread(
std::unique_ptr<CrossThreadFetchClientSettingsObjectData>
outside_settings_object,
WorkerResourceTimingNotifier* outside_resource_timing_notifier,
- network::mojom::FetchCredentialsMode credentials_mode) {
+ network::mojom::CredentialsMode credentials_mode) {
DCHECK(outside_resource_timing_notifier);
// Worklets have a different code path to import module scripts.
// TODO(nhiroki): Consider excluding this code path from WorkerThread like
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 f093762ce1f..45790f67425 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_thread.h
+++ b/chromium/third_party/blink/renderer/core/workers/worker_thread.h
@@ -35,19 +35,19 @@
#include "base/synchronization/waitable_event.h"
#include "base/thread_annotations.h"
#include "base/unguessable_token.h"
-#include "services/network/public/mojom/fetch_api.mojom-shared.h"
+#include "services/network/public/mojom/fetch_api.mojom-blink.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_thread_type.h"
#include "third_party/blink/renderer/core/core_export.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/platform/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/heap/persistent.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/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "v8/include/v8-inspector.h"
@@ -129,7 +129,7 @@ class CORE_EXPORT WorkerThread : public Thread::TaskObserver {
const KURL& script_url,
const FetchClientSettingsObjectSnapshot& outside_settings_object,
WorkerResourceTimingNotifier& outside_resource_timing_notifier,
- network::mojom::FetchCredentialsMode);
+ network::mojom::CredentialsMode);
// Posts a task to the worker thread to close the global scope and terminate
// the underlying thread. This task may be blocked by JavaScript execution on
@@ -336,7 +336,7 @@ class CORE_EXPORT WorkerThread : public Thread::TaskObserver {
std::unique_ptr<CrossThreadFetchClientSettingsObjectData>
outside_settings_object,
WorkerResourceTimingNotifier* outside_resource_timing_notifier,
- network::mojom::FetchCredentialsMode);
+ network::mojom::CredentialsMode);
// These are called in this order during worker thread termination.
void PrepareForShutdownOnWorkerThread() LOCKS_EXCLUDED(mutex_);
@@ -366,7 +366,7 @@ class CORE_EXPORT WorkerThread : public Thread::TaskObserver {
ThreadState thread_state_ GUARDED_BY(mutex_) = ThreadState::kNotStarted;
ExitCode exit_code_ GUARDED_BY(mutex_) = ExitCode::kNotTerminated;
- TimeDelta forcible_termination_delay_;
+ base::TimeDelta forcible_termination_delay_;
scoped_refptr<InspectorTaskRunner> inspector_task_runner_;
base::UnguessableToken devtools_worker_token_;
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 adb1f6027a7..072b9761207 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
@@ -23,6 +23,22 @@
#include "third_party/blink/renderer/platform/scheduler/test/fake_task_runner.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
+// TODO(crbug.com/960985): Fix memory leaks in tests and re-enable on LSAN.
+#ifdef LEAK_SANITIZER
+#define MAYBE_TerminateFrozenScript DISABLED_TerminateFrozenScript
+#define MAYBE_NestedPauseFreeze DISABLED_NestedPauseFreeze
+#define MAYBE_TerminateWhileWorkerPausedByDebugger \
+ DISABLED_TerminateWhileWorkerPausedByDebugger
+#define MAYBE_NestedPauseFreezeNoInterrupts \
+ DISABLED_NestedPauseFreezeNoInterrupts
+#else
+#define MAYBE_TerminateFrozenScript TerminateFrozenScript
+#define MAYBE_NestedPauseFreeze NestedPauseFreeze
+#define MAYBE_TerminateWhileWorkerPausedByDebugger \
+ TerminateWhileWorkerPausedByDebugger
+#define MAYBE_NestedPauseFreezeNoInterrupts NestedPauseFreezeNoInterrupts
+#endif
+
using testing::_;
using testing::AtMost;
@@ -172,7 +188,7 @@ class WorkerThreadTest : public testing::Test {
ParentExecutionContextTaskRunners::Create());
}
- void SetForcibleTerminationDelay(TimeDelta forcible_termination_delay) {
+ void SetForcibleTerminationDelay(base::TimeDelta forcible_termination_delay) {
worker_thread_->forcible_termination_delay_ = forcible_termination_delay;
}
@@ -313,7 +329,7 @@ TEST_F(WorkerThreadTest, SyncTerminate_ImmediatelyAfterStart) {
}
TEST_F(WorkerThreadTest, AsyncTerminate_WhileTaskIsRunning) {
- constexpr TimeDelta kDelay = TimeDelta::FromMilliseconds(10);
+ constexpr base::TimeDelta kDelay = base::TimeDelta::FromMilliseconds(10);
SetForcibleTerminationDelay(kDelay);
ExpectReportingCallsForWorkerForciblyTerminated();
@@ -349,7 +365,7 @@ TEST_F(WorkerThreadTest, SyncTerminate_WhileTaskIsRunning) {
TEST_F(WorkerThreadTest,
AsyncTerminateAndThenSyncTerminate_WhileTaskIsRunning) {
- SetForcibleTerminationDelay(TimeDelta::FromMilliseconds(10));
+ SetForcibleTerminationDelay(base::TimeDelta::FromMilliseconds(10));
ExpectReportingCallsForWorkerForciblyTerminated();
StartWithSourceCodeNotToFinish();
@@ -368,7 +384,7 @@ TEST_F(WorkerThreadTest,
}
TEST_F(WorkerThreadTest, Terminate_WhileDebuggerTaskIsRunningOnInitialization) {
- constexpr TimeDelta kDelay = TimeDelta::FromMilliseconds(10);
+ constexpr base::TimeDelta kDelay = base::TimeDelta::FromMilliseconds(10);
SetForcibleTerminationDelay(kDelay);
EXPECT_CALL(*reporting_proxy_, DidCreateWorkerGlobalScope(_)).Times(1);
@@ -442,7 +458,7 @@ TEST_F(WorkerThreadTest, Terminate_WhileDebuggerTaskIsRunningOnInitialization) {
}
TEST_F(WorkerThreadTest, Terminate_WhileDebuggerTaskIsRunning) {
- constexpr TimeDelta kDelay = TimeDelta::FromMilliseconds(10);
+ constexpr base::TimeDelta kDelay = base::TimeDelta::FromMilliseconds(10);
SetForcibleTerminationDelay(kDelay);
ExpectReportingCalls();
@@ -514,8 +530,8 @@ TEST_F(WorkerThreadTest, DISABLED_TerminateWorkerWhileChildIsLoading) {
}
// Tests terminating a worker when debugger is paused.
-TEST_F(WorkerThreadTest, TerminateWhileWorkerPausedByDebugger) {
- constexpr TimeDelta kDelay = TimeDelta::FromMilliseconds(10);
+TEST_F(WorkerThreadTest, MAYBE_TerminateWhileWorkerPausedByDebugger) {
+ constexpr base::TimeDelta kDelay = base::TimeDelta::FromMilliseconds(10);
SetForcibleTerminationDelay(kDelay);
ExpectReportingCallsForWorkerForciblyTerminated();
@@ -535,8 +551,8 @@ TEST_F(WorkerThreadTest, TerminateWhileWorkerPausedByDebugger) {
EXPECT_EQ(ExitCode::kAsyncForciblyTerminated, GetExitCode());
}
-TEST_F(WorkerThreadTest, TerminateFrozenScript) {
- constexpr TimeDelta kDelay = TimeDelta::FromMilliseconds(10);
+TEST_F(WorkerThreadTest, MAYBE_TerminateFrozenScript) {
+ constexpr base::TimeDelta kDelay = base::TimeDelta::FromMilliseconds(10);
SetForcibleTerminationDelay(kDelay);
ExpectReportingCallsForWorkerForciblyTerminated();
@@ -563,8 +579,8 @@ TEST_F(WorkerThreadTest, TerminateFrozenScript) {
EXPECT_EQ(ExitCode::kAsyncForciblyTerminated, GetExitCode());
}
-TEST_F(WorkerThreadTest, NestedPauseFreeze) {
- constexpr TimeDelta kDelay = TimeDelta::FromMilliseconds(10);
+TEST_F(WorkerThreadTest, MAYBE_NestedPauseFreeze) {
+ constexpr base::TimeDelta kDelay = base::TimeDelta::FromMilliseconds(10);
SetForcibleTerminationDelay(kDelay);
ExpectReportingCallsForWorkerForciblyTerminated();
@@ -602,8 +618,8 @@ TEST_F(WorkerThreadTest, NestedPauseFreeze) {
EXPECT_EQ(ExitCode::kAsyncForciblyTerminated, GetExitCode());
}
-TEST_F(WorkerThreadTest, NestedPauseFreezeNoInterrupts) {
- constexpr TimeDelta kDelay = TimeDelta::FromMilliseconds(10);
+TEST_F(WorkerThreadTest, MAYBE_NestedPauseFreezeNoInterrupts) {
+ constexpr base::TimeDelta kDelay = base::TimeDelta::FromMilliseconds(10);
SetForcibleTerminationDelay(kDelay);
ExpectReportingCalls();
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 30046b35723..c87e752cc10 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
@@ -29,13 +29,12 @@
#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/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/network/content_security_policy_parsers.h"
#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
-#include "third_party/blink/renderer/platform/web_thread_supporting_gc.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/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
@@ -50,8 +49,8 @@ class FakeWorkerGlobalScope : public WorkerGlobalScope {
WorkerThread* thread)
: WorkerGlobalScope(std::move(creation_params),
thread,
- CurrentTimeTicks()) {
- ReadyToRunClassicScript();
+ base::TimeTicks::Now()) {
+ ReadyToRunWorkerScript();
}
~FakeWorkerGlobalScope() override = default;
@@ -93,7 +92,7 @@ class FakeWorkerGlobalScope : public WorkerGlobalScope {
const KURL& module_url_record,
const FetchClientSettingsObjectSnapshot& outside_settings_object,
WorkerResourceTimingNotifier& outside_resource_timing_notifier,
- network::mojom::FetchCredentialsMode) override {
+ network::mojom::CredentialsMode) override {
NOTREACHED();
}
diff --git a/chromium/third_party/blink/renderer/core/workers/worklet.cc b/chromium/third_party/blink/renderer/core/workers/worklet.cc
index 6cda50df2a5..23f73cff032 100644
--- a/chromium/third_party/blink/renderer/core/workers/worklet.cc
+++ b/chromium/third_party/blink/renderer/core/workers/worklet.cc
@@ -5,18 +5,18 @@
#include "third_party/blink/renderer/core/workers/worklet.h"
#include "base/single_thread_task_runner.h"
-#include "services/network/public/mojom/fetch_api.mojom-shared.h"
-#include "third_party/blink/public/mojom/web_feature/web_feature.mojom-shared.h"
+#include "services/network/public/mojom/fetch_api.mojom-blink.h"
+#include "third_party/blink/public/mojom/web_feature/web_feature.mojom-blink.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/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/fetch/request.h"
-#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/loader/worker_resource_timing_notifier_impl.h"
#include "third_party/blink/renderer/core/workers/worklet_pending_tasks.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.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/loader/fetch/resource_fetcher_properties.h"
@@ -31,9 +31,12 @@ Worklet::Worklet(Document* document)
}
Worklet::~Worklet() {
+ DCHECK(!HasPendingTasks());
+}
+
+void Worklet::Dispose() {
for (const auto& proxy : proxies_)
proxy->WorkletObjectDestroyed();
- DCHECK(!HasPendingTasks());
}
// Implementation of the first half of the "addModule(moduleURL, options)"
@@ -122,7 +125,7 @@ void Worklet::FetchAndInvokeScript(const KURL& module_url_record,
return;
// Step 6: "Let credentialOptions be the credentials member of options."
- network::mojom::FetchCredentialsMode credentials_mode;
+ network::mojom::CredentialsMode credentials_mode;
bool result = Request::ParseCredentialsMode(credentials, &credentials_mode);
DCHECK(result);
diff --git a/chromium/third_party/blink/renderer/core/workers/worklet.h b/chromium/third_party/blink/renderer/core/workers/worklet.h
index 1d7cbf7d7b0..f0a802bf6e6 100644
--- a/chromium/third_party/blink/renderer/core/workers/worklet.h
+++ b/chromium/third_party/blink/renderer/core/workers/worklet.h
@@ -27,13 +27,13 @@ class CORE_EXPORT Worklet : public ScriptWrappable,
public ContextLifecycleObserver {
DEFINE_WRAPPERTYPEINFO();
USING_GARBAGE_COLLECTED_MIXIN(Worklet);
- // Eager finalization is needed to notify parent object destruction of the
- // GC-managed messaging proxy and to initiate worklet termination.
- EAGERLY_FINALIZE();
+ USING_PRE_FINALIZER(Worklet, Dispose);
public:
~Worklet() override;
+ void Dispose();
+
// Worklet.idl
// addModule() imports ES6 module scripts.
ScriptPromise addModule(ScriptState*,
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 f0b68275278..85633e92ba5 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
@@ -31,13 +31,15 @@ namespace blink {
WorkletGlobalScope::WorkletGlobalScope(
std::unique_ptr<GlobalScopeCreationParams> creation_params,
WorkerReportingProxy& reporting_proxy,
- LocalFrame* frame)
+ LocalFrame* frame,
+ Agent* agent)
: WorkletGlobalScope(std::move(creation_params),
reporting_proxy,
ToIsolate(frame),
ThreadType::kMainThread,
frame,
- nullptr /* worker_thread */) {}
+ nullptr /* worker_thread */,
+ agent) {}
WorkletGlobalScope::WorkletGlobalScope(
std::unique_ptr<GlobalScopeCreationParams> creation_params,
@@ -48,7 +50,8 @@ WorkletGlobalScope::WorkletGlobalScope(
worker_thread->GetIsolate(),
ThreadType::kOffMainThread,
nullptr /* frame */,
- worker_thread) {}
+ worker_thread,
+ nullptr /* agent */) {}
// Partial implementation of the "set up a worklet environment settings object"
// algorithm:
@@ -59,12 +62,14 @@ WorkletGlobalScope::WorkletGlobalScope(
v8::Isolate* isolate,
ThreadType thread_type,
LocalFrame* frame,
- WorkerThread* worker_thread)
+ WorkerThread* worker_thread,
+ Agent* agent)
: WorkerOrWorkletGlobalScope(
isolate,
+ SecurityOrigin::CreateUniqueOpaque(),
// TODO(tzik): Assign an Agent for Worklets after
// NonMainThreadScheduler gets ready to run microtasks.
- nullptr,
+ agent,
creation_params->off_main_thread_fetch_option,
creation_params->global_scope_name,
creation_params->parent_devtools_token,
@@ -91,9 +96,6 @@ WorkletGlobalScope::WorkletGlobalScope(
// Step 2: "Let inheritedAPIBaseURL be outsideSettings's API base URL."
// |url_| is the inheritedAPIBaseURL passed from the parent Document.
- // Step 3: "Let origin be a unique opaque origin."
- SetSecurityOrigin(SecurityOrigin::CreateUniqueOpaque());
-
// Step 5: "Let inheritedReferrerPolicy be outsideSettings's referrer policy."
SetReferrerPolicy(creation_params->referrer_policy);
@@ -206,7 +208,7 @@ LocalFrame* WorkletGlobalScope::GetFrame() const {
// https://drafts.css-houdini.org/worklets/#fetch-and-invoke-a-worklet-script
void WorkletGlobalScope::FetchAndInvokeScript(
const KURL& module_url_record,
- network::mojom::FetchCredentialsMode credentials_mode,
+ network::mojom::CredentialsMode credentials_mode,
const FetchClientSettingsObjectSnapshot& outside_settings_object,
WorkerResourceTimingNotifier& outside_resource_timing_notifier,
scoped_refptr<base::SingleThreadTaskRunner> outside_settings_task_runner,
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 4420c21c23f..bfde8214000 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
@@ -98,7 +98,7 @@ class CORE_EXPORT WorkletGlobalScope
// parent frame's task runner).
void FetchAndInvokeScript(
const KURL& module_url_record,
- network::mojom::FetchCredentialsMode,
+ network::mojom::CredentialsMode,
const FetchClientSettingsObjectSnapshot& outside_settings_object,
WorkerResourceTimingNotifier& outside_resource_timing_notifier,
scoped_refptr<base::SingleThreadTaskRunner> outside_settings_task_runner,
@@ -129,7 +129,8 @@ class CORE_EXPORT WorkletGlobalScope
// thread.
WorkletGlobalScope(std::unique_ptr<GlobalScopeCreationParams>,
WorkerReportingProxy&,
- LocalFrame*);
+ LocalFrame*,
+ Agent* = nullptr);
// Constructs an instance as a threaded worklet. Must be called on a worker
// thread.
WorkletGlobalScope(std::unique_ptr<GlobalScopeCreationParams>,
@@ -153,7 +154,8 @@ class CORE_EXPORT WorkletGlobalScope
v8::Isolate*,
ThreadType,
LocalFrame*,
- WorkerThread*);
+ WorkerThread*,
+ Agent*);
EventTarget* ErrorEventTarget() final { return nullptr; }
diff --git a/chromium/third_party/blink/renderer/core/workers/worklet_global_scope_proxy.h b/chromium/third_party/blink/renderer/core/workers/worklet_global_scope_proxy.h
index a08c026d895..173b26bf602 100644
--- a/chromium/third_party/blink/renderer/core/workers/worklet_global_scope_proxy.h
+++ b/chromium/third_party/blink/renderer/core/workers/worklet_global_scope_proxy.h
@@ -28,7 +28,7 @@ class CORE_EXPORT WorkletGlobalScopeProxy : public GarbageCollectedMixin {
// https://drafts.css-houdini.org/worklets/#fetch-and-invoke-a-worklet-script
virtual void FetchAndInvokeScript(
const KURL& module_url_record,
- network::mojom::FetchCredentialsMode,
+ network::mojom::CredentialsMode,
const FetchClientSettingsObjectSnapshot& outside_settings_object,
WorkerResourceTimingNotifier& outside_resource_timing_notifier,
scoped_refptr<base::SingleThreadTaskRunner> outside_settings_task_runner,
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 d2db5f2148e..85d81f3e036 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
@@ -5,8 +5,8 @@
#include "third_party/blink/renderer/core/workers/worklet_module_responses_map.h"
#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"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/workers/worklet_module_responses_map.h b/chromium/third_party/blink/renderer/core/workers/worklet_module_responses_map.h
index 507f2d37241..2e95cd12bf4 100644
--- a/chromium/third_party/blink/renderer/core/workers/worklet_module_responses_map.h
+++ b/chromium/third_party/blink/renderer/core/workers/worklet_module_responses_map.h
@@ -12,7 +12,7 @@
#include "third_party/blink/renderer/platform/heap/heap_allocator.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/weborigin/kurl_hash.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/threading_primitives.h"
namespace blink {
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 94f824f38f3..7cda3b97f80 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
@@ -8,8 +8,8 @@
#include "third_party/blink/renderer/core/script/module_script.h"
#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"
+#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/workers/worklet_thread_holder.h b/chromium/third_party/blink/renderer/core/workers/worklet_thread_holder.h
index a470796fa91..56e7c715f77 100644
--- a/chromium/third_party/blink/renderer/core/workers/worklet_thread_holder.h
+++ b/chromium/third_party/blink/renderer/core/workers/worklet_thread_holder.h
@@ -10,7 +10,6 @@
#include "third_party/blink/renderer/core/workers/worker_backing_thread.h"
#include "third_party/blink/renderer/core/workers/worker_backing_thread_startup_data.h"
#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
-#include "third_party/blink/renderer/platform/web_thread_supporting_gc.h"
namespace blink {
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 19f80650f34..0a787490830 100644
--- a/chromium/third_party/blink/renderer/core/xml/document_xslt.cc
+++ b/chromium/third_party/blink/renderer/core/xml/document_xslt.cc
@@ -11,12 +11,12 @@
#include "third_party/blink/renderer/core/dom/node.h"
#include "third_party/blink/renderer/core/dom/processing_instruction.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/core/xml/xsl_style_sheet.h"
#include "third_party/blink/renderer/core/xml/xslt_processor.h"
#include "third_party/blink/renderer/platform/bindings/dom_wrapper_world.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/xml/dom_parser.cc b/chromium/third_party/blink/renderer/core/xml/dom_parser.cc
index c7973483043..996234e7538 100644
--- a/chromium/third_party/blink/renderer/core/xml/dom_parser.cc
+++ b/chromium/third_party/blink/renderer/core/xml/dom_parser.cc
@@ -43,13 +43,15 @@ Document* DOMParser::parseFromString(const StringOrTrustedHTML& stringOrHTML,
Document* DOMParser::parseFromStringInternal(const String& str,
const String& type) {
Document* doc = DOMImplementation::createDocument(
- type, DocumentInit::Create().WithContextDocument(context_document_),
+ type,
+ DocumentInit::Create()
+ .WithContextDocument(context_document_)
+ .WithOwnerDocument(context_document_),
false);
doc->SetContent(str);
doc->SetMimeType(AtomicString(type));
if (context_document_) {
doc->SetURL(context_document_->Url());
- doc->SetSecurityOrigin(context_document_->GetMutableSecurityOrigin());
}
return doc;
}
diff --git a/chromium/third_party/blink/renderer/core/xml/parser/shared_buffer_reader.h b/chromium/third_party/blink/renderer/core/xml/parser/shared_buffer_reader.h
index f517788882e..02218b20e9c 100644
--- a/chromium/third_party/blink/renderer/core/xml/parser/shared_buffer_reader.h
+++ b/chromium/third_party/blink/renderer/core/xml/parser/shared_buffer_reader.h
@@ -33,7 +33,7 @@
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
namespace blink {
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 990c1988e75..bff4f12dba9 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
@@ -48,7 +48,6 @@
#include "third_party/blink/renderer/core/dom/processing_instruction.h"
#include "third_party/blink/renderer/core/dom/transform_source.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/html/html_html_element.h"
#include "third_party/blink/renderer/core/html/html_template_element.h"
#include "third_party/blink/renderer/core/html/parser/html_entity_parser.h"
@@ -66,6 +65,7 @@
#include "third_party/blink/renderer/core/xmlns_names.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_initiator_type_names.h"
#include "third_party/blink/renderer/platform/loader/fetch/raw_resource.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_error.h"
@@ -606,8 +606,8 @@ static void* OpenFunc(const char* uri) {
ResourceLoaderOptions options;
options.initiator_info.name = fetch_initiator_type_names::kXml;
FetchParameters params(ResourceRequest(url), options);
- params.MutableResourceRequest().SetFetchRequestMode(
- network::mojom::FetchRequestMode::kSameOrigin);
+ params.MutableResourceRequest().SetMode(
+ network::mojom::RequestMode::kSameOrigin);
Resource* resource =
RawResource::FetchSynchronously(params, document->Fetcher());
if (!resource->ErrorOccurred()) {
@@ -684,12 +684,12 @@ scoped_refptr<XMLParserContext> XMLParserContext::CreateStringParser(
scoped_refptr<XMLParserContext> XMLParserContext::CreateMemoryParser(
xmlSAXHandlerPtr handlers,
void* user_data,
- const CString& chunk) {
+ const std::string& chunk) {
InitializeLibXMLIfNecessary();
// appendFragmentSource() checks that the length doesn't overflow an int.
xmlParserCtxtPtr parser =
- xmlCreateMemoryParserCtxt(chunk.data(), chunk.length());
+ xmlCreateMemoryParserCtxt(chunk.c_str(), chunk.length());
if (!parser)
return nullptr;
@@ -1050,16 +1050,13 @@ void XMLDocumentParser::EndElementNs() {
return;
ContainerNode* n = current_node_;
- if (current_node_->IsElementNode())
- ToElement(n)->FinishParsingChildren();
-
- if (!n->IsElementNode()) {
+ auto* element = DynamicTo<Element>(n);
+ if (!element) {
PopCurrentNode();
return;
}
- Element* element = ToElement(n);
-
+ element->FinishParsingChildren();
if (element->IsScriptElement() &&
!ScriptingContentIsAllowed(GetParserContentPolicy())) {
PopCurrentNode();
@@ -1491,7 +1488,7 @@ static void IgnorableWhitespaceHandler(void*, const xmlChar*, int) {
// http://bugs.webkit.org/show_bug.cgi?id=5792
}
-void XMLDocumentParser::InitializeParserContext(const CString& chunk) {
+void XMLDocumentParser::InitializeParserContext(const std::string& chunk) {
xmlSAXHandler sax;
memset(&sax, 0, sizeof(sax));
@@ -1525,7 +1522,6 @@ void XMLDocumentParser::InitializeParserContext(const CString& chunk) {
if (parsing_fragment_) {
context_ = XMLParserContext::CreateMemoryParser(&sax, this, chunk);
} else {
- DCHECK(!chunk.data());
context_ = XMLParserContext::CreateStringParser(&sax, this);
}
}
@@ -1633,7 +1629,7 @@ bool XMLDocumentParser::AppendFragmentSource(const String& chunk) {
DCHECK(!context_);
DCHECK(parsing_fragment_);
- CString chunk_as_utf8 = chunk.Utf8();
+ std::string chunk_as_utf8 = chunk.Utf8();
// libxml2 takes an int for a length, and therefore can't handle XML chunks
// larger than 2 GiB.
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 aaf355cbc40..823977256d3 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
@@ -36,10 +36,9 @@
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_client.h"
#include "third_party/blink/renderer/platform/text/segmented_string.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
-#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
#include "third_party/blink/renderer/platform/wtf/text/string_hash.h"
namespace blink {
@@ -55,8 +54,10 @@ class XMLParserContext : public RefCounted<XMLParserContext> {
USING_FAST_MALLOC(XMLParserContext);
public:
- static scoped_refptr<XMLParserContext>
- CreateMemoryParser(xmlSAXHandlerPtr, void* user_data, const CString& chunk);
+ static scoped_refptr<XMLParserContext> CreateMemoryParser(
+ xmlSAXHandlerPtr,
+ void* user_data,
+ const std::string& chunk);
static scoped_refptr<XMLParserContext> CreateStringParser(xmlSAXHandlerPtr,
void* user_data);
~XMLParserContext();
@@ -158,7 +159,7 @@ class XMLDocumentParser final : public ScriptableDocumentParser,
void EndDocument();
private:
- void InitializeParserContext(const CString& chunk = CString());
+ void InitializeParserContext(const std::string& chunk = std::string());
void PushCurrentNode(ContainerNode*);
void PopCurrentNode();
diff --git a/chromium/third_party/blink/renderer/core/xml/parser/xml_document_parser_test.cc b/chromium/third_party/blink/renderer/core/xml/parser/xml_document_parser_test.cc
index 1fb07784637..d23e1f8c451 100644
--- a/chromium/third_party/blink/renderer/core/xml/parser/xml_document_parser_test.cc
+++ b/chromium/third_party/blink/renderer/core/xml/parser/xml_document_parser_test.cc
@@ -19,7 +19,7 @@ TEST(XMLDocumentParserTest, NodeNamespaceWithParseError) {
"<body><d:foo/></body></html>");
// The first child of <html> is <parseerror>, not <body>.
- Element* foo = ToElement(doc.documentElement()->lastChild()->firstChild());
+ auto* foo = To<Element>(doc.documentElement()->lastChild()->firstChild());
EXPECT_TRUE(foo->namespaceURI().IsNull()) << foo->namespaceURI();
EXPECT_TRUE(foo->prefix().IsNull()) << foo->prefix();
EXPECT_EQ(foo->localName(), "d:foo");
diff --git a/chromium/third_party/blink/renderer/core/xml/parser/xml_parser_input.h b/chromium/third_party/blink/renderer/core/xml/parser/xml_parser_input.h
index 5e9064062e8..0006ea5c486 100644
--- a/chromium/third_party/blink/renderer/core/xml/parser/xml_parser_input.h
+++ b/chromium/third_party/blink/renderer/core/xml/parser/xml_parser_input.h
@@ -31,7 +31,7 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_XML_PARSER_XML_PARSER_INPUT_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_XML_PARSER_XML_PARSER_INPUT_H_
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/xml/xml_serializer.cc b/chromium/third_party/blink/renderer/core/xml/xml_serializer.cc
index a866fc0bbee..3cd00f2d678 100644
--- a/chromium/third_party/blink/renderer/core/xml/xml_serializer.cc
+++ b/chromium/third_party/blink/renderer/core/xml/xml_serializer.cc
@@ -28,8 +28,7 @@ namespace blink {
String XMLSerializer::serializeToString(Node* root) {
DCHECK(root);
- MarkupAccumulator accumulator(kDoNotResolveURLs,
- SerializationType::kForcedXML);
+ MarkupAccumulator accumulator(kDoNotResolveURLs, SerializationType::kXML);
return accumulator.SerializeNodes<EditingStrategy>(*root, kIncludeNode);
}
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 f34df6c908d..c16650bffe2 100644
--- a/chromium/third_party/blink/renderer/core/xml/xpath_functions.cc
+++ b/chromium/third_party/blink/renderer/core/xml/xpath_functions.cc
@@ -382,7 +382,7 @@ static inline String ExpandedNameLocalPart(Node* node) {
// But note that Blink does not support namespace nodes.
switch (node->getNodeType()) {
case Node::kElementNode:
- return ToElement(node)->localName();
+ return To<Element>(node)->localName();
case Node::kAttributeNode:
return To<Attr>(node)->localName();
case Node::kProcessingInstructionNode:
@@ -395,7 +395,7 @@ static inline String ExpandedNameLocalPart(Node* node) {
static inline String ExpandedNamespaceURI(Node* node) {
switch (node->getNodeType()) {
case Node::kElementNode:
- return ToElement(node)->namespaceURI();
+ return To<Element>(node)->namespaceURI();
case Node::kAttributeNode:
return To<Attr>(node)->namespaceURI();
default:
@@ -408,7 +408,7 @@ static inline String ExpandedName(Node* node) {
switch (node->getNodeType()) {
case Node::kElementNode:
- prefix = ToElement(node)->prefix();
+ prefix = To<Element>(node)->prefix();
break;
case Node::kAttributeNode:
prefix = To<Attr>(node)->prefix();
@@ -629,10 +629,9 @@ Value FunLang::Evaluate(EvaluationContext& context) const {
const Attribute* language_attribute = nullptr;
Node* node = context.node.Get();
while (node) {
- if (node->IsElementNode()) {
- Element* element = ToElement(node);
+ if (auto* element = DynamicTo<Element>(node))
language_attribute = element->Attributes().Find(xml_names::kLangAttr);
- }
+
if (language_attribute)
break;
node = node->parentNode();
diff --git a/chromium/third_party/blink/renderer/core/xml/xpath_functions_test.cc b/chromium/third_party/blink/renderer/core/xml/xpath_functions_test.cc
index aec2da165b5..575ff415c52 100644
--- a/chromium/third_party/blink/renderer/core/xml/xpath_functions_test.cc
+++ b/chromium/third_party/blink/renderer/core/xml/xpath_functions_test.cc
@@ -11,7 +11,7 @@
#include "third_party/blink/renderer/core/xml/xpath_value.h"
#include "third_party/blink/renderer/platform/heap/handle.h" // HeapVector, Member, etc.
#include "third_party/blink/renderer/platform/heap/heap.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include <cmath>
#include <limits>
diff --git a/chromium/third_party/blink/renderer/core/xml/xpath_node_set.cc b/chromium/third_party/blink/renderer/core/xml/xpath_node_set.cc
index dfe3a488e53..3b945f1e71e 100644
--- a/chromium/third_party/blink/renderer/core/xml/xpath_node_set.cc
+++ b/chromium/third_party/blink/renderer/core/xml/xpath_node_set.cc
@@ -232,10 +232,10 @@ void NodeSet::TraversalSort() const {
if (nodes.Contains(&n))
sorted_nodes.push_back(&n);
- if (!contains_attribute_nodes || !n.IsElementNode())
+ auto* element = DynamicTo<Element>(&n);
+ if (!element || !contains_attribute_nodes)
continue;
- Element* element = ToElement(&n);
AttributeCollection attributes = element->Attributes();
for (auto& attribute : attributes) {
Attr* attr = element->AttrIfExists(attribute.GetName());
diff --git a/chromium/third_party/blink/renderer/core/xml/xpath_parser.h b/chromium/third_party/blink/renderer/core/xml/xpath_parser.h
index 46e69a16f40..5c05b54579f 100644
--- a/chromium/third_party/blink/renderer/core/xml/xpath_parser.h
+++ b/chromium/third_party/blink/renderer/core/xml/xpath_parser.h
@@ -31,7 +31,7 @@
#include "base/macros.h"
#include "third_party/blink/renderer/core/xml/xpath_predicate.h"
#include "third_party/blink/renderer/core/xml/xpath_step.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
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 e933e00aa25..9cd60e7d3c4 100644
--- a/chromium/third_party/blink/renderer/core/xml/xpath_step.cc
+++ b/chromium/third_party/blink/renderer/core/xml/xpath_step.cc
@@ -204,31 +204,32 @@ static inline bool NodeMatchesBasicTest(Node* node,
#if DCHECK_IS_ON()
DCHECK_EQ(Node::kElementNode, PrimaryNodeType(axis));
#endif
- if (!node->IsElementNode())
+ auto* element = DynamicTo<Element>(node);
+ if (!element)
return false;
- Element& element = ToElement(*node);
- if (name == g_star_atom)
+ if (name == g_star_atom) {
return namespace_uri.IsEmpty() ||
- namespace_uri == element.namespaceURI();
+ namespace_uri == element->namespaceURI();
+ }
- if (element.GetDocument().IsHTMLDocument()) {
- if (element.IsHTMLElement()) {
+ if (element->GetDocument().IsHTMLDocument()) {
+ if (element->IsHTMLElement()) {
// Paths without namespaces should match HTML elements in HTML
// documents despite those having an XHTML namespace. Names are
// compared case-insensitively.
- return EqualIgnoringASCIICase(element.localName(), name) &&
+ return EqualIgnoringASCIICase(element->localName(), name) &&
(namespace_uri.IsNull() ||
- namespace_uri == element.namespaceURI());
+ namespace_uri == element->namespaceURI());
}
// An expression without any prefix shouldn't match no-namespace
// nodes (because HTML5 says so).
- return element.HasLocalName(name) &&
- namespace_uri == element.namespaceURI() &&
+ return element->HasLocalName(name) &&
+ namespace_uri == element->namespaceURI() &&
!namespace_uri.IsNull();
}
- return element.HasLocalName(name) &&
- namespace_uri == element.namespaceURI();
+ return element->HasLocalName(name) &&
+ namespace_uri == element->namespaceURI();
}
}
NOTREACHED();
@@ -376,10 +377,10 @@ void Step::NodesInAxis(EvaluationContext& evaluation_context,
}
case kAttributeAxis: {
- if (!context->IsElementNode())
+ auto* context_element = DynamicTo<Element>(context);
+ if (!context_element)
return;
- Element* context_element = ToElement(context);
// Avoid lazily creating attribute nodes for attributes that we do not
// need anyway.
if (GetNodeTest().GetKind() == NodeTest::kNameTest &&
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 b97d69c71ac..f92ccdd36d2 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
@@ -33,7 +33,6 @@
#include "third_party/blink/renderer/core/xml/xslt_processor.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_initiator_type_names.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_parameters.h"
-#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
namespace blink {
@@ -143,7 +142,7 @@ bool XSLStyleSheet::ParseString(const String& source) {
stylesheet_doc_ =
xmlCtxtReadMemory(ctxt, input.Data(), input.size(),
- final_url_.GetString().Utf8().data(), input.Encoding(),
+ final_url_.GetString().Utf8().c_str(), input.Encoding(),
XML_PARSE_NOENT | XML_PARSE_DTDATTR |
XML_PARSE_NOWARNING | XML_PARSE_NOCDATA);
@@ -167,7 +166,7 @@ void XSLStyleSheet::LoadChildSheets() {
// We have to locate (by ID) the appropriate embedded stylesheet
// element, so that we can walk the import/include list.
xmlAttrPtr id_node = xmlGetID(
- GetDocument(), (const xmlChar*)(final_url_.GetString().Utf8().data()));
+ GetDocument(), (const xmlChar*)(final_url_.GetString().Utf8().c_str()));
if (!id_node)
return;
stylesheet_root = id_node->parent;
@@ -227,8 +226,8 @@ void XSLStyleSheet::LoadChildSheet(const String& href) {
fetch_options.initiator_info.name = fetch_initiator_type_names::kXml;
FetchParameters params(
ResourceRequest(OwnerDocument()->CompleteURL(url_string)), fetch_options);
- params.MutableResourceRequest().SetFetchRequestMode(
- network::mojom::FetchRequestMode::kSameOrigin);
+ params.MutableResourceRequest().SetMode(
+ network::mojom::RequestMode::kSameOrigin);
XSLStyleSheetResource* resource = XSLStyleSheetResource::FetchSynchronously(
params, OwnerDocument()->Fetcher());
if (!resource->Sheet())
@@ -287,10 +286,10 @@ xmlDocPtr XSLStyleSheet::LocateStylesheetSubResource(xmlDocPtr parent_doc,
// In order to ensure that libxml canonicalized both URLs, we get
// the original href string from the import rule and canonicalize it
// using libxml before comparing it with the URI argument.
- CString import_href = child->href().Utf8();
+ std::string import_href = child->href().Utf8();
xmlChar* base = xmlNodeGetBase(parent_doc, (xmlNodePtr)parent_doc);
xmlChar* child_uri =
- xmlBuildURI((const xmlChar*)import_href.data(), base);
+ xmlBuildURI((const xmlChar*)import_href.c_str(), base);
bool equal_ur_is = xmlStrEqual(uri, child_uri);
xmlFree(base);
xmlFree(child_uri);
diff --git a/chromium/third_party/blink/renderer/core/xml/xslt_processor.cc b/chromium/third_party/blink/renderer/core/xml/xslt_processor.cc
index dd4d2526cf7..1a2ebe4eee7 100644
--- a/chromium/third_party/blink/renderer/core/xml/xslt_processor.cc
+++ b/chromium/third_party/blink/renderer/core/xml/xslt_processor.cc
@@ -26,12 +26,14 @@
#include "third_party/blink/renderer/core/dom/document_fragment.h"
#include "third_party/blink/renderer/core/dom/document_init.h"
#include "third_party/blink/renderer/core/dom/dom_implementation.h"
+#include "third_party/blink/renderer/core/dom/ignore_opens_during_unload_count_incrementer.h"
#include "third_party/blink/renderer/core/editing/serializers/serialization.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"
#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/html/html_frame_owner_element.h"
#include "third_party/blink/renderer/core/xml/document_xslt.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
@@ -85,11 +87,23 @@ Document* XSLTProcessor::CreateDocumentFromSource(
if (frame) {
Document* old_document = frame->GetDocument();
+ init = init.WithOwnerDocument(old_document)
+ .WithSandboxFlags(old_document->GetSandboxFlags());
+
// Before parsing, we need to save & detach the old document and get the new
// document in place. Document::Shutdown() tears down the LocalFrameView, so
// remember whether or not there was one.
bool has_view = frame->View();
- old_document->Shutdown();
+ {
+ SubframeLoadingDisabler disabler(old_document);
+ IgnoreOpensDuringUnloadCountIncrementer ignore_opens_during_unload(
+ old_document);
+ frame->DetachChildren();
+ if (!frame->Client())
+ return nullptr;
+
+ old_document->Shutdown();
+ }
// Re-create the LocalFrameView if needed.
if (has_view)
frame->Client()->TransitionToCommittedForNewPage();
@@ -98,9 +112,7 @@ Document* XSLTProcessor::CreateDocumentFromSource(
if (old_document) {
DocumentXSLT::From(*result).SetTransformSourceDocument(old_document);
- result->UpdateSecurityOrigin(old_document->GetMutableSecurityOrigin());
result->SetCookieURL(old_document->CookieURL());
- result->EnforceSandboxFlags(old_document->GetSandboxFlags());
auto* csp = MakeGarbageCollected<ContentSecurityPolicy>();
csp->CopyStateFrom(old_document->GetContentSecurityPolicy());
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 eb1bdd36dd5..357492ef4dc 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
@@ -50,7 +50,6 @@
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
#include "third_party/blink/renderer/platform/wtf/allocator/partitions.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
-#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
#include "third_party/blink/renderer/platform/wtf/text/string_buffer.h"
#include "third_party/blink/renderer/platform/wtf/text/utf8.h"
@@ -109,8 +108,8 @@ static xmlDocPtr DocLoaderFunc(const xmlChar* uri,
ResourceLoaderOptions fetch_options;
fetch_options.initiator_info.name = fetch_initiator_type_names::kXml;
FetchParameters params(ResourceRequest(url), fetch_options);
- params.MutableResourceRequest().SetFetchRequestMode(
- network::mojom::FetchRequestMode::kSameOrigin);
+ params.MutableResourceRequest().SetMode(
+ network::mojom::RequestMode::kSameOrigin);
Resource* resource =
RawResource::FetchSynchronously(params, g_global_resource_fetcher);
if (!g_global_processor)
@@ -247,9 +246,9 @@ static const char** XsltParamArrayFromParameterMap(
unsigned index = 0;
for (auto& parameter : parameters) {
parameter_array[index++] =
- AllocateParameterArray(parameter.key.Utf8().data());
+ AllocateParameterArray(parameter.key.Utf8().c_str());
parameter_array[index++] =
- AllocateParameterArray(parameter.value.Utf8().data());
+ AllocateParameterArray(parameter.value.Utf8().c_str());
}
parameter_array[index] = nullptr;
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 c474f520f11..e5b327bc2a6 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
@@ -52,7 +52,6 @@
#include "third_party/blink/renderer/core/frame/deprecation.h"
#include "third_party/blink/renderer/core/frame/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/forms/form_data.h"
#include "third_party/blink/renderer/core/html/html_document.h"
#include "third_party/blink/renderer/core/html/parser/text_resource_decoder.h"
@@ -73,7 +72,8 @@
#include "third_party/blink/renderer/platform/blob/blob_data.h"
#include "third_party/blink/renderer/platform/file_metadata.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
-#include "third_party/blink/renderer/platform/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
+#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/loader/cors/cors.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_initiator_type_names.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_utils.h"
@@ -89,10 +89,9 @@
#include "third_party/blink/renderer/platform/shared_buffer.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/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.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/cstring.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
namespace blink {
@@ -359,6 +358,7 @@ void XMLHttpRequest::InitResponseDocument() {
DocumentInit init = DocumentInit::Create()
.WithContextDocument(GetDocument()->ContextDocument())
+ .WithOwnerDocument(GetDocument()->ContextDocument())
.WithURL(response_.ResponseUrl());
if (is_html)
response_document_ = MakeGarbageCollected<HTMLDocument>(init);
@@ -366,7 +366,6 @@ void XMLHttpRequest::InitResponseDocument() {
response_document_ = MakeGarbageCollected<XMLDocument>(init);
// FIXME: Set Last-Modified.
- response_document_->SetSecurityOrigin(GetMutableSecurityOrigin());
response_document_->SetContextFeatures(GetDocument()->GetContextFeatures());
response_document_->SetMimeType(FinalResponseMIMETypeWithFallback());
}
@@ -476,7 +475,7 @@ void XMLHttpRequest::setTimeout(unsigned timeout,
return;
}
- timeout_ = TimeDelta::FromMilliseconds(timeout);
+ timeout_ = base::TimeDelta::FromMilliseconds(timeout);
// From http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute:
// Note: This implies that the timeout attribute can be set while fetching is
@@ -1056,12 +1055,12 @@ void XMLHttpRequest::CreateRequest(scoped_refptr<EncodedFormData> http_body,
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);
- request.SetFetchCredentialsMode(
- with_credentials_ ? network::mojom::FetchCredentialsMode::kInclude
- : network::mojom::FetchCredentialsMode::kSameOrigin);
+ request.SetMode(upload_events
+ ? network::mojom::RequestMode::kCorsWithForcedPreflight
+ : network::mojom::RequestMode::kCors);
+ request.SetCredentialsMode(
+ with_credentials_ ? network::mojom::CredentialsMode::kInclude
+ : network::mojom::CredentialsMode::kSameOrigin);
request.SetSkipServiceWorker(is_isolated_world_);
request.SetExternalRequestStateFromRequestorAddressSpace(
execution_context.GetSecurityContext().AddressSpace());
@@ -1469,8 +1468,8 @@ String XMLHttpRequest::getAllResponseHeaders() const {
WebHTTPHeaderSet access_control_expose_header_set =
cors::ExtractCorsExposedHeaderNamesList(
- with_credentials_ ? network::mojom::FetchCredentialsMode::kInclude
- : network::mojom::FetchCredentialsMode::kSameOrigin,
+ with_credentials_ ? network::mojom::CredentialsMode::kInclude
+ : network::mojom::CredentialsMode::kSameOrigin,
response_);
HTTPHeaderMap::const_iterator end = response_.HttpHeaderFields().end();
@@ -1487,7 +1486,7 @@ String XMLHttpRequest::getAllResponseHeaders() const {
if (response_.GetType() == network::mojom::FetchResponseType::kCors &&
!cors::IsCorsSafelistedResponseHeader(it->key) &&
- access_control_expose_header_set.find(it->key.Ascii().data()) ==
+ access_control_expose_header_set.find(it->key.Ascii()) ==
access_control_expose_header_set.end()) {
continue;
}
@@ -1518,13 +1517,13 @@ const AtomicString& XMLHttpRequest::getResponseHeader(
WebHTTPHeaderSet access_control_expose_header_set =
cors::ExtractCorsExposedHeaderNamesList(
- with_credentials_ ? network::mojom::FetchCredentialsMode::kInclude
- : network::mojom::FetchCredentialsMode::kSameOrigin,
+ with_credentials_ ? network::mojom::CredentialsMode::kInclude
+ : network::mojom::CredentialsMode::kSameOrigin,
response_);
if (response_.GetType() == network::mojom::FetchResponseType::kCors &&
!cors::IsCorsSafelistedResponseHeader(name) &&
- access_control_expose_header_set.find(name.Ascii().data()) ==
+ access_control_expose_header_set.find(name.Ascii()) ==
access_control_expose_header_set.end()) {
LogConsoleError(GetExecutionContext(),
"Refused to get unsafe header \"" + name + "\"");
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 a77bc7a9dfe..54f9ce9fec3 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
@@ -304,7 +304,7 @@ class XMLHttpRequest final : public XMLHttpRequestEventTarget,
// Not converted to ASCII lowercase. Must be lowered later or compared
// using case insensitive comparison functions if needed.
AtomicString mime_type_override_;
- TimeDelta timeout_;
+ base::TimeDelta timeout_;
Member<Blob> response_blob_;
TaskHandle pending_abort_event_;
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 1dbea174864..318a2492c39 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
@@ -40,8 +40,8 @@
namespace blink {
-static constexpr TimeDelta kMinimumProgressEventDispatchingInterval =
- TimeDelta::FromMilliseconds(50); // 50 ms per specification.
+static constexpr base::TimeDelta kMinimumProgressEventDispatchingInterval =
+ base::TimeDelta::FromMilliseconds(50); // 50 ms per specification.
XMLHttpRequestProgressEventThrottle::DeferredEvent::DeferredEvent() {
Clear();
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 d8b7719aad9..fdc728e9dfc 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
@@ -30,7 +30,7 @@
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/timer.h"
-#include "third_party/blink/renderer/platform/wtf/allocator.h"
+#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
namespace blink {
@@ -52,6 +52,9 @@ class XMLHttpRequest;
class XMLHttpRequestProgressEventThrottle final
: public GarbageCollectedFinalized<XMLHttpRequestProgressEventThrottle>,
public TimerBase {
+ // Need to promptly stop this timer when it is deemed finalizable.
+ USING_PRE_FINALIZER(XMLHttpRequestProgressEventThrottle, Stop);
+
public:
explicit XMLHttpRequestProgressEventThrottle(XMLHttpRequest*);
~XMLHttpRequestProgressEventThrottle() override;
@@ -80,8 +83,6 @@ class XMLHttpRequestProgressEventThrottle final
// depending on the value of the ProgressEventAction argument.
void DispatchReadyStateChangeEvent(Event*, DeferredEventAction);
- // Need to promptly stop this timer when it is deemed finalizable.
- EAGERLY_FINALIZE();
void Trace(blink::Visitor*);
private: